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