Merge pull request #9769 from scardinius/crm-19958
[civicrm-core.git] / CRM / Core / BAO / Navigation.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
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
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
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 *
a6c01b45
CW
267 * @return array
268 * nested array of menus
6a488035 269 */
656e5c5b 270 public static function buildNavigationTree() {
6a488035 271 $domainID = CRM_Core_Config::domainID();
656e5c5b 272 $navigationTree = array();
6a488035
TO
273
274 // get the list of menus
275 $query = "
276SELECT id, label, url, permission, permission_operator, has_separator, parent_id, is_active, name
277FROM civicrm_navigation
656e5c5b 278WHERE domain_id = $domainID
6a488035
TO
279ORDER BY parent_id, weight";
280
281 $navigation = CRM_Core_DAO::executeQuery($query);
6a488035 282 while ($navigation->fetch()) {
6a488035 283 $navigationTree[$navigation->id] = array(
6ea503d4 284 'attributes' => array(
656e5c5b 285 'label' => $navigation->label,
6a488035
TO
286 'name' => $navigation->name,
287 'url' => $navigation->url,
288 'permission' => $navigation->permission,
289 'operator' => $navigation->permission_operator,
290 'separator' => $navigation->has_separator,
291 'parentID' => $navigation->parent_id,
292 'navID' => $navigation->id,
293 'active' => $navigation->is_active,
acb1052e 294 ),
353ffa53 295 );
6a488035
TO
296 }
297
656e5c5b 298 return self::buildTree($navigationTree);
6a488035
TO
299 }
300
301 /**
656e5c5b 302 * Convert flat array to nested.
6a488035 303 *
656e5c5b
CW
304 * @param array $elements
305 * @param int|null $parentId
306 *
307 * @return array
308 */
309 private static function buildTree($elements, $parentId = NULL) {
310 $branch = array();
311
312 foreach ($elements as $id => $element) {
313 if ($element['attributes']['parentID'] == $parentId) {
314 $children = self::buildTree($elements, $id);
315 if ($children) {
316 $element['child'] = $children;
317 }
318 $branch[$id] = $element;
319 }
320 }
321
322 return $branch;
323 }
324
325 /**
326 * Build menu.
6a488035 327 *
72b3a70c 328 * @return string
6a488035 329 */
656e5c5b
CW
330 public static function buildNavigation() {
331 $navigations = self::buildNavigationTree();
332 $navigationString = '';
6a488035
TO
333
334 // run the Navigation through a hook so users can modify it
335 CRM_Utils_Hook::navigationMenu($navigations);
b774b065 336 self::fixNavigationMenu($navigations);
6a488035 337
6a488035
TO
338 //skip children menu item if user don't have access to parent menu item
339 $skipMenuItems = array();
340 foreach ($navigations as $key => $value) {
656e5c5b
CW
341 // Home is a special case
342 if ($value['attributes']['name'] != 'Home') {
343 $name = self::getMenuName($value, $skipMenuItems);
344 if ($name) {
345 //separator before
346 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
347 $navigationString .= '<li class="menu-separator"></li>';
6a488035 348 }
656e5c5b
CW
349 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
350 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
6a488035
TO
351 }
352 }
656e5c5b 353 self::recurseNavigation($value, $navigationString, $skipMenuItems);
6a488035
TO
354 }
355
656e5c5b
CW
356 // clean up - Need to remove empty <ul>'s, this happens when user don't have
357 // permission to access parent
358 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
6a488035
TO
359
360 return $navigationString;
361 }
362
363 /**
fe482240 364 * Recursively check child menus.
6a488035
TO
365 *
366 * @param array $value
367 * @param string $navigationString
656e5c5b 368 * @param array $skipMenuItems
ffbff132 369 *
6a488035
TO
370 * @return string
371 */
656e5c5b
CW
372 public static function recurseNavigation(&$value, &$navigationString, $skipMenuItems) {
373 if (!empty($value['child'])) {
374 $navigationString .= '<ul>';
6a488035
TO
375 }
376 else {
656e5c5b
CW
377 $navigationString .= '</li>';
378 //locate separator after
379 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
380 $navigationString .= '<li class="menu-separator"></li>';
6a488035 381 }
656e5c5b 382 }
6a488035 383
656e5c5b
CW
384 if (!empty($value['child'])) {
385 foreach ($value['child'] as $val) {
386 $name = self::getMenuName($val, $skipMenuItems);
387 if ($name) {
388 //locate separator before
389 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
390 $navigationString .= '<li class="menu-separator"></li>';
6a488035 391 }
656e5c5b
CW
392 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
393 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
394 self::recurseNavigation($val, $navigationString, $skipMenuItems);
6a488035
TO
395 }
396 }
656e5c5b
CW
397 }
398 if (!empty($value['child'])) {
399 $navigationString .= '</ul></li>';
400 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
401 $navigationString .= '<li class="menu-separator"></li>';
6a488035
TO
402 }
403 }
404 return $navigationString;
405 }
406
b774b065
TO
407 /**
408 * Given a navigation menu, generate navIDs for any items which are
409 * missing them.
410 *
411 * @param array $nodes
412 * Each key is a numeral; each value is a node in
413 * the menu tree (with keys "child" and "attributes").
414 */
415 public static function fixNavigationMenu(&$nodes) {
416 $maxNavID = 1;
417 array_walk_recursive($nodes, function($item, $key) use (&$maxNavID) {
418 if ($key === 'navID') {
419 $maxNavID = max($maxNavID, $item);
420 }
421 });
422 self::_fixNavigationMenu($nodes, $maxNavID, NULL);
423 }
424
425 /**
426 * @param array $nodes
427 * Each key is a numeral; each value is a node in
428 * the menu tree (with keys "child" and "attributes").
ea3ddccf 429 * @param int $maxNavID
430 * @param int $parentID
b774b065
TO
431 */
432 private static function _fixNavigationMenu(&$nodes, &$maxNavID, $parentID) {
433 $origKeys = array_keys($nodes);
434 foreach ($origKeys as $origKey) {
435 if (!isset($nodes[$origKey]['attributes']['parentID']) && $parentID !== NULL) {
436 $nodes[$origKey]['attributes']['parentID'] = $parentID;
437 }
438 // If no navID, then assign navID and fix key.
439 if (!isset($nodes[$origKey]['attributes']['navID'])) {
440 $newKey = ++$maxNavID;
441 $nodes[$origKey]['attributes']['navID'] = $newKey;
442 $nodes[$newKey] = $nodes[$origKey];
443 unset($nodes[$origKey]);
444 $origKey = $newKey;
445 }
446 if (isset($nodes[$origKey]['child']) && is_array($nodes[$origKey]['child'])) {
447 self::_fixNavigationMenu($nodes[$origKey]['child'], $maxNavID, $nodes[$origKey]['attributes']['navID']);
448 }
449 }
450 }
451
6a488035 452 /**
fe482240 453 * Get Menu name.
6a488035
TO
454 *
455 * @param $value
100fef9d 456 * @param array $skipMenuItems
ffbff132 457 *
6a488035
TO
458 * @return bool|string
459 */
00be9182 460 public static function getMenuName(&$value, &$skipMenuItems) {
6a488035
TO
461 // we need to localise the menu labels (CRM-5456) and don’t
462 // want to use ts() as it would throw the ts-extractor off
463 $i18n = CRM_Core_I18n::singleton();
464
353ffa53 465 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
29c4b4bf
WA
466 $url = CRM_Utils_Array::value('url', $value['attributes']);
467 $permission = CRM_Utils_Array::value('permission', $value['attributes']);
468 $operator = CRM_Utils_Array::value('operator', $value['attributes']);
469 $parentID = CRM_Utils_Array::value('parentID', $value['attributes']);
470 $navID = CRM_Utils_Array::value('navID', $value['attributes']);
471 $active = CRM_Utils_Array::value('active', $value['attributes']);
472 $menuName = CRM_Utils_Array::value('name', $value['attributes']);
353ffa53 473 $target = CRM_Utils_Array::value('target', $value['attributes']);
6a488035
TO
474
475 if (in_array($parentID, $skipMenuItems) || !$active) {
476 $skipMenuItems[] = $navID;
477 return FALSE;
478 }
479
480 //we need to check core view/edit or supported acls.
481 if (in_array($menuName, array(
353ffa53 482 'Search...',
acb1052e 483 'Contacts',
353ffa53 484 ))) {
6a488035
TO
485 if (!CRM_Core_Permission::giveMeAllACLs()) {
486 $skipMenuItems[] = $navID;
487 return FALSE;
488 }
489 }
490
491 $config = CRM_Core_Config::singleton();
492
493 $makeLink = FALSE;
494 if (isset($url) && $url) {
8ce923d1 495 if (substr($url, 0, 4) !== 'http') {
6a488035
TO
496 //CRM-7656 --make sure to separate out url path from url params,
497 //as we'r going to validate url path across cross-site scripting.
710199c8 498 $urlParam = explode('?', $url);
499 if (empty($urlParam[1])) {
500 $urlParam[1] = NULL;
501 }
1351950a 502 $url = CRM_Utils_System::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
6a488035 503 }
f39c14c6
CW
504 elseif (strpos($url, '&amp;') === FALSE) {
505 $url = htmlspecialchars($url);
506 }
6a488035
TO
507 $makeLink = TRUE;
508 }
509
510 static $allComponents;
511 if (!$allComponents) {
512 $allComponents = CRM_Core_Component::getNames();
513 }
514
515 if (isset($permission) && $permission) {
516 $permissions = explode(',', $permission);
517
518 $hasPermission = FALSE;
519 foreach ($permissions as $key) {
520 $key = trim($key);
521 $showItem = TRUE;
522
523 //get the component name from permission.
524 $componentName = CRM_Core_Permission::getComponentName($key);
525
526 if ($componentName) {
527 if (!in_array($componentName, $config->enableComponents) ||
528 !CRM_Core_Permission::check($key)
529 ) {
530 $showItem = FALSE;
531 if ($operator == 'AND') {
532 $skipMenuItems[] = $navID;
533 return $showItem;
534 }
535 }
536 else {
537 $hasPermission = TRUE;
538 }
539 }
540 elseif (!CRM_Core_Permission::check($key)) {
541 $showItem = FALSE;
542 if ($operator == 'AND') {
543 $skipMenuItems[] = $navID;
544 return $showItem;
545 }
546 }
547 else {
548 $hasPermission = TRUE;
549 }
550 }
551
552 if (!$showItem && !$hasPermission) {
553 $skipMenuItems[] = $navID;
554 return FALSE;
555 }
556 }
557
558 if ($makeLink) {
202407d7 559 $url = CRM_Utils_System::evalUrl($url);
6a488035
TO
560 if ($target) {
561 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
562 }
563 else {
564 $name = "<a href=\"{$url}\">{$name}</a>";
565 }
566 }
567
568 return $name;
569 }
570
571 /**
fe482240 572 * Create navigation for CiviCRM Admin Menu.
6a488035 573 *
6a0b768e
TO
574 * @param int $contactID
575 * Contact id.
6a488035 576 *
a6c01b45
CW
577 * @return string
578 * returns navigation html
6a488035 579 */
00be9182 580 public static function createNavigation($contactID) {
6a488035
TO
581 $config = CRM_Core_Config::singleton();
582
73538697 583 $navigation = self::buildNavigation();
6a488035 584
73538697 585 if ($navigation) {
6a488035
TO
586
587 //add additional navigation items
588 $logoutURL = CRM_Utils_System::url('civicrm/logout', 'reset=1');
6a488035
TO
589
590 // get home menu from db
591 $homeParams = array('name' => 'Home');
592 $homeNav = array();
a2e1885c 593 $homeIcon = '<span class="crm-logo-sm" ></span>';
6a488035
TO
594 self::retrieve($homeParams, $homeNav);
595 if ($homeNav) {
710199c8 596 list($path, $q) = explode('?', $homeNav['url']);
6a488035
TO
597 $homeURL = CRM_Utils_System::url($path, $q);
598 $homeLabel = $homeNav['label'];
599 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
600 if ($homeLabel == 'Home') {
a65693e5 601 $homeLabel = ts('CiviCRM Home');
6a488035
TO
602 }
603 }
604 else {
605 $homeURL = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
a65693e5 606 $homeLabel = ts('CiviCRM Home');
6a488035 607 }
8960d9b9 608 // Link to hide the menubar
8b571e4c 609 $hideLabel = ts('Hide Menu');
6a488035 610
8960d9b9
CW
611 $prepandString = "
612 <li class='menumain crm-link-home'>$homeIcon
613 <ul id='civicrm-home'>
614 <li><a href='$homeURL'>$homeLabel</a></li>
615 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
86bfa4f6 616 <li><a href='$logoutURL' class='crm-logout-link'>" . ts('Log out') . "</a></li>
8960d9b9
CW
617 </ul>";
618 // <li> tag doesn't need to be closed
73538697 619 }
8960d9b9 620 return $prepandString . $navigation;
73538697 621 }
6a488035 622
73538697 623 /**
fe482240 624 * Reset navigation for all contacts or a specified contact.
73538697 625 *
6a0b768e
TO
626 * @param int $contactID
627 * Reset only entries belonging to that contact ID.
ffbff132 628 *
73538697
CW
629 * @return string
630 */
00be9182 631 public static function resetNavigation($contactID = NULL) {
73538697
CW
632 $newKey = CRM_Utils_String::createRandom(self::CACHE_KEY_STRLEN, CRM_Utils_String::ALPHANUMERIC);
633 if (!$contactID) {
634 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
635 CRM_Core_DAO::executeQuery($query);
636 CRM_Core_BAO_Cache::deleteGroup('navigation');
637 }
638 else {
6a488035 639 // before inserting check if contact id exists in db
73538697 640 // this is to handle weird case when contact id is in session but not in db
6a488035
TO
641 $contact = new CRM_Contact_DAO_Contact();
642 $contact->id = $contactID;
643 if ($contact->find(TRUE)) {
644 CRM_Core_BAO_Setting::setItem(
73538697 645 $newKey,
6a488035
TO
646 CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME,
647 'navigation',
648 NULL,
649 $contactID,
650 $contactID
651 );
652 }
653 }
73538697
CW
654
655 return $newKey;
6a488035
TO
656 }
657
658 /**
fe482240 659 * Process navigation.
6a488035 660 *
6a0b768e
TO
661 * @param array $params
662 * Associated array, $_GET.
6a488035 663 */
00be9182 664 public static function processNavigation(&$params) {
353ffa53
TO
665 $nodeID = (int) str_replace("node_", "", $params['id']);
666 $referenceID = (int) str_replace("node_", "", $params['ref_id']);
667 $position = $params['ps'];
668 $type = $params['type'];
669 $label = CRM_Utils_Array::value('data', $params);
6a488035
TO
670
671 switch ($type) {
672 case "move":
673 self::processMove($nodeID, $referenceID, $position);
674 break;
675
676 case "rename":
677 self::processRename($nodeID, $label);
678 break;
679
680 case "delete":
681 self::processDelete($nodeID);
682 break;
683 }
684
685 //reset navigation menus
686 self::resetNavigation();
687 CRM_Utils_System::civiExit();
688 }
689
690 /**
fe482240 691 * Process move action.
6a488035 692 *
6a0b768e
TO
693 * @param $nodeID
694 * Node that is being moved.
695 * @param $referenceID
696 * Parent id where node is moved. 0 mean no parent.
697 * @param $position
698 * New position of the nod, it starts with 0 - n.
6a488035 699 */
00be9182 700 public static function processMove($nodeID, $referenceID, $position) {
6a488035
TO
701 // based on the new position we need to get the weight of the node after moved node
702 // 1. update the weight of $position + 1 nodes to weight + 1
703 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
704
705 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
706 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
707 // accordingly set the new parent_id
708 if ($referenceID) {
709 $newParentID = $referenceID;
710 $parentClause = "parent_id = {$referenceID} ";
711 }
712 else {
713 $newParentID = 'NULL';
714 $parentClause = 'parent_id IS NULL';
715 }
716
4eeb9a5b 717 $incrementOtherNodes = TRUE;
353ffa53 718 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
481a74f4 719 $params = array(1 => array($position, 'Positive'));
6a488035
TO
720 $newWeight = CRM_Core_DAO::singleValueQuery($sql, $params);
721
722 // this means node is moved to last position, so you need to get the weight of last element + 1
723 if (!$newWeight) {
7cc5305f
CW
724 // If this is not the first item being added to a parent
725 if ($position) {
726 $lastPosition = $position - 1;
727 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
728 $params = array(1 => array($lastPosition, 'Positive'));
729 $newWeight = CRM_Core_DAO::singleValueQuery($sql, $params);
730
731 // since last node increment + 1
732 $newWeight = $newWeight + 1;
733 }
734 else {
735 $newWeight = '0';
736 }
6a488035
TO
737
738 // since this is a last node we don't need to increment other nodes
ab8a593e 739 $incrementOtherNodes = FALSE;
6a488035
TO
740 }
741
742 $transaction = new CRM_Core_Transaction();
743
744 // now update the existing nodes to weight + 1, if required.
481a74f4 745 if ($incrementOtherNodes) {
6a488035
TO
746 $query = "UPDATE civicrm_navigation SET weight = weight + 1
747 WHERE {$parentClause} AND weight >= {$newWeight}";
748
749 CRM_Core_DAO::executeQuery($query);
750 }
751
752 // finally set the weight of current node
753 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
754 CRM_Core_DAO::executeQuery($query);
755
756 $transaction->commit();
757 }
758
759 /**
ffbff132 760 * Function to process rename action for tree.
6a488035 761 *
100fef9d 762 * @param int $nodeID
6a488035
TO
763 * @param $label
764 */
00be9182 765 public static function processRename($nodeID, $label) {
6a488035
TO
766 CRM_Core_DAO::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
767 }
768
769 /**
fe482240 770 * Process delete action for tree.
6a488035 771 *
100fef9d 772 * @param int $nodeID
6a488035 773 */
00be9182 774 public static function processDelete($nodeID) {
6a488035
TO
775 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
776 CRM_Core_DAO::executeQuery($query);
777 }
778
6a488035 779 /**
fe482240 780 * Update menu.
6a488035 781 *
6a0b768e
TO
782 * @param array $params
783 * @param array $newParams
784 * New value of params.
6a488035 785 */
00be9182 786 public static function processUpdate($params, $newParams) {
6a488035
TO
787 $dao = new CRM_Core_DAO_Navigation();
788 $dao->copyValues($params);
789 if ($dao->find(TRUE)) {
790 $dao->copyValues($newParams);
791 $dao->save();
792 }
793 }
73538697 794
31cb1898
AN
795 /**
796 * Rebuild reports menu.
797 *
798 * All Contact reports will become sub-items of 'Contact Reports' and so on.
799 *
800 * @param int $domain_id
801 */
802 public static function rebuildReportsNavigation($domain_id) {
803 $component_to_nav_name = array(
804 'CiviContact' => 'Contact Reports',
805 'CiviContribute' => 'Contribution Reports',
806 'CiviMember' => 'Membership Reports',
807 'CiviEvent' => 'Event Reports',
808 'CiviPledge' => 'Pledge Reports',
809 'CiviGrant' => 'Grant Reports',
810 'CiviMail' => 'Mailing Reports',
811 'CiviCampaign' => 'Campaign Reports',
812 );
813
814 // Create or update the top level Reports link.
815 $reports_nav = self::createOrUpdateTopLevelReportsNavItem($domain_id);
816
817 // Get all active report instances grouped by component.
818 $components = self::getAllActiveReportsByComponent($domain_id);
819 foreach ($components as $component_id => $component) {
820 // Create or update the per component reports links.
821 $component_nav_name = $component['name'];
822 if (isset($component_to_nav_name[$component_nav_name])) {
823 $component_nav_name = $component_to_nav_name[$component_nav_name];
824 }
825 $permission = "access {$component['name']}";
826 if ($component['name'] === 'CiviContact') {
827 $permission = "administer CiviCRM";
828 }
829 elseif ($component['name'] === 'CiviCampaign') {
830 $permission = "access CiviReport";
831 }
0087242f 832 $component_nav = self::createOrUpdateReportNavItem($component_nav_name, 'civicrm/report/list',
833 "compid={$component_id}&reset=1", $reports_nav->id, $permission, $domain_id, TRUE);
31cb1898
AN
834 foreach ($component['reports'] as $report_id => $report) {
835 // Create or update the report instance links.
51704c4d 836 $report_nav = self::createOrUpdateReportNavItem($report['title'], $report['url'], 'reset=1', $component_nav->id, $report['permission'], $domain_id, FALSE, TRUE);
31cb1898
AN
837 // Update the report instance to include the navigation id.
838 $query = "UPDATE civicrm_report_instance SET navigation_id = %1 WHERE id = %2";
839 $params = array(
840 1 => array($report_nav->id, 'Integer'),
841 2 => array($report_id, 'Integer'),
842 );
843 CRM_Core_DAO::executeQuery($query, $params);
844 }
845 }
846
847 // Create or update the All Reports link.
dfbeefd8 848 self::createOrUpdateReportNavItem('All Reports', 'civicrm/report/list', 'reset=1', $reports_nav->id, 'access CiviReport', $domain_id, TRUE);
e24131b6 849 // Create or update the My Reports link.
850 self::createOrUpdateReportNavItem('My Reports', 'civicrm/report/list', 'myreports=1&reset=1', $reports_nav->id, 'access CiviReport', $domain_id, TRUE);
851
31cb1898
AN
852 }
853
854 /**
855 * Create the top level 'Reports' item in the navigation tree.
856 *
857 * @param int $domain_id
858 *
859 * @return bool|\CRM_Core_DAO
860 */
861 static public function createOrUpdateTopLevelReportsNavItem($domain_id) {
862 $id = NULL;
863
864 $dao = new CRM_Core_BAO_Navigation();
865 $dao->name = 'Reports';
866 $dao->domain_id = $domain_id;
867 // The first selectAdd clears it - so that we only retrieve the one field.
868 $dao->selectAdd();
869 $dao->selectAdd('id');
870 if ($dao->find(TRUE)) {
871 $id = $dao->id;
872 }
873
874 $nav = self::createReportNavItem('Reports', NULL, NULL, NULL, 'access CiviReport', $id, $domain_id);
875 return $nav;
876 }
877
878 /**
879 * Retrieve a navigation item using it's url.
880 *
51704c4d 881 * Note that we use LIKE to permit a wildcard as the calling code likely doesn't
882 * care about output params appended.
883 *
31cb1898
AN
884 * @param string $url
885 * @param array $url_params
886 *
0087242f 887 * @param int|null $parent_id
888 * Optionally restrict to one parent.
889 *
890 * @return bool|\CRM_Core_BAO_Navigation
31cb1898 891 */
0087242f 892 public static function getNavItemByUrl($url, $url_params, $parent_id = NULL) {
893 $nav = new CRM_Core_BAO_Navigation();
0087242f 894 $nav->parent_id = $parent_id;
51704c4d 895 $nav->whereAdd("url LIKE '{$url}?{$url_params}'");
896
0087242f 897 if ($nav->find(TRUE)) {
898 return $nav;
31cb1898
AN
899 }
900 return FALSE;
901 }
902
903 /**
904 * Get all active reports, organised by component.
905 *
906 * @param int $domain_id
907 *
908 * @return array
909 */
910 public static function getAllActiveReportsByComponent($domain_id) {
911 $sql = "
912 SELECT
913 civicrm_report_instance.id, civicrm_report_instance.title, civicrm_report_instance.permission, civicrm_component.name, civicrm_component.id AS component_id
914 FROM
915 civicrm_option_group
916 LEFT JOIN
917 civicrm_option_value ON civicrm_option_value.option_group_id = civicrm_option_group.id AND civicrm_option_group.name = 'report_template'
918 LEFT JOIN
919 civicrm_report_instance ON civicrm_option_value.value = civicrm_report_instance.report_id
920 LEFT JOIN
921 civicrm_component ON civicrm_option_value.component_id = civicrm_component.id
922 WHERE
923 civicrm_option_value.is_active = 1
924 AND
925 civicrm_report_instance.domain_id = %1
926 ORDER BY civicrm_option_value.weight";
927
928 $dao = CRM_Core_DAO::executeQuery($sql, array(
929 1 => array($domain_id, 'Integer'),
930 ));
931 $rows = array();
932 while ($dao->fetch()) {
933 $component_name = is_null($dao->name) ? 'CiviContact' : $dao->name;
934 $component_id = is_null($dao->component_id) ? 99 : $dao->component_id;
935 $rows[$component_id]['name'] = $component_name;
936 $rows[$component_id]['reports'][$dao->id] = array(
937 'title' => $dao->title,
938 'url' => "civicrm/report/instance/{$dao->id}",
939 'permission' => $dao->permission,
940 );
941 }
942 return $rows;
943 }
944
945 /**
946 * Create or update a navigation item for a report instance.
947 *
948 * The function will check whether create or update is required.
949 *
950 * @param string $name
951 * @param string $url
952 * @param string $url_params
953 * @param int $parent_id
954 * @param string $permission
955 * @param int $domain_id
956 *
0087242f 957 * @param bool $onlyMatchParentID
958 * If True then do not match with a url that has a different parent
959 * (This is because for top level items there is a risk of 'stealing' rows that normally
960 * live under 'Contact' and intentionally duplicate the report examples.)
961 *
31cb1898
AN
962 * @return \CRM_Core_DAO_Navigation
963 */
0087242f 964 protected static function createOrUpdateReportNavItem($name, $url, $url_params, $parent_id, $permission,
51704c4d 965 $domain_id, $onlyMatchParentID = FALSE, $useWildcard = TRUE) {
31cb1898 966 $id = NULL;
51704c4d 967 $existing_url_params = $useWildcard ? $url_params . '%' : $url_params;
968 $existing_nav = CRM_Core_BAO_Navigation::getNavItemByUrl($url, $existing_url_params, ($onlyMatchParentID ? $parent_id : NULL));
31cb1898
AN
969 if ($existing_nav) {
970 $id = $existing_nav->id;
971 }
0087242f 972
31cb1898
AN
973 $nav = self::createReportNavItem($name, $url, $url_params, $parent_id, $permission, $id, $domain_id);
974 return $nav;
975 }
976
977 /**
978 * Create a navigation item for a report instance.
979 *
980 * @param string $name
981 * @param string $url
982 * @param string $url_params
983 * @param int $parent_id
984 * @param string $permission
985 * @param int $id
986 * @param int $domain_id
987 * ID of domain to create item in.
988 *
989 * @return \CRM_Core_DAO_Navigation
990 */
991 public static function createReportNavItem($name, $url, $url_params, $parent_id, $permission, $id, $domain_id) {
992 if ($url !== NULL) {
993 $url = "{$url}?{$url_params}";
994 }
995 $params = array(
996 'name' => $name,
997 'label' => ts($name),
998 'url' => $url,
999 'parent_id' => $parent_id,
1000 'is_active' => TRUE,
1001 'permission' => array(
1002 $permission,
1003 ),
1004 'domain_id' => $domain_id,
1005 );
0087242f 1006 if ($id) {
31cb1898
AN
1007 $params['id'] = $id;
1008 }
0087242f 1009 return CRM_Core_BAO_Navigation::add($params);
31cb1898
AN
1010 }
1011
b5c2afd0 1012 /**
ffbff132
EM
1013 * Get cache key.
1014 *
100fef9d 1015 * @param int $cid
b5c2afd0
EM
1016 *
1017 * @return object|string
1018 */
00be9182 1019 public static function getCacheKey($cid) {
aaffa79f 1020 $key = Civi::service('settings_manager')
1021 ->getBagByContact(NULL, $cid)
1022 ->get('navigation');
73538697
CW
1023 if (strlen($key) !== self::CACHE_KEY_STRLEN) {
1024 $key = self::resetNavigation($cid);
1025 }
1026 return $key;
1027 }
96025800 1028
6a488035 1029}