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