Merge pull request #106 from colemanw/noconflict
[civicrm-core.git] / CRM / Core / Resources.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 * @static
53 */
54 private static $_singleton = NULL;
55
56 /**
57 * @var CRM_Extension_Mapper
58 */
59 private $extMapper = NULL;
60
61 /**
62 * @var CRM_Utils_Cache_Interface
63 */
64 private $cache = NULL;
65
66 /**
67 * @var array free-form data tree
68 */
69 protected $settings = array();
70 protected $addedSettings = FALSE;
71
72 /**
73 * @var array of callables
74 */
75 protected $settingsFactories = array();
76
77 /**
78 * @var array ($regionName => bool)
79 */
80 protected $addedCoreResources = array();
81
82 /**
83 * @var array ($regionName => bool)
84 */
85 protected $addedCoreStyles = array();
86
87 /**
88 * @var string a value to append to JS/CSS URLs to coerce cache resets
89 */
90 protected $cacheCode = NULL;
91
92 /**
93 * @var string the name of a setting which persistently stores the cacheCode
94 */
95 protected $cacheCodeKey = NULL;
96
97 /**
98 * Get or set the single instance of CRM_Core_Resources
99 *
100 * @param $instance CRM_Core_Resources, new copy of the manager
101 * @return CRM_Core_Resources
102 */
103 static public function singleton(CRM_Core_Resources $instance = NULL) {
104 if ($instance !== NULL) {
105 self::$_singleton = $instance;
106 }
107 if (self::$_singleton === NULL) {
108 $sys = CRM_Extension_System::singleton();
109 $cache = new CRM_Utils_Cache_SqlGroup(array(
110 'group' => 'js-strings',
111 'prefetch' => FALSE,
112 ));
113 self::$_singleton = new CRM_Core_Resources(
114 $sys->getMapper(),
115 $cache,
116 'resCacheCode'
117 );
118 }
119 return self::$_singleton;
120 }
121
122 /**
123 * Construct a resource manager
124 *
125 * @param CRM_Extension_Mapper $extMapper Map extension names to their base path or URLs.
126 */
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);
133 }
134 if (! $this->cacheCode) {
135 $this->resetCacheCode();
136 }
137 }
138
139 /**
140 * Add a JavaScript file to the current page using <SCRIPT SRC>.
141 *
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()
147 *
148 * @return CRM_Core_Resources
149 */
150 public function addScriptFile($ext, $file, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION, $translate = TRUE) {
151 if ($translate) {
152 $this->translateScript($ext, $file);
153 }
154 return $this->addScriptUrl($this->getUrl($ext, $file, TRUE), $weight, $region);
155 }
156
157 /**
158 * Add a JavaScript file to the current page using <SCRIPT SRC>.
159 *
160 * @param $url string
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
164 */
165 public function addScriptUrl($url, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
166 CRM_Core_Region::instance($region)->add(array(
167 'name' => $url,
168 'type' => 'scriptUrl',
169 'scriptUrl' => $url,
170 'weight' => $weight,
171 'region' => $region,
172 ));
173 return $this;
174 }
175
176 /**
177 * Add a JavaScript file to the current page using <SCRIPT SRC>.
178 *
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
183 */
184 public function addScript($code, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
185 CRM_Core_Region::instance($region)->add(array(
186 // 'name' => automatic
187 'type' => 'script',
188 'script' => $code,
189 'weight' => $weight,
190 'region' => $region,
191 ));
192 return $this;
193 }
194
195 /**
196 * Add JavaScript variables to the global CRM object.
197 *
198 * @param $settings array
199 * @return CRM_Core_Resources
200 */
201 public function addSetting($settings) {
202 $this->settings = $this->mergeSettings($this->settings, $settings);
203 if (!$this->addedSettings) {
204 $resources = $this;
205 CRM_Core_Region::instance('settings')->add(array(
206 'callback' => function(&$snippet, &$html) use ($resources) {
207 $html .= "\n" . $resources->renderSetting();
208 }
209 ));
210 $this->addedSettings = TRUE;
211 }
212 return $this;
213 }
214
215 /**
216 * Add JavaScript variables to the global CRM object.
217 *
218 * @param $callable function
219 * @return CRM_Core_Resources
220 */
221 public function addSettingsFactory($callable) {
222 $this->addSetting(array()); // ensure that 'settings' region is created, even if empty
223 $this->settingsFactories[] = $callable;
224 return $this;
225 }
226
227 public function getSettings() {
228 $result = $this->settings;
229 foreach ($this->settingsFactories as $callable) {
230 $result = $this->mergeSettings($result, $callable());
231 }
232 return $result;
233 }
234
235 /**
236 * @param array $settings
237 * @param array $additions
238 * @return array combination of $settings and $additions
239 */
240 protected function mergeSettings($settings, $additions) {
241 foreach ($additions as $k => $v) {
242 if (isset($settings[$k]) && is_array($settings[$k]) && is_array($v)) {
243 $v += $settings[$k];
244 }
245 $settings[$k] = $v;
246 }
247 return $settings;
248 }
249
250 /**
251 * Helper fn for addSetting
252 * Render JavaScript variables for the global CRM object.
253 *
254 * Example:
255 * From the server:
256 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('foo' => 'bar')));
257 * From javascript:
258 * CRM.myNamespace.foo // "bar"
259 *
260 * @return string
261 */
262 public function renderSetting() {
263 return 'CRM = cj.extend(true, ' . json_encode($this->getSettings()) . ', CRM);';
264 }
265
266 /**
267 * Add translated string to the js CRM object.
268 * It can then be retrived from the client-side ts() function
269 * Variable substitutions can happen from client-side
270 *
271 * Note: this function rarely needs to be called directly and is mostly for internal use.
272 * @see CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
273 *
274 * Simple example:
275 * // From php:
276 * CRM_Core_Resources::singleton()->addString('Hello');
277 * // The string is now available to javascript code i.e.
278 * ts('Hello');
279 *
280 * Example with client-side substitutions:
281 * // From php:
282 * CRM_Core_Resources::singleton()->addString('Your %1 has been %2');
283 * // ts() in javascript works the same as in php, for example:
284 * ts('Your %1 has been %2', {1: objectName, 2: actionTaken});
285 *
286 * NOTE: This function does not work with server-side substitutions
287 * (as this might result in collisions and unwanted variable injections)
288 * Instead, use code like:
289 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs)))));
290 * And from javascript access it at CRM.myNamespace.myString
291 *
292 * @param $text string|array
293 * @return CRM_Core_Resources
294 */
295 public function addString($text) {
296 foreach ((array) $text as $str) {
297 $translated = ts($str);
298 // We only need to push this string to client if the translation
299 // is actually different from the original
300 if ($translated != $str) {
301 $this->addSetting(array('strings' => array($str => $translated)));
302 }
303 }
304 return $this;
305 }
306
307 /**
308 * Add a CSS file to the current page using <LINK HREF>.
309 *
310 * @param $ext string, extension name; use 'civicrm' for core
311 * @param $file string, file path -- relative to the extension base dir
312 * @param $weight int, relative weight within a given region
313 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
314 * @return CRM_Core_Resources
315 */
316 public function addStyleFile($ext, $file, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
317 return $this->addStyleUrl($this->getUrl($ext, $file, TRUE), $weight, $region);
318 }
319
320 /**
321 * Add a CSS file to the current page using <LINK HREF>.
322 *
323 * @param $url string
324 * @param $weight int, relative weight within a given region
325 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
326 * @return CRM_Core_Resources
327 */
328 public function addStyleUrl($url, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
329 CRM_Core_Region::instance($region)->add(array(
330 'name' => $url,
331 'type' => 'styleUrl',
332 'styleUrl' => $url,
333 'weight' => $weight,
334 'region' => $region,
335 ));
336 return $this;
337 }
338
339 /**
340 * Add a CSS content to the current page using <STYLE>.
341 *
342 * @param $code string, CSS source code
343 * @param $weight int, relative weight within a given region
344 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
345 * @return CRM_Core_Resources
346 */
347 public function addStyle($code, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
348 CRM_Core_Region::instance($region)->add(array(
349 // 'name' => automatic
350 'type' => 'style',
351 'style' => $code,
352 'weight' => $weight,
353 'region' => $region,
354 ));
355 return $this;
356 }
357
358 /**
359 * Determine file path of a resource provided by an extension
360 *
361 * @param $ext string, extension name; use 'civicrm' for core
362 * @param $file string, file path -- relative to the extension base dir
363 *
364 * @return (string|bool), full file path or FALSE if not found
365 */
366 public function getPath($ext, $file) {
367 // TODO consider caching results
368 $path = $this->extMapper->keyToBasePath($ext) . '/' . $file;
369 if (is_file($path)) {
370 return $path;
371 }
372 return FALSE;
373 }
374
375 /**
376 * Determine public URL of a resource provided by an extension
377 *
378 * @param $ext string, extension name; use 'civicrm' for core
379 * @param $file string, file path -- relative to the extension base dir
380 * @return string, URL
381 */
382 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
383 if ($file === NULL) {
384 $file = '';
385 }
386 if ($addCacheCode) {
387 $file .= '?r=' . $this->getCacheCode();
388 }
389 // TODO consider caching results
390 return $this->extMapper->keyToUrl($ext) . '/' . $file;
391 }
392
393 public function getCacheCode() {
394 return $this->cacheCode;
395 }
396
397 public function setCacheCode($value) {
398 $this->cacheCode = $value;
399 if ($this->cacheCodeKey) {
400 CRM_Core_BAO_Setting::setItem($value, CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, $this->cacheCodeKey);
401 }
402 }
403
404 public function resetCacheCode() {
405 $this->setCacheCode(CRM_Utils_String::createRandom(5, CRM_Utils_String::ALPHANUMERIC));
406 }
407
408 /**
409 * This adds CiviCRM's standard css and js to the specified region of the document.
410 * It will only run once.
411 *
412 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
413 * (like addCoreResources/addCoreStyles).
414 *
415 * @return CRM_Core_Resources
416 * @access public
417 */
418 public function addCoreResources($region = 'html-header') {
419 if (!isset($this->addedCoreResources[$region])) {
420 $this->addedCoreResources[$region] = TRUE;
421 $config = CRM_Core_Config::singleton();
422
423 // Add resources from jquery.files.tpl
424 $files = self::parseTemplate('CRM/common/jquery.files.tpl');
425 $jsWeight = -9999;
426 foreach ($files as $file => $type) {
427 if ($type == 'js') {
428 $this->addScriptFile('civicrm', $file, $jsWeight++, $region, FALSE);
429 }
430 elseif ($type == 'css') {
431 $this->addStyleFile('civicrm', $file, -100, $region);
432 }
433 }
434
435 // Add localized calendar js
436 list($lang) = explode('_', $config->lcMessages);
437 $localizationFile = "packages/jquery/jquery-ui-1.9.0/development-bundle/ui/i18n/jquery.ui.datepicker-{$lang}.js";
438 if ($this->getPath('civicrm', $localizationFile)) {
439 $this->addScriptFile('civicrm', $localizationFile, $jsWeight++, $region, FALSE);
440 }
441
442 // Give control of jQuery back to the CMS - this loads last
443 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region);
444
445 $this->addCoreStyles($region);
446 }
447 return $this;
448 }
449
450 /**
451 * This will add CiviCRM's standard CSS
452 *
453 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
454 * (like addCoreResources/addCoreStyles).
455 *
456 * @param string $region
457 * @return CRM_Core_Resources
458 */
459 public function addCoreStyles($region = 'html-header') {
460 if (!isset($this->addedCoreStyles[$region])) {
461 $this->addedCoreStyles[$region] = TRUE;
462
463 // Load custom or core css
464 $config = CRM_Core_Config::singleton();
465 if (!empty($config->customCSSURL)) {
466 $this->addStyleUrl($config->customCSSURL, -99, $region);
467 }
468 else {
469 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
470 $this->addStyleFile('civicrm', 'css/extras.css', -98, $region);
471 }
472 }
473 return $this;
474 }
475
476 /**
477 * Translate strings in a javascript file
478 *
479 * @param $ext string, extension name
480 * @param $file string, file path
481 * @return void
482 */
483 private function translateScript($ext, $file) {
484 // For each extension, maintain one cache record which
485 // includes parsed (translatable) strings for all its JS files.
486 $stringsByFile = $this->cache->get($ext); // array($file => array(...strings...))
487 if (!$stringsByFile) {
488 $stringsByFile = array();
489 }
490 if (!isset($stringsByFile[$file])) {
491 $filePath = $this->getPath($ext, $file);
492 if ($filePath && is_readable($filePath)) {
493 $stringsByFile[$file] = CRM_Utils_JS::parseStrings(file_get_contents($filePath));
494 } else {
495 $stringsByFile[$file] = array();
496 }
497 $this->cache->set($ext, $stringsByFile);
498 }
499 $this->addString($stringsByFile[$file]);
500 }
501
502 /**
503 * Read resource files from a template
504 *
505 * @param $tpl (str) template file name
506 * @return array: filename => filetype
507 */
508 static function parseTemplate($tpl) {
509 $items = array();
510 $template = CRM_Core_Smarty::singleton();
511 $buffer = $template->fetch($tpl);
512 $lines = preg_split('/\s+/', $buffer);
513 foreach ($lines as $line) {
514 $line = trim($line);
515 if ($line) {
516 $items[$line] = substr($line, 1 + strrpos($line, '.'));
517 }
518 }
519 return $items;
520 }
521 }