3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
11 use Civi\Core\Event\GenericHookEvent
;
14 * This class facilitates the loading of resources
15 * such as JavaScript files and CSS files.
17 * Any URLs generated for resources may include a 'cache-code'. By resetting the
18 * cache-code, one may force clients to re-download resource files (regardless of
19 * any HTTP caching rules).
21 * TODO: This is currently a thin wrapper over CRM_Core_Region. We
22 * should incorporte services for aggregation, minimization, etc.
25 * @copyright CiviCRM LLC https://civicrm.org/licensing
27 class CRM_Core_Resources
{
28 const DEFAULT_WEIGHT
= 0;
29 const DEFAULT_REGION
= 'page-footer';
32 * We don't have a container or dependency-injection, so use singleton instead
36 private static $_singleton = NULL;
39 * @var CRM_Extension_Mapper
41 private $extMapper = NULL;
44 * @var CRM_Core_Resources_Strings
46 private $strings = NULL;
49 * Added core resources.
51 * Format is ($regionName => bool).
55 protected $addedCoreResources = [];
60 * Format is ($regionName => bool).
64 protected $addedCoreStyles = [];
69 * Format is ($regionName => bool).
73 protected $addedSettings = [];
76 * A value to append to JS/CSS URLs to coerce cache resets.
80 protected $cacheCode = NULL;
83 * The name of a setting which persistently stores the cacheCode.
87 protected $cacheCodeKey = NULL;
90 * Are ajax popup screens enabled.
94 public $ajaxPopupsEnabled;
97 * @var \Civi\Core\Paths
102 * Get or set the single instance of CRM_Core_Resources.
104 * @param CRM_Core_Resources $instance
105 * New copy of the manager.
107 * @return CRM_Core_Resources
109 public static function singleton(CRM_Core_Resources
$instance = NULL) {
110 if ($instance !== NULL) {
111 self
::$_singleton = $instance;
113 if (self
::$_singleton === NULL) {
114 self
::$_singleton = Civi
::service('resources');
116 return self
::$_singleton;
120 * Construct a resource manager.
122 * @param CRM_Extension_Mapper $extMapper
123 * Map extension names to their base path or URLs.
124 * @param CRM_Core_Resources_Strings $strings
125 * JS-localization cache.
126 * @param string|null $cacheCodeKey Random code to append to resource URLs; changing the code forces clients to reload resources
128 public function __construct($extMapper, $strings, $cacheCodeKey = NULL) {
129 $this->extMapper
= $extMapper;
130 $this->strings
= $strings;
131 $this->cacheCodeKey
= $cacheCodeKey;
132 if ($cacheCodeKey !== NULL) {
133 $this->cacheCode
= Civi
::settings()->get($cacheCodeKey);
135 if (!$this->cacheCode
) {
136 $this->resetCacheCode();
138 $this->ajaxPopupsEnabled
= (bool) Civi
::settings()->get('ajaxPopupsEnabled');
139 $this->paths
= Civi
::paths();
143 * Export permission data to the client to enable smarter GUIs.
145 * Note: Application security stems from the server's enforcement
146 * of the security logic (e.g. in the API permissions). There's no way
147 * the client can use this info to make the app more secure; however,
148 * it can produce a better-tuned (non-broken) UI.
150 * @param array $permNames
151 * List of permission names to check/export.
152 * @return CRM_Core_Resources
154 public function addPermissions($permNames) {
155 $permNames = (array) $permNames;
157 foreach ($permNames as $permName) {
158 $perms[$permName] = CRM_Core_Permission
::check($permName);
160 return $this->addSetting([
161 'permissions' => $perms,
166 * Add a JavaScript file to the current page using <SCRIPT SRC>.
169 * extension name; use 'civicrm' for core.
170 * @param string $file
171 * file path -- relative to the extension base dir.
173 * relative weight within a given region.
174 * @param string $region
175 * location within the file; 'html-header', 'page-header', 'page-footer'.
176 * @param bool|string $translate
177 * Whether to load translated strings for this file. Use one of:
178 * - FALSE: Do not load translated strings.
179 * - TRUE: Load translated strings. Use the $ext's default domain.
180 * - string: Load translated strings. Use a specific domain.
182 * @return CRM_Core_Resources
184 * @throws \CRM_Core_Exception
186 public function addScriptFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
, $translate = TRUE) {
188 $domain = ($translate === TRUE) ?
$ext : $translate;
189 $this->addString($this->strings
->get($domain, $this->getPath($ext, $file), 'text/javascript'), $domain);
191 $url = $this->getUrl($ext, $this->filterMinify($ext, $file), TRUE);
192 return $this->addScriptUrl($url, $weight, $region);
196 * Add a JavaScript file to the current page using <SCRIPT SRC>.
200 * relative weight within a given region.
201 * @param string $region
202 * location within the file; 'html-header', 'page-header', 'page-footer'.
203 * @return CRM_Core_Resources
205 public function addScriptUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
206 CRM_Core_Region
::instance($region)->add(['scriptUrl' => $url, 'weight' => $weight]);
211 * Add a JavaScript file to the current page using <SCRIPT SRC>.
213 * @param string $code
214 * JavaScript source code.
216 * relative weight within a given region.
217 * @param string $region
218 * location within the file; 'html-header', 'page-header', 'page-footer'.
219 * @return CRM_Core_Resources
221 public function addScript($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
222 CRM_Core_Region
::instance($region)->add(['script' => $code, 'weight' => $weight]);
227 * Add JavaScript variables to CRM.vars
231 * CRM_Core_Resources::singleton()->addVars('myNamespace', array('foo' => 'bar'));
232 * Access var from javascript:
233 * CRM.vars.myNamespace.foo // "bar"
235 * @see https://docs.civicrm.org/dev/en/latest/standards/javascript/
237 * @param string $nameSpace
238 * Usually the name of your extension.
240 * @param string $region
241 * The region to add settings to (eg. for payment processors usually billing-block)
243 * @return CRM_Core_Resources
245 public function addVars($nameSpace, $vars, $region = NULL) {
246 $s = &$this->findCreateSettingSnippet($region);
247 $s['settings']['vars'][$nameSpace] = $this->mergeSettings(
248 $s['settings']['vars'][$nameSpace] ??
[],
255 * Add JavaScript variables to the root of the CRM object.
256 * This function is usually reserved for low-level system use.
257 * Extensions and components should generally use addVars instead.
259 * @param array $settings
260 * @param string $region
261 * The region to add settings to (eg. for payment processors usually billing-block)
263 * @return CRM_Core_Resources
265 public function addSetting($settings, $region = NULL) {
266 $s = &$this->findCreateSettingSnippet($region);
267 $s['settings'] = $this->mergeSettings($s['settings'], $settings);
272 * Add JavaScript variables to the global CRM object via a callback function.
274 * @param callable $callable
275 * @param string|NULL $region
276 * @return CRM_Core_Resources
278 public function addSettingsFactory($callable, $region = NULL) {
279 $s = &$this->findCreateSettingSnippet($region);
280 $s['settingsFactories'][] = $callable;
285 * Helper fn for addSettingsFactory.
288 public function getSettings($region = NULL) {
289 $s = &$this->findCreateSettingSnippet($region);
290 $result = $s['settings'];
291 foreach ($s['settingsFactories'] as $callable) {
292 $result = $this->mergeSettings($result, $callable());
294 CRM_Utils_Hook
::alterResourceSettings($result);
299 * @param array $settings
300 * @param array $additions
302 * combination of $settings and $additions
304 protected function mergeSettings($settings, $additions) {
305 foreach ($additions as $k => $v) {
306 if (isset($settings[$k]) && is_array($settings[$k]) && is_array($v)) {
315 * @param string $regionName
318 private function &findCreateSettingSnippet($regionName) {
320 $regionName = self
::isAjaxMode() ?
'ajax-snippet' : 'html-header';
323 $region = CRM_Core_Region
::instance($regionName);
324 $snippet = &$region->get('settings');
325 if ($snippet !== NULL) {
330 'name' => 'settings',
331 'type' => 'settings',
333 'settingsFactories' => [],
336 return $region->get('settings');
340 * Add translated string to the js CRM object.
341 * It can then be retrived from the client-side ts() function
342 * Variable substitutions can happen from client-side
344 * Note: this function rarely needs to be called directly and is mostly for internal use.
345 * See CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
349 * CRM_Core_Resources::singleton()->addString('Hello');
350 * // The string is now available to javascript code i.e.
353 * Example with client-side substitutions:
355 * CRM_Core_Resources::singleton()->addString('Your %1 has been %2');
356 * // ts() in javascript works the same as in php, for example:
357 * ts('Your %1 has been %2', {1: objectName, 2: actionTaken});
359 * NOTE: This function does not work with server-side substitutions
360 * (as this might result in collisions and unwanted variable injections)
361 * Instead, use code like:
362 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs)))));
363 * And from javascript access it at CRM.myNamespace.myString
365 * @param string|array $text
366 * @param string|null $domain
367 * @return CRM_Core_Resources
369 public function addString($text, $domain = 'civicrm') {
370 foreach ((array) $text as $str) {
371 $translated = ts($str, [
372 'domain' => ($domain == 'civicrm') ?
NULL : [$domain, NULL],
376 // We only need to push this string to client if the translation
377 // is actually different from the original
378 if ($translated != $str) {
379 $bucket = $domain == 'civicrm' ?
'strings' : 'strings::' . $domain;
381 $bucket => [$str => $translated],
389 * Add a CSS file to the current page using <LINK HREF>.
392 * extension name; use 'civicrm' for core.
393 * @param string $file
394 * file path -- relative to the extension base dir.
396 * relative weight within a given region.
397 * @param string $region
398 * location within the file; 'html-header', 'page-header', 'page-footer'.
399 * @return CRM_Core_Resources
401 public function addStyleFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
402 /** @var Civi\Core\Themes $theme */
403 $theme = Civi
::service('themes');
404 foreach ($theme->resolveUrls($theme->getActiveThemeKey(), $ext, $file) as $url) {
405 $this->addStyleUrl($url, $weight, $region);
411 * Add a CSS file to the current page using <LINK HREF>.
415 * relative weight within a given region.
416 * @param string $region
417 * location within the file; 'html-header', 'page-header', 'page-footer'.
418 * @return CRM_Core_Resources
420 public function addStyleUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
421 CRM_Core_Region
::instance($region)->add(['styleUrl' => $url, 'weight' => $weight]);
426 * Add a CSS content to the current page using <STYLE>.
428 * @param string $code
431 * relative weight within a given region.
432 * @param string $region
433 * location within the file; 'html-header', 'page-header', 'page-footer'.
434 * @return CRM_Core_Resources
436 public function addStyle($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
437 CRM_Core_Region
::instance($region)->add(['style' => $code, 'weight' => $weight]);
442 * Determine file path of a resource provided by an extension.
445 * extension name; use 'civicrm' for core.
446 * @param string|null $file
447 * file path -- relative to the extension base dir.
449 * @return bool|string
450 * full file path or FALSE if not found
452 public function getPath($ext, $file = NULL) {
453 // TODO consider caching results
454 $base = $this->paths
->hasVariable($ext)
455 ?
rtrim($this->paths
->getVariable($ext, 'path'), '/')
456 : $this->extMapper
->keyToBasePath($ext);
457 if ($file === NULL) {
460 $path = $base . '/' . $file;
461 if (is_file($path)) {
468 * Determine public URL of a resource provided by an extension.
471 * extension name; use 'civicrm' for core.
472 * @param string $file
473 * file path -- relative to the extension base dir.
474 * @param bool $addCacheCode
476 * @return string, URL
478 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
479 if ($file === NULL) {
483 $file = $this->addCacheCode($file);
485 // TODO consider caching results
486 $base = $this->paths
->hasVariable($ext)
487 ?
$this->paths
->getVariable($ext, 'url')
488 : ($this->extMapper
->keyToUrl($ext) . '/');
489 return $base . $file;
493 * Evaluate a glob pattern in the context of a particular extension.
496 * Extension name; use 'civicrm' for core.
497 * @param string|array $patterns
498 * Glob pattern; e.g. "*.html".
499 * @param null|int $flags
502 * List of matching files, relative to the extension base dir.
505 public function glob($ext, $patterns, $flags = NULL) {
506 $path = $this->getPath($ext);
507 $patterns = (array) $patterns;
509 foreach ($patterns as $pattern) {
510 if (preg_match(';^(assetBuilder|ext)://;', $pattern)) {
513 if (CRM_Utils_File
::isAbsolute($pattern)) {
515 $files = array_merge($files, (array) glob($pattern, $flags));
519 $files = array_merge($files, (array) glob("$path/$pattern", $flags));
522 // Deterministic order.
524 $files = array_unique($files);
525 return array_map(function ($file) use ($path) {
526 return CRM_Utils_File
::relativize($file, "$path/");
533 public function getCacheCode() {
534 return $this->cacheCode
;
539 * @return CRM_Core_Resources
541 public function setCacheCode($value) {
542 $this->cacheCode
= $value;
543 if ($this->cacheCodeKey
) {
544 Civi
::settings()->set($this->cacheCodeKey
, $value);
550 * @return CRM_Core_Resources
552 public function resetCacheCode() {
553 $this->setCacheCode(CRM_Utils_String
::createRandom(5, CRM_Utils_String
::ALPHANUMERIC
));
554 // Also flush cms resource cache if needed
555 CRM_Core_Config
::singleton()->userSystem
->clearResourceCache();
560 * This adds CiviCRM's standard css and js to the specified region of the document.
561 * It will only run once.
563 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
564 * (like addCoreResources/addCoreStyles).
566 * @param string $region
567 * @return CRM_Core_Resources
569 public function addCoreResources($region = 'html-header') {
570 if (!isset($this->addedCoreResources
[$region]) && !self
::isAjaxMode()) {
571 $this->addedCoreResources
[$region] = TRUE;
572 $config = CRM_Core_Config
::singleton();
574 // Add resources from coreResourceList
576 foreach ($this->coreResourceList($region) as $item) {
577 if (is_array($item)) {
578 $this->addSetting($item);
580 elseif (strpos($item, '.css')) {
581 $this->isFullyFormedUrl($item) ?
$this->addStyleUrl($item, -100, $region) : $this->addStyleFile('civicrm', $item, -100, $region);
583 elseif ($this->isFullyFormedUrl($item)) {
584 $this->addScriptUrl($item, $jsWeight++
, $region);
587 // Don't bother looking for ts() calls in packages, there aren't any
588 $translate = (substr($item, 0, 3) == 'js/');
589 $this->addScriptFile('civicrm', $item, $jsWeight++
, $region, $translate);
592 // Add global settings
595 'isFrontend' => $config->userFrameworkFrontend
,
598 // Disable profile creation if user lacks permission
599 if (!CRM_Core_Permission
::check('edit all contacts') && !CRM_Core_Permission
::check('add contacts')) {
600 $settings['config']['entityRef']['contactCreate'] = FALSE;
602 $this->addSetting($settings);
604 // Give control of jQuery and _ back to the CMS - this loads last
605 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
607 $this->addCoreStyles($region);
613 * This will add CiviCRM's standard CSS
615 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
616 * (like addCoreResources/addCoreStyles).
618 * @param string $region
619 * @return CRM_Core_Resources
621 public function addCoreStyles($region = 'html-header') {
622 if (!isset($this->addedCoreStyles
[$region])) {
623 $this->addedCoreStyles
[$region] = TRUE;
625 // Load custom or core css
626 $config = CRM_Core_Config
::singleton();
627 if (!empty($config->customCSSURL
)) {
628 $customCSSURL = $this->addCacheCode($config->customCSSURL
);
629 $this->addStyleUrl($customCSSURL, 99, $region);
631 if (!Civi
::settings()->get('disable_core_css')) {
632 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
634 // crm-i.css added ahead of other styles so it can be overridden by FA.
635 $this->addStyleFile('civicrm', 'css/crm-i.css', -101, $region);
641 * Flushes cached translated strings.
642 * @return CRM_Core_Resources
644 public function flushStrings() {
645 $this->strings
->flush();
650 * @return CRM_Core_Resources_Strings
652 public function getStrings() {
653 return $this->strings
;
657 * Create dynamic script for localizing js widgets.
659 public static function outputLocalizationJS() {
660 CRM_Core_Page_AJAX
::setJsHeaders();
661 $config = CRM_Core_Config
::singleton();
663 'moneyFormat' => json_encode(CRM_Utils_Money
::format(1234.56)),
664 'contactSearch' => json_encode($config->includeEmailInName ?
ts('Start typing a name or email...') : ts('Start typing a name...')),
665 'otherSearch' => json_encode(ts('Enter search term...')),
666 'entityRef' => self
::getEntityRefMetadata(),
667 'ajaxPopupsEnabled' => self
::singleton()->ajaxPopupsEnabled
,
668 'allowAlertAutodismissal' => (bool) Civi
::settings()->get('allow_alert_autodismissal'),
669 'resourceCacheCode' => self
::singleton()->getCacheCode(),
670 'locale' => CRM_Core_I18n
::getLocale(),
671 'cid' => (int) CRM_Core_Session
::getLoggedInContactID(),
673 print CRM_Core_Smarty
::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
674 CRM_Utils_System
::civiExit();
678 * List of core resources we add to every CiviCRM page.
680 * Note: non-compressed versions of .min files will be used in debug mode
682 * @param string $region
685 public function coreResourceList($region) {
686 $config = CRM_Core_Config
::singleton();
688 // Scripts needed by everyone, everywhere
689 // FIXME: This is too long; list needs finer-grained segmentation
691 "bower_components/jquery/dist/jquery.min.js",
692 "bower_components/jquery-ui/jquery-ui.min.js",
693 "bower_components/jquery-ui/themes/smoothness/jquery-ui.min.css",
694 "bower_components/lodash-compat/lodash.min.js",
695 "packages/jquery/plugins/jquery.mousewheel.min.js",
696 "bower_components/select2/select2.min.js",
697 "bower_components/select2/select2.min.css",
698 "bower_components/font-awesome/css/font-awesome.min.css",
699 "packages/jquery/plugins/jquery.form.min.js",
700 "packages/jquery/plugins/jquery.timeentry.min.js",
701 "packages/jquery/plugins/jquery.blockUI.min.js",
702 "bower_components/datatables/media/js/jquery.dataTables.min.js",
703 "bower_components/datatables/media/css/jquery.dataTables.min.css",
704 "bower_components/jquery-validation/dist/jquery.validate.min.js",
705 "bower_components/jquery-validation/dist/additional-methods.min.js",
706 "packages/jquery/plugins/jquery.ui.datepicker.validation.min.js",
708 "js/crm.datepicker.js",
710 "js/wysiwyg/crm.wysiwyg.js",
713 // Dynamic localization script
714 $items[] = $this->addCacheCode(
715 CRM_Utils_System
::url('civicrm/ajax/l10n-js/' . CRM_Core_I18n
::getLocale(),
716 ['cid' => CRM_Core_Session
::getLoggedInContactID()], FALSE, NULL, FALSE)
719 // add wysiwyg editor
720 $editor = Civi
::settings()->get('editor_id');
721 if ($editor == "CKEditor") {
722 CRM_Admin_Form_CKEditorConfig
::setConfigDefault();
725 'wysisygScriptLocation' => Civi
::paths()->getUrl("[civicrm.root]/js/wysiwyg/crm.ckeditor.js"),
726 'CKEditorCustomConfig' => CRM_Admin_Form_CKEditorConfig
::getConfigUrl(),
731 // These scripts are only needed by back-office users
732 if (CRM_Core_Permission
::check('access CiviCRM')) {
733 $items[] = "packages/jquery/plugins/jquery.tableHeader.js";
734 $items[] = "packages/jquery/plugins/jquery.notify.min.js";
737 $contactID = CRM_Core_Session
::getLoggedInContactID();
742 $contactID && !$config->userFrameworkFrontend
743 && CRM_Core_Permission
::check('access CiviCRM')
744 && !@constant
('CIVICRM_DISABLE_DEFAULT_MENU')
745 && !CRM_Core_Config
::isUpgradeMode()
747 $position = Civi
::settings()->get('menubar_position') ?
: 'over-cms-menu';
749 if ($position !== 'none') {
750 $items[] = 'bower_components/smartmenus/dist/jquery.smartmenus.min.js';
751 $items[] = 'bower_components/smartmenus/dist/addons/keyboard/jquery.smartmenus.keyboard.min.js';
752 $items[] = 'js/crm.menubar.js';
753 // @see CRM_Core_Resources::renderMenubarStylesheet
754 $items[] = Civi
::service('asset_builder')->getUrl('crm-menubar.css', [
755 'menubarColor' => Civi
::settings()->get('menubar_color'),
759 // Variables for crm.menubar.js
762 'position' => $position,
763 'qfKey' => CRM_Core_Key
::get('CRM_Contact_Controller_Search', TRUE),
764 'cacheCode' => CRM_Core_BAO_Navigation
::getCacheKey($contactID),
769 // JS for multilingual installations
770 if (!empty($config->languageLimit
) && count($config->languageLimit
) > 1 && CRM_Core_Permission
::check('translate CiviCRM')) {
771 $items[] = "js/crm.multilingual.js";
774 // Enable administrators to edit option lists in a dialog
775 if (CRM_Core_Permission
::check('administer CiviCRM') && $this->ajaxPopupsEnabled
) {
776 $items[] = "js/crm.optionEdit.js";
779 $tsLocale = CRM_Core_I18n
::getLocale();
780 // Add localized jQuery UI files
781 if ($tsLocale && $tsLocale != 'en_US') {
782 // Search for i18n file in order of specificity (try fr-CA, then fr)
783 list($lang) = explode('_', $tsLocale);
784 $path = "bower_components/jquery-ui/ui/i18n";
785 foreach ([str_replace('_', '-', $tsLocale), $lang] as $language) {
786 $localizationFile = "$path/datepicker-{$language}.js";
787 if ($this->getPath('civicrm', $localizationFile)) {
788 $items[] = $localizationFile;
794 // Allow hooks to modify this list
795 CRM_Utils_Hook
::coreResourceList($items, $region);
797 // Oof, existing listeners would expect $items to typically begin with 'bower_components/' or 'packages/'
798 // (using an implicit base of `[civicrm.root]`). We preserve the hook contract and cleanup $items post-hook.
800 'bower_components' => rtrim(Civi
::paths()->getUrl('[civicrm.bower]/.', 'absolute'), '/'),
801 'packages' => rtrim(Civi
::paths()->getUrl('[civicrm.packages]/.', 'absolute'), '/'),
803 $filter = function($m) use ($map) {
804 return $map[$m[1]] . $m[2];
806 $items = array_map(function($item) use ($filter) {
807 return is_array($item) ?
$item : preg_replace_callback(';^(bower_components|packages)(/.*);', $filter, $item);
815 * is this page request an ajax snippet?
817 public static function isAjaxMode() {
818 if (in_array(CRM_Utils_Array
::value('snippet', $_REQUEST), [
819 CRM_Core_Smarty
::PRINT_SNIPPET
,
820 CRM_Core_Smarty
::PRINT_NOFORM
,
821 CRM_Core_Smarty
::PRINT_JSON
,
826 list($arg0, $arg1) = array_pad(explode('/', CRM_Utils_System
::currentPath()), 2, '');
827 return ($arg0 === 'civicrm' && in_array($arg1, ['ajax', 'angularprofiles', 'asset']));
831 * @param \Civi\Core\Event\GenericHookEvent $e
832 * @see \CRM_Utils_Hook::buildAsset()
834 public static function renderMenubarStylesheet(GenericHookEvent
$e) {
835 if ($e->asset
!== 'crm-menubar.css') {
838 $e->mimeType
= 'text/css';
840 $config = CRM_Core_Config
::singleton();
841 $cms = strtolower($config->userFramework
);
842 $cms = $cms === 'drupal' ?
'drupal7' : $cms;
844 'bower_components/smartmenus/dist/css/sm-core-css.css',
845 'css/crm-menubar.css',
846 "css/menubar-$cms.css",
848 foreach ($items as $item) {
849 $content .= file_get_contents(self
::singleton()->getPath('civicrm', $item));
851 $params = $e->params
;
852 // "color" is deprecated in favor of the more specific "menubarColor"
853 $menubarColor = $params['color'] ??
$params['menubarColor'];
855 '$resourceBase' => rtrim($config->resourceBase
, '/'),
856 '$menubarHeight' => $params['height'] . 'px',
857 '$breakMin' => $params['breakpoint'] . 'px',
858 '$breakMax' => ($params['breakpoint'] - 1) . 'px',
859 '$menubarColor' => $menubarColor,
860 '$menuItemColor' => $params['menuItemColor'] ??
$menubarColor,
861 '$highlightColor' => $params['highlightColor'] ?? CRM_Utils_Color
::getHighlight($menubarColor),
862 '$textColor' => $params['textColor'] ?? CRM_Utils_Color
::getContrast($menubarColor, '#333', '#ddd'),
864 $vars['$highlightTextColor'] = $params['highlightTextColor'] ?? CRM_Utils_Color
::getContrast($vars['$highlightColor'], '#333', '#ddd');
865 $e->content
= str_replace(array_keys($vars), array_values($vars), $content);
869 * Provide a list of available entityRef filters.
873 public static function getEntityRefMetadata() {
878 $config = CRM_Core_Config
::singleton();
880 $disabledComponents = [];
881 $dao = CRM_Core_DAO
::executeQuery("SELECT name, namespace FROM civicrm_component");
882 while ($dao->fetch()) {
883 if (!in_array($dao->name
, $config->enableComponents
)) {
884 $disabledComponents[$dao->name
] = $dao->namespace;
888 foreach (CRM_Core_DAO_AllCoreTables
::daoToClass() as $entity => $daoName) {
889 // Skip DAOs of disabled components
890 foreach ($disabledComponents as $nameSpace) {
891 if (strpos($daoName, $nameSpace) === 0) {
895 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
896 if (class_exists($baoName)) {
897 $filters = $baoName::getEntityRefFilters();
899 $data['filters'][$entity] = $filters;
901 if (is_callable([$baoName, 'getEntityRefCreateLinks'])) {
902 $createLinks = $baoName::getEntityRefCreateLinks();
904 $data['links'][$entity] = $createLinks;
910 CRM_Utils_Hook
::entityRefFilters($data['filters'], $data['links']);
916 * Determine the minified file name.
919 * @param string $file
921 * An updated $fileName. If a minified version exists and is supported by
922 * system policy, the minified version will be returned. Otherwise, the original.
924 public function filterMinify($ext, $file) {
925 if (CRM_Core_Config
::singleton()->debug
&& strpos($file, '.min.') !== FALSE) {
926 $nonMiniFile = str_replace('.min.', '.', $file);
927 if ($this->getPath($ext, $nonMiniFile)) {
928 $file = $nonMiniFile;
938 public function addCacheCode($url) {
939 $hasQuery = strpos($url, '?') !== FALSE;
940 $operator = $hasQuery ?
'&' : '?';
942 return $url . $operator . 'r=' . $this->cacheCode
;
946 * Checks if the given URL is fully-formed
952 public static function isFullyFormedUrl($url) {
953 return (substr($url, 0, 4) === 'http') ||
(substr($url, 0, 1) === '/');