Merge pull request #24059 from eileenmcnaughton/pledged
[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 /**
20 * Class CRM_Core_Menu.
21 */
22 class CRM_Core_Menu {
23
24 /**
25 * The list of menu items.
26 *
27 * @var array
28 */
29 public static $_items = NULL;
30
31 /**
32 * The list of permissioned menu items.
33 *
34 * @var array
35 */
36 public static $_permissionedItems = NULL;
37
38 public static $_serializedElements = [
39 'access_arguments',
40 'access_callback',
41 'page_arguments',
42 'page_callback',
43 'breadcrumb',
44 ];
45
46 public static $_menuCache = NULL;
47 const MENU_ITEM = 1;
48
49 /**
50 * This function fetches the menu items from xml and xmlMenu hooks.
51 *
52 * @param bool $fetchFromXML
53 * Fetch the menu items from xml and not from cache.
54 *
55 * @return array
56 */
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);
62 global $civicrm_root;
63 $files = CRM_Utils_File::getFilesByExtension($civicrm_root . DIRECTORY_SEPARATOR . $coreMenuFilesPath, 'xml');
64
65 // Grab component menu files
66 $files = array_merge($files,
67 CRM_Core_Component::xmlMenu()
68 );
69
70 // lets call a hook and get any additional files if needed
71 CRM_Utils_Hook::xmlMenu($files);
72
73 self::$_items = [];
74 foreach ($files as $file) {
75 self::read($file, self::$_items);
76 }
77
78 CRM_Utils_Hook::alterMenu(self::$_items);
79 }
80
81 return self::$_items;
82 }
83
84 /**
85 * Read menu.
86 *
87 * @param string $name
88 * File name
89 * @param array $menu
90 * An alterable list of menu items.
91 *
92 * @throws Exception
93 */
94 public static function read($name, &$menu) {
95 $xml = simplexml_load_string(file_get_contents($name));
96 self::readXML($xml, $menu);
97 }
98
99 /**
100 * @param SimpleXMLElement $xml
101 * An XML document defining a list of menu items.
102 * @param array $menu
103 * An alterable list of menu items.
104 *
105 * @throws CRM_Core_Exception
106 */
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');
113 }
114 $path = (string ) $item->path;
115 $menu[$path] = [];
116 unset($item->path);
117
118 if ($item->ids_arguments) {
119 $ids = [];
120 foreach (['json' => 'json', 'html' => 'html', 'exception' => 'exceptions'] as $tag => $attr) {
121 $ids[$attr] = [];
122 foreach ($item->ids_arguments->{$tag} as $value) {
123 $ids[$attr][] = (string) $value;
124 }
125 }
126 $menu[$path]['ids_arguments'] = $ids;
127 unset($item->ids_arguments);
128 }
129
130 foreach ($item as $key => $value) {
131 $key = (string ) $key;
132 $value = (string ) $value;
133 if (strpos($key, '_callback') &&
134 strpos($value, '::')
135 ) {
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);
139 }
140 elseif ($key == 'access_arguments') {
141 // FIXME Move the permission parser to its own class (or *maybe* CRM_Core_Permission).
142 if (strpos($value, ',') ||
143 strpos($value, ';')
144 ) {
145 if (strpos($value, ',')) {
146 $elements = explode(',', $value);
147 $op = 'and';
148 }
149 else {
150 $elements = explode(';', $value);
151 $op = 'or';
152 }
153 $items = [];
154 foreach ($elements as $element) {
155 $items[] = $element;
156 }
157 $value = [$items, $op];
158 }
159 else {
160 $value = [[$value], 'and'];
161 }
162 }
163 elseif ($key == 'is_public' || $key == 'is_ssl') {
164 $value = ($value == 'true' || $value == 1) ? 1 : 0;
165 }
166 $menu[$path][$key] = $value;
167 }
168 }
169 }
170
171 /**
172 * This function defines information for various menu items.
173 *
174 * @param bool $fetchFromXML
175 * Fetch the menu items from xml and not from cache.
176 *
177 * @return array
178 */
179 public static function &items($fetchFromXML = FALSE) {
180 return self::xmlItems($fetchFromXML);
181 }
182
183 /**
184 * Is array true (whatever that means!).
185 *
186 * @param array $values
187 *
188 * @return bool
189 */
190 public static function isArrayTrue($values) {
191 foreach ($values as $value) {
192 if (!$value) {
193 return FALSE;
194 }
195 }
196 return TRUE;
197 }
198
199 /**
200 * Fill menu values.
201 *
202 * @param array $menu
203 * @param string $path
204 *
205 * @throws CRM_Core_Exception
206 */
207 public static function fillMenuValues(&$menu, $path) {
208 $fieldsToPropagate = [
209 'access_callback',
210 'access_arguments',
211 'page_callback',
212 'page_arguments',
213 'is_ssl',
214 ];
215 $fieldsPresent = [];
216 foreach ($fieldsToPropagate as $field) {
217 $fieldsPresent[$field] = isset($menu[$path][$field]);
218 }
219
220 $args = explode('/', $path);
221 while (!self::isArrayTrue($fieldsPresent) && !empty($args)) {
222
223 array_pop($args);
224 $parentPath = implode('/', $args);
225
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;
232 }
233 }
234 }
235 }
236
237 if (self::isArrayTrue($fieldsPresent)) {
238 return;
239 }
240
241 $messages = [];
242 foreach ($fieldsToPropagate as $field) {
243 if (!$fieldsPresent[$field]) {
244 $messages[] = ts("Could not find %1 in path tree",
245 [1 => $field]
246 );
247 }
248 }
249 throw new CRM_Core_Exception("'$path': " . implode(', ', $messages));
250 }
251
252 /**
253 * We use this function to.
254 *
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
259 *
260 * @param array $menu
261 */
262 public static function build(&$menu) {
263 foreach ($menu as $path => $menuItems) {
264 try {
265 self::buildBreadcrumb($menu, $path);
266 self::fillMenuValues($menu, $path);
267 self::fillComponentIds($menu, $path);
268 self::buildReturnUrl($menu, $path);
269
270 // add add page_type if not present
271 if (!isset($menu[$path]['page_type'])) {
272 $menu[$path]['page_type'] = 0;
273 }
274 }
275 catch (CRM_Core_Exception $e) {
276 Civi::log()->error('Menu path skipped:' . $e->getMessage());
277 }
278 }
279
280 self::buildAdminLinks($menu);
281 }
282
283 /**
284 * This function recomputes menu from xml and populates civicrm_menu.
285 *
286 * @param bool $truncate
287 */
288 public static function store($truncate = TRUE) {
289 // first clean up the db
290 if ($truncate) {
291 $query = 'TRUNCATE civicrm_menu';
292 CRM_Core_DAO::executeQuery($query);
293 }
294 $menuArray = self::items($truncate);
295
296 self::build($menuArray);
297
298 $daoFields = CRM_Core_DAO_Menu::fields();
299
300 foreach ($menuArray as $path => $item) {
301 $menu = new CRM_Core_DAO_Menu();
302 $menu->path = $path;
303 $menu->domain_id = CRM_Core_Config::domainID();
304
305 $menu->find(TRUE);
306
307 if (!CRM_Core_Config::isUpgradeMode() ||
308 CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_menu', 'module_data', FALSE)
309 ) {
310 // Move unrecognized fields to $module_data.
311 $module_data = [];
312 foreach (array_keys($item) as $key) {
313 if (!isset($daoFields[$key])) {
314 $module_data[$key] = $item[$key];
315 unset($item[$key]);
316 }
317 }
318
319 $menu->module_data = serialize($module_data);
320 }
321
322 $menu->copyValues($item);
323
324 foreach (self::$_serializedElements as $element) {
325 if (!isset($item[$element]) ||
326 $item[$element] == 'null'
327 ) {
328 $menu->$element = NULL;
329 }
330 else {
331 $menu->$element = serialize($item[$element]);
332 }
333 }
334
335 $menu->save();
336 }
337 }
338
339 /**
340 * Build admin links.
341 *
342 * @param array $menu
343 */
344 public static function buildAdminLinks(&$menu) {
345 $values = [];
346
347 foreach ($menu as $path => $item) {
348 if (empty($item['adminGroup'])) {
349 continue;
350 }
351
352 $query = !empty($item['path_arguments']) ? str_replace(',', '&', $item['path_arguments']) . '&reset=1' : 'reset=1';
353
354 $value = [
355 'title' => $item['title'],
356 'desc' => $item['desc'] ?? NULL,
357 'id' => strtr($item['title'], [
358 '(' => '_',
359 ')' => '',
360 ' ' => '',
361 ',' => '_',
362 '/' => '_',
363 ]),
364 'url' => CRM_Utils_System::url($path, $query,
365 FALSE,
366 NULL,
367 TRUE,
368 FALSE,
369 // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
370 TRUE
371 ),
372 'icon' => $item['icon'] ?? NULL,
373 'extra' => $item['extra'] ?? NULL,
374 ];
375 if (!array_key_exists($item['adminGroup'], $values)) {
376 $values[$item['adminGroup']] = [];
377 $values[$item['adminGroup']]['fields'] = [];
378 }
379 $values[$item['adminGroup']]['fields']["{weight}.{$item['title']}"] = $value;
380 $values[$item['adminGroup']]['component_id'] = $item['component_id'];
381 }
382
383 foreach ($values as $group => $dontCare) {
384 ksort($values[$group]);
385 }
386
387 $menu['admin'] = ['breadcrumb' => $values];
388 }
389
390 /**
391 * Get admin links.
392 *
393 * @return array|null
394 */
395 public static function getAdminLinks() {
396 $links = self::get('admin');
397 return $links['breadcrumb'] ?? NULL;
398 }
399
400 /**
401 * Get the breadcrumb for a given path.
402 *
403 * @param array $menu
404 * An array of all the menu items.
405 * @param string $path
406 * Path for which breadcrumb is to be build.
407 *
408 * @return array
409 * The breadcrumb for this path
410 */
411 public static function buildBreadcrumb(&$menu, $path) {
412 $crumbs = [];
413
414 $pathElements = explode('/', $path);
415 array_pop($pathElements);
416
417 $currentPath = NULL;
418 while ($newPath = array_shift($pathElements)) {
419 $currentPath = $currentPath ? ($currentPath . '/' . $newPath) : $newPath;
420
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'])) {
424 continue;
425 }
426
427 // add to crumb, if current-path exists in params.
428 if (array_key_exists($currentPath, $menu) &&
429 isset($menu[$currentPath]['title'])
430 ) {
431 $urlVar = !empty($menu[$currentPath]['path_arguments']) ? '&' . $menu[$currentPath]['path_arguments'] : '';
432 $crumbs[] = [
433 'title' => $menu[$currentPath]['title'],
434 'url' => CRM_Utils_System::url($currentPath,
435 'reset=1' . $urlVar,
436 // absolute
437 FALSE,
438 // fragment
439 NULL,
440 // htmlize
441 TRUE,
442 // frontend
443 FALSE,
444 // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
445 TRUE
446 ),
447 ];
448 }
449 }
450 $menu[$path]['breadcrumb'] = $crumbs;
451
452 return $crumbs;
453 }
454
455 /**
456 * @param array $menu
457 * @param string|int $path
458 */
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);
462 }
463 }
464
465 /**
466 * @param $menu
467 * @param $path
468 *
469 * @return array
470 */
471 public static function getReturnUrl(&$menu, $path) {
472 if (!isset($menu[$path]['return_url'])) {
473 $pathElements = explode('/', $path);
474 array_pop($pathElements);
475
476 if (empty($pathElements)) {
477 return [NULL, NULL];
478 }
479 $newPath = implode('/', $pathElements);
480
481 return self::getReturnUrl($menu, $newPath);
482 }
483 else {
484 return [
485 $menu[$path]['return_url'] ?? NULL,
486 $menu[$path]['return_url_args'] ?? NULL,
487 ];
488 }
489 }
490
491 /**
492 * @param $menu
493 * @param $path
494 *
495 * @throws \CRM_Core_Exception
496 */
497 public static function fillComponentIds(&$menu, $path) {
498 static $cache = [];
499
500 if (array_key_exists('component_id', $menu[$path])) {
501 return;
502 }
503
504 $args = explode('/', $path);
505
506 if (count($args) > 1) {
507 $compPath = $args[0] . '/' . $args[1];
508 }
509 else {
510 $compPath = $args[0];
511 }
512
513 $componentId = NULL;
514
515 if (array_key_exists($compPath, $cache)) {
516 $menu[$path]['component_id'] = $cache[$compPath];
517 }
518 else {
519 if (!empty($menu[$compPath]['component'])) {
520 $componentId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Component',
521 $menu[$compPath]['component'],
522 'id', 'name'
523 );
524 }
525 $menu[$path]['component_id'] = $componentId ? $componentId : NULL;
526 $cache[$compPath] = $menu[$path]['component_id'];
527 }
528 }
529
530 /**
531 * @param string $path
532 * Path of menu item to retrieve.
533 *
534 * @return array
535 * Menu entry array.
536 */
537 public static function get($path) {
538 $args = explode('/', $path);
539
540 $elements = [];
541 while (!empty($args)) {
542 $string = implode('/', $args);
543 $string = CRM_Core_DAO::escapeString($string);
544 $elements[] = "'{$string}'";
545 array_pop($args);
546 }
547
548 $queryString = implode(', ', $elements);
549 $domainID = CRM_Core_Config::domainID();
550
551 $query = "
552 (
553 SELECT *
554 FROM civicrm_menu
555 WHERE path in ( $queryString )
556 AND domain_id = $domainID
557 ORDER BY length(path) DESC
558 LIMIT 1
559 )
560 ";
561
562 if ($path != 'navigation') {
563 $query .= "
564 UNION (
565 SELECT *
566 FROM civicrm_menu
567 WHERE path IN ( 'navigation' )
568 AND domain_id = $domainID
569 )
570 ";
571 }
572
573 $menu = new CRM_Core_DAO_Menu();
574 $menu->query($query);
575
576 self::$_menuCache = [];
577 $menuPath = NULL;
578 while ($menu->fetch()) {
579 self::$_menuCache[$menu->path] = [];
580 CRM_Core_DAO::storeValues($menu, self::$_menuCache[$menu->path]);
581
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']);
587 }
588
589 // Unserialize other elements.
590 foreach (self::$_serializedElements as $element) {
591 self::$_menuCache[$menu->path][$element] = CRM_Utils_String::unserialize($menu->$element);
592
593 if (strpos($path, $menu->path) !== FALSE) {
594 $menuPath = &self::$_menuCache[$menu->path];
595 }
596 }
597 }
598
599 if (strstr($path, 'report/instance')) {
600 $args = explode('/', $path);
601 if (is_numeric(end($args))) {
602 $menuPath['path'] .= '/' . end($args);
603 }
604 }
605
606 if (preg_match('/^civicrm\/(upgrade\/)?queue\//', $path)) {
607 CRM_Queue_Menu::alter($path, $menuPath);
608 }
609
610 if (!empty($menuPath)) {
611 $i18n = CRM_Core_I18n::singleton();
612 $i18n->localizeTitles($menuPath);
613 }
614 return $menuPath;
615 }
616
617 /**
618 * @param $pathArgs
619 *
620 * @return mixed
621 */
622 public static function getArrayForPathArgs($pathArgs) {
623 if (!is_string($pathArgs)) {
624 return;
625 }
626 $arr = [];
627
628 $elements = explode(',', $pathArgs);
629 foreach ($elements as $keyVal) {
630 list($key, $val) = explode('=', $keyVal, 2);
631 $arr[$key] = $val;
632 }
633
634 if (array_key_exists('urlToSession', $arr)) {
635 $urlToSession = [];
636
637 $params = explode(';', $arr['urlToSession']);
638 $count = 0;
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);
645 $count++;
646 }
647 $arr['urlToSession'] = $urlToSession;
648 }
649 return $arr;
650 }
651
652 }