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