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