Our changes
[civicrm-core.git] / CRM / Core / Resources.php
CommitLineData
6a488035
TO
1<?php
2/*
8d7a9d07 3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
8d7a9d07 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
8d7a9d07
CB
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 +--------------------------------------------------------------------+
e70a7fc0 26 */
1889d803 27use Civi\Core\Event\GenericHookEvent;
6a488035
TO
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
6b83d5bd 41 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
42 * $Id$
43 *
44 */
45class 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
6a488035
TO
53 */
54 private static $_singleton = NULL;
55
56 /**
57 * @var CRM_Extension_Mapper
58 */
59 private $extMapper = NULL;
60
61 /**
fd7dc3f3 62 * @var CRM_Core_Resources_Strings
6a488035 63 */
fd7dc3f3 64 private $strings = NULL;
6a488035
TO
65
66 /**
e97c66ff 67 * Settings in free-form data tree.
68 *
69 * @var array
6a488035 70 */
be2fb01f 71 protected $settings = [];
6a488035
TO
72 protected $addedSettings = FALSE;
73
74 /**
e97c66ff 75 * Setting factories.
76 *
77 * @var callable[]
6a488035 78 */
be2fb01f 79 protected $settingsFactories = [];
6a488035
TO
80
81 /**
e97c66ff 82 * Added core resources.
83 *
84 * Format is ($regionName => bool).
85 *
86 * @var array
6a488035 87 */
be2fb01f 88 protected $addedCoreResources = [];
6a488035
TO
89
90 /**
e97c66ff 91 * Added core styles.
92 *
93 * Format is ($regionName => bool).
94 *
95 * @var array
6a488035 96 */
be2fb01f 97 protected $addedCoreStyles = [];
6a488035
TO
98
99 /**
e97c66ff 100 * A value to append to JS/CSS URLs to coerce cache resets.
101 *
102 * @var string
6a488035
TO
103 */
104 protected $cacheCode = NULL;
105
106 /**
e97c66ff 107 * The name of a setting which persistently stores the cacheCode.
108 *
109 * @var string
6a488035
TO
110 */
111 protected $cacheCodeKey = NULL;
112
53f2643c 113 /**
e97c66ff 114 * Are ajax popup screens enabled.
115 *
53f2643c
CW
116 * @var bool
117 */
118 public $ajaxPopupsEnabled;
119
b698e2d5
TO
120 /**
121 * @var \Civi\Core\Paths
122 */
123 protected $paths;
124
6a488035 125 /**
fe482240 126 * Get or set the single instance of CRM_Core_Resources.
6a488035 127 *
5a4f6742
CW
128 * @param CRM_Core_Resources $instance
129 * New copy of the manager.
e97c66ff 130 *
6a488035
TO
131 * @return CRM_Core_Resources
132 */
518fa0ee 133 public static function singleton(CRM_Core_Resources $instance = NULL) {
6a488035
TO
134 if ($instance !== NULL) {
135 self::$_singleton = $instance;
136 }
137 if (self::$_singleton === NULL) {
223ba025 138 self::$_singleton = Civi::service('resources');
6a488035
TO
139 }
140 return self::$_singleton;
141 }
142
143 /**
d09edf64 144 * Construct a resource manager.
6a488035 145 *
6a0b768e
TO
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.
3be754d6 150 * @param string|null $cacheCodeKey Random code to append to resource URLs; changing the code forces clients to reload resources
6a488035
TO
151 */
152 public function __construct($extMapper, $cache, $cacheCodeKey = NULL) {
153 $this->extMapper = $extMapper;
fd7dc3f3 154 $this->strings = new CRM_Core_Resources_Strings($cache);
6a488035
TO
155 $this->cacheCodeKey = $cacheCodeKey;
156 if ($cacheCodeKey !== NULL) {
aaffa79f 157 $this->cacheCode = Civi::settings()->get($cacheCodeKey);
6a488035 158 }
150f50c1 159 if (!$this->cacheCode) {
6a488035
TO
160 $this->resetCacheCode();
161 }
84fb7424 162 $this->ajaxPopupsEnabled = (bool) Civi::settings()->get('ajaxPopupsEnabled');
b698e2d5 163 $this->paths = Civi::paths();
6a488035
TO
164 }
165
90efc417
TO
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;
be2fb01f 180 $perms = [];
90efc417
TO
181 foreach ($permNames as $permName) {
182 $perms[$permName] = CRM_Core_Permission::check($permName);
183 }
be2fb01f 184 return $this->addSetting([
90efc417 185 'permissions' => $perms,
be2fb01f 186 ]);
90efc417
TO
187 }
188
6a488035
TO
189 /**
190 * Add a JavaScript file to the current page using <SCRIPT SRC>.
191 *
5a4f6742
CW
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'.
3f3bba82
TO
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.
6a488035
TO
205 *
206 * @return CRM_Core_Resources
e97c66ff 207 * @throws \Exception
6a488035
TO
208 */
209 public function addScriptFile($ext, $file, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION, $translate = TRUE) {
210 if ($translate) {
3f3bba82
TO
211 $domain = ($translate === TRUE) ? $ext : $translate;
212 $this->addString($this->strings->get($domain, $this->getPath($ext, $file), 'text/javascript'), $domain);
6a488035 213 }
d89d2545
TO
214 $url = $this->getUrl($ext, $this->filterMinify($ext, $file), TRUE);
215 return $this->addScriptUrl($url, $weight, $region);
6a488035
TO
216 }
217
218 /**
219 * Add a JavaScript file to the current page using <SCRIPT SRC>.
220 *
5a4f6742
CW
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'.
6a488035
TO
226 * @return CRM_Core_Resources
227 */
228 public function addScriptUrl($url, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
be2fb01f 229 CRM_Core_Region::instance($region)->add([
518fa0ee
SL
230 'name' => $url,
231 'type' => 'scriptUrl',
232 'scriptUrl' => $url,
233 'weight' => $weight,
234 'region' => $region,
235 ]);
6a488035
TO
236 return $this;
237 }
238
239 /**
240 * Add a JavaScript file to the current page using <SCRIPT SRC>.
241 *
5a4f6742
CW
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'.
6a488035
TO
248 * @return CRM_Core_Resources
249 */
250 public function addScript($code, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
be2fb01f 251 CRM_Core_Region::instance($region)->add([
8d7a9d07 252 // 'name' => automatic
518fa0ee
SL
253 'type' => 'script',
254 'script' => $code,
255 'weight' => $weight,
256 'region' => $region,
257 ]);
6a488035
TO
258 return $this;
259 }
260
261 /**
73bcd446 262 * Add JavaScript variables to CRM.vars
6a488035 263 *
132fc68e
CW
264 * Example:
265 * From the server:
73bcd446
CW
266 * CRM_Core_Resources::singleton()->addVars('myNamespace', array('foo' => 'bar'));
267 * Access var from javascript:
268 * CRM.vars.myNamespace.foo // "bar"
132fc68e 269 *
01478033 270 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Javascript+Reference
132fc68e 271 *
6a0b768e
TO
272 * @param string $nameSpace
273 * Usually the name of your extension.
73bcd446
CW
274 * @param array $vars
275 * @return CRM_Core_Resources
276 */
277 public function addVars($nameSpace, $vars) {
be2fb01f 278 $existing = CRM_Utils_Array::value($nameSpace, CRM_Utils_Array::value('vars', $this->settings), []);
73bcd446 279 $vars = $this->mergeSettings($existing, $vars);
be2fb01f 280 $this->addSetting(['vars' => [$nameSpace => $vars]]);
73bcd446
CW
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 *
5a4f6742 289 * @param array $settings
6a488035
TO
290 * @return CRM_Core_Resources
291 */
292 public function addSetting($settings) {
293 $this->settings = $this->mergeSettings($this->settings, $settings);
294 if (!$this->addedSettings) {
88cd8875 295 $region = self::isAjaxMode() ? 'ajax-snippet' : 'html-header';
6a488035 296 $resources = $this;
be2fb01f 297 CRM_Core_Region::instance($region)->add([
353ffa53
TO
298 'callback' => function (&$snippet, &$html) use ($resources) {
299 $html .= "\n" . $resources->renderSetting();
300 },
8cb324cc 301 'weight' => -100000,
be2fb01f 302 ]);
6a488035
TO
303 $this->addedSettings = TRUE;
304 }
305 return $this;
306 }
307
308 /**
69847402 309 * Add JavaScript variables to the global CRM object via a callback function.
6a488035 310 *
3be754d6 311 * @param callable $callable
6a488035
TO
312 * @return CRM_Core_Resources
313 */
314 public function addSettingsFactory($callable) {
d937dbcd 315 // Make sure our callback has been registered
be2fb01f 316 $this->addSetting([]);
6a488035
TO
317 $this->settingsFactories[] = $callable;
318 return $this;
319 }
320
69847402 321 /**
d09edf64 322 * Helper fn for addSettingsFactory.
69847402 323 */
6a488035
TO
324 public function getSettings() {
325 $result = $this->settings;
326 foreach ($this->settingsFactories as $callable) {
327 $result = $this->mergeSettings($result, $callable());
328 }
898951c6 329 CRM_Utils_Hook::alterResourceSettings($result);
6a488035
TO
330 return $result;
331 }
332
333 /**
334 * @param array $settings
335 * @param array $additions
a6c01b45
CW
336 * @return array
337 * combination of $settings and $additions
6a488035
TO
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 /**
d09edf64 350 * Helper fn for addSetting.
6a488035
TO
351 * Render JavaScript variables for the global CRM object.
352 *
6a488035
TO
353 * @return string
354 */
355 public function renderSetting() {
270d3515 356 /*// On a standard page request we construct the CRM object from scratch
156fd9b9
CW
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 }
d759bd10 364 return sprintf("<script type=\"text/javascript\">\n%s\n</script>\n", $js);
270d3515
LMM
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);
6a488035
TO
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
8ef12e64 375 *
6a488035 376 * Note: this function rarely needs to be called directly and is mostly for internal use.
d3e86119 377 * See CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
6a488035
TO
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 *
5a4f6742 397 * @param string|array $text
e97c66ff 398 * @param string|null $domain
6a488035
TO
399 * @return CRM_Core_Resources
400 */
3f3bba82 401 public function addString($text, $domain = 'civicrm') {
6a488035 402 foreach ((array) $text as $str) {
be2fb01f
CW
403 $translated = ts($str, [
404 'domain' => ($domain == 'civicrm') ? NULL : [$domain, NULL],
1b4710da 405 'raw' => TRUE,
be2fb01f 406 ]);
3f3bba82 407
6a488035
TO
408 // We only need to push this string to client if the translation
409 // is actually different from the original
410 if ($translated != $str) {
3f3bba82 411 $bucket = $domain == 'civicrm' ? 'strings' : 'strings::' . $domain;
be2fb01f
CW
412 $this->addSetting([
413 $bucket => [$str => $translated],
414 ]);
6a488035
TO
415 }
416 }
417 return $this;
418 }
419
420 /**
421 * Add a CSS file to the current page using <LINK HREF>.
422 *
5a4f6742
CW
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'.
6a488035
TO
431 * @return CRM_Core_Resources
432 */
433 public function addStyleFile($ext, $file, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
d89d2545
TO
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;
6a488035
TO
440 }
441
442 /**
443 * Add a CSS file to the current page using <LINK HREF>.
444 *
5a4f6742
CW
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'.
6a488035
TO
450 * @return CRM_Core_Resources
451 */
452 public function addStyleUrl($url, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
be2fb01f 453 CRM_Core_Region::instance($region)->add([
518fa0ee
SL
454 'name' => $url,
455 'type' => 'styleUrl',
456 'styleUrl' => $url,
457 'weight' => $weight,
458 'region' => $region,
459 ]);
6a488035
TO
460 return $this;
461 }
462
463 /**
464 * Add a CSS content to the current page using <STYLE>.
465 *
5a4f6742
CW
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'.
6a488035
TO
472 * @return CRM_Core_Resources
473 */
474 public function addStyle($code, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
be2fb01f 475 CRM_Core_Region::instance($region)->add([
8d7a9d07 476 // 'name' => automatic
518fa0ee
SL
477 'type' => 'style',
478 'style' => $code,
479 'weight' => $weight,
480 'region' => $region,
481 ]);
6a488035
TO
482 return $this;
483 }
484
485 /**
d09edf64 486 * Determine file path of a resource provided by an extension.
6a488035 487 *
5a4f6742
CW
488 * @param string $ext
489 * extension name; use 'civicrm' for core.
e97c66ff 490 * @param string|null $file
5a4f6742 491 * file path -- relative to the extension base dir.
6a488035 492 *
72b3a70c
CW
493 * @return bool|string
494 * full file path or FALSE if not found
6a488035 495 */
16cd1eca 496 public function getPath($ext, $file = NULL) {
6a488035 497 // TODO consider caching results
b698e2d5
TO
498 $base = $this->paths->hasVariable($ext)
499 ? rtrim($this->paths->getVariable($ext, 'path'), '/')
500 : $this->extMapper->keyToBasePath($ext);
16cd1eca 501 if ($file === NULL) {
b698e2d5 502 return $base;
16cd1eca 503 }
b698e2d5 504 $path = $base . '/' . $file;
6a488035
TO
505 if (is_file($path)) {
506 return $path;
507 }
508 return FALSE;
509 }
510
511 /**
d09edf64 512 * Determine public URL of a resource provided by an extension.
6a488035 513 *
5a4f6742
CW
514 * @param string $ext
515 * extension name; use 'civicrm' for core.
516 * @param string $file
517 * file path -- relative to the extension base dir.
2a6da8d7
EM
518 * @param bool $addCacheCode
519 *
6a488035
TO
520 * @return string, URL
521 */
522 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
523 if ($file === NULL) {
524 $file = '';
525 }
526 if ($addCacheCode) {
6f12c6eb 527 $file = $this->addCacheCode($file);
6a488035
TO
528 }
529 // TODO consider caching results
b698e2d5
TO
530 $base = $this->paths->hasVariable($ext)
531 ? $this->paths->getVariable($ext, 'url')
532 : ($this->extMapper->keyToUrl($ext) . '/');
533 return $base . $file;
6a488035
TO
534 }
535
16cd1eca
TO
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;
be2fb01f 552 $files = [];
16cd1eca 553 foreach ($patterns as $pattern) {
e5c376e7
TO
554 if (preg_match(';^(assetBuilder|ext)://;', $pattern)) {
555 $files[] = $pattern;
556 }
9f87b14b 557 if (CRM_Utils_File::isAbsolute($pattern)) {
16cd1eca
TO
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 }
518fa0ee
SL
566 // Deterministic order.
567 sort($files);
16cd1eca
TO
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
a0ee3941
EM
574 /**
575 * @return string
576 */
6a488035
TO
577 public function getCacheCode() {
578 return $this->cacheCode;
579 }
580
a0ee3941
EM
581 /**
582 * @param $value
5badddc3 583 * @return CRM_Core_Resources
a0ee3941 584 */
6a488035
TO
585 public function setCacheCode($value) {
586 $this->cacheCode = $value;
587 if ($this->cacheCodeKey) {
08ef4ddd 588 Civi::settings()->set($this->cacheCodeKey, $value);
6a488035 589 }
9762f6ff 590 return $this;
6a488035
TO
591 }
592
5badddc3
CW
593 /**
594 * @return CRM_Core_Resources
595 */
6a488035
TO
596 public function resetCacheCode() {
597 $this->setCacheCode(CRM_Utils_String::createRandom(5, CRM_Utils_String::ALPHANUMERIC));
f091327b
CW
598 // Also flush cms resource cache if needed
599 CRM_Core_Config::singleton()->userSystem->clearResourceCache();
9762f6ff 600 return $this;
6a488035
TO
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 *
2a6da8d7 610 * @param string $region
6a488035 611 * @return CRM_Core_Resources
6a488035
TO
612 */
613 public function addCoreResources($region = 'html-header') {
156fd9b9 614 if (!isset($this->addedCoreResources[$region]) && !self::isAjaxMode()) {
6a488035
TO
615 $this->addedCoreResources[$region] = TRUE;
616 $config = CRM_Core_Config::singleton();
617
a43b1583 618 // Add resources from coreResourceList
6a488035 619 $jsWeight = -9999;
dbb12634 620 foreach ($this->coreResourceList($region) as $item) {
7266e09b
CW
621 if (is_array($item)) {
622 $this->addSetting($item);
623 }
adcd4bf7
CW
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 {
74227f77 631 // Don't bother looking for ts() calls in packages, there aren't any
7266e09b
CW
632 $translate = (substr($item, 0, 3) == 'js/');
633 $this->addScriptFile('civicrm', $item, $jsWeight++, $region, $translate);
6a488035 634 }
6a488035 635 }
d759bd10 636 // Add global settings
be2fb01f
CW
637 $settings = [
638 'config' => [
353ffa53 639 'isFrontend' => $config->userFrameworkFrontend,
be2fb01f
CW
640 ],
641 ];
4e56e743
CW
642 // Disable profile creation if user lacks permission
643 if (!CRM_Core_Permission::check('edit all contacts') && !CRM_Core_Permission::check('add contacts')) {
b7ceb253 644 $settings['config']['entityRef']['contactCreate'] = FALSE;
3d527838 645 }
4e56e743 646 $this->addSetting($settings);
3d527838
CW
647
648 // Give control of jQuery and _ back to the CMS - this loads last
c2777586 649 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
6a488035
TO
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)) {
6f12c6eb 672 $customCSSURL = $this->addCacheCode($config->customCSSURL);
673 $this->addStyleUrl($customCSSURL, 99, $region);
6a488035 674 }
aaffa79f 675 if (!Civi::settings()->get('disable_core_css')) {
6a488035 676 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
6a488035 677 }
a2c70872
AH
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);
6a488035
TO
680 }
681 return $this;
682 }
683
627668e8 684 /**
d09edf64 685 * Flushes cached translated strings.
5badddc3 686 * @return CRM_Core_Resources
627668e8
CW
687 */
688 public function flushStrings() {
fd7dc3f3 689 $this->strings->flush();
9762f6ff
CW
690 return $this;
691 }
692
6a488035 693 /**
fd7dc3f3
TO
694 * @return CRM_Core_Resources_Strings
695 */
696 public function getStrings() {
697 return $this->strings;
6a488035
TO
698 }
699
19f7e35e 700 /**
8d7a9d07 701 * Create dynamic script for localizing js widgets.
19f7e35e 702 */
00be9182 703 public static function outputLocalizationJS() {
4cc9b813 704 CRM_Core_Page_AJAX::setJsHeaders();
a88cf11a 705 $config = CRM_Core_Config::singleton();
be2fb01f 706 $vars = [
3d527838
CW
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...')),
e695ee7c 710 'entityRef' => self::getEntityRefMetadata(),
7b83e312 711 'ajaxPopupsEnabled' => self::singleton()->ajaxPopupsEnabled,
a9fb6123 712 'allowAlertAutodismissal' => (bool) Civi::settings()->get('allow_alert_autodismissal'),
c7e39a79 713 'resourceCacheCode' => self::singleton()->getCacheCode(),
b30809e4
CW
714 'locale' => CRM_Core_I18n::getLocale(),
715 'cid' => (int) CRM_Core_Session::getLoggedInContactID(),
be2fb01f 716 ];
3d4fb0ed 717 print CRM_Core_Smarty::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
4cc9b813 718 CRM_Utils_System::civiExit();
c66581f5
CW
719 }
720
6a488035 721 /**
d09edf64 722 * List of core resources we add to every CiviCRM page.
6a488035 723 *
e8038a7b
CW
724 * Note: non-compressed versions of .min files will be used in debug mode
725 *
e3c1e85b 726 * @param string $region
a43b1583 727 * @return array
6a488035 728 */
e3c1e85b 729 public function coreResourceList($region) {
dbe0bbc6 730 $config = CRM_Core_Config::singleton();
a43b1583 731
4968e732
CW
732 // Scripts needed by everyone, everywhere
733 // FIXME: This is too long; list needs finer-grained segmentation
be2fb01f 734 $items = [
3c61fc8f
CW
735 "bower_components/jquery/dist/jquery.min.js",
736 "bower_components/jquery-ui/jquery-ui.min.js",
e8038a7b 737 "bower_components/jquery-ui/themes/smoothness/jquery-ui.min.css",
1891a856 738 "bower_components/lodash-compat/lodash.min.js",
e8038a7b
CW
739 "packages/jquery/plugins/jquery.mousewheel.min.js",
740 "bower_components/select2/select2.min.js",
741 "bower_components/select2/select2.min.css",
90000c30 742 "bower_components/font-awesome/css/font-awesome.min.css",
e8038a7b
CW
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",
a0c8b50e 750 "js/Common.js",
ff2eb9e8 751 "js/crm.datepicker.js",
53f2643c 752 "js/crm.ajax.js",
7060d177 753 "js/wysiwyg/crm.wysiwyg.js",
be2fb01f 754 ];
adcd4bf7
CW
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
7c523661 762 // add wysiwyg editor
aaffa79f 763 $editor = Civi::settings()->get('editor_id');
b608cfb1 764 if ($editor == "CKEditor") {
5e0b4b77 765 CRM_Admin_Page_CKEditorConfig::setConfigDefault();
be2fb01f
CW
766 $items[] = [
767 'config' => [
286a7e5a
CW
768 'wysisygScriptLocation' => Civi::paths()->getUrl("[civicrm.root]/js/wysiwyg/crm.ckeditor.js"),
769 'CKEditorCustomConfig' => CRM_Admin_Page_CKEditorConfig::getConfigUrl(),
be2fb01f
CW
770 ],
771 ];
b608cfb1 772 }
dbe0bbc6 773
4968e732
CW
774 // These scripts are only needed by back-office users
775 if (CRM_Core_Permission::check('access CiviCRM')) {
642d43fa 776 $items[] = "packages/jquery/plugins/jquery.tableHeader.js";
e8038a7b 777 $items[] = "packages/jquery/plugins/jquery.notify.min.js";
4968e732
CW
778 }
779
b30809e4
CW
780 $contactID = CRM_Core_Session::getLoggedInContactID();
781
782 // Menubar
c931044d
CW
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') {
b30809e4
CW
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';
dcaf410f 796 // @see CRM_Core_Resources::renderMenubarStylesheet
08a3a519 797 $items[] = Civi::service('asset_builder')->getUrl('crm-menubar.css', [
dcaf410f 798 'menubarColor' => Civi::settings()->get('menubar_color'),
c4560ed2
CW
799 'height' => 40,
800 'breakpoint' => 768,
08a3a519 801 ]);
dcaf410f 802 // Variables for crm.menubar.js
b30809e4
CW
803 $items[] = [
804 'menubar' => [
c931044d 805 'position' => $position,
b30809e4
CW
806 'qfKey' => CRM_Core_Key::get('CRM_Contact_Controller_Search', TRUE),
807 'cacheCode' => CRM_Core_BAO_Navigation::getCacheKey($contactID),
808 ],
809 ];
810 }
811
d606fff7
CW
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
53f2643c
CW
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 }
9efeb642 821
98466ff9 822 $tsLocale = CRM_Core_I18n::getLocale();
dbe0bbc6 823 // Add localized jQuery UI files
5d26edf0 824 if ($tsLocale && $tsLocale != 'en_US') {
dbe0bbc6 825 // Search for i18n file in order of specificity (try fr-CA, then fr)
5d26edf0 826 list($lang) = explode('_', $tsLocale);
3c61fc8f 827 $path = "bower_components/jquery-ui/ui/i18n";
be2fb01f 828 foreach ([str_replace('_', '-', $tsLocale), $lang] as $language) {
f2f191fe 829 $localizationFile = "$path/datepicker-{$language}.js";
dbe0bbc6
CW
830 if ($this->getPath('civicrm', $localizationFile)) {
831 $items[] = $localizationFile;
832 break;
833 }
834 }
835 }
f9f361d0 836
72e86d7d 837 // Allow hooks to modify this list
e3c1e85b 838 CRM_Utils_Hook::coreResourceList($items, $region);
f9f361d0 839
6a488035
TO
840 return $items;
841 }
156fd9b9
CW
842
843 /**
a6c01b45
CW
844 * @return bool
845 * is this page request an ajax snippet?
156fd9b9 846 */
00be9182 847 public static function isAjaxMode() {
be2fb01f 848 if (in_array(CRM_Utils_Array::value('snippet', $_REQUEST), [
518fa0ee
SL
849 CRM_Core_Smarty::PRINT_SNIPPET,
850 CRM_Core_Smarty::PRINT_NOFORM,
851 CRM_Core_Smarty::PRINT_JSON,
852 ])
42a40a1c 853 ) {
854 return TRUE;
855 }
60c3b6e9
CW
856 list($arg0, $arg1) = array_pad(explode('/', CRM_Utils_System::getUrlPath()), 2, '');
857 return ($arg0 === 'civicrm' && in_array($arg1, ['ajax', 'angularprofiles', 'asset']));
156fd9b9 858 }
b7ceb253 859
1889d803 860 /**
518fa0ee 861 * @param \Civi\Core\Event\GenericHookEvent $e
1889d803
CW
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';
dcaf410f 869 $content = '';
1889d803
CW
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) {
dcaf410f 879 $content .= file_get_contents(self::singleton()->getPath('civicrm', $item));
8a52ae34 880 }
dcaf410f
CW
881 $params = $e->params;
882 // "color" is deprecated in favor of the more specific "menubarColor"
883 $menubarColor = $params['color'] ?? $params['menubarColor'];
1889d803 884 $vars = [
dcaf410f
CW
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'),
1889d803 893 ];
dcaf410f
CW
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);
1889d803
CW
896 }
897
b7ceb253 898 /**
f9e31d7f 899 * Provide a list of available entityRef filters.
fd7c068f 900 *
b7ceb253
CW
901 * @return array
902 */
e695ee7c
CW
903 public static function getEntityRefMetadata() {
904 $data = [
905 'filters' => [],
906 'links' => [],
907 ];
06606cd1 908 $config = CRM_Core_Config::singleton();
b7ceb253 909
1d6f94ab
CW
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;
06606cd1
CW
915 }
916 }
917
1d6f94ab
CW
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)) {
e695ee7c
CW
927 $filters = $baoName::getEntityRefFilters();
928 if ($filters) {
2229cf4f 929 $data['filters'][$entity] = $filters;
e695ee7c
CW
930 }
931 if (is_callable([$baoName, 'getEntityRefCreateLinks'])) {
932 $createLinks = $baoName::getEntityRefCreateLinks();
933 if ($createLinks) {
2229cf4f 934 $data['links'][$entity] = $createLinks;
e695ee7c 935 }
1d6f94ab
CW
936 }
937 }
b7b528bc
CW
938 }
939
e695ee7c 940 CRM_Utils_Hook::entityRefFilters($data['filters']);
fd7c068f 941
e695ee7c 942 return $data;
b7ceb253 943 }
96025800 944
09a4dcd5 945 /**
d89d2545 946 * Determine the minified file name.
09a4dcd5 947 *
d89d2545
TO
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;
09a4dcd5
CW
959 }
960 }
d89d2545 961 return $file;
09a4dcd5
CW
962 }
963
6f12c6eb 964 /**
965 * @param string $url
966 * @return string
967 */
968 public function addCacheCode($url) {
33603e1d 969 $hasQuery = strpos($url, '?') !== FALSE;
03449a5b 970 $operator = $hasQuery ? '&' : '?';
6f12c6eb 971
03449a5b 972 return $url . $operator . 'r=' . $this->cacheCode;
6f12c6eb 973 }
33603e1d 974
adcd4bf7
CW
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
6a488035 986}