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