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