3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * This class facilitates the loading of resources
30 * such as JavaScript files and CSS files.
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).
36 * TODO: This is currently a thin wrapper over CRM_Core_Region. We
37 * should incorporte services for aggregation, minimization, etc.
40 * @copyright CiviCRM LLC (c) 2004-2015
44 class CRM_Core_Resources
{
45 const DEFAULT_WEIGHT
= 0;
46 const DEFAULT_REGION
= 'page-footer';
49 * We don't have a container or dependency-injection, so use singleton instead
53 private static $_singleton = NULL;
56 * @var CRM_Extension_Mapper
58 private $extMapper = NULL;
61 * @var CRM_Core_Resources_Strings
63 private $strings = NULL;
66 * @var array free-form data tree
68 protected $settings = array();
69 protected $addedSettings = FALSE;
72 * @var array of callables
74 protected $settingsFactories = array();
77 * @var array ($regionName => bool)
79 protected $addedCoreResources = array();
82 * @var array ($regionName => bool)
84 protected $addedCoreStyles = array();
87 * @var string a value to append to JS/CSS URLs to coerce cache resets
89 protected $cacheCode = NULL;
92 * @var string the name of a setting which persistently stores the cacheCode
94 protected $cacheCodeKey = NULL;
99 public $ajaxPopupsEnabled;
102 * Get or set the single instance of CRM_Core_Resources.
104 * @param CRM_Core_Resources $instance
105 * New copy of the manager.
106 * @return CRM_Core_Resources
108 static public function singleton(CRM_Core_Resources
$instance = NULL) {
109 if ($instance !== NULL) {
110 self
::$_singleton = $instance;
112 if (self
::$_singleton === NULL) {
113 $sys = CRM_Extension_System
::singleton();
114 $cache = new CRM_Utils_Cache_SqlGroup(array(
115 'group' => 'js-strings',
118 self
::$_singleton = new CRM_Core_Resources(
121 CRM_Core_Config
::isUpgradeMode() ?
NULL : 'resCacheCode'
124 return self
::$_singleton;
128 * Construct a resource manager.
130 * @param CRM_Extension_Mapper $extMapper
131 * Map extension names to their base path or URLs.
132 * @param CRM_Utils_Cache_Interface $cache
133 * JS-localization cache.
134 * @param string|null $cacheCodeKey Random code to append to resource URLs; changing the code forces clients to reload resources
136 public function __construct($extMapper, $cache, $cacheCodeKey = NULL) {
137 $this->extMapper
= $extMapper;
138 $this->strings
= new CRM_Core_Resources_Strings($cache);
139 $this->cacheCodeKey
= $cacheCodeKey;
140 if ($cacheCodeKey !== NULL) {
141 $this->cacheCode
= CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, $cacheCodeKey);
143 if (!$this->cacheCode
) {
144 $this->resetCacheCode();
146 $this->ajaxPopupsEnabled
= (bool) CRM_Core_BAO_Setting
::getItem(
147 CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'ajaxPopupsEnabled', NULL, TRUE
152 * Export permission data to the client to enable smarter GUIs.
154 * Note: Application security stems from the server's enforcement
155 * of the security logic (e.g. in the API permissions). There's no way
156 * the client can use this info to make the app more secure; however,
157 * it can produce a better-tuned (non-broken) UI.
159 * @param array $permNames
160 * List of permission names to check/export.
161 * @return CRM_Core_Resources
163 public function addPermissions($permNames) {
164 $permNames = (array) $permNames;
166 foreach ($permNames as $permName) {
167 $perms[$permName] = CRM_Core_Permission
::check($permName);
169 return $this->addSetting(array(
170 'permissions' => $perms,
175 * Add a JavaScript file to the current page using <SCRIPT SRC>.
178 * extension name; use 'civicrm' for core.
179 * @param string $file
180 * file path -- relative to the extension base dir.
182 * relative weight within a given region.
183 * @param string $region
184 * location within the file; 'html-header', 'page-header', 'page-footer'.
185 * @param bool|string $translate
186 * Whether to load translated strings for this file. Use one of:
187 * - FALSE: Do not load translated strings.
188 * - TRUE: Load translated strings. Use the $ext's default domain.
189 * - string: Load translated strings. Use a specific domain.
191 * @return CRM_Core_Resources
193 public function addScriptFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
, $translate = TRUE) {
195 $domain = ($translate === TRUE) ?
$ext : $translate;
196 $this->addString($this->strings
->get($domain, $this->getPath($ext, $file), 'text/javascript'), $domain);
198 // Look for non-minified version if we are in debug mode
199 if (CRM_Core_Config
::singleton()->debug
&& strpos($file, '.min.js') !== FALSE) {
200 $nonMiniFile = str_replace('.min.js', '.js', $file);
201 if ($this->getPath($ext, $nonMiniFile)) {
202 $file = $nonMiniFile;
205 return $this->addScriptUrl($this->getUrl($ext, $file, TRUE), $weight, $region);
209 * Add a JavaScript file to the current page using <SCRIPT SRC>.
213 * relative weight within a given region.
214 * @param string $region
215 * location within the file; 'html-header', 'page-header', 'page-footer'.
216 * @return CRM_Core_Resources
218 public function addScriptUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
219 CRM_Core_Region
::instance($region)->add(array(
221 'type' => 'scriptUrl',
230 * Add a JavaScript file to the current page using <SCRIPT SRC>.
232 * @param string $code
233 * JavaScript source code.
235 * relative weight within a given region.
236 * @param string $region
237 * location within the file; 'html-header', 'page-header', 'page-footer'.
238 * @return CRM_Core_Resources
240 public function addScript($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
241 CRM_Core_Region
::instance($region)->add(array(
242 // 'name' => automatic
252 * Add JavaScript variables to CRM.vars
256 * CRM_Core_Resources::singleton()->addVars('myNamespace', array('foo' => 'bar'));
257 * Access var from javascript:
258 * CRM.vars.myNamespace.foo // "bar"
260 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Javascript+Reference
262 * @param string $nameSpace
263 * Usually the name of your extension.
265 * @return CRM_Core_Resources
267 public function addVars($nameSpace, $vars) {
268 $existing = CRM_Utils_Array
::value($nameSpace, CRM_Utils_Array
::value('vars', $this->settings
), array());
269 $vars = $this->mergeSettings($existing, $vars);
270 $this->addSetting(array('vars' => array($nameSpace => $vars)));
275 * Add JavaScript variables to the root of the CRM object.
276 * This function is usually reserved for low-level system use.
277 * Extensions and components should generally use addVars instead.
279 * @param array $settings
280 * @return CRM_Core_Resources
282 public function addSetting($settings) {
283 $this->settings
= $this->mergeSettings($this->settings
, $settings);
284 if (!$this->addedSettings
) {
285 $region = self
::isAjaxMode() ?
'ajax-snippet' : 'html-header';
287 CRM_Core_Region
::instance($region)->add(array(
288 'callback' => function (&$snippet, &$html) use ($resources) {
289 $html .= "\n" . $resources->renderSetting();
293 $this->addedSettings
= TRUE;
299 * Add JavaScript variables to the global CRM object via a callback function.
301 * @param callable $callable
302 * @return CRM_Core_Resources
304 public function addSettingsFactory($callable) {
305 // Make sure our callback has been registered
306 $this->addSetting(array());
307 $this->settingsFactories
[] = $callable;
312 * Helper fn for addSettingsFactory.
314 public function getSettings() {
315 $result = $this->settings
;
316 foreach ($this->settingsFactories
as $callable) {
317 $result = $this->mergeSettings($result, $callable());
323 * @param array $settings
324 * @param array $additions
326 * combination of $settings and $additions
328 protected function mergeSettings($settings, $additions) {
329 foreach ($additions as $k => $v) {
330 if (isset($settings[$k]) && is_array($settings[$k]) && is_array($v)) {
339 * Helper fn for addSetting.
340 * Render JavaScript variables for the global CRM object.
344 public function renderSetting() {
345 // On a standard page request we construct the CRM object from scratch
346 if (!self
::isAjaxMode()) {
347 $js = 'var CRM = ' . json_encode($this->getSettings()) . ';';
349 // For an ajax request we append to it
351 $js = 'CRM.$.extend(true, CRM, ' . json_encode($this->getSettings()) . ');';
353 return sprintf("<script type=\"text/javascript\">\n%s\n</script>\n", $js);
357 * Add translated string to the js CRM object.
358 * It can then be retrived from the client-side ts() function
359 * Variable substitutions can happen from client-side
361 * Note: this function rarely needs to be called directly and is mostly for internal use.
362 * See CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
366 * CRM_Core_Resources::singleton()->addString('Hello');
367 * // The string is now available to javascript code i.e.
370 * Example with client-side substitutions:
372 * CRM_Core_Resources::singleton()->addString('Your %1 has been %2');
373 * // ts() in javascript works the same as in php, for example:
374 * ts('Your %1 has been %2', {1: objectName, 2: actionTaken});
376 * NOTE: This function does not work with server-side substitutions
377 * (as this might result in collisions and unwanted variable injections)
378 * Instead, use code like:
379 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs)))));
380 * And from javascript access it at CRM.myNamespace.myString
382 * @param string|array $text
383 * @param string|NULL $domain
384 * @return CRM_Core_Resources
386 public function addString($text, $domain = 'civicrm') {
387 foreach ((array) $text as $str) {
388 $translated = ts($str, array(
389 'domain' => ($domain == 'civicrm') ?
NULL : array($domain, NULL),
393 // We only need to push this string to client if the translation
394 // is actually different from the original
395 if ($translated != $str) {
396 $bucket = $domain == 'civicrm' ?
'strings' : 'strings::' . $domain;
397 $this->addSetting(array(
398 $bucket => array($str => $translated),
406 * Add a CSS file to the current page using <LINK HREF>.
409 * extension name; use 'civicrm' for core.
410 * @param string $file
411 * file path -- relative to the extension base dir.
413 * relative weight within a given region.
414 * @param string $region
415 * location within the file; 'html-header', 'page-header', 'page-footer'.
416 * @return CRM_Core_Resources
418 public function addStyleFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
419 return $this->addStyleUrl($this->getUrl($ext, $file, TRUE), $weight, $region);
423 * Add a CSS file to the current page using <LINK HREF>.
427 * relative weight within a given region.
428 * @param string $region
429 * location within the file; 'html-header', 'page-header', 'page-footer'.
430 * @return CRM_Core_Resources
432 public function addStyleUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
433 CRM_Core_Region
::instance($region)->add(array(
435 'type' => 'styleUrl',
444 * Add a CSS content to the current page using <STYLE>.
446 * @param string $code
449 * relative weight within a given region.
450 * @param string $region
451 * location within the file; 'html-header', 'page-header', 'page-footer'.
452 * @return CRM_Core_Resources
454 public function addStyle($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
455 CRM_Core_Region
::instance($region)->add(array(
456 // 'name' => automatic
466 * Determine file path of a resource provided by an extension.
469 * extension name; use 'civicrm' for core.
470 * @param string|NULL $file
471 * file path -- relative to the extension base dir.
473 * @return bool|string
474 * full file path or FALSE if not found
476 public function getPath($ext, $file = NULL) {
477 // TODO consider caching results
478 if ($file === NULL) {
479 return $this->extMapper
->keyToBasePath($ext);
481 $path = $this->extMapper
->keyToBasePath($ext) . '/' . $file;
482 if (is_file($path)) {
489 * Determine public URL of a resource provided by an extension.
492 * extension name; use 'civicrm' for core.
493 * @param string $file
494 * file path -- relative to the extension base dir.
495 * @param bool $addCacheCode
497 * @return string, URL
499 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
500 if ($file === NULL) {
504 $file .= '?r=' . $this->getCacheCode();
506 // TODO consider caching results
507 return $this->extMapper
->keyToUrl($ext) . '/' . $file;
511 * Evaluate a glob pattern in the context of a particular extension.
514 * Extension name; use 'civicrm' for core.
515 * @param string|array $patterns
516 * Glob pattern; e.g. "*.html".
517 * @param null|int $flags
520 * List of matching files, relative to the extension base dir.
523 public function glob($ext, $patterns, $flags = NULL) {
524 $path = $this->getPath($ext);
525 $patterns = (array) $patterns;
527 foreach ($patterns as $pattern) {
528 if ($pattern{0} === '/') {
530 $files = array_merge($files, (array) glob($pattern, $flags));
534 $files = array_merge($files, (array) glob("$path/$pattern", $flags));
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/");
547 public function getCacheCode() {
548 return $this->cacheCode
;
553 * @return CRM_Core_Resources
555 public function setCacheCode($value) {
556 $this->cacheCode
= $value;
557 if ($this->cacheCodeKey
) {
558 CRM_Core_BAO_Setting
::setItem($value, CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, $this->cacheCodeKey
);
564 * @return CRM_Core_Resources
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();
574 * This adds CiviCRM's standard css and js to the specified region of the document.
575 * It will only run once.
577 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
578 * (like addCoreResources/addCoreStyles).
580 * @param string $region
581 * @return CRM_Core_Resources
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();
588 // Add resources from coreResourceList
590 foreach ($this->coreResourceList() as $file) {
591 if (substr($file, -2) == 'js') {
592 // Don't bother looking for ts() calls in packages, there aren't any
593 $translate = (substr($file, 0, 3) == 'js/');
594 $this->addScriptFile('civicrm', $file, $jsWeight++
, $region, $translate);
597 $this->addStyleFile('civicrm', $file, -100, $region);
601 // Dynamic localization script
602 $this->addScriptUrl(CRM_Utils_System
::url('civicrm/ajax/l10n-js/' . $config->lcMessages
, array('r' => $this->getCacheCode())), $jsWeight++
, $region);
604 // Add global settings
607 'isFrontend' => $config->userFrameworkFrontend
,
610 // Disable profile creation if user lacks permission
611 if (!CRM_Core_Permission
::check('edit all contacts') && !CRM_Core_Permission
::check('add contacts')) {
612 $settings['config']['entityRef']['contactCreate'] = FALSE;
614 $this->addSetting($settings);
616 // Give control of jQuery and _ back to the CMS - this loads last
617 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
619 $this->addCoreStyles($region);
625 * This will add CiviCRM's standard CSS
627 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
628 * (like addCoreResources/addCoreStyles).
630 * @param string $region
631 * @return CRM_Core_Resources
633 public function addCoreStyles($region = 'html-header') {
634 if (!isset($this->addedCoreStyles
[$region])) {
635 $this->addedCoreStyles
[$region] = TRUE;
637 // Load custom or core css
638 $config = CRM_Core_Config
::singleton();
639 if (!empty($config->customCSSURL
)) {
640 $this->addStyleUrl($config->customCSSURL
, 99, $region);
642 if (!CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'disable_core_css')) {
643 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
650 * Flushes cached translated strings.
651 * @return CRM_Core_Resources
653 public function flushStrings() {
654 $this->strings
->flush();
659 * @return CRM_Core_Resources_Strings
661 public function getStrings() {
662 return $this->strings
;
666 * Create dynamic script for localizing js widgets.
668 public static function outputLocalizationJS() {
669 CRM_Core_Page_AJAX
::setJsHeaders();
670 $config = CRM_Core_Config
::singleton();
672 'moneyFormat' => json_encode(CRM_Utils_Money
::format(1234.56)),
673 'contactSearch' => json_encode($config->includeEmailInName ?
ts('Start typing a name or email...') : ts('Start typing a name...')),
674 'otherSearch' => json_encode(ts('Enter search term...')),
675 'entityRef' => array(
676 'contactCreate' => CRM_Core_BAO_UFGroup
::getCreateLinks(),
677 'filters' => self
::getEntityRefFilters(),
679 'ajaxPopupsEnabled' => self
::singleton()->ajaxPopupsEnabled
,
681 print CRM_Core_Smarty
::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
682 CRM_Utils_System
::civiExit();
686 * List of core resources we add to every CiviCRM page.
690 public function coreResourceList() {
691 $config = CRM_Core_Config
::singleton();
692 // Use minified files for production, uncompressed in debug mode
693 // Note, $this->addScriptFile would automatically search for the non-minified file in debug mode but this is probably faster
694 $min = $config->debug ?
'' : '.min';
696 // Scripts needed by everyone, everywhere
697 // FIXME: This is too long; list needs finer-grained segmentation
699 "bower_components/jquery/dist/jquery.min.js",
700 "bower_components/jquery-ui/jquery-ui.min.js",
701 "bower_components/jquery-ui/themes/smoothness/jquery-ui$min.css",
702 "bower_components/lodash-compat/lodash.min.js",
703 "packages/jquery/plugins/jquery.mousewheel$min.js",
704 "bower_components/select2/select2$min.js",
705 "bower_components/select2/select2$min.css",
706 "packages/jquery/plugins/jquery.tableHeader.js",
707 "packages/jquery/plugins/jquery.textarearesizer.js",
708 "packages/jquery/plugins/jquery.form$min.js",
709 "packages/jquery/plugins/jquery.timeentry$min.js",
710 "packages/jquery/plugins/jquery.blockUI$min.js",
711 "packages/jquery/plugins/DataTables/media/js/jquery.dataTables$min.js",
712 "packages/jquery/plugins/DataTables/media/css/jquery.dataTables$min.css",
713 "bower_components/jquery-validation/dist/jquery.validate$min.js",
714 "packages/jquery/plugins/jquery.ui.datepicker.validation.pack.js",
719 // These scripts are only needed by back-office users
720 if (CRM_Core_Permission
::check('access CiviCRM')) {
721 $items[] = "packages/jquery/plugins/jquery.menu$min.js";
722 $items[] = "css/navigation.css";
723 $items[] = "packages/jquery/plugins/jquery.jeditable$min.js";
724 $items[] = "packages/jquery/plugins/jquery.notify$min.js";
725 $items[] = "js/jquery/jquery.crmeditable.js";
728 // JS for multilingual installations
729 if (!empty($config->languageLimit
) && count($config->languageLimit
) > 1 && CRM_Core_Permission
::check('translate CiviCRM')) {
730 $items[] = "js/crm.multilingual.js";
733 // Enable administrators to edit option lists in a dialog
734 if (CRM_Core_Permission
::check('administer CiviCRM') && $this->ajaxPopupsEnabled
) {
735 $items[] = "js/crm.optionEdit.js";
738 // Add localized jQuery UI files
739 if ($config->lcMessages
&& $config->lcMessages
!= 'en_US') {
740 // Search for i18n file in order of specificity (try fr-CA, then fr)
741 list($lang) = explode('_', $config->lcMessages
);
742 $path = "bower_components/jquery-ui/ui/i18n";
743 foreach (array(str_replace('_', '-', $config->lcMessages
), $lang) as $language) {
744 $localizationFile = "$path/datepicker-{$language}.js";
745 if ($this->getPath('civicrm', $localizationFile)) {
746 $items[] = $localizationFile;
752 // CMS-specific resources
753 $config->userSystem
->appendCoreResources($items);
760 * is this page request an ajax snippet?
762 public static function isAjaxMode() {
763 return in_array(CRM_Utils_Array
::value('snippet', $_REQUEST), array(
764 CRM_Core_Smarty
::PRINT_SNIPPET
,
765 CRM_Core_Smarty
::PRINT_NOFORM
,
766 CRM_Core_Smarty
::PRINT_JSON
,
771 * Provide a list of available entityRef filters.
772 * FIXME: This function doesn't really belong in this class
773 * @TODO: Provide a sane way to extend this list for other entities - a hook or??
776 public static function getEntityRefFilters() {
779 $filters['event'] = array(
780 array('key' => 'event_type_id', 'value' => ts('Event Type')),
782 'key' => 'start_date',
783 'value' => ts('Start Date'),
785 array('key' => '{">":"now"}', 'value' => ts('Upcoming')),
786 array('key' => '{"BETWEEN":["now - 3 month","now"]}', 'value' => ts('Past 3 Months')),
787 array('key' => '{"BETWEEN":["now - 6 month","now"]}', 'value' => ts('Past 6 Months')),
788 array('key' => '{"BETWEEN":["now - 1 year","now"]}', 'value' => ts('Past Year')),
793 $filters['activity'] = array(
794 array('key' => 'activity_type_id', 'value' => ts('Activity Type')),
795 array('key' => 'status_id', 'value' => ts('Activity Status')),
798 $filters['contact'] = array(
799 array('key' => 'contact_type', 'value' => ts('Contact Type')),
800 array('key' => 'group', 'value' => ts('Group'), 'entity' => 'group_contact'),
801 array('key' => 'tag', 'value' => ts('Tag'), 'entity' => 'entity_tag'),
802 array('key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'address'),
803 array('key' => 'country', 'value' => ts('Country'), 'entity' => 'address'),
804 array('key' => 'gender_id', 'value' => ts('Gender')),
805 array('key' => 'is_deceased', 'value' => ts('Deceased')),