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