3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Core_BAO_Navigation
extends CRM_Core_DAO_Navigation
{
19 // Number of characters in the menu js cache key
20 const CACHE_KEY_STRLEN
= 8;
23 * Update the is_active flag in the db.
26 * Id of the database record.
27 * @param bool $is_active
28 * Value we want to set the is_active field.
31 * true if we found and updated the object, else false
33 public static function setIsActive($id, $is_active) {
34 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $id, 'is_active', $is_active);
38 * Deprecated in favor of APIv4
41 * @param array $params Submitted values
42 * @return CRM_Core_DAO_Navigation
44 public static function add(&$params) {
45 $navigation = new CRM_Core_DAO_Navigation();
46 if (empty($params['id'])) {
47 $params['is_active'] = CRM_Utils_Array
::value('is_active', $params, FALSE);
48 $params['has_separator'] = CRM_Utils_Array
::value('has_separator', $params, FALSE);
49 $params['domain_id'] = CRM_Utils_Array
::value('domain_id', $params, CRM_Core_Config
::domainID());
52 if (!isset($params['id']) ||
53 (CRM_Utils_Array
::value('parent_id', $params) != CRM_Utils_Array
::value('current_parent_id', $params))
55 /* re/calculate the weight, if the Parent ID changed OR create new menu */
57 if ($navName = CRM_Utils_Array
::value('name', $params)) {
58 $params['name'] = $navName;
60 elseif ($navLabel = CRM_Utils_Array
::value('label', $params)) {
61 $params['name'] = $navLabel;
64 $params['weight'] = self
::calculateWeight(CRM_Utils_Array
::value('parent_id', $params));
67 if (array_key_exists('permission', $params) && is_array($params['permission'])) {
68 $params['permission'] = implode(',', $params['permission']);
71 $navigation->copyValues($params);
78 * Retrieve DB object and copy to defaults array.
80 * @param array $params
81 * Array of criteria values.
82 * @param array $defaults
83 * Array to be populated with found values.
86 * The DAO object, if found.
90 public static function retrieve($params, &$defaults) {
91 $params['domain_id'] = CRM_Core_Config
::domainID();
92 return self
::commonRetrieve(self
::class, $params, $defaults);
96 * Calculate navigation weight.
98 * @param int $parentID
99 * Parent_id of a menu.
106 public static function calculateWeight($parentID = NULL, $menuID = NULL) {
107 $domainID = CRM_Core_Config
::domainID();
110 // we reset weight for each parent, i.e we start from 1 to n
111 // calculate max weight for top level menus, if parent id is absent
113 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id IS NULL AND domain_id = $domainID";
116 // if parent is passed, we need to get max weight for that particular parent
117 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id = {$parentID} AND domain_id = $domainID";
120 $dao = CRM_Core_DAO
::executeQuery($query);
122 return $weight = $weight +
$dao->weight
;
126 * Get formatted menu list.
129 * returns associated array
131 public static function getNavigationList() {
132 $cacheKeyString = "navigationList_" . CRM_Core_Config
::domainID();
135 $config = CRM_Core_Config
::singleton();
137 // check if we can retrieve from database cache
138 $navigations = Civi
::cache('navigation')->get($cacheKeyString);
141 $domainID = CRM_Core_Config
::domainID();
143 SELECT id, label, parent_id, weight, is_active, name
144 FROM civicrm_navigation WHERE domain_id = $domainID";
145 $result = CRM_Core_DAO
::executeQuery($query);
148 while ($result->fetch()) {
149 $pidGroups[$result->parent_id
][$result->label
] = $result->id
;
152 foreach ($pidGroups[''] as $label => $val) {
153 $pidGroups[''][$label] = self
::_getNavigationValue($val, $pidGroups);
157 self
::_getNavigationLabel($pidGroups[''], $navigations);
159 Civi
::cache('navigation')->set($cacheKeyString, $navigations);
165 * Helper function for getNavigationList().
169 * @param array $navigations
171 * @param string $separator
174 public static function _getNavigationLabel($list, &$navigations, $separator = '') {
175 $i18n = CRM_Core_I18n
::singleton();
176 foreach ($list as $label => $val) {
177 if ($label == 'navigation_id') {
180 $translatedLabel = $i18n->crm_translate($label, ['context' => 'menu']);
181 $navigations[is_array($val) ?
$val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
182 if (is_array($val)) {
183 self
::_getNavigationLabel($val, $navigations, $separator . ' ');
189 * Helper function for getNavigationList().
193 * @param array $pidGroups
198 public static function _getNavigationValue($val, &$pidGroups) {
199 if (array_key_exists($val, $pidGroups)) {
200 $list = ['navigation_id' => $val];
201 foreach ($pidGroups[$val] as $label => $id) {
202 $list[$label] = self
::_getNavigationValue($id, $pidGroups);
204 unset($pidGroups[$val]);
213 * Build navigation tree.
216 * nested array of menus
218 public static function buildNavigationTree() {
219 $domainID = CRM_Core_Config
::domainID();
220 $navigationTree = [];
222 $navigationMenu = new self();
223 $navigationMenu->domain_id
= $domainID;
224 $navigationMenu->orderBy('parent_id, weight');
225 $navigationMenu->find();
227 while ($navigationMenu->fetch()) {
228 $navigationTree[$navigationMenu->id
] = [
230 'label' => $navigationMenu->label
,
231 'name' => $navigationMenu->name
,
232 'url' => $navigationMenu->url
,
233 'icon' => $navigationMenu->icon
,
234 'weight' => $navigationMenu->weight
,
235 'permission' => $navigationMenu->permission
,
236 'operator' => $navigationMenu->permission_operator
,
237 'separator' => $navigationMenu->has_separator
,
238 'parentID' => $navigationMenu->parent_id
,
239 'navID' => $navigationMenu->id
,
240 'active' => $navigationMenu->is_active
,
245 return self
::buildTree($navigationTree);
249 * Convert flat array to nested.
251 * @param array $elements
252 * @param int|null $parentId
256 private static function buildTree($elements, $parentId = NULL) {
259 foreach ($elements as $id => $element) {
260 if ($element['attributes']['parentID'] == $parentId) {
261 $children = self
::buildTree($elements, $id);
263 $element['child'] = $children;
265 $branch[$id] = $element;
273 * buildNavigationTree retreives items in order. We call this function to
274 * ensure that any items added by the hook are also in the correct order.
276 public static function orderByWeight(&$navigations) {
277 // sort each item in navigations by weight
278 usort($navigations, function($a, $b) {
280 // If no weight have been defined for an item put it at the end of the list
281 if (!isset($a['attributes']['weight'])) {
282 $a['attributes']['weight'] = 1000;
284 if (!isset($b['attributes']['weight'])) {
285 $b['attributes']['weight'] = 1000;
287 return $a['attributes']['weight'] - $b['attributes']['weight'];
290 // If any of the $navigations have children, recurse
291 foreach ($navigations as &$navigation) {
292 if (isset($navigation['child'])) {
293 self
::orderByWeight($navigation['child']);
299 * Given a navigation menu, generate navIDs for any items which are
302 * @param array $nodes
303 * Each key is a numeral; each value is a node in
304 * the menu tree (with keys "child" and "attributes").
306 public static function fixNavigationMenu(&$nodes) {
308 array_walk_recursive($nodes, function($item, $key) use (&$maxNavID) {
309 if ($key === 'navID') {
310 $maxNavID = max($maxNavID, $item);
313 self
::_fixNavigationMenu($nodes, $maxNavID, NULL);
317 * @param array $nodes
318 * Each key is a numeral; each value is a node in
319 * the menu tree (with keys "child" and "attributes").
320 * @param int $maxNavID
321 * @param int $parentID
323 private static function _fixNavigationMenu(&$nodes, &$maxNavID, $parentID) {
324 $origKeys = array_keys($nodes);
325 foreach ($origKeys as $origKey) {
326 if (!isset($nodes[$origKey]['attributes']['parentID']) && $parentID !== NULL) {
327 $nodes[$origKey]['attributes']['parentID'] = $parentID;
329 // If no navID, then assign navID and fix key.
330 if (!isset($nodes[$origKey]['attributes']['navID'])) {
331 $newKey = ++
$maxNavID;
332 $nodes[$origKey]['attributes']['navID'] = $newKey;
333 if ($origKey != $newKey) {
334 // If the keys are different, reset the array index to match.
335 $nodes[$newKey] = $nodes[$origKey];
336 unset($nodes[$origKey]);
340 if (isset($nodes[$origKey]['child']) && is_array($nodes[$origKey]['child'])) {
341 self
::_fixNavigationMenu($nodes[$origKey]['child'], $maxNavID, $nodes[$origKey]['attributes']['navID']);
347 * Check if a menu item should be visible based on permissions and component.
352 public static function checkPermission($item) {
353 if (!empty($item['permission'])) {
354 $permissions = explode(',', $item['permission']);
355 $operator = $item['operator'] ??
NULL;
356 $hasPermission = FALSE;
357 foreach ($permissions as $key) {
361 //get the component name from permission.
362 $componentName = CRM_Core_Permission
::getComponentName($key);
364 if ($componentName) {
365 if (!CRM_Core_Component
::isEnabled($componentName) ||
!CRM_Core_Permission
::check($key)) {
367 if ($operator == 'AND') {
372 $hasPermission = TRUE;
375 elseif (!CRM_Core_Permission
::check($key)) {
377 if ($operator == 'AND') {
382 $hasPermission = TRUE;
386 if (empty($showItem) && !$hasPermission) {
394 * Turns relative URLs (like civicrm/foo/bar) into fully-formed
395 * ones (i.e. example.com/wp-admin?q=civicrm/dashboard).
397 * If the URL is already fully-formed, nothing will be done.
403 public static function makeFullyFormedUrl($url) {
404 if (self
::isNotFullyFormedUrl($url)) {
405 //CRM-7656 --make sure to separate out url path from url params,
406 //as we'r going to validate url path across cross-site scripting.
407 $path = parse_url($url, PHP_URL_PATH
);
408 $q = parse_url($url, PHP_URL_QUERY
);
409 $fragment = parse_url($url, PHP_URL_FRAGMENT
);
410 return CRM_Utils_System
::url($path, $q, FALSE, $fragment);
413 if (strpos($url, '&') === FALSE) {
414 return htmlspecialchars($url);
421 * Checks if the given URL is not fully-formed
427 private static function isNotFullyFormedUrl($url) {
428 return substr($url, 0, 4) !== 'http' && $url[0] !== '/' && $url[0] !== '#';
432 * Reset navigation for all contacts or a specified contact.
434 * @param int $contactID
435 * Reset only entries belonging to that contact ID.
439 public static function resetNavigation($contactID = NULL) {
440 $newKey = CRM_Utils_String
::createRandom(self
::CACHE_KEY_STRLEN
, CRM_Utils_String
::ALPHANUMERIC
);
442 $ser = serialize($newKey);
443 $query = "UPDATE civicrm_setting SET value = '$ser' WHERE name='navigation' AND contact_id IS NOT NULL";
444 CRM_Core_DAO
::executeQuery($query);
445 Civi
::cache('navigation')->flush();
446 // reset ACL and System caches
447 CRM_Core_BAO_Cache
::resetCaches();
450 // before inserting check if contact id exists in db
451 // this is to handle weird case when contact id is in session but not in db
452 $contact = new CRM_Contact_DAO_Contact();
453 $contact->id
= $contactID;
454 if ($contact->find(TRUE)) {
455 Civi
::contactSettings($contactID)->set('navigation', $newKey);
463 * Process navigation.
465 * @param array $params
466 * Associated array, $_GET.
468 public static function processNavigation(&$params) {
469 $nodeID = (int) str_replace("node_", "", $params['id']);
470 $referenceID = (int) str_replace("node_", "", $params['ref_id']);
471 $position = $params['ps'];
472 $type = $params['type'];
473 $label = $params['data'] ??
NULL;
477 self
::processMove($nodeID, $referenceID, $position);
481 self
::processRename($nodeID, $label);
485 self
::processDelete($nodeID);
489 //reset navigation menus
490 self
::resetNavigation();
491 CRM_Utils_System
::civiExit();
495 * Process move action.
498 * Node that is being moved.
499 * @param $referenceID
500 * Parent id where node is moved. 0 mean no parent.
502 * New position of the nod, it starts with 0 - n.
504 public static function processMove($nodeID, $referenceID, $position) {
505 // based on the new position we need to get the weight of the node after moved node
506 // 1. update the weight of $position + 1 nodes to weight + 1
507 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
509 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
510 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
511 // accordingly set the new parent_id
513 $newParentID = $referenceID;
514 $parentClause = "parent_id = {$referenceID} ";
517 $newParentID = 'NULL';
518 $parentClause = 'parent_id IS NULL';
521 $incrementOtherNodes = TRUE;
522 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
523 $params = [1 => [$position, 'Positive']];
524 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
526 // this means node is moved to last position, so you need to get the weight of last element + 1
528 // If this is not the first item being added to a parent
530 $lastPosition = $position - 1;
531 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
532 $params = [1 => [$lastPosition, 'Positive']];
533 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
535 // since last node increment + 1
536 $newWeight = $newWeight +
1;
542 // since this is a last node we don't need to increment other nodes
543 $incrementOtherNodes = FALSE;
546 $transaction = new CRM_Core_Transaction();
548 // now update the existing nodes to weight + 1, if required.
549 if ($incrementOtherNodes) {
550 $query = "UPDATE civicrm_navigation SET weight = weight + 1
551 WHERE {$parentClause} AND weight >= {$newWeight}";
553 CRM_Core_DAO
::executeQuery($query);
556 // finally set the weight of current node
557 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
558 CRM_Core_DAO
::executeQuery($query);
560 $transaction->commit();
564 * Function to process rename action for tree.
569 public static function processRename($nodeID, $label) {
570 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
574 * Process delete action for tree.
578 public static function processDelete($nodeID) {
579 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
580 CRM_Core_DAO
::executeQuery($query);
586 * @param array $params
587 * @param array $newParams
588 * New value of params.
590 public static function processUpdate($params, $newParams) {
591 $dao = new CRM_Core_DAO_Navigation();
592 $dao->copyValues($params);
593 if ($dao->find(TRUE)) {
594 $dao->copyValues($newParams);
600 * Rebuild reports menu.
602 * All Contact reports will become sub-items of 'Contact Reports' and so on.
604 * @param int $domain_id
606 public static function rebuildReportsNavigation($domain_id) {
607 $component_to_nav_name = [
608 'CiviContact' => 'Contact Reports',
609 'CiviContribute' => 'Contribution Reports',
610 'CiviMember' => 'Membership Reports',
611 'CiviEvent' => 'Event Reports',
612 'CiviPledge' => 'Pledge Reports',
613 'CiviGrant' => 'Grant Reports',
614 'CiviMail' => 'Mailing Reports',
615 'CiviCampaign' => 'Campaign Reports',
618 // Create or update the top level Reports link.
619 $reports_nav = self
::createOrUpdateTopLevelReportsNavItem($domain_id);
621 // Get all active report instances grouped by component.
622 $components = self
::getAllActiveReportsByComponent($domain_id);
623 foreach ($components as $component_id => $component) {
624 // Create or update the per component reports links.
625 $component_nav_name = $component['name'];
626 if (isset($component_to_nav_name[$component_nav_name])) {
627 $component_nav_name = $component_to_nav_name[$component_nav_name];
629 $permission = "access {$component['name']}";
630 if ($component['name'] === 'CiviContact') {
631 $permission = "administer CiviCRM";
633 elseif ($component['name'] === 'CiviCampaign') {
634 $permission = "access CiviReport";
636 $component_nav = self
::createOrUpdateReportNavItem($component_nav_name, 'civicrm/report/list',
637 "compid={$component_id}&reset=1", $reports_nav->id
, $permission, $domain_id, TRUE);
638 foreach ($component['reports'] as $report_id => $report) {
639 // Create or update the report instance links.
640 $report_nav = self
::createOrUpdateReportNavItem($report['title'], $report['url'], 'reset=1', $component_nav->id
, $report['permission'], $domain_id, FALSE, TRUE);
641 // Update the report instance to include the navigation id.
642 $query = "UPDATE civicrm_report_instance SET navigation_id = %1 WHERE id = %2";
644 1 => [$report_nav->id
, 'Integer'],
645 2 => [$report_id, 'Integer'],
647 CRM_Core_DAO
::executeQuery($query, $params);
651 // Create or update the All Reports link.
652 self
::createOrUpdateReportNavItem('All Reports', 'civicrm/report/list', 'reset=1', $reports_nav->id
, 'access CiviReport', $domain_id, TRUE);
653 // Create or update the My Reports link.
654 self
::createOrUpdateReportNavItem('My Reports', 'civicrm/report/list', 'myreports=1&reset=1', $reports_nav->id
, 'access CiviReport', $domain_id, TRUE);
659 * Create the top level 'Reports' item in the navigation tree.
661 * @param int $domain_id
663 * @return bool|\CRM_Core_DAO
665 public static function createOrUpdateTopLevelReportsNavItem($domain_id) {
668 $dao = new CRM_Core_BAO_Navigation();
669 $dao->name
= 'Reports';
670 $dao->domain_id
= $domain_id;
671 // The first selectAdd clears it - so that we only retrieve the one field.
673 $dao->selectAdd('id');
674 if ($dao->find(TRUE)) {
678 $nav = self
::createReportNavItem('Reports', NULL, NULL, NULL, 'access CiviReport', $id, $domain_id);
683 * Retrieve a navigation item using it's url.
685 * Note that we use LIKE to permit a wildcard as the calling code likely doesn't
686 * care about output params appended.
689 * @param string $url_params
691 * @param int|null $parent_id
692 * Optionally restrict to one parent.
694 * @return bool|\CRM_Core_BAO_Navigation
696 public static function getNavItemByUrl($url, $url_params, $parent_id = NULL) {
697 $nav = new CRM_Core_BAO_Navigation();
698 $nav->parent_id
= $parent_id;
699 $nav->whereAdd("url LIKE '{$url}?{$url_params}'");
701 if ($nav->find(TRUE)) {
708 * Get all active reports, organised by component.
710 * @param int $domain_id
714 public static function getAllActiveReportsByComponent($domain_id) {
717 civicrm_report_instance.id, civicrm_report_instance.title, civicrm_report_instance.permission, civicrm_component.name, civicrm_component.id AS component_id
721 civicrm_option_value ON civicrm_option_value.option_group_id = civicrm_option_group.id AND civicrm_option_group.name = 'report_template'
723 civicrm_report_instance ON civicrm_option_value.value = civicrm_report_instance.report_id
725 civicrm_component ON civicrm_option_value.component_id = civicrm_component.id
727 civicrm_option_value.is_active = 1
729 civicrm_report_instance.domain_id = %1
730 ORDER BY civicrm_option_value.weight";
732 $dao = CRM_Core_DAO
::executeQuery($sql, [
733 1 => [$domain_id, 'Integer'],
736 while ($dao->fetch()) {
737 $component_name = is_null($dao->name
) ?
'CiviContact' : $dao->name
;
738 $component_id = is_null($dao->component_id
) ?
99 : $dao->component_id
;
739 $rows[$component_id]['name'] = $component_name;
740 $rows[$component_id]['reports'][$dao->id
] = [
741 'title' => $dao->title
,
742 'url' => "civicrm/report/instance/{$dao->id}",
743 'permission' => $dao->permission
,
750 * Create or update a navigation item for a report instance.
752 * The function will check whether create or update is required.
754 * @param string $name
756 * @param string $url_params
757 * @param int $parent_id
758 * @param string $permission
759 * @param int $domain_id
761 * @param bool $onlyMatchParentID
762 * If True then do not match with a url that has a different parent
763 * (This is because for top level items there is a risk of 'stealing' rows that normally
764 * live under 'Contact' and intentionally duplicate the report examples.)
765 * @param bool $useWildcard
766 * @return \CRM_Core_DAO_Navigation
768 protected static function createOrUpdateReportNavItem($name, $url, $url_params, $parent_id, $permission,
769 $domain_id, $onlyMatchParentID = FALSE, $useWildcard = TRUE) {
771 $existing_url_params = $useWildcard ?
$url_params . '%' : $url_params;
772 $existing_nav = CRM_Core_BAO_Navigation
::getNavItemByUrl($url, $existing_url_params, ($onlyMatchParentID ?
$parent_id : NULL));
774 $id = $existing_nav->id
;
777 $nav = self
::createReportNavItem($name, $url, $url_params, $parent_id, $permission, $id, $domain_id);
782 * Create a navigation item for a report instance.
784 * @param string $name
786 * @param string $url_params
787 * @param int $parent_id
788 * @param string $permission
790 * @param int $domain_id
791 * ID of domain to create item in.
793 * @return \CRM_Core_DAO_Navigation
795 public static function createReportNavItem($name, $url, $url_params, $parent_id, $permission, $id, $domain_id) {
797 $url = "{$url}?{$url_params}";
801 'label' => ts($name),
803 'parent_id' => $parent_id,
808 'domain_id' => $domain_id,
813 return CRM_Core_BAO_Navigation
::add($params);
821 * @return object|string
823 public static function getCacheKey($cid) {
824 $key = Civi
::service('settings_manager')
825 ->getBagByContact(NULL, $cid)
827 if (strlen($key) !== self
::CACHE_KEY_STRLEN
) {
828 $key = self
::resetNavigation($cid);
834 * Unset menu items for disabled components and non-permissioned users
838 public static function filterByPermission(&$menu) {
839 foreach ($menu as $key => $item) {
841 (array_key_exists('active', $item['attributes']) && !$item['attributes']['active']) ||
842 !CRM_Core_BAO_Navigation
::checkPermission($item['attributes'])
847 if (!empty($item['child'])) {
848 self
::filterByPermission($menu[$key]['child']);
856 public static function buildHomeMenu(&$menu) {
857 foreach ($menu as &$item) {
858 if (CRM_Utils_Array
::value('name', $item['attributes']) === 'Home') {
859 unset($item['attributes']['label'], $item['attributes']['url']);
860 $item['attributes']['icon'] = 'crm-logo-sm';
861 $item['attributes']['attr']['accesskey'] = 'm';
865 'label' => 'CiviCRM Home',
866 'name' => 'CiviCRM Home',
867 'url' => 'civicrm/dashboard?reset=1',
873 'label' => 'Hide Menu',
874 'name' => 'Hide Menu',
875 'url' => '#hidemenu',
881 'label' => 'Log out',
883 'url' => 'civicrm/logout?reset=1',