Merge remote-tracking branch 'origin/4.4' into 4.4-4.5-2014-09-14-13-58-42
[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 /**
72 * @return array
73 */
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
101 /**
102 * @param $name
103 * @param $menu
104 *
105 * @throws Exception
106 */
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
168 /**
169 * @param $values
170 *
171 * @return bool
172 */
173 static function isArrayTrue(&$values) {
174 foreach ($values as $name => $value) {
175 if (!$value) {
176 return FALSE;
177 }
178 }
179 return TRUE;
180 }
181
182 /**
183 * @param $menu
184 * @param $path
185 *
186 * @throws Exception
187 */
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
257 /**
258 * @param bool $truncate
259 */
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
297 /**
298 * @param $menu
299 */
300 static function buildAdminLinks(&$menu) {
301 $values = array();
302
303 foreach ($menu as $path => $item) {
304 if (empty($item['adminGroup'])) {
305 continue;
306 }
307
308 $query = !empty($item['path_arguments']) ? str_replace(',', '&', $item['path_arguments']) . '&reset=1' : 'reset=1';
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,
319 FALSE, // absolute
320 NULL, // fragment
321 TRUE, // htmlize
322 FALSE, // frontend
323 TRUE // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
324 ),
325 'icon' => CRM_Utils_Array::value('icon', $item),
326 'extra' => CRM_Utils_Array::value('extra', $item),
327 );
328 if (!array_key_exists($item['adminGroup'], $values)) {
329 $values[$item['adminGroup']] = array();
330 $values[$item['adminGroup']]['fields'] = array();
331 }
332 $weight = CRM_Utils_Array::value('weight', $item, 0);
333 $values[$item['adminGroup']]['fields']["{weight}.{$item['title']}"] = $value;
334 $values[$item['adminGroup']]['component_id'] = $item['component_id'];
335 }
336
337 foreach ($values as $group => $dontCare) {
338 $values[$group]['perColumn'] = round(count($values[$group]['fields']) / 2);
339 ksort($values[$group]);
340 }
341
342 $menu['admin'] = array('breadcrumb' => $values);
343 }
344
345 /**
346 * @param bool $all
347 *
348 * @return mixed
349 * @throws Exception
350 */
351 static function &getNavigation($all = FALSE) {
352 CRM_Core_Error::fatal();
353
354 if (!self::$_menuCache) {
355 self::get('navigation');
356 }
357
358 if (CRM_Core_Config::isUpgradeMode()) {
359 return array();
360 }
361
362 if (!array_key_exists('navigation', self::$_menuCache)) {
363 // problem could be due to menu table empty. Just do a
364 // menu store and try again
365 self::store();
366
367 // here we goo
368 self::get('navigation');
369 if (!array_key_exists('navigation', self::$_menuCache)) {
370 CRM_Core_Error::fatal();
371 }
372 }
373 $nav = &self::$_menuCache['navigation'];
374
375 if (!$nav ||
376 !isset($nav['breadcrumb'])
377 ) {
378 return NULL;
379 }
380
381 $values = &$nav['breadcrumb'];
382 $config = CRM_Core_Config::singleton();
383 foreach ($values as $index => $item) {
384 if (strpos(CRM_Utils_Array::value($config->userFrameworkURLVar, $_REQUEST),
385 $item['path']
386 ) === 0) {
387 $values[$index]['active'] = 'class="active"';
388 }
389 else {
390 $values[$index]['active'] = '';
391 }
392
393 if ($values[$index]['parent']) {
394 $parent = $values[$index]['parent'];
395
396 // only reset if still a leaf
397 if ($values[$parent]['class'] == 'leaf') {
398 $values[$parent]['class'] = 'collapsed';
399 }
400
401 // if a child or the parent is active, expand the menu
402 if ($values[$index]['active'] ||
403 $values[$parent]['active']
404 ) {
405 $values[$parent]['class'] = 'expanded';
406 }
407
408 // make the parent inactive if the child is active
409 if ($values[$index]['active'] &&
410 $values[$parent]['active']
411 ) {
412 $values[$parent]['active'] = '';
413 }
414 }
415 }
416
417
418 if (!$all) {
419 // remove all collapsed menu items from the array
420 foreach ($values as $weight => $v) {
421 if ($v['parent'] &&
422 $values[$v['parent']]['class'] == 'collapsed'
423 ) {
424 unset($values[$weight]);
425 }
426 }
427 }
428
429 // check permissions for the rest
430 $activeChildren = array();
431
432 foreach ($values as $weight => $v) {
433 if (CRM_Core_Permission::checkMenuItem($v)) {
434 if ($v['parent']) {
435 $activeChildren[] = $weight;
436 }
437 }
438 else {
439 unset($values[$weight]);
440 }
441 }
442
443 // add the start / end tags
444 $len = count($activeChildren) - 1;
445 if ($len >= 0) {
446 $values[$activeChildren[0]]['start'] = TRUE;
447 $values[$activeChildren[$len]]['end'] = TRUE;
448 }
449
450 ksort($values, SORT_NUMERIC);
451 $i18n = CRM_Core_I18n::singleton();
452 $i18n->localizeTitles($values);
453
454 return $values;
455 }
456
457 /**
458 * @return null
459 */
460 static function &getAdminLinks() {
461 $links = self::get('admin');
462
463 if (!$links ||
464 !isset($links['breadcrumb'])
465 ) {
466 return NULL;
467 }
468
469 $values = &$links['breadcrumb'];
470 return $values;
471 }
472
473 /**
474 * Get the breadcrumb for a given path.
475 *
476 * @param array $menu An array of all the menu items.
477 * @param string $path Path for which breadcrumb is to be build.
478 *
479 * @return array The breadcrumb for this path
480 *
481 * @static
482 * @access public
483 */
484 static function buildBreadcrumb(&$menu, $path) {
485 $crumbs = array();
486
487 $pathElements = explode('/', $path);
488 array_pop($pathElements);
489
490 $currentPath = NULL;
491 while ($newPath = array_shift($pathElements)) {
492 $currentPath = $currentPath ? ($currentPath . '/' . $newPath) : $newPath;
493
494 // when we come accross breadcrumb which involves ids,
495 // we should skip now and later on append dynamically.
496 if (isset($menu[$currentPath]['skipBreadcrumb'])) {
497 continue;
498 }
499
500 // add to crumb, if current-path exists in params.
501 if (array_key_exists($currentPath, $menu) &&
502 isset($menu[$currentPath]['title'])
503 ) {
504 $urlVar = !empty($menu[$currentPath]['path_arguments']) ? '&' . $menu[$currentPath]['path_arguments'] : '';
505 $crumbs[] = array(
506 'title' => $menu[$currentPath]['title'],
507 'url' => CRM_Utils_System::url($currentPath,
508 'reset=1' . $urlVar,
509 FALSE, // absolute
510 NULL, // fragment
511 TRUE, // htmlize
512 FALSE, // frontend
513 TRUE // forceBackend; CRM-14439 work-around; acceptable for now because we don't display breadcrumbs on frontend
514 ),
515 );
516 }
517 }
518 $menu[$path]['breadcrumb'] = $crumbs;
519
520 return $crumbs;
521 }
522
523 /**
524 * @param $menu
525 * @param $path
526 */
527 static function buildReturnUrl(&$menu, $path) {
528 if (!isset($menu[$path]['return_url'])) {
529 list($menu[$path]['return_url'], $menu[$path]['return_url_args']) = self::getReturnUrl($menu, $path);
530 }
531 }
532
533 /**
534 * @param $menu
535 * @param $path
536 *
537 * @return array
538 */
539 static function getReturnUrl(&$menu, $path) {
540 if (!isset($menu[$path]['return_url'])) {
541 $pathElements = explode('/', $path);
542 array_pop($pathElements);
543
544 if (empty($pathElements)) {
545 return array(NULL, NULL);
546 }
547 $newPath = implode('/', $pathElements);
548
549 return self::getReturnUrl($menu, $newPath);
550 }
551 else {
552 return array(
553 CRM_Utils_Array::value('return_url',
554 $menu[$path]
555 ),
556 CRM_Utils_Array::value('return_url_args',
557 $menu[$path]
558 ),
559 );
560 }
561 }
562
563 /**
564 * @param $menu
565 * @param $path
566 */
567 static function fillComponentIds(&$menu, $path) {
568 static $cache = array();
569
570 if (array_key_exists('component_id', $menu[$path])) {
571 return;
572 }
573
574 $args = explode('/', $path);
575
576 if (count($args) > 1) {
577 $compPath = $args[0] . '/' . $args[1];
578 }
579 else {
580 $compPath = $args[0];
581 }
582
583 $componentId = NULL;
584
585 if (array_key_exists($compPath, $cache)) {
586 $menu[$path]['component_id'] = $cache[$compPath];
587 }
588 else {
589 if (CRM_Utils_Array::value('component', CRM_Utils_Array::value($compPath, $menu))) {
590 $componentId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Component',
591 $menu[$compPath]['component'],
592 'id', 'name'
593 );
594 }
595 $menu[$path]['component_id'] = $componentId ? $componentId : NULL;
596 $cache[$compPath] = $menu[$path]['component_id'];
597 }
598 }
599
600 /**
601 * @param $path
602 *
603 * @return null
604 */
605 static function get($path) {
606 // return null if menu rebuild
607 $config = CRM_Core_Config::singleton();
608
609 $params = array();
610
611 $args = explode('/', $path);
612
613 $elements = array();
614 while (!empty($args)) {
615 $string = implode('/', $args);
616 $string = CRM_Core_DAO::escapeString($string);
617 $elements[] = "'{$string}'";
618 array_pop($args);
619 }
620
621 $queryString = implode(', ', $elements);
622 $domainID = CRM_Core_Config::domainID();
623 $domainWhereClause = " AND domain_id = $domainID ";
624 if ($config->isUpgradeMode() &&
625 !CRM_Core_DAO::checkFieldExists('civicrm_menu', 'domain_id')
626 ) {
627 //domain_id wouldn't be available for earlier version of
628 //3.0 and therefore can't be used as part of query for
629 //upgrade case
630 $domainWhereClause = "";
631 }
632
633 $query = "
634 (
635 SELECT *
636 FROM civicrm_menu
637 WHERE path in ( $queryString )
638 $domainWhereClause
639 ORDER BY length(path) DESC
640 LIMIT 1
641 )
642 ";
643
644 if ($path != 'navigation') {
645 $query .= "
646 UNION (
647 SELECT *
648 FROM civicrm_menu
649 WHERE path IN ( 'navigation' )
650 $domainWhereClause
651 )
652 ";
653 }
654
655 $menu = new CRM_Core_DAO_Menu();
656 $menu->query($query);
657
658 self::$_menuCache = array();
659 $menuPath = NULL;
660 while ($menu->fetch()) {
661 self::$_menuCache[$menu->path] = array();
662 CRM_Core_DAO::storeValues($menu, self::$_menuCache[$menu->path]);
663
664 foreach (self::$_serializedElements as $element) {
665 self::$_menuCache[$menu->path][$element] = unserialize($menu->$element);
666
667 if (strpos($path, $menu->path) !== FALSE) {
668 $menuPath = &self::$_menuCache[$menu->path];
669 }
670 }
671 }
672
673 if (strstr($path, 'report/instance')) {
674 $args = explode('/', $path);
675 if (is_numeric(end($args))) {
676 $menuPath['path'] .= '/' . end($args);
677 }
678 }
679
680 // *FIXME* : hack for 2.1 -> 2.2 upgrades.
681 if ($path == 'civicrm/upgrade') {
682 $menuPath['page_callback'] = 'CRM_Upgrade_Page_Upgrade';
683 $menuPath['access_arguments'][0][] = 'administer CiviCRM';
684 $menuPath['access_callback'] = array('CRM_Core_Permission', 'checkMenu');
685 }
686 // *FIXME* : hack for 4.1 -> 4.2 upgrades.
687 if (preg_match('/^civicrm\/(upgrade\/)?queue\//', $path)) {
688 CRM_Queue_Menu::alter($path, $menuPath);
689 }
690
691 // Part of upgrade framework but not run inside main upgrade because it deletes data
692 // Once we have another example of a 'cleanup' we should generalize the clause below so it grabs string
693 // which follows upgrade/ and checks for existence of a function in Cleanup class.
694 if ($path == 'civicrm/upgrade/cleanup425') {
695 $menuPath['page_callback'] = array('CRM_Upgrade_Page_Cleanup','cleanup425');
696 $menuPath['access_arguments'][0][] = 'administer CiviCRM';
697 $menuPath['access_callback'] = array('CRM_Core_Permission', 'checkMenu');
698 }
699
700 if (!empty($menuPath)) {
701 $i18n = CRM_Core_I18n::singleton();
702 $i18n->localizeTitles($menuPath);
703 }
704 return $menuPath;
705 }
706
707 /**
708 * @param $pathArgs
709 *
710 * @return mixed
711 */
712 static function getArrayForPathArgs($pathArgs) {
713 if (!is_string($pathArgs)) {
714 return;
715 }
716 $args = array();
717
718 $elements = explode(',', $pathArgs);
719 //CRM_Core_Error::debug( 'e', $elements );
720 foreach ($elements as $keyVal) {
721 list($key, $val) = explode('=', $keyVal, 2);
722 $arr[$key] = $val;
723 }
724
725 if (array_key_exists('urlToSession', $arr)) {
726 $urlToSession = array();
727
728 $params = explode(';', $arr['urlToSession']);
729 $count = 0;
730 foreach ($params as $keyVal) {
731 list($urlToSession[$count]['urlVar'],
732 $urlToSession[$count]['sessionVar'],
733 $urlToSession[$count]['type'],
734 $urlToSession[$count]['default']
735 ) = explode(':', $keyVal);
736 $count++;
737 }
738 $arr['urlToSession'] = $urlToSession;
739 }
740 return $arr;
741 }
742 }
743