CRM-13930 - fix jquery.menu namespace
[civicrm-core.git] / CRM / Core / Resources.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
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 */
44class 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,
eb897088 116 CRM_Core_Config::isUpgradeMode() ? NULL : 'resCacheCode'
6a488035
TO
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 }
150f50c1 134 if (!$this->cacheCode) {
6a488035
TO
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 *
132fc68e
CW
198 * Example:
199 * From the server:
200 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('foo' => 'bar')));
201 * From javascript:
202 * CRM.myNamespace.foo // "bar"
203 *
01478033 204 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Javascript+Reference
132fc68e 205 *
6a488035
TO
206 * @param $settings array
207 * @return CRM_Core_Resources
208 */
209 public function addSetting($settings) {
210 $this->settings = $this->mergeSettings($this->settings, $settings);
211 if (!$this->addedSettings) {
212 $resources = $this;
d759bd10 213 CRM_Core_Region::instance('html-header')->add(array(
6a488035
TO
214 'callback' => function(&$snippet, &$html) use ($resources) {
215 $html .= "\n" . $resources->renderSetting();
8cb324cc
CW
216 },
217 'weight' => -100000,
6a488035
TO
218 ));
219 $this->addedSettings = TRUE;
220 }
221 return $this;
222 }
223
224 /**
69847402 225 * Add JavaScript variables to the global CRM object via a callback function.
6a488035
TO
226 *
227 * @param $callable function
228 * @return CRM_Core_Resources
229 */
230 public function addSettingsFactory($callable) {
d937dbcd
CW
231 // Make sure our callback has been registered
232 $this->addSetting(array());
6a488035
TO
233 $this->settingsFactories[] = $callable;
234 return $this;
235 }
236
69847402
CW
237 /**
238 * Helper fn for addSettingsFactory
239 */
6a488035
TO
240 public function getSettings() {
241 $result = $this->settings;
242 foreach ($this->settingsFactories as $callable) {
243 $result = $this->mergeSettings($result, $callable());
244 }
245 return $result;
246 }
247
248 /**
249 * @param array $settings
250 * @param array $additions
251 * @return array combination of $settings and $additions
252 */
253 protected function mergeSettings($settings, $additions) {
254 foreach ($additions as $k => $v) {
255 if (isset($settings[$k]) && is_array($settings[$k]) && is_array($v)) {
256 $v += $settings[$k];
257 }
258 $settings[$k] = $v;
259 }
260 return $settings;
261 }
262
263 /**
264 * Helper fn for addSetting
265 * Render JavaScript variables for the global CRM object.
266 *
6a488035
TO
267 * @return string
268 */
269 public function renderSetting() {
8cb324cc 270 $js = 'var CRM = ' . json_encode($this->getSettings()) . ';';
d759bd10 271 return sprintf("<script type=\"text/javascript\">\n%s\n</script>\n", $js);
6a488035
TO
272 }
273
274 /**
275 * Add translated string to the js CRM object.
276 * It can then be retrived from the client-side ts() function
277 * Variable substitutions can happen from client-side
8ef12e64 278 *
6a488035
TO
279 * Note: this function rarely needs to be called directly and is mostly for internal use.
280 * @see CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
281 *
282 * Simple example:
283 * // From php:
284 * CRM_Core_Resources::singleton()->addString('Hello');
285 * // The string is now available to javascript code i.e.
286 * ts('Hello');
287 *
288 * Example with client-side substitutions:
289 * // From php:
290 * CRM_Core_Resources::singleton()->addString('Your %1 has been %2');
291 * // ts() in javascript works the same as in php, for example:
292 * ts('Your %1 has been %2', {1: objectName, 2: actionTaken});
293 *
294 * NOTE: This function does not work with server-side substitutions
295 * (as this might result in collisions and unwanted variable injections)
296 * Instead, use code like:
297 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs)))));
298 * And from javascript access it at CRM.myNamespace.myString
299 *
300 * @param $text string|array
301 * @return CRM_Core_Resources
302 */
303 public function addString($text) {
304 foreach ((array) $text as $str) {
305 $translated = ts($str);
306 // We only need to push this string to client if the translation
307 // is actually different from the original
308 if ($translated != $str) {
309 $this->addSetting(array('strings' => array($str => $translated)));
310 }
311 }
312 return $this;
313 }
314
315 /**
316 * Add a CSS file to the current page using <LINK HREF>.
317 *
318 * @param $ext string, extension name; use 'civicrm' for core
319 * @param $file string, file path -- relative to the extension base dir
320 * @param $weight int, relative weight within a given region
321 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
322 * @return CRM_Core_Resources
323 */
324 public function addStyleFile($ext, $file, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
325 return $this->addStyleUrl($this->getUrl($ext, $file, TRUE), $weight, $region);
326 }
327
328 /**
329 * Add a CSS file to the current page using <LINK HREF>.
330 *
331 * @param $url string
332 * @param $weight int, relative weight within a given region
333 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
334 * @return CRM_Core_Resources
335 */
336 public function addStyleUrl($url, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
337 CRM_Core_Region::instance($region)->add(array(
338 'name' => $url,
339 'type' => 'styleUrl',
340 'styleUrl' => $url,
341 'weight' => $weight,
342 'region' => $region,
343 ));
344 return $this;
345 }
346
347 /**
348 * Add a CSS content to the current page using <STYLE>.
349 *
350 * @param $code string, CSS source code
351 * @param $weight int, relative weight within a given region
352 * @param $region string, location within the file; 'html-header', 'page-header', 'page-footer'
353 * @return CRM_Core_Resources
354 */
355 public function addStyle($code, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
356 CRM_Core_Region::instance($region)->add(array(
357 // 'name' => automatic
358 'type' => 'style',
359 'style' => $code,
360 'weight' => $weight,
361 'region' => $region,
362 ));
363 return $this;
364 }
365
366 /**
367 * Determine file path of a resource provided by an extension
368 *
369 * @param $ext string, extension name; use 'civicrm' for core
370 * @param $file string, file path -- relative to the extension base dir
371 *
372 * @return (string|bool), full file path or FALSE if not found
373 */
374 public function getPath($ext, $file) {
375 // TODO consider caching results
376 $path = $this->extMapper->keyToBasePath($ext) . '/' . $file;
377 if (is_file($path)) {
378 return $path;
379 }
380 return FALSE;
381 }
382
383 /**
384 * Determine public URL of a resource provided by an extension
385 *
386 * @param $ext string, extension name; use 'civicrm' for core
387 * @param $file string, file path -- relative to the extension base dir
388 * @return string, URL
389 */
390 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
391 if ($file === NULL) {
392 $file = '';
393 }
394 if ($addCacheCode) {
395 $file .= '?r=' . $this->getCacheCode();
396 }
397 // TODO consider caching results
398 return $this->extMapper->keyToUrl($ext) . '/' . $file;
399 }
400
401 public function getCacheCode() {
402 return $this->cacheCode;
403 }
404
405 public function setCacheCode($value) {
406 $this->cacheCode = $value;
407 if ($this->cacheCodeKey) {
408 CRM_Core_BAO_Setting::setItem($value, CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, $this->cacheCodeKey);
409 }
410 }
411
412 public function resetCacheCode() {
413 $this->setCacheCode(CRM_Utils_String::createRandom(5, CRM_Utils_String::ALPHANUMERIC));
414 }
415
416 /**
417 * This adds CiviCRM's standard css and js to the specified region of the document.
418 * It will only run once.
419 *
420 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
421 * (like addCoreResources/addCoreStyles).
422 *
423 * @return CRM_Core_Resources
424 * @access public
425 */
426 public function addCoreResources($region = 'html-header') {
427 if (!isset($this->addedCoreResources[$region])) {
428 $this->addedCoreResources[$region] = TRUE;
429 $config = CRM_Core_Config::singleton();
430
a43b1583 431 // Add resources from coreResourceList
dbe0bbc6 432 $files = $this->coreResourceList();
6a488035 433 $jsWeight = -9999;
a43b1583
CW
434 foreach ($files as $file) {
435 if (substr($file, -2) == 'js') {
74227f77
CW
436 // Don't bother looking for ts() calls in packages, there aren't any
437 $translate = (substr($file, 0, 9) != 'packages/');
438 $this->addScriptFile('civicrm', $file, $jsWeight++, $region, $translate);
6a488035 439 }
a43b1583 440 else {
6a488035
TO
441 $this->addStyleFile('civicrm', $file, -100, $region);
442 }
443 }
444
5ec182d9 445 // Initialize CRM.url and CRM.formatMoney
8053ab8a 446 $url = CRM_Utils_System::url('civicrm/example', 'placeholder', FALSE, NULL, FALSE);
5ec182d9 447 $js = "CRM.url('init', '$url');\n";
f0c40b90 448 $js .= "CRM.formatMoney('init', " . json_encode(CRM_Utils_Money::format(1234.56)) . ");";
8053ab8a
CW
449 $this->addScript($js, $jsWeight++, $region);
450
d759bd10
CW
451 // Add global settings
452 $settings = array(
4a7fe6f4
CW
453 'userFramework' => $config->userFramework,
454 'resourceBase' => $config->resourceBase,
1ec934ce 455 'lcMessages' => $config->lcMessages,
d759bd10
CW
456 );
457 $this->addSetting(array('config' => $settings));
458
6a488035 459 // Give control of jQuery back to the CMS - this loads last
c2777586 460 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
6a488035
TO
461
462 $this->addCoreStyles($region);
463 }
464 return $this;
465 }
466
467 /**
468 * This will add CiviCRM's standard CSS
469 *
470 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
471 * (like addCoreResources/addCoreStyles).
472 *
473 * @param string $region
474 * @return CRM_Core_Resources
475 */
476 public function addCoreStyles($region = 'html-header') {
477 if (!isset($this->addedCoreStyles[$region])) {
478 $this->addedCoreStyles[$region] = TRUE;
479
480 // Load custom or core css
481 $config = CRM_Core_Config::singleton();
482 if (!empty($config->customCSSURL)) {
57018a3e 483 $this->addStyleUrl($config->customCSSURL, 99, $region);
6a488035 484 }
14f20d22 485 if (!CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'disable_core_css')) {
6a488035 486 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
6a488035
TO
487 }
488 }
489 return $this;
490 }
491
627668e8
CW
492 /**
493 * Flushes cached translated strings
494 */
495 public function flushStrings() {
496 $this->cache->flush();
497 }
498
6a488035
TO
499 /**
500 * Translate strings in a javascript file
501 *
502 * @param $ext string, extension name
503 * @param $file string, file path
504 * @return void
505 */
506 private function translateScript($ext, $file) {
507 // For each extension, maintain one cache record which
508 // includes parsed (translatable) strings for all its JS files.
509 $stringsByFile = $this->cache->get($ext); // array($file => array(...strings...))
510 if (!$stringsByFile) {
511 $stringsByFile = array();
512 }
513 if (!isset($stringsByFile[$file])) {
514 $filePath = $this->getPath($ext, $file);
515 if ($filePath && is_readable($filePath)) {
516 $stringsByFile[$file] = CRM_Utils_JS::parseStrings(file_get_contents($filePath));
517 } else {
518 $stringsByFile[$file] = array();
519 }
520 $this->cache->set($ext, $stringsByFile);
521 }
522 $this->addString($stringsByFile[$file]);
523 }
524
525 /**
a43b1583 526 * List of core resources we add to every CiviCRM page
6a488035 527 *
a43b1583 528 * @return array
6a488035 529 */
dbe0bbc6
CW
530 public function coreResourceList() {
531 $config = CRM_Core_Config::singleton();
532 // Use minified files for production, uncompressed in debug mode
533 $min = $config->debug ? '' : '.min';
a43b1583 534
a0c8b50e
CW
535 $items = array(
536 "packages/jquery/jquery-1.10.2.min.js",
537 "packages/jquery/jquery-migrate-1.2.1.js",
dbe0bbc6
CW
538 "packages/jquery/jquery-ui/js/jquery-ui-1.10.3.custom$min.js",
539 "packages/jquery/jquery-ui/css/black-tie/jquery-ui-1.10.3.custom$min.css",
a0c8b50e
CW
540
541 "packages/jquery/plugins/jquery.autocomplete.js",
542 "packages/jquery/css/jquery.autocomplete.css",
a43b1583 543
fb9daa75 544 "packages/jquery/plugins/jquery.menu$min.js",
a0c8b50e 545 "packages/jquery/css/menu.css",
a43b1583 546
a0c8b50e 547 "packages/jquery/plugins/jquery.tableHeader.js",
a43b1583 548
a0c8b50e 549 "packages/jquery/plugins/jquery.textarearesizer.js",
a43b1583 550
a0c8b50e 551 "packages/jquery/plugins/jquery.form$min.js",
a43b1583 552
8ec6dd48 553 "packages/jquery/plugins/jquery.tokeninput$min.js",
a0c8b50e 554 "packages/jquery/css/token-input-facebook.css",
a43b1583 555
a0c8b50e 556 "packages/jquery/plugins/jquery.timeentry$min.js",
a43b1583 557
a0c8b50e
CW
558 "packages/jquery/plugins/DataTables/media/css/demo_table_jui.css",
559 "packages/jquery/plugins/DataTables/media/js/jquery.dataTables$min.js",
a43b1583 560
8ec6dd48 561 "packages/jquery/plugins/jquery.FormNavigate$min.js",
a43b1583 562
a0c8b50e
CW
563 "packages/jquery/plugins/jquery.validate$min.js",
564 "packages/jquery/plugins/jquery.ui.datepicker.validation.pack.js",
a43b1583 565
8ec6dd48 566 "packages/jquery/plugins/jquery.jeditable$min.js",
a43b1583 567
d3975b81 568 "packages/jquery/plugins/jquery.blockUI$min.js",
a43b1583 569
a0c8b50e 570 "packages/jquery/plugins/jquery.notify$min.js",
a43b1583 571
a0c8b50e
CW
572 "js/rest.js",
573 "js/Common.js",
a43b1583 574
a0c8b50e
CW
575 "js/jquery/jquery.crmeditable.js",
576 "js/jquery/jquery.crmasmselect.js",
a43b1583 577 );
dbe0bbc6
CW
578
579 // Add localized jQuery UI files
580 if ($config->lcMessages && $config->lcMessages != 'en_US') {
581 // Search for i18n file in order of specificity (try fr-CA, then fr)
582 list($lang) = explode('_', $config->lcMessages);
583 $path = "packages/jquery/jquery-ui/development-bundle/ui/" . ($min ? 'minified/' : '') . "i18n";
584 foreach (array(str_replace('_', '-', $config->lcMessages), $lang) as $language) {
585 $localizationFile = "$path/jquery.ui.datepicker-{$language}{$min}.js";
586 if ($this->getPath('civicrm', $localizationFile)) {
587 $items[] = $localizationFile;
588 break;
589 }
590 }
591 }
6a488035
TO
592 return $items;
593 }
594}