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