Merge pull request #12557 from eileenmcnaughton/activity
[civicrm-core.git] / CRM / Core / Resources.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 (substr($item, -2) == 'js') {
595 // Don't bother looking for ts() calls in packages, there aren't any
596 $translate = (substr($item, 0, 3) == 'js/');
597 $this->addScriptFile('civicrm', $item, $jsWeight++, $region, $translate);
598 }
599 else {
600 $this->addStyleFile('civicrm', $item, -100, $region);
601 }
602 }
603
604 $tsLocale = CRM_Core_I18n::getLocale();
605 // Dynamic localization script
606 $this->addScriptUrl(CRM_Utils_System::url('civicrm/ajax/l10n-js/' . $tsLocale, array('r' => $this->getCacheCode())), $jsWeight++, $region);
607
608 // Add global settings
609 $settings = array(
610 'config' => array(
611 'isFrontend' => $config->userFrameworkFrontend,
612 ),
613 );
614 // Disable profile creation if user lacks permission
615 if (!CRM_Core_Permission::check('edit all contacts') && !CRM_Core_Permission::check('add contacts')) {
616 $settings['config']['entityRef']['contactCreate'] = FALSE;
617 }
618 $this->addSetting($settings);
619
620 // Give control of jQuery and _ back to the CMS - this loads last
621 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
622
623 $this->addCoreStyles($region);
624 }
625 return $this;
626 }
627
628 /**
629 * This will add CiviCRM's standard CSS
630 *
631 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
632 * (like addCoreResources/addCoreStyles).
633 *
634 * @param string $region
635 * @return CRM_Core_Resources
636 */
637 public function addCoreStyles($region = 'html-header') {
638 if (!isset($this->addedCoreStyles[$region])) {
639 $this->addedCoreStyles[$region] = TRUE;
640
641 // Load custom or core css
642 $config = CRM_Core_Config::singleton();
643 if (!empty($config->customCSSURL)) {
644 $customCSSURL = $this->addCacheCode($config->customCSSURL);
645 $this->addStyleUrl($customCSSURL, 99, $region);
646 }
647 if (!Civi::settings()->get('disable_core_css')) {
648 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
649 }
650 // crm-i.css added ahead of other styles so it can be overridden by FA.
651 $this->addStyleFile('civicrm', 'css/crm-i.css', -101, $region);
652 }
653 return $this;
654 }
655
656 /**
657 * Flushes cached translated strings.
658 * @return CRM_Core_Resources
659 */
660 public function flushStrings() {
661 $this->strings->flush();
662 return $this;
663 }
664
665 /**
666 * @return CRM_Core_Resources_Strings
667 */
668 public function getStrings() {
669 return $this->strings;
670 }
671
672 /**
673 * Create dynamic script for localizing js widgets.
674 */
675 public static function outputLocalizationJS() {
676 CRM_Core_Page_AJAX::setJsHeaders();
677 $config = CRM_Core_Config::singleton();
678 $vars = array(
679 'moneyFormat' => json_encode(CRM_Utils_Money::format(1234.56)),
680 'contactSearch' => json_encode($config->includeEmailInName ? ts('Start typing a name or email...') : ts('Start typing a name...')),
681 'otherSearch' => json_encode(ts('Enter search term...')),
682 'entityRef' => array(
683 'contactCreate' => CRM_Core_BAO_UFGroup::getCreateLinks(),
684 'filters' => self::getEntityRefFilters(),
685 ),
686 'ajaxPopupsEnabled' => self::singleton()->ajaxPopupsEnabled,
687 'allowAlertAutodismissal' => (bool) Civi::settings()->get('allow_alert_autodismissal'),
688 );
689 print CRM_Core_Smarty::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
690 CRM_Utils_System::civiExit();
691 }
692
693 /**
694 * List of core resources we add to every CiviCRM page.
695 *
696 * Note: non-compressed versions of .min files will be used in debug mode
697 *
698 * @param string $region
699 * @return array
700 */
701 public function coreResourceList($region) {
702 $config = CRM_Core_Config::singleton();
703
704 // Scripts needed by everyone, everywhere
705 // FIXME: This is too long; list needs finer-grained segmentation
706 $items = array(
707 "bower_components/jquery/dist/jquery.min.js",
708 "bower_components/jquery-ui/jquery-ui.min.js",
709 "bower_components/jquery-ui/themes/smoothness/jquery-ui.min.css",
710 "bower_components/lodash-compat/lodash.min.js",
711 "packages/jquery/plugins/jquery.mousewheel.min.js",
712 "bower_components/select2/select2.min.js",
713 "bower_components/select2/select2.min.css",
714 "bower_components/font-awesome/css/font-awesome.min.css",
715 "packages/jquery/plugins/jquery.form.min.js",
716 "packages/jquery/plugins/jquery.timeentry.min.js",
717 "packages/jquery/plugins/jquery.blockUI.min.js",
718 "bower_components/datatables/media/js/jquery.dataTables.min.js",
719 "bower_components/datatables/media/css/jquery.dataTables.min.css",
720 "bower_components/jquery-validation/dist/jquery.validate.min.js",
721 "packages/jquery/plugins/jquery.ui.datepicker.validation.min.js",
722 "js/Common.js",
723 "js/crm.datepicker.js",
724 "js/crm.ajax.js",
725 "js/wysiwyg/crm.wysiwyg.js",
726 );
727 // add wysiwyg editor
728 $editor = Civi::settings()->get('editor_id');
729 if ($editor == "CKEditor") {
730 CRM_Admin_Page_CKEditorConfig::setConfigDefault();
731 $items[] = array(
732 'config' => array(
733 'wysisygScriptLocation' => Civi::paths()->getUrl("[civicrm.root]/js/wysiwyg/crm.ckeditor.js"),
734 'CKEditorCustomConfig' => CRM_Admin_Page_CKEditorConfig::getConfigUrl(),
735 ),
736 );
737 }
738
739 // These scripts are only needed by back-office users
740 if (CRM_Core_Permission::check('access CiviCRM')) {
741 $items[] = "packages/jquery/plugins/jquery.tableHeader.js";
742 $items[] = "packages/jquery/plugins/jquery.menu.min.js";
743 $items[] = "css/civicrmNavigation.css";
744 $items[] = "packages/jquery/plugins/jquery.notify.min.js";
745 }
746
747 // JS for multilingual installations
748 if (!empty($config->languageLimit) && count($config->languageLimit) > 1 && CRM_Core_Permission::check('translate CiviCRM')) {
749 $items[] = "js/crm.multilingual.js";
750 }
751
752 // Enable administrators to edit option lists in a dialog
753 if (CRM_Core_Permission::check('administer CiviCRM') && $this->ajaxPopupsEnabled) {
754 $items[] = "js/crm.optionEdit.js";
755 }
756
757 $tsLocale = CRM_Core_I18n::getLocale();
758 // Add localized jQuery UI files
759 if ($tsLocale && $tsLocale != 'en_US') {
760 // Search for i18n file in order of specificity (try fr-CA, then fr)
761 list($lang) = explode('_', $tsLocale);
762 $path = "bower_components/jquery-ui/ui/i18n";
763 foreach (array(str_replace('_', '-', $tsLocale), $lang) as $language) {
764 $localizationFile = "$path/datepicker-{$language}.js";
765 if ($this->getPath('civicrm', $localizationFile)) {
766 $items[] = $localizationFile;
767 break;
768 }
769 }
770 }
771
772 // Allow hooks to modify this list
773 CRM_Utils_Hook::coreResourceList($items, $region);
774
775 return $items;
776 }
777
778 /**
779 * @return bool
780 * is this page request an ajax snippet?
781 */
782 public static function isAjaxMode() {
783 if (in_array(CRM_Utils_Array::value('snippet', $_REQUEST), array(
784 CRM_Core_Smarty::PRINT_SNIPPET,
785 CRM_Core_Smarty::PRINT_NOFORM,
786 CRM_Core_Smarty::PRINT_JSON,
787 ))
788 ) {
789 return TRUE;
790 }
791 $url = CRM_Utils_System::getUrlPath();
792 return (strpos($url, 'civicrm/ajax') === 0) || (strpos($url, 'civicrm/angular') === 0);
793 }
794
795 /**
796 * Provide a list of available entityRef filters.
797 * @todo: move component filters into their respective components (e.g. CiviEvent)
798 *
799 * @return array
800 */
801 public static function getEntityRefFilters() {
802 $filters = array();
803 $config = CRM_Core_Config::singleton();
804
805 if (in_array('CiviEvent', $config->enableComponents)) {
806 $filters['event'] = array(
807 array('key' => 'event_type_id', 'value' => ts('Event Type')),
808 array(
809 'key' => 'start_date',
810 'value' => ts('Start Date'),
811 'options' => array(
812 array('key' => '{">":"now"}', 'value' => ts('Upcoming')),
813 array(
814 'key' => '{"BETWEEN":["now - 3 month","now"]}',
815 'value' => ts('Past 3 Months'),
816 ),
817 array(
818 'key' => '{"BETWEEN":["now - 6 month","now"]}',
819 'value' => ts('Past 6 Months'),
820 ),
821 array(
822 'key' => '{"BETWEEN":["now - 1 year","now"]}',
823 'value' => ts('Past Year'),
824 ),
825 ),
826 ),
827 );
828 }
829
830 $filters['activity'] = array(
831 array('key' => 'activity_type_id', 'value' => ts('Activity Type')),
832 array('key' => 'status_id', 'value' => ts('Activity Status')),
833 );
834
835 $filters['contact'] = array(
836 array('key' => 'contact_type', 'value' => ts('Contact Type')),
837 array('key' => 'group', 'value' => ts('Group'), 'entity' => 'group_contact'),
838 array('key' => 'tag', 'value' => ts('Tag'), 'entity' => 'entity_tag'),
839 array('key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'address'),
840 array('key' => 'country', 'value' => ts('Country'), 'entity' => 'address'),
841 array('key' => 'gender_id', 'value' => ts('Gender')),
842 array('key' => 'is_deceased', 'value' => ts('Deceased')),
843 array('key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'),
844 array('key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'),
845 array('key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'),
846 );
847
848 if (in_array('CiviCase', $config->enableComponents)) {
849 $filters['case'] = array(
850 array(
851 'key' => 'case_id.case_type_id',
852 'value' => ts('Case Type'),
853 'entity' => 'Case',
854 ),
855 array(
856 'key' => 'case_id.status_id',
857 'value' => ts('Case Status'),
858 'entity' => 'Case',
859 ),
860 );
861 foreach ($filters['contact'] as $filter) {
862 $filter += array('entity' => 'contact');
863 $filter['key'] = 'contact_id.' . $filter['key'];
864 $filters['case'][] = $filter;
865 }
866 }
867
868 CRM_Utils_Hook::entityRefFilters($filters);
869
870 return $filters;
871 }
872
873 /**
874 * In debug mode, look for a non-minified version of this file
875 *
876 * @param string $fileName
877 * @param string $extName
878 */
879 private function resolveFileName(&$fileName, $extName) {
880 if (CRM_Core_Config::singleton()->debug && strpos($fileName, '.min.') !== FALSE) {
881 $nonMiniFile = str_replace('.min.', '.', $fileName);
882 if ($this->getPath($extName, $nonMiniFile)) {
883 $fileName = $nonMiniFile;
884 }
885 }
886 }
887
888 /**
889 * @param string $url
890 * @return string
891 */
892 public function addCacheCode($url) {
893 $hasQuery = strpos($url, '?') !== FALSE;
894 $operator = $hasQuery ? '&' : '?';
895
896 return $url . $operator . 'r=' . $this->cacheCode;
897 }
898
899 }