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