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