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([
208 'type' => 'scriptUrl',
217 * Add a JavaScript file to the current page using <SCRIPT SRC>.
219 * @param string $code
220 * JavaScript source code.
222 * relative weight within a given region.
223 * @param string $region
224 * location within the file; 'html-header', 'page-header', 'page-footer'.
225 * @return CRM_Core_Resources
227 public function addScript($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
228 CRM_Core_Region
::instance($region)->add([
229 // 'name' => automatic
239 * Add JavaScript variables to CRM.vars
243 * CRM_Core_Resources::singleton()->addVars('myNamespace', array('foo' => 'bar'));
244 * Access var from javascript:
245 * CRM.vars.myNamespace.foo // "bar"
247 * @see https://docs.civicrm.org/dev/en/latest/standards/javascript/
249 * @param string $nameSpace
250 * Usually the name of your extension.
252 * @param string $region
253 * The region to add settings to (eg. for payment processors usually billing-block)
255 * @return CRM_Core_Resources
257 public function addVars($nameSpace, $vars, $region = NULL) {
258 $s = &$this->findCreateSettingSnippet($region);
259 $s['settings']['vars'][$nameSpace] = $this->mergeSettings(
260 $s['settings']['vars'][$nameSpace] ??
[],
267 * Add JavaScript variables to the root of the CRM object.
268 * This function is usually reserved for low-level system use.
269 * Extensions and components should generally use addVars instead.
271 * @param array $settings
272 * @param string $region
273 * The region to add settings to (eg. for payment processors usually billing-block)
275 * @return CRM_Core_Resources
277 public function addSetting($settings, $region = NULL) {
278 $s = &$this->findCreateSettingSnippet($region);
279 $s['settings'] = $this->mergeSettings($s['settings'], $settings);
284 * Add JavaScript variables to the global CRM object via a callback function.
286 * @param callable $callable
287 * @param string|NULL $region
288 * @return CRM_Core_Resources
290 public function addSettingsFactory($callable, $region = NULL) {
291 $s = &$this->findCreateSettingSnippet($region);
292 $s['settingsFactories'][] = $callable;
297 * Helper fn for addSettingsFactory.
300 public function getSettings($region = NULL) {
301 $s = &$this->findCreateSettingSnippet($region);
302 $result = $s['settings'];
303 foreach ($s['settingsFactories'] as $callable) {
304 $result = $this->mergeSettings($result, $callable());
306 CRM_Utils_Hook
::alterResourceSettings($result);
311 * @param array $settings
312 * @param array $additions
314 * combination of $settings and $additions
316 protected function mergeSettings($settings, $additions) {
317 foreach ($additions as $k => $v) {
318 if (isset($settings[$k]) && is_array($settings[$k]) && is_array($v)) {
327 * @param string $regionName
330 private function &findCreateSettingSnippet($regionName) {
332 $regionName = self
::isAjaxMode() ?
'ajax-snippet' : 'html-header';
335 $region = CRM_Core_Region
::instance($regionName);
336 $snippet = &$region->get('settings');
337 if ($snippet !== NULL) {
342 'name' => 'settings',
343 'type' => 'settings',
345 'settingsFactories' => [],
348 return $region->get('settings');
352 * Add translated string to the js CRM object.
353 * It can then be retrived from the client-side ts() function
354 * Variable substitutions can happen from client-side
356 * Note: this function rarely needs to be called directly and is mostly for internal use.
357 * See CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
361 * CRM_Core_Resources::singleton()->addString('Hello');
362 * // The string is now available to javascript code i.e.
365 * Example with client-side substitutions:
367 * CRM_Core_Resources::singleton()->addString('Your %1 has been %2');
368 * // ts() in javascript works the same as in php, for example:
369 * ts('Your %1 has been %2', {1: objectName, 2: actionTaken});
371 * NOTE: This function does not work with server-side substitutions
372 * (as this might result in collisions and unwanted variable injections)
373 * Instead, use code like:
374 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs)))));
375 * And from javascript access it at CRM.myNamespace.myString
377 * @param string|array $text
378 * @param string|null $domain
379 * @return CRM_Core_Resources
381 public function addString($text, $domain = 'civicrm') {
382 foreach ((array) $text as $str) {
383 $translated = ts($str, [
384 'domain' => ($domain == 'civicrm') ?
NULL : [$domain, NULL],
388 // We only need to push this string to client if the translation
389 // is actually different from the original
390 if ($translated != $str) {
391 $bucket = $domain == 'civicrm' ?
'strings' : 'strings::' . $domain;
393 $bucket => [$str => $translated],
401 * Add a CSS file to the current page using <LINK HREF>.
404 * extension name; use 'civicrm' for core.
405 * @param string $file
406 * file path -- relative to the extension base dir.
408 * relative weight within a given region.
409 * @param string $region
410 * location within the file; 'html-header', 'page-header', 'page-footer'.
411 * @return CRM_Core_Resources
413 public function addStyleFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
414 /** @var Civi\Core\Themes $theme */
415 $theme = Civi
::service('themes');
416 foreach ($theme->resolveUrls($theme->getActiveThemeKey(), $ext, $file) as $url) {
417 $this->addStyleUrl($url, $weight, $region);
423 * Add a CSS file to the current page using <LINK HREF>.
427 * relative weight within a given region.
428 * @param string $region
429 * location within the file; 'html-header', 'page-header', 'page-footer'.
430 * @return CRM_Core_Resources
432 public function addStyleUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
433 CRM_Core_Region
::instance($region)->add([
435 'type' => 'styleUrl',
444 * Add a CSS content to the current page using <STYLE>.
446 * @param string $code
449 * relative weight within a given region.
450 * @param string $region
451 * location within the file; 'html-header', 'page-header', 'page-footer'.
452 * @return CRM_Core_Resources
454 public function addStyle($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
455 CRM_Core_Region
::instance($region)->add([
456 // 'name' => automatic
466 * Determine file path of a resource provided by an extension.
469 * extension name; use 'civicrm' for core.
470 * @param string|null $file
471 * file path -- relative to the extension base dir.
473 * @return bool|string
474 * full file path or FALSE if not found
476 public function getPath($ext, $file = NULL) {
477 // TODO consider caching results
478 $base = $this->paths
->hasVariable($ext)
479 ?
rtrim($this->paths
->getVariable($ext, 'path'), '/')
480 : $this->extMapper
->keyToBasePath($ext);
481 if ($file === NULL) {
484 $path = $base . '/' . $file;
485 if (is_file($path)) {
492 * Determine public URL of a resource provided by an extension.
495 * extension name; use 'civicrm' for core.
496 * @param string $file
497 * file path -- relative to the extension base dir.
498 * @param bool $addCacheCode
500 * @return string, URL
502 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
503 if ($file === NULL) {
507 $file = $this->addCacheCode($file);
509 // TODO consider caching results
510 $base = $this->paths
->hasVariable($ext)
511 ?
$this->paths
->getVariable($ext, 'url')
512 : ($this->extMapper
->keyToUrl($ext) . '/');
513 return $base . $file;
517 * Evaluate a glob pattern in the context of a particular extension.
520 * Extension name; use 'civicrm' for core.
521 * @param string|array $patterns
522 * Glob pattern; e.g. "*.html".
523 * @param null|int $flags
526 * List of matching files, relative to the extension base dir.
529 public function glob($ext, $patterns, $flags = NULL) {
530 $path = $this->getPath($ext);
531 $patterns = (array) $patterns;
533 foreach ($patterns as $pattern) {
534 if (preg_match(';^(assetBuilder|ext)://;', $pattern)) {
537 if (CRM_Utils_File
::isAbsolute($pattern)) {
539 $files = array_merge($files, (array) glob($pattern, $flags));
543 $files = array_merge($files, (array) glob("$path/$pattern", $flags));
546 // Deterministic order.
548 $files = array_unique($files);
549 return array_map(function ($file) use ($path) {
550 return CRM_Utils_File
::relativize($file, "$path/");
557 public function getCacheCode() {
558 return $this->cacheCode
;
563 * @return CRM_Core_Resources
565 public function setCacheCode($value) {
566 $this->cacheCode
= $value;
567 if ($this->cacheCodeKey
) {
568 Civi
::settings()->set($this->cacheCodeKey
, $value);
574 * @return CRM_Core_Resources
576 public function resetCacheCode() {
577 $this->setCacheCode(CRM_Utils_String
::createRandom(5, CRM_Utils_String
::ALPHANUMERIC
));
578 // Also flush cms resource cache if needed
579 CRM_Core_Config
::singleton()->userSystem
->clearResourceCache();
584 * This adds CiviCRM's standard css and js to the specified region of the document.
585 * It will only run once.
587 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
588 * (like addCoreResources/addCoreStyles).
590 * @param string $region
591 * @return CRM_Core_Resources
593 public function addCoreResources($region = 'html-header') {
594 if (!isset($this->addedCoreResources
[$region]) && !self
::isAjaxMode()) {
595 $this->addedCoreResources
[$region] = TRUE;
596 $config = CRM_Core_Config
::singleton();
598 // Add resources from coreResourceList
600 foreach ($this->coreResourceList($region) as $item) {
601 if (is_array($item)) {
602 $this->addSetting($item);
604 elseif (strpos($item, '.css')) {
605 $this->isFullyFormedUrl($item) ?
$this->addStyleUrl($item, -100, $region) : $this->addStyleFile('civicrm', $item, -100, $region);
607 elseif ($this->isFullyFormedUrl($item)) {
608 $this->addScriptUrl($item, $jsWeight++
, $region);
611 // Don't bother looking for ts() calls in packages, there aren't any
612 $translate = (substr($item, 0, 3) == 'js/');
613 $this->addScriptFile('civicrm', $item, $jsWeight++
, $region, $translate);
616 // Add global settings
619 'isFrontend' => $config->userFrameworkFrontend
,
622 // Disable profile creation if user lacks permission
623 if (!CRM_Core_Permission
::check('edit all contacts') && !CRM_Core_Permission
::check('add contacts')) {
624 $settings['config']['entityRef']['contactCreate'] = FALSE;
626 $this->addSetting($settings);
628 // Give control of jQuery and _ back to the CMS - this loads last
629 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
631 $this->addCoreStyles($region);
637 * This will add CiviCRM's standard CSS
639 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
640 * (like addCoreResources/addCoreStyles).
642 * @param string $region
643 * @return CRM_Core_Resources
645 public function addCoreStyles($region = 'html-header') {
646 if (!isset($this->addedCoreStyles
[$region])) {
647 $this->addedCoreStyles
[$region] = TRUE;
649 // Load custom or core css
650 $config = CRM_Core_Config
::singleton();
651 if (!empty($config->customCSSURL
)) {
652 $customCSSURL = $this->addCacheCode($config->customCSSURL
);
653 $this->addStyleUrl($customCSSURL, 99, $region);
655 if (!Civi
::settings()->get('disable_core_css')) {
656 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
658 // crm-i.css added ahead of other styles so it can be overridden by FA.
659 $this->addStyleFile('civicrm', 'css/crm-i.css', -101, $region);
665 * Flushes cached translated strings.
666 * @return CRM_Core_Resources
668 public function flushStrings() {
669 $this->strings
->flush();
674 * @return CRM_Core_Resources_Strings
676 public function getStrings() {
677 return $this->strings
;
681 * Create dynamic script for localizing js widgets.
683 public static function outputLocalizationJS() {
684 CRM_Core_Page_AJAX
::setJsHeaders();
685 $config = CRM_Core_Config
::singleton();
687 'moneyFormat' => json_encode(CRM_Utils_Money
::format(1234.56)),
688 'contactSearch' => json_encode($config->includeEmailInName ?
ts('Start typing a name or email...') : ts('Start typing a name...')),
689 'otherSearch' => json_encode(ts('Enter search term...')),
690 'entityRef' => self
::getEntityRefMetadata(),
691 'ajaxPopupsEnabled' => self
::singleton()->ajaxPopupsEnabled
,
692 'allowAlertAutodismissal' => (bool) Civi
::settings()->get('allow_alert_autodismissal'),
693 'resourceCacheCode' => self
::singleton()->getCacheCode(),
694 'locale' => CRM_Core_I18n
::getLocale(),
695 'cid' => (int) CRM_Core_Session
::getLoggedInContactID(),
697 print CRM_Core_Smarty
::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
698 CRM_Utils_System
::civiExit();
702 * List of core resources we add to every CiviCRM page.
704 * Note: non-compressed versions of .min files will be used in debug mode
706 * @param string $region
709 public function coreResourceList($region) {
710 $config = CRM_Core_Config
::singleton();
712 // Scripts needed by everyone, everywhere
713 // FIXME: This is too long; list needs finer-grained segmentation
715 "bower_components/jquery/dist/jquery.min.js",
716 "bower_components/jquery-ui/jquery-ui.min.js",
717 "bower_components/jquery-ui/themes/smoothness/jquery-ui.min.css",
718 "bower_components/lodash-compat/lodash.min.js",
719 "packages/jquery/plugins/jquery.mousewheel.min.js",
720 "bower_components/select2/select2.min.js",
721 "bower_components/select2/select2.min.css",
722 "bower_components/font-awesome/css/font-awesome.min.css",
723 "packages/jquery/plugins/jquery.form.min.js",
724 "packages/jquery/plugins/jquery.timeentry.min.js",
725 "packages/jquery/plugins/jquery.blockUI.min.js",
726 "bower_components/datatables/media/js/jquery.dataTables.min.js",
727 "bower_components/datatables/media/css/jquery.dataTables.min.css",
728 "bower_components/jquery-validation/dist/jquery.validate.min.js",
729 "bower_components/jquery-validation/dist/additional-methods.min.js",
730 "packages/jquery/plugins/jquery.ui.datepicker.validation.min.js",
732 "js/crm.datepicker.js",
734 "js/wysiwyg/crm.wysiwyg.js",
737 // Dynamic localization script
738 $items[] = $this->addCacheCode(
739 CRM_Utils_System
::url('civicrm/ajax/l10n-js/' . CRM_Core_I18n
::getLocale(),
740 ['cid' => CRM_Core_Session
::getLoggedInContactID()], FALSE, NULL, FALSE)
743 // add wysiwyg editor
744 $editor = Civi
::settings()->get('editor_id');
745 if ($editor == "CKEditor") {
746 CRM_Admin_Form_CKEditorConfig
::setConfigDefault();
749 'wysisygScriptLocation' => Civi
::paths()->getUrl("[civicrm.root]/js/wysiwyg/crm.ckeditor.js"),
750 'CKEditorCustomConfig' => CRM_Admin_Form_CKEditorConfig
::getConfigUrl(),
755 // These scripts are only needed by back-office users
756 if (CRM_Core_Permission
::check('access CiviCRM')) {
757 $items[] = "packages/jquery/plugins/jquery.tableHeader.js";
758 $items[] = "packages/jquery/plugins/jquery.notify.min.js";
761 $contactID = CRM_Core_Session
::getLoggedInContactID();
766 $contactID && !$config->userFrameworkFrontend
767 && CRM_Core_Permission
::check('access CiviCRM')
768 && !@constant
('CIVICRM_DISABLE_DEFAULT_MENU')
769 && !CRM_Core_Config
::isUpgradeMode()
771 $position = Civi
::settings()->get('menubar_position') ?
: 'over-cms-menu';
773 if ($position !== 'none') {
774 $items[] = 'bower_components/smartmenus/dist/jquery.smartmenus.min.js';
775 $items[] = 'bower_components/smartmenus/dist/addons/keyboard/jquery.smartmenus.keyboard.min.js';
776 $items[] = 'js/crm.menubar.js';
777 // @see CRM_Core_Resources::renderMenubarStylesheet
778 $items[] = Civi
::service('asset_builder')->getUrl('crm-menubar.css', [
779 'menubarColor' => Civi
::settings()->get('menubar_color'),
783 // Variables for crm.menubar.js
786 'position' => $position,
787 'qfKey' => CRM_Core_Key
::get('CRM_Contact_Controller_Search', TRUE),
788 'cacheCode' => CRM_Core_BAO_Navigation
::getCacheKey($contactID),
793 // JS for multilingual installations
794 if (!empty($config->languageLimit
) && count($config->languageLimit
) > 1 && CRM_Core_Permission
::check('translate CiviCRM')) {
795 $items[] = "js/crm.multilingual.js";
798 // Enable administrators to edit option lists in a dialog
799 if (CRM_Core_Permission
::check('administer CiviCRM') && $this->ajaxPopupsEnabled
) {
800 $items[] = "js/crm.optionEdit.js";
803 $tsLocale = CRM_Core_I18n
::getLocale();
804 // Add localized jQuery UI files
805 if ($tsLocale && $tsLocale != 'en_US') {
806 // Search for i18n file in order of specificity (try fr-CA, then fr)
807 list($lang) = explode('_', $tsLocale);
808 $path = "bower_components/jquery-ui/ui/i18n";
809 foreach ([str_replace('_', '-', $tsLocale), $lang] as $language) {
810 $localizationFile = "$path/datepicker-{$language}.js";
811 if ($this->getPath('civicrm', $localizationFile)) {
812 $items[] = $localizationFile;
818 // Allow hooks to modify this list
819 CRM_Utils_Hook
::coreResourceList($items, $region);
821 // Oof, existing listeners would expect $items to typically begin with 'bower_components/' or 'packages/'
822 // (using an implicit base of `[civicrm.root]`). We preserve the hook contract and cleanup $items post-hook.
824 'bower_components' => rtrim(Civi
::paths()->getUrl('[civicrm.bower]/.', 'absolute'), '/'),
825 'packages' => rtrim(Civi
::paths()->getUrl('[civicrm.packages]/.', 'absolute'), '/'),
827 $filter = function($m) use ($map) {
828 return $map[$m[1]] . $m[2];
830 $items = array_map(function($item) use ($filter) {
831 return is_array($item) ?
$item : preg_replace_callback(';^(bower_components|packages)(/.*);', $filter, $item);
839 * is this page request an ajax snippet?
841 public static function isAjaxMode() {
842 if (in_array(CRM_Utils_Array
::value('snippet', $_REQUEST), [
843 CRM_Core_Smarty
::PRINT_SNIPPET
,
844 CRM_Core_Smarty
::PRINT_NOFORM
,
845 CRM_Core_Smarty
::PRINT_JSON
,
850 list($arg0, $arg1) = array_pad(explode('/', CRM_Utils_System
::currentPath()), 2, '');
851 return ($arg0 === 'civicrm' && in_array($arg1, ['ajax', 'angularprofiles', 'asset']));
855 * @param \Civi\Core\Event\GenericHookEvent $e
856 * @see \CRM_Utils_Hook::buildAsset()
858 public static function renderMenubarStylesheet(GenericHookEvent
$e) {
859 if ($e->asset
!== 'crm-menubar.css') {
862 $e->mimeType
= 'text/css';
864 $config = CRM_Core_Config
::singleton();
865 $cms = strtolower($config->userFramework
);
866 $cms = $cms === 'drupal' ?
'drupal7' : $cms;
868 'bower_components/smartmenus/dist/css/sm-core-css.css',
869 'css/crm-menubar.css',
870 "css/menubar-$cms.css",
872 foreach ($items as $item) {
873 $content .= file_get_contents(self
::singleton()->getPath('civicrm', $item));
875 $params = $e->params
;
876 // "color" is deprecated in favor of the more specific "menubarColor"
877 $menubarColor = $params['color'] ??
$params['menubarColor'];
879 '$resourceBase' => rtrim($config->resourceBase
, '/'),
880 '$menubarHeight' => $params['height'] . 'px',
881 '$breakMin' => $params['breakpoint'] . 'px',
882 '$breakMax' => ($params['breakpoint'] - 1) . 'px',
883 '$menubarColor' => $menubarColor,
884 '$menuItemColor' => $params['menuItemColor'] ??
$menubarColor,
885 '$highlightColor' => $params['highlightColor'] ?? CRM_Utils_Color
::getHighlight($menubarColor),
886 '$textColor' => $params['textColor'] ?? CRM_Utils_Color
::getContrast($menubarColor, '#333', '#ddd'),
888 $vars['$highlightTextColor'] = $params['highlightTextColor'] ?? CRM_Utils_Color
::getContrast($vars['$highlightColor'], '#333', '#ddd');
889 $e->content
= str_replace(array_keys($vars), array_values($vars), $content);
893 * Provide a list of available entityRef filters.
897 public static function getEntityRefMetadata() {
902 $config = CRM_Core_Config
::singleton();
904 $disabledComponents = [];
905 $dao = CRM_Core_DAO
::executeQuery("SELECT name, namespace FROM civicrm_component");
906 while ($dao->fetch()) {
907 if (!in_array($dao->name
, $config->enableComponents
)) {
908 $disabledComponents[$dao->name
] = $dao->namespace;
912 foreach (CRM_Core_DAO_AllCoreTables
::daoToClass() as $entity => $daoName) {
913 // Skip DAOs of disabled components
914 foreach ($disabledComponents as $nameSpace) {
915 if (strpos($daoName, $nameSpace) === 0) {
919 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
920 if (class_exists($baoName)) {
921 $filters = $baoName::getEntityRefFilters();
923 $data['filters'][$entity] = $filters;
925 if (is_callable([$baoName, 'getEntityRefCreateLinks'])) {
926 $createLinks = $baoName::getEntityRefCreateLinks();
928 $data['links'][$entity] = $createLinks;
934 CRM_Utils_Hook
::entityRefFilters($data['filters'], $data['links']);
940 * Determine the minified file name.
943 * @param string $file
945 * An updated $fileName. If a minified version exists and is supported by
946 * system policy, the minified version will be returned. Otherwise, the original.
948 public function filterMinify($ext, $file) {
949 if (CRM_Core_Config
::singleton()->debug
&& strpos($file, '.min.') !== FALSE) {
950 $nonMiniFile = str_replace('.min.', '.', $file);
951 if ($this->getPath($ext, $nonMiniFile)) {
952 $file = $nonMiniFile;
962 public function addCacheCode($url) {
963 $hasQuery = strpos($url, '?') !== FALSE;
964 $operator = $hasQuery ?
'&' : '?';
966 return $url . $operator . 'r=' . $this->cacheCode
;
970 * Checks if the given URL is fully-formed
976 public static function isFullyFormedUrl($url) {
977 return (substr($url, 0, 4) === 'http') ||
(substr($url, 0, 1) === '/');