b431eb30b5ec9a65ddd3bfcdbbd724e438ea18fc
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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
54 private static $_singleton = NULL;
57 * @var CRM_Extension_Mapper
59 private $extMapper = NULL;
62 * @var CRM_Utils_Cache_Interface
64 private $cache = NULL;
67 * @var array free-form data tree
69 protected $settings = array();
70 protected $addedSettings = FALSE;
73 * @var array of callables
75 protected $settingsFactories = array();
78 * @var array ($regionName => bool)
80 protected $addedCoreResources = array();
83 * @var array ($regionName => bool)
85 protected $addedCoreStyles = array();
88 * @var string a value to append to JS/CSS URLs to coerce cache resets
90 protected $cacheCode = NULL;
93 * @var string the name of a setting which persistently stores the cacheCode
95 protected $cacheCodeKey = NULL;
100 public $ajaxPopupsEnabled;
103 * Get or set the single instance of CRM_Core_Resources
106 * CRM_Core_Resources, new copy of the manager.
107 * @return CRM_Core_Resources
109 static public function singleton(CRM_Core_Resources
$instance = NULL) {
110 if ($instance !== NULL) {
111 self
::$_singleton = $instance;
113 if (self
::$_singleton === NULL) {
114 $sys = CRM_Extension_System
::singleton();
115 $cache = new CRM_Utils_Cache_SqlGroup(array(
116 'group' => 'js-strings',
119 self
::$_singleton = new CRM_Core_Resources(
122 CRM_Core_Config
::isUpgradeMode() ?
NULL : 'resCacheCode'
125 return self
::$_singleton;
129 * Construct a resource manager
131 * @param CRM_Extension_Mapper $extMapper
132 * Map extension names to their base path or URLs.
133 * @param CRM_Utils_Cache_Interface $cache
134 * JS-localization cache.
135 * @param string|null $cacheCodeKey Random code to append to resource URLs; changing the code forces clients to reload resources
137 public function __construct($extMapper, $cache, $cacheCodeKey = NULL) {
138 $this->extMapper
= $extMapper;
139 $this->cache
= $cache;
140 $this->cacheCodeKey
= $cacheCodeKey;
141 if ($cacheCodeKey !== NULL) {
142 $this->cacheCode
= CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, $cacheCodeKey);
144 if (!$this->cacheCode
) {
145 $this->resetCacheCode();
147 $this->ajaxPopupsEnabled
= (bool) CRM_Core_BAO_Setting
::getItem(
148 CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'ajaxPopupsEnabled', NULL, TRUE
153 * Add a JavaScript file to the current page using <SCRIPT SRC>.
156 * String, extension name; use 'civicrm' for core.
158 * String, file path -- relative to the extension base dir.
160 * Int, relative weight within a given region.
162 * String, location within the file; 'html-header', 'page-header', 'page-footer'.
163 * @param $translate, whether to parse this file for strings enclosed in ts()
165 * @return CRM_Core_Resources
167 public function addScriptFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
, $translate = TRUE) {
169 $this->translateScript($ext, $file);
171 // Look for non-minified version if we are in debug mode
172 if (CRM_Core_Config
::singleton()->debug
&& strpos($file, '.min.js') !== FALSE) {
173 $nonMiniFile = str_replace('.min.js', '.js', $file);
174 if ($this->getPath($ext, $nonMiniFile)) {
175 $file = $nonMiniFile;
178 return $this->addScriptUrl($this->getUrl($ext, $file, TRUE), $weight, $region);
182 * Add a JavaScript file to the current page using <SCRIPT SRC>.
187 * Int, relative weight within a given region.
189 * String, location within the file; 'html-header', 'page-header', 'page-footer'.
190 * @return CRM_Core_Resources
192 public function addScriptUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
193 CRM_Core_Region
::instance($region)->add(array(
195 'type' => 'scriptUrl',
204 * Add a JavaScript file to the current page using <SCRIPT SRC>.
207 * String, JavaScript source code.
209 * Int, relative weight within a given region.
211 * String, location within the file; 'html-header', 'page-header', 'page-footer'.
212 * @return CRM_Core_Resources
214 public function addScript($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
215 CRM_Core_Region
::instance($region)->add(array(
216 // 'name' => automatic
226 * Add JavaScript variables to CRM.vars
230 * CRM_Core_Resources::singleton()->addVars('myNamespace', array('foo' => 'bar'));
231 * Access var from javascript:
232 * CRM.vars.myNamespace.foo // "bar"
234 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Javascript+Reference
236 * @param string $nameSpace
237 * Usually the name of your extension.
239 * @return CRM_Core_Resources
241 public function addVars($nameSpace, $vars) {
242 $existing = CRM_Utils_Array
::value($nameSpace, CRM_Utils_Array
::value('vars', $this->settings
), array());
243 $vars = $this->mergeSettings($existing, $vars);
244 $this->addSetting(array('vars' => array($nameSpace => $vars)));
249 * Add JavaScript variables to the root of the CRM object.
250 * This function is usually reserved for low-level system use.
251 * Extensions and components should generally use addVars instead.
255 * @return CRM_Core_Resources
257 public function addSetting($settings) {
258 $this->settings
= $this->mergeSettings($this->settings
, $settings);
259 if (!$this->addedSettings
) {
260 $region = self
::isAjaxMode() ?
'ajax-snippet' : 'html-header';
262 CRM_Core_Region
::instance($region)->add(array(
263 'callback' => function(&$snippet, &$html) use ($resources) {
264 $html .= "\n" . $resources->renderSetting();
268 $this->addedSettings
= TRUE;
274 * Add JavaScript variables to the global CRM object via a callback function.
276 * @param callable $callable
277 * @return CRM_Core_Resources
279 public function addSettingsFactory($callable) {
280 // Make sure our callback has been registered
281 $this->addSetting(array());
282 $this->settingsFactories
[] = $callable;
287 * Helper fn for addSettingsFactory
289 public function getSettings() {
290 $result = $this->settings
;
291 foreach ($this->settingsFactories
as $callable) {
292 $result = $this->mergeSettings($result, $callable());
298 * @param array $settings
299 * @param array $additions
300 * @return array combination of $settings and $additions
302 protected function mergeSettings($settings, $additions) {
303 foreach ($additions as $k => $v) {
304 if (isset($settings[$k]) && is_array($settings[$k]) && is_array($v)) {
313 * Helper fn for addSetting
314 * Render JavaScript variables for the global CRM object.
318 public function renderSetting() {
319 // On a standard page request we construct the CRM object from scratch
320 if (!self
::isAjaxMode()) {
321 $js = 'var CRM = ' . json_encode($this->getSettings()) . ';';
323 // For an ajax request we append to it
325 $js = 'CRM.$.extend(true, CRM, ' . json_encode($this->getSettings()) . ');';
327 return sprintf("<script type=\"text/javascript\">\n%s\n</script>\n", $js);
331 * Add translated string to the js CRM object.
332 * It can then be retrived from the client-side ts() function
333 * Variable substitutions can happen from client-side
335 * Note: this function rarely needs to be called directly and is mostly for internal use.
336 * @see CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
340 * CRM_Core_Resources::singleton()->addString('Hello');
341 * // The string is now available to javascript code i.e.
344 * Example with client-side substitutions:
346 * CRM_Core_Resources::singleton()->addString('Your %1 has been %2');
347 * // ts() in javascript works the same as in php, for example:
348 * ts('Your %1 has been %2', {1: objectName, 2: actionTaken});
350 * NOTE: This function does not work with server-side substitutions
351 * (as this might result in collisions and unwanted variable injections)
352 * Instead, use code like:
353 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs)))));
354 * And from javascript access it at CRM.myNamespace.myString
358 * @return CRM_Core_Resources
360 public function addString($text) {
361 foreach ((array) $text as $str) {
362 $translated = ts($str);
363 // We only need to push this string to client if the translation
364 // is actually different from the original
365 if ($translated != $str) {
366 $this->addSetting(array('strings' => array($str => $translated)));
373 * Add a CSS file to the current page using <LINK HREF>.
376 * String, extension name; use 'civicrm' for core.
378 * String, file path -- relative to the extension base dir.
380 * Int, relative weight within a given region.
382 * String, location within the file; 'html-header', 'page-header', 'page-footer'.
383 * @return CRM_Core_Resources
385 public function addStyleFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
386 return $this->addStyleUrl($this->getUrl($ext, $file, TRUE), $weight, $region);
390 * Add a CSS file to the current page using <LINK HREF>.
395 * Int, relative weight within a given region.
397 * String, location within the file; 'html-header', 'page-header', 'page-footer'.
398 * @return CRM_Core_Resources
400 public function addStyleUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
401 CRM_Core_Region
::instance($region)->add(array(
403 'type' => 'styleUrl',
412 * Add a CSS content to the current page using <STYLE>.
415 * String, CSS source code.
417 * Int, relative weight within a given region.
419 * String, location within the file; 'html-header', 'page-header', 'page-footer'.
420 * @return CRM_Core_Resources
422 public function addStyle($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
423 CRM_Core_Region
::instance($region)->add(array(
424 // 'name' => automatic
434 * Determine file path of a resource provided by an extension
437 * String, extension name; use 'civicrm' for core.
439 * String, file path -- relative to the extension base dir.
441 * @return bool|string (string|bool), full file path or FALSE if not found
443 public function getPath($ext, $file) {
444 // TODO consider caching results
445 $path = $this->extMapper
->keyToBasePath($ext) . '/' . $file;
446 if (is_file($path)) {
453 * Determine public URL of a resource provided by an extension
456 * String, extension name; use 'civicrm' for core.
458 * String, file path -- relative to the extension base dir.
459 * @param bool $addCacheCode
461 * @return string, URL
463 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
464 if ($file === NULL) {
468 $file .= '?r=' . $this->getCacheCode();
470 // TODO consider caching results
471 return $this->extMapper
->keyToUrl($ext) . '/' . $file;
477 public function getCacheCode() {
478 return $this->cacheCode
;
483 * @return CRM_Core_Resources
485 public function setCacheCode($value) {
486 $this->cacheCode
= $value;
487 if ($this->cacheCodeKey
) {
488 CRM_Core_BAO_Setting
::setItem($value, CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, $this->cacheCodeKey
);
494 * @return CRM_Core_Resources
496 public function resetCacheCode() {
497 $this->setCacheCode(CRM_Utils_String
::createRandom(5, CRM_Utils_String
::ALPHANUMERIC
));
498 // Also flush cms resource cache if needed
499 CRM_Core_Config
::singleton()->userSystem
->clearResourceCache();
504 * This adds CiviCRM's standard css and js to the specified region of the document.
505 * It will only run once.
507 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
508 * (like addCoreResources/addCoreStyles).
510 * @param string $region
511 * @return CRM_Core_Resources
513 public function addCoreResources($region = 'html-header') {
514 if (!isset($this->addedCoreResources
[$region]) && !self
::isAjaxMode()) {
515 $this->addedCoreResources
[$region] = TRUE;
516 $config = CRM_Core_Config
::singleton();
518 // Add resources from coreResourceList
520 foreach ($this->coreResourceList() as $file) {
521 if (substr($file, -2) == 'js') {
522 // Don't bother looking for ts() calls in packages, there aren't any
523 $translate = (substr($file, 0, 9) != 'packages/');
524 $this->addScriptFile('civicrm', $file, $jsWeight++
, $region, $translate);
527 $this->addStyleFile('civicrm', $file, -100, $region);
531 // Dynamic localization script
532 $this->addScriptUrl(CRM_Utils_System
::url('civicrm/ajax/l10n-js/' . $config->lcMessages
, array('r' => $this->getCacheCode())), $jsWeight++
, $region);
534 // Add global settings
537 'ajaxPopupsEnabled' => $this->ajaxPopupsEnabled
,
538 'isFrontend' => $config->userFrameworkFrontend
,
540 // Disable profile creation if user lacks permission
541 if (!CRM_Core_Permission
::check('edit all contacts') && !CRM_Core_Permission
::check('add contacts')) {
542 $settings['config']['entityRef']['contactCreate'] = FALSE;
544 $this->addSetting($settings);
546 // Give control of jQuery and _ back to the CMS - this loads last
547 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
549 $this->addCoreStyles($region);
555 * This will add CiviCRM's standard CSS
557 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
558 * (like addCoreResources/addCoreStyles).
560 * @param string $region
561 * @return CRM_Core_Resources
563 public function addCoreStyles($region = 'html-header') {
564 if (!isset($this->addedCoreStyles
[$region])) {
565 $this->addedCoreStyles
[$region] = TRUE;
567 // Load custom or core css
568 $config = CRM_Core_Config
::singleton();
569 if (!empty($config->customCSSURL
)) {
570 $this->addStyleUrl($config->customCSSURL
, 99, $region);
572 if (!CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'disable_core_css')) {
573 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
580 * Flushes cached translated strings
581 * @return CRM_Core_Resources
583 public function flushStrings() {
584 $this->cache
->flush();
589 * Translate strings in a javascript file
592 * String, extension name.
597 private function translateScript($ext, $file) {
598 // For each extension, maintain one cache record which
599 // includes parsed (translatable) strings for all its JS files.
600 $stringsByFile = $this->cache
->get($ext); // array($file => array(...strings...))
601 if (!$stringsByFile) {
602 $stringsByFile = array();
604 if (!isset($stringsByFile[$file])) {
605 $filePath = $this->getPath($ext, $file);
606 if ($filePath && is_readable($filePath)) {
607 $stringsByFile[$file] = CRM_Utils_JS
::parseStrings(file_get_contents($filePath));
610 $stringsByFile[$file] = array();
612 $this->cache
->set($ext, $stringsByFile);
614 $this->addString($stringsByFile[$file]);
618 * Create dynamic script for localizing js widgets
620 * @return string javascript content
622 public static function outputLocalizationJS() {
623 CRM_Core_Page_AJAX
::setJsHeaders();
624 $config = CRM_Core_Config
::singleton();
626 'moneyFormat' => json_encode(CRM_Utils_Money
::format(1234.56)),
627 'contactSearch' => json_encode($config->includeEmailInName ?
ts('Start typing a name or email...') : ts('Start typing a name...')),
628 'otherSearch' => json_encode(ts('Enter search term...')),
629 'entityRef' => array(
630 'contactCreate' => CRM_Core_BAO_UFGroup
::getCreateLinks(),
631 'filters' => self
::getEntityRefFilters(),
634 print CRM_Core_Smarty
::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
635 CRM_Utils_System
::civiExit();
639 * List of core resources we add to every CiviCRM page
643 public function coreResourceList() {
644 $config = CRM_Core_Config
::singleton();
645 // Use minified files for production, uncompressed in debug mode
646 // Note, $this->addScriptFile would automatically search for the non-minified file in debug mode but this is probably faster
647 $min = $config->debug ?
'' : '.min';
649 // Scripts needed by everyone, everywhere
650 // FIXME: This is too long; list needs finer-grained segmentation
652 "packages/jquery/jquery-1.11.1$min.js",
653 "packages/jquery/jquery-ui/jquery-ui$min.js",
654 "packages/jquery/jquery-ui/jquery-ui$min.css",
656 "packages/backbone/lodash.compat$min.js",
658 "packages/jquery/plugins/jquery.mousewheel$min.js",
660 "packages/jquery/plugins/select2/select2$min.js",
661 "packages/jquery/plugins/select2/select2.css",
663 "packages/jquery/plugins/jquery.tableHeader.js",
665 "packages/jquery/plugins/jquery.textarearesizer.js",
667 "packages/jquery/plugins/jquery.form$min.js",
669 "packages/jquery/plugins/jquery.timeentry$min.js",
671 "packages/jquery/plugins/jquery.blockUI$min.js",
673 "packages/jquery/plugins/DataTables/media/js/jquery.dataTables$min.js",
674 "packages/jquery/plugins/DataTables/media/css/jquery.dataTables$min.css",
676 "packages/jquery/plugins/jquery.validate$min.js",
677 "packages/jquery/plugins/jquery.ui.datepicker.validation.pack.js",
683 // These scripts are only needed by back-office users
684 if (CRM_Core_Permission
::check('access CiviCRM')) {
685 $items[] = "packages/jquery/plugins/jquery.menu$min.js";
686 $items[] = "packages/jquery/css/menu.css";
687 $items[] = "packages/jquery/plugins/jquery.jeditable$min.js";
688 $items[] = "packages/jquery/plugins/jquery.notify$min.js";
689 $items[] = "js/jquery/jquery.crmeditable.js";
692 // JS for multilingual installations
693 if (!empty($config->languageLimit
) && count($config->languageLimit
) > 1 && CRM_Core_Permission
::check('translate CiviCRM')) {
694 $items[] = "js/crm.multilingual.js";
697 // Enable administrators to edit option lists in a dialog
698 if (CRM_Core_Permission
::check('administer CiviCRM') && $this->ajaxPopupsEnabled
) {
699 $items[] = "js/crm.optionEdit.js";
702 // Add localized jQuery UI files
703 if ($config->lcMessages
&& $config->lcMessages
!= 'en_US') {
704 // Search for i18n file in order of specificity (try fr-CA, then fr)
705 list($lang) = explode('_', $config->lcMessages
);
706 $path = "packages/jquery/jquery-ui/i18n";
707 foreach (array(str_replace('_', '-', $config->lcMessages
), $lang) as $language) {
708 $localizationFile = "$path/datepicker-{$language}.js";
709 if ($this->getPath('civicrm', $localizationFile)) {
710 $items[] = $localizationFile;
716 // CMS-specific resources
717 $config->userSystem
->appendCoreResources($items);
723 * @return bool - is this page request an ajax snippet?
725 public static function isAjaxMode() {
726 return in_array(CRM_Utils_Array
::value('snippet', $_REQUEST), array(CRM_Core_Smarty
::PRINT_SNIPPET
, CRM_Core_Smarty
::PRINT_NOFORM
, CRM_Core_Smarty
::PRINT_JSON
));
730 * Provide a list of available entityRef filters
731 * FIXME: This function doesn't really belong in this class
732 * @TODO: Provide a sane way to extend this list for other entities - a hook or??
735 public static function getEntityRefFilters() {
738 $filters['event'] = array(
739 array('key' => 'event_type_id', 'value' => ts('Event Type')),
741 'key' => 'start_date',
742 'value' => ts('Start Date'),
744 array('key' => '{">":"now"}', 'value' => ts('Upcoming')),
745 array('key' => '{"BETWEEN":["now - 3 month","now"]}', 'value' => ts('Past 3 Months')),
746 array('key' => '{"BETWEEN":["now - 6 month","now"]}', 'value' => ts('Past 6 Months')),
747 array('key' => '{"BETWEEN":["now - 1 year","now"]}', 'value' => ts('Past Year')),
751 $filters['activity'] = array(
752 array('key' => 'activity_type_id', 'value' => ts('Activity Type')),
753 array('key' => 'status_id', 'value' => ts('Activity Status')),
756 $filters['contact'] = array(
757 array('key' => 'contact_type', 'value' => ts('Contact Type')),
758 array('key' => 'group', 'value' => ts('Group'), 'entity' => 'group_contact'),
759 array('key' => 'tag', 'value' => ts('Tag'), 'entity' => 'entity_tag'),
760 array('key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'address'),
761 array('key' => 'country', 'value' => ts('Country'), 'entity' => 'address'),
762 array('key' => 'gender_id', 'value' => ts('Gender')),
763 array('key' => 'is_deceased', 'value' => ts('Deceased')),