3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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
105 * @param $instance CRM_Core_Resources, 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 Map extension names to their base path or URLs.
132 public function __construct($extMapper, $cache, $cacheCodeKey = NULL) {
133 $this->extMapper
= $extMapper;
134 $this->cache
= $cache;
135 $this->cacheCodeKey
= $cacheCodeKey;
136 if ($cacheCodeKey !== NULL) {
137 $this->cacheCode
= CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, $cacheCodeKey);
139 if (!$this->cacheCode
) {
140 $this->resetCacheCode();
142 $this->ajaxPopupsEnabled
= (bool) CRM_Core_BAO_Setting
::getItem(
143 CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'ajaxPopupsEnabled', NULL, TRUE
148 * Add a JavaScript file to the current page using <SCRIPT SRC>.
150 * @param $ext string, extension name; use 'civicrm' for core
151 * @param $file string, file path -- relative to the extension base dir
152 * @param $weight int, relative weight within a given region
153 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
154 * @param $translate, whether to parse this file for strings enclosed in ts()
156 * @return CRM_Core_Resources
158 public function addScriptFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
, $translate = TRUE) {
160 $this->translateScript($ext, $file);
162 return $this->addScriptUrl($this->getUrl($ext, $file, TRUE), $weight, $region);
166 * Add a JavaScript file to the current page using <SCRIPT SRC>.
169 * @param $weight int, relative weight within a given region
170 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
171 * @return CRM_Core_Resources
173 public function addScriptUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
174 CRM_Core_Region
::instance($region)->add(array(
176 'type' => 'scriptUrl',
185 * Add a JavaScript file to the current page using <SCRIPT SRC>.
187 * @param $code string, JavaScript source code
188 * @param $weight int, relative weight within a given region
189 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
190 * @return CRM_Core_Resources
192 public function addScript($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
193 CRM_Core_Region
::instance($region)->add(array(
194 // 'name' => automatic
204 * Add JavaScript variables to the global CRM object.
208 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('foo' => 'bar')));
210 * CRM.myNamespace.foo // "bar"
212 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Javascript+Reference
214 * @param $settings array
215 * @return CRM_Core_Resources
217 public function addSetting($settings) {
218 $this->settings
= $this->mergeSettings($this->settings
, $settings);
219 if (!$this->addedSettings
) {
221 CRM_Core_Region
::instance('html-header')->add(array(
222 'callback' => function(&$snippet, &$html) use ($resources) {
223 $html .= "\n" . $resources->renderSetting();
227 $this->addedSettings
= TRUE;
233 * Add JavaScript variables to the global CRM object via a callback function.
235 * @param $callable function
236 * @return CRM_Core_Resources
238 public function addSettingsFactory($callable) {
239 // Make sure our callback has been registered
240 $this->addSetting(array());
241 $this->settingsFactories
[] = $callable;
246 * Helper fn for addSettingsFactory
248 public function getSettings() {
249 $result = $this->settings
;
250 foreach ($this->settingsFactories
as $callable) {
251 $result = $this->mergeSettings($result, $callable());
257 * @param array $settings
258 * @param array $additions
259 * @return array combination of $settings and $additions
261 protected function mergeSettings($settings, $additions) {
262 foreach ($additions as $k => $v) {
263 if (isset($settings[$k]) && is_array($settings[$k]) && is_array($v)) {
272 * Helper fn for addSetting
273 * Render JavaScript variables for the global CRM object.
277 public function renderSetting() {
278 $js = 'var CRM = ' . json_encode($this->getSettings()) . ';';
279 return sprintf("<script type=\"text/javascript\">\n%s\n</script>\n", $js);
283 * Add translated string to the js CRM object.
284 * It can then be retrived from the client-side ts() function
285 * Variable substitutions can happen from client-side
287 * Note: this function rarely needs to be called directly and is mostly for internal use.
288 * @see CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
292 * CRM_Core_Resources::singleton()->addString('Hello');
293 * // The string is now available to javascript code i.e.
296 * Example with client-side substitutions:
298 * CRM_Core_Resources::singleton()->addString('Your %1 has been %2');
299 * // ts() in javascript works the same as in php, for example:
300 * ts('Your %1 has been %2', {1: objectName, 2: actionTaken});
302 * NOTE: This function does not work with server-side substitutions
303 * (as this might result in collisions and unwanted variable injections)
304 * Instead, use code like:
305 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs)))));
306 * And from javascript access it at CRM.myNamespace.myString
308 * @param $text string|array
309 * @return CRM_Core_Resources
311 public function addString($text) {
312 foreach ((array) $text as $str) {
313 $translated = ts($str);
314 // We only need to push this string to client if the translation
315 // is actually different from the original
316 if ($translated != $str) {
317 $this->addSetting(array('strings' => array($str => $translated)));
324 * Add a CSS file to the current page using <LINK HREF>.
326 * @param $ext string, extension name; use 'civicrm' for core
327 * @param $file string, file path -- relative to the extension base dir
328 * @param $weight int, relative weight within a given region
329 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
330 * @return CRM_Core_Resources
332 public function addStyleFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
333 return $this->addStyleUrl($this->getUrl($ext, $file, TRUE), $weight, $region);
337 * Add a CSS file to the current page using <LINK HREF>.
340 * @param $weight int, relative weight within a given region
341 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
342 * @return CRM_Core_Resources
344 public function addStyleUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
345 CRM_Core_Region
::instance($region)->add(array(
347 'type' => 'styleUrl',
356 * Add a CSS content to the current page using <STYLE>.
358 * @param $code string, CSS source code
359 * @param $weight int, relative weight within a given region
360 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
361 * @return CRM_Core_Resources
363 public function addStyle($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
364 CRM_Core_Region
::instance($region)->add(array(
365 // 'name' => automatic
375 * Determine file path of a resource provided by an extension
377 * @param $ext string, extension name; use 'civicrm' for core
378 * @param $file string, file path -- relative to the extension base dir
380 * @return (string|bool), full file path or FALSE if not found
382 public function getPath($ext, $file) {
383 // TODO consider caching results
384 $path = $this->extMapper
->keyToBasePath($ext) . '/' . $file;
385 if (is_file($path)) {
392 * Determine public URL of a resource provided by an extension
394 * @param $ext string, extension name; use 'civicrm' for core
395 * @param $file string, file path -- relative to the extension base dir
396 * @return string, URL
398 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
399 if ($file === NULL) {
403 $file .= '?r=' . $this->getCacheCode();
405 // TODO consider caching results
406 return $this->extMapper
->keyToUrl($ext) . '/' . $file;
409 public function getCacheCode() {
410 return $this->cacheCode
;
413 public function setCacheCode($value) {
414 $this->cacheCode
= $value;
415 if ($this->cacheCodeKey
) {
416 CRM_Core_BAO_Setting
::setItem($value, CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, $this->cacheCodeKey
);
420 public function resetCacheCode() {
421 $this->setCacheCode(CRM_Utils_String
::createRandom(5, CRM_Utils_String
::ALPHANUMERIC
));
425 * This adds CiviCRM's standard css and js to the specified region of the document.
426 * It will only run once.
428 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
429 * (like addCoreResources/addCoreStyles).
431 * @return CRM_Core_Resources
434 public function addCoreResources($region = 'html-header') {
435 if (!isset($this->addedCoreResources
[$region])) {
436 $this->addedCoreResources
[$region] = TRUE;
437 $config = CRM_Core_Config
::singleton();
439 // Add resources from coreResourceList
441 foreach ($this->coreResourceList() as $file) {
442 if (substr($file, -2) == 'js') {
443 // Don't bother looking for ts() calls in packages, there aren't any
444 $translate = (substr($file, 0, 9) != 'packages/');
445 $this->addScriptFile('civicrm', $file, $jsWeight++
, $region, $translate);
448 $this->addStyleFile('civicrm', $file, -100, $region);
452 // Initialize CRM.url and CRM.formatMoney
453 $url = CRM_Utils_System
::url('civicrm/example', 'placeholder', FALSE, NULL, FALSE);
454 $js = "CRM.url('init', '$url');\n";
455 $js .= "CRM.formatMoney('init', " . json_encode(CRM_Utils_Money
::format(1234.56)) . ");";
457 $this->addLocalization($js);
458 $this->addScript($js, $jsWeight++
, $region);
460 // Add global settings
462 'userFramework' => $config->userFramework
,
463 'resourceBase' => $config->resourceBase
,
464 'lcMessages' => $config->lcMessages
,
465 'ajaxPopupsEnabled' => $this->ajaxPopupsEnabled
,
467 $this->addSetting(array('config' => $settings));
469 // Give control of jQuery back to the CMS - this loads last
470 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
472 $this->addCoreStyles($region);
478 * This will add CiviCRM's standard CSS
480 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
481 * (like addCoreResources/addCoreStyles).
483 * @param string $region
484 * @return CRM_Core_Resources
486 public function addCoreStyles($region = 'html-header') {
487 if (!isset($this->addedCoreStyles
[$region])) {
488 $this->addedCoreStyles
[$region] = TRUE;
490 // Load custom or core css
491 $config = CRM_Core_Config
::singleton();
492 if (!empty($config->customCSSURL
)) {
493 $this->addStyleUrl($config->customCSSURL
, 99, $region);
495 if (!CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'disable_core_css')) {
496 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
503 * Flushes cached translated strings
505 public function flushStrings() {
506 $this->cache
->flush();
510 * Translate strings in a javascript file
512 * @param $ext string, extension name
513 * @param $file string, file path
516 private function translateScript($ext, $file) {
517 // For each extension, maintain one cache record which
518 // includes parsed (translatable) strings for all its JS files.
519 $stringsByFile = $this->cache
->get($ext); // array($file => array(...strings...))
520 if (!$stringsByFile) {
521 $stringsByFile = array();
523 if (!isset($stringsByFile[$file])) {
524 $filePath = $this->getPath($ext, $file);
525 if ($filePath && is_readable($filePath)) {
526 $stringsByFile[$file] = CRM_Utils_JS
::parseStrings(file_get_contents($filePath));
528 $stringsByFile[$file] = array();
530 $this->cache
->set($ext, $stringsByFile);
532 $this->addString($stringsByFile[$file]);
536 * Add inline scripts needed to localize js widgets
539 function addLocalization(&$js) {
540 $config = CRM_Core_Config
::singleton();
542 // Localize select2 strings
543 $contactSearch = json_encode($config->includeEmailInName ?
ts('Start typing a name or email...') : ts('Start typing a name...'));
544 $otherSearch = json_encode(ts('Enter search term...'));
546 $.fn.select2.defaults.formatNoMatches = " . json_encode(ts("None found.")) . ";
547 $.fn.select2.defaults.formatLoadMore = " . json_encode(ts("Loading...")) . ";
548 $.fn.select2.defaults.formatSearching = " . json_encode(ts("Searching...")) . ";
549 $.fn.select2.defaults.formatInputTooShort = function(){return cj(this).data('api-entity') == 'contact' ? $contactSearch : $otherSearch};
552 // Contact create profiles with localized names
553 if (CRM_Core_Permission
::check('edit all contacts') || CRM_Core_Permission
::check('add contacts')) {
554 $this->addSetting(array('profile' => array('contactCreate' => CRM_Core_BAO_UFGroup
::getCreateLinks())));
559 * List of core resources we add to every CiviCRM page
563 public function coreResourceList() {
564 $config = CRM_Core_Config
::singleton();
565 // Use minified files for production, uncompressed in debug mode
566 $min = $config->debug ?
'' : '.min';
568 // Scripts needed by everyone, everywhere
569 // FIXME: This is too long; list needs finer-grained segmentation
571 "packages/jquery/jquery-1.11.0$min.js",
572 "packages/jquery/jquery-migrate-1.2.1.js", // TODO: Remove before 4.5 release
573 "packages/jquery/jquery-ui/js/jquery-ui-1.10.4.custom$min.js",
574 "packages/jquery/jquery-ui/css/theme/jquery-ui-1.10.4.custom$min.css",
576 "packages/backbone/lodash.compat$min.js",
578 "packages/jquery/plugins/jquery.mousewheel$min.js",
580 "packages/jquery/plugins/select2/select2.js", // No mini until release of select2 3.4.6
581 "packages/jquery/plugins/select2/select2.css",
583 // TODO: Remove before 4.5 release
584 "packages/jquery/plugins/jquery.autocomplete.js",
585 "packages/jquery/css/jquery.autocomplete.css",
587 "packages/jquery/plugins/jquery.tableHeader.js",
589 "packages/jquery/plugins/jquery.textarearesizer.js",
591 "packages/jquery/plugins/jquery.form$min.js",
593 "packages/jquery/plugins/jquery.timeentry$min.js",
595 "packages/jquery/plugins/DataTables/media/js/jquery.dataTables$min.js",
597 "packages/jquery/plugins/jquery.FormNavigate$min.js",
599 "packages/jquery/plugins/jquery.validate$min.js",
600 "packages/jquery/plugins/jquery.ui.datepicker.validation.pack.js",
606 // These scripts are only needed by back-office users
607 if (CRM_Core_Permission
::check('access CiviCRM')) {
608 $items[] = "packages/jquery/plugins/jquery.menu$min.js";
609 $items[] = "packages/jquery/css/menu.css";
610 $items[] = "packages/jquery/plugins/jquery.jeditable$min.js";
611 $items[] = "packages/jquery/plugins/jquery.blockUI$min.js";
612 $items[] = "packages/jquery/plugins/jquery.notify$min.js";
613 $items[] = "js/jquery/jquery.crmeditable.js";
615 // TODO: tokeninput is deprecated in favor of select2 and will be removed soon
616 $items[] = "packages/jquery/plugins/jquery.tokeninput$min.js";
617 $items[] = "packages/jquery/css/token-input-facebook.css";
620 // Enable administrators to edit option lists in a dialog
621 if (CRM_Core_Permission
::check('administer CiviCRM') && $this->ajaxPopupsEnabled
) {
622 $items[] = "js/crm.optionEdit.js";
625 // Add localized jQuery UI files
626 if ($config->lcMessages
&& $config->lcMessages
!= 'en_US') {
627 // Search for i18n file in order of specificity (try fr-CA, then fr)
628 list($lang) = explode('_', $config->lcMessages
);
629 $path = "packages/jquery/jquery-ui/development-bundle/ui/" . ($min ?
'minified/' : '') . "i18n";
630 foreach (array(str_replace('_', '-', $config->lcMessages
), $lang) as $language) {
631 $localizationFile = "$path/jquery.ui.datepicker-{$language}{$min}.js";
632 if ($this->getPath('civicrm', $localizationFile)) {
633 $items[] = $localizationFile;