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
29 class CRM_Core_Resources
{
30 const DEFAULT_WEIGHT
= 0;
31 const DEFAULT_REGION
= 'page-footer';
34 * We don't have a container or dependency-injection, so use singleton instead
38 private static $_singleton = NULL;
41 * @var CRM_Extension_Mapper
43 private $extMapper = NULL;
46 * @var CRM_Core_Resources_Strings
48 private $strings = NULL;
51 * Settings in free-form data tree.
55 protected $settings = [];
56 protected $addedSettings = FALSE;
63 protected $settingsFactories = [];
66 * Added core resources.
68 * Format is ($regionName => bool).
72 protected $addedCoreResources = [];
77 * Format is ($regionName => bool).
81 protected $addedCoreStyles = [];
84 * A value to append to JS/CSS URLs to coerce cache resets.
88 protected $cacheCode = NULL;
91 * The name of a setting which persistently stores the cacheCode.
95 protected $cacheCodeKey = NULL;
98 * Are ajax popup screens enabled.
102 public $ajaxPopupsEnabled;
105 * @var \Civi\Core\Paths
110 * Get or set the single instance of CRM_Core_Resources.
112 * @param CRM_Core_Resources $instance
113 * New copy of the manager.
115 * @return CRM_Core_Resources
117 public static function singleton(CRM_Core_Resources
$instance = NULL) {
118 if ($instance !== NULL) {
119 self
::$_singleton = $instance;
121 if (self
::$_singleton === NULL) {
122 self
::$_singleton = Civi
::service('resources');
124 return self
::$_singleton;
128 * Construct a resource manager.
130 * @param CRM_Extension_Mapper $extMapper
131 * Map extension names to their base path or URLs.
132 * @param CRM_Utils_Cache_Interface $cache
133 * JS-localization cache.
134 * @param string|null $cacheCodeKey Random code to append to resource URLs; changing the code forces clients to reload resources
136 public function __construct($extMapper, $cache, $cacheCodeKey = NULL) {
137 $this->extMapper
= $extMapper;
138 $this->strings
= new CRM_Core_Resources_Strings($cache);
139 $this->cacheCodeKey
= $cacheCodeKey;
140 if ($cacheCodeKey !== NULL) {
141 $this->cacheCode
= Civi
::settings()->get($cacheCodeKey);
143 if (!$this->cacheCode
) {
144 $this->resetCacheCode();
146 $this->ajaxPopupsEnabled
= (bool) Civi
::settings()->get('ajaxPopupsEnabled');
147 $this->paths
= Civi
::paths();
151 * Export permission data to the client to enable smarter GUIs.
153 * Note: Application security stems from the server's enforcement
154 * of the security logic (e.g. in the API permissions). There's no way
155 * the client can use this info to make the app more secure; however,
156 * it can produce a better-tuned (non-broken) UI.
158 * @param array $permNames
159 * List of permission names to check/export.
160 * @return CRM_Core_Resources
162 public function addPermissions($permNames) {
163 $permNames = (array) $permNames;
165 foreach ($permNames as $permName) {
166 $perms[$permName] = CRM_Core_Permission
::check($permName);
168 return $this->addSetting([
169 'permissions' => $perms,
174 * Add a JavaScript file to the current page using <SCRIPT SRC>.
177 * extension name; use 'civicrm' for core.
178 * @param string $file
179 * file path -- relative to the extension base dir.
181 * relative weight within a given region.
182 * @param string $region
183 * location within the file; 'html-header', 'page-header', 'page-footer'.
184 * @param bool|string $translate
185 * Whether to load translated strings for this file. Use one of:
186 * - FALSE: Do not load translated strings.
187 * - TRUE: Load translated strings. Use the $ext's default domain.
188 * - string: Load translated strings. Use a specific domain.
190 * @return CRM_Core_Resources
192 * @throws \CRM_Core_Exception
194 public function addScriptFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
, $translate = TRUE) {
196 $domain = ($translate === TRUE) ?
$ext : $translate;
197 $this->addString($this->strings
->get($domain, $this->getPath($ext, $file), 'text/javascript'), $domain);
199 $url = $this->getUrl($ext, $this->filterMinify($ext, $file), TRUE);
200 return $this->addScriptUrl($url, $weight, $region);
204 * Add a JavaScript file to the current page using <SCRIPT SRC>.
208 * relative weight within a given region.
209 * @param string $region
210 * location within the file; 'html-header', 'page-header', 'page-footer'.
211 * @return CRM_Core_Resources
213 public function addScriptUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
214 CRM_Core_Region
::instance($region)->add([
216 'type' => 'scriptUrl',
225 * Add a JavaScript file to the current page using <SCRIPT SRC>.
227 * @param string $code
228 * JavaScript source code.
230 * relative weight within a given region.
231 * @param string $region
232 * location within the file; 'html-header', 'page-header', 'page-footer'.
233 * @return CRM_Core_Resources
235 public function addScript($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
236 CRM_Core_Region
::instance($region)->add([
237 // 'name' => automatic
247 * Add JavaScript variables to CRM.vars
251 * CRM_Core_Resources::singleton()->addVars('myNamespace', array('foo' => 'bar'));
252 * Access var from javascript:
253 * CRM.vars.myNamespace.foo // "bar"
255 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Javascript+Reference
257 * @param string $nameSpace
258 * Usually the name of your extension.
260 * @return CRM_Core_Resources
262 public function addVars($nameSpace, $vars) {
263 $existing = CRM_Utils_Array
::value($nameSpace, CRM_Utils_Array
::value('vars', $this->settings
), []);
264 $vars = $this->mergeSettings($existing, $vars);
265 $this->addSetting(['vars' => [$nameSpace => $vars]]);
270 * Add JavaScript variables to the root of the CRM object.
271 * This function is usually reserved for low-level system use.
272 * Extensions and components should generally use addVars instead.
274 * @param array $settings
275 * @return CRM_Core_Resources
277 public function addSetting($settings) {
278 $this->settings
= $this->mergeSettings($this->settings
, $settings);
279 if (!$this->addedSettings
) {
280 $region = self
::isAjaxMode() ?
'ajax-snippet' : 'html-header';
282 CRM_Core_Region
::instance($region)->add([
283 'callback' => function (&$snippet, &$html) use ($resources) {
284 $html .= "\n" . $resources->renderSetting();
288 $this->addedSettings
= TRUE;
294 * Add JavaScript variables to the global CRM object via a callback function.
296 * @param callable $callable
297 * @return CRM_Core_Resources
299 public function addSettingsFactory($callable) {
300 // Make sure our callback has been registered
301 $this->addSetting([]);
302 $this->settingsFactories
[] = $callable;
307 * Helper fn for addSettingsFactory.
309 public function getSettings() {
310 $result = $this->settings
;
311 foreach ($this->settingsFactories
as $callable) {
312 $result = $this->mergeSettings($result, $callable());
314 CRM_Utils_Hook
::alterResourceSettings($result);
319 * @param array $settings
320 * @param array $additions
322 * combination of $settings and $additions
324 protected function mergeSettings($settings, $additions) {
325 foreach ($additions as $k => $v) {
326 if (isset($settings[$k]) && is_array($settings[$k]) && is_array($v)) {
335 * Helper fn for addSetting.
336 * Render JavaScript variables for the global CRM object.
340 public function renderSetting() {
341 // On a standard page request we construct the CRM object from scratch
342 if (!self
::isAjaxMode()) {
343 $js = 'var CRM = ' . json_encode($this->getSettings()) . ';';
345 // For an ajax request we append to it
347 $js = 'CRM.$.extend(true, CRM, ' . json_encode($this->getSettings()) . ');';
349 return sprintf("<script type=\"text/javascript\">\n%s\n</script>\n", $js);
353 * Add translated string to the js CRM object.
354 * It can then be retrived from the client-side ts() function
355 * Variable substitutions can happen from client-side
357 * Note: this function rarely needs to be called directly and is mostly for internal use.
358 * See CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
362 * CRM_Core_Resources::singleton()->addString('Hello');
363 * // The string is now available to javascript code i.e.
366 * Example with client-side substitutions:
368 * CRM_Core_Resources::singleton()->addString('Your %1 has been %2');
369 * // ts() in javascript works the same as in php, for example:
370 * ts('Your %1 has been %2', {1: objectName, 2: actionTaken});
372 * NOTE: This function does not work with server-side substitutions
373 * (as this might result in collisions and unwanted variable injections)
374 * Instead, use code like:
375 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs)))));
376 * And from javascript access it at CRM.myNamespace.myString
378 * @param string|array $text
379 * @param string|null $domain
380 * @return CRM_Core_Resources
382 public function addString($text, $domain = 'civicrm') {
383 foreach ((array) $text as $str) {
384 $translated = ts($str, [
385 'domain' => ($domain == 'civicrm') ?
NULL : [$domain, NULL],
389 // We only need to push this string to client if the translation
390 // is actually different from the original
391 if ($translated != $str) {
392 $bucket = $domain == 'civicrm' ?
'strings' : 'strings::' . $domain;
394 $bucket => [$str => $translated],
402 * Add a CSS file to the current page using <LINK HREF>.
405 * extension name; use 'civicrm' for core.
406 * @param string $file
407 * file path -- relative to the extension base dir.
409 * relative weight within a given region.
410 * @param string $region
411 * location within the file; 'html-header', 'page-header', 'page-footer'.
412 * @return CRM_Core_Resources
414 public function addStyleFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
415 /** @var Civi\Core\Themes $theme */
416 $theme = Civi
::service('themes');
417 foreach ($theme->resolveUrls($theme->getActiveThemeKey(), $ext, $file) as $url) {
418 $this->addStyleUrl($url, $weight, $region);
424 * Add a CSS file to the current page using <LINK HREF>.
428 * relative weight within a given region.
429 * @param string $region
430 * location within the file; 'html-header', 'page-header', 'page-footer'.
431 * @return CRM_Core_Resources
433 public function addStyleUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
434 CRM_Core_Region
::instance($region)->add([
436 'type' => 'styleUrl',
445 * Add a CSS content to the current page using <STYLE>.
447 * @param string $code
450 * relative weight within a given region.
451 * @param string $region
452 * location within the file; 'html-header', 'page-header', 'page-footer'.
453 * @return CRM_Core_Resources
455 public function addStyle($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
456 CRM_Core_Region
::instance($region)->add([
457 // 'name' => automatic
467 * Determine file path of a resource provided by an extension.
470 * extension name; use 'civicrm' for core.
471 * @param string|null $file
472 * file path -- relative to the extension base dir.
474 * @return bool|string
475 * full file path or FALSE if not found
477 public function getPath($ext, $file = NULL) {
478 // TODO consider caching results
479 $base = $this->paths
->hasVariable($ext)
480 ?
rtrim($this->paths
->getVariable($ext, 'path'), '/')
481 : $this->extMapper
->keyToBasePath($ext);
482 if ($file === NULL) {
485 $path = $base . '/' . $file;
486 if (is_file($path)) {
493 * Determine public URL of a resource provided by an extension.
496 * extension name; use 'civicrm' for core.
497 * @param string $file
498 * file path -- relative to the extension base dir.
499 * @param bool $addCacheCode
501 * @return string, URL
503 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
504 if ($file === NULL) {
508 $file = $this->addCacheCode($file);
510 // TODO consider caching results
511 $base = $this->paths
->hasVariable($ext)
512 ?
$this->paths
->getVariable($ext, 'url')
513 : ($this->extMapper
->keyToUrl($ext) . '/');
514 return $base . $file;
518 * Evaluate a glob pattern in the context of a particular extension.
521 * Extension name; use 'civicrm' for core.
522 * @param string|array $patterns
523 * Glob pattern; e.g. "*.html".
524 * @param null|int $flags
527 * List of matching files, relative to the extension base dir.
530 public function glob($ext, $patterns, $flags = NULL) {
531 $path = $this->getPath($ext);
532 $patterns = (array) $patterns;
534 foreach ($patterns as $pattern) {
535 if (preg_match(';^(assetBuilder|ext)://;', $pattern)) {
538 if (CRM_Utils_File
::isAbsolute($pattern)) {
540 $files = array_merge($files, (array) glob($pattern, $flags));
544 $files = array_merge($files, (array) glob("$path/$pattern", $flags));
547 // Deterministic order.
549 $files = array_unique($files);
550 return array_map(function ($file) use ($path) {
551 return CRM_Utils_File
::relativize($file, "$path/");
558 public function getCacheCode() {
559 return $this->cacheCode
;
564 * @return CRM_Core_Resources
566 public function setCacheCode($value) {
567 $this->cacheCode
= $value;
568 if ($this->cacheCodeKey
) {
569 Civi
::settings()->set($this->cacheCodeKey
, $value);
575 * @return CRM_Core_Resources
577 public function resetCacheCode() {
578 $this->setCacheCode(CRM_Utils_String
::createRandom(5, CRM_Utils_String
::ALPHANUMERIC
));
579 // Also flush cms resource cache if needed
580 CRM_Core_Config
::singleton()->userSystem
->clearResourceCache();
585 * This adds CiviCRM's standard css and js to the specified region of the document.
586 * It will only run once.
588 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
589 * (like addCoreResources/addCoreStyles).
591 * @param string $region
592 * @return CRM_Core_Resources
594 public function addCoreResources($region = 'html-header') {
595 if (!isset($this->addedCoreResources
[$region]) && !self
::isAjaxMode()) {
596 $this->addedCoreResources
[$region] = TRUE;
597 $config = CRM_Core_Config
::singleton();
599 // Add resources from coreResourceList
601 foreach ($this->coreResourceList($region) as $item) {
602 if (is_array($item)) {
603 $this->addSetting($item);
605 elseif (strpos($item, '.css')) {
606 $this->isFullyFormedUrl($item) ?
$this->addStyleUrl($item, -100, $region) : $this->addStyleFile('civicrm', $item, -100, $region);
608 elseif ($this->isFullyFormedUrl($item)) {
609 $this->addScriptUrl($item, $jsWeight++
, $region);
612 // Don't bother looking for ts() calls in packages, there aren't any
613 $translate = (substr($item, 0, 3) == 'js/');
614 $this->addScriptFile('civicrm', $item, $jsWeight++
, $region, $translate);
617 // Add global settings
620 'isFrontend' => $config->userFrameworkFrontend
,
623 // Disable profile creation if user lacks permission
624 if (!CRM_Core_Permission
::check('edit all contacts') && !CRM_Core_Permission
::check('add contacts')) {
625 $settings['config']['entityRef']['contactCreate'] = FALSE;
627 $this->addSetting($settings);
629 // Give control of jQuery and _ back to the CMS - this loads last
630 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
632 $this->addCoreStyles($region);
638 * This will add CiviCRM's standard CSS
640 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
641 * (like addCoreResources/addCoreStyles).
643 * @param string $region
644 * @return CRM_Core_Resources
646 public function addCoreStyles($region = 'html-header') {
647 if (!isset($this->addedCoreStyles
[$region])) {
648 $this->addedCoreStyles
[$region] = TRUE;
650 // Load custom or core css
651 $config = CRM_Core_Config
::singleton();
652 if (!empty($config->customCSSURL
)) {
653 $customCSSURL = $this->addCacheCode($config->customCSSURL
);
654 $this->addStyleUrl($customCSSURL, 99, $region);
656 if (!Civi
::settings()->get('disable_core_css')) {
657 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
659 // crm-i.css added ahead of other styles so it can be overridden by FA.
660 $this->addStyleFile('civicrm', 'css/crm-i.css', -101, $region);
666 * Flushes cached translated strings.
667 * @return CRM_Core_Resources
669 public function flushStrings() {
670 $this->strings
->flush();
675 * @return CRM_Core_Resources_Strings
677 public function getStrings() {
678 return $this->strings
;
682 * Create dynamic script for localizing js widgets.
684 public static function outputLocalizationJS() {
685 CRM_Core_Page_AJAX
::setJsHeaders();
686 $config = CRM_Core_Config
::singleton();
688 'moneyFormat' => json_encode(CRM_Utils_Money
::format(1234.56)),
689 'contactSearch' => json_encode($config->includeEmailInName ?
ts('Start typing a name or email...') : ts('Start typing a name...')),
690 'otherSearch' => json_encode(ts('Enter search term...')),
691 'entityRef' => self
::getEntityRefMetadata(),
692 'ajaxPopupsEnabled' => self
::singleton()->ajaxPopupsEnabled
,
693 'allowAlertAutodismissal' => (bool) Civi
::settings()->get('allow_alert_autodismissal'),
694 'resourceCacheCode' => self
::singleton()->getCacheCode(),
695 'locale' => CRM_Core_I18n
::getLocale(),
696 'cid' => (int) CRM_Core_Session
::getLoggedInContactID(),
698 print CRM_Core_Smarty
::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
699 CRM_Utils_System
::civiExit();
703 * List of core resources we add to every CiviCRM page.
705 * Note: non-compressed versions of .min files will be used in debug mode
707 * @param string $region
710 public function coreResourceList($region) {
711 $config = CRM_Core_Config
::singleton();
713 // Scripts needed by everyone, everywhere
714 // FIXME: This is too long; list needs finer-grained segmentation
716 "bower_components/jquery/dist/jquery.min.js",
717 "bower_components/jquery-ui/jquery-ui.min.js",
718 "bower_components/jquery-ui/themes/smoothness/jquery-ui.min.css",
719 "bower_components/lodash-compat/lodash.min.js",
720 "packages/jquery/plugins/jquery.mousewheel.min.js",
721 "bower_components/select2/select2.min.js",
722 "bower_components/select2/select2.min.css",
723 "bower_components/font-awesome/css/font-awesome.min.css",
724 "packages/jquery/plugins/jquery.form.min.js",
725 "packages/jquery/plugins/jquery.timeentry.min.js",
726 "packages/jquery/plugins/jquery.blockUI.min.js",
727 "bower_components/datatables/media/js/jquery.dataTables.min.js",
728 "bower_components/datatables/media/css/jquery.dataTables.min.css",
729 "bower_components/jquery-validation/dist/jquery.validate.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_Page_CKEditorConfig
::setConfigDefault();
749 'wysisygScriptLocation' => Civi
::paths()->getUrl("[civicrm.root]/js/wysiwyg/crm.ckeditor.js"),
750 'CKEditorCustomConfig' => CRM_Admin_Page_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
::getUrlPath()), 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) === '/');