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