Use ?? operator instead of CRM_Utils_Array::value() when fetching ids
[civicrm-core.git] / CRM / Core / Menu.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 * This file contains the various menus of the CiviCRM module
14 *
15 * @package CRM
ca5cec67 16 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
17 */
18
19require_once 'CRM/Core/I18n.php';
28518c90
EM
20
21/**
ad37ac8e 22 * Class CRM_Core_Menu.
28518c90 23 */
6a488035
TO
24class CRM_Core_Menu {
25
26 /**
fe482240 27 * The list of menu items.
6a488035
TO
28 *
29 * @var array
6a488035 30 */
518fa0ee 31 public static $_items = NULL;
6a488035
TO
32
33 /**
fe482240 34 * The list of permissioned menu items.
6a488035
TO
35 *
36 * @var array
6a488035 37 */
518fa0ee 38 public static $_permissionedItems = NULL;
6a488035 39
518fa0ee 40 public static $_serializedElements = array(
6a488035
TO
41 'access_arguments',
42 'access_callback',
43 'page_arguments',
44 'page_callback',
45 'breadcrumb',
46 );
47
518fa0ee 48 public static $_menuCache = NULL;
7da04cde 49 const MENU_ITEM = 1;
6a488035 50
a0ee3941 51 /**
fe482240 52 * This function fetches the menu items from xml and xmlMenu hooks.
49d97c48 53 *
ad37ac8e 54 * @param bool $fetchFromXML
6a0b768e 55 * Fetch the menu items from xml and not from cache.
49d97c48 56 *
a0ee3941
EM
57 * @return array
58 */
00be9182 59 public static function &xmlItems($fetchFromXML = FALSE) {
49d97c48 60 if (!self::$_items || $fetchFromXML) {
6a488035
TO
61 $config = CRM_Core_Config::singleton();
62
63 // We needs this until Core becomes a component
64 $coreMenuFilesNamespace = 'CRM_Core_xml_Menu';
65 $coreMenuFilesPath = str_replace('_', DIRECTORY_SEPARATOR, $coreMenuFilesNamespace);
66 global $civicrm_root;
67 $files = CRM_Utils_File::getFilesByExtension($civicrm_root . DIRECTORY_SEPARATOR . $coreMenuFilesPath, 'xml');
68
69 // Grab component menu files
70 $files = array_merge($files,
71 CRM_Core_Component::xmlMenu()
72 );
73
74 // lets call a hook and get any additional files if needed
75 CRM_Utils_Hook::xmlMenu($files);
76
77 self::$_items = array();
78 foreach ($files as $file) {
79 self::read($file, self::$_items);
80 }
7dc34fb8
TO
81
82 CRM_Utils_Hook::alterMenu(self::$_items);
6a488035
TO
83 }
84
85 return self::$_items;
86 }
87
a0ee3941 88 /**
ad37ac8e 89 * Read menu.
90 *
100fef9d 91 * @param string $name
5bfe764c
TO
92 * File name
93 * @param array $menu
94 * An alterable list of menu items.
a0ee3941
EM
95 *
96 * @throws Exception
97 */
00be9182 98 public static function read($name, &$menu) {
292fbfa3 99 $xml = simplexml_load_string(file_get_contents($name));
5bfe764c
TO
100 self::readXML($xml, $menu);
101 }
6a488035 102
5bfe764c
TO
103 /**
104 * @param SimpleXMLElement $xml
105 * An XML document defining a list of menu items.
106 * @param array $menu
107 * An alterable list of menu items.
108 */
109 public static function readXML($xml, &$menu) {
6a488035 110 $config = CRM_Core_Config::singleton();
6a488035
TO
111 foreach ($xml->item as $item) {
112 if (!(string ) $item->path) {
113 CRM_Core_Error::debug('i', $item);
114 CRM_Core_Error::fatal();
115 }
116 $path = (string ) $item->path;
117 $menu[$path] = array();
118 unset($item->path);
4535c1f5
TO
119
120 if ($item->ids_arguments) {
121 $ids = array();
36d4fa1b
TO
122 foreach (array('json' => 'json', 'html' => 'html', 'exception' => 'exceptions') as $tag => $attr) {
123 $ids[$attr] = array();
124 foreach ($item->ids_arguments->{$tag} as $value) {
125 $ids[$attr][] = (string) $value;
4535c1f5
TO
126 }
127 }
128 $menu[$path]['ids_arguments'] = $ids;
129 unset($item->ids_arguments);
130 }
131
6a488035
TO
132 foreach ($item as $key => $value) {
133 $key = (string ) $key;
134 $value = (string ) $value;
135 if (strpos($key, '_callback') &&
136 strpos($value, '::')
137 ) {
c8074a93
TO
138 // FIXME Remove the rewrite at this level. Instead, change downstream call_user_func*($value)
139 // to call_user_func*(Civi\Core\Resolver::singleton()->get($value)).
6a488035
TO
140 $value = explode('::', $value);
141 }
142 elseif ($key == 'access_arguments') {
c8074a93 143 // FIXME Move the permission parser to its own class (or *maybe* CRM_Core_Permission).
6a488035
TO
144 if (strpos($value, ',') ||
145 strpos($value, ';')
146 ) {
147 if (strpos($value, ',')) {
148 $elements = explode(',', $value);
149 $op = 'and';
150 }
151 else {
152 $elements = explode(';', $value);
153 $op = 'or';
154 }
155 $items = array();
156 foreach ($elements as $element) {
157 $items[] = $element;
158 }
159 $value = array($items, $op);
160 }
161 else {
162 $value = array(array($value), 'and');
163 }
164 }
165 elseif ($key == 'is_public' || $key == 'is_ssl') {
166 $value = ($value == 'true' || $value == 1) ? 1 : 0;
167 }
168 $menu[$path][$key] = $value;
169 }
170 }
171 }
172
173 /**
fe482240 174 * This function defines information for various menu items.
6a488035 175 *
ad37ac8e 176 * @param bool $fetchFromXML
6a0b768e 177 * Fetch the menu items from xml and not from cache.
49d97c48 178 *
7a9ab499 179 * @return array
6a488035 180 */
00be9182 181 public static function &items($fetchFromXML = FALSE) {
49d97c48 182 return self::xmlItems($fetchFromXML);
6a488035
TO
183 }
184
a0ee3941 185 /**
ad37ac8e 186 * Is array true (whatever that means!).
187 *
188 * @param array $values
a0ee3941
EM
189 *
190 * @return bool
191 */
00be9182 192 public static function isArrayTrue(&$values) {
6a488035
TO
193 foreach ($values as $name => $value) {
194 if (!$value) {
195 return FALSE;
196 }
197 }
198 return TRUE;
199 }
200
a0ee3941 201 /**
ad37ac8e 202 * Fill menu values.
203 *
204 * @param array $menu
205 * @param string $path
a0ee3941
EM
206 *
207 * @throws Exception
208 */
00be9182 209 public static function fillMenuValues(&$menu, $path) {
6a488035
TO
210 $fieldsToPropagate = array(
211 'access_callback',
212 'access_arguments',
213 'page_callback',
214 'page_arguments',
215 'is_ssl',
216 );
217 $fieldsPresent = array();
218 foreach ($fieldsToPropagate as $field) {
219 $fieldsPresent[$field] = CRM_Utils_Array::value($field, $menu[$path]) !== NULL ? TRUE : FALSE;
220 }
221
222 $args = explode('/', $path);
223 while (!self::isArrayTrue($fieldsPresent) && !empty($args)) {
224
225 array_pop($args);
226 $parentPath = implode('/', $args);
227
228 foreach ($fieldsToPropagate as $field) {
229 if (!$fieldsPresent[$field]) {
8d9ce16a 230 $fieldInParentMenu = $menu[$parentPath][$field] ?? NULL;
231 if ($fieldInParentMenu !== NULL) {
6a488035 232 $fieldsPresent[$field] = TRUE;
8d9ce16a 233 $menu[$path][$field] = $fieldInParentMenu;
6a488035
TO
234 }
235 }
236 }
237 }
238
239 if (self::isArrayTrue($fieldsPresent)) {
240 return;
241 }
242
243 $messages = array();
244 foreach ($fieldsToPropagate as $field) {
245 if (!$fieldsPresent[$field]) {
246 $messages[] = ts("Could not find %1 in path tree",
247 array(1 => $field)
248 );
249 }
250 }
251 CRM_Core_Error::fatal("'$path': " . implode(', ', $messages));
252 }
253
254 /**
fe482240 255 * We use this function to.
6a488035
TO
256 *
257 * 1. Compute the breadcrumb
258 * 2. Compute local tasks value if any
259 * 3. Propagate access argument, access callback, page callback to the menu item
260 * 4. Build the global navigation block
ea3ddccf 261 *
262 * @param array $menu
6a488035 263 */
00be9182 264 public static function build(&$menu) {
6a488035
TO
265 foreach ($menu as $path => $menuItems) {
266 self::buildBreadcrumb($menu, $path);
267 self::fillMenuValues($menu, $path);
268 self::fillComponentIds($menu, $path);
269 self::buildReturnUrl($menu, $path);
270
271 // add add page_type if not present
272 if (!isset($menu[$path]['page_type'])) {
273 $menu[$path]['page_type'] = 0;
274 }
275 }
276
277 self::buildAdminLinks($menu);
278 }
279
a0ee3941 280 /**
fe482240 281 * This function recomputes menu from xml and populates civicrm_menu.
ad37ac8e 282 *
a0ee3941
EM
283 * @param bool $truncate
284 */
00be9182 285 public static function store($truncate = TRUE) {
6a488035
TO
286 // first clean up the db
287 if ($truncate) {
288 $query = 'TRUNCATE civicrm_menu';
289 CRM_Core_DAO::executeQuery($query);
290 }
49d97c48 291 $menuArray = self::items($truncate);
6a488035
TO
292
293 self::build($menuArray);
294
b44dc91e 295 $daoFields = CRM_Core_DAO_Menu::fields();
6a488035
TO
296
297 foreach ($menuArray as $path => $item) {
353ffa53
TO
298 $menu = new CRM_Core_DAO_Menu();
299 $menu->path = $path;
6a488035
TO
300 $menu->domain_id = CRM_Core_Config::domainID();
301
302 $menu->find(TRUE);
303
d6f1a16c 304 if (!CRM_Core_Config::isUpgradeMode() ||
eed7e803 305 CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_menu', 'module_data', FALSE)
d6f1a16c
NM
306 ) {
307 // Move unrecognized fields to $module_data.
308 $module_data = array();
309 foreach (array_keys($item) as $key) {
310 if (!isset($daoFields[$key])) {
311 $module_data[$key] = $item[$key];
312 unset($item[$key]);
313 }
b44dc91e 314 }
b44dc91e 315
d6f1a16c
NM
316 $menu->module_data = serialize($module_data);
317 }
6a488035 318
c09129a5
NM
319 $menu->copyValues($item);
320
6a488035
TO
321 foreach (self::$_serializedElements as $element) {
322 if (!isset($item[$element]) ||
323 $item[$element] == 'null'
324 ) {
325 $menu->$element = NULL;
326 }
327 else {
328 $menu->$element = serialize($item[$element]);
329 }
330 }
331
332 $menu->save();
333 }
334 }
335
a0ee3941 336 /**
ad37ac8e 337 * Build admin links.
338 *
339 * @param array $menu
a0ee3941 340 */
00be9182 341 public static function buildAdminLinks(&$menu) {
6a488035
TO
342 $values = array();
343
344 foreach ($menu as $path => $item) {
a7488080 345 if (empty($item['adminGroup'])) {
6a488035
TO
346 continue;
347 }
348
0d8afee2 349 $query = !empty($item['path_arguments']) ? str_replace(',', '&', $item['path_arguments']) . '&reset=1' : 'reset=1';
6a488035
TO
350
351 $value = array(
352 'title' => $item['title'],
353 'desc' => CRM_Utils_Array::value('desc', $item),
354 'id' => strtr($item['title'], array(
518fa0ee
SL
355 '(' => '_',
356 ')' => '',
357 ' ' => '',
358 ',' => '_',
359 '/' => '_',
360 )),
d75f2f47 361 'url' => CRM_Utils_System::url($path, $query,
ad37ac8e 362 FALSE,
363 NULL,
364 TRUE,
365 FALSE,
366 // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
367 TRUE
f4bdec6a 368 ),
6a488035
TO
369 'icon' => CRM_Utils_Array::value('icon', $item),
370 'extra' => CRM_Utils_Array::value('extra', $item),
371 );
372 if (!array_key_exists($item['adminGroup'], $values)) {
373 $values[$item['adminGroup']] = array();
374 $values[$item['adminGroup']]['fields'] = array();
375 }
376 $weight = CRM_Utils_Array::value('weight', $item, 0);
377 $values[$item['adminGroup']]['fields']["{weight}.{$item['title']}"] = $value;
378 $values[$item['adminGroup']]['component_id'] = $item['component_id'];
379 }
380
381 foreach ($values as $group => $dontCare) {
382 $values[$group]['perColumn'] = round(count($values[$group]['fields']) / 2);
383 ksort($values[$group]);
384 }
385
386 $menu['admin'] = array('breadcrumb' => $values);
387 }
388
a0ee3941 389 /**
ad37ac8e 390 * Get admin links.
391 *
a0ee3941
EM
392 * @return null
393 */
00be9182 394 public static function &getAdminLinks() {
6a488035
TO
395 $links = self::get('admin');
396
397 if (!$links ||
398 !isset($links['breadcrumb'])
399 ) {
400 return NULL;
401 }
402
403 $values = &$links['breadcrumb'];
404 return $values;
405 }
406
407 /**
408 * Get the breadcrumb for a given path.
409 *
6a0b768e
TO
410 * @param array $menu
411 * An array of all the menu items.
412 * @param string $path
413 * Path for which breadcrumb is to be build.
6a488035 414 *
a6c01b45
CW
415 * @return array
416 * The breadcrumb for this path
6a488035 417 */
00be9182 418 public static function buildBreadcrumb(&$menu, $path) {
6a488035
TO
419 $crumbs = array();
420
421 $pathElements = explode('/', $path);
422 array_pop($pathElements);
423
424 $currentPath = NULL;
425 while ($newPath = array_shift($pathElements)) {
426 $currentPath = $currentPath ? ($currentPath . '/' . $newPath) : $newPath;
427
b44e3f84 428 // when we come across breadcrumb which involves ids,
6a488035
TO
429 // we should skip now and later on append dynamically.
430 if (isset($menu[$currentPath]['skipBreadcrumb'])) {
431 continue;
432 }
433
434 // add to crumb, if current-path exists in params.
435 if (array_key_exists($currentPath, $menu) &&
436 isset($menu[$currentPath]['title'])
437 ) {
0d8afee2 438 $urlVar = !empty($menu[$currentPath]['path_arguments']) ? '&' . $menu[$currentPath]['path_arguments'] : '';
6a488035
TO
439 $crumbs[] = array(
440 'title' => $menu[$currentPath]['title'],
441 'url' => CRM_Utils_System::url($currentPath,
38a0e912 442 'reset=1' . $urlVar,
518fa0ee
SL
443 // absolute
444 FALSE,
445 // fragment
446 NULL,
447 // htmlize
448 TRUE,
449 // frontend
450 FALSE,
451 // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
452 TRUE
6a488035
TO
453 ),
454 );
455 }
456 }
457 $menu[$path]['breadcrumb'] = $crumbs;
458
459 return $crumbs;
460 }
461
a0ee3941
EM
462 /**
463 * @param $menu
464 * @param $path
465 */
00be9182 466 public static function buildReturnUrl(&$menu, $path) {
6a488035
TO
467 if (!isset($menu[$path]['return_url'])) {
468 list($menu[$path]['return_url'], $menu[$path]['return_url_args']) = self::getReturnUrl($menu, $path);
469 }
470 }
471
a0ee3941
EM
472 /**
473 * @param $menu
474 * @param $path
475 *
476 * @return array
477 */
00be9182 478 public static function getReturnUrl(&$menu, $path) {
6a488035
TO
479 if (!isset($menu[$path]['return_url'])) {
480 $pathElements = explode('/', $path);
481 array_pop($pathElements);
482
483 if (empty($pathElements)) {
484 return array(NULL, NULL);
485 }
486 $newPath = implode('/', $pathElements);
487
488 return self::getReturnUrl($menu, $newPath);
489 }
490 else {
491 return array(
492 CRM_Utils_Array::value('return_url',
493 $menu[$path]
494 ),
495 CRM_Utils_Array::value('return_url_args',
496 $menu[$path]
497 ),
498 );
499 }
500 }
501
a0ee3941
EM
502 /**
503 * @param $menu
504 * @param $path
508db412 505 *
506 * @throws \CRM_Core_Exception
a0ee3941 507 */
00be9182 508 public static function fillComponentIds(&$menu, $path) {
6a488035
TO
509 static $cache = array();
510
511 if (array_key_exists('component_id', $menu[$path])) {
512 return;
513 }
514
515 $args = explode('/', $path);
516
517 if (count($args) > 1) {
518 $compPath = $args[0] . '/' . $args[1];
519 }
520 else {
521 $compPath = $args[0];
522 }
523
524 $componentId = NULL;
525
526 if (array_key_exists($compPath, $cache)) {
527 $menu[$path]['component_id'] = $cache[$compPath];
528 }
529 else {
508db412 530 if (!empty($menu[$compPath]['component'])) {
6a488035
TO
531 $componentId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Component',
532 $menu[$compPath]['component'],
533 'id', 'name'
534 );
535 }
536 $menu[$path]['component_id'] = $componentId ? $componentId : NULL;
537 $cache[$compPath] = $menu[$path]['component_id'];
538 }
539 }
540
a0ee3941 541 /**
35146d69 542 * @param $path string
2bc65854 543 * Path of menu item to retrieve.
a0ee3941 544 *
35146d69 545 * @return array
2bc65854 546 * Menu entry array.
a0ee3941 547 */
00be9182 548 public static function get($path) {
6a488035
TO
549 // return null if menu rebuild
550 $config = CRM_Core_Config::singleton();
551
6a488035
TO
552 $args = explode('/', $path);
553
554 $elements = array();
555 while (!empty($args)) {
353ffa53
TO
556 $string = implode('/', $args);
557 $string = CRM_Core_DAO::escapeString($string);
6a488035
TO
558 $elements[] = "'{$string}'";
559 array_pop($args);
560 }
561
353ffa53
TO
562 $queryString = implode(', ', $elements);
563 $domainID = CRM_Core_Config::domainID();
6a488035
TO
564
565 $query = "
566(
567 SELECT *
568 FROM civicrm_menu
569 WHERE path in ( $queryString )
99a2c00a 570 AND domain_id = $domainID
6a488035
TO
571 ORDER BY length(path) DESC
572 LIMIT 1
573)
574";
575
576 if ($path != 'navigation') {
577 $query .= "
578UNION (
579 SELECT *
580 FROM civicrm_menu
581 WHERE path IN ( 'navigation' )
99a2c00a 582 AND domain_id = $domainID
6a488035
TO
583)
584";
585 }
586
587 $menu = new CRM_Core_DAO_Menu();
588 $menu->query($query);
589
590 self::$_menuCache = array();
591 $menuPath = NULL;
592 while ($menu->fetch()) {
593 self::$_menuCache[$menu->path] = array();
594 CRM_Core_DAO::storeValues($menu, self::$_menuCache[$menu->path]);
595
b44dc91e
TO
596 // Move module_data into main item.
597 if (isset(self::$_menuCache[$menu->path]['module_data'])) {
598 CRM_Utils_Array::extend(self::$_menuCache[$menu->path],
f24846d5 599 CRM_Utils_String::unserialize(self::$_menuCache[$menu->path]['module_data']));
b44dc91e
TO
600 unset(self::$_menuCache[$menu->path]['module_data']);
601 }
602
603 // Unserialize other elements.
6a488035 604 foreach (self::$_serializedElements as $element) {
f24846d5 605 self::$_menuCache[$menu->path][$element] = CRM_Utils_String::unserialize($menu->$element);
6a488035
TO
606
607 if (strpos($path, $menu->path) !== FALSE) {
608 $menuPath = &self::$_menuCache[$menu->path];
609 }
610 }
611 }
612
613 if (strstr($path, 'report/instance')) {
614 $args = explode('/', $path);
615 if (is_numeric(end($args))) {
616 $menuPath['path'] .= '/' . end($args);
617 }
618 }
619
6a488035
TO
620 // *FIXME* : hack for 4.1 -> 4.2 upgrades.
621 if (preg_match('/^civicrm\/(upgrade\/)?queue\//', $path)) {
622 CRM_Queue_Menu::alter($path, $menuPath);
623 }
624
625 // Part of upgrade framework but not run inside main upgrade because it deletes data
626 // Once we have another example of a 'cleanup' we should generalize the clause below so it grabs string
627 // which follows upgrade/ and checks for existence of a function in Cleanup class.
628 if ($path == 'civicrm/upgrade/cleanup425') {
2aa397bc 629 $menuPath['page_callback'] = array('CRM_Upgrade_Page_Cleanup', 'cleanup425');
6a488035
TO
630 $menuPath['access_arguments'][0][] = 'administer CiviCRM';
631 $menuPath['access_callback'] = array('CRM_Core_Permission', 'checkMenu');
632 }
633
634 if (!empty($menuPath)) {
635 $i18n = CRM_Core_I18n::singleton();
636 $i18n->localizeTitles($menuPath);
637 }
638 return $menuPath;
639 }
640
a0ee3941
EM
641 /**
642 * @param $pathArgs
643 *
644 * @return mixed
645 */
00be9182 646 public static function getArrayForPathArgs($pathArgs) {
6a488035
TO
647 if (!is_string($pathArgs)) {
648 return;
649 }
650 $args = array();
651
652 $elements = explode(',', $pathArgs);
6a488035 653 foreach ($elements as $keyVal) {
3b4339fd 654 list($key, $val) = explode('=', $keyVal, 2);
6a488035
TO
655 $arr[$key] = $val;
656 }
657
658 if (array_key_exists('urlToSession', $arr)) {
659 $urlToSession = array();
660
661 $params = explode(';', $arr['urlToSession']);
662 $count = 0;
663 foreach ($params as $keyVal) {
664 list($urlToSession[$count]['urlVar'],
665 $urlToSession[$count]['sessionVar'],
666 $urlToSession[$count]['type'],
667 $urlToSession[$count]['default']
353ffa53 668 ) = explode(':', $keyVal);
6a488035
TO
669 $count++;
670 }
671 $arr['urlToSession'] = $urlToSession;
672 }
673 return $arr;
674 }
96025800 675
6a488035 676}