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