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