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