Our changes
[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 $js = 'var CRM = ' . json_encode($this->getSettings()) . ';';
367 //return sprintf("<script type=\"text/javascript\">\n%s\n</script>\n", $js);
368 return sprintf("<script type=\"text/javascript\">\n// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3\n%s\n// @license-end\n</script>\n", $js);
369 }
370
371 /**
372 * Add translated string to the js CRM object.
373 * It can then be retrived from the client-side ts() function
374 * Variable substitutions can happen from client-side
375 *
376 * Note: this function rarely needs to be called directly and is mostly for internal use.
377 * See CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
378 *
379 * Simple example:
380 * // From php:
381 * CRM_Core_Resources::singleton()->addString('Hello');
382 * // The string is now available to javascript code i.e.
383 * ts('Hello');
384 *
385 * Example with client-side substitutions:
386 * // From php:
387 * CRM_Core_Resources::singleton()->addString('Your %1 has been %2');
388 * // ts() in javascript works the same as in php, for example:
389 * ts('Your %1 has been %2', {1: objectName, 2: actionTaken});
390 *
391 * NOTE: This function does not work with server-side substitutions
392 * (as this might result in collisions and unwanted variable injections)
393 * Instead, use code like:
394 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs)))));
395 * And from javascript access it at CRM.myNamespace.myString
396 *
397 * @param string|array $text
398 * @param string|null $domain
399 * @return CRM_Core_Resources
400 */
401 public function addString($text, $domain = 'civicrm') {
402 foreach ((array) $text as $str) {
403 $translated = ts($str, [
404 'domain' => ($domain == 'civicrm') ? NULL : [$domain, NULL],
405 'raw' => TRUE,
406 ]);
407
408 // We only need to push this string to client if the translation
409 // is actually different from the original
410 if ($translated != $str) {
411 $bucket = $domain == 'civicrm' ? 'strings' : 'strings::' . $domain;
412 $this->addSetting([
413 $bucket => [$str => $translated],
414 ]);
415 }
416 }
417 return $this;
418 }
419
420 /**
421 * Add a CSS file to the current page using <LINK HREF>.
422 *
423 * @param string $ext
424 * extension name; use 'civicrm' for core.
425 * @param string $file
426 * file path -- relative to the extension base dir.
427 * @param int $weight
428 * relative weight within a given region.
429 * @param string $region
430 * location within the file; 'html-header', 'page-header', 'page-footer'.
431 * @return CRM_Core_Resources
432 */
433 public function addStyleFile($ext, $file, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
434 /** @var Civi\Core\Themes $theme */
435 $theme = Civi::service('themes');
436 foreach ($theme->resolveUrls($theme->getActiveThemeKey(), $ext, $file) as $url) {
437 $this->addStyleUrl($url, $weight, $region);
438 }
439 return $this;
440 }
441
442 /**
443 * Add a CSS file to the current page using <LINK HREF>.
444 *
445 * @param string $url
446 * @param int $weight
447 * relative weight within a given region.
448 * @param string $region
449 * location within the file; 'html-header', 'page-header', 'page-footer'.
450 * @return CRM_Core_Resources
451 */
452 public function addStyleUrl($url, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
453 CRM_Core_Region::instance($region)->add([
454 'name' => $url,
455 'type' => 'styleUrl',
456 'styleUrl' => $url,
457 'weight' => $weight,
458 'region' => $region,
459 ]);
460 return $this;
461 }
462
463 /**
464 * Add a CSS content to the current page using <STYLE>.
465 *
466 * @param string $code
467 * CSS source code.
468 * @param int $weight
469 * relative weight within a given region.
470 * @param string $region
471 * location within the file; 'html-header', 'page-header', 'page-footer'.
472 * @return CRM_Core_Resources
473 */
474 public function addStyle($code, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
475 CRM_Core_Region::instance($region)->add([
476 // 'name' => automatic
477 'type' => 'style',
478 'style' => $code,
479 'weight' => $weight,
480 'region' => $region,
481 ]);
482 return $this;
483 }
484
485 /**
486 * Determine file path of a resource provided by an extension.
487 *
488 * @param string $ext
489 * extension name; use 'civicrm' for core.
490 * @param string|null $file
491 * file path -- relative to the extension base dir.
492 *
493 * @return bool|string
494 * full file path or FALSE if not found
495 */
496 public function getPath($ext, $file = NULL) {
497 // TODO consider caching results
498 $base = $this->paths->hasVariable($ext)
499 ? rtrim($this->paths->getVariable($ext, 'path'), '/')
500 : $this->extMapper->keyToBasePath($ext);
501 if ($file === NULL) {
502 return $base;
503 }
504 $path = $base . '/' . $file;
505 if (is_file($path)) {
506 return $path;
507 }
508 return FALSE;
509 }
510
511 /**
512 * Determine public URL of a resource provided by an extension.
513 *
514 * @param string $ext
515 * extension name; use 'civicrm' for core.
516 * @param string $file
517 * file path -- relative to the extension base dir.
518 * @param bool $addCacheCode
519 *
520 * @return string, URL
521 */
522 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
523 if ($file === NULL) {
524 $file = '';
525 }
526 if ($addCacheCode) {
527 $file = $this->addCacheCode($file);
528 }
529 // TODO consider caching results
530 $base = $this->paths->hasVariable($ext)
531 ? $this->paths->getVariable($ext, 'url')
532 : ($this->extMapper->keyToUrl($ext) . '/');
533 return $base . $file;
534 }
535
536 /**
537 * Evaluate a glob pattern in the context of a particular extension.
538 *
539 * @param string $ext
540 * Extension name; use 'civicrm' for core.
541 * @param string|array $patterns
542 * Glob pattern; e.g. "*.html".
543 * @param null|int $flags
544 * See glob().
545 * @return array
546 * List of matching files, relative to the extension base dir.
547 * @see glob()
548 */
549 public function glob($ext, $patterns, $flags = NULL) {
550 $path = $this->getPath($ext);
551 $patterns = (array) $patterns;
552 $files = [];
553 foreach ($patterns as $pattern) {
554 if (preg_match(';^(assetBuilder|ext)://;', $pattern)) {
555 $files[] = $pattern;
556 }
557 if (CRM_Utils_File::isAbsolute($pattern)) {
558 // Absolute path.
559 $files = array_merge($files, (array) glob($pattern, $flags));
560 }
561 else {
562 // Relative path.
563 $files = array_merge($files, (array) glob("$path/$pattern", $flags));
564 }
565 }
566 // Deterministic order.
567 sort($files);
568 $files = array_unique($files);
569 return array_map(function ($file) use ($path) {
570 return CRM_Utils_File::relativize($file, "$path/");
571 }, $files);
572 }
573
574 /**
575 * @return string
576 */
577 public function getCacheCode() {
578 return $this->cacheCode;
579 }
580
581 /**
582 * @param $value
583 * @return CRM_Core_Resources
584 */
585 public function setCacheCode($value) {
586 $this->cacheCode = $value;
587 if ($this->cacheCodeKey) {
588 Civi::settings()->set($this->cacheCodeKey, $value);
589 }
590 return $this;
591 }
592
593 /**
594 * @return CRM_Core_Resources
595 */
596 public function resetCacheCode() {
597 $this->setCacheCode(CRM_Utils_String::createRandom(5, CRM_Utils_String::ALPHANUMERIC));
598 // Also flush cms resource cache if needed
599 CRM_Core_Config::singleton()->userSystem->clearResourceCache();
600 return $this;
601 }
602
603 /**
604 * This adds CiviCRM's standard css and js to the specified region of the document.
605 * It will only run once.
606 *
607 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
608 * (like addCoreResources/addCoreStyles).
609 *
610 * @param string $region
611 * @return CRM_Core_Resources
612 */
613 public function addCoreResources($region = 'html-header') {
614 if (!isset($this->addedCoreResources[$region]) && !self::isAjaxMode()) {
615 $this->addedCoreResources[$region] = TRUE;
616 $config = CRM_Core_Config::singleton();
617
618 // Add resources from coreResourceList
619 $jsWeight = -9999;
620 foreach ($this->coreResourceList($region) as $item) {
621 if (is_array($item)) {
622 $this->addSetting($item);
623 }
624 elseif (strpos($item, '.css')) {
625 $this->isFullyFormedUrl($item) ? $this->addStyleUrl($item, -100, $region) : $this->addStyleFile('civicrm', $item, -100, $region);
626 }
627 elseif ($this->isFullyFormedUrl($item)) {
628 $this->addScriptUrl($item, $jsWeight++, $region);
629 }
630 else {
631 // Don't bother looking for ts() calls in packages, there aren't any
632 $translate = (substr($item, 0, 3) == 'js/');
633 $this->addScriptFile('civicrm', $item, $jsWeight++, $region, $translate);
634 }
635 }
636 // Add global settings
637 $settings = [
638 'config' => [
639 'isFrontend' => $config->userFrameworkFrontend,
640 ],
641 ];
642 // Disable profile creation if user lacks permission
643 if (!CRM_Core_Permission::check('edit all contacts') && !CRM_Core_Permission::check('add contacts')) {
644 $settings['config']['entityRef']['contactCreate'] = FALSE;
645 }
646 $this->addSetting($settings);
647
648 // Give control of jQuery and _ back to the CMS - this loads last
649 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
650
651 $this->addCoreStyles($region);
652 }
653 return $this;
654 }
655
656 /**
657 * This will add CiviCRM's standard CSS
658 *
659 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
660 * (like addCoreResources/addCoreStyles).
661 *
662 * @param string $region
663 * @return CRM_Core_Resources
664 */
665 public function addCoreStyles($region = 'html-header') {
666 if (!isset($this->addedCoreStyles[$region])) {
667 $this->addedCoreStyles[$region] = TRUE;
668
669 // Load custom or core css
670 $config = CRM_Core_Config::singleton();
671 if (!empty($config->customCSSURL)) {
672 $customCSSURL = $this->addCacheCode($config->customCSSURL);
673 $this->addStyleUrl($customCSSURL, 99, $region);
674 }
675 if (!Civi::settings()->get('disable_core_css')) {
676 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
677 }
678 // crm-i.css added ahead of other styles so it can be overridden by FA.
679 $this->addStyleFile('civicrm', 'css/crm-i.css', -101, $region);
680 }
681 return $this;
682 }
683
684 /**
685 * Flushes cached translated strings.
686 * @return CRM_Core_Resources
687 */
688 public function flushStrings() {
689 $this->strings->flush();
690 return $this;
691 }
692
693 /**
694 * @return CRM_Core_Resources_Strings
695 */
696 public function getStrings() {
697 return $this->strings;
698 }
699
700 /**
701 * Create dynamic script for localizing js widgets.
702 */
703 public static function outputLocalizationJS() {
704 CRM_Core_Page_AJAX::setJsHeaders();
705 $config = CRM_Core_Config::singleton();
706 $vars = [
707 'moneyFormat' => json_encode(CRM_Utils_Money::format(1234.56)),
708 'contactSearch' => json_encode($config->includeEmailInName ? ts('Start typing a name or email...') : ts('Start typing a name...')),
709 'otherSearch' => json_encode(ts('Enter search term...')),
710 'entityRef' => self::getEntityRefMetadata(),
711 'ajaxPopupsEnabled' => self::singleton()->ajaxPopupsEnabled,
712 'allowAlertAutodismissal' => (bool) Civi::settings()->get('allow_alert_autodismissal'),
713 'resourceCacheCode' => self::singleton()->getCacheCode(),
714 'locale' => CRM_Core_I18n::getLocale(),
715 'cid' => (int) CRM_Core_Session::getLoggedInContactID(),
716 ];
717 print CRM_Core_Smarty::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
718 CRM_Utils_System::civiExit();
719 }
720
721 /**
722 * List of core resources we add to every CiviCRM page.
723 *
724 * Note: non-compressed versions of .min files will be used in debug mode
725 *
726 * @param string $region
727 * @return array
728 */
729 public function coreResourceList($region) {
730 $config = CRM_Core_Config::singleton();
731
732 // Scripts needed by everyone, everywhere
733 // FIXME: This is too long; list needs finer-grained segmentation
734 $items = [
735 "bower_components/jquery/dist/jquery.min.js",
736 "bower_components/jquery-ui/jquery-ui.min.js",
737 "bower_components/jquery-ui/themes/smoothness/jquery-ui.min.css",
738 "bower_components/lodash-compat/lodash.min.js",
739 "packages/jquery/plugins/jquery.mousewheel.min.js",
740 "bower_components/select2/select2.min.js",
741 "bower_components/select2/select2.min.css",
742 "bower_components/font-awesome/css/font-awesome.min.css",
743 "packages/jquery/plugins/jquery.form.min.js",
744 "packages/jquery/plugins/jquery.timeentry.min.js",
745 "packages/jquery/plugins/jquery.blockUI.min.js",
746 "bower_components/datatables/media/js/jquery.dataTables.min.js",
747 "bower_components/datatables/media/css/jquery.dataTables.min.css",
748 "bower_components/jquery-validation/dist/jquery.validate.min.js",
749 "packages/jquery/plugins/jquery.ui.datepicker.validation.min.js",
750 "js/Common.js",
751 "js/crm.datepicker.js",
752 "js/crm.ajax.js",
753 "js/wysiwyg/crm.wysiwyg.js",
754 ];
755
756 // Dynamic localization script
757 $items[] = $this->addCacheCode(
758 CRM_Utils_System::url('civicrm/ajax/l10n-js/' . CRM_Core_I18n::getLocale(),
759 ['cid' => CRM_Core_Session::getLoggedInContactID()], FALSE, NULL, FALSE)
760 );
761
762 // add wysiwyg editor
763 $editor = Civi::settings()->get('editor_id');
764 if ($editor == "CKEditor") {
765 CRM_Admin_Page_CKEditorConfig::setConfigDefault();
766 $items[] = [
767 'config' => [
768 'wysisygScriptLocation' => Civi::paths()->getUrl("[civicrm.root]/js/wysiwyg/crm.ckeditor.js"),
769 'CKEditorCustomConfig' => CRM_Admin_Page_CKEditorConfig::getConfigUrl(),
770 ],
771 ];
772 }
773
774 // These scripts are only needed by back-office users
775 if (CRM_Core_Permission::check('access CiviCRM')) {
776 $items[] = "packages/jquery/plugins/jquery.tableHeader.js";
777 $items[] = "packages/jquery/plugins/jquery.notify.min.js";
778 }
779
780 $contactID = CRM_Core_Session::getLoggedInContactID();
781
782 // Menubar
783 $position = 'none';
784 if (
785 $contactID && !$config->userFrameworkFrontend
786 && CRM_Core_Permission::check('access CiviCRM')
787 && !@constant('CIVICRM_DISABLE_DEFAULT_MENU')
788 && !CRM_Core_Config::isUpgradeMode()
789 ) {
790 $position = Civi::settings()->get('menubar_position') ?: 'over-cms-menu';
791 }
792 if ($position !== 'none') {
793 $items[] = 'bower_components/smartmenus/dist/jquery.smartmenus.min.js';
794 $items[] = 'bower_components/smartmenus/dist/addons/keyboard/jquery.smartmenus.keyboard.min.js';
795 $items[] = 'js/crm.menubar.js';
796 // @see CRM_Core_Resources::renderMenubarStylesheet
797 $items[] = Civi::service('asset_builder')->getUrl('crm-menubar.css', [
798 'menubarColor' => Civi::settings()->get('menubar_color'),
799 'height' => 40,
800 'breakpoint' => 768,
801 ]);
802 // Variables for crm.menubar.js
803 $items[] = [
804 'menubar' => [
805 'position' => $position,
806 'qfKey' => CRM_Core_Key::get('CRM_Contact_Controller_Search', TRUE),
807 'cacheCode' => CRM_Core_BAO_Navigation::getCacheKey($contactID),
808 ],
809 ];
810 }
811
812 // JS for multilingual installations
813 if (!empty($config->languageLimit) && count($config->languageLimit) > 1 && CRM_Core_Permission::check('translate CiviCRM')) {
814 $items[] = "js/crm.multilingual.js";
815 }
816
817 // Enable administrators to edit option lists in a dialog
818 if (CRM_Core_Permission::check('administer CiviCRM') && $this->ajaxPopupsEnabled) {
819 $items[] = "js/crm.optionEdit.js";
820 }
821
822 $tsLocale = CRM_Core_I18n::getLocale();
823 // Add localized jQuery UI files
824 if ($tsLocale && $tsLocale != 'en_US') {
825 // Search for i18n file in order of specificity (try fr-CA, then fr)
826 list($lang) = explode('_', $tsLocale);
827 $path = "bower_components/jquery-ui/ui/i18n";
828 foreach ([str_replace('_', '-', $tsLocale), $lang] as $language) {
829 $localizationFile = "$path/datepicker-{$language}.js";
830 if ($this->getPath('civicrm', $localizationFile)) {
831 $items[] = $localizationFile;
832 break;
833 }
834 }
835 }
836
837 // Allow hooks to modify this list
838 CRM_Utils_Hook::coreResourceList($items, $region);
839
840 return $items;
841 }
842
843 /**
844 * @return bool
845 * is this page request an ajax snippet?
846 */
847 public static function isAjaxMode() {
848 if (in_array(CRM_Utils_Array::value('snippet', $_REQUEST), [
849 CRM_Core_Smarty::PRINT_SNIPPET,
850 CRM_Core_Smarty::PRINT_NOFORM,
851 CRM_Core_Smarty::PRINT_JSON,
852 ])
853 ) {
854 return TRUE;
855 }
856 list($arg0, $arg1) = array_pad(explode('/', CRM_Utils_System::getUrlPath()), 2, '');
857 return ($arg0 === 'civicrm' && in_array($arg1, ['ajax', 'angularprofiles', 'asset']));
858 }
859
860 /**
861 * @param \Civi\Core\Event\GenericHookEvent $e
862 * @see \CRM_Utils_Hook::buildAsset()
863 */
864 public static function renderMenubarStylesheet(GenericHookEvent $e) {
865 if ($e->asset !== 'crm-menubar.css') {
866 return;
867 }
868 $e->mimeType = 'text/css';
869 $content = '';
870 $config = CRM_Core_Config::singleton();
871 $cms = strtolower($config->userFramework);
872 $cms = $cms === 'drupal' ? 'drupal7' : $cms;
873 $items = [
874 'bower_components/smartmenus/dist/css/sm-core-css.css',
875 'css/crm-menubar.css',
876 "css/menubar-$cms.css",
877 ];
878 foreach ($items as $item) {
879 $content .= file_get_contents(self::singleton()->getPath('civicrm', $item));
880 }
881 $params = $e->params;
882 // "color" is deprecated in favor of the more specific "menubarColor"
883 $menubarColor = $params['color'] ?? $params['menubarColor'];
884 $vars = [
885 '$resourceBase' => rtrim($config->resourceBase, '/'),
886 '$menubarHeight' => $params['height'] . 'px',
887 '$breakMin' => $params['breakpoint'] . 'px',
888 '$breakMax' => ($params['breakpoint'] - 1) . 'px',
889 '$menubarColor' => $menubarColor,
890 '$menuItemColor' => $params['menuItemColor'] ?? 'rgba(' . implode(', ', CRM_Utils_Color::getRgb($menubarColor)) . ", .9)",
891 '$highlightColor' => $params['highlightColor'] ?? CRM_Utils_Color::getHighlight($menubarColor),
892 '$textColor' => $params['textColor'] ?? CRM_Utils_Color::getContrast($menubarColor, '#333', '#ddd'),
893 ];
894 $vars['$highlightTextColor'] = $params['highlightTextColor'] ?? CRM_Utils_Color::getContrast($vars['$highlightColor'], '#333', '#ddd');
895 $e->content = str_replace(array_keys($vars), array_values($vars), $content);
896 }
897
898 /**
899 * Provide a list of available entityRef filters.
900 *
901 * @return array
902 */
903 public static function getEntityRefMetadata() {
904 $data = [
905 'filters' => [],
906 'links' => [],
907 ];
908 $config = CRM_Core_Config::singleton();
909
910 $disabledComponents = [];
911 $dao = CRM_Core_DAO::executeQuery("SELECT name, namespace FROM civicrm_component");
912 while ($dao->fetch()) {
913 if (!in_array($dao->name, $config->enableComponents)) {
914 $disabledComponents[$dao->name] = $dao->namespace;
915 }
916 }
917
918 foreach (CRM_Core_DAO_AllCoreTables::daoToClass() as $entity => $daoName) {
919 // Skip DAOs of disabled components
920 foreach ($disabledComponents as $nameSpace) {
921 if (strpos($daoName, $nameSpace) === 0) {
922 continue 2;
923 }
924 }
925 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
926 if (class_exists($baoName)) {
927 $filters = $baoName::getEntityRefFilters();
928 if ($filters) {
929 $data['filters'][$entity] = $filters;
930 }
931 if (is_callable([$baoName, 'getEntityRefCreateLinks'])) {
932 $createLinks = $baoName::getEntityRefCreateLinks();
933 if ($createLinks) {
934 $data['links'][$entity] = $createLinks;
935 }
936 }
937 }
938 }
939
940 CRM_Utils_Hook::entityRefFilters($data['filters']);
941
942 return $data;
943 }
944
945 /**
946 * Determine the minified file name.
947 *
948 * @param string $ext
949 * @param string $file
950 * @return string
951 * An updated $fileName. If a minified version exists and is supported by
952 * system policy, the minified version will be returned. Otherwise, the original.
953 */
954 public function filterMinify($ext, $file) {
955 if (CRM_Core_Config::singleton()->debug && strpos($file, '.min.') !== FALSE) {
956 $nonMiniFile = str_replace('.min.', '.', $file);
957 if ($this->getPath($ext, $nonMiniFile)) {
958 $file = $nonMiniFile;
959 }
960 }
961 return $file;
962 }
963
964 /**
965 * @param string $url
966 * @return string
967 */
968 public function addCacheCode($url) {
969 $hasQuery = strpos($url, '?') !== FALSE;
970 $operator = $hasQuery ? '&' : '?';
971
972 return $url . $operator . 'r=' . $this->cacheCode;
973 }
974
975 /**
976 * Checks if the given URL is fully-formed
977 *
978 * @param string $url
979 *
980 * @return bool
981 */
982 public static function isFullyFormedUrl($url) {
983 return (substr($url, 0, 4) === 'http') || (substr($url, 0, 1) === '/');
984 }
985
986 }