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