Queue - When UserJob.queue_id works down to zero tasks, update status and fire hook
[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
28518c90 19/**
ad37ac8e 20 * Class CRM_Core_Menu.
28518c90 21 */
6a488035
TO
22class CRM_Core_Menu {
23
24 /**
fe482240 25 * The list of menu items.
6a488035
TO
26 *
27 * @var array
6a488035 28 */
518fa0ee 29 public static $_items = NULL;
6a488035
TO
30
31 /**
fe482240 32 * The list of permissioned menu items.
6a488035
TO
33 *
34 * @var array
6a488035 35 */
518fa0ee 36 public static $_permissionedItems = NULL;
6a488035 37
1a7f0e94 38 public static $_serializedElements = [
6a488035
TO
39 'access_arguments',
40 'access_callback',
41 'page_arguments',
42 'page_callback',
43 'breadcrumb',
1a7f0e94 44 ];
6a488035 45
518fa0ee 46 public static $_menuCache = NULL;
7da04cde 47 const MENU_ITEM = 1;
6a488035 48
a0ee3941 49 /**
fe482240 50 * This function fetches the menu items from xml and xmlMenu hooks.
49d97c48 51 *
ad37ac8e 52 * @param bool $fetchFromXML
6a0b768e 53 * Fetch the menu items from xml and not from cache.
49d97c48 54 *
a0ee3941
EM
55 * @return array
56 */
00be9182 57 public static function &xmlItems($fetchFromXML = FALSE) {
49d97c48 58 if (!self::$_items || $fetchFromXML) {
6a488035
TO
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
affcc9d2 73 self::$_items = [];
6a488035
TO
74 foreach ($files as $file) {
75 self::read($file, self::$_items);
76 }
7dc34fb8
TO
77
78 CRM_Utils_Hook::alterMenu(self::$_items);
6a488035
TO
79 }
80
81 return self::$_items;
82 }
83
a0ee3941 84 /**
ad37ac8e 85 * Read menu.
86 *
100fef9d 87 * @param string $name
5bfe764c
TO
88 * File name
89 * @param array $menu
90 * An alterable list of menu items.
a0ee3941
EM
91 *
92 * @throws Exception
93 */
00be9182 94 public static function read($name, &$menu) {
292fbfa3 95 $xml = simplexml_load_string(file_get_contents($name));
5bfe764c
TO
96 self::readXML($xml, $menu);
97 }
6a488035 98
5bfe764c
TO
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.
ac15829d
SL
104 *
105 * @throws CRM_Core_Exception
5bfe764c
TO
106 */
107 public static function readXML($xml, &$menu) {
6a488035 108 $config = CRM_Core_Config::singleton();
6a488035
TO
109 foreach ($xml->item as $item) {
110 if (!(string ) $item->path) {
111 CRM_Core_Error::debug('i', $item);
ac15829d 112 throw new CRM_Core_Exception('Unable to read XML file');
6a488035
TO
113 }
114 $path = (string ) $item->path;
affcc9d2 115 $menu[$path] = [];
6a488035 116 unset($item->path);
4535c1f5
TO
117
118 if ($item->ids_arguments) {
affcc9d2 119 $ids = [];
1a7f0e94 120 foreach (['json' => 'json', 'html' => 'html', 'exception' => 'exceptions'] as $tag => $attr) {
affcc9d2 121 $ids[$attr] = [];
36d4fa1b
TO
122 foreach ($item->ids_arguments->{$tag} as $value) {
123 $ids[$attr][] = (string) $value;
4535c1f5
TO
124 }
125 }
126 $menu[$path]['ids_arguments'] = $ids;
127 unset($item->ids_arguments);
128 }
129
6a488035
TO
130 foreach ($item as $key => $value) {
131 $key = (string ) $key;
132 $value = (string ) $value;
133 if (strpos($key, '_callback') &&
134 strpos($value, '::')
135 ) {
c8074a93
TO
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)).
6a488035
TO
138 $value = explode('::', $value);
139 }
140 elseif ($key == 'access_arguments') {
c8074a93 141 // FIXME Move the permission parser to its own class (or *maybe* CRM_Core_Permission).
6a488035
TO
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 }
affcc9d2 153 $items = [];
6a488035
TO
154 foreach ($elements as $element) {
155 $items[] = $element;
156 }
1a7f0e94 157 $value = [$items, $op];
6a488035
TO
158 }
159 else {
1a7f0e94 160 $value = [[$value], 'and'];
6a488035
TO
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 /**
fe482240 172 * This function defines information for various menu items.
6a488035 173 *
ad37ac8e 174 * @param bool $fetchFromXML
6a0b768e 175 * Fetch the menu items from xml and not from cache.
49d97c48 176 *
7a9ab499 177 * @return array
6a488035 178 */
00be9182 179 public static function &items($fetchFromXML = FALSE) {
49d97c48 180 return self::xmlItems($fetchFromXML);
6a488035
TO
181 }
182
a0ee3941 183 /**
ad37ac8e 184 * Is array true (whatever that means!).
185 *
186 * @param array $values
a0ee3941
EM
187 *
188 * @return bool
189 */
1a7f0e94
CW
190 public static function isArrayTrue($values) {
191 foreach ($values as $value) {
6a488035
TO
192 if (!$value) {
193 return FALSE;
194 }
195 }
196 return TRUE;
197 }
198
a0ee3941 199 /**
ad37ac8e 200 * Fill menu values.
201 *
202 * @param array $menu
203 * @param string $path
a0ee3941 204 *
ac15829d 205 * @throws CRM_Core_Exception
a0ee3941 206 */
00be9182 207 public static function fillMenuValues(&$menu, $path) {
1a7f0e94 208 $fieldsToPropagate = [
6a488035
TO
209 'access_callback',
210 'access_arguments',
211 'page_callback',
212 'page_arguments',
213 'is_ssl',
1a7f0e94 214 ];
affcc9d2 215 $fieldsPresent = [];
6a488035 216 foreach ($fieldsToPropagate as $field) {
63d76404 217 $fieldsPresent[$field] = isset($menu[$path][$field]);
6a488035
TO
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]) {
8d9ce16a 228 $fieldInParentMenu = $menu[$parentPath][$field] ?? NULL;
229 if ($fieldInParentMenu !== NULL) {
6a488035 230 $fieldsPresent[$field] = TRUE;
8d9ce16a 231 $menu[$path][$field] = $fieldInParentMenu;
6a488035
TO
232 }
233 }
234 }
235 }
236
237 if (self::isArrayTrue($fieldsPresent)) {
238 return;
239 }
240
ac15829d 241 $messages = [];
6a488035
TO
242 foreach ($fieldsToPropagate as $field) {
243 if (!$fieldsPresent[$field]) {
244 $messages[] = ts("Could not find %1 in path tree",
ac15829d 245 [1 => $field]
6a488035
TO
246 );
247 }
248 }
ac15829d 249 throw new CRM_Core_Exception("'$path': " . implode(', ', $messages));
6a488035
TO
250 }
251
252 /**
fe482240 253 * We use this function to.
6a488035
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
ea3ddccf 259 *
260 * @param array $menu
6a488035 261 */
00be9182 262 public static function build(&$menu) {
6a488035 263 foreach ($menu as $path => $menuItems) {
bc537a0c 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());
6a488035
TO
277 }
278 }
279
280 self::buildAdminLinks($menu);
281 }
282
a0ee3941 283 /**
fe482240 284 * This function recomputes menu from xml and populates civicrm_menu.
ad37ac8e 285 *
a0ee3941
EM
286 * @param bool $truncate
287 */
00be9182 288 public static function store($truncate = TRUE) {
6a488035
TO
289 // first clean up the db
290 if ($truncate) {
291 $query = 'TRUNCATE civicrm_menu';
292 CRM_Core_DAO::executeQuery($query);
293 }
49d97c48 294 $menuArray = self::items($truncate);
6a488035
TO
295
296 self::build($menuArray);
297
b44dc91e 298 $daoFields = CRM_Core_DAO_Menu::fields();
6a488035
TO
299
300 foreach ($menuArray as $path => $item) {
353ffa53
TO
301 $menu = new CRM_Core_DAO_Menu();
302 $menu->path = $path;
6a488035
TO
303 $menu->domain_id = CRM_Core_Config::domainID();
304
305 $menu->find(TRUE);
306
d6f1a16c 307 if (!CRM_Core_Config::isUpgradeMode() ||
eed7e803 308 CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_menu', 'module_data', FALSE)
d6f1a16c
NM
309 ) {
310 // Move unrecognized fields to $module_data.
affcc9d2 311 $module_data = [];
d6f1a16c
NM
312 foreach (array_keys($item) as $key) {
313 if (!isset($daoFields[$key])) {
314 $module_data[$key] = $item[$key];
315 unset($item[$key]);
316 }
b44dc91e 317 }
b44dc91e 318
d6f1a16c
NM
319 $menu->module_data = serialize($module_data);
320 }
6a488035 321
c09129a5
NM
322 $menu->copyValues($item);
323
6a488035
TO
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
a0ee3941 339 /**
ad37ac8e 340 * Build admin links.
341 *
342 * @param array $menu
a0ee3941 343 */
00be9182 344 public static function buildAdminLinks(&$menu) {
affcc9d2 345 $values = [];
6a488035
TO
346
347 foreach ($menu as $path => $item) {
a7488080 348 if (empty($item['adminGroup'])) {
6a488035
TO
349 continue;
350 }
351
0d8afee2 352 $query = !empty($item['path_arguments']) ? str_replace(',', '&', $item['path_arguments']) . '&reset=1' : 'reset=1';
6a488035 353
1a7f0e94 354 $value = [
6a488035 355 'title' => $item['title'],
6b409353 356 'desc' => $item['desc'] ?? NULL,
1a7f0e94 357 'id' => strtr($item['title'], [
518fa0ee
SL
358 '(' => '_',
359 ')' => '',
360 ' ' => '',
361 ',' => '_',
362 '/' => '_',
1a7f0e94 363 ]),
d75f2f47 364 'url' => CRM_Utils_System::url($path, $query,
ad37ac8e 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
f4bdec6a 371 ),
6b409353
CW
372 'icon' => $item['icon'] ?? NULL,
373 'extra' => $item['extra'] ?? NULL,
1a7f0e94 374 ];
6a488035 375 if (!array_key_exists($item['adminGroup'], $values)) {
affcc9d2
CW
376 $values[$item['adminGroup']] = [];
377 $values[$item['adminGroup']]['fields'] = [];
6a488035 378 }
6a488035
TO
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) {
6a488035
TO
384 ksort($values[$group]);
385 }
386
1a7f0e94 387 $menu['admin'] = ['breadcrumb' => $values];
6a488035
TO
388 }
389
a0ee3941 390 /**
ad37ac8e 391 * Get admin links.
392 *
1a7f0e94 393 * @return array|null
a0ee3941 394 */
1a7f0e94 395 public static function getAdminLinks() {
6a488035 396 $links = self::get('admin');
1a7f0e94 397 return $links['breadcrumb'] ?? NULL;
6a488035
TO
398 }
399
400 /**
401 * Get the breadcrumb for a given path.
402 *
6a0b768e
TO
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.
6a488035 407 *
a6c01b45
CW
408 * @return array
409 * The breadcrumb for this path
6a488035 410 */
00be9182 411 public static function buildBreadcrumb(&$menu, $path) {
affcc9d2 412 $crumbs = [];
6a488035
TO
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
b44e3f84 421 // when we come across breadcrumb which involves ids,
6a488035
TO
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 ) {
0d8afee2 431 $urlVar = !empty($menu[$currentPath]['path_arguments']) ? '&' . $menu[$currentPath]['path_arguments'] : '';
1a7f0e94 432 $crumbs[] = [
6a488035
TO
433 'title' => $menu[$currentPath]['title'],
434 'url' => CRM_Utils_System::url($currentPath,
38a0e912 435 'reset=1' . $urlVar,
518fa0ee
SL
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
6a488035 446 ),
1a7f0e94 447 ];
6a488035
TO
448 }
449 }
450 $menu[$path]['breadcrumb'] = $crumbs;
451
452 return $crumbs;
453 }
454
a0ee3941 455 /**
fa3fdebc
BT
456 * @param array $menu
457 * @param string|int $path
a0ee3941 458 */
00be9182 459 public static function buildReturnUrl(&$menu, $path) {
6a488035 460 if (!isset($menu[$path]['return_url'])) {
bc537a0c 461 [$menu[$path]['return_url'], $menu[$path]['return_url_args']] = self::getReturnUrl($menu, $path);
6a488035
TO
462 }
463 }
464
a0ee3941
EM
465 /**
466 * @param $menu
467 * @param $path
468 *
469 * @return array
470 */
00be9182 471 public static function getReturnUrl(&$menu, $path) {
6a488035
TO
472 if (!isset($menu[$path]['return_url'])) {
473 $pathElements = explode('/', $path);
474 array_pop($pathElements);
475
476 if (empty($pathElements)) {
1a7f0e94 477 return [NULL, NULL];
6a488035
TO
478 }
479 $newPath = implode('/', $pathElements);
480
481 return self::getReturnUrl($menu, $newPath);
482 }
483 else {
1a7f0e94
CW
484 return [
485 $menu[$path]['return_url'] ?? NULL,
486 $menu[$path]['return_url_args'] ?? NULL,
487 ];
6a488035
TO
488 }
489 }
490
a0ee3941
EM
491 /**
492 * @param $menu
493 * @param $path
508db412 494 *
495 * @throws \CRM_Core_Exception
a0ee3941 496 */
00be9182 497 public static function fillComponentIds(&$menu, $path) {
affcc9d2 498 static $cache = [];
6a488035
TO
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 {
508db412 519 if (!empty($menu[$compPath]['component'])) {
6a488035
TO
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
a0ee3941 530 /**
a2f24340 531 * @param string $path
2bc65854 532 * Path of menu item to retrieve.
a0ee3941 533 *
35146d69 534 * @return array
2bc65854 535 * Menu entry array.
a0ee3941 536 */
00be9182 537 public static function get($path) {
6a488035
TO
538 $args = explode('/', $path);
539
affcc9d2 540 $elements = [];
6a488035 541 while (!empty($args)) {
353ffa53
TO
542 $string = implode('/', $args);
543 $string = CRM_Core_DAO::escapeString($string);
6a488035
TO
544 $elements[] = "'{$string}'";
545 array_pop($args);
546 }
547
353ffa53
TO
548 $queryString = implode(', ', $elements);
549 $domainID = CRM_Core_Config::domainID();
6a488035
TO
550
551 $query = "
552(
553 SELECT *
554 FROM civicrm_menu
555 WHERE path in ( $queryString )
99a2c00a 556 AND domain_id = $domainID
6a488035
TO
557 ORDER BY length(path) DESC
558 LIMIT 1
559)
560";
561
562 if ($path != 'navigation') {
563 $query .= "
564UNION (
565 SELECT *
566 FROM civicrm_menu
567 WHERE path IN ( 'navigation' )
99a2c00a 568 AND domain_id = $domainID
6a488035
TO
569)
570";
571 }
572
573 $menu = new CRM_Core_DAO_Menu();
574 $menu->query($query);
575
affcc9d2 576 self::$_menuCache = [];
6a488035
TO
577 $menuPath = NULL;
578 while ($menu->fetch()) {
affcc9d2 579 self::$_menuCache[$menu->path] = [];
6a488035
TO
580 CRM_Core_DAO::storeValues($menu, self::$_menuCache[$menu->path]);
581
b44dc91e
TO
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],
f24846d5 585 CRM_Utils_String::unserialize(self::$_menuCache[$menu->path]['module_data']));
b44dc91e
TO
586 unset(self::$_menuCache[$menu->path]['module_data']);
587 }
588
589 // Unserialize other elements.
6a488035 590 foreach (self::$_serializedElements as $element) {
f24846d5 591 self::$_menuCache[$menu->path][$element] = CRM_Utils_String::unserialize($menu->$element);
6a488035
TO
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
6a488035
TO
606 if (preg_match('/^civicrm\/(upgrade\/)?queue\//', $path)) {
607 CRM_Queue_Menu::alter($path, $menuPath);
608 }
609
6a488035
TO
610 if (!empty($menuPath)) {
611 $i18n = CRM_Core_I18n::singleton();
612 $i18n->localizeTitles($menuPath);
613 }
614 return $menuPath;
615 }
616
a0ee3941
EM
617 /**
618 * @param $pathArgs
619 *
620 * @return mixed
621 */
00be9182 622 public static function getArrayForPathArgs($pathArgs) {
6a488035
TO
623 if (!is_string($pathArgs)) {
624 return;
625 }
1a7f0e94 626 $arr = [];
6a488035
TO
627
628 $elements = explode(',', $pathArgs);
6a488035 629 foreach ($elements as $keyVal) {
3b4339fd 630 list($key, $val) = explode('=', $keyVal, 2);
6a488035
TO
631 $arr[$key] = $val;
632 }
633
634 if (array_key_exists('urlToSession', $arr)) {
affcc9d2 635 $urlToSession = [];
6a488035
TO
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']
353ffa53 644 ) = explode(':', $keyVal);
6a488035
TO
645 $count++;
646 }
647 $arr['urlToSession'] = $urlToSession;
648 }
649 return $arr;
650 }
96025800 651
6a488035 652}