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