INFRA-132 - CRM/ - PHPStorm cleanup
[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 returns html or json object
338 * @static
339 */
340 public static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
341 $navigations = array();
342 self::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
343 $navigationString = NULL;
344
345 // run the Navigation through a hook so users can modify it
346 CRM_Utils_Hook::navigationMenu($navigations);
347
348 $i18n = CRM_Core_I18n::singleton();
349
350 //skip children menu item if user don't have access to parent menu item
351 $skipMenuItems = array();
352 foreach ($navigations as $key => $value) {
353 if ($json) {
354 if ($navigationString) {
355 $navigationString .= '},';
356 }
357 $data = $value['attributes']['label'];
358 $class = '';
359 if (!$value['attributes']['active']) {
360 $class = ', "attr": { "class" : "disabled"} ';
361 }
362 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
363 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
364 }
365 else {
366 // Home is a special case
367 if ($value['attributes']['name'] != 'Home') {
368 $name = self::getMenuName($value, $skipMenuItems);
369 if ($name) {
370 //separator before
371 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
372 $navigationString .= '<li class="menu-separator"></li>';
373 }
374 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
375 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
376 }
377 }
378 }
379
380 self::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
381 }
382
383 if ($json) {
384 $navigationString = '[' . $navigationString . '}]';
385 }
386 else {
387 // clean up - Need to remove empty <ul>'s, this happens when user don't have
388 // permission to access parent
389 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
390 }
391
392 return $navigationString;
393 }
394
395 /**
396 * Recursively check child menus
397 *
398 * @param array $value
399 * @param string $navigationString
400 * @param bool $json
401 * @param bool $skipMenuItems
402 * @return string
403 */
404 public static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
405 if ($json) {
406 if (!empty($value['child'])) {
407 $navigationString .= ', "children": [ ';
408 }
409 else {
410 return $navigationString;
411 }
412
413 if (!empty($value['child'])) {
414 $appendComma = TRUE;
415 $count = 1;
416 foreach ($value['child'] as $k => $val) {
417 if ($count == count($value['child'])) {
418 $appendComma = FALSE;
419 }
420 $data = $val['attributes']['label'];
421 $class = '';
422 if (!$val['attributes']['active']) {
423 $class = ', "attr": { "class" : "disabled"} ';
424 }
425 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
426 self::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
427 $navigationString .= $appendComma ? ' },' : ' }';
428 $count++;
429 }
430 }
431
432 if (!empty($value['child'])) {
433 $navigationString .= ' ]';
434 }
435 }
436 else {
437 if (!empty($value['child'])) {
438 $navigationString .= '<ul>';
439 }
440 else {
441 $navigationString .= '</li>';
442 //locate separator after
443 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
444 $navigationString .= '<li class="menu-separator"></li>';
445 }
446 }
447
448 if (!empty($value['child'])) {
449 foreach ($value['child'] as $val) {
450 $name = self::getMenuName($val, $skipMenuItems);
451 if ($name) {
452 //locate separator before
453 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
454 $navigationString .= '<li class="menu-separator"></li>';
455 }
456 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
457 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
458 self::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
459 }
460 }
461 }
462 if (!empty($value['child'])) {
463 $navigationString .= '</ul></li>';
464 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
465 $navigationString .= '<li class="menu-separator"></li>';
466 }
467 }
468 }
469 return $navigationString;
470 }
471
472 /**
473 * Get Menu name
474 *
475 * @param $value
476 * @param array $skipMenuItems
477 * @return bool|string
478 */
479 public static function getMenuName(&$value, &$skipMenuItems) {
480 // we need to localise the menu labels (CRM-5456) and don’t
481 // want to use ts() as it would throw the ts-extractor off
482 $i18n = CRM_Core_I18n::singleton();
483
484 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
485 $url = $value['attributes']['url'];
486 $permission = $value['attributes']['permission'];
487 $operator = $value['attributes']['operator'];
488 $parentID = $value['attributes']['parentID'];
489 $navID = $value['attributes']['navID'];
490 $active = $value['attributes']['active'];
491 $menuName = $value['attributes']['name'];
492 $target = CRM_Utils_Array::value('target', $value['attributes']);
493
494 if (in_array($parentID, $skipMenuItems) || !$active) {
495 $skipMenuItems[] = $navID;
496 return FALSE;
497 }
498
499 //we need to check core view/edit or supported acls.
500 if (in_array($menuName, array(
501 'Search...',
502 'Contacts'
503 ))) {
504 if (!CRM_Core_Permission::giveMeAllACLs()) {
505 $skipMenuItems[] = $navID;
506 return FALSE;
507 }
508 }
509
510 $config = CRM_Core_Config::singleton();
511
512 $makeLink = FALSE;
513 if (isset($url) && $url) {
514 if (substr($url, 0, 4) !== 'http') {
515 //CRM-7656 --make sure to separate out url path from url params,
516 //as we'r going to validate url path across cross-site scripting.
517 $urlParam = explode('?', $url);
518 if (empty($urlParam[1])) {
519 $urlParam[1] = NULL;
520 }
521 $url = CRM_Utils_System::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
522 }
523 $makeLink = TRUE;
524 }
525
526 static $allComponents;
527 if (!$allComponents) {
528 $allComponents = CRM_Core_Component::getNames();
529 }
530
531 if (isset($permission) && $permission) {
532 $permissions = explode(',', $permission);
533
534 $hasPermission = FALSE;
535 foreach ($permissions as $key) {
536 $key = trim($key);
537 $showItem = TRUE;
538
539 //get the component name from permission.
540 $componentName = CRM_Core_Permission::getComponentName($key);
541
542 if ($componentName) {
543 if (!in_array($componentName, $config->enableComponents) ||
544 !CRM_Core_Permission::check($key)
545 ) {
546 $showItem = FALSE;
547 if ($operator == 'AND') {
548 $skipMenuItems[] = $navID;
549 return $showItem;
550 }
551 }
552 else {
553 $hasPermission = TRUE;
554 }
555 }
556 elseif (!CRM_Core_Permission::check($key)) {
557 $showItem = FALSE;
558 if ($operator == 'AND') {
559 $skipMenuItems[] = $navID;
560 return $showItem;
561 }
562 }
563 else {
564 $hasPermission = TRUE;
565 }
566 }
567
568 if (!$showItem && !$hasPermission) {
569 $skipMenuItems[] = $navID;
570 return FALSE;
571 }
572 }
573
574 if ($makeLink) {
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 * @static
595 */
596 public static function createNavigation($contactID) {
597 $config = CRM_Core_Config::singleton();
598
599 $navigation = self::buildNavigation();
600
601 if ($navigation) {
602
603 //add additional navigation items
604 $logoutURL = CRM_Utils_System::url('civicrm/logout', 'reset=1');
605
606 // get home menu from db
607 $homeParams = array('name' => 'Home');
608 $homeNav = array();
609 $homeIcon = '<img src="' . $config->userFrameworkResourceURL . 'i/logo16px.png" style="vertical-align:middle;" />';
610 self::retrieve($homeParams, $homeNav);
611 if ($homeNav) {
612 list($path, $q) = explode('?', $homeNav['url']);
613 $homeURL = CRM_Utils_System::url($path, $q);
614 $homeLabel = $homeNav['label'];
615 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
616 if ($homeLabel == 'Home') {
617 $homeLabel = ts('CiviCRM Home');
618 }
619 }
620 else {
621 $homeURL = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
622 $homeLabel = ts('CiviCRM Home');
623 }
624 // Link to hide the menubar
625 if (
626 ($config->userSystem->is_drupal) &&
627 ((module_exists('toolbar') && user_access('access toolbar')) ||
628 module_exists('admin_menu') && user_access('access administration menu')
629 )
630 ) {
631 $hideLabel = ts('Drupal Menu');
632 }
633 elseif ($config->userSystem->is_wordpress) {
634 $hideLabel = ts('WordPress Menu');
635 }
636 else {
637 $hideLabel = ts('Hide Menu');
638 }
639
640 $prepandString = "
641 <li class='menumain crm-link-home'>$homeIcon
642 <ul id='civicrm-home'>
643 <li><a href='$homeURL'>$homeLabel</a></li>
644 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
645 <li><a href='$logoutURL' class='crm-logout-link'>" . ts('Log out') . "</a></li>
646 </ul>";
647 // <li> tag doesn't need to be closed
648 }
649 return $prepandString . $navigation;
650 }
651
652 /**
653 * Reset navigation for all contacts or a specified contact
654 *
655 * @param int $contactID
656 * Reset only entries belonging to that contact ID.
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 * @return void
696 * @static
697 */
698 public static function processNavigation(&$params) {
699 $nodeID = (int) str_replace("node_", "", $params['id']);
700 $referenceID = (int) str_replace("node_", "", $params['ref_id']);
701 $position = $params['ps'];
702 $type = $params['type'];
703 $label = CRM_Utils_Array::value('data', $params);
704
705 switch ($type) {
706 case "move":
707 self::processMove($nodeID, $referenceID, $position);
708 break;
709
710 case "rename":
711 self::processRename($nodeID, $label);
712 break;
713
714 case "delete":
715 self::processDelete($nodeID);
716 break;
717 }
718
719 //reset navigation menus
720 self::resetNavigation();
721 CRM_Utils_System::civiExit();
722 }
723
724 /**
725 * Process move action
726 *
727 * @param $nodeID
728 * Node that is being moved.
729 * @param $referenceID
730 * Parent id where node is moved. 0 mean no parent.
731 * @param $position
732 * New position of the nod, it starts with 0 - n.
733 *
734 * @return void
735 * @static
736 */
737 public static function processMove($nodeID, $referenceID, $position) {
738 // based on the new position we need to get the weight of the node after moved node
739 // 1. update the weight of $position + 1 nodes to weight + 1
740 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
741
742 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
743 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
744 // accordingly set the new parent_id
745 if ($referenceID) {
746 $newParentID = $referenceID;
747 $parentClause = "parent_id = {$referenceID} ";
748 }
749 else {
750 $newParentID = 'NULL';
751 $parentClause = 'parent_id IS NULL';
752 }
753
754 $incrementOtherNodes = TRUE;
755 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
756 $params = array(1 => array($position, 'Positive'));
757 $newWeight = CRM_Core_DAO::singleValueQuery($sql, $params);
758
759 // this means node is moved to last position, so you need to get the weight of last element + 1
760 if (!$newWeight) {
761 $lastPosition = $position - 1;
762 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
763 $params = array(1 => array($lastPosition, 'Positive'));
764 $newWeight = CRM_Core_DAO::singleValueQuery($sql, $params);
765
766 // since last node increment + 1
767 $newWeight = $newWeight + 1;
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 * @static
819 */
820 public static function getNavigationInfo($navigationID) {
821 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
822 $params = array($navigationID, 'Integer');
823 $dao = CRM_Core_DAO::executeQuery($query, array(1 => $params));
824 $dao->fetch();
825 return array(
826 'parent_id' => $dao->parent_id,
827 'weight' => $dao->weight,
828 );
829 }
830
831 /**
832 * Update menu
833 *
834 * @param array $params
835 * @param array $newParams
836 * New value of params.
837 * @static
838 */
839 public static function processUpdate($params, $newParams) {
840 $dao = new CRM_Core_DAO_Navigation();
841 $dao->copyValues($params);
842 if ($dao->find(TRUE)) {
843 $dao->copyValues($newParams);
844 $dao->save();
845 }
846 }
847
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 }