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