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