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 * Settings in free-form data tree.
53 protected $settings = [];
60 protected $settingsFactories = [];
63 * Added core resources.
65 * Format is ($regionName => bool).
69 protected $addedCoreResources = [];
74 * Format is ($regionName => bool).
78 protected $addedCoreStyles = [];
83 * Format is ($regionName => bool).
87 protected $addedSettings = [];
90 * A value to append to JS/CSS URLs to coerce cache resets.
94 protected $cacheCode = NULL;
97 * The name of a setting which persistently stores the cacheCode.
101 protected $cacheCodeKey = NULL;
104 * Are ajax popup screens enabled.
108 public $ajaxPopupsEnabled;
111 * @var \Civi\Core\Paths
116 * Get or set the single instance of CRM_Core_Resources.
118 * @param CRM_Core_Resources $instance
119 * New copy of the manager.
121 * @return CRM_Core_Resources
123 public static function singleton(CRM_Core_Resources
$instance = NULL) {
124 if ($instance !== NULL) {
125 self
::$_singleton = $instance;
127 if (self
::$_singleton === NULL) {
128 self
::$_singleton = Civi
::service('resources');
130 return self
::$_singleton;
134 * Construct a resource manager.
136 * @param CRM_Extension_Mapper $extMapper
137 * Map extension names to their base path or URLs.
138 * @param CRM_Utils_Cache_Interface $cache
139 * JS-localization cache.
140 * @param string|null $cacheCodeKey Random code to append to resource URLs; changing the code forces clients to reload resources
142 public function __construct($extMapper, $cache, $cacheCodeKey = NULL) {
143 $this->extMapper
= $extMapper;
144 $this->strings
= new CRM_Core_Resources_Strings($cache);
145 $this->cacheCodeKey
= $cacheCodeKey;
146 if ($cacheCodeKey !== NULL) {
147 $this->cacheCode
= Civi
::settings()->get($cacheCodeKey);
149 if (!$this->cacheCode
) {
150 $this->resetCacheCode();
152 $this->ajaxPopupsEnabled
= (bool) Civi
::settings()->get('ajaxPopupsEnabled');
153 $this->paths
= Civi
::paths();
157 * Export permission data to the client to enable smarter GUIs.
159 * Note: Application security stems from the server's enforcement
160 * of the security logic (e.g. in the API permissions). There's no way
161 * the client can use this info to make the app more secure; however,
162 * it can produce a better-tuned (non-broken) UI.
164 * @param array $permNames
165 * List of permission names to check/export.
166 * @return CRM_Core_Resources
168 public function addPermissions($permNames) {
169 $permNames = (array) $permNames;
171 foreach ($permNames as $permName) {
172 $perms[$permName] = CRM_Core_Permission
::check($permName);
174 return $this->addSetting([
175 'permissions' => $perms,
180 * Add a JavaScript file to the current page using <SCRIPT SRC>.
183 * extension name; use 'civicrm' for core.
184 * @param string $file
185 * file path -- relative to the extension base dir.
187 * relative weight within a given region.
188 * @param string $region
189 * location within the file; 'html-header', 'page-header', 'page-footer'.
190 * @param bool|string $translate
191 * Whether to load translated strings for this file. Use one of:
192 * - FALSE: Do not load translated strings.
193 * - TRUE: Load translated strings. Use the $ext's default domain.
194 * - string: Load translated strings. Use a specific domain.
196 * @return CRM_Core_Resources
198 * @throws \CRM_Core_Exception
200 public function addScriptFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
, $translate = TRUE) {
202 $domain = ($translate === TRUE) ?
$ext : $translate;
203 $this->addString($this->strings
->get($domain, $this->getPath($ext, $file), 'text/javascript'), $domain);
205 $url = $this->getUrl($ext, $this->filterMinify($ext, $file), TRUE);
206 return $this->addScriptUrl($url, $weight, $region);
210 * Add a JavaScript file to the current page using <SCRIPT SRC>.
214 * relative weight within a given region.
215 * @param string $region
216 * location within the file; 'html-header', 'page-header', 'page-footer'.
217 * @return CRM_Core_Resources
219 public function addScriptUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
220 CRM_Core_Region
::instance($region)->add([
222 'type' => 'scriptUrl',
231 * Add a JavaScript file to the current page using <SCRIPT SRC>.
233 * @param string $code
234 * JavaScript source code.
236 * relative weight within a given region.
237 * @param string $region
238 * location within the file; 'html-header', 'page-header', 'page-footer'.
239 * @return CRM_Core_Resources
241 public function addScript($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
242 CRM_Core_Region
::instance($region)->add([
243 // 'name' => automatic
253 * Add JavaScript variables to CRM.vars
257 * CRM_Core_Resources::singleton()->addVars('myNamespace', array('foo' => 'bar'));
258 * Access var from javascript:
259 * CRM.vars.myNamespace.foo // "bar"
261 * @see https://docs.civicrm.org/dev/en/latest/standards/javascript/
263 * @param string $nameSpace
264 * Usually the name of your extension.
266 * @param string $region
267 * The region to add settings to (eg. for payment processors usually billing-block)
269 * @return CRM_Core_Resources
271 public function addVars($nameSpace, $vars, $region = NULL) {
272 $existing = CRM_Utils_Array
::value($nameSpace, CRM_Utils_Array
::value('vars', $this->settings
), []);
273 $vars = $this->mergeSettings($existing, $vars);
274 $this->addSetting(['vars' => [$nameSpace => $vars]], $region);
279 * Add JavaScript variables to the root of the CRM object.
280 * This function is usually reserved for low-level system use.
281 * Extensions and components should generally use addVars instead.
283 * @param array $settings
284 * @param string $region
285 * The region to add settings to (eg. for payment processors usually billing-block)
287 * @return CRM_Core_Resources
289 public function addSetting($settings, $region = NULL) {
291 $region = self
::isAjaxMode() ?
'ajax-snippet' : 'html-header';
293 $this->settings
= $this->mergeSettings($this->settings
, $settings);
294 if (isset($this->addedSettings
[$region])) {
298 $settingsResource = [
299 'callback' => function (&$snippet, &$html) use ($resources, $region) {
300 $html .= "\n" . $resources->renderSetting($region);
304 CRM_Core_Region
::instance($region)->add($settingsResource);
305 $this->addedSettings
[$region] = TRUE;
310 * Add JavaScript variables to the global CRM object via a callback function.
312 * @param callable $callable
313 * @return CRM_Core_Resources
315 public function addSettingsFactory($callable) {
316 // Make sure our callback has been registered
317 $this->addSetting([]);
318 $this->settingsFactories
[] = $callable;
323 * Helper fn for addSettingsFactory.
325 public function getSettings() {
326 $result = $this->settings
;
327 foreach ($this->settingsFactories
as $callable) {
328 $result = $this->mergeSettings($result, $callable());
330 CRM_Utils_Hook
::alterResourceSettings($result);
335 * @param array $settings
336 * @param array $additions
338 * combination of $settings and $additions
340 protected function mergeSettings($settings, $additions) {
341 foreach ($additions as $k => $v) {
342 if (isset($settings[$k]) && is_array($settings[$k]) && is_array($v)) {
351 * Helper fn for addSetting.
352 * Render JavaScript variables for the global CRM object.
356 public function renderSetting($region = NULL) {
357 // On a standard page request we construct the CRM object from scratch
358 if (($region === 'html-header') ||
!self
::isAjaxMode()) {
359 $js = 'var CRM = ' . json_encode($this->getSettings()) . ';';
361 // For an ajax request we append to it
363 $js = 'CRM.$.extend(true, CRM, ' . json_encode($this->getSettings()) . ');';
365 return sprintf("<script type=\"text/javascript\">\n%s\n</script>\n", $js);
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
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
378 * CRM_Core_Resources::singleton()->addString('Hello');
379 * // The string is now available to javascript code i.e.
382 * Example with client-side substitutions:
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});
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
394 * @param string|array $text
395 * @param string|null $domain
396 * @return CRM_Core_Resources
398 public function addString($text, $domain = 'civicrm') {
399 foreach ((array) $text as $str) {
400 $translated = ts($str, [
401 'domain' => ($domain == 'civicrm') ?
NULL : [$domain, NULL],
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;
410 $bucket => [$str => $translated],
418 * Add a CSS file to the current page using <LINK HREF>.
421 * extension name; use 'civicrm' for core.
422 * @param string $file
423 * file path -- relative to the extension base dir.
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
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);
440 * Add a CSS file to the current page using <LINK HREF>.
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
449 public function addStyleUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
450 CRM_Core_Region
::instance($region)->add([
452 'type' => 'styleUrl',
461 * Add a CSS content to the current page using <STYLE>.
463 * @param string $code
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
471 public function addStyle($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
472 CRM_Core_Region
::instance($region)->add([
473 // 'name' => automatic
483 * Determine file path of a resource provided by an extension.
486 * extension name; use 'civicrm' for core.
487 * @param string|null $file
488 * file path -- relative to the extension base dir.
490 * @return bool|string
491 * full file path or FALSE if not found
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) {
501 $path = $base . '/' . $file;
502 if (is_file($path)) {
509 * Determine public URL of a resource provided by an extension.
512 * extension name; use 'civicrm' for core.
513 * @param string $file
514 * file path -- relative to the extension base dir.
515 * @param bool $addCacheCode
517 * @return string, URL
519 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
520 if ($file === NULL) {
524 $file = $this->addCacheCode($file);
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;
534 * Evaluate a glob pattern in the context of a particular extension.
537 * Extension name; use 'civicrm' for core.
538 * @param string|array $patterns
539 * Glob pattern; e.g. "*.html".
540 * @param null|int $flags
543 * List of matching files, relative to the extension base dir.
546 public function glob($ext, $patterns, $flags = NULL) {
547 $path = $this->getPath($ext);
548 $patterns = (array) $patterns;
550 foreach ($patterns as $pattern) {
551 if (preg_match(';^(assetBuilder|ext)://;', $pattern)) {
554 if (CRM_Utils_File
::isAbsolute($pattern)) {
556 $files = array_merge($files, (array) glob($pattern, $flags));
560 $files = array_merge($files, (array) glob("$path/$pattern", $flags));
563 // Deterministic order.
565 $files = array_unique($files);
566 return array_map(function ($file) use ($path) {
567 return CRM_Utils_File
::relativize($file, "$path/");
574 public function getCacheCode() {
575 return $this->cacheCode
;
580 * @return CRM_Core_Resources
582 public function setCacheCode($value) {
583 $this->cacheCode
= $value;
584 if ($this->cacheCodeKey
) {
585 Civi
::settings()->set($this->cacheCodeKey
, $value);
591 * @return CRM_Core_Resources
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();
601 * This adds CiviCRM's standard css and js to the specified region of the document.
602 * It will only run once.
604 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
605 * (like addCoreResources/addCoreStyles).
607 * @param string $region
608 * @return CRM_Core_Resources
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();
615 // Add resources from coreResourceList
617 foreach ($this->coreResourceList($region) as $item) {
618 if (is_array($item)) {
619 $this->addSetting($item);
621 elseif (strpos($item, '.css')) {
622 $this->isFullyFormedUrl($item) ?
$this->addStyleUrl($item, -100, $region) : $this->addStyleFile('civicrm', $item, -100, $region);
624 elseif ($this->isFullyFormedUrl($item)) {
625 $this->addScriptUrl($item, $jsWeight++
, $region);
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);
633 // Add global settings
636 'isFrontend' => $config->userFrameworkFrontend
,
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;
643 $this->addSetting($settings);
645 // Give control of jQuery and _ back to the CMS - this loads last
646 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
648 $this->addCoreStyles($region);
654 * This will add CiviCRM's standard CSS
656 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
657 * (like addCoreResources/addCoreStyles).
659 * @param string $region
660 * @return CRM_Core_Resources
662 public function addCoreStyles($region = 'html-header') {
663 if (!isset($this->addedCoreStyles
[$region])) {
664 $this->addedCoreStyles
[$region] = TRUE;
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);
672 if (!Civi
::settings()->get('disable_core_css')) {
673 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
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);
682 * Flushes cached translated strings.
683 * @return CRM_Core_Resources
685 public function flushStrings() {
686 $this->strings
->flush();
691 * @return CRM_Core_Resources_Strings
693 public function getStrings() {
694 return $this->strings
;
698 * Create dynamic script for localizing js widgets.
700 public static function outputLocalizationJS() {
701 CRM_Core_Page_AJAX
::setJsHeaders();
702 $config = CRM_Core_Config
::singleton();
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(),
714 print CRM_Core_Smarty
::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
715 CRM_Utils_System
::civiExit();
719 * List of core resources we add to every CiviCRM page.
721 * Note: non-compressed versions of .min files will be used in debug mode
723 * @param string $region
726 public function coreResourceList($region) {
727 $config = CRM_Core_Config
::singleton();
729 // Scripts needed by everyone, everywhere
730 // FIXME: This is too long; list needs finer-grained segmentation
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 "bower_components/jquery-validation/dist/additional-methods.min.js",
747 "packages/jquery/plugins/jquery.ui.datepicker.validation.min.js",
749 "js/crm.datepicker.js",
751 "js/wysiwyg/crm.wysiwyg.js",
754 // Dynamic localization script
755 $items[] = $this->addCacheCode(
756 CRM_Utils_System
::url('civicrm/ajax/l10n-js/' . CRM_Core_I18n
::getLocale(),
757 ['cid' => CRM_Core_Session
::getLoggedInContactID()], FALSE, NULL, FALSE)
760 // add wysiwyg editor
761 $editor = Civi
::settings()->get('editor_id');
762 if ($editor == "CKEditor") {
763 CRM_Admin_Page_CKEditorConfig
::setConfigDefault();
766 'wysisygScriptLocation' => Civi
::paths()->getUrl("[civicrm.root]/js/wysiwyg/crm.ckeditor.js"),
767 'CKEditorCustomConfig' => CRM_Admin_Page_CKEditorConfig
::getConfigUrl(),
772 // These scripts are only needed by back-office users
773 if (CRM_Core_Permission
::check('access CiviCRM')) {
774 $items[] = "packages/jquery/plugins/jquery.tableHeader.js";
775 $items[] = "packages/jquery/plugins/jquery.notify.min.js";
778 $contactID = CRM_Core_Session
::getLoggedInContactID();
783 $contactID && !$config->userFrameworkFrontend
784 && CRM_Core_Permission
::check('access CiviCRM')
785 && !@constant
('CIVICRM_DISABLE_DEFAULT_MENU')
786 && !CRM_Core_Config
::isUpgradeMode()
788 $position = Civi
::settings()->get('menubar_position') ?
: 'over-cms-menu';
790 if ($position !== 'none') {
791 $items[] = 'bower_components/smartmenus/dist/jquery.smartmenus.min.js';
792 $items[] = 'bower_components/smartmenus/dist/addons/keyboard/jquery.smartmenus.keyboard.min.js';
793 $items[] = 'js/crm.menubar.js';
794 // @see CRM_Core_Resources::renderMenubarStylesheet
795 $items[] = Civi
::service('asset_builder')->getUrl('crm-menubar.css', [
796 'menubarColor' => Civi
::settings()->get('menubar_color'),
800 // Variables for crm.menubar.js
803 'position' => $position,
804 'qfKey' => CRM_Core_Key
::get('CRM_Contact_Controller_Search', TRUE),
805 'cacheCode' => CRM_Core_BAO_Navigation
::getCacheKey($contactID),
810 // JS for multilingual installations
811 if (!empty($config->languageLimit
) && count($config->languageLimit
) > 1 && CRM_Core_Permission
::check('translate CiviCRM')) {
812 $items[] = "js/crm.multilingual.js";
815 // Enable administrators to edit option lists in a dialog
816 if (CRM_Core_Permission
::check('administer CiviCRM') && $this->ajaxPopupsEnabled
) {
817 $items[] = "js/crm.optionEdit.js";
820 $tsLocale = CRM_Core_I18n
::getLocale();
821 // Add localized jQuery UI files
822 if ($tsLocale && $tsLocale != 'en_US') {
823 // Search for i18n file in order of specificity (try fr-CA, then fr)
824 list($lang) = explode('_', $tsLocale);
825 $path = "bower_components/jquery-ui/ui/i18n";
826 foreach ([str_replace('_', '-', $tsLocale), $lang] as $language) {
827 $localizationFile = "$path/datepicker-{$language}.js";
828 if ($this->getPath('civicrm', $localizationFile)) {
829 $items[] = $localizationFile;
835 // Allow hooks to modify this list
836 CRM_Utils_Hook
::coreResourceList($items, $region);
838 // Oof, existing listeners would expect $items to typically begin with 'bower_components/' or 'packages/'
839 // (using an implicit base of `[civicrm.root]`). We preserve the hook contract and cleanup $items post-hook.
841 'bower_components' => rtrim(Civi
::paths()->getUrl('[civicrm.bower]/.', 'absolute'), '/'),
842 'packages' => rtrim(Civi
::paths()->getUrl('[civicrm.packages]/.', 'absolute'), '/'),
844 $filter = function($m) use ($map) {
845 return $map[$m[1]] . $m[2];
847 $items = array_map(function($item) use ($filter) {
848 return is_array($item) ?
$item : preg_replace_callback(';^(bower_components|packages)(/.*);', $filter, $item);
856 * is this page request an ajax snippet?
858 public static function isAjaxMode() {
859 if (in_array(CRM_Utils_Array
::value('snippet', $_REQUEST), [
860 CRM_Core_Smarty
::PRINT_SNIPPET
,
861 CRM_Core_Smarty
::PRINT_NOFORM
,
862 CRM_Core_Smarty
::PRINT_JSON
,
867 list($arg0, $arg1) = array_pad(explode('/', CRM_Utils_System
::currentPath()), 2, '');
868 return ($arg0 === 'civicrm' && in_array($arg1, ['ajax', 'angularprofiles', 'asset']));
872 * @param \Civi\Core\Event\GenericHookEvent $e
873 * @see \CRM_Utils_Hook::buildAsset()
875 public static function renderMenubarStylesheet(GenericHookEvent
$e) {
876 if ($e->asset
!== 'crm-menubar.css') {
879 $e->mimeType
= 'text/css';
881 $config = CRM_Core_Config
::singleton();
882 $cms = strtolower($config->userFramework
);
883 $cms = $cms === 'drupal' ?
'drupal7' : $cms;
885 'bower_components/smartmenus/dist/css/sm-core-css.css',
886 'css/crm-menubar.css',
887 "css/menubar-$cms.css",
889 foreach ($items as $item) {
890 $content .= file_get_contents(self
::singleton()->getPath('civicrm', $item));
892 $params = $e->params
;
893 // "color" is deprecated in favor of the more specific "menubarColor"
894 $menubarColor = $params['color'] ??
$params['menubarColor'];
896 '$resourceBase' => rtrim($config->resourceBase
, '/'),
897 '$menubarHeight' => $params['height'] . 'px',
898 '$breakMin' => $params['breakpoint'] . 'px',
899 '$breakMax' => ($params['breakpoint'] - 1) . 'px',
900 '$menubarColor' => $menubarColor,
901 '$menuItemColor' => $params['menuItemColor'] ??
$menubarColor,
902 '$highlightColor' => $params['highlightColor'] ?? CRM_Utils_Color
::getHighlight($menubarColor),
903 '$textColor' => $params['textColor'] ?? CRM_Utils_Color
::getContrast($menubarColor, '#333', '#ddd'),
905 $vars['$highlightTextColor'] = $params['highlightTextColor'] ?? CRM_Utils_Color
::getContrast($vars['$highlightColor'], '#333', '#ddd');
906 $e->content
= str_replace(array_keys($vars), array_values($vars), $content);
910 * Provide a list of available entityRef filters.
914 public static function getEntityRefMetadata() {
919 $config = CRM_Core_Config
::singleton();
921 $disabledComponents = [];
922 $dao = CRM_Core_DAO
::executeQuery("SELECT name, namespace FROM civicrm_component");
923 while ($dao->fetch()) {
924 if (!in_array($dao->name
, $config->enableComponents
)) {
925 $disabledComponents[$dao->name
] = $dao->namespace;
929 foreach (CRM_Core_DAO_AllCoreTables
::daoToClass() as $entity => $daoName) {
930 // Skip DAOs of disabled components
931 foreach ($disabledComponents as $nameSpace) {
932 if (strpos($daoName, $nameSpace) === 0) {
936 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
937 if (class_exists($baoName)) {
938 $filters = $baoName::getEntityRefFilters();
940 $data['filters'][$entity] = $filters;
942 if (is_callable([$baoName, 'getEntityRefCreateLinks'])) {
943 $createLinks = $baoName::getEntityRefCreateLinks();
945 $data['links'][$entity] = $createLinks;
951 CRM_Utils_Hook
::entityRefFilters($data['filters'], $data['links']);
957 * Determine the minified file name.
960 * @param string $file
962 * An updated $fileName. If a minified version exists and is supported by
963 * system policy, the minified version will be returned. Otherwise, the original.
965 public function filterMinify($ext, $file) {
966 if (CRM_Core_Config
::singleton()->debug
&& strpos($file, '.min.') !== FALSE) {
967 $nonMiniFile = str_replace('.min.', '.', $file);
968 if ($this->getPath($ext, $nonMiniFile)) {
969 $file = $nonMiniFile;
979 public function addCacheCode($url) {
980 $hasQuery = strpos($url, '?') !== FALSE;
981 $operator = $hasQuery ?
'&' : '?';
983 return $url . $operator . 'r=' . $this->cacheCode
;
987 * Checks if the given URL is fully-formed
993 public static function isFullyFormedUrl($url) {
994 return (substr($url, 0, 4) === 'http') ||
(substr($url, 0, 1) === '/');