Merge pull request #4772 from jitendrapurohit/CRM-15750
[civicrm-core.git] / CRM / Core / BAO / Navigation.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35 class CRM_Core_BAO_Navigation extends CRM_Core_DAO_Navigation {
36
37 // Number of characters in the menu js cache key
38 const CACHE_KEY_STRLEN = 8;
39
40 /**
41 * Class constructor
42 */
43 function __construct() {
44 parent::__construct();
45 }
46
47 /**
48 * Update the is_active flag in the db
49 *
50 * @param int $id id of the database record
51 * @param boolean $is_active value we want to set the is_active field
52 *
53 * @return Object DAO object on sucess, null otherwise
54 *
55 * @access public
56 * @static
57 */
58 static function setIsActive($id, $is_active) {
59 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_Navigation', $id, 'is_active', $is_active);
60 }
61
62 /**
63 * Get existing / build navigation for CiviCRM Admin Menu
64 *
65 * @static
66 * @return array associated array
67 */
68 static function getMenus() {
69 $menus = array();
70
71 $menu = new CRM_Core_DAO_Menu();
72 $menu->domain_id = CRM_Core_Config::domainID();
73 $menu->find();
74
75 while ($menu->fetch()) {
76 if ($menu->title) {
77 $menus[$menu->path] = $menu->title;
78 }
79 }
80 return $menus;
81 }
82
83 /**
84 * Add/update navigation record
85 *
86 * @param array associated array of submitted values
87 *
88 * @return object navigation object
89 * @static
90 */
91 static function add(&$params) {
92 $navigation = new CRM_Core_DAO_Navigation();
93
94 $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
95 $params['has_separator'] = CRM_Utils_Array::value('has_separator', $params, FALSE);
96
97 if (!isset($params['id']) ||
98 (CRM_Utils_Array::value( 'parent_id', $params ) != CRM_Utils_Array::value('current_parent_id', $params))
99 ) {
100 /* re/calculate the weight, if the Parent ID changed OR create new menu */
101
102 if ($navName = CRM_Utils_Array::value('name', $params)) {
103 $params['name'] = $navName;
104 }
105 elseif ($navLabel = CRM_Utils_Array::value('label', $params)) {
106 $params['name'] = $navLabel;
107 }
108
109 $params['weight'] = self::calculateWeight(CRM_Utils_Array::value('parent_id', $params));
110 }
111
112 if (array_key_exists('permission', $params) && is_array($params['permission'])) {
113 $params['permission'] = implode(',', $params['permission']);
114 }
115
116 $navigation->copyValues($params);
117
118 $navigation->domain_id = CRM_Core_Config::domainID();
119
120 $navigation->save();
121 return $navigation;
122 }
123
124 /**
125 * Fetch object based on array of properties
126 *
127 * @param array $params (reference ) an assoc array of name/value pairs
128 * @param array $defaults (reference ) an assoc array to hold the flattened values
129 *
130 * @return CRM_Core_BAO_Navigation object on success, null otherwise
131 * @access public
132 * @static
133 */
134 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 $parentID parent_id of a menu
151 * @param $menuID menu id
152 *
153 * @return int $weight string@static
154 */
155 static function calculateWeight($parentID = NULL, $menuID = NULL) {
156 $domainID = CRM_Core_Config::domainID();
157
158 $weight = 1;
159 // we reset weight for each parent, i.e we start from 1 to n
160 // calculate max weight for top level menus, if parent id is absent
161 if (!$parentID) {
162 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id IS NULL AND domain_id = $domainID";
163 }
164 else {
165 // if parent is passed, we need to get max weight for that particular parent
166 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id = {$parentID} AND domain_id = $domainID";
167 }
168
169 $dao = CRM_Core_DAO::executeQuery($query);
170 $dao->fetch();
171 return $weight = $weight + $dao->weight;
172 }
173
174 /**
175 * Get formatted menu list
176 *
177 * @return array $navigations returns associated array
178 * @static
179 */
180 static function getNavigationList() {
181 $cacheKeyString = "navigationList";
182 $whereClause = '';
183
184 $config = CRM_Core_Config::singleton();
185
186 // check if we can retrieve from database cache
187 $navigations = CRM_Core_BAO_Cache::getItem('navigation', $cacheKeyString);
188
189 if (!$navigations) {
190 $domainID = CRM_Core_Config::domainID();
191 $query = "
192 SELECT id, label, parent_id, weight, is_active, name
193 FROM civicrm_navigation WHERE domain_id = $domainID {$whereClause} ORDER BY parent_id, weight ASC";
194 $result = CRM_Core_DAO::executeQuery($query);
195
196 $pidGroups = array();
197 while ($result->fetch()) {
198 $pidGroups[$result->parent_id][$result->label] = $result->id;
199 }
200
201 foreach ($pidGroups[''] as $label => $val) {
202 $pidGroups[''][$label] = self::_getNavigationValue($val, $pidGroups);
203 }
204
205 $navigations = array();
206 self::_getNavigationLabel($pidGroups[''], $navigations);
207
208 CRM_Core_BAO_Cache::setItem($navigations, 'navigation', $cacheKeyString);
209 }
210 return $navigations;
211 }
212
213 /**
214 * Helper function for getNavigationList( )
215 *
216 * @param array $list menu info
217 * @param array $navigations navigation menus
218 * @param string $separator menu separator
219 */
220 static function _getNavigationLabel($list, &$navigations, $separator = '') {
221 $i18n = CRM_Core_I18n::singleton();
222 foreach ($list as $label => $val) {
223 if ($label == 'navigation_id') {
224 continue;
225 }
226 $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
227 $navigations[is_array($val) ? $val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
228 if (is_array($val)) {
229 self::_getNavigationLabel($val, $navigations, $separator . '&nbsp;&nbsp;&nbsp;&nbsp;');
230 }
231 }
232 }
233
234 /**
235 * Helper function for getNavigationList( )
236 *
237 * @param string $val menu name
238 * @param array $pidGroups parent menus
239 * @return array
240 */
241 static function _getNavigationValue($val, &$pidGroups) {
242 if (array_key_exists($val, $pidGroups)) {
243 $list = array('navigation_id' => $val);
244 foreach ($pidGroups[$val] as $label => $id) {
245 $list[$label] = self::_getNavigationValue($id, $pidGroups);
246 }
247 unset($pidGroups[$val]);
248 return $list;
249 }
250 else {
251 return $val;
252 }
253 }
254
255 /**
256 * Build navigation tree
257 *
258 * @param array $navigationTree nested array of menus
259 * @param int $parentID parent id
260 * @param boolean $navigationMenu true when called for building top navigation menu
261 *
262 * @return array $navigationTree nested array of menus
263 * @static
264 */
265 static function buildNavigationTree(&$navigationTree, $parentID, $navigationMenu = TRUE) {
266 $whereClause = " parent_id IS NULL";
267
268 if ($parentID) {
269 $whereClause = " parent_id = {$parentID}";
270 }
271
272 $domainID = CRM_Core_Config::domainID();
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 {$whereClause}
279 AND domain_id = $domainID
280 ORDER BY parent_id, weight";
281
282 $navigation = CRM_Core_DAO::executeQuery($query);
283 $config = CRM_Core_Config::singleton();
284 while ($navigation->fetch()) {
285 $label = $navigation->label;
286 if (!$navigationMenu) {
287 $label = addcslashes($label, '"');
288 }
289
290 // for each menu get their children
291 $navigationTree[$navigation->id] = array(
292 'attributes' => array('label' => $label,
293 'name' => $navigation->name,
294 'url' => $navigation->url,
295 'permission' => $navigation->permission,
296 'operator' => $navigation->permission_operator,
297 'separator' => $navigation->has_separator,
298 'parentID' => $navigation->parent_id,
299 'navID' => $navigation->id,
300 'active' => $navigation->is_active,
301 ));
302 self::buildNavigationTree($navigationTree[$navigation->id]['child'], $navigation->id, $navigationMenu);
303 }
304
305 return $navigationTree;
306 }
307
308 /**
309 * Build menu
310 *
311 * @param boolean $json by default output is html
312 * @param boolean $navigationMenu true when called for building top navigation menu
313 *
314 * @return returns html or json object
315 * @static
316 */
317 static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
318 $navigations = array();
319 self::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
320 $navigationString = NULL;
321
322 // run the Navigation through a hook so users can modify it
323 CRM_Utils_Hook::navigationMenu($navigations);
324
325 $i18n = CRM_Core_I18n::singleton();
326
327 //skip children menu item if user don't have access to parent menu item
328 $skipMenuItems = array();
329 foreach ($navigations as $key => $value) {
330 if ($json) {
331 if ($navigationString) {
332 $navigationString .= '},';
333 }
334 $data = $value['attributes']['label'];
335 $class = '';
336 if (!$value['attributes']['active']) {
337 $class = ', "attr": { "class" : "disabled"} ';
338 }
339 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
340 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
341 }
342 else {
343 // Home is a special case
344 if ($value['attributes']['name'] != 'Home') {
345 $name = self::getMenuName($value, $skipMenuItems);
346 if ($name) {
347 //separator before
348 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
349 $navigationString .= '<li class="menu-separator"></li>';
350 }
351 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
352 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
353 }
354 }
355 }
356
357 self::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
358 }
359
360 if ($json) {
361 $navigationString = '[' . $navigationString . '}]';
362 }
363 else {
364 // clean up - Need to remove empty <ul>'s, this happens when user don't have
365 // permission to access parent
366 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
367 }
368
369 return $navigationString;
370 }
371
372 /**
373 * Recursively check child menus
374 *
375 * @param array $value
376 * @param string $navigationString
377 * @param boolean $json
378 * @param boolean $skipMenuItems
379 * @return string
380 */
381 static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
382 if ($json) {
383 if (!empty($value['child'])) {
384 $navigationString .= ', "children": [ ';
385 }
386 else {
387 return $navigationString;
388 }
389
390 if (!empty($value['child'])) {
391 $appendComma = TRUE;
392 $count = 1;
393 foreach ($value['child'] as $k => $val) {
394 if ($count == count($value['child'])) {
395 $appendComma = FALSE;
396 }
397 $data = $val['attributes']['label'];
398 $class = '';
399 if (!$val['attributes']['active']) {
400 $class = ', "attr": { "class" : "disabled"} ';
401 }
402 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
403 self::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
404 $navigationString .= $appendComma ? ' },' : ' }';
405 $count++;
406 }
407 }
408
409 if (!empty($value['child'])) {
410 $navigationString .= ' ]';
411 }
412 }
413 else {
414 if (!empty($value['child'])) {
415 $navigationString .= '<ul>';
416 }
417 else {
418 $navigationString .= '</li>';
419 //locate separator after
420 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
421 $navigationString .= '<li class="menu-separator"></li>';
422 }
423 }
424
425 if (!empty($value['child'])) {
426 foreach ($value['child'] as $val) {
427 $name = self::getMenuName($val, $skipMenuItems);
428 if ($name) {
429 //locate separator before
430 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
431 $navigationString .= '<li class="menu-separator"></li>';
432 }
433 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
434 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
435 self::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
436 }
437 }
438 }
439 if (!empty($value['child'])) {
440 $navigationString .= '</ul></li>';
441 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
442 $navigationString .= '<li class="menu-separator"></li>';
443 }
444 }
445 }
446 return $navigationString;
447 }
448
449 /**
450 * Get Menu name
451 *
452 * @param $value
453 * @param array $skipMenuItems
454 * @return bool|string
455 */
456 static function getMenuName(&$value, &$skipMenuItems) {
457 // we need to localise the menu labels (CRM-5456) and don’t
458 // want to use ts() as it would throw the ts-extractor off
459 $i18n = CRM_Core_I18n::singleton();
460
461 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
462 $url = $value['attributes']['url'];
463 $permission = $value['attributes']['permission'];
464 $operator = $value['attributes']['operator'];
465 $parentID = $value['attributes']['parentID'];
466 $navID = $value['attributes']['navID'];
467 $active = $value['attributes']['active'];
468 $menuName = $value['attributes']['name'];
469 $target = CRM_Utils_Array::value('target', $value['attributes']);
470
471 if (in_array($parentID, $skipMenuItems) || !$active) {
472 $skipMenuItems[] = $navID;
473 return FALSE;
474 }
475
476 //we need to check core view/edit or supported acls.
477 if (in_array($menuName, array(
478 'Search...', 'Contacts'))) {
479 if (!CRM_Core_Permission::giveMeAllACLs()) {
480 $skipMenuItems[] = $navID;
481 return FALSE;
482 }
483 }
484
485 $config = CRM_Core_Config::singleton();
486
487 $makeLink = FALSE;
488 if (isset($url) && $url) {
489 if (substr($url, 0, 4) !== 'http') {
490 //CRM-7656 --make sure to separate out url path from url params,
491 //as we'r going to validate url path across cross-site scripting.
492 $urlParam = explode('?', $url);
493 if (empty($urlParam[1])) {
494 $urlParam[1] = NULL;
495 }
496 $url = CRM_Utils_System::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
497 }
498 $makeLink = TRUE;
499 }
500
501 static $allComponents;
502 if (!$allComponents) {
503 $allComponents = CRM_Core_Component::getNames();
504 }
505
506 if (isset($permission) && $permission) {
507 $permissions = explode(',', $permission);
508
509 $hasPermission = FALSE;
510 foreach ($permissions as $key) {
511 $key = trim($key);
512 $showItem = TRUE;
513
514 //get the component name from permission.
515 $componentName = CRM_Core_Permission::getComponentName($key);
516
517 if ($componentName) {
518 if (!in_array($componentName, $config->enableComponents) ||
519 !CRM_Core_Permission::check($key)
520 ) {
521 $showItem = FALSE;
522 if ($operator == 'AND') {
523 $skipMenuItems[] = $navID;
524 return $showItem;
525 }
526 }
527 else {
528 $hasPermission = TRUE;
529 }
530 }
531 elseif (!CRM_Core_Permission::check($key)) {
532 $showItem = FALSE;
533 if ($operator == 'AND') {
534 $skipMenuItems[] = $navID;
535 return $showItem;
536 }
537 }
538 else {
539 $hasPermission = TRUE;
540 }
541 }
542
543 if (!$showItem && !$hasPermission) {
544 $skipMenuItems[] = $navID;
545 return FALSE;
546 }
547 }
548
549 if ($makeLink) {
550 if ($target) {
551 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
552 }
553 else {
554 $name = "<a href=\"{$url}\">{$name}</a>";
555 }
556 }
557
558 return $name;
559 }
560
561 /**
562 * Create navigation for CiviCRM Admin Menu
563 *
564 * @param int $contactID contact id
565 *
566 * @return string $navigation returns navigation html
567 * @static
568 */
569 static function createNavigation($contactID) {
570 $config = CRM_Core_Config::singleton();
571
572 $navigation = self::buildNavigation();
573
574 if ($navigation) {
575
576 //add additional navigation items
577 $logoutURL = CRM_Utils_System::url('civicrm/logout', 'reset=1');
578
579 // get home menu from db
580 $homeParams = array('name' => 'Home');
581 $homeNav = array();
582 $homeIcon = '<img src="' . $config->userFrameworkResourceURL . 'i/logo16px.png" style="vertical-align:middle;" />';
583 self::retrieve($homeParams, $homeNav);
584 if ($homeNav) {
585 list($path, $q) = explode('?', $homeNav['url']);
586 $homeURL = CRM_Utils_System::url($path, $q);
587 $homeLabel = $homeNav['label'];
588 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
589 if ($homeLabel == 'Home') {
590 $homeLabel = ts('CiviCRM Home');
591 }
592 }
593 else {
594 $homeURL = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
595 $homeLabel = ts('CiviCRM Home');
596 }
597 // Link to hide the menubar
598 if (
599 ($config->userSystem->is_drupal) &&
600 ((module_exists('toolbar') && user_access('access toolbar')) ||
601 module_exists('admin_menu') && user_access('access administration menu')
602 )
603 ) {
604 $hideLabel = ts('Drupal Menu');
605 }
606 elseif ($config->userSystem->is_wordpress) {
607 $hideLabel = ts('WordPress Menu');
608 }
609 else {
610 $hideLabel = ts('Hide Menu');
611 }
612
613 $prepandString = "
614 <li class='menumain crm-link-home'>$homeIcon
615 <ul id='civicrm-home'>
616 <li><a href='$homeURL'>$homeLabel</a></li>
617 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
618 <li><a href='$logoutURL' class='crm-logout-link'>". ts('Log out') ."</a></li>
619 </ul>";
620 // <li> tag doesn't need to be closed
621 }
622 return $prepandString . $navigation;
623 }
624
625 /**
626 * Reset navigation for all contacts or a specified contact
627 *
628 * @param integer $contactID - reset only entries belonging to that contact ID
629 * @return string
630 */
631 static function resetNavigation($contactID = NULL) {
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 {
639 // before inserting check if contact id exists in db
640 // this is to handle weird case when contact id is in session but not in db
641 $contact = new CRM_Contact_DAO_Contact();
642 $contact->id = $contactID;
643 if ($contact->find(TRUE)) {
644 CRM_Core_BAO_Setting::setItem(
645 $newKey,
646 CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME,
647 'navigation',
648 NULL,
649 $contactID,
650 $contactID
651 );
652 }
653 }
654 // also reset the dashlet cache in case permissions have changed etc
655 // FIXME: decouple this
656 CRM_Core_BAO_Dashboard::resetDashletCache($contactID);
657
658 return $newKey;
659 }
660
661 /**
662 * Process navigation
663 *
664 * @param array $params associated array, $_GET
665 *
666 * @return void
667 * @static
668 */
669 static function processNavigation(&$params) {
670 $nodeID = (int)str_replace("node_", "", $params['id']);
671 $referenceID = (int)str_replace("node_", "", $params['ref_id']);
672 $position = $params['ps'];
673 $type = $params['type'];
674 $label = CRM_Utils_Array::value('data', $params);
675
676 switch ($type) {
677 case "move":
678 self::processMove($nodeID, $referenceID, $position);
679 break;
680
681 case "rename":
682 self::processRename($nodeID, $label);
683 break;
684
685 case "delete":
686 self::processDelete($nodeID);
687 break;
688 }
689
690 //reset navigation menus
691 self::resetNavigation();
692 CRM_Utils_System::civiExit();
693 }
694
695 /**
696 * Process move action
697 *
698 * @param $nodeID node that is being moved
699 * @param $referenceID parent id where node is moved. 0 mean no parent
700 * @param $position new position of the nod, it starts with 0 - n
701 *
702 * @return void
703 * @static
704 */
705 static function processMove($nodeID, $referenceID, $position) {
706 // based on the new position we need to get the weight of the node after moved node
707 // 1. update the weight of $position + 1 nodes to weight + 1
708 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
709
710 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
711 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
712 // accordingly set the new parent_id
713 if ($referenceID) {
714 $newParentID = $referenceID;
715 $parentClause = "parent_id = {$referenceID} ";
716 }
717 else {
718 $newParentID = 'NULL';
719 $parentClause = 'parent_id IS NULL';
720 }
721
722 $incrementOtherNodes = true;
723 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
724 $params = array(1 => array( $position, 'Positive'));
725 $newWeight = CRM_Core_DAO::singleValueQuery($sql, $params);
726
727 // this means node is moved to last position, so you need to get the weight of last element + 1
728 if (!$newWeight) {
729 $lastPosition = $position - 1;
730 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
731 $params = array(1 => array($lastPosition, 'Positive'));
732 $newWeight = CRM_Core_DAO::singleValueQuery($sql, $params);
733
734 // since last node increment + 1
735 $newWeight = $newWeight + 1;
736
737 // since this is a last node we don't need to increment other nodes
738 $incrementOtherNodes = false;
739 }
740
741 $transaction = new CRM_Core_Transaction();
742
743 // now update the existing nodes to weight + 1, if required.
744 if ( $incrementOtherNodes ) {
745 $query = "UPDATE civicrm_navigation SET weight = weight + 1
746 WHERE {$parentClause} AND weight >= {$newWeight}";
747
748 CRM_Core_DAO::executeQuery($query);
749 }
750
751 // finally set the weight of current node
752 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
753 CRM_Core_DAO::executeQuery($query);
754
755 $transaction->commit();
756 }
757
758 /**
759 * Function to process rename action for tree
760 *
761 * @param int $nodeID
762 * @param $label
763 */
764 static function processRename($nodeID, $label) {
765 CRM_Core_DAO::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
766 }
767
768 /**
769 * Process delete action for tree
770 *
771 * @param int $nodeID
772 */
773 static function processDelete($nodeID) {
774 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
775 CRM_Core_DAO::executeQuery($query);
776 }
777
778 /**
779 * Get the info on navigation item
780 *
781 * @param int $navigationID navigation id
782 *
783 * @return array associated array
784 * @static
785 */
786 static function getNavigationInfo($navigationID) {
787 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
788 $params = array($navigationID, 'Integer');
789 $dao = CRM_Core_DAO::executeQuery($query, array(1 => $params));
790 $dao->fetch();
791 return array(
792 'parent_id' => $dao->parent_id,
793 'weight' => $dao->weight,
794 );
795 }
796
797 /**
798 * Update menu
799 *
800 * @param array $params
801 * @param array $newParams new value of params
802 * @static
803 */
804 static function processUpdate($params, $newParams) {
805 $dao = new CRM_Core_DAO_Navigation();
806 $dao->copyValues($params);
807 if ($dao->find(TRUE)) {
808 $dao->copyValues($newParams);
809 $dao->save();
810 }
811 }
812
813 /**
814 * @param int $cid
815 *
816 * @return object|string
817 */
818 static function getCacheKey($cid) {
819 $key = CRM_Core_BAO_Setting::getItem(
820 CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME,
821 'navigation',
822 NULL,
823 '',
824 $cid
825 );
826 if (strlen($key) !== self::CACHE_KEY_STRLEN) {
827 $key = self::resetNavigation($cid);
828 }
829 return $key;
830 }
831 }
832