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