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