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