| 1 | <?php |
| 2 | /* |
| 3 | +--------------------------------------------------------------------+ |
| 4 | | CiviCRM version 5 | |
| 5 | +--------------------------------------------------------------------+ |
| 6 | | Copyright CiviCRM LLC (c) 2004-2019 | |
| 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 | use Civi\Core\Event\GenericHookEvent; |
| 28 | |
| 29 | /** |
| 30 | * This class facilitates the loading of resources |
| 31 | * such as JavaScript files and CSS files. |
| 32 | * |
| 33 | * Any URLs generated for resources may include a 'cache-code'. By resetting the |
| 34 | * cache-code, one may force clients to re-download resource files (regardless of |
| 35 | * any HTTP caching rules). |
| 36 | * |
| 37 | * TODO: This is currently a thin wrapper over CRM_Core_Region. We |
| 38 | * should incorporte services for aggregation, minimization, etc. |
| 39 | * |
| 40 | * @package CRM |
| 41 | * @copyright CiviCRM LLC (c) 2004-2019 |
| 42 | * $Id$ |
| 43 | * |
| 44 | */ |
| 45 | class CRM_Core_Resources { |
| 46 | const DEFAULT_WEIGHT = 0; |
| 47 | const DEFAULT_REGION = 'page-footer'; |
| 48 | |
| 49 | /** |
| 50 | * We don't have a container or dependency-injection, so use singleton instead |
| 51 | * |
| 52 | * @var object |
| 53 | */ |
| 54 | private static $_singleton = NULL; |
| 55 | |
| 56 | /** |
| 57 | * @var CRM_Extension_Mapper |
| 58 | */ |
| 59 | private $extMapper = NULL; |
| 60 | |
| 61 | /** |
| 62 | * @var CRM_Core_Resources_Strings |
| 63 | */ |
| 64 | private $strings = NULL; |
| 65 | |
| 66 | /** |
| 67 | * Settings in free-form data tree. |
| 68 | * |
| 69 | * @var array |
| 70 | */ |
| 71 | protected $settings = []; |
| 72 | protected $addedSettings = FALSE; |
| 73 | |
| 74 | /** |
| 75 | * Setting factories. |
| 76 | * |
| 77 | * @var callable[] |
| 78 | */ |
| 79 | protected $settingsFactories = []; |
| 80 | |
| 81 | /** |
| 82 | * Added core resources. |
| 83 | * |
| 84 | * Format is ($regionName => bool). |
| 85 | * |
| 86 | * @var array |
| 87 | */ |
| 88 | protected $addedCoreResources = []; |
| 89 | |
| 90 | /** |
| 91 | * Added core styles. |
| 92 | * |
| 93 | * Format is ($regionName => bool). |
| 94 | * |
| 95 | * @var array |
| 96 | */ |
| 97 | protected $addedCoreStyles = []; |
| 98 | |
| 99 | /** |
| 100 | * A value to append to JS/CSS URLs to coerce cache resets. |
| 101 | * |
| 102 | * @var string |
| 103 | */ |
| 104 | protected $cacheCode = NULL; |
| 105 | |
| 106 | /** |
| 107 | * The name of a setting which persistently stores the cacheCode. |
| 108 | * |
| 109 | * @var string |
| 110 | */ |
| 111 | protected $cacheCodeKey = NULL; |
| 112 | |
| 113 | /** |
| 114 | * Are ajax popup screens enabled. |
| 115 | * |
| 116 | * @var bool |
| 117 | */ |
| 118 | public $ajaxPopupsEnabled; |
| 119 | |
| 120 | /** |
| 121 | * @var \Civi\Core\Paths |
| 122 | */ |
| 123 | protected $paths; |
| 124 | |
| 125 | /** |
| 126 | * Get or set the single instance of CRM_Core_Resources. |
| 127 | * |
| 128 | * @param CRM_Core_Resources $instance |
| 129 | * New copy of the manager. |
| 130 | * |
| 131 | * @return CRM_Core_Resources |
| 132 | */ |
| 133 | public static function singleton(CRM_Core_Resources $instance = NULL) { |
| 134 | if ($instance !== NULL) { |
| 135 | self::$_singleton = $instance; |
| 136 | } |
| 137 | if (self::$_singleton === NULL) { |
| 138 | self::$_singleton = Civi::service('resources'); |
| 139 | } |
| 140 | return self::$_singleton; |
| 141 | } |
| 142 | |
| 143 | /** |
| 144 | * Construct a resource manager. |
| 145 | * |
| 146 | * @param CRM_Extension_Mapper $extMapper |
| 147 | * Map extension names to their base path or URLs. |
| 148 | * @param CRM_Utils_Cache_Interface $cache |
| 149 | * JS-localization cache. |
| 150 | * @param string|null $cacheCodeKey Random code to append to resource URLs; changing the code forces clients to reload resources |
| 151 | */ |
| 152 | public function __construct($extMapper, $cache, $cacheCodeKey = NULL) { |
| 153 | $this->extMapper = $extMapper; |
| 154 | $this->strings = new CRM_Core_Resources_Strings($cache); |
| 155 | $this->cacheCodeKey = $cacheCodeKey; |
| 156 | if ($cacheCodeKey !== NULL) { |
| 157 | $this->cacheCode = Civi::settings()->get($cacheCodeKey); |
| 158 | } |
| 159 | if (!$this->cacheCode) { |
| 160 | $this->resetCacheCode(); |
| 161 | } |
| 162 | $this->ajaxPopupsEnabled = (bool) Civi::settings()->get('ajaxPopupsEnabled'); |
| 163 | $this->paths = Civi::paths(); |
| 164 | } |
| 165 | |
| 166 | /** |
| 167 | * Export permission data to the client to enable smarter GUIs. |
| 168 | * |
| 169 | * Note: Application security stems from the server's enforcement |
| 170 | * of the security logic (e.g. in the API permissions). There's no way |
| 171 | * the client can use this info to make the app more secure; however, |
| 172 | * it can produce a better-tuned (non-broken) UI. |
| 173 | * |
| 174 | * @param array $permNames |
| 175 | * List of permission names to check/export. |
| 176 | * @return CRM_Core_Resources |
| 177 | */ |
| 178 | public function addPermissions($permNames) { |
| 179 | $permNames = (array) $permNames; |
| 180 | $perms = []; |
| 181 | foreach ($permNames as $permName) { |
| 182 | $perms[$permName] = CRM_Core_Permission::check($permName); |
| 183 | } |
| 184 | return $this->addSetting([ |
| 185 | 'permissions' => $perms, |
| 186 | ]); |
| 187 | } |
| 188 | |
| 189 | /** |
| 190 | * Add a JavaScript file to the current page using <SCRIPT SRC>. |
| 191 | * |
| 192 | * @param string $ext |
| 193 | * extension name; use 'civicrm' for core. |
| 194 | * @param string $file |
| 195 | * file path -- relative to the extension base dir. |
| 196 | * @param int $weight |
| 197 | * relative weight within a given region. |
| 198 | * @param string $region |
| 199 | * location within the file; 'html-header', 'page-header', 'page-footer'. |
| 200 | * @param bool|string $translate |
| 201 | * Whether to load translated strings for this file. Use one of: |
| 202 | * - FALSE: Do not load translated strings. |
| 203 | * - TRUE: Load translated strings. Use the $ext's default domain. |
| 204 | * - string: Load translated strings. Use a specific domain. |
| 205 | * |
| 206 | * @return CRM_Core_Resources |
| 207 | * |
| 208 | * @throws \CRM_Core_Exception |
| 209 | */ |
| 210 | public function addScriptFile($ext, $file, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION, $translate = TRUE) { |
| 211 | if ($translate) { |
| 212 | $domain = ($translate === TRUE) ? $ext : $translate; |
| 213 | $this->addString($this->strings->get($domain, $this->getPath($ext, $file), 'text/javascript'), $domain); |
| 214 | } |
| 215 | $url = $this->getUrl($ext, $this->filterMinify($ext, $file), TRUE); |
| 216 | return $this->addScriptUrl($url, $weight, $region); |
| 217 | } |
| 218 | |
| 219 | /** |
| 220 | * Add a JavaScript file to the current page using <SCRIPT SRC>. |
| 221 | * |
| 222 | * @param string $url |
| 223 | * @param int $weight |
| 224 | * relative weight within a given region. |
| 225 | * @param string $region |
| 226 | * location within the file; 'html-header', 'page-header', 'page-footer'. |
| 227 | * @return CRM_Core_Resources |
| 228 | */ |
| 229 | public function addScriptUrl($url, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) { |
| 230 | CRM_Core_Region::instance($region)->add([ |
| 231 | 'name' => $url, |
| 232 | 'type' => 'scriptUrl', |
| 233 | 'scriptUrl' => $url, |
| 234 | 'weight' => $weight, |
| 235 | 'region' => $region, |
| 236 | ]); |
| 237 | return $this; |
| 238 | } |
| 239 | |
| 240 | /** |
| 241 | * Add a JavaScript file to the current page using <SCRIPT SRC>. |
| 242 | * |
| 243 | * @param string $code |
| 244 | * JavaScript source code. |
| 245 | * @param int $weight |
| 246 | * relative weight within a given region. |
| 247 | * @param string $region |
| 248 | * location within the file; 'html-header', 'page-header', 'page-footer'. |
| 249 | * @return CRM_Core_Resources |
| 250 | */ |
| 251 | public function addScript($code, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) { |
| 252 | CRM_Core_Region::instance($region)->add([ |
| 253 | // 'name' => automatic |
| 254 | 'type' => 'script', |
| 255 | 'script' => $code, |
| 256 | 'weight' => $weight, |
| 257 | 'region' => $region, |
| 258 | ]); |
| 259 | return $this; |
| 260 | } |
| 261 | |
| 262 | /** |
| 263 | * Add JavaScript variables to CRM.vars |
| 264 | * |
| 265 | * Example: |
| 266 | * From the server: |
| 267 | * CRM_Core_Resources::singleton()->addVars('myNamespace', array('foo' => 'bar')); |
| 268 | * Access var from javascript: |
| 269 | * CRM.vars.myNamespace.foo // "bar" |
| 270 | * |
| 271 | * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Javascript+Reference |
| 272 | * |
| 273 | * @param string $nameSpace |
| 274 | * Usually the name of your extension. |
| 275 | * @param array $vars |
| 276 | * @return CRM_Core_Resources |
| 277 | */ |
| 278 | public function addVars($nameSpace, $vars) { |
| 279 | $existing = CRM_Utils_Array::value($nameSpace, CRM_Utils_Array::value('vars', $this->settings), []); |
| 280 | $vars = $this->mergeSettings($existing, $vars); |
| 281 | $this->addSetting(['vars' => [$nameSpace => $vars]]); |
| 282 | return $this; |
| 283 | } |
| 284 | |
| 285 | /** |
| 286 | * Add JavaScript variables to the root of the CRM object. |
| 287 | * This function is usually reserved for low-level system use. |
| 288 | * Extensions and components should generally use addVars instead. |
| 289 | * |
| 290 | * @param array $settings |
| 291 | * @return CRM_Core_Resources |
| 292 | */ |
| 293 | public function addSetting($settings) { |
| 294 | $this->settings = $this->mergeSettings($this->settings, $settings); |
| 295 | if (!$this->addedSettings) { |
| 296 | $region = self::isAjaxMode() ? 'ajax-snippet' : 'html-header'; |
| 297 | $resources = $this; |
| 298 | CRM_Core_Region::instance($region)->add([ |
| 299 | 'callback' => function (&$snippet, &$html) use ($resources) { |
| 300 | $html .= "\n" . $resources->renderSetting(); |
| 301 | }, |
| 302 | 'weight' => -100000, |
| 303 | ]); |
| 304 | $this->addedSettings = TRUE; |
| 305 | } |
| 306 | return $this; |
| 307 | } |
| 308 | |
| 309 | /** |
| 310 | * Add JavaScript variables to the global CRM object via a callback function. |
| 311 | * |
| 312 | * @param callable $callable |
| 313 | * @return CRM_Core_Resources |
| 314 | */ |
| 315 | public function addSettingsFactory($callable) { |
| 316 | // Make sure our callback has been registered |
| 317 | $this->addSetting([]); |
| 318 | $this->settingsFactories[] = $callable; |
| 319 | return $this; |
| 320 | } |
| 321 | |
| 322 | /** |
| 323 | * Helper fn for addSettingsFactory. |
| 324 | */ |
| 325 | public function getSettings() { |
| 326 | $result = $this->settings; |
| 327 | foreach ($this->settingsFactories as $callable) { |
| 328 | $result = $this->mergeSettings($result, $callable()); |
| 329 | } |
| 330 | CRM_Utils_Hook::alterResourceSettings($result); |
| 331 | return $result; |
| 332 | } |
| 333 | |
| 334 | /** |
| 335 | * @param array $settings |
| 336 | * @param array $additions |
| 337 | * @return array |
| 338 | * combination of $settings and $additions |
| 339 | */ |
| 340 | protected function mergeSettings($settings, $additions) { |
| 341 | foreach ($additions as $k => $v) { |
| 342 | if (isset($settings[$k]) && is_array($settings[$k]) && is_array($v)) { |
| 343 | $v += $settings[$k]; |
| 344 | } |
| 345 | $settings[$k] = $v; |
| 346 | } |
| 347 | return $settings; |
| 348 | } |
| 349 | |
| 350 | /** |
| 351 | * Helper fn for addSetting. |
| 352 | * Render JavaScript variables for the global CRM object. |
| 353 | * |
| 354 | * @return string |
| 355 | */ |
| 356 | public function renderSetting() { |
| 357 | // On a standard page request we construct the CRM object from scratch |
| 358 | if (!self::isAjaxMode()) { |
| 359 | $js = 'var CRM = ' . json_encode($this->getSettings()) . ';'; |
| 360 | } |
| 361 | // For an ajax request we append to it |
| 362 | else { |
| 363 | $js = 'CRM.$.extend(true, CRM, ' . json_encode($this->getSettings()) . ');'; |
| 364 | } |
| 365 | return sprintf("<script type=\"text/javascript\">\n%s\n</script>\n", $js); |
| 366 | } |
| 367 | |
| 368 | /** |
| 369 | * Add translated string to the js CRM object. |
| 370 | * It can then be retrived from the client-side ts() function |
| 371 | * Variable substitutions can happen from client-side |
| 372 | * |
| 373 | * Note: this function rarely needs to be called directly and is mostly for internal use. |
| 374 | * See CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files |
| 375 | * |
| 376 | * Simple example: |
| 377 | * // From php: |
| 378 | * CRM_Core_Resources::singleton()->addString('Hello'); |
| 379 | * // The string is now available to javascript code i.e. |
| 380 | * ts('Hello'); |
| 381 | * |
| 382 | * Example with client-side substitutions: |
| 383 | * // From php: |
| 384 | * CRM_Core_Resources::singleton()->addString('Your %1 has been %2'); |
| 385 | * // ts() in javascript works the same as in php, for example: |
| 386 | * ts('Your %1 has been %2', {1: objectName, 2: actionTaken}); |
| 387 | * |
| 388 | * NOTE: This function does not work with server-side substitutions |
| 389 | * (as this might result in collisions and unwanted variable injections) |
| 390 | * Instead, use code like: |
| 391 | * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs))))); |
| 392 | * And from javascript access it at CRM.myNamespace.myString |
| 393 | * |
| 394 | * @param string|array $text |
| 395 | * @param string|null $domain |
| 396 | * @return CRM_Core_Resources |
| 397 | */ |
| 398 | public function addString($text, $domain = 'civicrm') { |
| 399 | foreach ((array) $text as $str) { |
| 400 | $translated = ts($str, [ |
| 401 | 'domain' => ($domain == 'civicrm') ? NULL : [$domain, NULL], |
| 402 | 'raw' => TRUE, |
| 403 | ]); |
| 404 | |
| 405 | // We only need to push this string to client if the translation |
| 406 | // is actually different from the original |
| 407 | if ($translated != $str) { |
| 408 | $bucket = $domain == 'civicrm' ? 'strings' : 'strings::' . $domain; |
| 409 | $this->addSetting([ |
| 410 | $bucket => [$str => $translated], |
| 411 | ]); |
| 412 | } |
| 413 | } |
| 414 | return $this; |
| 415 | } |
| 416 | |
| 417 | /** |
| 418 | * Add a CSS file to the current page using <LINK HREF>. |
| 419 | * |
| 420 | * @param string $ext |
| 421 | * extension name; use 'civicrm' for core. |
| 422 | * @param string $file |
| 423 | * file path -- relative to the extension base dir. |
| 424 | * @param int $weight |
| 425 | * relative weight within a given region. |
| 426 | * @param string $region |
| 427 | * location within the file; 'html-header', 'page-header', 'page-footer'. |
| 428 | * @return CRM_Core_Resources |
| 429 | */ |
| 430 | public function addStyleFile($ext, $file, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) { |
| 431 | /** @var Civi\Core\Themes $theme */ |
| 432 | $theme = Civi::service('themes'); |
| 433 | foreach ($theme->resolveUrls($theme->getActiveThemeKey(), $ext, $file) as $url) { |
| 434 | $this->addStyleUrl($url, $weight, $region); |
| 435 | } |
| 436 | return $this; |
| 437 | } |
| 438 | |
| 439 | /** |
| 440 | * Add a CSS file to the current page using <LINK HREF>. |
| 441 | * |
| 442 | * @param string $url |
| 443 | * @param int $weight |
| 444 | * relative weight within a given region. |
| 445 | * @param string $region |
| 446 | * location within the file; 'html-header', 'page-header', 'page-footer'. |
| 447 | * @return CRM_Core_Resources |
| 448 | */ |
| 449 | public function addStyleUrl($url, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) { |
| 450 | CRM_Core_Region::instance($region)->add([ |
| 451 | 'name' => $url, |
| 452 | 'type' => 'styleUrl', |
| 453 | 'styleUrl' => $url, |
| 454 | 'weight' => $weight, |
| 455 | 'region' => $region, |
| 456 | ]); |
| 457 | return $this; |
| 458 | } |
| 459 | |
| 460 | /** |
| 461 | * Add a CSS content to the current page using <STYLE>. |
| 462 | * |
| 463 | * @param string $code |
| 464 | * CSS source code. |
| 465 | * @param int $weight |
| 466 | * relative weight within a given region. |
| 467 | * @param string $region |
| 468 | * location within the file; 'html-header', 'page-header', 'page-footer'. |
| 469 | * @return CRM_Core_Resources |
| 470 | */ |
| 471 | public function addStyle($code, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) { |
| 472 | CRM_Core_Region::instance($region)->add([ |
| 473 | // 'name' => automatic |
| 474 | 'type' => 'style', |
| 475 | 'style' => $code, |
| 476 | 'weight' => $weight, |
| 477 | 'region' => $region, |
| 478 | ]); |
| 479 | return $this; |
| 480 | } |
| 481 | |
| 482 | /** |
| 483 | * Determine file path of a resource provided by an extension. |
| 484 | * |
| 485 | * @param string $ext |
| 486 | * extension name; use 'civicrm' for core. |
| 487 | * @param string|null $file |
| 488 | * file path -- relative to the extension base dir. |
| 489 | * |
| 490 | * @return bool|string |
| 491 | * full file path or FALSE if not found |
| 492 | */ |
| 493 | public function getPath($ext, $file = NULL) { |
| 494 | // TODO consider caching results |
| 495 | $base = $this->paths->hasVariable($ext) |
| 496 | ? rtrim($this->paths->getVariable($ext, 'path'), '/') |
| 497 | : $this->extMapper->keyToBasePath($ext); |
| 498 | if ($file === NULL) { |
| 499 | return $base; |
| 500 | } |
| 501 | $path = $base . '/' . $file; |
| 502 | if (is_file($path)) { |
| 503 | return $path; |
| 504 | } |
| 505 | return FALSE; |
| 506 | } |
| 507 | |
| 508 | /** |
| 509 | * Determine public URL of a resource provided by an extension. |
| 510 | * |
| 511 | * @param string $ext |
| 512 | * extension name; use 'civicrm' for core. |
| 513 | * @param string $file |
| 514 | * file path -- relative to the extension base dir. |
| 515 | * @param bool $addCacheCode |
| 516 | * |
| 517 | * @return string, URL |
| 518 | */ |
| 519 | public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) { |
| 520 | if ($file === NULL) { |
| 521 | $file = ''; |
| 522 | } |
| 523 | if ($addCacheCode) { |
| 524 | $file = $this->addCacheCode($file); |
| 525 | } |
| 526 | // TODO consider caching results |
| 527 | $base = $this->paths->hasVariable($ext) |
| 528 | ? $this->paths->getVariable($ext, 'url') |
| 529 | : ($this->extMapper->keyToUrl($ext) . '/'); |
| 530 | return $base . $file; |
| 531 | } |
| 532 | |
| 533 | /** |
| 534 | * Evaluate a glob pattern in the context of a particular extension. |
| 535 | * |
| 536 | * @param string $ext |
| 537 | * Extension name; use 'civicrm' for core. |
| 538 | * @param string|array $patterns |
| 539 | * Glob pattern; e.g. "*.html". |
| 540 | * @param null|int $flags |
| 541 | * See glob(). |
| 542 | * @return array |
| 543 | * List of matching files, relative to the extension base dir. |
| 544 | * @see glob() |
| 545 | */ |
| 546 | public function glob($ext, $patterns, $flags = NULL) { |
| 547 | $path = $this->getPath($ext); |
| 548 | $patterns = (array) $patterns; |
| 549 | $files = []; |
| 550 | foreach ($patterns as $pattern) { |
| 551 | if (preg_match(';^(assetBuilder|ext)://;', $pattern)) { |
| 552 | $files[] = $pattern; |
| 553 | } |
| 554 | if (CRM_Utils_File::isAbsolute($pattern)) { |
| 555 | // Absolute path. |
| 556 | $files = array_merge($files, (array) glob($pattern, $flags)); |
| 557 | } |
| 558 | else { |
| 559 | // Relative path. |
| 560 | $files = array_merge($files, (array) glob("$path/$pattern", $flags)); |
| 561 | } |
| 562 | } |
| 563 | // Deterministic order. |
| 564 | sort($files); |
| 565 | $files = array_unique($files); |
| 566 | return array_map(function ($file) use ($path) { |
| 567 | return CRM_Utils_File::relativize($file, "$path/"); |
| 568 | }, $files); |
| 569 | } |
| 570 | |
| 571 | /** |
| 572 | * @return string |
| 573 | */ |
| 574 | public function getCacheCode() { |
| 575 | return $this->cacheCode; |
| 576 | } |
| 577 | |
| 578 | /** |
| 579 | * @param $value |
| 580 | * @return CRM_Core_Resources |
| 581 | */ |
| 582 | public function setCacheCode($value) { |
| 583 | $this->cacheCode = $value; |
| 584 | if ($this->cacheCodeKey) { |
| 585 | Civi::settings()->set($this->cacheCodeKey, $value); |
| 586 | } |
| 587 | return $this; |
| 588 | } |
| 589 | |
| 590 | /** |
| 591 | * @return CRM_Core_Resources |
| 592 | */ |
| 593 | public function resetCacheCode() { |
| 594 | $this->setCacheCode(CRM_Utils_String::createRandom(5, CRM_Utils_String::ALPHANUMERIC)); |
| 595 | // Also flush cms resource cache if needed |
| 596 | CRM_Core_Config::singleton()->userSystem->clearResourceCache(); |
| 597 | return $this; |
| 598 | } |
| 599 | |
| 600 | /** |
| 601 | * This adds CiviCRM's standard css and js to the specified region of the document. |
| 602 | * It will only run once. |
| 603 | * |
| 604 | * TODO: Separate the functional code (like addStyle/addScript) from the policy code |
| 605 | * (like addCoreResources/addCoreStyles). |
| 606 | * |
| 607 | * @param string $region |
| 608 | * @return CRM_Core_Resources |
| 609 | */ |
| 610 | public function addCoreResources($region = 'html-header') { |
| 611 | if (!isset($this->addedCoreResources[$region]) && !self::isAjaxMode()) { |
| 612 | $this->addedCoreResources[$region] = TRUE; |
| 613 | $config = CRM_Core_Config::singleton(); |
| 614 | |
| 615 | // Add resources from coreResourceList |
| 616 | $jsWeight = -9999; |
| 617 | foreach ($this->coreResourceList($region) as $item) { |
| 618 | if (is_array($item)) { |
| 619 | $this->addSetting($item); |
| 620 | } |
| 621 | elseif (strpos($item, '.css')) { |
| 622 | $this->isFullyFormedUrl($item) ? $this->addStyleUrl($item, -100, $region) : $this->addStyleFile('civicrm', $item, -100, $region); |
| 623 | } |
| 624 | elseif ($this->isFullyFormedUrl($item)) { |
| 625 | $this->addScriptUrl($item, $jsWeight++, $region); |
| 626 | } |
| 627 | else { |
| 628 | // Don't bother looking for ts() calls in packages, there aren't any |
| 629 | $translate = (substr($item, 0, 3) == 'js/'); |
| 630 | $this->addScriptFile('civicrm', $item, $jsWeight++, $region, $translate); |
| 631 | } |
| 632 | } |
| 633 | // Add global settings |
| 634 | $settings = [ |
| 635 | 'config' => [ |
| 636 | 'isFrontend' => $config->userFrameworkFrontend, |
| 637 | ], |
| 638 | ]; |
| 639 | // Disable profile creation if user lacks permission |
| 640 | if (!CRM_Core_Permission::check('edit all contacts') && !CRM_Core_Permission::check('add contacts')) { |
| 641 | $settings['config']['entityRef']['contactCreate'] = FALSE; |
| 642 | } |
| 643 | $this->addSetting($settings); |
| 644 | |
| 645 | // Give control of jQuery and _ back to the CMS - this loads last |
| 646 | $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE); |
| 647 | |
| 648 | $this->addCoreStyles($region); |
| 649 | } |
| 650 | return $this; |
| 651 | } |
| 652 | |
| 653 | /** |
| 654 | * This will add CiviCRM's standard CSS |
| 655 | * |
| 656 | * TODO: Separate the functional code (like addStyle/addScript) from the policy code |
| 657 | * (like addCoreResources/addCoreStyles). |
| 658 | * |
| 659 | * @param string $region |
| 660 | * @return CRM_Core_Resources |
| 661 | */ |
| 662 | public function addCoreStyles($region = 'html-header') { |
| 663 | if (!isset($this->addedCoreStyles[$region])) { |
| 664 | $this->addedCoreStyles[$region] = TRUE; |
| 665 | |
| 666 | // Load custom or core css |
| 667 | $config = CRM_Core_Config::singleton(); |
| 668 | if (!empty($config->customCSSURL)) { |
| 669 | $customCSSURL = $this->addCacheCode($config->customCSSURL); |
| 670 | $this->addStyleUrl($customCSSURL, 99, $region); |
| 671 | } |
| 672 | if (!Civi::settings()->get('disable_core_css')) { |
| 673 | $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region); |
| 674 | } |
| 675 | // crm-i.css added ahead of other styles so it can be overridden by FA. |
| 676 | $this->addStyleFile('civicrm', 'css/crm-i.css', -101, $region); |
| 677 | } |
| 678 | return $this; |
| 679 | } |
| 680 | |
| 681 | /** |
| 682 | * Flushes cached translated strings. |
| 683 | * @return CRM_Core_Resources |
| 684 | */ |
| 685 | public function flushStrings() { |
| 686 | $this->strings->flush(); |
| 687 | return $this; |
| 688 | } |
| 689 | |
| 690 | /** |
| 691 | * @return CRM_Core_Resources_Strings |
| 692 | */ |
| 693 | public function getStrings() { |
| 694 | return $this->strings; |
| 695 | } |
| 696 | |
| 697 | /** |
| 698 | * Create dynamic script for localizing js widgets. |
| 699 | */ |
| 700 | public static function outputLocalizationJS() { |
| 701 | CRM_Core_Page_AJAX::setJsHeaders(); |
| 702 | $config = CRM_Core_Config::singleton(); |
| 703 | $vars = [ |
| 704 | 'moneyFormat' => json_encode(CRM_Utils_Money::format(1234.56)), |
| 705 | 'contactSearch' => json_encode($config->includeEmailInName ? ts('Start typing a name or email...') : ts('Start typing a name...')), |
| 706 | 'otherSearch' => json_encode(ts('Enter search term...')), |
| 707 | 'entityRef' => self::getEntityRefMetadata(), |
| 708 | 'ajaxPopupsEnabled' => self::singleton()->ajaxPopupsEnabled, |
| 709 | 'allowAlertAutodismissal' => (bool) Civi::settings()->get('allow_alert_autodismissal'), |
| 710 | 'resourceCacheCode' => self::singleton()->getCacheCode(), |
| 711 | 'locale' => CRM_Core_I18n::getLocale(), |
| 712 | 'cid' => (int) CRM_Core_Session::getLoggedInContactID(), |
| 713 | ]; |
| 714 | print CRM_Core_Smarty::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars); |
| 715 | CRM_Utils_System::civiExit(); |
| 716 | } |
| 717 | |
| 718 | /** |
| 719 | * List of core resources we add to every CiviCRM page. |
| 720 | * |
| 721 | * Note: non-compressed versions of .min files will be used in debug mode |
| 722 | * |
| 723 | * @param string $region |
| 724 | * @return array |
| 725 | */ |
| 726 | public function coreResourceList($region) { |
| 727 | $config = CRM_Core_Config::singleton(); |
| 728 | |
| 729 | // Scripts needed by everyone, everywhere |
| 730 | // FIXME: This is too long; list needs finer-grained segmentation |
| 731 | $items = [ |
| 732 | "bower_components/jquery/dist/jquery.min.js", |
| 733 | "bower_components/jquery-ui/jquery-ui.min.js", |
| 734 | "bower_components/jquery-ui/themes/smoothness/jquery-ui.min.css", |
| 735 | "bower_components/lodash-compat/lodash.min.js", |
| 736 | "packages/jquery/plugins/jquery.mousewheel.min.js", |
| 737 | "bower_components/select2/select2.min.js", |
| 738 | "bower_components/select2/select2.min.css", |
| 739 | "bower_components/font-awesome/css/font-awesome.min.css", |
| 740 | "packages/jquery/plugins/jquery.form.min.js", |
| 741 | "packages/jquery/plugins/jquery.timeentry.min.js", |
| 742 | "packages/jquery/plugins/jquery.blockUI.min.js", |
| 743 | "bower_components/datatables/media/js/jquery.dataTables.min.js", |
| 744 | "bower_components/datatables/media/css/jquery.dataTables.min.css", |
| 745 | "bower_components/jquery-validation/dist/jquery.validate.min.js", |
| 746 | "packages/jquery/plugins/jquery.ui.datepicker.validation.min.js", |
| 747 | "js/Common.js", |
| 748 | "js/crm.datepicker.js", |
| 749 | "js/crm.ajax.js", |
| 750 | "js/wysiwyg/crm.wysiwyg.js", |
| 751 | ]; |
| 752 | |
| 753 | // Dynamic localization script |
| 754 | $items[] = $this->addCacheCode( |
| 755 | CRM_Utils_System::url('civicrm/ajax/l10n-js/' . CRM_Core_I18n::getLocale(), |
| 756 | ['cid' => CRM_Core_Session::getLoggedInContactID()], FALSE, NULL, FALSE) |
| 757 | ); |
| 758 | |
| 759 | // add wysiwyg editor |
| 760 | $editor = Civi::settings()->get('editor_id'); |
| 761 | if ($editor == "CKEditor") { |
| 762 | CRM_Admin_Page_CKEditorConfig::setConfigDefault(); |
| 763 | $items[] = [ |
| 764 | 'config' => [ |
| 765 | 'wysisygScriptLocation' => Civi::paths()->getUrl("[civicrm.root]/js/wysiwyg/crm.ckeditor.js"), |
| 766 | 'CKEditorCustomConfig' => CRM_Admin_Page_CKEditorConfig::getConfigUrl(), |
| 767 | ], |
| 768 | ]; |
| 769 | } |
| 770 | |
| 771 | // These scripts are only needed by back-office users |
| 772 | if (CRM_Core_Permission::check('access CiviCRM')) { |
| 773 | $items[] = "packages/jquery/plugins/jquery.tableHeader.js"; |
| 774 | $items[] = "packages/jquery/plugins/jquery.notify.min.js"; |
| 775 | } |
| 776 | |
| 777 | $contactID = CRM_Core_Session::getLoggedInContactID(); |
| 778 | |
| 779 | // Menubar |
| 780 | $position = 'none'; |
| 781 | if ( |
| 782 | $contactID && !$config->userFrameworkFrontend |
| 783 | && CRM_Core_Permission::check('access CiviCRM') |
| 784 | && !@constant('CIVICRM_DISABLE_DEFAULT_MENU') |
| 785 | && !CRM_Core_Config::isUpgradeMode() |
| 786 | ) { |
| 787 | $position = Civi::settings()->get('menubar_position') ?: 'over-cms-menu'; |
| 788 | } |
| 789 | if ($position !== 'none') { |
| 790 | $items[] = 'bower_components/smartmenus/dist/jquery.smartmenus.min.js'; |
| 791 | $items[] = 'bower_components/smartmenus/dist/addons/keyboard/jquery.smartmenus.keyboard.min.js'; |
| 792 | $items[] = 'js/crm.menubar.js'; |
| 793 | // @see CRM_Core_Resources::renderMenubarStylesheet |
| 794 | $items[] = Civi::service('asset_builder')->getUrl('crm-menubar.css', [ |
| 795 | 'menubarColor' => Civi::settings()->get('menubar_color'), |
| 796 | 'height' => 40, |
| 797 | 'breakpoint' => 768, |
| 798 | ]); |
| 799 | // Variables for crm.menubar.js |
| 800 | $items[] = [ |
| 801 | 'menubar' => [ |
| 802 | 'position' => $position, |
| 803 | 'qfKey' => CRM_Core_Key::get('CRM_Contact_Controller_Search', TRUE), |
| 804 | 'cacheCode' => CRM_Core_BAO_Navigation::getCacheKey($contactID), |
| 805 | ], |
| 806 | ]; |
| 807 | } |
| 808 | |
| 809 | // JS for multilingual installations |
| 810 | if (!empty($config->languageLimit) && count($config->languageLimit) > 1 && CRM_Core_Permission::check('translate CiviCRM')) { |
| 811 | $items[] = "js/crm.multilingual.js"; |
| 812 | } |
| 813 | |
| 814 | // Enable administrators to edit option lists in a dialog |
| 815 | if (CRM_Core_Permission::check('administer CiviCRM') && $this->ajaxPopupsEnabled) { |
| 816 | $items[] = "js/crm.optionEdit.js"; |
| 817 | } |
| 818 | |
| 819 | $tsLocale = CRM_Core_I18n::getLocale(); |
| 820 | // Add localized jQuery UI files |
| 821 | if ($tsLocale && $tsLocale != 'en_US') { |
| 822 | // Search for i18n file in order of specificity (try fr-CA, then fr) |
| 823 | list($lang) = explode('_', $tsLocale); |
| 824 | $path = "bower_components/jquery-ui/ui/i18n"; |
| 825 | foreach ([str_replace('_', '-', $tsLocale), $lang] as $language) { |
| 826 | $localizationFile = "$path/datepicker-{$language}.js"; |
| 827 | if ($this->getPath('civicrm', $localizationFile)) { |
| 828 | $items[] = $localizationFile; |
| 829 | break; |
| 830 | } |
| 831 | } |
| 832 | } |
| 833 | |
| 834 | // Allow hooks to modify this list |
| 835 | CRM_Utils_Hook::coreResourceList($items, $region); |
| 836 | |
| 837 | return $items; |
| 838 | } |
| 839 | |
| 840 | /** |
| 841 | * @return bool |
| 842 | * is this page request an ajax snippet? |
| 843 | */ |
| 844 | public static function isAjaxMode() { |
| 845 | if (in_array(CRM_Utils_Array::value('snippet', $_REQUEST), [ |
| 846 | CRM_Core_Smarty::PRINT_SNIPPET, |
| 847 | CRM_Core_Smarty::PRINT_NOFORM, |
| 848 | CRM_Core_Smarty::PRINT_JSON, |
| 849 | ]) |
| 850 | ) { |
| 851 | return TRUE; |
| 852 | } |
| 853 | list($arg0, $arg1) = array_pad(explode('/', CRM_Utils_System::getUrlPath()), 2, ''); |
| 854 | return ($arg0 === 'civicrm' && in_array($arg1, ['ajax', 'angularprofiles', 'asset'])); |
| 855 | } |
| 856 | |
| 857 | /** |
| 858 | * @param \Civi\Core\Event\GenericHookEvent $e |
| 859 | * @see \CRM_Utils_Hook::buildAsset() |
| 860 | */ |
| 861 | public static function renderMenubarStylesheet(GenericHookEvent $e) { |
| 862 | if ($e->asset !== 'crm-menubar.css') { |
| 863 | return; |
| 864 | } |
| 865 | $e->mimeType = 'text/css'; |
| 866 | $content = ''; |
| 867 | $config = CRM_Core_Config::singleton(); |
| 868 | $cms = strtolower($config->userFramework); |
| 869 | $cms = $cms === 'drupal' ? 'drupal7' : $cms; |
| 870 | $items = [ |
| 871 | 'bower_components/smartmenus/dist/css/sm-core-css.css', |
| 872 | 'css/crm-menubar.css', |
| 873 | "css/menubar-$cms.css", |
| 874 | ]; |
| 875 | foreach ($items as $item) { |
| 876 | $content .= file_get_contents(self::singleton()->getPath('civicrm', $item)); |
| 877 | } |
| 878 | $params = $e->params; |
| 879 | // "color" is deprecated in favor of the more specific "menubarColor" |
| 880 | $menubarColor = $params['color'] ?? $params['menubarColor']; |
| 881 | $vars = [ |
| 882 | '$resourceBase' => rtrim($config->resourceBase, '/'), |
| 883 | '$menubarHeight' => $params['height'] . 'px', |
| 884 | '$breakMin' => $params['breakpoint'] . 'px', |
| 885 | '$breakMax' => ($params['breakpoint'] - 1) . 'px', |
| 886 | '$menubarColor' => $menubarColor, |
| 887 | '$menuItemColor' => $params['menuItemColor'] ?? 'rgba(' . implode(', ', CRM_Utils_Color::getRgb($menubarColor)) . ", .9)", |
| 888 | '$highlightColor' => $params['highlightColor'] ?? CRM_Utils_Color::getHighlight($menubarColor), |
| 889 | '$textColor' => $params['textColor'] ?? CRM_Utils_Color::getContrast($menubarColor, '#333', '#ddd'), |
| 890 | ]; |
| 891 | $vars['$highlightTextColor'] = $params['highlightTextColor'] ?? CRM_Utils_Color::getContrast($vars['$highlightColor'], '#333', '#ddd'); |
| 892 | $e->content = str_replace(array_keys($vars), array_values($vars), $content); |
| 893 | } |
| 894 | |
| 895 | /** |
| 896 | * Provide a list of available entityRef filters. |
| 897 | * |
| 898 | * @return array |
| 899 | */ |
| 900 | public static function getEntityRefMetadata() { |
| 901 | $data = [ |
| 902 | 'filters' => [], |
| 903 | 'links' => [], |
| 904 | ]; |
| 905 | $config = CRM_Core_Config::singleton(); |
| 906 | |
| 907 | $disabledComponents = []; |
| 908 | $dao = CRM_Core_DAO::executeQuery("SELECT name, namespace FROM civicrm_component"); |
| 909 | while ($dao->fetch()) { |
| 910 | if (!in_array($dao->name, $config->enableComponents)) { |
| 911 | $disabledComponents[$dao->name] = $dao->namespace; |
| 912 | } |
| 913 | } |
| 914 | |
| 915 | foreach (CRM_Core_DAO_AllCoreTables::daoToClass() as $entity => $daoName) { |
| 916 | // Skip DAOs of disabled components |
| 917 | foreach ($disabledComponents as $nameSpace) { |
| 918 | if (strpos($daoName, $nameSpace) === 0) { |
| 919 | continue 2; |
| 920 | } |
| 921 | } |
| 922 | $baoName = str_replace('_DAO_', '_BAO_', $daoName); |
| 923 | if (class_exists($baoName)) { |
| 924 | $filters = $baoName::getEntityRefFilters(); |
| 925 | if ($filters) { |
| 926 | $data['filters'][$entity] = $filters; |
| 927 | } |
| 928 | if (is_callable([$baoName, 'getEntityRefCreateLinks'])) { |
| 929 | $createLinks = $baoName::getEntityRefCreateLinks(); |
| 930 | if ($createLinks) { |
| 931 | $data['links'][$entity] = $createLinks; |
| 932 | } |
| 933 | } |
| 934 | } |
| 935 | } |
| 936 | |
| 937 | CRM_Utils_Hook::entityRefFilters($data['filters'], $data['links']); |
| 938 | |
| 939 | return $data; |
| 940 | } |
| 941 | |
| 942 | /** |
| 943 | * Determine the minified file name. |
| 944 | * |
| 945 | * @param string $ext |
| 946 | * @param string $file |
| 947 | * @return string |
| 948 | * An updated $fileName. If a minified version exists and is supported by |
| 949 | * system policy, the minified version will be returned. Otherwise, the original. |
| 950 | */ |
| 951 | public function filterMinify($ext, $file) { |
| 952 | if (CRM_Core_Config::singleton()->debug && strpos($file, '.min.') !== FALSE) { |
| 953 | $nonMiniFile = str_replace('.min.', '.', $file); |
| 954 | if ($this->getPath($ext, $nonMiniFile)) { |
| 955 | $file = $nonMiniFile; |
| 956 | } |
| 957 | } |
| 958 | return $file; |
| 959 | } |
| 960 | |
| 961 | /** |
| 962 | * @param string $url |
| 963 | * @return string |
| 964 | */ |
| 965 | public function addCacheCode($url) { |
| 966 | $hasQuery = strpos($url, '?') !== FALSE; |
| 967 | $operator = $hasQuery ? '&' : '?'; |
| 968 | |
| 969 | return $url . $operator . 'r=' . $this->cacheCode; |
| 970 | } |
| 971 | |
| 972 | /** |
| 973 | * Checks if the given URL is fully-formed |
| 974 | * |
| 975 | * @param string $url |
| 976 | * |
| 977 | * @return bool |
| 978 | */ |
| 979 | public static function isFullyFormedUrl($url) { |
| 980 | return (substr($url, 0, 4) === 'http') || (substr($url, 0, 1) === '/'); |
| 981 | } |
| 982 | |
| 983 | } |