CRM-15578 - Add Civi\Core\Resolver. Fix loading of Angular content after updating...
[civicrm-core.git] / CRM / Core / Menu.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 * This file contains the various menus of the CiviCRM module
30 *
31 * @package CRM
06b69b18 32 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
33 * $Id$
34 *
35 */
36
37require_once 'CRM/Core/I18n.php';
28518c90
EM
38
39/**
40 * Class CRM_Core_Menu
41 */
6a488035
TO
42class CRM_Core_Menu {
43
44 /**
100fef9d 45 * The list of menu items
6a488035
TO
46 *
47 * @var array
6a488035
TO
48 */
49 static $_items = NULL;
50
51 /**
100fef9d 52 * The list of permissioned menu items
6a488035
TO
53 *
54 * @var array
6a488035
TO
55 */
56 static $_permissionedItems = NULL;
57
58 static $_serializedElements = array(
59 'access_arguments',
60 'access_callback',
61 'page_arguments',
62 'page_callback',
63 'breadcrumb',
64 );
65
66 static $_menuCache = NULL;
7da04cde 67 const MENU_ITEM = 1;
6a488035 68
a0ee3941 69 /**
49d97c48 70 * This function fetches the menu items from xml and xmlMenu hooks
71 *
6a0b768e
TO
72 * @param boolen $fetchFromXML
73 * Fetch the menu items from xml and not from cache.
49d97c48 74 *
a0ee3941
EM
75 * @return array
76 */
00be9182 77 public static function &xmlItems($fetchFromXML = FALSE) {
49d97c48 78 if (!self::$_items || $fetchFromXML) {
6a488035
TO
79 $config = CRM_Core_Config::singleton();
80
81 // We needs this until Core becomes a component
82 $coreMenuFilesNamespace = 'CRM_Core_xml_Menu';
83 $coreMenuFilesPath = str_replace('_', DIRECTORY_SEPARATOR, $coreMenuFilesNamespace);
84 global $civicrm_root;
85 $files = CRM_Utils_File::getFilesByExtension($civicrm_root . DIRECTORY_SEPARATOR . $coreMenuFilesPath, 'xml');
86
87 // Grab component menu files
88 $files = array_merge($files,
89 CRM_Core_Component::xmlMenu()
90 );
91
92 // lets call a hook and get any additional files if needed
93 CRM_Utils_Hook::xmlMenu($files);
94
95 self::$_items = array();
96 foreach ($files as $file) {
97 self::read($file, self::$_items);
98 }
99 }
100
101 return self::$_items;
102 }
103
a0ee3941 104 /**
100fef9d 105 * @param string $name
a0ee3941
EM
106 * @param $menu
107 *
108 * @throws Exception
109 */
00be9182 110 public static function read($name, &$menu) {
6a488035
TO
111
112 $config = CRM_Core_Config::singleton();
113
114 $xml = simplexml_load_file($name);
115 foreach ($xml->item as $item) {
116 if (!(string ) $item->path) {
117 CRM_Core_Error::debug('i', $item);
118 CRM_Core_Error::fatal();
119 }
120 $path = (string ) $item->path;
121 $menu[$path] = array();
122 unset($item->path);
123 foreach ($item as $key => $value) {
124 $key = (string ) $key;
125 $value = (string ) $value;
126 if (strpos($key, '_callback') &&
127 strpos($value, '::')
128 ) {
c8074a93
TO
129 // FIXME Remove the rewrite at this level. Instead, change downstream call_user_func*($value)
130 // to call_user_func*(Civi\Core\Resolver::singleton()->get($value)).
6a488035
TO
131 $value = explode('::', $value);
132 }
133 elseif ($key == 'access_arguments') {
c8074a93 134 // FIXME Move the permission parser to its own class (or *maybe* CRM_Core_Permission).
6a488035
TO
135 if (strpos($value, ',') ||
136 strpos($value, ';')
137 ) {
138 if (strpos($value, ',')) {
139 $elements = explode(',', $value);
140 $op = 'and';
141 }
142 else {
143 $elements = explode(';', $value);
144 $op = 'or';
145 }
146 $items = array();
147 foreach ($elements as $element) {
148 $items[] = $element;
149 }
150 $value = array($items, $op);
151 }
152 else {
153 $value = array(array($value), 'and');
154 }
155 }
156 elseif ($key == 'is_public' || $key == 'is_ssl') {
157 $value = ($value == 'true' || $value == 1) ? 1 : 0;
158 }
159 $menu[$path][$key] = $value;
160 }
161 }
162 }
163
164 /**
165 * This function defines information for various menu items
166 *
6a0b768e
TO
167 * @param boolen $fetchFromXML
168 * Fetch the menu items from xml and not from cache.
49d97c48 169 *
6a488035 170 */
00be9182 171 public static function &items($fetchFromXML = FALSE) {
49d97c48 172 return self::xmlItems($fetchFromXML);
6a488035
TO
173 }
174
a0ee3941
EM
175 /**
176 * @param $values
177 *
178 * @return bool
179 */
00be9182 180 public static function isArrayTrue(&$values) {
6a488035
TO
181 foreach ($values as $name => $value) {
182 if (!$value) {
183 return FALSE;
184 }
185 }
186 return TRUE;
187 }
188
a0ee3941
EM
189 /**
190 * @param $menu
191 * @param $path
192 *
193 * @throws Exception
194 */
00be9182 195 public static function fillMenuValues(&$menu, $path) {
6a488035
TO
196 $fieldsToPropagate = array(
197 'access_callback',
198 'access_arguments',
199 'page_callback',
200 'page_arguments',
201 'is_ssl',
202 );
203 $fieldsPresent = array();
204 foreach ($fieldsToPropagate as $field) {
205 $fieldsPresent[$field] = CRM_Utils_Array::value($field, $menu[$path]) !== NULL ? TRUE : FALSE;
206 }
207
208 $args = explode('/', $path);
209 while (!self::isArrayTrue($fieldsPresent) && !empty($args)) {
210
211 array_pop($args);
212 $parentPath = implode('/', $args);
213
214 foreach ($fieldsToPropagate as $field) {
215 if (!$fieldsPresent[$field]) {
216 if (CRM_Utils_Array::value($field, CRM_Utils_Array::value($parentPath, $menu)) !== NULL) {
217 $fieldsPresent[$field] = TRUE;
218 $menu[$path][$field] = $menu[$parentPath][$field];
219 }
220 }
221 }
222 }
223
224 if (self::isArrayTrue($fieldsPresent)) {
225 return;
226 }
227
228 $messages = array();
229 foreach ($fieldsToPropagate as $field) {
230 if (!$fieldsPresent[$field]) {
231 $messages[] = ts("Could not find %1 in path tree",
232 array(1 => $field)
233 );
234 }
235 }
236 CRM_Core_Error::fatal("'$path': " . implode(', ', $messages));
237 }
238
239 /**
240 * We use this function to
241 *
242 * 1. Compute the breadcrumb
243 * 2. Compute local tasks value if any
244 * 3. Propagate access argument, access callback, page callback to the menu item
245 * 4. Build the global navigation block
6a488035 246 */
00be9182 247 public static function build(&$menu) {
6a488035
TO
248 foreach ($menu as $path => $menuItems) {
249 self::buildBreadcrumb($menu, $path);
250 self::fillMenuValues($menu, $path);
251 self::fillComponentIds($menu, $path);
252 self::buildReturnUrl($menu, $path);
253
254 // add add page_type if not present
255 if (!isset($menu[$path]['page_type'])) {
256 $menu[$path]['page_type'] = 0;
257 }
258 }
259
260 self::buildAdminLinks($menu);
261 }
262
a0ee3941 263 /**
49d97c48 264 * This function recomputes menu from xml and populates civicrm_menu
a0ee3941
EM
265 * @param bool $truncate
266 */
00be9182 267 public static function store($truncate = TRUE) {
6a488035
TO
268 // first clean up the db
269 if ($truncate) {
270 $query = 'TRUNCATE civicrm_menu';
271 CRM_Core_DAO::executeQuery($query);
272 }
49d97c48 273 $menuArray = self::items($truncate);
6a488035
TO
274
275 self::build($menuArray);
276
6a488035
TO
277 $config = CRM_Core_Config::singleton();
278
279 foreach ($menuArray as $path => $item) {
353ffa53
TO
280 $menu = new CRM_Core_DAO_Menu();
281 $menu->path = $path;
6a488035
TO
282 $menu->domain_id = CRM_Core_Config::domainID();
283
284 $menu->find(TRUE);
285
286 $menu->copyValues($item);
287
288 foreach (self::$_serializedElements as $element) {
289 if (!isset($item[$element]) ||
290 $item[$element] == 'null'
291 ) {
292 $menu->$element = NULL;
293 }
294 else {
295 $menu->$element = serialize($item[$element]);
296 }
297 }
298
299 $menu->save();
300 }
301 }
302
a0ee3941
EM
303 /**
304 * @param $menu
305 */
00be9182 306 public static function buildAdminLinks(&$menu) {
6a488035
TO
307 $values = array();
308
309 foreach ($menu as $path => $item) {
a7488080 310 if (empty($item['adminGroup'])) {
6a488035
TO
311 continue;
312 }
313
0d8afee2 314 $query = !empty($item['path_arguments']) ? str_replace(',', '&', $item['path_arguments']) . '&reset=1' : 'reset=1';
6a488035
TO
315
316 $value = array(
317 'title' => $item['title'],
318 'desc' => CRM_Utils_Array::value('desc', $item),
319 'id' => strtr($item['title'], array(
353ffa53
TO
320 '(' => '_',
321 ')' => '',
322 ' ' => '',
2aa397bc 323 ',' => '_',
353ffa53 324 '/' => '_',
6a488035
TO
325 )
326 ),
d75f2f47 327 'url' => CRM_Utils_System::url($path, $query,
353ffa53
TO
328 FALSE, // absolute
329 NULL, // fragment
330 TRUE, // htmlize
331 FALSE, // frontend
332 TRUE // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
f4bdec6a 333 ),
6a488035
TO
334 'icon' => CRM_Utils_Array::value('icon', $item),
335 'extra' => CRM_Utils_Array::value('extra', $item),
336 );
337 if (!array_key_exists($item['adminGroup'], $values)) {
338 $values[$item['adminGroup']] = array();
339 $values[$item['adminGroup']]['fields'] = array();
340 }
341 $weight = CRM_Utils_Array::value('weight', $item, 0);
342 $values[$item['adminGroup']]['fields']["{weight}.{$item['title']}"] = $value;
343 $values[$item['adminGroup']]['component_id'] = $item['component_id'];
344 }
345
346 foreach ($values as $group => $dontCare) {
347 $values[$group]['perColumn'] = round(count($values[$group]['fields']) / 2);
348 ksort($values[$group]);
349 }
350
351 $menu['admin'] = array('breadcrumb' => $values);
352 }
353
a0ee3941
EM
354 /**
355 * @param bool $all
356 *
357 * @return mixed
358 * @throws Exception
359 */
00be9182 360 public static function &getNavigation($all = FALSE) {
6a488035
TO
361 CRM_Core_Error::fatal();
362
363 if (!self::$_menuCache) {
364 self::get('navigation');
365 }
366
367 if (CRM_Core_Config::isUpgradeMode()) {
368 return array();
369 }
370
371 if (!array_key_exists('navigation', self::$_menuCache)) {
372 // problem could be due to menu table empty. Just do a
373 // menu store and try again
374 self::store();
375
376 // here we goo
377 self::get('navigation');
378 if (!array_key_exists('navigation', self::$_menuCache)) {
379 CRM_Core_Error::fatal();
380 }
381 }
382 $nav = &self::$_menuCache['navigation'];
383
384 if (!$nav ||
385 !isset($nav['breadcrumb'])
386 ) {
387 return NULL;
388 }
389
390 $values = &$nav['breadcrumb'];
391 $config = CRM_Core_Config::singleton();
392 foreach ($values as $index => $item) {
393 if (strpos(CRM_Utils_Array::value($config->userFrameworkURLVar, $_REQUEST),
394 $item['path']
353ffa53
TO
395 ) === 0
396 ) {
6a488035
TO
397 $values[$index]['active'] = 'class="active"';
398 }
399 else {
400 $values[$index]['active'] = '';
401 }
402
403 if ($values[$index]['parent']) {
404 $parent = $values[$index]['parent'];
405
406 // only reset if still a leaf
407 if ($values[$parent]['class'] == 'leaf') {
408 $values[$parent]['class'] = 'collapsed';
409 }
410
411 // if a child or the parent is active, expand the menu
412 if ($values[$index]['active'] ||
413 $values[$parent]['active']
414 ) {
415 $values[$parent]['class'] = 'expanded';
416 }
417
418 // make the parent inactive if the child is active
419 if ($values[$index]['active'] &&
420 $values[$parent]['active']
421 ) {
422 $values[$parent]['active'] = '';
423 }
424 }
425 }
426
6a488035
TO
427 if (!$all) {
428 // remove all collapsed menu items from the array
429 foreach ($values as $weight => $v) {
430 if ($v['parent'] &&
431 $values[$v['parent']]['class'] == 'collapsed'
432 ) {
433 unset($values[$weight]);
434 }
435 }
436 }
437
438 // check permissions for the rest
439 $activeChildren = array();
440
441 foreach ($values as $weight => $v) {
442 if (CRM_Core_Permission::checkMenuItem($v)) {
443 if ($v['parent']) {
444 $activeChildren[] = $weight;
445 }
446 }
447 else {
448 unset($values[$weight]);
449 }
450 }
451
452 // add the start / end tags
453 $len = count($activeChildren) - 1;
454 if ($len >= 0) {
455 $values[$activeChildren[0]]['start'] = TRUE;
456 $values[$activeChildren[$len]]['end'] = TRUE;
457 }
458
459 ksort($values, SORT_NUMERIC);
460 $i18n = CRM_Core_I18n::singleton();
461 $i18n->localizeTitles($values);
462
463 return $values;
464 }
465
a0ee3941
EM
466 /**
467 * @return null
468 */
00be9182 469 public static function &getAdminLinks() {
6a488035
TO
470 $links = self::get('admin');
471
472 if (!$links ||
473 !isset($links['breadcrumb'])
474 ) {
475 return NULL;
476 }
477
478 $values = &$links['breadcrumb'];
479 return $values;
480 }
481
482 /**
483 * Get the breadcrumb for a given path.
484 *
6a0b768e
TO
485 * @param array $menu
486 * An array of all the menu items.
487 * @param string $path
488 * Path for which breadcrumb is to be build.
6a488035 489 *
a6c01b45
CW
490 * @return array
491 * The breadcrumb for this path
6a488035 492 *
6a488035 493 */
00be9182 494 public static function buildBreadcrumb(&$menu, $path) {
6a488035
TO
495 $crumbs = array();
496
497 $pathElements = explode('/', $path);
498 array_pop($pathElements);
499
500 $currentPath = NULL;
501 while ($newPath = array_shift($pathElements)) {
502 $currentPath = $currentPath ? ($currentPath . '/' . $newPath) : $newPath;
503
504 // when we come accross breadcrumb which involves ids,
505 // we should skip now and later on append dynamically.
506 if (isset($menu[$currentPath]['skipBreadcrumb'])) {
507 continue;
508 }
509
510 // add to crumb, if current-path exists in params.
511 if (array_key_exists($currentPath, $menu) &&
512 isset($menu[$currentPath]['title'])
513 ) {
0d8afee2 514 $urlVar = !empty($menu[$currentPath]['path_arguments']) ? '&' . $menu[$currentPath]['path_arguments'] : '';
6a488035
TO
515 $crumbs[] = array(
516 'title' => $menu[$currentPath]['title'],
517 'url' => CRM_Utils_System::url($currentPath,
38a0e912
TO
518 'reset=1' . $urlVar,
519 FALSE, // absolute
520 NULL, // fragment
521 TRUE, // htmlize
522 FALSE, // frontend
523 TRUE // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
6a488035
TO
524 ),
525 );
526 }
527 }
528 $menu[$path]['breadcrumb'] = $crumbs;
529
530 return $crumbs;
531 }
532
a0ee3941
EM
533 /**
534 * @param $menu
535 * @param $path
536 */
00be9182 537 public static function buildReturnUrl(&$menu, $path) {
6a488035
TO
538 if (!isset($menu[$path]['return_url'])) {
539 list($menu[$path]['return_url'], $menu[$path]['return_url_args']) = self::getReturnUrl($menu, $path);
540 }
541 }
542
a0ee3941
EM
543 /**
544 * @param $menu
545 * @param $path
546 *
547 * @return array
548 */
00be9182 549 public static function getReturnUrl(&$menu, $path) {
6a488035
TO
550 if (!isset($menu[$path]['return_url'])) {
551 $pathElements = explode('/', $path);
552 array_pop($pathElements);
553
554 if (empty($pathElements)) {
555 return array(NULL, NULL);
556 }
557 $newPath = implode('/', $pathElements);
558
559 return self::getReturnUrl($menu, $newPath);
560 }
561 else {
562 return array(
563 CRM_Utils_Array::value('return_url',
564 $menu[$path]
565 ),
566 CRM_Utils_Array::value('return_url_args',
567 $menu[$path]
568 ),
569 );
570 }
571 }
572
a0ee3941
EM
573 /**
574 * @param $menu
575 * @param $path
576 */
00be9182 577 public static function fillComponentIds(&$menu, $path) {
6a488035
TO
578 static $cache = array();
579
580 if (array_key_exists('component_id', $menu[$path])) {
581 return;
582 }
583
584 $args = explode('/', $path);
585
586 if (count($args) > 1) {
587 $compPath = $args[0] . '/' . $args[1];
588 }
589 else {
590 $compPath = $args[0];
591 }
592
593 $componentId = NULL;
594
595 if (array_key_exists($compPath, $cache)) {
596 $menu[$path]['component_id'] = $cache[$compPath];
597 }
598 else {
599 if (CRM_Utils_Array::value('component', CRM_Utils_Array::value($compPath, $menu))) {
600 $componentId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Component',
601 $menu[$compPath]['component'],
602 'id', 'name'
603 );
604 }
605 $menu[$path]['component_id'] = $componentId ? $componentId : NULL;
606 $cache[$compPath] = $menu[$path]['component_id'];
607 }
608 }
609
a0ee3941
EM
610 /**
611 * @param $path
612 *
613 * @return null
614 */
00be9182 615 public static function get($path) {
6a488035
TO
616 // return null if menu rebuild
617 $config = CRM_Core_Config::singleton();
618
619 $params = array();
620
621 $args = explode('/', $path);
622
623 $elements = array();
624 while (!empty($args)) {
353ffa53
TO
625 $string = implode('/', $args);
626 $string = CRM_Core_DAO::escapeString($string);
6a488035
TO
627 $elements[] = "'{$string}'";
628 array_pop($args);
629 }
630
353ffa53
TO
631 $queryString = implode(', ', $elements);
632 $domainID = CRM_Core_Config::domainID();
6a488035
TO
633 $domainWhereClause = " AND domain_id = $domainID ";
634 if ($config->isUpgradeMode() &&
635 !CRM_Core_DAO::checkFieldExists('civicrm_menu', 'domain_id')
636 ) {
637 //domain_id wouldn't be available for earlier version of
638 //3.0 and therefore can't be used as part of query for
639 //upgrade case
640 $domainWhereClause = "";
641 }
642
643 $query = "
644(
645 SELECT *
646 FROM civicrm_menu
647 WHERE path in ( $queryString )
648 $domainWhereClause
649 ORDER BY length(path) DESC
650 LIMIT 1
651)
652";
653
654 if ($path != 'navigation') {
655 $query .= "
656UNION (
657 SELECT *
658 FROM civicrm_menu
659 WHERE path IN ( 'navigation' )
660 $domainWhereClause
661)
662";
663 }
664
665 $menu = new CRM_Core_DAO_Menu();
666 $menu->query($query);
667
668 self::$_menuCache = array();
669 $menuPath = NULL;
670 while ($menu->fetch()) {
671 self::$_menuCache[$menu->path] = array();
672 CRM_Core_DAO::storeValues($menu, self::$_menuCache[$menu->path]);
673
674 foreach (self::$_serializedElements as $element) {
675 self::$_menuCache[$menu->path][$element] = unserialize($menu->$element);
676
677 if (strpos($path, $menu->path) !== FALSE) {
678 $menuPath = &self::$_menuCache[$menu->path];
679 }
680 }
681 }
682
683 if (strstr($path, 'report/instance')) {
684 $args = explode('/', $path);
685 if (is_numeric(end($args))) {
686 $menuPath['path'] .= '/' . end($args);
687 }
688 }
689
690 // *FIXME* : hack for 2.1 -> 2.2 upgrades.
691 if ($path == 'civicrm/upgrade') {
692 $menuPath['page_callback'] = 'CRM_Upgrade_Page_Upgrade';
693 $menuPath['access_arguments'][0][] = 'administer CiviCRM';
694 $menuPath['access_callback'] = array('CRM_Core_Permission', 'checkMenu');
695 }
696 // *FIXME* : hack for 4.1 -> 4.2 upgrades.
697 if (preg_match('/^civicrm\/(upgrade\/)?queue\//', $path)) {
698 CRM_Queue_Menu::alter($path, $menuPath);
699 }
700
701 // Part of upgrade framework but not run inside main upgrade because it deletes data
702 // Once we have another example of a 'cleanup' we should generalize the clause below so it grabs string
703 // which follows upgrade/ and checks for existence of a function in Cleanup class.
704 if ($path == 'civicrm/upgrade/cleanup425') {
2aa397bc 705 $menuPath['page_callback'] = array('CRM_Upgrade_Page_Cleanup', 'cleanup425');
6a488035
TO
706 $menuPath['access_arguments'][0][] = 'administer CiviCRM';
707 $menuPath['access_callback'] = array('CRM_Core_Permission', 'checkMenu');
708 }
709
710 if (!empty($menuPath)) {
711 $i18n = CRM_Core_I18n::singleton();
712 $i18n->localizeTitles($menuPath);
713 }
714 return $menuPath;
715 }
716
a0ee3941
EM
717 /**
718 * @param $pathArgs
719 *
720 * @return mixed
721 */
00be9182 722 public static function getArrayForPathArgs($pathArgs) {
6a488035
TO
723 if (!is_string($pathArgs)) {
724 return;
725 }
726 $args = array();
727
728 $elements = explode(',', $pathArgs);
6a488035 729 foreach ($elements as $keyVal) {
3b4339fd 730 list($key, $val) = explode('=', $keyVal, 2);
6a488035
TO
731 $arr[$key] = $val;
732 }
733
734 if (array_key_exists('urlToSession', $arr)) {
735 $urlToSession = array();
736
737 $params = explode(';', $arr['urlToSession']);
738 $count = 0;
739 foreach ($params as $keyVal) {
740 list($urlToSession[$count]['urlVar'],
741 $urlToSession[$count]['sessionVar'],
742 $urlToSession[$count]['type'],
743 $urlToSession[$count]['default']
353ffa53 744 ) = explode(':', $keyVal);
6a488035
TO
745 $count++;
746 }
747 $arr['urlToSession'] = $urlToSession;
748 }
749 return $arr;
750 }
96025800 751
6a488035 752}