Merge pull request #10464 from kryptothesuperdog/CRM-20679
[civicrm-core.git] / CRM / Core / BAO / Navigation.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2017
32 */
33 class CRM_Core_BAO_Navigation extends CRM_Core_DAO_Navigation {
34
35 // Number of characters in the menu js cache key
36 const CACHE_KEY_STRLEN = 8;
37
38 /**
39 * Class constructor.
40 */
41 public function __construct() {
42 parent::__construct();
43 }
44
45 /**
46 * Update the is_active flag in the db.
47 *
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.
52 *
53 * @return CRM_Core_DAO_Navigation|NULL
54 * DAO object on success, NULL otherwise
55 */
56 public static function setIsActive($id, $is_active) {
57 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_Navigation', $id, 'is_active', $is_active);
58 }
59
60 /**
61 * Get existing / build navigation for CiviCRM Admin Menu.
62 *
63 * @return array
64 * associated array
65 */
66 public static function getMenus() {
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 /**
82 * Add/update navigation record.
83 *
84 * @param array $params Submitted values
85 *
86 * @return CRM_Core_DAO_Navigation
87 * navigation object
88 */
89 public static function add(&$params) {
90 $navigation = new CRM_Core_DAO_Navigation();
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 }
95
96 if (!isset($params['id']) ||
97 (CRM_Utils_Array::value('parent_id', $params) != CRM_Utils_Array::value('current_parent_id', $params))
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 }
104 elseif ($navLabel = CRM_Utils_Array::value('label', $params)) {
105 $params['name'] = $navLabel;
106 }
107
108 $params['weight'] = self::calculateWeight(CRM_Utils_Array::value('parent_id', $params));
109 }
110
111 if (array_key_exists('permission', $params) && is_array($params['permission'])) {
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 /**
124 * Fetch object based on array of properties.
125 *
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.
130 *
131 * @return CRM_Core_BAO_Navigation|null
132 * object on success, NULL otherwise
133 */
134 public static function retrieve(&$params, &$defaults) {
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 /**
148 * Calculate navigation weight.
149 *
150 * @param int $parentID
151 * Parent_id of a menu.
152 * @param int $menuID
153 * Menu id.
154 *
155 * @return int
156 * $weight string
157 */
158 public static function calculateWeight($parentID = NULL, $menuID = NULL) {
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 /**
178 * Get formatted menu list.
179 *
180 * @return array
181 * returns associated array
182 */
183 public static function getNavigationList() {
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 = "
195 SELECT id, label, parent_id, weight, is_active, name
196 FROM 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 /**
217 * Helper function for getNavigationList().
218 *
219 * @param array $list
220 * Menu info.
221 * @param array $navigations
222 * Navigation menus.
223 * @param string $separator
224 * Menu separator.
225 */
226 public static function _getNavigationLabel($list, &$navigations, $separator = '') {
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 /**
241 * Helper function for getNavigationList().
242 *
243 * @param string $val
244 * Menu name.
245 * @param array $pidGroups
246 * Parent menus.
247 *
248 * @return array
249 */
250 public static function _getNavigationValue($val, &$pidGroups) {
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 /**
265 * Build navigation tree.
266 *
267 * @return array
268 * nested array of menus
269 */
270 public static function buildNavigationTree() {
271 $domainID = CRM_Core_Config::domainID();
272 $navigationTree = array();
273
274 // get the list of menus
275 $query = "
276 SELECT id, label, url, permission, permission_operator, has_separator, parent_id, is_active, name
277 FROM civicrm_navigation
278 WHERE domain_id = $domainID
279 ORDER BY parent_id, weight";
280
281 $navigation = CRM_Core_DAO::executeQuery($query);
282 while ($navigation->fetch()) {
283 $navigationTree[$navigation->id] = array(
284 'attributes' => array(
285 'label' => $navigation->label,
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,
294 ),
295 );
296 }
297
298 return self::buildTree($navigationTree);
299 }
300
301 /**
302 * Convert flat array to nested.
303 *
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.
327 *
328 * @return string
329 */
330 public static function buildNavigation() {
331 $navigations = self::buildNavigationTree();
332 $navigationString = '';
333
334 // run the Navigation through a hook so users can modify it
335 CRM_Utils_Hook::navigationMenu($navigations);
336 self::fixNavigationMenu($navigations);
337
338 //skip children menu item if user don't have access to parent menu item
339 $skipMenuItems = array();
340 foreach ($navigations as $key => $value) {
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>';
348 }
349 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
350 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
351 }
352 }
353 self::recurseNavigation($value, $navigationString, $skipMenuItems);
354 }
355
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);
359
360 return $navigationString;
361 }
362
363 /**
364 * Recursively check child menus.
365 *
366 * @param array $value
367 * @param string $navigationString
368 * @param array $skipMenuItems
369 *
370 * @return string
371 */
372 public static function recurseNavigation(&$value, &$navigationString, $skipMenuItems) {
373 if (!empty($value['child'])) {
374 $navigationString .= '<ul>';
375 }
376 else {
377 $navigationString .= '</li>';
378 //locate separator after
379 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
380 $navigationString .= '<li class="menu-separator"></li>';
381 }
382 }
383
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>';
391 }
392 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
393 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
394 self::recurseNavigation($val, $navigationString, $skipMenuItems);
395 }
396 }
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>';
402 }
403 }
404 return $navigationString;
405 }
406
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").
429 * @param int $maxNavID
430 * @param int $parentID
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 if ($origKey != $newKey) {
443 // If the keys are different, reset the array index to match.
444 $nodes[$newKey] = $nodes[$origKey];
445 unset($nodes[$origKey]);
446 $origKey = $newKey;
447 }
448 }
449 if (isset($nodes[$origKey]['child']) && is_array($nodes[$origKey]['child'])) {
450 self::_fixNavigationMenu($nodes[$origKey]['child'], $maxNavID, $nodes[$origKey]['attributes']['navID']);
451 }
452 }
453 }
454
455 /**
456 * Get Menu name.
457 *
458 * @param $value
459 * @param array $skipMenuItems
460 *
461 * @return bool|string
462 */
463 public static function getMenuName(&$value, &$skipMenuItems) {
464 // we need to localise the menu labels (CRM-5456) and don’t
465 // want to use ts() as it would throw the ts-extractor off
466 $i18n = CRM_Core_I18n::singleton();
467
468 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
469 $url = CRM_Utils_Array::value('url', $value['attributes']);
470 $permission = CRM_Utils_Array::value('permission', $value['attributes']);
471 $operator = CRM_Utils_Array::value('operator', $value['attributes']);
472 $parentID = CRM_Utils_Array::value('parentID', $value['attributes']);
473 $navID = CRM_Utils_Array::value('navID', $value['attributes']);
474 $active = CRM_Utils_Array::value('active', $value['attributes']);
475 $menuName = CRM_Utils_Array::value('name', $value['attributes']);
476 $target = CRM_Utils_Array::value('target', $value['attributes']);
477
478 if (in_array($parentID, $skipMenuItems) || !$active) {
479 $skipMenuItems[] = $navID;
480 return FALSE;
481 }
482
483 $config = CRM_Core_Config::singleton();
484
485 $makeLink = FALSE;
486 if (isset($url) && $url) {
487 if (substr($url, 0, 4) !== 'http') {
488 //CRM-7656 --make sure to separate out url path from url params,
489 //as we'r going to validate url path across cross-site scripting.
490 $urlParam = explode('?', $url);
491 if (empty($urlParam[1])) {
492 $urlParam[1] = NULL;
493 }
494 $url = CRM_Utils_System::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
495 }
496 elseif (strpos($url, '&amp;') === FALSE) {
497 $url = htmlspecialchars($url);
498 }
499 $makeLink = TRUE;
500 }
501
502 static $allComponents;
503 if (!$allComponents) {
504 $allComponents = CRM_Core_Component::getNames();
505 }
506
507 if (isset($permission) && $permission) {
508 $permissions = explode(',', $permission);
509
510 $hasPermission = FALSE;
511 foreach ($permissions as $key) {
512 $key = trim($key);
513 $showItem = TRUE;
514
515 //get the component name from permission.
516 $componentName = CRM_Core_Permission::getComponentName($key);
517
518 if ($componentName) {
519 if (!in_array($componentName, $config->enableComponents) ||
520 !CRM_Core_Permission::check($key)
521 ) {
522 $showItem = FALSE;
523 if ($operator == 'AND') {
524 $skipMenuItems[] = $navID;
525 return $showItem;
526 }
527 }
528 else {
529 $hasPermission = TRUE;
530 }
531 }
532 elseif (!CRM_Core_Permission::check($key)) {
533 $showItem = FALSE;
534 if ($operator == 'AND') {
535 $skipMenuItems[] = $navID;
536 return $showItem;
537 }
538 }
539 else {
540 $hasPermission = TRUE;
541 }
542 }
543
544 if (!$showItem && !$hasPermission) {
545 $skipMenuItems[] = $navID;
546 return FALSE;
547 }
548 }
549
550 if ($makeLink) {
551 $url = CRM_Utils_System::evalUrl($url);
552 if ($target) {
553 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
554 }
555 else {
556 $name = "<a href=\"{$url}\">{$name}</a>";
557 }
558 }
559
560 return $name;
561 }
562
563 /**
564 * Create navigation for CiviCRM Admin Menu.
565 *
566 * @param int $contactID
567 * Contact id.
568 *
569 * @return string
570 * returns navigation html
571 */
572 public static function createNavigation($contactID) {
573 $config = CRM_Core_Config::singleton();
574
575 $navigation = self::buildNavigation();
576
577 if ($navigation) {
578
579 //add additional navigation items
580 $logoutURL = CRM_Utils_System::url('civicrm/logout', 'reset=1');
581
582 // get home menu from db
583 $homeParams = array('name' => 'Home');
584 $homeNav = array();
585 $homeIcon = '<span class="crm-logo-sm" ></span>';
586 self::retrieve($homeParams, $homeNav);
587 if ($homeNav) {
588 list($path, $q) = explode('?', $homeNav['url']);
589 $homeURL = CRM_Utils_System::url($path, $q);
590 $homeLabel = $homeNav['label'];
591 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
592 if ($homeLabel == 'Home') {
593 $homeLabel = ts('CiviCRM Home');
594 }
595 }
596 else {
597 $homeURL = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
598 $homeLabel = ts('CiviCRM Home');
599 }
600 // Link to hide the menubar
601 $hideLabel = ts('Hide Menu');
602
603 $prepandString = "
604 <li class='menumain crm-link-home'>$homeIcon
605 <ul id='civicrm-home'>
606 <li><a href='$homeURL'>$homeLabel</a></li>
607 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
608 <li><a href='$logoutURL' class='crm-logout-link'>" . ts('Log out') . "</a></li>
609 </ul>";
610 // <li> tag doesn't need to be closed
611 }
612 return $prepandString . $navigation;
613 }
614
615 /**
616 * Reset navigation for all contacts or a specified contact.
617 *
618 * @param int $contactID
619 * Reset only entries belonging to that contact ID.
620 *
621 * @return string
622 */
623 public static function resetNavigation($contactID = NULL) {
624 $newKey = CRM_Utils_String::createRandom(self::CACHE_KEY_STRLEN, CRM_Utils_String::ALPHANUMERIC);
625 if (!$contactID) {
626 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
627 CRM_Core_DAO::executeQuery($query);
628 CRM_Core_BAO_Cache::deleteGroup('navigation');
629 }
630 else {
631 // before inserting check if contact id exists in db
632 // this is to handle weird case when contact id is in session but not in db
633 $contact = new CRM_Contact_DAO_Contact();
634 $contact->id = $contactID;
635 if ($contact->find(TRUE)) {
636 CRM_Core_BAO_Setting::setItem(
637 $newKey,
638 CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME,
639 'navigation',
640 NULL,
641 $contactID,
642 $contactID
643 );
644 }
645 }
646
647 return $newKey;
648 }
649
650 /**
651 * Process navigation.
652 *
653 * @param array $params
654 * Associated array, $_GET.
655 */
656 public static function processNavigation(&$params) {
657 $nodeID = (int) str_replace("node_", "", $params['id']);
658 $referenceID = (int) str_replace("node_", "", $params['ref_id']);
659 $position = $params['ps'];
660 $type = $params['type'];
661 $label = CRM_Utils_Array::value('data', $params);
662
663 switch ($type) {
664 case "move":
665 self::processMove($nodeID, $referenceID, $position);
666 break;
667
668 case "rename":
669 self::processRename($nodeID, $label);
670 break;
671
672 case "delete":
673 self::processDelete($nodeID);
674 break;
675 }
676
677 //reset navigation menus
678 self::resetNavigation();
679 CRM_Utils_System::civiExit();
680 }
681
682 /**
683 * Process move action.
684 *
685 * @param $nodeID
686 * Node that is being moved.
687 * @param $referenceID
688 * Parent id where node is moved. 0 mean no parent.
689 * @param $position
690 * New position of the nod, it starts with 0 - n.
691 */
692 public static function processMove($nodeID, $referenceID, $position) {
693 // based on the new position we need to get the weight of the node after moved node
694 // 1. update the weight of $position + 1 nodes to weight + 1
695 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
696
697 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
698 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
699 // accordingly set the new parent_id
700 if ($referenceID) {
701 $newParentID = $referenceID;
702 $parentClause = "parent_id = {$referenceID} ";
703 }
704 else {
705 $newParentID = 'NULL';
706 $parentClause = 'parent_id IS NULL';
707 }
708
709 $incrementOtherNodes = TRUE;
710 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
711 $params = array(1 => array($position, 'Positive'));
712 $newWeight = CRM_Core_DAO::singleValueQuery($sql, $params);
713
714 // this means node is moved to last position, so you need to get the weight of last element + 1
715 if (!$newWeight) {
716 // If this is not the first item being added to a parent
717 if ($position) {
718 $lastPosition = $position - 1;
719 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
720 $params = array(1 => array($lastPosition, 'Positive'));
721 $newWeight = CRM_Core_DAO::singleValueQuery($sql, $params);
722
723 // since last node increment + 1
724 $newWeight = $newWeight + 1;
725 }
726 else {
727 $newWeight = '0';
728 }
729
730 // since this is a last node we don't need to increment other nodes
731 $incrementOtherNodes = FALSE;
732 }
733
734 $transaction = new CRM_Core_Transaction();
735
736 // now update the existing nodes to weight + 1, if required.
737 if ($incrementOtherNodes) {
738 $query = "UPDATE civicrm_navigation SET weight = weight + 1
739 WHERE {$parentClause} AND weight >= {$newWeight}";
740
741 CRM_Core_DAO::executeQuery($query);
742 }
743
744 // finally set the weight of current node
745 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
746 CRM_Core_DAO::executeQuery($query);
747
748 $transaction->commit();
749 }
750
751 /**
752 * Function to process rename action for tree.
753 *
754 * @param int $nodeID
755 * @param $label
756 */
757 public static function processRename($nodeID, $label) {
758 CRM_Core_DAO::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
759 }
760
761 /**
762 * Process delete action for tree.
763 *
764 * @param int $nodeID
765 */
766 public static function processDelete($nodeID) {
767 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
768 CRM_Core_DAO::executeQuery($query);
769 }
770
771 /**
772 * Update menu.
773 *
774 * @param array $params
775 * @param array $newParams
776 * New value of params.
777 */
778 public static function processUpdate($params, $newParams) {
779 $dao = new CRM_Core_DAO_Navigation();
780 $dao->copyValues($params);
781 if ($dao->find(TRUE)) {
782 $dao->copyValues($newParams);
783 $dao->save();
784 }
785 }
786
787 /**
788 * Rebuild reports menu.
789 *
790 * All Contact reports will become sub-items of 'Contact Reports' and so on.
791 *
792 * @param int $domain_id
793 */
794 public static function rebuildReportsNavigation($domain_id) {
795 $component_to_nav_name = array(
796 'CiviContact' => 'Contact Reports',
797 'CiviContribute' => 'Contribution Reports',
798 'CiviMember' => 'Membership Reports',
799 'CiviEvent' => 'Event Reports',
800 'CiviPledge' => 'Pledge Reports',
801 'CiviGrant' => 'Grant Reports',
802 'CiviMail' => 'Mailing Reports',
803 'CiviCampaign' => 'Campaign Reports',
804 );
805
806 // Create or update the top level Reports link.
807 $reports_nav = self::createOrUpdateTopLevelReportsNavItem($domain_id);
808
809 // Get all active report instances grouped by component.
810 $components = self::getAllActiveReportsByComponent($domain_id);
811 foreach ($components as $component_id => $component) {
812 // Create or update the per component reports links.
813 $component_nav_name = $component['name'];
814 if (isset($component_to_nav_name[$component_nav_name])) {
815 $component_nav_name = $component_to_nav_name[$component_nav_name];
816 }
817 $permission = "access {$component['name']}";
818 if ($component['name'] === 'CiviContact') {
819 $permission = "administer CiviCRM";
820 }
821 elseif ($component['name'] === 'CiviCampaign') {
822 $permission = "access CiviReport";
823 }
824 $component_nav = self::createOrUpdateReportNavItem($component_nav_name, 'civicrm/report/list',
825 "compid={$component_id}&reset=1", $reports_nav->id, $permission, $domain_id, TRUE);
826 foreach ($component['reports'] as $report_id => $report) {
827 // Create or update the report instance links.
828 $report_nav = self::createOrUpdateReportNavItem($report['title'], $report['url'], 'reset=1', $component_nav->id, $report['permission'], $domain_id, FALSE, TRUE);
829 // Update the report instance to include the navigation id.
830 $query = "UPDATE civicrm_report_instance SET navigation_id = %1 WHERE id = %2";
831 $params = array(
832 1 => array($report_nav->id, 'Integer'),
833 2 => array($report_id, 'Integer'),
834 );
835 CRM_Core_DAO::executeQuery($query, $params);
836 }
837 }
838
839 // Create or update the All Reports link.
840 self::createOrUpdateReportNavItem('All Reports', 'civicrm/report/list', 'reset=1', $reports_nav->id, 'access CiviReport', $domain_id, TRUE);
841 // Create or update the My Reports link.
842 self::createOrUpdateReportNavItem('My Reports', 'civicrm/report/list', 'myreports=1&reset=1', $reports_nav->id, 'access CiviReport', $domain_id, TRUE);
843
844 }
845
846 /**
847 * Create the top level 'Reports' item in the navigation tree.
848 *
849 * @param int $domain_id
850 *
851 * @return bool|\CRM_Core_DAO
852 */
853 static public function createOrUpdateTopLevelReportsNavItem($domain_id) {
854 $id = NULL;
855
856 $dao = new CRM_Core_BAO_Navigation();
857 $dao->name = 'Reports';
858 $dao->domain_id = $domain_id;
859 // The first selectAdd clears it - so that we only retrieve the one field.
860 $dao->selectAdd();
861 $dao->selectAdd('id');
862 if ($dao->find(TRUE)) {
863 $id = $dao->id;
864 }
865
866 $nav = self::createReportNavItem('Reports', NULL, NULL, NULL, 'access CiviReport', $id, $domain_id);
867 return $nav;
868 }
869
870 /**
871 * Retrieve a navigation item using it's url.
872 *
873 * Note that we use LIKE to permit a wildcard as the calling code likely doesn't
874 * care about output params appended.
875 *
876 * @param string $url
877 * @param array $url_params
878 *
879 * @param int|null $parent_id
880 * Optionally restrict to one parent.
881 *
882 * @return bool|\CRM_Core_BAO_Navigation
883 */
884 public static function getNavItemByUrl($url, $url_params, $parent_id = NULL) {
885 $nav = new CRM_Core_BAO_Navigation();
886 $nav->parent_id = $parent_id;
887 $nav->whereAdd("url LIKE '{$url}?{$url_params}'");
888
889 if ($nav->find(TRUE)) {
890 return $nav;
891 }
892 return FALSE;
893 }
894
895 /**
896 * Get all active reports, organised by component.
897 *
898 * @param int $domain_id
899 *
900 * @return array
901 */
902 public static function getAllActiveReportsByComponent($domain_id) {
903 $sql = "
904 SELECT
905 civicrm_report_instance.id, civicrm_report_instance.title, civicrm_report_instance.permission, civicrm_component.name, civicrm_component.id AS component_id
906 FROM
907 civicrm_option_group
908 LEFT JOIN
909 civicrm_option_value ON civicrm_option_value.option_group_id = civicrm_option_group.id AND civicrm_option_group.name = 'report_template'
910 LEFT JOIN
911 civicrm_report_instance ON civicrm_option_value.value = civicrm_report_instance.report_id
912 LEFT JOIN
913 civicrm_component ON civicrm_option_value.component_id = civicrm_component.id
914 WHERE
915 civicrm_option_value.is_active = 1
916 AND
917 civicrm_report_instance.domain_id = %1
918 ORDER BY civicrm_option_value.weight";
919
920 $dao = CRM_Core_DAO::executeQuery($sql, array(
921 1 => array($domain_id, 'Integer'),
922 ));
923 $rows = array();
924 while ($dao->fetch()) {
925 $component_name = is_null($dao->name) ? 'CiviContact' : $dao->name;
926 $component_id = is_null($dao->component_id) ? 99 : $dao->component_id;
927 $rows[$component_id]['name'] = $component_name;
928 $rows[$component_id]['reports'][$dao->id] = array(
929 'title' => $dao->title,
930 'url' => "civicrm/report/instance/{$dao->id}",
931 'permission' => $dao->permission,
932 );
933 }
934 return $rows;
935 }
936
937 /**
938 * Create or update a navigation item for a report instance.
939 *
940 * The function will check whether create or update is required.
941 *
942 * @param string $name
943 * @param string $url
944 * @param string $url_params
945 * @param int $parent_id
946 * @param string $permission
947 * @param int $domain_id
948 *
949 * @param bool $onlyMatchParentID
950 * If True then do not match with a url that has a different parent
951 * (This is because for top level items there is a risk of 'stealing' rows that normally
952 * live under 'Contact' and intentionally duplicate the report examples.)
953 *
954 * @return \CRM_Core_DAO_Navigation
955 */
956 protected static function createOrUpdateReportNavItem($name, $url, $url_params, $parent_id, $permission,
957 $domain_id, $onlyMatchParentID = FALSE, $useWildcard = TRUE) {
958 $id = NULL;
959 $existing_url_params = $useWildcard ? $url_params . '%' : $url_params;
960 $existing_nav = CRM_Core_BAO_Navigation::getNavItemByUrl($url, $existing_url_params, ($onlyMatchParentID ? $parent_id : NULL));
961 if ($existing_nav) {
962 $id = $existing_nav->id;
963 }
964
965 $nav = self::createReportNavItem($name, $url, $url_params, $parent_id, $permission, $id, $domain_id);
966 return $nav;
967 }
968
969 /**
970 * Create a navigation item for a report instance.
971 *
972 * @param string $name
973 * @param string $url
974 * @param string $url_params
975 * @param int $parent_id
976 * @param string $permission
977 * @param int $id
978 * @param int $domain_id
979 * ID of domain to create item in.
980 *
981 * @return \CRM_Core_DAO_Navigation
982 */
983 public static function createReportNavItem($name, $url, $url_params, $parent_id, $permission, $id, $domain_id) {
984 if ($url !== NULL) {
985 $url = "{$url}?{$url_params}";
986 }
987 $params = array(
988 'name' => $name,
989 'label' => ts($name),
990 'url' => $url,
991 'parent_id' => $parent_id,
992 'is_active' => TRUE,
993 'permission' => array(
994 $permission,
995 ),
996 'domain_id' => $domain_id,
997 );
998 if ($id) {
999 $params['id'] = $id;
1000 }
1001 return CRM_Core_BAO_Navigation::add($params);
1002 }
1003
1004 /**
1005 * Get cache key.
1006 *
1007 * @param int $cid
1008 *
1009 * @return object|string
1010 */
1011 public static function getCacheKey($cid) {
1012 $key = Civi::service('settings_manager')
1013 ->getBagByContact(NULL, $cid)
1014 ->get('navigation');
1015 if (strlen($key) !== self::CACHE_KEY_STRLEN) {
1016 $key = self::resetNavigation($cid);
1017 }
1018 return $key;
1019 }
1020
1021 }