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