fix for single value for multi-select-fields passed by the api-explorer
[civicrm-core.git] / CRM / Core / BAO / Navigation.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
6a488035
TO
32 */
33class CRM_Core_BAO_Navigation extends CRM_Core_DAO_Navigation {
34
73538697
CW
35 // Number of characters in the menu js cache key
36 const CACHE_KEY_STRLEN = 8;
37
6a488035 38 /**
fe482240 39 * Class constructor.
6a488035 40 */
00be9182 41 public function __construct() {
6a488035
TO
42 parent::__construct();
43 }
44
45 /**
fe482240 46 * Update the is_active flag in the db.
6a488035 47 *
6a0b768e
TO
48 * @param int $id
49 * Id of the database record.
50 * @param bool $is_active
51 * Value we want to set the is_active field.
6a488035 52 *
ffbff132
EM
53 * @return CRM_Core_DAO_Navigation|NULL
54 * DAO object on success, NULL otherwise
6a488035 55 */
00be9182 56 public static function setIsActive($id, $is_active) {
6a488035
TO
57 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_Navigation', $id, 'is_active', $is_active);
58 }
59
60 /**
ffbff132 61 * Get existing / build navigation for CiviCRM Admin Menu.
6a488035 62 *
a6c01b45
CW
63 * @return array
64 * associated array
6a488035 65 */
00be9182 66 public static function getMenus() {
6a488035
TO
67 $menus = array();
68
69 $menu = new CRM_Core_DAO_Menu();
70 $menu->domain_id = CRM_Core_Config::domainID();
71 $menu->find();
72
73 while ($menu->fetch()) {
74 if ($menu->title) {
75 $menus[$menu->path] = $menu->title;
76 }
77 }
78 return $menus;
79 }
80
81 /**
ffbff132 82 * Add/update navigation record.
6a488035 83 *
ffbff132 84 * @param array $params Submitted values
6a488035 85 *
ffbff132 86 * @return CRM_Core_DAO_Navigation
a6c01b45 87 * navigation object
6a488035 88 */
00be9182 89 public static function add(&$params) {
6a488035 90 $navigation = new CRM_Core_DAO_Navigation();
3523b615 91 if (empty($params['id'])) {
92 $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
93 $params['has_separator'] = CRM_Utils_Array::value('has_separator', $params, FALSE);
94 }
6a488035
TO
95
96 if (!isset($params['id']) ||
481a74f4 97 (CRM_Utils_Array::value('parent_id', $params) != CRM_Utils_Array::value('current_parent_id', $params))
6a488035
TO
98 ) {
99 /* re/calculate the weight, if the Parent ID changed OR create new menu */
100
101 if ($navName = CRM_Utils_Array::value('name', $params)) {
102 $params['name'] = $navName;
103 }
c5e077b2
PJ
104 elseif ($navLabel = CRM_Utils_Array::value('label', $params)) {
105 $params['name'] = $navLabel;
6a488035
TO
106 }
107
108 $params['weight'] = self::calculateWeight(CRM_Utils_Array::value('parent_id', $params));
109 }
110
c5e077b2 111 if (array_key_exists('permission', $params) && is_array($params['permission'])) {
6a488035
TO
112 $params['permission'] = implode(',', $params['permission']);
113 }
114
115 $navigation->copyValues($params);
116
117 $navigation->domain_id = CRM_Core_Config::domainID();
118
119 $navigation->save();
120 return $navigation;
121 }
122
123 /**
fe482240 124 * Fetch object based on array of properties.
6a488035 125 *
6a0b768e
TO
126 * @param array $params
127 * (reference ) an assoc array of name/value pairs.
128 * @param array $defaults
129 * (reference ) an assoc array to hold the flattened values.
6a488035 130 *
16b10e64
CW
131 * @return CRM_Core_BAO_Navigation|null
132 * object on success, NULL otherwise
6a488035 133 */
00be9182 134 public static function retrieve(&$params, &$defaults) {
6a488035
TO
135 $navigation = new CRM_Core_DAO_Navigation();
136 $navigation->copyValues($params);
137
138 $navigation->domain_id = CRM_Core_Config::domainID();
139
140 if ($navigation->find(TRUE)) {
141 CRM_Core_DAO::storeValues($navigation, $defaults);
142 return $navigation;
143 }
144 return NULL;
145 }
146
147 /**
fe482240 148 * Calculate navigation weight.
6a488035 149 *
5a4f6742 150 * @param int $parentID
6a0b768e 151 * Parent_id of a menu.
5a4f6742 152 * @param int $menuID
6a0b768e 153 * Menu id.
6a488035 154 *
a6c01b45
CW
155 * @return int
156 * $weight string
6a488035 157 */
00be9182 158 public static function calculateWeight($parentID = NULL, $menuID = NULL) {
6a488035
TO
159 $domainID = CRM_Core_Config::domainID();
160
161 $weight = 1;
162 // we reset weight for each parent, i.e we start from 1 to n
163 // calculate max weight for top level menus, if parent id is absent
164 if (!$parentID) {
165 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id IS NULL AND domain_id = $domainID";
166 }
167 else {
168 // if parent is passed, we need to get max weight for that particular parent
169 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id = {$parentID} AND domain_id = $domainID";
170 }
171
172 $dao = CRM_Core_DAO::executeQuery($query);
173 $dao->fetch();
174 return $weight = $weight + $dao->weight;
175 }
176
177 /**
fe482240 178 * Get formatted menu list.
6a488035 179 *
a6c01b45
CW
180 * @return array
181 * returns associated array
6a488035 182 */
00be9182 183 public static function getNavigationList() {
6a488035
TO
184 $cacheKeyString = "navigationList";
185 $whereClause = '';
186
187 $config = CRM_Core_Config::singleton();
188
189 // check if we can retrieve from database cache
190 $navigations = CRM_Core_BAO_Cache::getItem('navigation', $cacheKeyString);
191
192 if (!$navigations) {
193 $domainID = CRM_Core_Config::domainID();
194 $query = "
195SELECT id, label, parent_id, weight, is_active, name
196FROM civicrm_navigation WHERE domain_id = $domainID {$whereClause} ORDER BY parent_id, weight ASC";
197 $result = CRM_Core_DAO::executeQuery($query);
198
199 $pidGroups = array();
200 while ($result->fetch()) {
201 $pidGroups[$result->parent_id][$result->label] = $result->id;
202 }
203
204 foreach ($pidGroups[''] as $label => $val) {
205 $pidGroups[''][$label] = self::_getNavigationValue($val, $pidGroups);
206 }
207
208 $navigations = array();
209 self::_getNavigationLabel($pidGroups[''], $navigations);
210
211 CRM_Core_BAO_Cache::setItem($navigations, 'navigation', $cacheKeyString);
212 }
213 return $navigations;
214 }
215
216 /**
ffbff132 217 * Helper function for getNavigationList().
6a488035 218 *
6a0b768e
TO
219 * @param array $list
220 * Menu info.
221 * @param array $navigations
222 * Navigation menus.
223 * @param string $separator
224 * Menu separator.
6a488035 225 */
00be9182 226 public static function _getNavigationLabel($list, &$navigations, $separator = '') {
6a488035
TO
227 $i18n = CRM_Core_I18n::singleton();
228 foreach ($list as $label => $val) {
229 if ($label == 'navigation_id') {
230 continue;
231 }
232 $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
233 $navigations[is_array($val) ? $val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
234 if (is_array($val)) {
235 self::_getNavigationLabel($val, $navigations, $separator . '&nbsp;&nbsp;&nbsp;&nbsp;');
236 }
237 }
238 }
239
240 /**
ffbff132 241 * Helper function for getNavigationList().
6a488035 242 *
6a0b768e
TO
243 * @param string $val
244 * Menu name.
245 * @param array $pidGroups
246 * Parent menus.
ffbff132 247 *
6a488035
TO
248 * @return array
249 */
00be9182 250 public static function _getNavigationValue($val, &$pidGroups) {
6a488035
TO
251 if (array_key_exists($val, $pidGroups)) {
252 $list = array('navigation_id' => $val);
253 foreach ($pidGroups[$val] as $label => $id) {
254 $list[$label] = self::_getNavigationValue($id, $pidGroups);
255 }
256 unset($pidGroups[$val]);
257 return $list;
258 }
259 else {
260 return $val;
261 }
262 }
263
264 /**
fe482240 265 * Build navigation tree.
6a488035 266 *
6a0b768e
TO
267 * @param array $navigationTree
268 * Nested array of menus.
269 * @param int $parentID
270 * Parent id.
271 * @param bool $navigationMenu
272 * True when called for building top navigation menu.
6a488035 273 *
a6c01b45
CW
274 * @return array
275 * nested array of menus
6a488035 276 */
00be9182 277 public static function buildNavigationTree(&$navigationTree, $parentID, $navigationMenu = TRUE) {
6a488035
TO
278 $whereClause = " parent_id IS NULL";
279
280 if ($parentID) {
281 $whereClause = " parent_id = {$parentID}";
282 }
283
284 $domainID = CRM_Core_Config::domainID();
285
286 // get the list of menus
287 $query = "
288SELECT id, label, url, permission, permission_operator, has_separator, parent_id, is_active, name
289FROM civicrm_navigation
290WHERE {$whereClause}
291AND domain_id = $domainID
292ORDER BY parent_id, weight";
293
294 $navigation = CRM_Core_DAO::executeQuery($query);
295 $config = CRM_Core_Config::singleton();
296 while ($navigation->fetch()) {
297 $label = $navigation->label;
298 if (!$navigationMenu) {
299 $label = addcslashes($label, '"');
300 }
301
302 // for each menu get their children
303 $navigationTree[$navigation->id] = array(
6ea503d4
TO
304 'attributes' => array(
305 'label' => $label,
6a488035
TO
306 'name' => $navigation->name,
307 'url' => $navigation->url,
308 'permission' => $navigation->permission,
309 'operator' => $navigation->permission_operator,
310 'separator' => $navigation->has_separator,
311 'parentID' => $navigation->parent_id,
312 'navID' => $navigation->id,
313 'active' => $navigation->is_active,
acb1052e 314 ),
353ffa53 315 );
6a488035
TO
316 self::buildNavigationTree($navigationTree[$navigation->id]['child'], $navigation->id, $navigationMenu);
317 }
318
319 return $navigationTree;
320 }
321
322 /**
fe482240 323 * Build menu.
6a488035 324 *
6a0b768e
TO
325 * @param bool $json
326 * By default output is html.
327 * @param bool $navigationMenu
328 * True when called for building top navigation menu.
6a488035 329 *
72b3a70c
CW
330 * @return string
331 * html or json string
6a488035 332 */
00be9182 333 public static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
6a488035
TO
334 $navigations = array();
335 self::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
336 $navigationString = NULL;
337
338 // run the Navigation through a hook so users can modify it
339 CRM_Utils_Hook::navigationMenu($navigations);
b774b065 340 self::fixNavigationMenu($navigations);
6a488035
TO
341
342 $i18n = CRM_Core_I18n::singleton();
343
344 //skip children menu item if user don't have access to parent menu item
345 $skipMenuItems = array();
346 foreach ($navigations as $key => $value) {
347 if ($json) {
348 if ($navigationString) {
349 $navigationString .= '},';
350 }
351 $data = $value['attributes']['label'];
352 $class = '';
353 if (!$value['attributes']['active']) {
354 $class = ', "attr": { "class" : "disabled"} ';
355 }
356 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
357 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
358 }
359 else {
360 // Home is a special case
361 if ($value['attributes']['name'] != 'Home') {
362 $name = self::getMenuName($value, $skipMenuItems);
363 if ($name) {
364 //separator before
365 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
366 $navigationString .= '<li class="menu-separator"></li>';
367 }
368 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
369 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
370 }
371 }
372 }
373
374 self::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
375 }
376
377 if ($json) {
378 $navigationString = '[' . $navigationString . '}]';
379 }
380 else {
381 // clean up - Need to remove empty <ul>'s, this happens when user don't have
382 // permission to access parent
383 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
384 }
385
386 return $navigationString;
387 }
388
389 /**
fe482240 390 * Recursively check child menus.
6a488035
TO
391 *
392 * @param array $value
393 * @param string $navigationString
6a0b768e
TO
394 * @param bool $json
395 * @param bool $skipMenuItems
ffbff132 396 *
6a488035
TO
397 * @return string
398 */
00be9182 399 public static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
6a488035
TO
400 if ($json) {
401 if (!empty($value['child'])) {
402 $navigationString .= ', "children": [ ';
403 }
404 else {
405 return $navigationString;
406 }
407
408 if (!empty($value['child'])) {
409 $appendComma = TRUE;
410 $count = 1;
411 foreach ($value['child'] as $k => $val) {
412 if ($count == count($value['child'])) {
413 $appendComma = FALSE;
414 }
415 $data = $val['attributes']['label'];
416 $class = '';
417 if (!$val['attributes']['active']) {
418 $class = ', "attr": { "class" : "disabled"} ';
419 }
420 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
421 self::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
422 $navigationString .= $appendComma ? ' },' : ' }';
423 $count++;
424 }
425 }
426
427 if (!empty($value['child'])) {
428 $navigationString .= ' ]';
429 }
430 }
431 else {
432 if (!empty($value['child'])) {
433 $navigationString .= '<ul>';
434 }
435 else {
436 $navigationString .= '</li>';
437 //locate separator after
438 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
439 $navigationString .= '<li class="menu-separator"></li>';
440 }
441 }
442
443 if (!empty($value['child'])) {
444 foreach ($value['child'] as $val) {
445 $name = self::getMenuName($val, $skipMenuItems);
446 if ($name) {
447 //locate separator before
448 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
449 $navigationString .= '<li class="menu-separator"></li>';
450 }
451 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
452 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
453 self::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
454 }
455 }
456 }
457 if (!empty($value['child'])) {
458 $navigationString .= '</ul></li>';
459 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
460 $navigationString .= '<li class="menu-separator"></li>';
461 }
462 }
463 }
464 return $navigationString;
465 }
466
b774b065
TO
467 /**
468 * Given a navigation menu, generate navIDs for any items which are
469 * missing them.
470 *
471 * @param array $nodes
472 * Each key is a numeral; each value is a node in
473 * the menu tree (with keys "child" and "attributes").
474 */
475 public static function fixNavigationMenu(&$nodes) {
476 $maxNavID = 1;
477 array_walk_recursive($nodes, function($item, $key) use (&$maxNavID) {
478 if ($key === 'navID') {
479 $maxNavID = max($maxNavID, $item);
480 }
481 });
482 self::_fixNavigationMenu($nodes, $maxNavID, NULL);
483 }
484
485 /**
486 * @param array $nodes
487 * Each key is a numeral; each value is a node in
488 * the menu tree (with keys "child" and "attributes").
ea3ddccf 489 * @param int $maxNavID
490 * @param int $parentID
b774b065
TO
491 */
492 private static function _fixNavigationMenu(&$nodes, &$maxNavID, $parentID) {
493 $origKeys = array_keys($nodes);
494 foreach ($origKeys as $origKey) {
495 if (!isset($nodes[$origKey]['attributes']['parentID']) && $parentID !== NULL) {
496 $nodes[$origKey]['attributes']['parentID'] = $parentID;
497 }
498 // If no navID, then assign navID and fix key.
499 if (!isset($nodes[$origKey]['attributes']['navID'])) {
500 $newKey = ++$maxNavID;
501 $nodes[$origKey]['attributes']['navID'] = $newKey;
502 $nodes[$newKey] = $nodes[$origKey];
503 unset($nodes[$origKey]);
504 $origKey = $newKey;
505 }
506 if (isset($nodes[$origKey]['child']) && is_array($nodes[$origKey]['child'])) {
507 self::_fixNavigationMenu($nodes[$origKey]['child'], $maxNavID, $nodes[$origKey]['attributes']['navID']);
508 }
509 }
510 }
511
6a488035 512 /**
fe482240 513 * Get Menu name.
6a488035
TO
514 *
515 * @param $value
100fef9d 516 * @param array $skipMenuItems
ffbff132 517 *
6a488035
TO
518 * @return bool|string
519 */
00be9182 520 public static function getMenuName(&$value, &$skipMenuItems) {
6a488035
TO
521 // we need to localise the menu labels (CRM-5456) and don’t
522 // want to use ts() as it would throw the ts-extractor off
523 $i18n = CRM_Core_I18n::singleton();
524
353ffa53 525 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
29c4b4bf
WA
526 $url = CRM_Utils_Array::value('url', $value['attributes']);
527 $permission = CRM_Utils_Array::value('permission', $value['attributes']);
528 $operator = CRM_Utils_Array::value('operator', $value['attributes']);
529 $parentID = CRM_Utils_Array::value('parentID', $value['attributes']);
530 $navID = CRM_Utils_Array::value('navID', $value['attributes']);
531 $active = CRM_Utils_Array::value('active', $value['attributes']);
532 $menuName = CRM_Utils_Array::value('name', $value['attributes']);
353ffa53 533 $target = CRM_Utils_Array::value('target', $value['attributes']);
6a488035
TO
534
535 if (in_array($parentID, $skipMenuItems) || !$active) {
536 $skipMenuItems[] = $navID;
537 return FALSE;
538 }
539
540 //we need to check core view/edit or supported acls.
541 if (in_array($menuName, array(
353ffa53 542 'Search...',
acb1052e 543 'Contacts',
353ffa53 544 ))) {
6a488035
TO
545 if (!CRM_Core_Permission::giveMeAllACLs()) {
546 $skipMenuItems[] = $navID;
547 return FALSE;
548 }
549 }
550
551 $config = CRM_Core_Config::singleton();
552
553 $makeLink = FALSE;
554 if (isset($url) && $url) {
8ce923d1 555 if (substr($url, 0, 4) !== 'http') {
6a488035
TO
556 //CRM-7656 --make sure to separate out url path from url params,
557 //as we'r going to validate url path across cross-site scripting.
710199c8 558 $urlParam = explode('?', $url);
559 if (empty($urlParam[1])) {
560 $urlParam[1] = NULL;
561 }
1351950a 562 $url = CRM_Utils_System::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
6a488035 563 }
f39c14c6
CW
564 elseif (strpos($url, '&amp;') === FALSE) {
565 $url = htmlspecialchars($url);
566 }
6a488035
TO
567 $makeLink = TRUE;
568 }
569
570 static $allComponents;
571 if (!$allComponents) {
572 $allComponents = CRM_Core_Component::getNames();
573 }
574
575 if (isset($permission) && $permission) {
576 $permissions = explode(',', $permission);
577
578 $hasPermission = FALSE;
579 foreach ($permissions as $key) {
580 $key = trim($key);
581 $showItem = TRUE;
582
583 //get the component name from permission.
584 $componentName = CRM_Core_Permission::getComponentName($key);
585
586 if ($componentName) {
587 if (!in_array($componentName, $config->enableComponents) ||
588 !CRM_Core_Permission::check($key)
589 ) {
590 $showItem = FALSE;
591 if ($operator == 'AND') {
592 $skipMenuItems[] = $navID;
593 return $showItem;
594 }
595 }
596 else {
597 $hasPermission = TRUE;
598 }
599 }
600 elseif (!CRM_Core_Permission::check($key)) {
601 $showItem = FALSE;
602 if ($operator == 'AND') {
603 $skipMenuItems[] = $navID;
604 return $showItem;
605 }
606 }
607 else {
608 $hasPermission = TRUE;
609 }
610 }
611
612 if (!$showItem && !$hasPermission) {
613 $skipMenuItems[] = $navID;
614 return FALSE;
615 }
616 }
617
618 if ($makeLink) {
202407d7 619 $url = CRM_Utils_System::evalUrl($url);
6a488035
TO
620 if ($target) {
621 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
622 }
623 else {
624 $name = "<a href=\"{$url}\">{$name}</a>";
625 }
626 }
627
628 return $name;
629 }
630
631 /**
fe482240 632 * Create navigation for CiviCRM Admin Menu.
6a488035 633 *
6a0b768e
TO
634 * @param int $contactID
635 * Contact id.
6a488035 636 *
a6c01b45
CW
637 * @return string
638 * returns navigation html
6a488035 639 */
00be9182 640 public static function createNavigation($contactID) {
6a488035
TO
641 $config = CRM_Core_Config::singleton();
642
73538697 643 $navigation = self::buildNavigation();
6a488035 644
73538697 645 if ($navigation) {
6a488035
TO
646
647 //add additional navigation items
648 $logoutURL = CRM_Utils_System::url('civicrm/logout', 'reset=1');
6a488035
TO
649
650 // get home menu from db
651 $homeParams = array('name' => 'Home');
652 $homeNav = array();
a2e1885c 653 $homeIcon = '<span class="crm-logo-sm" ></span>';
6a488035
TO
654 self::retrieve($homeParams, $homeNav);
655 if ($homeNav) {
710199c8 656 list($path, $q) = explode('?', $homeNav['url']);
6a488035
TO
657 $homeURL = CRM_Utils_System::url($path, $q);
658 $homeLabel = $homeNav['label'];
659 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
660 if ($homeLabel == 'Home') {
a65693e5 661 $homeLabel = ts('CiviCRM Home');
6a488035
TO
662 }
663 }
664 else {
665 $homeURL = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
a65693e5 666 $homeLabel = ts('CiviCRM Home');
6a488035 667 }
8960d9b9 668 // Link to hide the menubar
8b571e4c 669 $hideLabel = ts('Hide Menu');
6a488035 670
8960d9b9
CW
671 $prepandString = "
672 <li class='menumain crm-link-home'>$homeIcon
673 <ul id='civicrm-home'>
674 <li><a href='$homeURL'>$homeLabel</a></li>
675 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
86bfa4f6 676 <li><a href='$logoutURL' class='crm-logout-link'>" . ts('Log out') . "</a></li>
8960d9b9
CW
677 </ul>";
678 // <li> tag doesn't need to be closed
73538697 679 }
8960d9b9 680 return $prepandString . $navigation;
73538697 681 }
6a488035 682
73538697 683 /**
fe482240 684 * Reset navigation for all contacts or a specified contact.
73538697 685 *
6a0b768e
TO
686 * @param int $contactID
687 * Reset only entries belonging to that contact ID.
ffbff132 688 *
73538697
CW
689 * @return string
690 */
00be9182 691 public static function resetNavigation($contactID = NULL) {
73538697
CW
692 $newKey = CRM_Utils_String::createRandom(self::CACHE_KEY_STRLEN, CRM_Utils_String::ALPHANUMERIC);
693 if (!$contactID) {
694 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
695 CRM_Core_DAO::executeQuery($query);
696 CRM_Core_BAO_Cache::deleteGroup('navigation');
697 }
698 else {
6a488035 699 // before inserting check if contact id exists in db
73538697 700 // this is to handle weird case when contact id is in session but not in db
6a488035
TO
701 $contact = new CRM_Contact_DAO_Contact();
702 $contact->id = $contactID;
703 if ($contact->find(TRUE)) {
704 CRM_Core_BAO_Setting::setItem(
73538697 705 $newKey,
6a488035
TO
706 CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME,
707 'navigation',
708 NULL,
709 $contactID,
710 $contactID
711 );
712 }
713 }
6a488035 714 // also reset the dashlet cache in case permissions have changed etc
73538697 715 // FIXME: decouple this
6a488035 716 CRM_Core_BAO_Dashboard::resetDashletCache($contactID);
73538697
CW
717
718 return $newKey;
6a488035
TO
719 }
720
721 /**
fe482240 722 * Process navigation.
6a488035 723 *
6a0b768e
TO
724 * @param array $params
725 * Associated array, $_GET.
6a488035 726 */
00be9182 727 public static function processNavigation(&$params) {
353ffa53
TO
728 $nodeID = (int) str_replace("node_", "", $params['id']);
729 $referenceID = (int) str_replace("node_", "", $params['ref_id']);
730 $position = $params['ps'];
731 $type = $params['type'];
732 $label = CRM_Utils_Array::value('data', $params);
6a488035
TO
733
734 switch ($type) {
735 case "move":
736 self::processMove($nodeID, $referenceID, $position);
737 break;
738
739 case "rename":
740 self::processRename($nodeID, $label);
741 break;
742
743 case "delete":
744 self::processDelete($nodeID);
745 break;
746 }
747
748 //reset navigation menus
749 self::resetNavigation();
750 CRM_Utils_System::civiExit();
751 }
752
753 /**
fe482240 754 * Process move action.
6a488035 755 *
6a0b768e
TO
756 * @param $nodeID
757 * Node that is being moved.
758 * @param $referenceID
759 * Parent id where node is moved. 0 mean no parent.
760 * @param $position
761 * New position of the nod, it starts with 0 - n.
6a488035 762 */
00be9182 763 public static function processMove($nodeID, $referenceID, $position) {
6a488035
TO
764 // based on the new position we need to get the weight of the node after moved node
765 // 1. update the weight of $position + 1 nodes to weight + 1
766 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
767
768 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
769 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
770 // accordingly set the new parent_id
771 if ($referenceID) {
772 $newParentID = $referenceID;
773 $parentClause = "parent_id = {$referenceID} ";
774 }
775 else {
776 $newParentID = 'NULL';
777 $parentClause = 'parent_id IS NULL';
778 }
779
4eeb9a5b 780 $incrementOtherNodes = TRUE;
353ffa53 781 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
481a74f4 782 $params = array(1 => array($position, 'Positive'));
6a488035
TO
783 $newWeight = CRM_Core_DAO::singleValueQuery($sql, $params);
784
785 // this means node is moved to last position, so you need to get the weight of last element + 1
786 if (!$newWeight) {
7cc5305f
CW
787 // If this is not the first item being added to a parent
788 if ($position) {
789 $lastPosition = $position - 1;
790 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
791 $params = array(1 => array($lastPosition, 'Positive'));
792 $newWeight = CRM_Core_DAO::singleValueQuery($sql, $params);
793
794 // since last node increment + 1
795 $newWeight = $newWeight + 1;
796 }
797 else {
798 $newWeight = '0';
799 }
6a488035
TO
800
801 // since this is a last node we don't need to increment other nodes
ab8a593e 802 $incrementOtherNodes = FALSE;
6a488035
TO
803 }
804
805 $transaction = new CRM_Core_Transaction();
806
807 // now update the existing nodes to weight + 1, if required.
481a74f4 808 if ($incrementOtherNodes) {
6a488035
TO
809 $query = "UPDATE civicrm_navigation SET weight = weight + 1
810 WHERE {$parentClause} AND weight >= {$newWeight}";
811
812 CRM_Core_DAO::executeQuery($query);
813 }
814
815 // finally set the weight of current node
816 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
817 CRM_Core_DAO::executeQuery($query);
818
819 $transaction->commit();
820 }
821
822 /**
ffbff132 823 * Function to process rename action for tree.
6a488035 824 *
100fef9d 825 * @param int $nodeID
6a488035
TO
826 * @param $label
827 */
00be9182 828 public static function processRename($nodeID, $label) {
6a488035
TO
829 CRM_Core_DAO::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
830 }
831
832 /**
fe482240 833 * Process delete action for tree.
6a488035 834 *
100fef9d 835 * @param int $nodeID
6a488035 836 */
00be9182 837 public static function processDelete($nodeID) {
6a488035
TO
838 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
839 CRM_Core_DAO::executeQuery($query);
840 }
841
842 /**
fe482240 843 * Get the info on navigation item.
6a488035 844 *
6a0b768e
TO
845 * @param int $navigationID
846 * Navigation id.
6a488035 847 *
a6c01b45
CW
848 * @return array
849 * associated array
6a488035 850 */
00be9182 851 public static function getNavigationInfo($navigationID) {
353ffa53 852 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
6a488035 853 $params = array($navigationID, 'Integer');
353ffa53 854 $dao = CRM_Core_DAO::executeQuery($query, array(1 => $params));
6a488035
TO
855 $dao->fetch();
856 return array(
857 'parent_id' => $dao->parent_id,
858 'weight' => $dao->weight,
859 );
860 }
861
862 /**
fe482240 863 * Update menu.
6a488035 864 *
6a0b768e
TO
865 * @param array $params
866 * @param array $newParams
867 * New value of params.
6a488035 868 */
00be9182 869 public static function processUpdate($params, $newParams) {
6a488035
TO
870 $dao = new CRM_Core_DAO_Navigation();
871 $dao->copyValues($params);
872 if ($dao->find(TRUE)) {
873 $dao->copyValues($newParams);
874 $dao->save();
875 }
876 }
73538697 877
31cb1898
AN
878 /**
879 * Rebuild reports menu.
880 *
881 * All Contact reports will become sub-items of 'Contact Reports' and so on.
882 *
883 * @param int $domain_id
884 */
885 public static function rebuildReportsNavigation($domain_id) {
886 $component_to_nav_name = array(
887 'CiviContact' => 'Contact Reports',
888 'CiviContribute' => 'Contribution Reports',
889 'CiviMember' => 'Membership Reports',
890 'CiviEvent' => 'Event Reports',
891 'CiviPledge' => 'Pledge Reports',
892 'CiviGrant' => 'Grant Reports',
893 'CiviMail' => 'Mailing Reports',
894 'CiviCampaign' => 'Campaign Reports',
895 );
896
897 // Create or update the top level Reports link.
898 $reports_nav = self::createOrUpdateTopLevelReportsNavItem($domain_id);
899
900 // Get all active report instances grouped by component.
901 $components = self::getAllActiveReportsByComponent($domain_id);
902 foreach ($components as $component_id => $component) {
903 // Create or update the per component reports links.
904 $component_nav_name = $component['name'];
905 if (isset($component_to_nav_name[$component_nav_name])) {
906 $component_nav_name = $component_to_nav_name[$component_nav_name];
907 }
908 $permission = "access {$component['name']}";
909 if ($component['name'] === 'CiviContact') {
910 $permission = "administer CiviCRM";
911 }
912 elseif ($component['name'] === 'CiviCampaign') {
913 $permission = "access CiviReport";
914 }
0087242f 915 $component_nav = self::createOrUpdateReportNavItem($component_nav_name, 'civicrm/report/list',
916 "compid={$component_id}&reset=1", $reports_nav->id, $permission, $domain_id, TRUE);
31cb1898
AN
917 foreach ($component['reports'] as $report_id => $report) {
918 // Create or update the report instance links.
51704c4d 919 $report_nav = self::createOrUpdateReportNavItem($report['title'], $report['url'], 'reset=1', $component_nav->id, $report['permission'], $domain_id, FALSE, TRUE);
31cb1898
AN
920 // Update the report instance to include the navigation id.
921 $query = "UPDATE civicrm_report_instance SET navigation_id = %1 WHERE id = %2";
922 $params = array(
923 1 => array($report_nav->id, 'Integer'),
924 2 => array($report_id, 'Integer'),
925 );
926 CRM_Core_DAO::executeQuery($query, $params);
927 }
928 }
929
930 // Create or update the All Reports link.
dfbeefd8 931 self::createOrUpdateReportNavItem('All Reports', 'civicrm/report/list', 'reset=1', $reports_nav->id, 'access CiviReport', $domain_id, TRUE);
31cb1898
AN
932 }
933
934 /**
935 * Create the top level 'Reports' item in the navigation tree.
936 *
937 * @param int $domain_id
938 *
939 * @return bool|\CRM_Core_DAO
940 */
941 static public function createOrUpdateTopLevelReportsNavItem($domain_id) {
942 $id = NULL;
943
944 $dao = new CRM_Core_BAO_Navigation();
945 $dao->name = 'Reports';
946 $dao->domain_id = $domain_id;
947 // The first selectAdd clears it - so that we only retrieve the one field.
948 $dao->selectAdd();
949 $dao->selectAdd('id');
950 if ($dao->find(TRUE)) {
951 $id = $dao->id;
952 }
953
954 $nav = self::createReportNavItem('Reports', NULL, NULL, NULL, 'access CiviReport', $id, $domain_id);
955 return $nav;
956 }
957
958 /**
959 * Retrieve a navigation item using it's url.
960 *
51704c4d 961 * Note that we use LIKE to permit a wildcard as the calling code likely doesn't
962 * care about output params appended.
963 *
31cb1898
AN
964 * @param string $url
965 * @param array $url_params
966 *
0087242f 967 * @param int|null $parent_id
968 * Optionally restrict to one parent.
969 *
970 * @return bool|\CRM_Core_BAO_Navigation
31cb1898 971 */
0087242f 972 public static function getNavItemByUrl($url, $url_params, $parent_id = NULL) {
973 $nav = new CRM_Core_BAO_Navigation();
0087242f 974 $nav->parent_id = $parent_id;
51704c4d 975 $nav->whereAdd("url LIKE '{$url}?{$url_params}'");
976
0087242f 977 if ($nav->find(TRUE)) {
978 return $nav;
31cb1898
AN
979 }
980 return FALSE;
981 }
982
983 /**
984 * Get all active reports, organised by component.
985 *
986 * @param int $domain_id
987 *
988 * @return array
989 */
990 public static function getAllActiveReportsByComponent($domain_id) {
991 $sql = "
992 SELECT
993 civicrm_report_instance.id, civicrm_report_instance.title, civicrm_report_instance.permission, civicrm_component.name, civicrm_component.id AS component_id
994 FROM
995 civicrm_option_group
996 LEFT JOIN
997 civicrm_option_value ON civicrm_option_value.option_group_id = civicrm_option_group.id AND civicrm_option_group.name = 'report_template'
998 LEFT JOIN
999 civicrm_report_instance ON civicrm_option_value.value = civicrm_report_instance.report_id
1000 LEFT JOIN
1001 civicrm_component ON civicrm_option_value.component_id = civicrm_component.id
1002 WHERE
1003 civicrm_option_value.is_active = 1
1004 AND
1005 civicrm_report_instance.domain_id = %1
1006 ORDER BY civicrm_option_value.weight";
1007
1008 $dao = CRM_Core_DAO::executeQuery($sql, array(
1009 1 => array($domain_id, 'Integer'),
1010 ));
1011 $rows = array();
1012 while ($dao->fetch()) {
1013 $component_name = is_null($dao->name) ? 'CiviContact' : $dao->name;
1014 $component_id = is_null($dao->component_id) ? 99 : $dao->component_id;
1015 $rows[$component_id]['name'] = $component_name;
1016 $rows[$component_id]['reports'][$dao->id] = array(
1017 'title' => $dao->title,
1018 'url' => "civicrm/report/instance/{$dao->id}",
1019 'permission' => $dao->permission,
1020 );
1021 }
1022 return $rows;
1023 }
1024
1025 /**
1026 * Create or update a navigation item for a report instance.
1027 *
1028 * The function will check whether create or update is required.
1029 *
1030 * @param string $name
1031 * @param string $url
1032 * @param string $url_params
1033 * @param int $parent_id
1034 * @param string $permission
1035 * @param int $domain_id
1036 *
0087242f 1037 * @param bool $onlyMatchParentID
1038 * If True then do not match with a url that has a different parent
1039 * (This is because for top level items there is a risk of 'stealing' rows that normally
1040 * live under 'Contact' and intentionally duplicate the report examples.)
1041 *
31cb1898
AN
1042 * @return \CRM_Core_DAO_Navigation
1043 */
0087242f 1044 protected static function createOrUpdateReportNavItem($name, $url, $url_params, $parent_id, $permission,
51704c4d 1045 $domain_id, $onlyMatchParentID = FALSE, $useWildcard = TRUE) {
31cb1898 1046 $id = NULL;
51704c4d 1047 $existing_url_params = $useWildcard ? $url_params . '%' : $url_params;
1048 $existing_nav = CRM_Core_BAO_Navigation::getNavItemByUrl($url, $existing_url_params, ($onlyMatchParentID ? $parent_id : NULL));
31cb1898
AN
1049 if ($existing_nav) {
1050 $id = $existing_nav->id;
1051 }
0087242f 1052
31cb1898
AN
1053 $nav = self::createReportNavItem($name, $url, $url_params, $parent_id, $permission, $id, $domain_id);
1054 return $nav;
1055 }
1056
1057 /**
1058 * Create a navigation item for a report instance.
1059 *
1060 * @param string $name
1061 * @param string $url
1062 * @param string $url_params
1063 * @param int $parent_id
1064 * @param string $permission
1065 * @param int $id
1066 * @param int $domain_id
1067 * ID of domain to create item in.
1068 *
1069 * @return \CRM_Core_DAO_Navigation
1070 */
1071 public static function createReportNavItem($name, $url, $url_params, $parent_id, $permission, $id, $domain_id) {
1072 if ($url !== NULL) {
1073 $url = "{$url}?{$url_params}";
1074 }
1075 $params = array(
1076 'name' => $name,
1077 'label' => ts($name),
1078 'url' => $url,
1079 'parent_id' => $parent_id,
1080 'is_active' => TRUE,
1081 'permission' => array(
1082 $permission,
1083 ),
1084 'domain_id' => $domain_id,
1085 );
0087242f 1086 if ($id) {
31cb1898
AN
1087 $params['id'] = $id;
1088 }
0087242f 1089 return CRM_Core_BAO_Navigation::add($params);
31cb1898
AN
1090 }
1091
b5c2afd0 1092 /**
ffbff132
EM
1093 * Get cache key.
1094 *
100fef9d 1095 * @param int $cid
b5c2afd0
EM
1096 *
1097 * @return object|string
1098 */
00be9182 1099 public static function getCacheKey($cid) {
73538697
CW
1100 $key = CRM_Core_BAO_Setting::getItem(
1101 CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME,
1102 'navigation',
1103 NULL,
1104 '',
1105 $cid
1106 );
1107 if (strlen($key) !== self::CACHE_KEY_STRLEN) {
1108 $key = self::resetNavigation($cid);
1109 }
1110 return $key;
1111 }
96025800 1112
6a488035 1113}