Merge pull request #6589 from eileenmcnaughton/CRM-11338
[civicrm-core.git] / CRM / Core / Menu.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 */
49 static $_items = NULL;
50
51 /**
52 * The list of permissioned menu items.
53 *
54 * @var array
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;
67 const MENU_ITEM = 1;
68
69 /**
70 * This function fetches the menu items from xml and xmlMenu hooks.
71 *
72 * @param boolen $fetchFromXML
73 * Fetch the menu items from xml and not from cache.
74 *
75 * @return array
76 */
77 public static function &xmlItems($fetchFromXML = FALSE) {
78 if (!self::$_items || $fetchFromXML) {
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
104 /**
105 * @param string $name
106 * @param $menu
107 *
108 * @throws Exception
109 */
110 public static function read($name, &$menu) {
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 ) {
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)).
131 $value = explode('::', $value);
132 }
133 elseif ($key == 'access_arguments') {
134 // FIXME Move the permission parser to its own class (or *maybe* CRM_Core_Permission).
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 *
167 * @param boolen $fetchFromXML
168 * Fetch the menu items from xml and not from cache.
169 *
170 * @return array
171 */
172 public static function &items($fetchFromXML = FALSE) {
173 return self::xmlItems($fetchFromXML);
174 }
175
176 /**
177 * @param $values
178 *
179 * @return bool
180 */
181 public static function isArrayTrue(&$values) {
182 foreach ($values as $name => $value) {
183 if (!$value) {
184 return FALSE;
185 }
186 }
187 return TRUE;
188 }
189
190 /**
191 * @param $menu
192 * @param $path
193 *
194 * @throws Exception
195 */
196 public static function fillMenuValues(&$menu, $path) {
197 $fieldsToPropagate = array(
198 'access_callback',
199 'access_arguments',
200 'page_callback',
201 'page_arguments',
202 'is_ssl',
203 );
204 $fieldsPresent = array();
205 foreach ($fieldsToPropagate as $field) {
206 $fieldsPresent[$field] = CRM_Utils_Array::value($field, $menu[$path]) !== NULL ? TRUE : FALSE;
207 }
208
209 $args = explode('/', $path);
210 while (!self::isArrayTrue($fieldsPresent) && !empty($args)) {
211
212 array_pop($args);
213 $parentPath = implode('/', $args);
214
215 foreach ($fieldsToPropagate as $field) {
216 if (!$fieldsPresent[$field]) {
217 if (CRM_Utils_Array::value($field, CRM_Utils_Array::value($parentPath, $menu)) !== NULL) {
218 $fieldsPresent[$field] = TRUE;
219 $menu[$path][$field] = $menu[$parentPath][$field];
220 }
221 }
222 }
223 }
224
225 if (self::isArrayTrue($fieldsPresent)) {
226 return;
227 }
228
229 $messages = array();
230 foreach ($fieldsToPropagate as $field) {
231 if (!$fieldsPresent[$field]) {
232 $messages[] = ts("Could not find %1 in path tree",
233 array(1 => $field)
234 );
235 }
236 }
237 CRM_Core_Error::fatal("'$path': " . implode(', ', $messages));
238 }
239
240 /**
241 * We use this function to.
242 *
243 * 1. Compute the breadcrumb
244 * 2. Compute local tasks value if any
245 * 3. Propagate access argument, access callback, page callback to the menu item
246 * 4. Build the global navigation block
247 */
248 public static function build(&$menu) {
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
264 /**
265 * This function recomputes menu from xml and populates civicrm_menu.
266 * @param bool $truncate
267 */
268 public static function store($truncate = TRUE) {
269 // first clean up the db
270 if ($truncate) {
271 $query = 'TRUNCATE civicrm_menu';
272 CRM_Core_DAO::executeQuery($query);
273 }
274 $menuArray = self::items($truncate);
275
276 self::build($menuArray);
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 public 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 '/' => '_',
326 )
327 ),
328 'url' => CRM_Utils_System::url($path, $query,
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 ),
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
355 /**
356 * @param bool $all
357 *
358 * @return mixed
359 * @throws Exception
360 */
361 public static function &getNavigation($all = FALSE) {
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 ) {
398 $values[$index]['active'] = 'class="active"';
399 }
400 else {
401 $values[$index]['active'] = '';
402 }
403
404 if ($values[$index]['parent']) {
405 $parent = $values[$index]['parent'];
406
407 // only reset if still a leaf
408 if ($values[$parent]['class'] == 'leaf') {
409 $values[$parent]['class'] = 'collapsed';
410 }
411
412 // if a child or the parent is active, expand the menu
413 if ($values[$index]['active'] ||
414 $values[$parent]['active']
415 ) {
416 $values[$parent]['class'] = 'expanded';
417 }
418
419 // make the parent inactive if the child is active
420 if ($values[$index]['active'] &&
421 $values[$parent]['active']
422 ) {
423 $values[$parent]['active'] = '';
424 }
425 }
426 }
427
428 if (!$all) {
429 // remove all collapsed menu items from the array
430 foreach ($values as $weight => $v) {
431 if ($v['parent'] &&
432 $values[$v['parent']]['class'] == 'collapsed'
433 ) {
434 unset($values[$weight]);
435 }
436 }
437 }
438
439 // check permissions for the rest
440 $activeChildren = array();
441
442 foreach ($values as $weight => $v) {
443 if (CRM_Core_Permission::checkMenuItem($v)) {
444 if ($v['parent']) {
445 $activeChildren[] = $weight;
446 }
447 }
448 else {
449 unset($values[$weight]);
450 }
451 }
452
453 // add the start / end tags
454 $len = count($activeChildren) - 1;
455 if ($len >= 0) {
456 $values[$activeChildren[0]]['start'] = TRUE;
457 $values[$activeChildren[$len]]['end'] = TRUE;
458 }
459
460 ksort($values, SORT_NUMERIC);
461 $i18n = CRM_Core_I18n::singleton();
462 $i18n->localizeTitles($values);
463
464 return $values;
465 }
466
467 /**
468 * @return null
469 */
470 public static function &getAdminLinks() {
471 $links = self::get('admin');
472
473 if (!$links ||
474 !isset($links['breadcrumb'])
475 ) {
476 return NULL;
477 }
478
479 $values = &$links['breadcrumb'];
480 return $values;
481 }
482
483 /**
484 * Get the breadcrumb for a given path.
485 *
486 * @param array $menu
487 * An array of all the menu items.
488 * @param string $path
489 * Path for which breadcrumb is to be build.
490 *
491 * @return array
492 * The breadcrumb for this path
493 *
494 */
495 public static function buildBreadcrumb(&$menu, $path) {
496 $crumbs = array();
497
498 $pathElements = explode('/', $path);
499 array_pop($pathElements);
500
501 $currentPath = NULL;
502 while ($newPath = array_shift($pathElements)) {
503 $currentPath = $currentPath ? ($currentPath . '/' . $newPath) : $newPath;
504
505 // when we come across breadcrumb which involves ids,
506 // we should skip now and later on append dynamically.
507 if (isset($menu[$currentPath]['skipBreadcrumb'])) {
508 continue;
509 }
510
511 // add to crumb, if current-path exists in params.
512 if (array_key_exists($currentPath, $menu) &&
513 isset($menu[$currentPath]['title'])
514 ) {
515 $urlVar = !empty($menu[$currentPath]['path_arguments']) ? '&' . $menu[$currentPath]['path_arguments'] : '';
516 $crumbs[] = array(
517 'title' => $menu[$currentPath]['title'],
518 'url' => CRM_Utils_System::url($currentPath,
519 'reset=1' . $urlVar,
520 FALSE, // absolute
521 NULL, // fragment
522 TRUE, // htmlize
523 FALSE, // frontend
524 TRUE // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
525 ),
526 );
527 }
528 }
529 $menu[$path]['breadcrumb'] = $crumbs;
530
531 return $crumbs;
532 }
533
534 /**
535 * @param $menu
536 * @param $path
537 */
538 public static function buildReturnUrl(&$menu, $path) {
539 if (!isset($menu[$path]['return_url'])) {
540 list($menu[$path]['return_url'], $menu[$path]['return_url_args']) = self::getReturnUrl($menu, $path);
541 }
542 }
543
544 /**
545 * @param $menu
546 * @param $path
547 *
548 * @return array
549 */
550 public static function getReturnUrl(&$menu, $path) {
551 if (!isset($menu[$path]['return_url'])) {
552 $pathElements = explode('/', $path);
553 array_pop($pathElements);
554
555 if (empty($pathElements)) {
556 return array(NULL, NULL);
557 }
558 $newPath = implode('/', $pathElements);
559
560 return self::getReturnUrl($menu, $newPath);
561 }
562 else {
563 return array(
564 CRM_Utils_Array::value('return_url',
565 $menu[$path]
566 ),
567 CRM_Utils_Array::value('return_url_args',
568 $menu[$path]
569 ),
570 );
571 }
572 }
573
574 /**
575 * @param $menu
576 * @param $path
577 */
578 public static function fillComponentIds(&$menu, $path) {
579 static $cache = array();
580
581 if (array_key_exists('component_id', $menu[$path])) {
582 return;
583 }
584
585 $args = explode('/', $path);
586
587 if (count($args) > 1) {
588 $compPath = $args[0] . '/' . $args[1];
589 }
590 else {
591 $compPath = $args[0];
592 }
593
594 $componentId = NULL;
595
596 if (array_key_exists($compPath, $cache)) {
597 $menu[$path]['component_id'] = $cache[$compPath];
598 }
599 else {
600 if (CRM_Utils_Array::value('component', CRM_Utils_Array::value($compPath, $menu))) {
601 $componentId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Component',
602 $menu[$compPath]['component'],
603 'id', 'name'
604 );
605 }
606 $menu[$path]['component_id'] = $componentId ? $componentId : NULL;
607 $cache[$compPath] = $menu[$path]['component_id'];
608 }
609 }
610
611 /**
612 * @param $path
613 *
614 * @return null
615 */
616 public static function get($path) {
617 // return null if menu rebuild
618 $config = CRM_Core_Config::singleton();
619
620 $params = array();
621
622 $args = explode('/', $path);
623
624 $elements = array();
625 while (!empty($args)) {
626 $string = implode('/', $args);
627 $string = CRM_Core_DAO::escapeString($string);
628 $elements[] = "'{$string}'";
629 array_pop($args);
630 }
631
632 $queryString = implode(', ', $elements);
633 $domainID = CRM_Core_Config::domainID();
634 $domainWhereClause = " AND domain_id = $domainID ";
635 if ($config->isUpgradeMode() &&
636 !CRM_Core_DAO::checkFieldExists('civicrm_menu', 'domain_id')
637 ) {
638 //domain_id wouldn't be available for earlier version of
639 //3.0 and therefore can't be used as part of query for
640 //upgrade case
641 $domainWhereClause = "";
642 }
643
644 $query = "
645 (
646 SELECT *
647 FROM civicrm_menu
648 WHERE path in ( $queryString )
649 $domainWhereClause
650 ORDER BY length(path) DESC
651 LIMIT 1
652 )
653 ";
654
655 if ($path != 'navigation') {
656 $query .= "
657 UNION (
658 SELECT *
659 FROM civicrm_menu
660 WHERE path IN ( 'navigation' )
661 $domainWhereClause
662 )
663 ";
664 }
665
666 $menu = new CRM_Core_DAO_Menu();
667 $menu->query($query);
668
669 self::$_menuCache = array();
670 $menuPath = NULL;
671 while ($menu->fetch()) {
672 self::$_menuCache[$menu->path] = array();
673 CRM_Core_DAO::storeValues($menu, self::$_menuCache[$menu->path]);
674
675 foreach (self::$_serializedElements as $element) {
676 self::$_menuCache[$menu->path][$element] = unserialize($menu->$element);
677
678 if (strpos($path, $menu->path) !== FALSE) {
679 $menuPath = &self::$_menuCache[$menu->path];
680 }
681 }
682 }
683
684 if (strstr($path, 'report/instance')) {
685 $args = explode('/', $path);
686 if (is_numeric(end($args))) {
687 $menuPath['path'] .= '/' . end($args);
688 }
689 }
690
691 // *FIXME* : hack for 2.1 -> 2.2 upgrades.
692 if ($path == 'civicrm/upgrade') {
693 $menuPath['page_callback'] = 'CRM_Upgrade_Page_Upgrade';
694 $menuPath['access_arguments'][0][] = 'administer CiviCRM';
695 $menuPath['access_callback'] = array('CRM_Core_Permission', 'checkMenu');
696 }
697 // *FIXME* : hack for 4.1 -> 4.2 upgrades.
698 if (preg_match('/^civicrm\/(upgrade\/)?queue\//', $path)) {
699 CRM_Queue_Menu::alter($path, $menuPath);
700 }
701
702 // Part of upgrade framework but not run inside main upgrade because it deletes data
703 // Once we have another example of a 'cleanup' we should generalize the clause below so it grabs string
704 // which follows upgrade/ and checks for existence of a function in Cleanup class.
705 if ($path == 'civicrm/upgrade/cleanup425') {
706 $menuPath['page_callback'] = array('CRM_Upgrade_Page_Cleanup', 'cleanup425');
707 $menuPath['access_arguments'][0][] = 'administer CiviCRM';
708 $menuPath['access_callback'] = array('CRM_Core_Permission', 'checkMenu');
709 }
710
711 if (!empty($menuPath)) {
712 $i18n = CRM_Core_I18n::singleton();
713 $i18n->localizeTitles($menuPath);
714 }
715 return $menuPath;
716 }
717
718 /**
719 * @param $pathArgs
720 *
721 * @return mixed
722 */
723 public static function getArrayForPathArgs($pathArgs) {
724 if (!is_string($pathArgs)) {
725 return;
726 }
727 $args = array();
728
729 $elements = explode(',', $pathArgs);
730 foreach ($elements as $keyVal) {
731 list($key, $val) = explode('=', $keyVal, 2);
732 $arr[$key] = $val;
733 }
734
735 if (array_key_exists('urlToSession', $arr)) {
736 $urlToSession = array();
737
738 $params = explode(';', $arr['urlToSession']);
739 $count = 0;
740 foreach ($params as $keyVal) {
741 list($urlToSession[$count]['urlVar'],
742 $urlToSession[$count]['sessionVar'],
743 $urlToSession[$count]['type'],
744 $urlToSession[$count]['default']
745 ) = explode(':', $keyVal);
746 $count++;
747 }
748 $arr['urlToSession'] = $urlToSession;
749 }
750 return $arr;
751 }
752
753 }