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 +--------------------------------------------------------------------+
13 * This file contains the various menus of the CiviCRM module
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
20 * Class CRM_Core_Menu.
25 * The list of menu items.
29 public static $_items = NULL;
32 * The list of permissioned menu items.
36 public static $_permissionedItems = NULL;
38 public static $_serializedElements = [
46 public static $_menuCache = NULL;
50 * This function fetches the menu items from xml and xmlMenu hooks.
52 * @param bool $fetchFromXML
53 * Fetch the menu items from xml and not from cache.
57 public static function &xmlItems($fetchFromXML = FALSE) {
58 if (!self
::$_items ||
$fetchFromXML) {
59 // We needs this until Core becomes a component
60 $coreMenuFilesNamespace = 'CRM_Core_xml_Menu';
61 $coreMenuFilesPath = str_replace('_', DIRECTORY_SEPARATOR
, $coreMenuFilesNamespace);
63 $files = CRM_Utils_File
::getFilesByExtension($civicrm_root . DIRECTORY_SEPARATOR
. $coreMenuFilesPath, 'xml');
65 // Grab component menu files
66 $files = array_merge($files,
67 CRM_Core_Component
::xmlMenu()
70 // lets call a hook and get any additional files if needed
71 CRM_Utils_Hook
::xmlMenu($files);
74 foreach ($files as $file) {
75 self
::read($file, self
::$_items);
78 CRM_Utils_Hook
::alterMenu(self
::$_items);
90 * An alterable list of menu items.
94 public static function read($name, &$menu) {
95 $xml = simplexml_load_string(file_get_contents($name));
96 self
::readXML($xml, $menu);
100 * @param SimpleXMLElement $xml
101 * An XML document defining a list of menu items.
103 * An alterable list of menu items.
105 * @throws CRM_Core_Exception
107 public static function readXML($xml, &$menu) {
108 $config = CRM_Core_Config
::singleton();
109 foreach ($xml->item
as $item) {
110 if (!(string ) $item->path
) {
111 CRM_Core_Error
::debug('i', $item);
112 throw new CRM_Core_Exception('Unable to read XML file');
114 $path = (string ) $item->path
;
118 if ($item->ids_arguments
) {
120 foreach (['json' => 'json', 'html' => 'html', 'exception' => 'exceptions'] as $tag => $attr) {
122 foreach ($item->ids_arguments
->{$tag} as $value) {
123 $ids[$attr][] = (string) $value;
126 $menu[$path]['ids_arguments'] = $ids;
127 unset($item->ids_arguments
);
130 foreach ($item as $key => $value) {
131 $key = (string ) $key;
132 $value = (string ) $value;
133 if (strpos($key, '_callback') &&
136 // FIXME Remove the rewrite at this level. Instead, change downstream call_user_func*($value)
137 // to call_user_func*(Civi\Core\Resolver::singleton()->get($value)).
138 $value = explode('::', $value);
140 elseif ($key == 'access_arguments') {
141 // FIXME Move the permission parser to its own class (or *maybe* CRM_Core_Permission).
142 if (strpos($value, ',') ||
145 if (strpos($value, ',')) {
146 $elements = explode(',', $value);
150 $elements = explode(';', $value);
154 foreach ($elements as $element) {
157 $value = [$items, $op];
160 $value = [[$value], 'and'];
163 elseif ($key == 'is_public' ||
$key == 'is_ssl') {
164 $value = ($value == 'true' ||
$value == 1) ?
1 : 0;
166 $menu[$path][$key] = $value;
172 * This function defines information for various menu items.
174 * @param bool $fetchFromXML
175 * Fetch the menu items from xml and not from cache.
179 public static function &items($fetchFromXML = FALSE) {
180 return self
::xmlItems($fetchFromXML);
184 * Is array true (whatever that means!).
186 * @param array $values
190 public static function isArrayTrue($values) {
191 foreach ($values as $value) {
203 * @param string $path
205 * @throws CRM_Core_Exception
207 public static function fillMenuValues(&$menu, $path) {
208 $fieldsToPropagate = [
216 foreach ($fieldsToPropagate as $field) {
217 $fieldsPresent[$field] = isset($menu[$path][$field]);
220 $args = explode('/', $path);
221 while (!self
::isArrayTrue($fieldsPresent) && !empty($args)) {
224 $parentPath = implode('/', $args);
226 foreach ($fieldsToPropagate as $field) {
227 if (!$fieldsPresent[$field]) {
228 $fieldInParentMenu = $menu[$parentPath][$field] ??
NULL;
229 if ($fieldInParentMenu !== NULL) {
230 $fieldsPresent[$field] = TRUE;
231 $menu[$path][$field] = $fieldInParentMenu;
237 if (self
::isArrayTrue($fieldsPresent)) {
242 foreach ($fieldsToPropagate as $field) {
243 if (!$fieldsPresent[$field]) {
244 $messages[] = ts("Could not find %1 in path tree",
249 throw new CRM_Core_Exception("'$path': " . implode(', ', $messages));
253 * We use this function to.
255 * 1. Compute the breadcrumb
256 * 2. Compute local tasks value if any
257 * 3. Propagate access argument, access callback, page callback to the menu item
258 * 4. Build the global navigation block
262 public static function build(&$menu) {
263 foreach ($menu as $path => $menuItems) {
265 self
::buildBreadcrumb($menu, $path);
266 self
::fillMenuValues($menu, $path);
267 self
::fillComponentIds($menu, $path);
268 self
::buildReturnUrl($menu, $path);
270 // add add page_type if not present
271 if (!isset($menu[$path]['page_type'])) {
272 $menu[$path]['page_type'] = 0;
275 catch (CRM_Core_Exception
$e) {
276 Civi
::log()->error('Menu path skipped:' . $e->getMessage());
280 self
::buildAdminLinks($menu);
284 * This function recomputes menu from xml and populates civicrm_menu.
286 * @param bool $truncate
288 public static function store($truncate = TRUE) {
289 // first clean up the db
291 $query = 'TRUNCATE civicrm_menu';
292 CRM_Core_DAO
::executeQuery($query);
294 $menuArray = self
::items($truncate);
296 self
::build($menuArray);
298 $daoFields = CRM_Core_DAO_Menu
::fields();
300 foreach ($menuArray as $path => $item) {
301 $menu = new CRM_Core_DAO_Menu();
303 $menu->domain_id
= CRM_Core_Config
::domainID();
307 if (!CRM_Core_Config
::isUpgradeMode() ||
308 CRM_Core_BAO_SchemaHandler
::checkIfFieldExists('civicrm_menu', 'module_data', FALSE)
310 // Move unrecognized fields to $module_data.
312 foreach (array_keys($item) as $key) {
313 if (!isset($daoFields[$key])) {
314 $module_data[$key] = $item[$key];
319 $menu->module_data
= serialize($module_data);
322 $menu->copyValues($item);
324 foreach (self
::$_serializedElements as $element) {
325 if (!isset($item[$element]) ||
326 $item[$element] == 'null'
328 $menu->$element = NULL;
331 $menu->$element = serialize($item[$element]);
344 public static function buildAdminLinks(&$menu) {
347 foreach ($menu as $path => $item) {
348 if (empty($item['adminGroup'])) {
352 $query = !empty($item['path_arguments']) ?
str_replace(',', '&', $item['path_arguments']) . '&reset=1' : 'reset=1';
355 'title' => $item['title'],
356 'desc' => $item['desc'] ??
NULL,
357 'id' => strtr($item['title'], [
364 'url' => CRM_Utils_System
::url($path, $query,
369 // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
372 'icon' => $item['icon'] ??
NULL,
373 'extra' => $item['extra'] ??
NULL,
375 if (!array_key_exists($item['adminGroup'], $values)) {
376 $values[$item['adminGroup']] = [];
377 $values[$item['adminGroup']]['fields'] = [];
379 $values[$item['adminGroup']]['fields']["{weight}.{$item['title']}"] = $value;
380 $values[$item['adminGroup']]['component_id'] = $item['component_id'];
383 foreach ($values as $group => $dontCare) {
384 ksort($values[$group]);
387 $menu['admin'] = ['breadcrumb' => $values];
395 public static function getAdminLinks() {
396 $links = self
::get('admin');
397 return $links['breadcrumb'] ??
NULL;
401 * Get the breadcrumb for a given path.
404 * An array of all the menu items.
405 * @param string $path
406 * Path for which breadcrumb is to be build.
409 * The breadcrumb for this path
411 public static function buildBreadcrumb(&$menu, $path) {
414 $pathElements = explode('/', $path);
415 array_pop($pathElements);
418 while ($newPath = array_shift($pathElements)) {
419 $currentPath = $currentPath ?
($currentPath . '/' . $newPath) : $newPath;
421 // when we come across breadcrumb which involves ids,
422 // we should skip now and later on append dynamically.
423 if (isset($menu[$currentPath]['skipBreadcrumb'])) {
427 // add to crumb, if current-path exists in params.
428 if (array_key_exists($currentPath, $menu) &&
429 isset($menu[$currentPath]['title'])
431 $urlVar = !empty($menu[$currentPath]['path_arguments']) ?
'&' . $menu[$currentPath]['path_arguments'] : '';
433 'title' => $menu[$currentPath]['title'],
434 'url' => CRM_Utils_System
::url($currentPath,
444 // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
450 $menu[$path]['breadcrumb'] = $crumbs;
457 * @param string|int $path
459 public static function buildReturnUrl(&$menu, $path) {
460 if (!isset($menu[$path]['return_url'])) {
461 [$menu[$path]['return_url'], $menu[$path]['return_url_args']] = self
::getReturnUrl($menu, $path);
471 public static function getReturnUrl(&$menu, $path) {
472 if (!isset($menu[$path]['return_url'])) {
473 $pathElements = explode('/', $path);
474 array_pop($pathElements);
476 if (empty($pathElements)) {
479 $newPath = implode('/', $pathElements);
481 return self
::getReturnUrl($menu, $newPath);
485 $menu[$path]['return_url'] ??
NULL,
486 $menu[$path]['return_url_args'] ??
NULL,
495 * @throws \CRM_Core_Exception
497 public static function fillComponentIds(&$menu, $path) {
500 if (array_key_exists('component_id', $menu[$path])) {
504 $args = explode('/', $path);
506 if (count($args) > 1) {
507 $compPath = $args[0] . '/' . $args[1];
510 $compPath = $args[0];
515 if (array_key_exists($compPath, $cache)) {
516 $menu[$path]['component_id'] = $cache[$compPath];
519 if (!empty($menu[$compPath]['component'])) {
520 $componentId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Component',
521 $menu[$compPath]['component'],
525 $menu[$path]['component_id'] = $componentId ?
$componentId : NULL;
526 $cache[$compPath] = $menu[$path]['component_id'];
531 * @param string $path
532 * Path of menu item to retrieve.
537 public static function get($path) {
538 $args = explode('/', $path);
541 while (!empty($args)) {
542 $string = implode('/', $args);
543 $string = CRM_Core_DAO
::escapeString($string);
544 $elements[] = "'{$string}'";
548 $queryString = implode(', ', $elements);
549 $domainID = CRM_Core_Config
::domainID();
555 WHERE path in ( $queryString )
556 AND domain_id = $domainID
557 ORDER BY length(path) DESC
562 if ($path != 'navigation') {
567 WHERE path IN ( 'navigation' )
568 AND domain_id = $domainID
573 $menu = new CRM_Core_DAO_Menu();
574 $menu->query($query);
576 self
::$_menuCache = [];
578 while ($menu->fetch()) {
579 self
::$_menuCache[$menu->path
] = [];
580 CRM_Core_DAO
::storeValues($menu, self
::$_menuCache[$menu->path
]);
582 // Move module_data into main item.
583 if (isset(self
::$_menuCache[$menu->path
]['module_data'])) {
584 CRM_Utils_Array
::extend(self
::$_menuCache[$menu->path
],
585 CRM_Utils_String
::unserialize(self
::$_menuCache[$menu->path
]['module_data']));
586 unset(self
::$_menuCache[$menu->path
]['module_data']);
589 // Unserialize other elements.
590 foreach (self
::$_serializedElements as $element) {
591 self
::$_menuCache[$menu->path
][$element] = CRM_Utils_String
::unserialize($menu->$element);
593 if (strpos($path, $menu->path
) !== FALSE) {
594 $menuPath = &self
::$_menuCache[$menu->path
];
599 if (strstr($path, 'report/instance')) {
600 $args = explode('/', $path);
601 if (is_numeric(end($args))) {
602 $menuPath['path'] .= '/' . end($args);
606 if (preg_match('/^civicrm\/(upgrade\/)?queue\//', $path)) {
607 CRM_Queue_Menu
::alter($path, $menuPath);
610 if (!empty($menuPath)) {
611 $i18n = CRM_Core_I18n
::singleton();
612 $i18n->localizeTitles($menuPath);
622 public static function getArrayForPathArgs($pathArgs) {
623 if (!is_string($pathArgs)) {
628 $elements = explode(',', $pathArgs);
629 foreach ($elements as $keyVal) {
630 list($key, $val) = explode('=', $keyVal, 2);
634 if (array_key_exists('urlToSession', $arr)) {
637 $params = explode(';', $arr['urlToSession']);
639 foreach ($params as $keyVal) {
640 list($urlToSession[$count]['urlVar'],
641 $urlToSession[$count]['sessionVar'],
642 $urlToSession[$count]['type'],
643 $urlToSession[$count]['default']
644 ) = explode(':', $keyVal);
647 $arr['urlToSession'] = $urlToSession;