9b694bb03a193b050e655325ba493ef952f7cbb1
[civicrm-core.git] / CRM / Core / Resources.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11 use Civi\Core\Event\GenericHookEvent;
12
13 /**
14 * This class facilitates the loading of resources
15 * such as JavaScript files and CSS files.
16 *
17 * Any URLs generated for resources may include a 'cache-code'. By resetting the
18 * cache-code, one may force clients to re-download resource files (regardless of
19 * any HTTP caching rules).
20 *
21 * TODO: This is currently a thin wrapper over CRM_Core_Region. We
22 * should incorporte services for aggregation, minimization, etc.
23 *
24 * @package CRM
25 * @copyright CiviCRM LLC https://civicrm.org/licensing
26 */
27 class CRM_Core_Resources {
28 const DEFAULT_WEIGHT = 0;
29 const DEFAULT_REGION = 'page-footer';
30
31 /**
32 * We don't have a container or dependency-injection, so use singleton instead
33 *
34 * @var object
35 */
36 private static $_singleton = NULL;
37
38 /**
39 * @var CRM_Extension_Mapper
40 */
41 private $extMapper = NULL;
42
43 /**
44 * @var CRM_Core_Resources_Strings
45 */
46 private $strings = NULL;
47
48 /**
49 * Added core resources.
50 *
51 * Format is ($regionName => bool).
52 *
53 * @var array
54 */
55 protected $addedCoreResources = [];
56
57 /**
58 * Added core styles.
59 *
60 * Format is ($regionName => bool).
61 *
62 * @var array
63 */
64 protected $addedCoreStyles = [];
65
66 /**
67 * Added settings.
68 *
69 * Format is ($regionName => bool).
70 *
71 * @var array
72 */
73 protected $addedSettings = [];
74
75 /**
76 * A value to append to JS/CSS URLs to coerce cache resets.
77 *
78 * @var string
79 */
80 protected $cacheCode = NULL;
81
82 /**
83 * The name of a setting which persistently stores the cacheCode.
84 *
85 * @var string
86 */
87 protected $cacheCodeKey = NULL;
88
89 /**
90 * Are ajax popup screens enabled.
91 *
92 * @var bool
93 */
94 public $ajaxPopupsEnabled;
95
96 /**
97 * @var \Civi\Core\Paths
98 */
99 protected $paths;
100
101 /**
102 * Get or set the single instance of CRM_Core_Resources.
103 *
104 * @param CRM_Core_Resources $instance
105 * New copy of the manager.
106 *
107 * @return CRM_Core_Resources
108 */
109 public static function singleton(CRM_Core_Resources $instance = NULL) {
110 if ($instance !== NULL) {
111 self::$_singleton = $instance;
112 }
113 if (self::$_singleton === NULL) {
114 self::$_singleton = Civi::service('resources');
115 }
116 return self::$_singleton;
117 }
118
119 /**
120 * Construct a resource manager.
121 *
122 * @param CRM_Extension_Mapper $extMapper
123 * Map extension names to their base path or URLs.
124 * @param CRM_Core_Resources_Strings $strings
125 * JS-localization cache.
126 * @param string|null $cacheCodeKey Random code to append to resource URLs; changing the code forces clients to reload resources
127 */
128 public function __construct($extMapper, $strings, $cacheCodeKey = NULL) {
129 $this->extMapper = $extMapper;
130 $this->strings = $strings;
131 $this->cacheCodeKey = $cacheCodeKey;
132 if ($cacheCodeKey !== NULL) {
133 $this->cacheCode = Civi::settings()->get($cacheCodeKey);
134 }
135 if (!$this->cacheCode) {
136 $this->resetCacheCode();
137 }
138 $this->ajaxPopupsEnabled = (bool) Civi::settings()->get('ajaxPopupsEnabled');
139 $this->paths = Civi::paths();
140 }
141
142 /**
143 * Export permission data to the client to enable smarter GUIs.
144 *
145 * Note: Application security stems from the server's enforcement
146 * of the security logic (e.g. in the API permissions). There's no way
147 * the client can use this info to make the app more secure; however,
148 * it can produce a better-tuned (non-broken) UI.
149 *
150 * @param string|iterable $permNames
151 * List of permission names to check/export.
152 * @return CRM_Core_Resources
153 */
154 public function addPermissions($permNames) {
155 $this->getSettingRegion()->addPermissions($permNames);
156 return $this;
157 }
158
159 /**
160 * Add a JavaScript file to the current page using <SCRIPT SRC>.
161 *
162 * @param string $ext
163 * extension name; use 'civicrm' for core.
164 * @param string $file
165 * file path -- relative to the extension base dir.
166 * @param int $weight
167 * relative weight within a given region.
168 * @param string $region
169 * location within the file; 'html-header', 'page-header', 'page-footer'.
170 * @param bool|string $translate
171 * Whether to load translated strings for this file. Use one of:
172 * - FALSE: Do not load translated strings.
173 * - TRUE: Load translated strings. Use the $ext's default domain.
174 * - string: Load translated strings. Use a specific domain.
175 *
176 * @return CRM_Core_Resources
177 *
178 * @throws \CRM_Core_Exception
179 */
180 public function addScriptFile($ext, $file, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION, $translate = TRUE) {
181 CRM_Core_Region::instance($region)->addScriptFile($ext, $file, [
182 'weight' => $weight,
183 'translate' => $translate,
184 'name' => "$ext:$file",
185 // Setting the name above may appear superfluous, but it preserves a historical quirk
186 // where Region::add() and Resources::addScriptFile() produce slightly different orderings..
187 ]);
188 return $this;
189 }
190
191 /**
192 * Add a JavaScript file to the current page using <SCRIPT SRC>.
193 *
194 * @param string $url
195 * @param int $weight
196 * relative weight within a given region.
197 * @param string $region
198 * location within the file; 'html-header', 'page-header', 'page-footer'.
199 * @return CRM_Core_Resources
200 */
201 public function addScriptUrl($url, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
202 CRM_Core_Region::instance($region)->add([
203 'scriptUrl' => $url,
204 'weight' => $weight,
205 'name' => $url,
206 // Setting the name above may appear superfluous, but it preserves a historical quirk
207 // where Region::add() and Resources::addScriptUrl() produce slightly different orderings..
208 ]);
209 return $this;
210 }
211
212 /**
213 * Add a JavaScript file to the current page using <SCRIPT SRC>.
214 *
215 * @param string $code
216 * JavaScript source code.
217 * @param int $weight
218 * relative weight within a given region.
219 * @param string $region
220 * location within the file; 'html-header', 'page-header', 'page-footer'.
221 * @return CRM_Core_Resources
222 */
223 public function addScript($code, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
224 CRM_Core_Region::instance($region)->add(['script' => $code, 'weight' => $weight]);
225 return $this;
226 }
227
228 /**
229 * Add JavaScript variables to CRM.vars
230 *
231 * Example:
232 * From the server:
233 * CRM_Core_Resources::singleton()->addVars('myNamespace', array('foo' => 'bar'));
234 * Access var from javascript:
235 * CRM.vars.myNamespace.foo // "bar"
236 *
237 * @see https://docs.civicrm.org/dev/en/latest/standards/javascript/
238 *
239 * @param string $nameSpace
240 * Usually the name of your extension.
241 * @param array $vars
242 * @param string $region
243 * The region to add settings to (eg. for payment processors usually billing-block)
244 *
245 * @return CRM_Core_Resources
246 */
247 public function addVars($nameSpace, $vars, $region = NULL) {
248 $this->getSettingRegion($region)->addVars($nameSpace, $vars);
249 return $this;
250 }
251
252 /**
253 * Add JavaScript variables to the root of the CRM object.
254 * This function is usually reserved for low-level system use.
255 * Extensions and components should generally use addVars instead.
256 *
257 * @param array $settings
258 * @param string $region
259 * The region to add settings to (eg. for payment processors usually billing-block)
260 *
261 * @return CRM_Core_Resources
262 */
263 public function addSetting($settings, $region = NULL) {
264 $this->getSettingRegion($region)->addSetting($settings);
265 return $this;
266 }
267
268 /**
269 * Add JavaScript variables to the global CRM object via a callback function.
270 *
271 * @param callable $callable
272 * @return CRM_Core_Resources
273 */
274 public function addSettingsFactory($callable) {
275 $this->getSettingRegion()->addSettingsFactory($callable);
276 return $this;
277 }
278
279 /**
280 * Helper fn for addSettingsFactory.
281 */
282 public function getSettings() {
283 return $this->getSettingRegion()->getSettings();
284 }
285
286 /**
287 * Add translated string to the js CRM object.
288 * It can then be retrived from the client-side ts() function
289 * Variable substitutions can happen from client-side
290 *
291 * Note: this function rarely needs to be called directly and is mostly for internal use.
292 * See CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
293 *
294 * Simple example:
295 * // From php:
296 * CRM_Core_Resources::singleton()->addString('Hello');
297 * // The string is now available to javascript code i.e.
298 * ts('Hello');
299 *
300 * Example with client-side substitutions:
301 * // From php:
302 * CRM_Core_Resources::singleton()->addString('Your %1 has been %2');
303 * // ts() in javascript works the same as in php, for example:
304 * ts('Your %1 has been %2', {1: objectName, 2: actionTaken});
305 *
306 * NOTE: This function does not work with server-side substitutions
307 * (as this might result in collisions and unwanted variable injections)
308 * Instead, use code like:
309 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs)))));
310 * And from javascript access it at CRM.myNamespace.myString
311 *
312 * @param string|array $text
313 * @param string|null $domain
314 * @return CRM_Core_Resources
315 */
316 public function addString($text, $domain = 'civicrm') {
317 $this->getSettingRegion()->addString($text, $domain);
318 return $this;
319 }
320
321 /**
322 * Add a CSS file to the current page using <LINK HREF>.
323 *
324 * @param string $ext
325 * extension name; use 'civicrm' for core.
326 * @param string $file
327 * file path -- relative to the extension base dir.
328 * @param int $weight
329 * relative weight within a given region.
330 * @param string $region
331 * location within the file; 'html-header', 'page-header', 'page-footer'.
332 * @return CRM_Core_Resources
333 */
334 public function addStyleFile($ext, $file, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
335 CRM_Core_Region::instance($region)->addStyleFile($ext, $file, [
336 'weight' => $weight,
337 'name' => "$ext:$file",
338 // Setting the name above may appear superfluous, but it preserves a historical quirk
339 // where Region::add() and Resources::addScriptUrl() produce slightly different orderings..
340 ]);
341 return $this;
342 }
343
344 /**
345 * Add a CSS file to the current page using <LINK HREF>.
346 *
347 * @param string $url
348 * @param int $weight
349 * relative weight within a given region.
350 * @param string $region
351 * location within the file; 'html-header', 'page-header', 'page-footer'.
352 * @return CRM_Core_Resources
353 */
354 public function addStyleUrl($url, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
355 CRM_Core_Region::instance($region)->add([
356 'styleUrl' => $url,
357 'weight' => $weight,
358 'name' => $url,
359 // Setting the name above may appear superfluous, but it preserves a historical quirk
360 // where Region::add() and Resources::addScriptUrl() produce slightly different orderings..
361 ]);
362 return $this;
363 }
364
365 /**
366 * Add a CSS content to the current page using <STYLE>.
367 *
368 * @param string $code
369 * CSS source code.
370 * @param int $weight
371 * relative weight within a given region.
372 * @param string $region
373 * location within the file; 'html-header', 'page-header', 'page-footer'.
374 * @return CRM_Core_Resources
375 */
376 public function addStyle($code, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
377 CRM_Core_Region::instance($region)->add(['style' => $code, 'weight' => $weight]);
378 return $this;
379 }
380
381 /**
382 * Determine file path of a resource provided by an extension.
383 *
384 * @param string $ext
385 * extension name; use 'civicrm' for core.
386 * @param string|null $file
387 * file path -- relative to the extension base dir.
388 *
389 * @return bool|string
390 * full file path or FALSE if not found
391 */
392 public function getPath($ext, $file = NULL) {
393 // TODO consider caching results
394 $base = $this->paths->hasVariable($ext)
395 ? rtrim($this->paths->getVariable($ext, 'path'), '/')
396 : $this->extMapper->keyToBasePath($ext);
397 if ($file === NULL) {
398 return $base;
399 }
400 $path = $base . '/' . $file;
401 if (is_file($path)) {
402 return $path;
403 }
404 return FALSE;
405 }
406
407 /**
408 * Determine public URL of a resource provided by an extension.
409 *
410 * @param string $ext
411 * extension name; use 'civicrm' for core.
412 * @param string $file
413 * file path -- relative to the extension base dir.
414 * @param bool $addCacheCode
415 *
416 * @return string, URL
417 */
418 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
419 if ($file === NULL) {
420 $file = '';
421 }
422 if ($addCacheCode) {
423 $file = $this->addCacheCode($file);
424 }
425 // TODO consider caching results
426 $base = $this->paths->hasVariable($ext)
427 ? $this->paths->getVariable($ext, 'url')
428 : ($this->extMapper->keyToUrl($ext) . '/');
429 return $base . $file;
430 }
431
432 /**
433 * Evaluate a glob pattern in the context of a particular extension.
434 *
435 * @param string $ext
436 * Extension name; use 'civicrm' for core.
437 * @param string|array $patterns
438 * Glob pattern; e.g. "*.html".
439 * @param null|int $flags
440 * See glob().
441 * @return array
442 * List of matching files, relative to the extension base dir.
443 * @see glob()
444 */
445 public function glob($ext, $patterns, $flags = NULL) {
446 $path = $this->getPath($ext);
447 $patterns = (array) $patterns;
448 $files = [];
449 foreach ($patterns as $pattern) {
450 if (preg_match(';^(assetBuilder|ext)://;', $pattern)) {
451 $files[] = $pattern;
452 }
453 if (CRM_Utils_File::isAbsolute($pattern)) {
454 // Absolute path.
455 $files = array_merge($files, (array) glob($pattern, $flags));
456 }
457 else {
458 // Relative path.
459 $files = array_merge($files, (array) glob("$path/$pattern", $flags));
460 }
461 }
462 // Deterministic order.
463 sort($files);
464 $files = array_unique($files);
465 return array_map(function ($file) use ($path) {
466 return CRM_Utils_File::relativize($file, "$path/");
467 }, $files);
468 }
469
470 /**
471 * @return string
472 */
473 public function getCacheCode() {
474 return $this->cacheCode;
475 }
476
477 /**
478 * @param $value
479 * @return CRM_Core_Resources
480 */
481 public function setCacheCode($value) {
482 $this->cacheCode = $value;
483 if ($this->cacheCodeKey) {
484 Civi::settings()->set($this->cacheCodeKey, $value);
485 }
486 return $this;
487 }
488
489 /**
490 * @return CRM_Core_Resources
491 */
492 public function resetCacheCode() {
493 $this->setCacheCode(CRM_Utils_String::createRandom(5, CRM_Utils_String::ALPHANUMERIC));
494 // Also flush cms resource cache if needed
495 CRM_Core_Config::singleton()->userSystem->clearResourceCache();
496 return $this;
497 }
498
499 /**
500 * This adds CiviCRM's standard css and js to the specified region of the document.
501 * It will only run once.
502 *
503 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
504 * (like addCoreResources/addCoreStyles).
505 *
506 * @param string $region
507 * @return CRM_Core_Resources
508 */
509 public function addCoreResources($region = 'html-header') {
510 if (!isset($this->addedCoreResources[$region]) && !self::isAjaxMode()) {
511 $this->addedCoreResources[$region] = TRUE;
512 $config = CRM_Core_Config::singleton();
513
514 // Add resources from coreResourceList
515 $jsWeight = -9999;
516 foreach ($this->coreResourceList($region) as $item) {
517 if (is_array($item)) {
518 $this->addSetting($item);
519 }
520 elseif (strpos($item, '.css')) {
521 $this->isFullyFormedUrl($item) ? $this->addStyleUrl($item, -100, $region) : $this->addStyleFile('civicrm', $item, -100, $region);
522 }
523 elseif ($this->isFullyFormedUrl($item)) {
524 $this->addScriptUrl($item, $jsWeight++, $region);
525 }
526 else {
527 // Don't bother looking for ts() calls in packages, there aren't any
528 $translate = (substr($item, 0, 3) == 'js/');
529 $this->addScriptFile('civicrm', $item, $jsWeight++, $region, $translate);
530 }
531 }
532 // Add global settings
533 $settings = [
534 'config' => [
535 'isFrontend' => $config->userFrameworkFrontend,
536 ],
537 ];
538 // Disable profile creation if user lacks permission
539 if (!CRM_Core_Permission::check('edit all contacts') && !CRM_Core_Permission::check('add contacts')) {
540 $settings['config']['entityRef']['contactCreate'] = FALSE;
541 }
542 $this->addSetting($settings);
543
544 // Give control of jQuery and _ back to the CMS - this loads last
545 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
546
547 $this->addCoreStyles($region);
548 }
549 return $this;
550 }
551
552 /**
553 * This will add CiviCRM's standard CSS
554 *
555 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
556 * (like addCoreResources/addCoreStyles).
557 *
558 * @param string $region
559 * @return CRM_Core_Resources
560 */
561 public function addCoreStyles($region = 'html-header') {
562 if (!isset($this->addedCoreStyles[$region])) {
563 $this->addedCoreStyles[$region] = TRUE;
564
565 // Load custom or core css
566 $config = CRM_Core_Config::singleton();
567 if (!empty($config->customCSSURL)) {
568 $customCSSURL = $this->addCacheCode($config->customCSSURL);
569 $this->addStyleUrl($customCSSURL, 99, $region);
570 }
571 if (!Civi::settings()->get('disable_core_css')) {
572 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
573 }
574 // crm-i.css added ahead of other styles so it can be overridden by FA.
575 $this->addStyleFile('civicrm', 'css/crm-i.css', -101, $region);
576 }
577 return $this;
578 }
579
580 /**
581 * Flushes cached translated strings.
582 * @return CRM_Core_Resources
583 */
584 public function flushStrings() {
585 $this->strings->flush();
586 return $this;
587 }
588
589 /**
590 * @return CRM_Core_Resources_Strings
591 */
592 public function getStrings() {
593 return $this->strings;
594 }
595
596 /**
597 * Create dynamic script for localizing js widgets.
598 */
599 public static function outputLocalizationJS() {
600 CRM_Core_Page_AJAX::setJsHeaders();
601 $config = CRM_Core_Config::singleton();
602 $vars = [
603 'moneyFormat' => json_encode(CRM_Utils_Money::format(1234.56)),
604 'contactSearch' => json_encode($config->includeEmailInName ? ts('Start typing a name or email...') : ts('Start typing a name...')),
605 'otherSearch' => json_encode(ts('Enter search term...')),
606 'entityRef' => self::getEntityRefMetadata(),
607 'ajaxPopupsEnabled' => self::singleton()->ajaxPopupsEnabled,
608 'allowAlertAutodismissal' => (bool) Civi::settings()->get('allow_alert_autodismissal'),
609 'resourceCacheCode' => self::singleton()->getCacheCode(),
610 'locale' => CRM_Core_I18n::getLocale(),
611 'cid' => (int) CRM_Core_Session::getLoggedInContactID(),
612 ];
613 print CRM_Core_Smarty::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
614 CRM_Utils_System::civiExit();
615 }
616
617 /**
618 * List of core resources we add to every CiviCRM page.
619 *
620 * Note: non-compressed versions of .min files will be used in debug mode
621 *
622 * @param string $region
623 * @return array
624 */
625 public function coreResourceList($region) {
626 $config = CRM_Core_Config::singleton();
627
628 // Scripts needed by everyone, everywhere
629 // FIXME: This is too long; list needs finer-grained segmentation
630 $items = [
631 "bower_components/jquery/dist/jquery.min.js",
632 "bower_components/jquery-ui/jquery-ui.min.js",
633 "bower_components/jquery-ui/themes/smoothness/jquery-ui.min.css",
634 "bower_components/lodash-compat/lodash.min.js",
635 "packages/jquery/plugins/jquery.mousewheel.min.js",
636 "bower_components/select2/select2.min.js",
637 "bower_components/select2/select2.min.css",
638 "bower_components/font-awesome/css/font-awesome.min.css",
639 "packages/jquery/plugins/jquery.form.min.js",
640 "packages/jquery/plugins/jquery.timeentry.min.js",
641 "packages/jquery/plugins/jquery.blockUI.min.js",
642 "bower_components/datatables/media/js/jquery.dataTables.min.js",
643 "bower_components/datatables/media/css/jquery.dataTables.min.css",
644 "bower_components/jquery-validation/dist/jquery.validate.min.js",
645 "bower_components/jquery-validation/dist/additional-methods.min.js",
646 "packages/jquery/plugins/jquery.ui.datepicker.validation.min.js",
647 "js/Common.js",
648 "js/crm.datepicker.js",
649 "js/crm.ajax.js",
650 "js/wysiwyg/crm.wysiwyg.js",
651 ];
652
653 // Dynamic localization script
654 $items[] = $this->addCacheCode(
655 CRM_Utils_System::url('civicrm/ajax/l10n-js/' . CRM_Core_I18n::getLocale(),
656 ['cid' => CRM_Core_Session::getLoggedInContactID()], FALSE, NULL, FALSE)
657 );
658
659 // add wysiwyg editor
660 $editor = Civi::settings()->get('editor_id');
661 if ($editor == "CKEditor") {
662 CRM_Admin_Form_CKEditorConfig::setConfigDefault();
663 $items[] = [
664 'config' => [
665 'wysisygScriptLocation' => Civi::paths()->getUrl("[civicrm.root]/js/wysiwyg/crm.ckeditor.js"),
666 'CKEditorCustomConfig' => CRM_Admin_Form_CKEditorConfig::getConfigUrl(),
667 ],
668 ];
669 }
670
671 // These scripts are only needed by back-office users
672 if (CRM_Core_Permission::check('access CiviCRM')) {
673 $items[] = "packages/jquery/plugins/jquery.tableHeader.js";
674 $items[] = "packages/jquery/plugins/jquery.notify.min.js";
675 }
676
677 $contactID = CRM_Core_Session::getLoggedInContactID();
678
679 // Menubar
680 $position = 'none';
681 if (
682 $contactID && !$config->userFrameworkFrontend
683 && CRM_Core_Permission::check('access CiviCRM')
684 && !@constant('CIVICRM_DISABLE_DEFAULT_MENU')
685 && !CRM_Core_Config::isUpgradeMode()
686 ) {
687 $position = Civi::settings()->get('menubar_position') ?: 'over-cms-menu';
688 }
689 if ($position !== 'none') {
690 $items[] = 'bower_components/smartmenus/dist/jquery.smartmenus.min.js';
691 $items[] = 'bower_components/smartmenus/dist/addons/keyboard/jquery.smartmenus.keyboard.min.js';
692 $items[] = 'js/crm.menubar.js';
693 // @see CRM_Core_Resources::renderMenubarStylesheet
694 $items[] = Civi::service('asset_builder')->getUrl('crm-menubar.css', [
695 'menubarColor' => Civi::settings()->get('menubar_color'),
696 'height' => 40,
697 'breakpoint' => 768,
698 ]);
699 // Variables for crm.menubar.js
700 $items[] = [
701 'menubar' => [
702 'position' => $position,
703 'qfKey' => CRM_Core_Key::get('CRM_Contact_Controller_Search', TRUE),
704 'cacheCode' => CRM_Core_BAO_Navigation::getCacheKey($contactID),
705 ],
706 ];
707 }
708
709 // JS for multilingual installations
710 if (!empty($config->languageLimit) && count($config->languageLimit) > 1 && CRM_Core_Permission::check('translate CiviCRM')) {
711 $items[] = "js/crm.multilingual.js";
712 }
713
714 // Enable administrators to edit option lists in a dialog
715 if (CRM_Core_Permission::check('administer CiviCRM') && $this->ajaxPopupsEnabled) {
716 $items[] = "js/crm.optionEdit.js";
717 }
718
719 $tsLocale = CRM_Core_I18n::getLocale();
720 // Add localized jQuery UI files
721 if ($tsLocale && $tsLocale != 'en_US') {
722 // Search for i18n file in order of specificity (try fr-CA, then fr)
723 list($lang) = explode('_', $tsLocale);
724 $path = "bower_components/jquery-ui/ui/i18n";
725 foreach ([str_replace('_', '-', $tsLocale), $lang] as $language) {
726 $localizationFile = "$path/datepicker-{$language}.js";
727 if ($this->getPath('civicrm', $localizationFile)) {
728 $items[] = $localizationFile;
729 break;
730 }
731 }
732 }
733
734 // Allow hooks to modify this list
735 CRM_Utils_Hook::coreResourceList($items, $region);
736
737 // Oof, existing listeners would expect $items to typically begin with 'bower_components/' or 'packages/'
738 // (using an implicit base of `[civicrm.root]`). We preserve the hook contract and cleanup $items post-hook.
739 $map = [
740 'bower_components' => rtrim(Civi::paths()->getUrl('[civicrm.bower]/.', 'absolute'), '/'),
741 'packages' => rtrim(Civi::paths()->getUrl('[civicrm.packages]/.', 'absolute'), '/'),
742 ];
743 $filter = function($m) use ($map) {
744 return $map[$m[1]] . $m[2];
745 };
746 $items = array_map(function($item) use ($filter) {
747 return is_array($item) ? $item : preg_replace_callback(';^(bower_components|packages)(/.*);', $filter, $item);
748 }, $items);
749
750 return $items;
751 }
752
753 /**
754 * @return bool
755 * is this page request an ajax snippet?
756 */
757 public static function isAjaxMode() {
758 if (in_array(CRM_Utils_Array::value('snippet', $_REQUEST), [
759 CRM_Core_Smarty::PRINT_SNIPPET,
760 CRM_Core_Smarty::PRINT_NOFORM,
761 CRM_Core_Smarty::PRINT_JSON,
762 ])
763 ) {
764 return TRUE;
765 }
766 list($arg0, $arg1) = array_pad(explode('/', CRM_Utils_System::currentPath()), 2, '');
767 return ($arg0 === 'civicrm' && in_array($arg1, ['ajax', 'angularprofiles', 'asset']));
768 }
769
770 /**
771 * @param \Civi\Core\Event\GenericHookEvent $e
772 * @see \CRM_Utils_Hook::buildAsset()
773 */
774 public static function renderMenubarStylesheet(GenericHookEvent $e) {
775 if ($e->asset !== 'crm-menubar.css') {
776 return;
777 }
778 $e->mimeType = 'text/css';
779 $content = '';
780 $config = CRM_Core_Config::singleton();
781 $cms = strtolower($config->userFramework);
782 $cms = $cms === 'drupal' ? 'drupal7' : $cms;
783 $items = [
784 'bower_components/smartmenus/dist/css/sm-core-css.css',
785 'css/crm-menubar.css',
786 "css/menubar-$cms.css",
787 ];
788 foreach ($items as $item) {
789 $content .= file_get_contents(self::singleton()->getPath('civicrm', $item));
790 }
791 $params = $e->params;
792 // "color" is deprecated in favor of the more specific "menubarColor"
793 $menubarColor = $params['color'] ?? $params['menubarColor'];
794 $vars = [
795 '$resourceBase' => rtrim($config->resourceBase, '/'),
796 '$menubarHeight' => $params['height'] . 'px',
797 '$breakMin' => $params['breakpoint'] . 'px',
798 '$breakMax' => ($params['breakpoint'] - 1) . 'px',
799 '$menubarColor' => $menubarColor,
800 '$menuItemColor' => $params['menuItemColor'] ?? $menubarColor,
801 '$highlightColor' => $params['highlightColor'] ?? CRM_Utils_Color::getHighlight($menubarColor),
802 '$textColor' => $params['textColor'] ?? CRM_Utils_Color::getContrast($menubarColor, '#333', '#ddd'),
803 ];
804 $vars['$highlightTextColor'] = $params['highlightTextColor'] ?? CRM_Utils_Color::getContrast($vars['$highlightColor'], '#333', '#ddd');
805 $e->content = str_replace(array_keys($vars), array_values($vars), $content);
806 }
807
808 /**
809 * Provide a list of available entityRef filters.
810 *
811 * @return array
812 */
813 public static function getEntityRefMetadata() {
814 $data = [
815 'filters' => [],
816 'links' => [],
817 ];
818 $config = CRM_Core_Config::singleton();
819
820 $disabledComponents = [];
821 $dao = CRM_Core_DAO::executeQuery("SELECT name, namespace FROM civicrm_component");
822 while ($dao->fetch()) {
823 if (!in_array($dao->name, $config->enableComponents)) {
824 $disabledComponents[$dao->name] = $dao->namespace;
825 }
826 }
827
828 foreach (CRM_Core_DAO_AllCoreTables::daoToClass() as $entity => $daoName) {
829 // Skip DAOs of disabled components
830 foreach ($disabledComponents as $nameSpace) {
831 if (strpos($daoName, $nameSpace) === 0) {
832 continue 2;
833 }
834 }
835 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
836 if (class_exists($baoName)) {
837 $filters = $baoName::getEntityRefFilters();
838 if ($filters) {
839 $data['filters'][$entity] = $filters;
840 }
841 if (is_callable([$baoName, 'getEntityRefCreateLinks'])) {
842 $createLinks = $baoName::getEntityRefCreateLinks();
843 if ($createLinks) {
844 $data['links'][$entity] = $createLinks;
845 }
846 }
847 }
848 }
849
850 CRM_Utils_Hook::entityRefFilters($data['filters'], $data['links']);
851
852 return $data;
853 }
854
855 /**
856 * Determine the minified file name.
857 *
858 * @param string $ext
859 * @param string $file
860 * @return string
861 * An updated $fileName. If a minified version exists and is supported by
862 * system policy, the minified version will be returned. Otherwise, the original.
863 */
864 public function filterMinify($ext, $file) {
865 if (CRM_Core_Config::singleton()->debug && strpos($file, '.min.') !== FALSE) {
866 $nonMiniFile = str_replace('.min.', '.', $file);
867 if ($this->getPath($ext, $nonMiniFile)) {
868 $file = $nonMiniFile;
869 }
870 }
871 return $file;
872 }
873
874 /**
875 * @param string $url
876 * @return string
877 */
878 public function addCacheCode($url) {
879 $hasQuery = strpos($url, '?') !== FALSE;
880 $operator = $hasQuery ? '&' : '?';
881
882 return $url . $operator . 'r=' . $this->cacheCode;
883 }
884
885 /**
886 * Checks if the given URL is fully-formed
887 *
888 * @param string $url
889 *
890 * @return bool
891 */
892 public static function isFullyFormedUrl($url) {
893 return (substr($url, 0, 4) === 'http') || (substr($url, 0, 1) === '/');
894 }
895
896 /**
897 * @param string|NULL $region
898 * Optional request for a specific region. If NULL/omitted, use global default.
899 * @return \CRM_Core_Region
900 */
901 private function getSettingRegion($region = NULL) {
902 $region = $region ?: (self::isAjaxMode() ? 'ajax-snippet' : 'html-header');
903 return CRM_Core_Region::instance($region);
904 }
905
906 }