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