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