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