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