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