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