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