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