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