Merge pull request #19135 from civicrm/5.33
[civicrm-core.git] / CRM / Core / Menu.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * This file contains the various menus of the CiviCRM module
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 */
18
19 require_once 'CRM/Core/I18n.php';
20
21 /**
22 * Class CRM_Core_Menu.
23 */
24 class CRM_Core_Menu {
25
26 /**
27 * The list of menu items.
28 *
29 * @var array
30 */
31 public static $_items = NULL;
32
33 /**
34 * The list of permissioned menu items.
35 *
36 * @var array
37 */
38 public static $_permissionedItems = NULL;
39
40 public static $_serializedElements = array(
41 'access_arguments',
42 'access_callback',
43 'page_arguments',
44 'page_callback',
45 'breadcrumb',
46 );
47
48 public static $_menuCache = NULL;
49 const MENU_ITEM = 1;
50
51 /**
52 * This function fetches the menu items from xml and xmlMenu hooks.
53 *
54 * @param bool $fetchFromXML
55 * Fetch the menu items from xml and not from cache.
56 *
57 * @return array
58 */
59 public static function &xmlItems($fetchFromXML = FALSE) {
60 if (!self::$_items || $fetchFromXML) {
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 = [];
78 foreach ($files as $file) {
79 self::read($file, self::$_items);
80 }
81
82 CRM_Utils_Hook::alterMenu(self::$_items);
83 }
84
85 return self::$_items;
86 }
87
88 /**
89 * Read menu.
90 *
91 * @param string $name
92 * File name
93 * @param array $menu
94 * An alterable list of menu items.
95 *
96 * @throws Exception
97 */
98 public static function read($name, &$menu) {
99 $xml = simplexml_load_string(file_get_contents($name));
100 self::readXML($xml, $menu);
101 }
102
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 * @throws CRM_Core_Exception
110 */
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');
117 }
118 $path = (string ) $item->path;
119 $menu[$path] = [];
120 unset($item->path);
121
122 if ($item->ids_arguments) {
123 $ids = [];
124 foreach (array('json' => 'json', 'html' => 'html', 'exception' => 'exceptions') as $tag => $attr) {
125 $ids[$attr] = [];
126 foreach ($item->ids_arguments->{$tag} as $value) {
127 $ids[$attr][] = (string) $value;
128 }
129 }
130 $menu[$path]['ids_arguments'] = $ids;
131 unset($item->ids_arguments);
132 }
133
134 foreach ($item as $key => $value) {
135 $key = (string ) $key;
136 $value = (string ) $value;
137 if (strpos($key, '_callback') &&
138 strpos($value, '::')
139 ) {
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);
143 }
144 elseif ($key == 'access_arguments') {
145 // FIXME Move the permission parser to its own class (or *maybe* CRM_Core_Permission).
146 if (strpos($value, ',') ||
147 strpos($value, ';')
148 ) {
149 if (strpos($value, ',')) {
150 $elements = explode(',', $value);
151 $op = 'and';
152 }
153 else {
154 $elements = explode(';', $value);
155 $op = 'or';
156 }
157 $items = [];
158 foreach ($elements as $element) {
159 $items[] = $element;
160 }
161 $value = array($items, $op);
162 }
163 else {
164 $value = array(array($value), 'and');
165 }
166 }
167 elseif ($key == 'is_public' || $key == 'is_ssl') {
168 $value = ($value == 'true' || $value == 1) ? 1 : 0;
169 }
170 $menu[$path][$key] = $value;
171 }
172 }
173 }
174
175 /**
176 * This function defines information for various menu items.
177 *
178 * @param bool $fetchFromXML
179 * Fetch the menu items from xml and not from cache.
180 *
181 * @return array
182 */
183 public static function &items($fetchFromXML = FALSE) {
184 return self::xmlItems($fetchFromXML);
185 }
186
187 /**
188 * Is array true (whatever that means!).
189 *
190 * @param array $values
191 *
192 * @return bool
193 */
194 public static function isArrayTrue(&$values) {
195 foreach ($values as $name => $value) {
196 if (!$value) {
197 return FALSE;
198 }
199 }
200 return TRUE;
201 }
202
203 /**
204 * Fill menu values.
205 *
206 * @param array $menu
207 * @param string $path
208 *
209 * @throws CRM_Core_Exception
210 */
211 public static function fillMenuValues(&$menu, $path) {
212 $fieldsToPropagate = array(
213 'access_callback',
214 'access_arguments',
215 'page_callback',
216 'page_arguments',
217 'is_ssl',
218 );
219 $fieldsPresent = [];
220 foreach ($fieldsToPropagate as $field) {
221 $fieldsPresent[$field] = isset($menu[$path][$field]);
222 }
223
224 $args = explode('/', $path);
225 while (!self::isArrayTrue($fieldsPresent) && !empty($args)) {
226
227 array_pop($args);
228 $parentPath = implode('/', $args);
229
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;
236 }
237 }
238 }
239 }
240
241 if (self::isArrayTrue($fieldsPresent)) {
242 return;
243 }
244
245 $messages = [];
246 foreach ($fieldsToPropagate as $field) {
247 if (!$fieldsPresent[$field]) {
248 $messages[] = ts("Could not find %1 in path tree",
249 [1 => $field]
250 );
251 }
252 }
253 throw new CRM_Core_Exception("'$path': " . implode(', ', $messages));
254 }
255
256 /**
257 * We use this function to.
258 *
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
263 *
264 * @param array $menu
265 */
266 public static function build(&$menu) {
267 foreach ($menu as $path => $menuItems) {
268 self::buildBreadcrumb($menu, $path);
269 self::fillMenuValues($menu, $path);
270 self::fillComponentIds($menu, $path);
271 self::buildReturnUrl($menu, $path);
272
273 // add add page_type if not present
274 if (!isset($menu[$path]['page_type'])) {
275 $menu[$path]['page_type'] = 0;
276 }
277 }
278
279 self::buildAdminLinks($menu);
280 }
281
282 /**
283 * This function recomputes menu from xml and populates civicrm_menu.
284 *
285 * @param bool $truncate
286 */
287 public static function store($truncate = TRUE) {
288 // first clean up the db
289 if ($truncate) {
290 $query = 'TRUNCATE civicrm_menu';
291 CRM_Core_DAO::executeQuery($query);
292 }
293 $menuArray = self::items($truncate);
294
295 self::build($menuArray);
296
297 $daoFields = CRM_Core_DAO_Menu::fields();
298
299 foreach ($menuArray as $path => $item) {
300 $menu = new CRM_Core_DAO_Menu();
301 $menu->path = $path;
302 $menu->domain_id = CRM_Core_Config::domainID();
303
304 $menu->find(TRUE);
305
306 if (!CRM_Core_Config::isUpgradeMode() ||
307 CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_menu', 'module_data', FALSE)
308 ) {
309 // Move unrecognized fields to $module_data.
310 $module_data = [];
311 foreach (array_keys($item) as $key) {
312 if (!isset($daoFields[$key])) {
313 $module_data[$key] = $item[$key];
314 unset($item[$key]);
315 }
316 }
317
318 $menu->module_data = serialize($module_data);
319 }
320
321 $menu->copyValues($item);
322
323 foreach (self::$_serializedElements as $element) {
324 if (!isset($item[$element]) ||
325 $item[$element] == 'null'
326 ) {
327 $menu->$element = NULL;
328 }
329 else {
330 $menu->$element = serialize($item[$element]);
331 }
332 }
333
334 $menu->save();
335 }
336 }
337
338 /**
339 * Build admin links.
340 *
341 * @param array $menu
342 */
343 public static function buildAdminLinks(&$menu) {
344 $values = [];
345
346 foreach ($menu as $path => $item) {
347 if (empty($item['adminGroup'])) {
348 continue;
349 }
350
351 $query = !empty($item['path_arguments']) ? str_replace(',', '&', $item['path_arguments']) . '&reset=1' : 'reset=1';
352
353 $value = array(
354 'title' => $item['title'],
355 'desc' => $item['desc'] ?? NULL,
356 'id' => strtr($item['title'], array(
357 '(' => '_',
358 ')' => '',
359 ' ' => '',
360 ',' => '_',
361 '/' => '_',
362 )),
363 'url' => CRM_Utils_System::url($path, $query,
364 FALSE,
365 NULL,
366 TRUE,
367 FALSE,
368 // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
369 TRUE
370 ),
371 'icon' => $item['icon'] ?? NULL,
372 'extra' => $item['extra'] ?? NULL,
373 );
374 if (!array_key_exists($item['adminGroup'], $values)) {
375 $values[$item['adminGroup']] = [];
376 $values[$item['adminGroup']]['fields'] = [];
377 }
378 $values[$item['adminGroup']]['fields']["{weight}.{$item['title']}"] = $value;
379 $values[$item['adminGroup']]['component_id'] = $item['component_id'];
380 }
381
382 foreach ($values as $group => $dontCare) {
383 ksort($values[$group]);
384 }
385
386 $menu['admin'] = array('breadcrumb' => $values);
387 }
388
389 /**
390 * Get admin links.
391 *
392 * @return null
393 */
394 public static function &getAdminLinks() {
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 *
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.
414 *
415 * @return array
416 * The breadcrumb for this path
417 */
418 public static function buildBreadcrumb(&$menu, $path) {
419 $crumbs = [];
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
428 // when we come across breadcrumb which involves ids,
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 ) {
438 $urlVar = !empty($menu[$currentPath]['path_arguments']) ? '&' . $menu[$currentPath]['path_arguments'] : '';
439 $crumbs[] = array(
440 'title' => $menu[$currentPath]['title'],
441 'url' => CRM_Utils_System::url($currentPath,
442 'reset=1' . $urlVar,
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
453 ),
454 );
455 }
456 }
457 $menu[$path]['breadcrumb'] = $crumbs;
458
459 return $crumbs;
460 }
461
462 /**
463 * @param $menu
464 * @param $path
465 */
466 public static function buildReturnUrl(&$menu, $path) {
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
472 /**
473 * @param $menu
474 * @param $path
475 *
476 * @return array
477 */
478 public static function getReturnUrl(&$menu, $path) {
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
502 /**
503 * @param $menu
504 * @param $path
505 *
506 * @throws \CRM_Core_Exception
507 */
508 public static function fillComponentIds(&$menu, $path) {
509 static $cache = [];
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 {
530 if (!empty($menu[$compPath]['component'])) {
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
541 /**
542 * @param $path string
543 * Path of menu item to retrieve.
544 *
545 * @return array
546 * Menu entry array.
547 */
548 public static function get($path) {
549 // return null if menu rebuild
550 $config = CRM_Core_Config::singleton();
551
552 $args = explode('/', $path);
553
554 $elements = [];
555 while (!empty($args)) {
556 $string = implode('/', $args);
557 $string = CRM_Core_DAO::escapeString($string);
558 $elements[] = "'{$string}'";
559 array_pop($args);
560 }
561
562 $queryString = implode(', ', $elements);
563 $domainID = CRM_Core_Config::domainID();
564
565 $query = "
566 (
567 SELECT *
568 FROM civicrm_menu
569 WHERE path in ( $queryString )
570 AND domain_id = $domainID
571 ORDER BY length(path) DESC
572 LIMIT 1
573 )
574 ";
575
576 if ($path != 'navigation') {
577 $query .= "
578 UNION (
579 SELECT *
580 FROM civicrm_menu
581 WHERE path IN ( 'navigation' )
582 AND domain_id = $domainID
583 )
584 ";
585 }
586
587 $menu = new CRM_Core_DAO_Menu();
588 $menu->query($query);
589
590 self::$_menuCache = [];
591 $menuPath = NULL;
592 while ($menu->fetch()) {
593 self::$_menuCache[$menu->path] = [];
594 CRM_Core_DAO::storeValues($menu, self::$_menuCache[$menu->path]);
595
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],
599 CRM_Utils_String::unserialize(self::$_menuCache[$menu->path]['module_data']));
600 unset(self::$_menuCache[$menu->path]['module_data']);
601 }
602
603 // Unserialize other elements.
604 foreach (self::$_serializedElements as $element) {
605 self::$_menuCache[$menu->path][$element] = CRM_Utils_String::unserialize($menu->$element);
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
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') {
629 $menuPath['page_callback'] = array('CRM_Upgrade_Page_Cleanup', 'cleanup425');
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
641 /**
642 * @param $pathArgs
643 *
644 * @return mixed
645 */
646 public static function getArrayForPathArgs($pathArgs) {
647 if (!is_string($pathArgs)) {
648 return;
649 }
650 $args = [];
651
652 $elements = explode(',', $pathArgs);
653 foreach ($elements as $keyVal) {
654 list($key, $val) = explode('=', $keyVal, 2);
655 $arr[$key] = $val;
656 }
657
658 if (array_key_exists('urlToSession', $arr)) {
659 $urlToSession = [];
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']
668 ) = explode(':', $keyVal);
669 $count++;
670 }
671 $arr['urlToSession'] = $urlToSession;
672 }
673 return $arr;
674 }
675
676 }