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