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