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