3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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;
98 * Get or set the single instance of CRM_Core_Resources
100 * @param $instance CRM_Core_Resources, new copy of the manager
101 * @return CRM_Core_Resources
103 static public function singleton(CRM_Core_Resources
$instance = NULL) {
104 if ($instance !== NULL) {
105 self
::$_singleton = $instance;
107 if (self
::$_singleton === NULL) {
108 $sys = CRM_Extension_System
::singleton();
109 $cache = new CRM_Utils_Cache_SqlGroup(array(
110 'group' => 'js-strings',
113 self
::$_singleton = new CRM_Core_Resources(
116 CRM_Core_Config
::isUpgradeMode() ?
NULL : 'resCacheCode'
119 return self
::$_singleton;
123 * Construct a resource manager
125 * @param CRM_Extension_Mapper $extMapper Map extension names to their base path or URLs.
127 public function __construct($extMapper, $cache, $cacheCodeKey = NULL) {
128 $this->extMapper
= $extMapper;
129 $this->cache
= $cache;
130 $this->cacheCodeKey
= $cacheCodeKey;
131 if ($cacheCodeKey !== NULL) {
132 $this->cacheCode
= CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, $cacheCodeKey);
134 if (!$this->cacheCode
) {
135 $this->resetCacheCode();
140 * Add a JavaScript file to the current page using <SCRIPT SRC>.
142 * @param $ext string, extension name; use 'civicrm' for core
143 * @param $file string, file path -- relative to the extension base dir
144 * @param $weight int, relative weight within a given region
145 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
146 * @param $translate, whether to parse this file for strings enclosed in ts()
148 * @return CRM_Core_Resources
150 public function addScriptFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
, $translate = TRUE) {
152 $this->translateScript($ext, $file);
154 return $this->addScriptUrl($this->getUrl($ext, $file, TRUE), $weight, $region);
158 * Add a JavaScript file to the current page using <SCRIPT SRC>.
161 * @param $weight int, relative weight within a given region
162 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
163 * @return CRM_Core_Resources
165 public function addScriptUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
166 CRM_Core_Region
::instance($region)->add(array(
168 'type' => 'scriptUrl',
177 * Add a JavaScript file to the current page using <SCRIPT SRC>.
179 * @param $code string, JavaScript source code
180 * @param $weight int, relative weight within a given region
181 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
182 * @return CRM_Core_Resources
184 public function addScript($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
185 CRM_Core_Region
::instance($region)->add(array(
186 // 'name' => automatic
196 * Add JavaScript variables to the global CRM object.
198 * @param $settings array
199 * @return CRM_Core_Resources
201 public function addSetting($settings) {
202 $this->settings
= $this->mergeSettings($this->settings
, $settings);
203 if (!$this->addedSettings
) {
205 CRM_Core_Region
::instance('html-header')->add(array(
206 'callback' => function(&$snippet, &$html) use ($resources) {
207 $html .= "\n" . $resources->renderSetting();
211 $this->addedSettings
= TRUE;
217 * Add JavaScript variables to the global CRM object.
219 * @param $callable function
220 * @return CRM_Core_Resources
222 public function addSettingsFactory($callable) {
223 // Make sure our callback has been registered
224 $this->addSetting(array());
225 $this->settingsFactories
[] = $callable;
229 public function getSettings() {
230 $result = $this->settings
;
231 foreach ($this->settingsFactories
as $callable) {
232 $result = $this->mergeSettings($result, $callable());
238 * @param array $settings
239 * @param array $additions
240 * @return array combination of $settings and $additions
242 protected function mergeSettings($settings, $additions) {
243 foreach ($additions as $k => $v) {
244 if (isset($settings[$k]) && is_array($settings[$k]) && is_array($v)) {
253 * Helper fn for addSetting
254 * Render JavaScript variables for the global CRM object.
258 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('foo' => 'bar')));
260 * CRM.myNamespace.foo // "bar"
264 public function renderSetting() {
265 $js = 'var CRM = ' . json_encode($this->getSettings()) . ';';
266 return sprintf("<script type=\"text/javascript\">\n%s\n</script>\n", $js);
270 * Add translated string to the js CRM object.
271 * It can then be retrived from the client-side ts() function
272 * Variable substitutions can happen from client-side
274 * Note: this function rarely needs to be called directly and is mostly for internal use.
275 * @see CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
279 * CRM_Core_Resources::singleton()->addString('Hello');
280 * // The string is now available to javascript code i.e.
283 * Example with client-side substitutions:
285 * CRM_Core_Resources::singleton()->addString('Your %1 has been %2');
286 * // ts() in javascript works the same as in php, for example:
287 * ts('Your %1 has been %2', {1: objectName, 2: actionTaken});
289 * NOTE: This function does not work with server-side substitutions
290 * (as this might result in collisions and unwanted variable injections)
291 * Instead, use code like:
292 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs)))));
293 * And from javascript access it at CRM.myNamespace.myString
295 * @param $text string|array
296 * @return CRM_Core_Resources
298 public function addString($text) {
299 foreach ((array) $text as $str) {
300 $translated = ts($str);
301 // We only need to push this string to client if the translation
302 // is actually different from the original
303 if ($translated != $str) {
304 $this->addSetting(array('strings' => array($str => $translated)));
311 * Add a CSS file to the current page using <LINK HREF>.
313 * @param $ext string, extension name; use 'civicrm' for core
314 * @param $file string, file path -- relative to the extension base dir
315 * @param $weight int, relative weight within a given region
316 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
317 * @return CRM_Core_Resources
319 public function addStyleFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
320 return $this->addStyleUrl($this->getUrl($ext, $file, TRUE), $weight, $region);
324 * Add a CSS file to the current page using <LINK HREF>.
327 * @param $weight int, relative weight within a given region
328 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
329 * @return CRM_Core_Resources
331 public function addStyleUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
332 CRM_Core_Region
::instance($region)->add(array(
334 'type' => 'styleUrl',
343 * Add a CSS content to the current page using <STYLE>.
345 * @param $code string, CSS source code
346 * @param $weight int, relative weight within a given region
347 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
348 * @return CRM_Core_Resources
350 public function addStyle($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
351 CRM_Core_Region
::instance($region)->add(array(
352 // 'name' => automatic
362 * Determine file path of a resource provided by an extension
364 * @param $ext string, extension name; use 'civicrm' for core
365 * @param $file string, file path -- relative to the extension base dir
367 * @return (string|bool), full file path or FALSE if not found
369 public function getPath($ext, $file) {
370 // TODO consider caching results
371 $path = $this->extMapper
->keyToBasePath($ext) . '/' . $file;
372 if (is_file($path)) {
379 * Determine public URL of a resource provided by an extension
381 * @param $ext string, extension name; use 'civicrm' for core
382 * @param $file string, file path -- relative to the extension base dir
383 * @return string, URL
385 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
386 if ($file === NULL) {
390 $file .= '?r=' . $this->getCacheCode();
392 // TODO consider caching results
393 return $this->extMapper
->keyToUrl($ext) . '/' . $file;
396 public function getCacheCode() {
397 return $this->cacheCode
;
400 public function setCacheCode($value) {
401 $this->cacheCode
= $value;
402 if ($this->cacheCodeKey
) {
403 CRM_Core_BAO_Setting
::setItem($value, CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, $this->cacheCodeKey
);
407 public function resetCacheCode() {
408 $this->setCacheCode(CRM_Utils_String
::createRandom(5, CRM_Utils_String
::ALPHANUMERIC
));
412 * This adds CiviCRM's standard css and js to the specified region of the document.
413 * It will only run once.
415 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
416 * (like addCoreResources/addCoreStyles).
418 * @return CRM_Core_Resources
421 public function addCoreResources($region = 'html-header') {
422 if (!isset($this->addedCoreResources
[$region])) {
423 $this->addedCoreResources
[$region] = TRUE;
424 $config = CRM_Core_Config
::singleton();
426 // Add resources from jquery.files.tpl
427 $files = self
::parseTemplate('CRM/common/jquery.files.tpl');
429 foreach ($files as $file => $type) {
431 // Don't bother looking for ts() calls in packages, there aren't any
432 $translate = (substr($file, 0, 9) != 'packages/');
433 $this->addScriptFile('civicrm', $file, $jsWeight++
, $region, $translate);
435 elseif ($type == 'css') {
436 $this->addStyleFile('civicrm', $file, -100, $region);
440 // Add localized calendar js
441 // Search for i18n file in order of specificity (try fr-CA, then fr)
442 list($lang) = explode('_', $config->lcMessages
);
443 foreach (array(str_replace('_', '-', $config->lcMessages
), $lang) as $language) {
444 $localizationFile = "packages/jquery/jquery-ui-1.9.0/development-bundle/ui/i18n/jquery.ui.datepicker-{$language}.js";
445 if ($this->getPath('civicrm', $localizationFile)) {
446 $this->addScriptFile('civicrm', $localizationFile, $jsWeight++
, $region, FALSE);
451 // Initialize CRM.url
452 $url = CRM_Utils_System
::url('civicrm/example', 'placeholder', FALSE, NULL, FALSE);
453 $js = "CRM.url('init', '$url');";
454 $this->addScript($js, $jsWeight++
, $region);
456 // Add global settings
458 'userFramework' => $config->userFramework
,
459 'resourceBase' => $config->resourceBase
,
461 $this->addSetting(array('config' => $settings));
463 // Give control of jQuery back to the CMS - this loads last
464 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
466 $this->addCoreStyles($region);
472 * This will add CiviCRM's standard CSS
474 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
475 * (like addCoreResources/addCoreStyles).
477 * @param string $region
478 * @return CRM_Core_Resources
480 public function addCoreStyles($region = 'html-header') {
481 if (!isset($this->addedCoreStyles
[$region])) {
482 $this->addedCoreStyles
[$region] = TRUE;
484 // Load custom or core css
485 $config = CRM_Core_Config
::singleton();
486 if (!empty($config->customCSSURL
)) {
487 $this->addStyleUrl($config->customCSSURL
, -99, $region);
490 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
491 $this->addStyleFile('civicrm', 'css/extras.css', -98, $region);
498 * Flushes cached translated strings
500 public function flushStrings() {
501 $this->cache
->flush();
505 * Translate strings in a javascript file
507 * @param $ext string, extension name
508 * @param $file string, file path
511 private function translateScript($ext, $file) {
512 // For each extension, maintain one cache record which
513 // includes parsed (translatable) strings for all its JS files.
514 $stringsByFile = $this->cache
->get($ext); // array($file => array(...strings...))
515 if (!$stringsByFile) {
516 $stringsByFile = array();
518 if (!isset($stringsByFile[$file])) {
519 $filePath = $this->getPath($ext, $file);
520 if ($filePath && is_readable($filePath)) {
521 $stringsByFile[$file] = CRM_Utils_JS
::parseStrings(file_get_contents($filePath));
523 $stringsByFile[$file] = array();
525 $this->cache
->set($ext, $stringsByFile);
527 $this->addString($stringsByFile[$file]);
531 * Read resource files from a template
533 * @param $tpl (str) template file name
534 * @return array: filename => filetype
536 static function parseTemplate($tpl) {
538 $template = CRM_Core_Smarty
::singleton();
539 $buffer = $template->fetch($tpl);
540 $lines = preg_split('/\s+/', $buffer);
541 foreach ($lines as $line) {
544 $items[$line] = substr($line, 1 +
strrpos($line, '.'));