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