Merge pull request #16967 from wmortada/wp#46-2
[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 = array();
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 public static function readXML($xml, &$menu) {
110 $config = CRM_Core_Config::singleton();
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);
119
120 if ($item->ids_arguments) {
121 $ids = array();
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;
126 }
127 }
128 $menu[$path]['ids_arguments'] = $ids;
129 unset($item->ids_arguments);
130 }
131
132 foreach ($item as $key => $value) {
133 $key = (string ) $key;
134 $value = (string ) $value;
135 if (strpos($key, '_callback') &&
136 strpos($value, '::')
137 ) {
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)).
140 $value = explode('::', $value);
141 }
142 elseif ($key == 'access_arguments') {
143 // FIXME Move the permission parser to its own class (or *maybe* CRM_Core_Permission).
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 /**
174 * This function defines information for various menu items.
175 *
176 * @param bool $fetchFromXML
177 * Fetch the menu items from xml and not from cache.
178 *
179 * @return array
180 */
181 public static function &items($fetchFromXML = FALSE) {
182 return self::xmlItems($fetchFromXML);
183 }
184
185 /**
186 * Is array true (whatever that means!).
187 *
188 * @param array $values
189 *
190 * @return bool
191 */
192 public static function isArrayTrue(&$values) {
193 foreach ($values as $name => $value) {
194 if (!$value) {
195 return FALSE;
196 }
197 }
198 return TRUE;
199 }
200
201 /**
202 * Fill menu values.
203 *
204 * @param array $menu
205 * @param string $path
206 *
207 * @throws Exception
208 */
209 public static function fillMenuValues(&$menu, $path) {
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] = isset($menu[$path][$field]);
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]) {
230 $fieldInParentMenu = $menu[$parentPath][$field] ?? NULL;
231 if ($fieldInParentMenu !== NULL) {
232 $fieldsPresent[$field] = TRUE;
233 $menu[$path][$field] = $fieldInParentMenu;
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 /**
255 * We use this function 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
261 *
262 * @param array $menu
263 */
264 public static function build(&$menu) {
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
280 /**
281 * This function recomputes menu from xml and populates civicrm_menu.
282 *
283 * @param bool $truncate
284 */
285 public static function store($truncate = TRUE) {
286 // first clean up the db
287 if ($truncate) {
288 $query = 'TRUNCATE civicrm_menu';
289 CRM_Core_DAO::executeQuery($query);
290 }
291 $menuArray = self::items($truncate);
292
293 self::build($menuArray);
294
295 $daoFields = CRM_Core_DAO_Menu::fields();
296
297 foreach ($menuArray as $path => $item) {
298 $menu = new CRM_Core_DAO_Menu();
299 $menu->path = $path;
300 $menu->domain_id = CRM_Core_Config::domainID();
301
302 $menu->find(TRUE);
303
304 if (!CRM_Core_Config::isUpgradeMode() ||
305 CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_menu', 'module_data', FALSE)
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 }
314 }
315
316 $menu->module_data = serialize($module_data);
317 }
318
319 $menu->copyValues($item);
320
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
336 /**
337 * Build admin links.
338 *
339 * @param array $menu
340 */
341 public static function buildAdminLinks(&$menu) {
342 $values = array();
343
344 foreach ($menu as $path => $item) {
345 if (empty($item['adminGroup'])) {
346 continue;
347 }
348
349 $query = !empty($item['path_arguments']) ? str_replace(',', '&', $item['path_arguments']) . '&reset=1' : 'reset=1';
350
351 $value = array(
352 'title' => $item['title'],
353 'desc' => $item['desc'] ?? NULL,
354 'id' => strtr($item['title'], array(
355 '(' => '_',
356 ')' => '',
357 ' ' => '',
358 ',' => '_',
359 '/' => '_',
360 )),
361 'url' => CRM_Utils_System::url($path, $query,
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
368 ),
369 'icon' => $item['icon'] ?? NULL,
370 'extra' => $item['extra'] ?? NULL,
371 );
372 if (!array_key_exists($item['adminGroup'], $values)) {
373 $values[$item['adminGroup']] = array();
374 $values[$item['adminGroup']]['fields'] = array();
375 }
376 $values[$item['adminGroup']]['fields']["{weight}.{$item['title']}"] = $value;
377 $values[$item['adminGroup']]['component_id'] = $item['component_id'];
378 }
379
380 foreach ($values as $group => $dontCare) {
381 ksort($values[$group]);
382 }
383
384 $menu['admin'] = array('breadcrumb' => $values);
385 }
386
387 /**
388 * Get admin links.
389 *
390 * @return null
391 */
392 public static function &getAdminLinks() {
393 $links = self::get('admin');
394
395 if (!$links ||
396 !isset($links['breadcrumb'])
397 ) {
398 return NULL;
399 }
400
401 $values = &$links['breadcrumb'];
402 return $values;
403 }
404
405 /**
406 * Get the breadcrumb for a given path.
407 *
408 * @param array $menu
409 * An array of all the menu items.
410 * @param string $path
411 * Path for which breadcrumb is to be build.
412 *
413 * @return array
414 * The breadcrumb for this path
415 */
416 public static function buildBreadcrumb(&$menu, $path) {
417 $crumbs = array();
418
419 $pathElements = explode('/', $path);
420 array_pop($pathElements);
421
422 $currentPath = NULL;
423 while ($newPath = array_shift($pathElements)) {
424 $currentPath = $currentPath ? ($currentPath . '/' . $newPath) : $newPath;
425
426 // when we come across breadcrumb which involves ids,
427 // we should skip now and later on append dynamically.
428 if (isset($menu[$currentPath]['skipBreadcrumb'])) {
429 continue;
430 }
431
432 // add to crumb, if current-path exists in params.
433 if (array_key_exists($currentPath, $menu) &&
434 isset($menu[$currentPath]['title'])
435 ) {
436 $urlVar = !empty($menu[$currentPath]['path_arguments']) ? '&' . $menu[$currentPath]['path_arguments'] : '';
437 $crumbs[] = array(
438 'title' => $menu[$currentPath]['title'],
439 'url' => CRM_Utils_System::url($currentPath,
440 'reset=1' . $urlVar,
441 // absolute
442 FALSE,
443 // fragment
444 NULL,
445 // htmlize
446 TRUE,
447 // frontend
448 FALSE,
449 // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
450 TRUE
451 ),
452 );
453 }
454 }
455 $menu[$path]['breadcrumb'] = $crumbs;
456
457 return $crumbs;
458 }
459
460 /**
461 * @param $menu
462 * @param $path
463 */
464 public static function buildReturnUrl(&$menu, $path) {
465 if (!isset($menu[$path]['return_url'])) {
466 list($menu[$path]['return_url'], $menu[$path]['return_url_args']) = self::getReturnUrl($menu, $path);
467 }
468 }
469
470 /**
471 * @param $menu
472 * @param $path
473 *
474 * @return array
475 */
476 public static function getReturnUrl(&$menu, $path) {
477 if (!isset($menu[$path]['return_url'])) {
478 $pathElements = explode('/', $path);
479 array_pop($pathElements);
480
481 if (empty($pathElements)) {
482 return array(NULL, NULL);
483 }
484 $newPath = implode('/', $pathElements);
485
486 return self::getReturnUrl($menu, $newPath);
487 }
488 else {
489 return array(
490 CRM_Utils_Array::value('return_url',
491 $menu[$path]
492 ),
493 CRM_Utils_Array::value('return_url_args',
494 $menu[$path]
495 ),
496 );
497 }
498 }
499
500 /**
501 * @param $menu
502 * @param $path
503 *
504 * @throws \CRM_Core_Exception
505 */
506 public static function fillComponentIds(&$menu, $path) {
507 static $cache = array();
508
509 if (array_key_exists('component_id', $menu[$path])) {
510 return;
511 }
512
513 $args = explode('/', $path);
514
515 if (count($args) > 1) {
516 $compPath = $args[0] . '/' . $args[1];
517 }
518 else {
519 $compPath = $args[0];
520 }
521
522 $componentId = NULL;
523
524 if (array_key_exists($compPath, $cache)) {
525 $menu[$path]['component_id'] = $cache[$compPath];
526 }
527 else {
528 if (!empty($menu[$compPath]['component'])) {
529 $componentId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Component',
530 $menu[$compPath]['component'],
531 'id', 'name'
532 );
533 }
534 $menu[$path]['component_id'] = $componentId ? $componentId : NULL;
535 $cache[$compPath] = $menu[$path]['component_id'];
536 }
537 }
538
539 /**
540 * @param $path string
541 * Path of menu item to retrieve.
542 *
543 * @return array
544 * Menu entry array.
545 */
546 public static function get($path) {
547 // return null if menu rebuild
548 $config = CRM_Core_Config::singleton();
549
550 $args = explode('/', $path);
551
552 $elements = array();
553 while (!empty($args)) {
554 $string = implode('/', $args);
555 $string = CRM_Core_DAO::escapeString($string);
556 $elements[] = "'{$string}'";
557 array_pop($args);
558 }
559
560 $queryString = implode(', ', $elements);
561 $domainID = CRM_Core_Config::domainID();
562
563 $query = "
564 (
565 SELECT *
566 FROM civicrm_menu
567 WHERE path in ( $queryString )
568 AND domain_id = $domainID
569 ORDER BY length(path) DESC
570 LIMIT 1
571 )
572 ";
573
574 if ($path != 'navigation') {
575 $query .= "
576 UNION (
577 SELECT *
578 FROM civicrm_menu
579 WHERE path IN ( 'navigation' )
580 AND domain_id = $domainID
581 )
582 ";
583 }
584
585 $menu = new CRM_Core_DAO_Menu();
586 $menu->query($query);
587
588 self::$_menuCache = array();
589 $menuPath = NULL;
590 while ($menu->fetch()) {
591 self::$_menuCache[$menu->path] = array();
592 CRM_Core_DAO::storeValues($menu, self::$_menuCache[$menu->path]);
593
594 // Move module_data into main item.
595 if (isset(self::$_menuCache[$menu->path]['module_data'])) {
596 CRM_Utils_Array::extend(self::$_menuCache[$menu->path],
597 CRM_Utils_String::unserialize(self::$_menuCache[$menu->path]['module_data']));
598 unset(self::$_menuCache[$menu->path]['module_data']);
599 }
600
601 // Unserialize other elements.
602 foreach (self::$_serializedElements as $element) {
603 self::$_menuCache[$menu->path][$element] = CRM_Utils_String::unserialize($menu->$element);
604
605 if (strpos($path, $menu->path) !== FALSE) {
606 $menuPath = &self::$_menuCache[$menu->path];
607 }
608 }
609 }
610
611 if (strstr($path, 'report/instance')) {
612 $args = explode('/', $path);
613 if (is_numeric(end($args))) {
614 $menuPath['path'] .= '/' . end($args);
615 }
616 }
617
618 // *FIXME* : hack for 4.1 -> 4.2 upgrades.
619 if (preg_match('/^civicrm\/(upgrade\/)?queue\//', $path)) {
620 CRM_Queue_Menu::alter($path, $menuPath);
621 }
622
623 // Part of upgrade framework but not run inside main upgrade because it deletes data
624 // Once we have another example of a 'cleanup' we should generalize the clause below so it grabs string
625 // which follows upgrade/ and checks for existence of a function in Cleanup class.
626 if ($path == 'civicrm/upgrade/cleanup425') {
627 $menuPath['page_callback'] = array('CRM_Upgrade_Page_Cleanup', 'cleanup425');
628 $menuPath['access_arguments'][0][] = 'administer CiviCRM';
629 $menuPath['access_callback'] = array('CRM_Core_Permission', 'checkMenu');
630 }
631
632 if (!empty($menuPath)) {
633 $i18n = CRM_Core_I18n::singleton();
634 $i18n->localizeTitles($menuPath);
635 }
636 return $menuPath;
637 }
638
639 /**
640 * @param $pathArgs
641 *
642 * @return mixed
643 */
644 public static function getArrayForPathArgs($pathArgs) {
645 if (!is_string($pathArgs)) {
646 return;
647 }
648 $args = array();
649
650 $elements = explode(',', $pathArgs);
651 foreach ($elements as $keyVal) {
652 list($key, $val) = explode('=', $keyVal, 2);
653 $arr[$key] = $val;
654 }
655
656 if (array_key_exists('urlToSession', $arr)) {
657 $urlToSession = array();
658
659 $params = explode(';', $arr['urlToSession']);
660 $count = 0;
661 foreach ($params as $keyVal) {
662 list($urlToSession[$count]['urlVar'],
663 $urlToSession[$count]['sessionVar'],
664 $urlToSession[$count]['type'],
665 $urlToSession[$count]['default']
666 ) = explode(':', $keyVal);
667 $count++;
668 }
669 $arr['urlToSession'] = $urlToSession;
670 }
671 return $arr;
672 }
673
674 }