Merge pull request #6959 from colemanw/CRM-16415
[civicrm-core.git] / CRM / Core / BAO / Navigation.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 */
33 class CRM_Core_BAO_Navigation extends CRM_Core_DAO_Navigation {
34
35 // Number of characters in the menu js cache key
36 const CACHE_KEY_STRLEN = 8;
37
38 /**
39 * Class constructor.
40 */
41 public function __construct() {
42 parent::__construct();
43 }
44
45 /**
46 * Update the is_active flag in the db.
47 *
48 * @param int $id
49 * Id of the database record.
50 * @param bool $is_active
51 * Value we want to set the is_active field.
52 *
53 * @return CRM_Core_DAO_Navigation|NULL
54 * DAO object on success, NULL otherwise
55 */
56 public static function setIsActive($id, $is_active) {
57 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_Navigation', $id, 'is_active', $is_active);
58 }
59
60 /**
61 * Get existing / build navigation for CiviCRM Admin Menu.
62 *
63 * @return array
64 * associated array
65 */
66 public static function getMenus() {
67 $menus = array();
68
69 $menu = new CRM_Core_DAO_Menu();
70 $menu->domain_id = CRM_Core_Config::domainID();
71 $menu->find();
72
73 while ($menu->fetch()) {
74 if ($menu->title) {
75 $menus[$menu->path] = $menu->title;
76 }
77 }
78 return $menus;
79 }
80
81 /**
82 * Add/update navigation record.
83 *
84 * @param array $params Submitted values
85 *
86 * @return CRM_Core_DAO_Navigation
87 * navigation object
88 */
89 public static function add(&$params) {
90 $navigation = new CRM_Core_DAO_Navigation();
91 if (empty($params['id'])) {
92 $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
93 $params['has_separator'] = CRM_Utils_Array::value('has_separator', $params, FALSE);
94 }
95
96 if (!isset($params['id']) ||
97 (CRM_Utils_Array::value('parent_id', $params) != CRM_Utils_Array::value('current_parent_id', $params))
98 ) {
99 /* re/calculate the weight, if the Parent ID changed OR create new menu */
100
101 if ($navName = CRM_Utils_Array::value('name', $params)) {
102 $params['name'] = $navName;
103 }
104 elseif ($navLabel = CRM_Utils_Array::value('label', $params)) {
105 $params['name'] = $navLabel;
106 }
107
108 $params['weight'] = self::calculateWeight(CRM_Utils_Array::value('parent_id', $params));
109 }
110
111 if (array_key_exists('permission', $params) && is_array($params['permission'])) {
112 $params['permission'] = implode(',', $params['permission']);
113 }
114
115 $navigation->copyValues($params);
116
117 $navigation->domain_id = CRM_Core_Config::domainID();
118
119 $navigation->save();
120 return $navigation;
121 }
122
123 /**
124 * Fetch object based on array of properties.
125 *
126 * @param array $params
127 * (reference ) an assoc array of name/value pairs.
128 * @param array $defaults
129 * (reference ) an assoc array to hold the flattened values.
130 *
131 * @return CRM_Core_BAO_Navigation|null
132 * object on success, NULL otherwise
133 */
134 public static function retrieve(&$params, &$defaults) {
135 $navigation = new CRM_Core_DAO_Navigation();
136 $navigation->copyValues($params);
137
138 $navigation->domain_id = CRM_Core_Config::domainID();
139
140 if ($navigation->find(TRUE)) {
141 CRM_Core_DAO::storeValues($navigation, $defaults);
142 return $navigation;
143 }
144 return NULL;
145 }
146
147 /**
148 * Calculate navigation weight.
149 *
150 * @param int $parentID
151 * Parent_id of a menu.
152 * @param int $menuID
153 * Menu id.
154 *
155 * @return int
156 * $weight string
157 */
158 public static function calculateWeight($parentID = NULL, $menuID = NULL) {
159 $domainID = CRM_Core_Config::domainID();
160
161 $weight = 1;
162 // we reset weight for each parent, i.e we start from 1 to n
163 // calculate max weight for top level menus, if parent id is absent
164 if (!$parentID) {
165 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id IS NULL AND domain_id = $domainID";
166 }
167 else {
168 // if parent is passed, we need to get max weight for that particular parent
169 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id = {$parentID} AND domain_id = $domainID";
170 }
171
172 $dao = CRM_Core_DAO::executeQuery($query);
173 $dao->fetch();
174 return $weight = $weight + $dao->weight;
175 }
176
177 /**
178 * Get formatted menu list.
179 *
180 * @return array
181 * returns associated array
182 */
183 public static function getNavigationList() {
184 $cacheKeyString = "navigationList";
185 $whereClause = '';
186
187 $config = CRM_Core_Config::singleton();
188
189 // check if we can retrieve from database cache
190 $navigations = CRM_Core_BAO_Cache::getItem('navigation', $cacheKeyString);
191
192 if (!$navigations) {
193 $domainID = CRM_Core_Config::domainID();
194 $query = "
195 SELECT id, label, parent_id, weight, is_active, name
196 FROM civicrm_navigation WHERE domain_id = $domainID {$whereClause} ORDER BY parent_id, weight ASC";
197 $result = CRM_Core_DAO::executeQuery($query);
198
199 $pidGroups = array();
200 while ($result->fetch()) {
201 $pidGroups[$result->parent_id][$result->label] = $result->id;
202 }
203
204 foreach ($pidGroups[''] as $label => $val) {
205 $pidGroups[''][$label] = self::_getNavigationValue($val, $pidGroups);
206 }
207
208 $navigations = array();
209 self::_getNavigationLabel($pidGroups[''], $navigations);
210
211 CRM_Core_BAO_Cache::setItem($navigations, 'navigation', $cacheKeyString);
212 }
213 return $navigations;
214 }
215
216 /**
217 * Helper function for getNavigationList().
218 *
219 * @param array $list
220 * Menu info.
221 * @param array $navigations
222 * Navigation menus.
223 * @param string $separator
224 * Menu separator.
225 */
226 public static function _getNavigationLabel($list, &$navigations, $separator = '') {
227 $i18n = CRM_Core_I18n::singleton();
228 foreach ($list as $label => $val) {
229 if ($label == 'navigation_id') {
230 continue;
231 }
232 $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
233 $navigations[is_array($val) ? $val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
234 if (is_array($val)) {
235 self::_getNavigationLabel($val, $navigations, $separator . '&nbsp;&nbsp;&nbsp;&nbsp;');
236 }
237 }
238 }
239
240 /**
241 * Helper function for getNavigationList().
242 *
243 * @param string $val
244 * Menu name.
245 * @param array $pidGroups
246 * Parent menus.
247 *
248 * @return array
249 */
250 public static function _getNavigationValue($val, &$pidGroups) {
251 if (array_key_exists($val, $pidGroups)) {
252 $list = array('navigation_id' => $val);
253 foreach ($pidGroups[$val] as $label => $id) {
254 $list[$label] = self::_getNavigationValue($id, $pidGroups);
255 }
256 unset($pidGroups[$val]);
257 return $list;
258 }
259 else {
260 return $val;
261 }
262 }
263
264 /**
265 * Build navigation tree.
266 *
267 * @param array $navigationTree
268 * Nested array of menus.
269 * @param int $parentID
270 * Parent id.
271 * @param bool $navigationMenu
272 * True when called for building top navigation menu.
273 *
274 * @return array
275 * nested array of menus
276 */
277 public static function buildNavigationTree(&$navigationTree, $parentID, $navigationMenu = TRUE) {
278 $whereClause = " parent_id IS NULL";
279
280 if ($parentID) {
281 $whereClause = " parent_id = {$parentID}";
282 }
283
284 $domainID = CRM_Core_Config::domainID();
285
286 // get the list of menus
287 $query = "
288 SELECT id, label, url, permission, permission_operator, has_separator, parent_id, is_active, name
289 FROM civicrm_navigation
290 WHERE {$whereClause}
291 AND domain_id = $domainID
292 ORDER BY parent_id, weight";
293
294 $navigation = CRM_Core_DAO::executeQuery($query);
295 $config = CRM_Core_Config::singleton();
296 while ($navigation->fetch()) {
297 $label = $navigation->label;
298 if (!$navigationMenu) {
299 $label = addcslashes($label, '"');
300 }
301
302 // for each menu get their children
303 $navigationTree[$navigation->id] = array(
304 'attributes' => array(
305 '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 );
316 self::buildNavigationTree($navigationTree[$navigation->id]['child'], $navigation->id, $navigationMenu);
317 }
318
319 return $navigationTree;
320 }
321
322 /**
323 * Build menu.
324 *
325 * @param bool $json
326 * By default output is html.
327 * @param bool $navigationMenu
328 * True when called for building top navigation menu.
329 *
330 * @return string
331 * html or json string
332 */
333 public static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
334 $navigations = array();
335 self::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
336 $navigationString = NULL;
337
338 // run the Navigation through a hook so users can modify it
339 CRM_Utils_Hook::navigationMenu($navigations);
340 self::fixNavigationMenu($navigations);
341
342 $i18n = CRM_Core_I18n::singleton();
343
344 //skip children menu item if user don't have access to parent menu item
345 $skipMenuItems = array();
346 foreach ($navigations as $key => $value) {
347 if ($json) {
348 if ($navigationString) {
349 $navigationString .= '},';
350 }
351 $data = $value['attributes']['label'];
352 $class = '';
353 if (!$value['attributes']['active']) {
354 $class = ', "attr": { "class" : "disabled"} ';
355 }
356 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
357 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
358 }
359 else {
360 // Home is a special case
361 if ($value['attributes']['name'] != 'Home') {
362 $name = self::getMenuName($value, $skipMenuItems);
363 if ($name) {
364 //separator before
365 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
366 $navigationString .= '<li class="menu-separator"></li>';
367 }
368 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
369 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
370 }
371 }
372 }
373
374 self::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
375 }
376
377 if ($json) {
378 $navigationString = '[' . $navigationString . '}]';
379 }
380 else {
381 // clean up - Need to remove empty <ul>'s, this happens when user don't have
382 // permission to access parent
383 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
384 }
385
386 return $navigationString;
387 }
388
389 /**
390 * Recursively check child menus.
391 *
392 * @param array $value
393 * @param string $navigationString
394 * @param bool $json
395 * @param bool $skipMenuItems
396 *
397 * @return string
398 */
399 public static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
400 if ($json) {
401 if (!empty($value['child'])) {
402 $navigationString .= ', "children": [ ';
403 }
404 else {
405 return $navigationString;
406 }
407
408 if (!empty($value['child'])) {
409 $appendComma = TRUE;
410 $count = 1;
411 foreach ($value['child'] as $k => $val) {
412 if ($count == count($value['child'])) {
413 $appendComma = FALSE;
414 }
415 $data = $val['attributes']['label'];
416 $class = '';
417 if (!$val['attributes']['active']) {
418 $class = ', "attr": { "class" : "disabled"} ';
419 }
420 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
421 self::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
422 $navigationString .= $appendComma ? ' },' : ' }';
423 $count++;
424 }
425 }
426
427 if (!empty($value['child'])) {
428 $navigationString .= ' ]';
429 }
430 }
431 else {
432 if (!empty($value['child'])) {
433 $navigationString .= '<ul>';
434 }
435 else {
436 $navigationString .= '</li>';
437 //locate separator after
438 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
439 $navigationString .= '<li class="menu-separator"></li>';
440 }
441 }
442
443 if (!empty($value['child'])) {
444 foreach ($value['child'] as $val) {
445 $name = self::getMenuName($val, $skipMenuItems);
446 if ($name) {
447 //locate separator before
448 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
449 $navigationString .= '<li class="menu-separator"></li>';
450 }
451 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
452 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
453 self::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
454 }
455 }
456 }
457 if (!empty($value['child'])) {
458 $navigationString .= '</ul></li>';
459 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
460 $navigationString .= '<li class="menu-separator"></li>';
461 }
462 }
463 }
464 return $navigationString;
465 }
466
467 /**
468 * Given a navigation menu, generate navIDs for any items which are
469 * missing them.
470 *
471 * @param array $nodes
472 * Each key is a numeral; each value is a node in
473 * the menu tree (with keys "child" and "attributes").
474 */
475 public static function fixNavigationMenu(&$nodes) {
476 $maxNavID = 1;
477 array_walk_recursive($nodes, function($item, $key) use (&$maxNavID) {
478 if ($key === 'navID') {
479 $maxNavID = max($maxNavID, $item);
480 }
481 });
482 self::_fixNavigationMenu($nodes, $maxNavID, NULL);
483 }
484
485 /**
486 * @param array $nodes
487 * Each key is a numeral; each value is a node in
488 * the menu tree (with keys "child" and "attributes").
489 */
490 private static function _fixNavigationMenu(&$nodes, &$maxNavID, $parentID) {
491 $origKeys = array_keys($nodes);
492 foreach ($origKeys as $origKey) {
493 if (!isset($nodes[$origKey]['attributes']['parentID']) && $parentID !== NULL) {
494 $nodes[$origKey]['attributes']['parentID'] = $parentID;
495 }
496 // If no navID, then assign navID and fix key.
497 if (!isset($nodes[$origKey]['attributes']['navID'])) {
498 $newKey = ++$maxNavID;
499 $nodes[$origKey]['attributes']['navID'] = $newKey;
500 $nodes[$newKey] = $nodes[$origKey];
501 unset($nodes[$origKey]);
502 $origKey = $newKey;
503 }
504 if (isset($nodes[$origKey]['child']) && is_array($nodes[$origKey]['child'])) {
505 self::_fixNavigationMenu($nodes[$origKey]['child'], $maxNavID, $nodes[$origKey]['attributes']['navID']);
506 }
507 }
508 }
509
510 /**
511 * Get Menu name.
512 *
513 * @param $value
514 * @param array $skipMenuItems
515 *
516 * @return bool|string
517 */
518 public static function getMenuName(&$value, &$skipMenuItems) {
519 // we need to localise the menu labels (CRM-5456) and don’t
520 // want to use ts() as it would throw the ts-extractor off
521 $i18n = CRM_Core_I18n::singleton();
522
523 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
524 $url = CRM_Utils_Array::value('url', $value['attributes']);
525 $permission = CRM_Utils_Array::value('permission', $value['attributes']);
526 $operator = CRM_Utils_Array::value('operator', $value['attributes']);
527 $parentID = CRM_Utils_Array::value('parentID', $value['attributes']);
528 $navID = CRM_Utils_Array::value('navID', $value['attributes']);
529 $active = CRM_Utils_Array::value('active', $value['attributes']);
530 $menuName = CRM_Utils_Array::value('name', $value['attributes']);
531 $target = CRM_Utils_Array::value('target', $value['attributes']);
532
533 if (in_array($parentID, $skipMenuItems) || !$active) {
534 $skipMenuItems[] = $navID;
535 return FALSE;
536 }
537
538 //we need to check core view/edit or supported acls.
539 if (in_array($menuName, array(
540 'Search...',
541 'Contacts',
542 ))) {
543 if (!CRM_Core_Permission::giveMeAllACLs()) {
544 $skipMenuItems[] = $navID;
545 return FALSE;
546 }
547 }
548
549 $config = CRM_Core_Config::singleton();
550
551 $makeLink = FALSE;
552 if (isset($url) && $url) {
553 if (substr($url, 0, 4) !== 'http') {
554 //CRM-7656 --make sure to separate out url path from url params,
555 //as we'r going to validate url path across cross-site scripting.
556 $urlParam = explode('?', $url);
557 if (empty($urlParam[1])) {
558 $urlParam[1] = NULL;
559 }
560 $url = CRM_Utils_System::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
561 }
562 elseif (strpos($url, '&amp;') === FALSE) {
563 $url = htmlspecialchars($url);
564 }
565 $makeLink = TRUE;
566 }
567
568 static $allComponents;
569 if (!$allComponents) {
570 $allComponents = CRM_Core_Component::getNames();
571 }
572
573 if (isset($permission) && $permission) {
574 $permissions = explode(',', $permission);
575
576 $hasPermission = FALSE;
577 foreach ($permissions as $key) {
578 $key = trim($key);
579 $showItem = TRUE;
580
581 //get the component name from permission.
582 $componentName = CRM_Core_Permission::getComponentName($key);
583
584 if ($componentName) {
585 if (!in_array($componentName, $config->enableComponents) ||
586 !CRM_Core_Permission::check($key)
587 ) {
588 $showItem = FALSE;
589 if ($operator == 'AND') {
590 $skipMenuItems[] = $navID;
591 return $showItem;
592 }
593 }
594 else {
595 $hasPermission = TRUE;
596 }
597 }
598 elseif (!CRM_Core_Permission::check($key)) {
599 $showItem = FALSE;
600 if ($operator == 'AND') {
601 $skipMenuItems[] = $navID;
602 return $showItem;
603 }
604 }
605 else {
606 $hasPermission = TRUE;
607 }
608 }
609
610 if (!$showItem && !$hasPermission) {
611 $skipMenuItems[] = $navID;
612 return FALSE;
613 }
614 }
615
616 if ($makeLink) {
617 $url = CRM_Utils_System::evalUrl($url);
618 if ($target) {
619 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
620 }
621 else {
622 $name = "<a href=\"{$url}\">{$name}</a>";
623 }
624 }
625
626 return $name;
627 }
628
629 /**
630 * Create navigation for CiviCRM Admin Menu.
631 *
632 * @param int $contactID
633 * Contact id.
634 *
635 * @return string
636 * returns navigation html
637 */
638 public static function createNavigation($contactID) {
639 $config = CRM_Core_Config::singleton();
640
641 $navigation = self::buildNavigation();
642
643 if ($navigation) {
644
645 //add additional navigation items
646 $logoutURL = CRM_Utils_System::url('civicrm/logout', 'reset=1');
647
648 // get home menu from db
649 $homeParams = array('name' => 'Home');
650 $homeNav = array();
651 $homeIcon = '<span class="crm-logo-sm" ></span>';
652 self::retrieve($homeParams, $homeNav);
653 if ($homeNav) {
654 list($path, $q) = explode('?', $homeNav['url']);
655 $homeURL = CRM_Utils_System::url($path, $q);
656 $homeLabel = $homeNav['label'];
657 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
658 if ($homeLabel == 'Home') {
659 $homeLabel = ts('CiviCRM Home');
660 }
661 }
662 else {
663 $homeURL = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
664 $homeLabel = ts('CiviCRM Home');
665 }
666 // Link to hide the menubar
667 $hideLabel = ts('Hide Menu');
668
669 $prepandString = "
670 <li class='menumain crm-link-home'>$homeIcon
671 <ul id='civicrm-home'>
672 <li><a href='$homeURL'>$homeLabel</a></li>
673 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
674 <li><a href='$logoutURL' class='crm-logout-link'>" . ts('Log out') . "</a></li>
675 </ul>";
676 // <li> tag doesn't need to be closed
677 }
678 return $prepandString . $navigation;
679 }
680
681 /**
682 * Reset navigation for all contacts or a specified contact.
683 *
684 * @param int $contactID
685 * Reset only entries belonging to that contact ID.
686 *
687 * @return string
688 */
689 public static function resetNavigation($contactID = NULL) {
690 $newKey = CRM_Utils_String::createRandom(self::CACHE_KEY_STRLEN, CRM_Utils_String::ALPHANUMERIC);
691 if (!$contactID) {
692 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
693 CRM_Core_DAO::executeQuery($query);
694 CRM_Core_BAO_Cache::deleteGroup('navigation');
695 }
696 else {
697 // before inserting check if contact id exists in db
698 // this is to handle weird case when contact id is in session but not in db
699 $contact = new CRM_Contact_DAO_Contact();
700 $contact->id = $contactID;
701 if ($contact->find(TRUE)) {
702 CRM_Core_BAO_Setting::setItem(
703 $newKey,
704 CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME,
705 'navigation',
706 NULL,
707 $contactID,
708 $contactID
709 );
710 }
711 }
712 // also reset the dashlet cache in case permissions have changed etc
713 // FIXME: decouple this
714 CRM_Core_BAO_Dashboard::resetDashletCache($contactID);
715
716 return $newKey;
717 }
718
719 /**
720 * Process navigation.
721 *
722 * @param array $params
723 * Associated array, $_GET.
724 */
725 public static function processNavigation(&$params) {
726 $nodeID = (int) str_replace("node_", "", $params['id']);
727 $referenceID = (int) str_replace("node_", "", $params['ref_id']);
728 $position = $params['ps'];
729 $type = $params['type'];
730 $label = CRM_Utils_Array::value('data', $params);
731
732 switch ($type) {
733 case "move":
734 self::processMove($nodeID, $referenceID, $position);
735 break;
736
737 case "rename":
738 self::processRename($nodeID, $label);
739 break;
740
741 case "delete":
742 self::processDelete($nodeID);
743 break;
744 }
745
746 //reset navigation menus
747 self::resetNavigation();
748 CRM_Utils_System::civiExit();
749 }
750
751 /**
752 * Process move action.
753 *
754 * @param $nodeID
755 * Node that is being moved.
756 * @param $referenceID
757 * Parent id where node is moved. 0 mean no parent.
758 * @param $position
759 * New position of the nod, it starts with 0 - n.
760 */
761 public static function processMove($nodeID, $referenceID, $position) {
762 // based on the new position we need to get the weight of the node after moved node
763 // 1. update the weight of $position + 1 nodes to weight + 1
764 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
765
766 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
767 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
768 // accordingly set the new parent_id
769 if ($referenceID) {
770 $newParentID = $referenceID;
771 $parentClause = "parent_id = {$referenceID} ";
772 }
773 else {
774 $newParentID = 'NULL';
775 $parentClause = 'parent_id IS NULL';
776 }
777
778 $incrementOtherNodes = TRUE;
779 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
780 $params = array(1 => array($position, 'Positive'));
781 $newWeight = CRM_Core_DAO::singleValueQuery($sql, $params);
782
783 // this means node is moved to last position, so you need to get the weight of last element + 1
784 if (!$newWeight) {
785 // If this is not the first item being added to a parent
786 if ($position) {
787 $lastPosition = $position - 1;
788 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
789 $params = array(1 => array($lastPosition, 'Positive'));
790 $newWeight = CRM_Core_DAO::singleValueQuery($sql, $params);
791
792 // since last node increment + 1
793 $newWeight = $newWeight + 1;
794 }
795 else {
796 $newWeight = '0';
797 }
798
799 // since this is a last node we don't need to increment other nodes
800 $incrementOtherNodes = FALSE;
801 }
802
803 $transaction = new CRM_Core_Transaction();
804
805 // now update the existing nodes to weight + 1, if required.
806 if ($incrementOtherNodes) {
807 $query = "UPDATE civicrm_navigation SET weight = weight + 1
808 WHERE {$parentClause} AND weight >= {$newWeight}";
809
810 CRM_Core_DAO::executeQuery($query);
811 }
812
813 // finally set the weight of current node
814 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
815 CRM_Core_DAO::executeQuery($query);
816
817 $transaction->commit();
818 }
819
820 /**
821 * Function to process rename action for tree.
822 *
823 * @param int $nodeID
824 * @param $label
825 */
826 public static function processRename($nodeID, $label) {
827 CRM_Core_DAO::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
828 }
829
830 /**
831 * Process delete action for tree.
832 *
833 * @param int $nodeID
834 */
835 public static function processDelete($nodeID) {
836 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
837 CRM_Core_DAO::executeQuery($query);
838 }
839
840 /**
841 * Get the info on navigation item.
842 *
843 * @param int $navigationID
844 * Navigation id.
845 *
846 * @return array
847 * associated array
848 */
849 public static function getNavigationInfo($navigationID) {
850 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
851 $params = array($navigationID, 'Integer');
852 $dao = CRM_Core_DAO::executeQuery($query, array(1 => $params));
853 $dao->fetch();
854 return array(
855 'parent_id' => $dao->parent_id,
856 'weight' => $dao->weight,
857 );
858 }
859
860 /**
861 * Update menu.
862 *
863 * @param array $params
864 * @param array $newParams
865 * New value of params.
866 */
867 public static function processUpdate($params, $newParams) {
868 $dao = new CRM_Core_DAO_Navigation();
869 $dao->copyValues($params);
870 if ($dao->find(TRUE)) {
871 $dao->copyValues($newParams);
872 $dao->save();
873 }
874 }
875
876 /**
877 * Rebuild reports menu.
878 *
879 * All Contact reports will become sub-items of 'Contact Reports' and so on.
880 *
881 * @param int $domain_id
882 */
883 public static function rebuildReportsNavigation($domain_id) {
884 $component_to_nav_name = array(
885 'CiviContact' => 'Contact Reports',
886 'CiviContribute' => 'Contribution Reports',
887 'CiviMember' => 'Membership Reports',
888 'CiviEvent' => 'Event Reports',
889 'CiviPledge' => 'Pledge Reports',
890 'CiviGrant' => 'Grant Reports',
891 'CiviMail' => 'Mailing Reports',
892 'CiviCampaign' => 'Campaign Reports',
893 );
894
895 // Create or update the top level Reports link.
896 $reports_nav = self::createOrUpdateTopLevelReportsNavItem($domain_id);
897
898 // Get all active report instances grouped by component.
899 $components = self::getAllActiveReportsByComponent($domain_id);
900 foreach ($components as $component_id => $component) {
901 // Create or update the per component reports links.
902 $component_nav_name = $component['name'];
903 if (isset($component_to_nav_name[$component_nav_name])) {
904 $component_nav_name = $component_to_nav_name[$component_nav_name];
905 }
906 $permission = "access {$component['name']}";
907 if ($component['name'] === 'CiviContact') {
908 $permission = "administer CiviCRM";
909 }
910 elseif ($component['name'] === 'CiviCampaign') {
911 $permission = "access CiviReport";
912 }
913 $component_nav = self::createOrUpdateReportNavItem($component_nav_name, 'civicrm/report/list',
914 "compid={$component_id}&reset=1", $reports_nav->id, $permission, $domain_id, TRUE);
915 foreach ($component['reports'] as $report_id => $report) {
916 // Create or update the report instance links.
917 $report_nav = self::createOrUpdateReportNavItem($report['title'], $report['url'], 'reset=1', $component_nav->id, $report['permission'], $domain_id);
918 // Update the report instance to include the navigation id.
919 $query = "UPDATE civicrm_report_instance SET navigation_id = %1 WHERE id = %2";
920 $params = array(
921 1 => array($report_nav->id, 'Integer'),
922 2 => array($report_id, 'Integer'),
923 );
924 CRM_Core_DAO::executeQuery($query, $params);
925 }
926 }
927
928 // Create or update the All Reports link.
929 self::createOrUpdateReportNavItem('All Reports', 'civicrm/report/list', 'reset=1', $reports_nav->id, 'access CiviReport', $domain_id);
930 }
931
932 /**
933 * Create the top level 'Reports' item in the navigation tree.
934 *
935 * @param int $domain_id
936 *
937 * @return bool|\CRM_Core_DAO
938 */
939 static public function createOrUpdateTopLevelReportsNavItem($domain_id) {
940 $id = NULL;
941
942 $dao = new CRM_Core_BAO_Navigation();
943 $dao->name = 'Reports';
944 $dao->domain_id = $domain_id;
945 // The first selectAdd clears it - so that we only retrieve the one field.
946 $dao->selectAdd();
947 $dao->selectAdd('id');
948 if ($dao->find(TRUE)) {
949 $id = $dao->id;
950 }
951
952 $nav = self::createReportNavItem('Reports', NULL, NULL, NULL, 'access CiviReport', $id, $domain_id);
953 return $nav;
954 }
955
956 /**
957 * Retrieve a navigation item using it's url.
958 *
959 * @param string $url
960 * @param array $url_params
961 *
962 * @param int|null $parent_id
963 * Optionally restrict to one parent.
964 *
965 * @return bool|\CRM_Core_BAO_Navigation
966 */
967 public static function getNavItemByUrl($url, $url_params, $parent_id = NULL) {
968 $nav = new CRM_Core_BAO_Navigation();
969 $nav->url = "{$url}?{$url_params}";
970 $nav->parent_id = $parent_id;
971 if ($nav->find(TRUE)) {
972 return $nav;
973 }
974 return FALSE;
975 }
976
977 /**
978 * Get all active reports, organised by component.
979 *
980 * @param int $domain_id
981 *
982 * @return array
983 */
984 public static function getAllActiveReportsByComponent($domain_id) {
985 $sql = "
986 SELECT
987 civicrm_report_instance.id, civicrm_report_instance.title, civicrm_report_instance.permission, civicrm_component.name, civicrm_component.id AS component_id
988 FROM
989 civicrm_option_group
990 LEFT JOIN
991 civicrm_option_value ON civicrm_option_value.option_group_id = civicrm_option_group.id AND civicrm_option_group.name = 'report_template'
992 LEFT JOIN
993 civicrm_report_instance ON civicrm_option_value.value = civicrm_report_instance.report_id
994 LEFT JOIN
995 civicrm_component ON civicrm_option_value.component_id = civicrm_component.id
996 WHERE
997 civicrm_option_value.is_active = 1
998 AND
999 civicrm_report_instance.domain_id = %1
1000 ORDER BY civicrm_option_value.weight";
1001
1002 $dao = CRM_Core_DAO::executeQuery($sql, array(
1003 1 => array($domain_id, 'Integer'),
1004 ));
1005 $rows = array();
1006 while ($dao->fetch()) {
1007 $component_name = is_null($dao->name) ? 'CiviContact' : $dao->name;
1008 $component_id = is_null($dao->component_id) ? 99 : $dao->component_id;
1009 $rows[$component_id]['name'] = $component_name;
1010 $rows[$component_id]['reports'][$dao->id] = array(
1011 'title' => $dao->title,
1012 'url' => "civicrm/report/instance/{$dao->id}",
1013 'permission' => $dao->permission,
1014 );
1015 }
1016 return $rows;
1017 }
1018
1019 /**
1020 * Create or update a navigation item for a report instance.
1021 *
1022 * The function will check whether create or update is required.
1023 *
1024 * @param string $name
1025 * @param string $url
1026 * @param string $url_params
1027 * @param int $parent_id
1028 * @param string $permission
1029 * @param int $domain_id
1030 *
1031 * @param bool $onlyMatchParentID
1032 * If True then do not match with a url that has a different parent
1033 * (This is because for top level items there is a risk of 'stealing' rows that normally
1034 * live under 'Contact' and intentionally duplicate the report examples.)
1035 *
1036 * @return \CRM_Core_DAO_Navigation
1037 */
1038 protected static function createOrUpdateReportNavItem($name, $url, $url_params, $parent_id, $permission,
1039 $domain_id, $onlyMatchParentID = FALSE) {
1040 $id = NULL;
1041 $existing_nav = CRM_Core_BAO_Navigation::getNavItemByUrl($url, $url_params, ($onlyMatchParentID ? $parent_id : NULL));
1042 if ($existing_nav) {
1043 $id = $existing_nav->id;
1044 }
1045
1046 $nav = self::createReportNavItem($name, $url, $url_params, $parent_id, $permission, $id, $domain_id);
1047 return $nav;
1048 }
1049
1050 /**
1051 * Create a navigation item for a report instance.
1052 *
1053 * @param string $name
1054 * @param string $url
1055 * @param string $url_params
1056 * @param int $parent_id
1057 * @param string $permission
1058 * @param int $id
1059 * @param int $domain_id
1060 * ID of domain to create item in.
1061 *
1062 * @return \CRM_Core_DAO_Navigation
1063 */
1064 public static function createReportNavItem($name, $url, $url_params, $parent_id, $permission, $id, $domain_id) {
1065 if ($url !== NULL) {
1066 $url = "{$url}?{$url_params}";
1067 }
1068 $params = array(
1069 'name' => $name,
1070 'label' => ts($name),
1071 'url' => $url,
1072 'parent_id' => $parent_id,
1073 'is_active' => TRUE,
1074 'permission' => array(
1075 $permission,
1076 ),
1077 'domain_id' => $domain_id,
1078 );
1079 if ($id) {
1080 $params['id'] = $id;
1081 }
1082 return CRM_Core_BAO_Navigation::add($params);
1083 }
1084
1085 /**
1086 * Get cache key.
1087 *
1088 * @param int $cid
1089 *
1090 * @return object|string
1091 */
1092 public static function getCacheKey($cid) {
1093 $key = CRM_Core_BAO_Setting::getItem(
1094 CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME,
1095 'navigation',
1096 NULL,
1097 '',
1098 $cid
1099 );
1100 if (strlen($key) !== self::CACHE_KEY_STRLEN) {
1101 $key = self::resetNavigation($cid);
1102 }
1103 return $key;
1104 }
1105
1106 }