INFRA-132 - Change "else if" to "elseif"
[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 +--------------------------------------------------------------------+
26*/
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
48 * @static
49 */
50 static $_items = NULL;
51
52 /**
100fef9d 53 * The list of permissioned menu items
6a488035
TO
54 *
55 * @var array
56 * @static
57 */
58 static $_permissionedItems = NULL;
59
60 static $_serializedElements = array(
61 'access_arguments',
62 'access_callback',
63 'page_arguments',
64 'page_callback',
65 'breadcrumb',
66 );
67
68 static $_menuCache = NULL;
7da04cde 69 const MENU_ITEM = 1;
6a488035 70
a0ee3941 71 /**
49d97c48 72 * This function fetches the menu items from xml and xmlMenu hooks
73 *
6a0b768e
TO
74 * @param boolen $fetchFromXML
75 * Fetch the menu items from xml and not from cache.
49d97c48 76 *
a0ee3941
EM
77 * @return array
78 */
00be9182 79 public static function &xmlItems($fetchFromXML = FALSE) {
49d97c48 80 if (!self::$_items || $fetchFromXML) {
6a488035
TO
81 $config = CRM_Core_Config::singleton();
82
83 // We needs this until Core becomes a component
84 $coreMenuFilesNamespace = 'CRM_Core_xml_Menu';
85 $coreMenuFilesPath = str_replace('_', DIRECTORY_SEPARATOR, $coreMenuFilesNamespace);
86 global $civicrm_root;
87 $files = CRM_Utils_File::getFilesByExtension($civicrm_root . DIRECTORY_SEPARATOR . $coreMenuFilesPath, 'xml');
88
89 // Grab component menu files
90 $files = array_merge($files,
91 CRM_Core_Component::xmlMenu()
92 );
93
94 // lets call a hook and get any additional files if needed
95 CRM_Utils_Hook::xmlMenu($files);
96
97 self::$_items = array();
98 foreach ($files as $file) {
99 self::read($file, self::$_items);
100 }
101 }
102
103 return self::$_items;
104 }
105
a0ee3941 106 /**
100fef9d 107 * @param string $name
a0ee3941
EM
108 * @param $menu
109 *
110 * @throws Exception
111 */
00be9182 112 public static function read($name, &$menu) {
6a488035
TO
113
114 $config = CRM_Core_Config::singleton();
115
116 $xml = simplexml_load_file($name);
117 foreach ($xml->item as $item) {
118 if (!(string ) $item->path) {
119 CRM_Core_Error::debug('i', $item);
120 CRM_Core_Error::fatal();
121 }
122 $path = (string ) $item->path;
123 $menu[$path] = array();
124 unset($item->path);
125 foreach ($item as $key => $value) {
126 $key = (string ) $key;
127 $value = (string ) $value;
128 if (strpos($key, '_callback') &&
129 strpos($value, '::')
130 ) {
131 $value = explode('::', $value);
132 }
133 elseif ($key == 'access_arguments') {
134 if (strpos($value, ',') ||
135 strpos($value, ';')
136 ) {
137 if (strpos($value, ',')) {
138 $elements = explode(',', $value);
139 $op = 'and';
140 }
141 else {
142 $elements = explode(';', $value);
143 $op = 'or';
144 }
145 $items = array();
146 foreach ($elements as $element) {
147 $items[] = $element;
148 }
149 $value = array($items, $op);
150 }
151 else {
152 $value = array(array($value), 'and');
153 }
154 }
155 elseif ($key == 'is_public' || $key == 'is_ssl') {
156 $value = ($value == 'true' || $value == 1) ? 1 : 0;
157 }
158 $menu[$path][$key] = $value;
159 }
160 }
161 }
162
163 /**
164 * This function defines information for various menu items
165 *
6a0b768e
TO
166 * @param boolen $fetchFromXML
167 * Fetch the menu items from xml and not from cache.
49d97c48 168 *
6a488035 169 * @static
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
246 *
247 */
00be9182 248 public static function build(&$menu) {
6a488035
TO
249 foreach ($menu as $path => $menuItems) {
250 self::buildBreadcrumb($menu, $path);
251 self::fillMenuValues($menu, $path);
252 self::fillComponentIds($menu, $path);
253 self::buildReturnUrl($menu, $path);
254
255 // add add page_type if not present
256 if (!isset($menu[$path]['page_type'])) {
257 $menu[$path]['page_type'] = 0;
258 }
259 }
260
261 self::buildAdminLinks($menu);
262 }
263
a0ee3941 264 /**
49d97c48 265 * This function recomputes menu from xml and populates civicrm_menu
a0ee3941
EM
266 * @param bool $truncate
267 */
00be9182 268 public static function store($truncate = TRUE) {
6a488035
TO
269 // first clean up the db
270 if ($truncate) {
271 $query = 'TRUNCATE civicrm_menu';
272 CRM_Core_DAO::executeQuery($query);
273 }
49d97c48 274 $menuArray = self::items($truncate);
6a488035
TO
275
276 self::build($menuArray);
277
6a488035
TO
278 $config = CRM_Core_Config::singleton();
279
280 foreach ($menuArray as $path => $item) {
281 $menu = new CRM_Core_DAO_Menu();
282 $menu->path = $path;
283 $menu->domain_id = CRM_Core_Config::domainID();
284
285 $menu->find(TRUE);
286
287 $menu->copyValues($item);
288
289 foreach (self::$_serializedElements as $element) {
290 if (!isset($item[$element]) ||
291 $item[$element] == 'null'
292 ) {
293 $menu->$element = NULL;
294 }
295 else {
296 $menu->$element = serialize($item[$element]);
297 }
298 }
299
300 $menu->save();
301 }
302 }
303
a0ee3941
EM
304 /**
305 * @param $menu
306 */
00be9182 307 public static function buildAdminLinks(&$menu) {
6a488035
TO
308 $values = array();
309
310 foreach ($menu as $path => $item) {
a7488080 311 if (empty($item['adminGroup'])) {
6a488035
TO
312 continue;
313 }
314
0d8afee2 315 $query = !empty($item['path_arguments']) ? str_replace(',', '&', $item['path_arguments']) . '&reset=1' : 'reset=1';
6a488035
TO
316
317 $value = array(
318 'title' => $item['title'],
319 'desc' => CRM_Utils_Array::value('desc', $item),
320 'id' => strtr($item['title'], array(
2aa397bc
TO
321 '(' => '_',
322 ')' => '',
323 ' ' => '',
324 ',' => '_',
325 '/' => '_',
6a488035
TO
326 )
327 ),
d75f2f47 328 'url' => CRM_Utils_System::url($path, $query,
f4bdec6a
TO
329 FALSE, // absolute
330 NULL, // fragment
331 TRUE, // htmlize
332 FALSE, // frontend
333 TRUE // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
334 ),
6a488035
TO
335 'icon' => CRM_Utils_Array::value('icon', $item),
336 'extra' => CRM_Utils_Array::value('extra', $item),
337 );
338 if (!array_key_exists($item['adminGroup'], $values)) {
339 $values[$item['adminGroup']] = array();
340 $values[$item['adminGroup']]['fields'] = array();
341 }
342 $weight = CRM_Utils_Array::value('weight', $item, 0);
343 $values[$item['adminGroup']]['fields']["{weight}.{$item['title']}"] = $value;
344 $values[$item['adminGroup']]['component_id'] = $item['component_id'];
345 }
346
347 foreach ($values as $group => $dontCare) {
348 $values[$group]['perColumn'] = round(count($values[$group]['fields']) / 2);
349 ksort($values[$group]);
350 }
351
352 $menu['admin'] = array('breadcrumb' => $values);
353 }
354
a0ee3941
EM
355 /**
356 * @param bool $all
357 *
358 * @return mixed
359 * @throws Exception
360 */
00be9182 361 public static function &getNavigation($all = FALSE) {
6a488035
TO
362 CRM_Core_Error::fatal();
363
364 if (!self::$_menuCache) {
365 self::get('navigation');
366 }
367
368 if (CRM_Core_Config::isUpgradeMode()) {
369 return array();
370 }
371
372 if (!array_key_exists('navigation', self::$_menuCache)) {
373 // problem could be due to menu table empty. Just do a
374 // menu store and try again
375 self::store();
376
377 // here we goo
378 self::get('navigation');
379 if (!array_key_exists('navigation', self::$_menuCache)) {
380 CRM_Core_Error::fatal();
381 }
382 }
383 $nav = &self::$_menuCache['navigation'];
384
385 if (!$nav ||
386 !isset($nav['breadcrumb'])
387 ) {
388 return NULL;
389 }
390
391 $values = &$nav['breadcrumb'];
392 $config = CRM_Core_Config::singleton();
393 foreach ($values as $index => $item) {
394 if (strpos(CRM_Utils_Array::value($config->userFrameworkURLVar, $_REQUEST),
395 $item['path']
396 ) === 0) {
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
TO
489 *
490 * @return array The breadcrumb for this path
491 *
492 * @static
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)) {
625 $string = implode('/', $args);
626 $string = CRM_Core_DAO::escapeString($string);
627 $elements[] = "'{$string}'";
628 array_pop($args);
629 }
630
631 $queryString = implode(', ', $elements);
632 $domainID = CRM_Core_Config::domainID();
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']
744 ) = explode(':', $keyVal);
745 $count++;
746 }
747 $arr['urlToSession'] = $urlToSession;
748 }
749 return $arr;
750 }
751}