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