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
19 require_once 'CRM/Core/I18n.php';
22 * Class CRM_Core_Menu.
27 * The list of menu items.
31 public static $_items = NULL;
34 * The list of permissioned menu items.
38 public static $_permissionedItems = NULL;
40 public static $_serializedElements = array(
48 public static $_menuCache = NULL;
52 * This function fetches the menu items from xml and xmlMenu hooks.
54 * @param bool $fetchFromXML
55 * Fetch the menu items from xml and not from cache.
59 public static function &xmlItems($fetchFromXML = FALSE) {
60 if (!self
::$_items ||
$fetchFromXML) {
61 $config = CRM_Core_Config
::singleton();
63 // We needs this until Core becomes a component
64 $coreMenuFilesNamespace = 'CRM_Core_xml_Menu';
65 $coreMenuFilesPath = str_replace('_', DIRECTORY_SEPARATOR
, $coreMenuFilesNamespace);
67 $files = CRM_Utils_File
::getFilesByExtension($civicrm_root . DIRECTORY_SEPARATOR
. $coreMenuFilesPath, 'xml');
69 // Grab component menu files
70 $files = array_merge($files,
71 CRM_Core_Component
::xmlMenu()
74 // lets call a hook and get any additional files if needed
75 CRM_Utils_Hook
::xmlMenu($files);
78 foreach ($files as $file) {
79 self
::read($file, self
::$_items);
82 CRM_Utils_Hook
::alterMenu(self
::$_items);
94 * An alterable list of menu items.
98 public static function read($name, &$menu) {
99 $xml = simplexml_load_string(file_get_contents($name));
100 self
::readXML($xml, $menu);
104 * @param SimpleXMLElement $xml
105 * An XML document defining a list of menu items.
107 * An alterable list of menu items.
109 * @throws CRM_Core_Exception
111 public static function readXML($xml, &$menu) {
112 $config = CRM_Core_Config
::singleton();
113 foreach ($xml->item
as $item) {
114 if (!(string ) $item->path
) {
115 CRM_Core_Error
::debug('i', $item);
116 throw new CRM_Core_Exception('Unable to read XML file');
118 $path = (string ) $item->path
;
122 if ($item->ids_arguments
) {
124 foreach (array('json' => 'json', 'html' => 'html', 'exception' => 'exceptions') as $tag => $attr) {
126 foreach ($item->ids_arguments
->{$tag} as $value) {
127 $ids[$attr][] = (string) $value;
130 $menu[$path]['ids_arguments'] = $ids;
131 unset($item->ids_arguments
);
134 foreach ($item as $key => $value) {
135 $key = (string ) $key;
136 $value = (string ) $value;
137 if (strpos($key, '_callback') &&
140 // FIXME Remove the rewrite at this level. Instead, change downstream call_user_func*($value)
141 // to call_user_func*(Civi\Core\Resolver::singleton()->get($value)).
142 $value = explode('::', $value);
144 elseif ($key == 'access_arguments') {
145 // FIXME Move the permission parser to its own class (or *maybe* CRM_Core_Permission).
146 if (strpos($value, ',') ||
149 if (strpos($value, ',')) {
150 $elements = explode(',', $value);
154 $elements = explode(';', $value);
158 foreach ($elements as $element) {
161 $value = array($items, $op);
164 $value = array(array($value), 'and');
167 elseif ($key == 'is_public' ||
$key == 'is_ssl') {
168 $value = ($value == 'true' ||
$value == 1) ?
1 : 0;
170 $menu[$path][$key] = $value;
176 * This function defines information for various menu items.
178 * @param bool $fetchFromXML
179 * Fetch the menu items from xml and not from cache.
183 public static function &items($fetchFromXML = FALSE) {
184 return self
::xmlItems($fetchFromXML);
188 * Is array true (whatever that means!).
190 * @param array $values
194 public static function isArrayTrue(&$values) {
195 foreach ($values as $name => $value) {
207 * @param string $path
209 * @throws CRM_Core_Exception
211 public static function fillMenuValues(&$menu, $path) {
212 $fieldsToPropagate = array(
220 foreach ($fieldsToPropagate as $field) {
221 $fieldsPresent[$field] = isset($menu[$path][$field]);
224 $args = explode('/', $path);
225 while (!self
::isArrayTrue($fieldsPresent) && !empty($args)) {
228 $parentPath = implode('/', $args);
230 foreach ($fieldsToPropagate as $field) {
231 if (!$fieldsPresent[$field]) {
232 $fieldInParentMenu = $menu[$parentPath][$field] ??
NULL;
233 if ($fieldInParentMenu !== NULL) {
234 $fieldsPresent[$field] = TRUE;
235 $menu[$path][$field] = $fieldInParentMenu;
241 if (self
::isArrayTrue($fieldsPresent)) {
246 foreach ($fieldsToPropagate as $field) {
247 if (!$fieldsPresent[$field]) {
248 $messages[] = ts("Could not find %1 in path tree",
253 throw new CRM_Core_Exception("'$path': " . implode(', ', $messages));
257 * We use this function to.
259 * 1. Compute the breadcrumb
260 * 2. Compute local tasks value if any
261 * 3. Propagate access argument, access callback, page callback to the menu item
262 * 4. Build the global navigation block
266 public static function build(&$menu) {
267 foreach ($menu as $path => $menuItems) {
269 self
::buildBreadcrumb($menu, $path);
270 self
::fillMenuValues($menu, $path);
271 self
::fillComponentIds($menu, $path);
272 self
::buildReturnUrl($menu, $path);
274 // add add page_type if not present
275 if (!isset($menu[$path]['page_type'])) {
276 $menu[$path]['page_type'] = 0;
279 catch (CRM_Core_Exception
$e) {
280 Civi
::log()->error('Menu path skipped:' . $e->getMessage());
284 self
::buildAdminLinks($menu);
288 * This function recomputes menu from xml and populates civicrm_menu.
290 * @param bool $truncate
292 public static function store($truncate = TRUE) {
293 // first clean up the db
295 $query = 'TRUNCATE civicrm_menu';
296 CRM_Core_DAO
::executeQuery($query);
298 $menuArray = self
::items($truncate);
300 self
::build($menuArray);
302 $daoFields = CRM_Core_DAO_Menu
::fields();
304 foreach ($menuArray as $path => $item) {
305 $menu = new CRM_Core_DAO_Menu();
307 $menu->domain_id
= CRM_Core_Config
::domainID();
311 if (!CRM_Core_Config
::isUpgradeMode() ||
312 CRM_Core_BAO_SchemaHandler
::checkIfFieldExists('civicrm_menu', 'module_data', FALSE)
314 // Move unrecognized fields to $module_data.
316 foreach (array_keys($item) as $key) {
317 if (!isset($daoFields[$key])) {
318 $module_data[$key] = $item[$key];
323 $menu->module_data
= serialize($module_data);
326 $menu->copyValues($item);
328 foreach (self
::$_serializedElements as $element) {
329 if (!isset($item[$element]) ||
330 $item[$element] == 'null'
332 $menu->$element = NULL;
335 $menu->$element = serialize($item[$element]);
348 public static function buildAdminLinks(&$menu) {
351 foreach ($menu as $path => $item) {
352 if (empty($item['adminGroup'])) {
356 $query = !empty($item['path_arguments']) ?
str_replace(',', '&', $item['path_arguments']) . '&reset=1' : 'reset=1';
359 'title' => $item['title'],
360 'desc' => $item['desc'] ??
NULL,
361 'id' => strtr($item['title'], array(
368 'url' => CRM_Utils_System
::url($path, $query,
373 // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
376 'icon' => $item['icon'] ??
NULL,
377 'extra' => $item['extra'] ??
NULL,
379 if (!array_key_exists($item['adminGroup'], $values)) {
380 $values[$item['adminGroup']] = [];
381 $values[$item['adminGroup']]['fields'] = [];
383 $values[$item['adminGroup']]['fields']["{weight}.{$item['title']}"] = $value;
384 $values[$item['adminGroup']]['component_id'] = $item['component_id'];
387 foreach ($values as $group => $dontCare) {
388 ksort($values[$group]);
391 $menu['admin'] = array('breadcrumb' => $values);
399 public static function &getAdminLinks() {
400 $links = self
::get('admin');
403 !isset($links['breadcrumb'])
408 $values = &$links['breadcrumb'];
413 * Get the breadcrumb for a given path.
416 * An array of all the menu items.
417 * @param string $path
418 * Path for which breadcrumb is to be build.
421 * The breadcrumb for this path
423 public static function buildBreadcrumb(&$menu, $path) {
426 $pathElements = explode('/', $path);
427 array_pop($pathElements);
430 while ($newPath = array_shift($pathElements)) {
431 $currentPath = $currentPath ?
($currentPath . '/' . $newPath) : $newPath;
433 // when we come across breadcrumb which involves ids,
434 // we should skip now and later on append dynamically.
435 if (isset($menu[$currentPath]['skipBreadcrumb'])) {
439 // add to crumb, if current-path exists in params.
440 if (array_key_exists($currentPath, $menu) &&
441 isset($menu[$currentPath]['title'])
443 $urlVar = !empty($menu[$currentPath]['path_arguments']) ?
'&' . $menu[$currentPath]['path_arguments'] : '';
445 'title' => $menu[$currentPath]['title'],
446 'url' => CRM_Utils_System
::url($currentPath,
456 // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
462 $menu[$path]['breadcrumb'] = $crumbs;
471 public static function buildReturnUrl(&$menu, $path) {
472 if (!isset($menu[$path]['return_url'])) {
473 [$menu[$path]['return_url'], $menu[$path]['return_url_args']] = self
::getReturnUrl($menu, $path);
483 public static function getReturnUrl(&$menu, $path) {
484 if (!isset($menu[$path]['return_url'])) {
485 $pathElements = explode('/', $path);
486 array_pop($pathElements);
488 if (empty($pathElements)) {
489 return array(NULL, NULL);
491 $newPath = implode('/', $pathElements);
493 return self
::getReturnUrl($menu, $newPath);
497 CRM_Utils_Array
::value('return_url',
500 CRM_Utils_Array
::value('return_url_args',
511 * @throws \CRM_Core_Exception
513 public static function fillComponentIds(&$menu, $path) {
516 if (array_key_exists('component_id', $menu[$path])) {
520 $args = explode('/', $path);
522 if (count($args) > 1) {
523 $compPath = $args[0] . '/' . $args[1];
526 $compPath = $args[0];
531 if (array_key_exists($compPath, $cache)) {
532 $menu[$path]['component_id'] = $cache[$compPath];
535 if (!empty($menu[$compPath]['component'])) {
536 $componentId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Component',
537 $menu[$compPath]['component'],
541 $menu[$path]['component_id'] = $componentId ?
$componentId : NULL;
542 $cache[$compPath] = $menu[$path]['component_id'];
547 * @param $path string
548 * Path of menu item to retrieve.
553 public static function get($path) {
554 // return null if menu rebuild
555 $config = CRM_Core_Config
::singleton();
557 $args = explode('/', $path);
560 while (!empty($args)) {
561 $string = implode('/', $args);
562 $string = CRM_Core_DAO
::escapeString($string);
563 $elements[] = "'{$string}'";
567 $queryString = implode(', ', $elements);
568 $domainID = CRM_Core_Config
::domainID();
574 WHERE path in ( $queryString )
575 AND domain_id = $domainID
576 ORDER BY length(path) DESC
581 if ($path != 'navigation') {
586 WHERE path IN ( 'navigation' )
587 AND domain_id = $domainID
592 $menu = new CRM_Core_DAO_Menu();
593 $menu->query($query);
595 self
::$_menuCache = [];
597 while ($menu->fetch()) {
598 self
::$_menuCache[$menu->path
] = [];
599 CRM_Core_DAO
::storeValues($menu, self
::$_menuCache[$menu->path
]);
601 // Move module_data into main item.
602 if (isset(self
::$_menuCache[$menu->path
]['module_data'])) {
603 CRM_Utils_Array
::extend(self
::$_menuCache[$menu->path
],
604 CRM_Utils_String
::unserialize(self
::$_menuCache[$menu->path
]['module_data']));
605 unset(self
::$_menuCache[$menu->path
]['module_data']);
608 // Unserialize other elements.
609 foreach (self
::$_serializedElements as $element) {
610 self
::$_menuCache[$menu->path
][$element] = CRM_Utils_String
::unserialize($menu->$element);
612 if (strpos($path, $menu->path
) !== FALSE) {
613 $menuPath = &self
::$_menuCache[$menu->path
];
618 if (strstr($path, 'report/instance')) {
619 $args = explode('/', $path);
620 if (is_numeric(end($args))) {
621 $menuPath['path'] .= '/' . end($args);
625 // *FIXME* : hack for 4.1 -> 4.2 upgrades.
626 if (preg_match('/^civicrm\/(upgrade\/)?queue\//', $path)) {
627 CRM_Queue_Menu
::alter($path, $menuPath);
630 // Part of upgrade framework but not run inside main upgrade because it deletes data
631 // Once we have another example of a 'cleanup' we should generalize the clause below so it grabs string
632 // which follows upgrade/ and checks for existence of a function in Cleanup class.
633 if ($path == 'civicrm/upgrade/cleanup425') {
634 $menuPath['page_callback'] = array('CRM_Upgrade_Page_Cleanup', 'cleanup425');
635 $menuPath['access_arguments'][0][] = 'administer CiviCRM';
636 $menuPath['access_callback'] = array('CRM_Core_Permission', 'checkMenu');
639 if (!empty($menuPath)) {
640 $i18n = CRM_Core_I18n
::singleton();
641 $i18n->localizeTitles($menuPath);
651 public static function getArrayForPathArgs($pathArgs) {
652 if (!is_string($pathArgs)) {
657 $elements = explode(',', $pathArgs);
658 foreach ($elements as $keyVal) {
659 list($key, $val) = explode('=', $keyVal, 2);
663 if (array_key_exists('urlToSession', $arr)) {
666 $params = explode(';', $arr['urlToSession']);
668 foreach ($params as $keyVal) {
669 list($urlToSession[$count]['urlVar'],
670 $urlToSession[$count]['sessionVar'],
671 $urlToSession[$count]['type'],
672 $urlToSession[$count]['default']
673 ) = explode(':', $keyVal);
676 $arr['urlToSession'] = $urlToSession;