3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
27 use Civi\Core\Event\GenericHookEvent
;
30 * This class facilitates the loading of resources
31 * such as JavaScript files and CSS files.
33 * Any URLs generated for resources may include a 'cache-code'. By resetting the
34 * cache-code, one may force clients to re-download resource files (regardless of
35 * any HTTP caching rules).
37 * TODO: This is currently a thin wrapper over CRM_Core_Region. We
38 * should incorporte services for aggregation, minimization, etc.
41 * @copyright CiviCRM LLC (c) 2004-2019
45 class CRM_Core_Resources
{
46 const DEFAULT_WEIGHT
= 0;
47 const DEFAULT_REGION
= 'page-footer';
50 * We don't have a container or dependency-injection, so use singleton instead
54 private static $_singleton = NULL;
57 * @var CRM_Extension_Mapper
59 private $extMapper = NULL;
62 * @var CRM_Core_Resources_Strings
64 private $strings = NULL;
67 * Settings in free-form data tree.
71 protected $settings = [];
72 protected $addedSettings = FALSE;
79 protected $settingsFactories = [];
82 * Added core resources.
84 * Format is ($regionName => bool).
88 protected $addedCoreResources = [];
93 * Format is ($regionName => bool).
97 protected $addedCoreStyles = [];
100 * A value to append to JS/CSS URLs to coerce cache resets.
104 protected $cacheCode = NULL;
107 * The name of a setting which persistently stores the cacheCode.
111 protected $cacheCodeKey = NULL;
114 * Are ajax popup screens enabled.
118 public $ajaxPopupsEnabled;
121 * @var \Civi\Core\Paths
126 * Get or set the single instance of CRM_Core_Resources.
128 * @param CRM_Core_Resources $instance
129 * New copy of the manager.
131 * @return CRM_Core_Resources
133 public static function singleton(CRM_Core_Resources
$instance = NULL) {
134 if ($instance !== NULL) {
135 self
::$_singleton = $instance;
137 if (self
::$_singleton === NULL) {
138 self
::$_singleton = Civi
::service('resources');
140 return self
::$_singleton;
144 * Construct a resource manager.
146 * @param CRM_Extension_Mapper $extMapper
147 * Map extension names to their base path or URLs.
148 * @param CRM_Utils_Cache_Interface $cache
149 * JS-localization cache.
150 * @param string|null $cacheCodeKey Random code to append to resource URLs; changing the code forces clients to reload resources
152 public function __construct($extMapper, $cache, $cacheCodeKey = NULL) {
153 $this->extMapper
= $extMapper;
154 $this->strings
= new CRM_Core_Resources_Strings($cache);
155 $this->cacheCodeKey
= $cacheCodeKey;
156 if ($cacheCodeKey !== NULL) {
157 $this->cacheCode
= Civi
::settings()->get($cacheCodeKey);
159 if (!$this->cacheCode
) {
160 $this->resetCacheCode();
162 $this->ajaxPopupsEnabled
= (bool) Civi
::settings()->get('ajaxPopupsEnabled');
163 $this->paths
= Civi
::paths();
167 * Export permission data to the client to enable smarter GUIs.
169 * Note: Application security stems from the server's enforcement
170 * of the security logic (e.g. in the API permissions). There's no way
171 * the client can use this info to make the app more secure; however,
172 * it can produce a better-tuned (non-broken) UI.
174 * @param array $permNames
175 * List of permission names to check/export.
176 * @return CRM_Core_Resources
178 public function addPermissions($permNames) {
179 $permNames = (array) $permNames;
181 foreach ($permNames as $permName) {
182 $perms[$permName] = CRM_Core_Permission
::check($permName);
184 return $this->addSetting([
185 'permissions' => $perms,
190 * Add a JavaScript file to the current page using <SCRIPT SRC>.
193 * extension name; use 'civicrm' for core.
194 * @param string $file
195 * file path -- relative to the extension base dir.
197 * relative weight within a given region.
198 * @param string $region
199 * location within the file; 'html-header', 'page-header', 'page-footer'.
200 * @param bool|string $translate
201 * Whether to load translated strings for this file. Use one of:
202 * - FALSE: Do not load translated strings.
203 * - TRUE: Load translated strings. Use the $ext's default domain.
204 * - string: Load translated strings. Use a specific domain.
206 * @return CRM_Core_Resources
209 public function addScriptFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
, $translate = TRUE) {
211 $domain = ($translate === TRUE) ?
$ext : $translate;
212 $this->addString($this->strings
->get($domain, $this->getPath($ext, $file), 'text/javascript'), $domain);
214 $url = $this->getUrl($ext, $this->filterMinify($ext, $file), TRUE);
215 return $this->addScriptUrl($url, $weight, $region);
219 * Add a JavaScript file to the current page using <SCRIPT SRC>.
223 * relative weight within a given region.
224 * @param string $region
225 * location within the file; 'html-header', 'page-header', 'page-footer'.
226 * @return CRM_Core_Resources
228 public function addScriptUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
229 CRM_Core_Region
::instance($region)->add([
231 'type' => 'scriptUrl',
240 * Add a JavaScript file to the current page using <SCRIPT SRC>.
242 * @param string $code
243 * JavaScript source code.
245 * relative weight within a given region.
246 * @param string $region
247 * location within the file; 'html-header', 'page-header', 'page-footer'.
248 * @return CRM_Core_Resources
250 public function addScript($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
251 CRM_Core_Region
::instance($region)->add([
252 // 'name' => automatic
262 * Add JavaScript variables to CRM.vars
266 * CRM_Core_Resources::singleton()->addVars('myNamespace', array('foo' => 'bar'));
267 * Access var from javascript:
268 * CRM.vars.myNamespace.foo // "bar"
270 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Javascript+Reference
272 * @param string $nameSpace
273 * Usually the name of your extension.
275 * @return CRM_Core_Resources
277 public function addVars($nameSpace, $vars) {
278 $existing = CRM_Utils_Array
::value($nameSpace, CRM_Utils_Array
::value('vars', $this->settings
), []);
279 $vars = $this->mergeSettings($existing, $vars);
280 $this->addSetting(['vars' => [$nameSpace => $vars]]);
285 * Add JavaScript variables to the root of the CRM object.
286 * This function is usually reserved for low-level system use.
287 * Extensions and components should generally use addVars instead.
289 * @param array $settings
290 * @return CRM_Core_Resources
292 public function addSetting($settings) {
293 $this->settings
= $this->mergeSettings($this->settings
, $settings);
294 if (!$this->addedSettings
) {
295 $region = self
::isAjaxMode() ?
'ajax-snippet' : 'html-header';
297 CRM_Core_Region
::instance($region)->add([
298 'callback' => function (&$snippet, &$html) use ($resources) {
299 $html .= "\n" . $resources->renderSetting();
303 $this->addedSettings
= TRUE;
309 * Add JavaScript variables to the global CRM object via a callback function.
311 * @param callable $callable
312 * @return CRM_Core_Resources
314 public function addSettingsFactory($callable) {
315 // Make sure our callback has been registered
316 $this->addSetting([]);
317 $this->settingsFactories
[] = $callable;
322 * Helper fn for addSettingsFactory.
324 public function getSettings() {
325 $result = $this->settings
;
326 foreach ($this->settingsFactories
as $callable) {
327 $result = $this->mergeSettings($result, $callable());
329 CRM_Utils_Hook
::alterResourceSettings($result);
334 * @param array $settings
335 * @param array $additions
337 * combination of $settings and $additions
339 protected function mergeSettings($settings, $additions) {
340 foreach ($additions as $k => $v) {
341 if (isset($settings[$k]) && is_array($settings[$k]) && is_array($v)) {
350 * Helper fn for addSetting.
351 * Render JavaScript variables for the global CRM object.
355 public function renderSetting() {
356 // On a standard page request we construct the CRM object from scratch
357 if (!self
::isAjaxMode()) {
358 $js = 'var CRM = ' . json_encode($this->getSettings()) . ';';
360 // For an ajax request we append to it
362 $js = 'CRM.$.extend(true, CRM, ' . json_encode($this->getSettings()) . ');';
364 return sprintf("<script type=\"text/javascript\">\n%s\n</script>\n", $js);
368 * Add translated string to the js CRM object.
369 * It can then be retrived from the client-side ts() function
370 * Variable substitutions can happen from client-side
372 * Note: this function rarely needs to be called directly and is mostly for internal use.
373 * See CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
377 * CRM_Core_Resources::singleton()->addString('Hello');
378 * // The string is now available to javascript code i.e.
381 * Example with client-side substitutions:
383 * CRM_Core_Resources::singleton()->addString('Your %1 has been %2');
384 * // ts() in javascript works the same as in php, for example:
385 * ts('Your %1 has been %2', {1: objectName, 2: actionTaken});
387 * NOTE: This function does not work with server-side substitutions
388 * (as this might result in collisions and unwanted variable injections)
389 * Instead, use code like:
390 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs)))));
391 * And from javascript access it at CRM.myNamespace.myString
393 * @param string|array $text
394 * @param string|null $domain
395 * @return CRM_Core_Resources
397 public function addString($text, $domain = 'civicrm') {
398 foreach ((array) $text as $str) {
399 $translated = ts($str, [
400 'domain' => ($domain == 'civicrm') ?
NULL : [$domain, NULL],
404 // We only need to push this string to client if the translation
405 // is actually different from the original
406 if ($translated != $str) {
407 $bucket = $domain == 'civicrm' ?
'strings' : 'strings::' . $domain;
409 $bucket => [$str => $translated],
417 * Add a CSS file to the current page using <LINK HREF>.
420 * extension name; use 'civicrm' for core.
421 * @param string $file
422 * file path -- relative to the extension base dir.
424 * relative weight within a given region.
425 * @param string $region
426 * location within the file; 'html-header', 'page-header', 'page-footer'.
427 * @return CRM_Core_Resources
429 public function addStyleFile($ext, $file, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
430 /** @var Civi\Core\Themes $theme */
431 $theme = Civi
::service('themes');
432 foreach ($theme->resolveUrls($theme->getActiveThemeKey(), $ext, $file) as $url) {
433 $this->addStyleUrl($url, $weight, $region);
439 * Add a CSS file to the current page using <LINK HREF>.
443 * relative weight within a given region.
444 * @param string $region
445 * location within the file; 'html-header', 'page-header', 'page-footer'.
446 * @return CRM_Core_Resources
448 public function addStyleUrl($url, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
449 CRM_Core_Region
::instance($region)->add([
451 'type' => 'styleUrl',
460 * Add a CSS content to the current page using <STYLE>.
462 * @param string $code
465 * relative weight within a given region.
466 * @param string $region
467 * location within the file; 'html-header', 'page-header', 'page-footer'.
468 * @return CRM_Core_Resources
470 public function addStyle($code, $weight = self
::DEFAULT_WEIGHT
, $region = self
::DEFAULT_REGION
) {
471 CRM_Core_Region
::instance($region)->add([
472 // 'name' => automatic
482 * Determine file path of a resource provided by an extension.
485 * extension name; use 'civicrm' for core.
486 * @param string|null $file
487 * file path -- relative to the extension base dir.
489 * @return bool|string
490 * full file path or FALSE if not found
492 public function getPath($ext, $file = NULL) {
493 // TODO consider caching results
494 $base = $this->paths
->hasVariable($ext)
495 ?
rtrim($this->paths
->getVariable($ext, 'path'), '/')
496 : $this->extMapper
->keyToBasePath($ext);
497 if ($file === NULL) {
500 $path = $base . '/' . $file;
501 if (is_file($path)) {
508 * Determine public URL of a resource provided by an extension.
511 * extension name; use 'civicrm' for core.
512 * @param string $file
513 * file path -- relative to the extension base dir.
514 * @param bool $addCacheCode
516 * @return string, URL
518 public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
519 if ($file === NULL) {
523 $file = $this->addCacheCode($file);
525 // TODO consider caching results
526 $base = $this->paths
->hasVariable($ext)
527 ?
$this->paths
->getVariable($ext, 'url')
528 : ($this->extMapper
->keyToUrl($ext) . '/');
529 return $base . $file;
533 * Evaluate a glob pattern in the context of a particular extension.
536 * Extension name; use 'civicrm' for core.
537 * @param string|array $patterns
538 * Glob pattern; e.g. "*.html".
539 * @param null|int $flags
542 * List of matching files, relative to the extension base dir.
545 public function glob($ext, $patterns, $flags = NULL) {
546 $path = $this->getPath($ext);
547 $patterns = (array) $patterns;
549 foreach ($patterns as $pattern) {
550 if (preg_match(';^(assetBuilder|ext)://;', $pattern)) {
553 if (CRM_Utils_File
::isAbsolute($pattern)) {
555 $files = array_merge($files, (array) glob($pattern, $flags));
559 $files = array_merge($files, (array) glob("$path/$pattern", $flags));
562 // Deterministic order.
564 $files = array_unique($files);
565 return array_map(function ($file) use ($path) {
566 return CRM_Utils_File
::relativize($file, "$path/");
573 public function getCacheCode() {
574 return $this->cacheCode
;
579 * @return CRM_Core_Resources
581 public function setCacheCode($value) {
582 $this->cacheCode
= $value;
583 if ($this->cacheCodeKey
) {
584 Civi
::settings()->set($this->cacheCodeKey
, $value);
590 * @return CRM_Core_Resources
592 public function resetCacheCode() {
593 $this->setCacheCode(CRM_Utils_String
::createRandom(5, CRM_Utils_String
::ALPHANUMERIC
));
594 // Also flush cms resource cache if needed
595 CRM_Core_Config
::singleton()->userSystem
->clearResourceCache();
600 * This adds CiviCRM's standard css and js to the specified region of the document.
601 * It will only run once.
603 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
604 * (like addCoreResources/addCoreStyles).
606 * @param string $region
607 * @return CRM_Core_Resources
609 public function addCoreResources($region = 'html-header') {
610 if (!isset($this->addedCoreResources
[$region]) && !self
::isAjaxMode()) {
611 $this->addedCoreResources
[$region] = TRUE;
612 $config = CRM_Core_Config
::singleton();
614 // Add resources from coreResourceList
616 foreach ($this->coreResourceList($region) as $item) {
617 if (is_array($item)) {
618 $this->addSetting($item);
620 elseif (strpos($item, '.css')) {
621 $this->isFullyFormedUrl($item) ?
$this->addStyleUrl($item, -100, $region) : $this->addStyleFile('civicrm', $item, -100, $region);
623 elseif ($this->isFullyFormedUrl($item)) {
624 $this->addScriptUrl($item, $jsWeight++
, $region);
627 // Don't bother looking for ts() calls in packages, there aren't any
628 $translate = (substr($item, 0, 3) == 'js/');
629 $this->addScriptFile('civicrm', $item, $jsWeight++
, $region, $translate);
632 // Add global settings
635 'isFrontend' => $config->userFrameworkFrontend
,
638 // Disable profile creation if user lacks permission
639 if (!CRM_Core_Permission
::check('edit all contacts') && !CRM_Core_Permission
::check('add contacts')) {
640 $settings['config']['entityRef']['contactCreate'] = FALSE;
642 $this->addSetting($settings);
644 // Give control of jQuery and _ back to the CMS - this loads last
645 $this->addScriptFile('civicrm', 'js/noconflict.js', 9999, $region, FALSE);
647 $this->addCoreStyles($region);
653 * This will add CiviCRM's standard CSS
655 * TODO: Separate the functional code (like addStyle/addScript) from the policy code
656 * (like addCoreResources/addCoreStyles).
658 * @param string $region
659 * @return CRM_Core_Resources
661 public function addCoreStyles($region = 'html-header') {
662 if (!isset($this->addedCoreStyles
[$region])) {
663 $this->addedCoreStyles
[$region] = TRUE;
665 // Load custom or core css
666 $config = CRM_Core_Config
::singleton();
667 if (!empty($config->customCSSURL
)) {
668 $customCSSURL = $this->addCacheCode($config->customCSSURL
);
669 $this->addStyleUrl($customCSSURL, 99, $region);
671 if (!Civi
::settings()->get('disable_core_css')) {
672 $this->addStyleFile('civicrm', 'css/civicrm.css', -99, $region);
674 // crm-i.css added ahead of other styles so it can be overridden by FA.
675 $this->addStyleFile('civicrm', 'css/crm-i.css', -101, $region);
681 * Flushes cached translated strings.
682 * @return CRM_Core_Resources
684 public function flushStrings() {
685 $this->strings
->flush();
690 * @return CRM_Core_Resources_Strings
692 public function getStrings() {
693 return $this->strings
;
697 * Create dynamic script for localizing js widgets.
699 public static function outputLocalizationJS() {
700 CRM_Core_Page_AJAX
::setJsHeaders();
701 $config = CRM_Core_Config
::singleton();
703 'moneyFormat' => json_encode(CRM_Utils_Money
::format(1234.56)),
704 'contactSearch' => json_encode($config->includeEmailInName ?
ts('Start typing a name or email...') : ts('Start typing a name...')),
705 'otherSearch' => json_encode(ts('Enter search term...')),
706 'entityRef' => self
::getEntityRefMetadata(),
707 'ajaxPopupsEnabled' => self
::singleton()->ajaxPopupsEnabled
,
708 'allowAlertAutodismissal' => (bool) Civi
::settings()->get('allow_alert_autodismissal'),
709 'resourceCacheCode' => self
::singleton()->getCacheCode(),
710 'locale' => CRM_Core_I18n
::getLocale(),
711 'cid' => (int) CRM_Core_Session
::getLoggedInContactID(),
713 print CRM_Core_Smarty
::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
714 CRM_Utils_System
::civiExit();
718 * List of core resources we add to every CiviCRM page.
720 * Note: non-compressed versions of .min files will be used in debug mode
722 * @param string $region
725 public function coreResourceList($region) {
726 $config = CRM_Core_Config
::singleton();
728 // Scripts needed by everyone, everywhere
729 // FIXME: This is too long; list needs finer-grained segmentation
731 "bower_components/jquery/dist/jquery.min.js",
732 "bower_components/jquery-ui/jquery-ui.min.js",
733 "bower_components/jquery-ui/themes/smoothness/jquery-ui.min.css",
734 "bower_components/lodash-compat/lodash.min.js",
735 "packages/jquery/plugins/jquery.mousewheel.min.js",
736 "bower_components/select2/select2.min.js",
737 "bower_components/select2/select2.min.css",
738 "bower_components/font-awesome/css/font-awesome.min.css",
739 "packages/jquery/plugins/jquery.form.min.js",
740 "packages/jquery/plugins/jquery.timeentry.min.js",
741 "packages/jquery/plugins/jquery.blockUI.min.js",
742 "bower_components/datatables/media/js/jquery.dataTables.min.js",
743 "bower_components/datatables/media/css/jquery.dataTables.min.css",
744 "bower_components/jquery-validation/dist/jquery.validate.min.js",
745 "packages/jquery/plugins/jquery.ui.datepicker.validation.min.js",
747 "js/crm.datepicker.js",
749 "js/wysiwyg/crm.wysiwyg.js",
752 // Dynamic localization script
753 $items[] = $this->addCacheCode(
754 CRM_Utils_System
::url('civicrm/ajax/l10n-js/' . CRM_Core_I18n
::getLocale(),
755 ['cid' => CRM_Core_Session
::getLoggedInContactID()], FALSE, NULL, FALSE)
758 // add wysiwyg editor
759 $editor = Civi
::settings()->get('editor_id');
760 if ($editor == "CKEditor") {
761 CRM_Admin_Page_CKEditorConfig
::setConfigDefault();
764 'wysisygScriptLocation' => Civi
::paths()->getUrl("[civicrm.root]/js/wysiwyg/crm.ckeditor.js"),
765 'CKEditorCustomConfig' => CRM_Admin_Page_CKEditorConfig
::getConfigUrl(),
770 // These scripts are only needed by back-office users
771 if (CRM_Core_Permission
::check('access CiviCRM')) {
772 $items[] = "packages/jquery/plugins/jquery.tableHeader.js";
773 $items[] = "packages/jquery/plugins/jquery.notify.min.js";
776 $contactID = CRM_Core_Session
::getLoggedInContactID();
781 $contactID && !$config->userFrameworkFrontend
782 && CRM_Core_Permission
::check('access CiviCRM')
783 && !@constant
('CIVICRM_DISABLE_DEFAULT_MENU')
784 && !CRM_Core_Config
::isUpgradeMode()
786 $position = Civi
::settings()->get('menubar_position') ?
: 'over-cms-menu';
788 if ($position !== 'none') {
789 $items[] = 'bower_components/smartmenus/dist/jquery.smartmenus.min.js';
790 $items[] = 'bower_components/smartmenus/dist/addons/keyboard/jquery.smartmenus.keyboard.min.js';
791 $items[] = 'js/crm.menubar.js';
792 // @see CRM_Core_Resources::renderMenubarStylesheet
793 $items[] = Civi
::service('asset_builder')->getUrl('crm-menubar.css', [
794 'menubarColor' => Civi
::settings()->get('menubar_color'),
798 // Variables for crm.menubar.js
801 'position' => $position,
802 'qfKey' => CRM_Core_Key
::get('CRM_Contact_Controller_Search', TRUE),
803 'cacheCode' => CRM_Core_BAO_Navigation
::getCacheKey($contactID),
808 // JS for multilingual installations
809 if (!empty($config->languageLimit
) && count($config->languageLimit
) > 1 && CRM_Core_Permission
::check('translate CiviCRM')) {
810 $items[] = "js/crm.multilingual.js";
813 // Enable administrators to edit option lists in a dialog
814 if (CRM_Core_Permission
::check('administer CiviCRM') && $this->ajaxPopupsEnabled
) {
815 $items[] = "js/crm.optionEdit.js";
818 $tsLocale = CRM_Core_I18n
::getLocale();
819 // Add localized jQuery UI files
820 if ($tsLocale && $tsLocale != 'en_US') {
821 // Search for i18n file in order of specificity (try fr-CA, then fr)
822 list($lang) = explode('_', $tsLocale);
823 $path = "bower_components/jquery-ui/ui/i18n";
824 foreach ([str_replace('_', '-', $tsLocale), $lang] as $language) {
825 $localizationFile = "$path/datepicker-{$language}.js";
826 if ($this->getPath('civicrm', $localizationFile)) {
827 $items[] = $localizationFile;
833 // Allow hooks to modify this list
834 CRM_Utils_Hook
::coreResourceList($items, $region);
841 * is this page request an ajax snippet?
843 public static function isAjaxMode() {
844 if (in_array(CRM_Utils_Array
::value('snippet', $_REQUEST), [
845 CRM_Core_Smarty
::PRINT_SNIPPET
,
846 CRM_Core_Smarty
::PRINT_NOFORM
,
847 CRM_Core_Smarty
::PRINT_JSON
,
852 list($arg0, $arg1) = array_pad(explode('/', CRM_Utils_System
::getUrlPath()), 2, '');
853 return ($arg0 === 'civicrm' && in_array($arg1, ['ajax', 'angularprofiles', 'asset']));
857 * @param \Civi\Core\Event\GenericHookEvent $e
858 * @see \CRM_Utils_Hook::buildAsset()
860 public static function renderMenubarStylesheet(GenericHookEvent
$e) {
861 if ($e->asset
!== 'crm-menubar.css') {
864 $e->mimeType
= 'text/css';
866 $config = CRM_Core_Config
::singleton();
867 $cms = strtolower($config->userFramework
);
868 $cms = $cms === 'drupal' ?
'drupal7' : $cms;
870 'bower_components/smartmenus/dist/css/sm-core-css.css',
871 'css/crm-menubar.css',
872 "css/menubar-$cms.css",
874 foreach ($items as $item) {
875 $content .= file_get_contents(self
::singleton()->getPath('civicrm', $item));
877 $params = $e->params
;
878 // "color" is deprecated in favor of the more specific "menubarColor"
879 $menubarColor = $params['color'] ??
$params['menubarColor'];
881 '$resourceBase' => rtrim($config->resourceBase
, '/'),
882 '$menubarHeight' => $params['height'] . 'px',
883 '$breakMin' => $params['breakpoint'] . 'px',
884 '$breakMax' => ($params['breakpoint'] - 1) . 'px',
885 '$menubarColor' => $menubarColor,
886 '$menuItemColor' => $params['menuItemColor'] ??
'rgba(' . implode(', ', CRM_Utils_Color
::getRgb($menubarColor)) . ", .9)",
887 '$highlightColor' => $params['highlightColor'] ?? CRM_Utils_Color
::getHighlight($menubarColor),
888 '$textColor' => $params['textColor'] ?? CRM_Utils_Color
::getContrast($menubarColor, '#333', '#ddd'),
890 $vars['$highlightTextColor'] = $params['highlightTextColor'] ?? CRM_Utils_Color
::getContrast($vars['$highlightColor'], '#333', '#ddd');
891 $e->content
= str_replace(array_keys($vars), array_values($vars), $content);
895 * Provide a list of available entityRef filters.
899 public static function getEntityRefMetadata() {
904 $config = CRM_Core_Config
::singleton();
906 $disabledComponents = [];
907 $dao = CRM_Core_DAO
::executeQuery("SELECT name, namespace FROM civicrm_component");
908 while ($dao->fetch()) {
909 if (!in_array($dao->name
, $config->enableComponents
)) {
910 $disabledComponents[$dao->name
] = $dao->namespace;
914 foreach (CRM_Core_DAO_AllCoreTables
::daoToClass() as $entity => $daoName) {
915 // Skip DAOs of disabled components
916 foreach ($disabledComponents as $nameSpace) {
917 if (strpos($daoName, $nameSpace) === 0) {
921 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
922 if (class_exists($baoName)) {
923 $filters = $baoName::getEntityRefFilters();
925 $data['filters'][$entity] = $filters;
927 if (is_callable([$baoName, 'getEntityRefCreateLinks'])) {
928 $createLinks = $baoName::getEntityRefCreateLinks();
930 $data['links'][$entity] = $createLinks;
936 CRM_Utils_Hook
::entityRefFilters($data['filters']);
942 * Determine the minified file name.
945 * @param string $file
947 * An updated $fileName. If a minified version exists and is supported by
948 * system policy, the minified version will be returned. Otherwise, the original.
950 public function filterMinify($ext, $file) {
951 if (CRM_Core_Config
::singleton()->debug
&& strpos($file, '.min.') !== FALSE) {
952 $nonMiniFile = str_replace('.min.', '.', $file);
953 if ($this->getPath($ext, $nonMiniFile)) {
954 $file = $nonMiniFile;
964 public function addCacheCode($url) {
965 $hasQuery = strpos($url, '?') !== FALSE;
966 $operator = $hasQuery ?
'&' : '?';
968 return $url . $operator . 'r=' . $this->cacheCode
;
972 * Checks if the given URL is fully-formed
978 public static function isFullyFormedUrl($url) {
979 return (substr($url, 0, 4) === 'http') ||
(substr($url, 0, 1) === '/');