3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
35 class CRM_Core_BAO_Navigation
extends CRM_Core_DAO_Navigation
{
37 // Number of characters in the menu js cache key
38 const CACHE_KEY_STRLEN
= 8;
43 public function __construct() {
44 parent
::__construct();
48 * Update the is_active flag in the db.
51 * Id of the database record.
52 * @param bool $is_active
53 * Value we want to set the is_active field.
55 * @return CRM_Core_DAO_Navigation|NULL
56 * DAO object on success, NULL otherwise
58 public static function setIsActive($id, $is_active) {
59 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $id, 'is_active', $is_active);
63 * Get existing / build navigation for CiviCRM Admin Menu.
68 public static function getMenus() {
71 $menu = new CRM_Core_DAO_Menu();
72 $menu->domain_id
= CRM_Core_Config
::domainID();
75 while ($menu->fetch()) {
77 $menus[$menu->path
] = $menu->title
;
84 * Add/update navigation record.
86 * @param array $params Submitted values
88 * @return CRM_Core_DAO_Navigation
91 public static function add(&$params) {
92 $navigation = new CRM_Core_DAO_Navigation();
94 $params['is_active'] = CRM_Utils_Array
::value('is_active', $params, FALSE);
95 $params['has_separator'] = CRM_Utils_Array
::value('has_separator', $params, FALSE);
97 if (!isset($params['id']) ||
98 (CRM_Utils_Array
::value('parent_id', $params) != CRM_Utils_Array
::value('current_parent_id', $params))
100 /* re/calculate the weight, if the Parent ID changed OR create new menu */
102 if ($navName = CRM_Utils_Array
::value('name', $params)) {
103 $params['name'] = $navName;
105 elseif ($navLabel = CRM_Utils_Array
::value('label', $params)) {
106 $params['name'] = $navLabel;
109 $params['weight'] = self
::calculateWeight(CRM_Utils_Array
::value('parent_id', $params));
112 if (array_key_exists('permission', $params) && is_array($params['permission'])) {
113 $params['permission'] = implode(',', $params['permission']);
116 $navigation->copyValues($params);
118 $navigation->domain_id
= CRM_Core_Config
::domainID();
125 * Fetch object based on array of properties.
127 * @param array $params
128 * (reference ) an assoc array of name/value pairs.
129 * @param array $defaults
130 * (reference ) an assoc array to hold the flattened values.
132 * @return CRM_Core_BAO_Navigation|null
133 * object on success, NULL otherwise
135 public static function retrieve(&$params, &$defaults) {
136 $navigation = new CRM_Core_DAO_Navigation();
137 $navigation->copyValues($params);
139 $navigation->domain_id
= CRM_Core_Config
::domainID();
141 if ($navigation->find(TRUE)) {
142 CRM_Core_DAO
::storeValues($navigation, $defaults);
149 * Calculate navigation weight.
151 * @param int $parentID
152 * Parent_id of a menu.
159 public static function calculateWeight($parentID = NULL, $menuID = NULL) {
160 $domainID = CRM_Core_Config
::domainID();
163 // we reset weight for each parent, i.e we start from 1 to n
164 // calculate max weight for top level menus, if parent id is absent
166 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id IS NULL AND domain_id = $domainID";
169 // if parent is passed, we need to get max weight for that particular parent
170 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id = {$parentID} AND domain_id = $domainID";
173 $dao = CRM_Core_DAO
::executeQuery($query);
175 return $weight = $weight +
$dao->weight
;
179 * Get formatted menu list.
182 * returns associated array
184 public static function getNavigationList() {
185 $cacheKeyString = "navigationList";
188 $config = CRM_Core_Config
::singleton();
190 // check if we can retrieve from database cache
191 $navigations = CRM_Core_BAO_Cache
::getItem('navigation', $cacheKeyString);
194 $domainID = CRM_Core_Config
::domainID();
196 SELECT id, label, parent_id, weight, is_active, name
197 FROM civicrm_navigation WHERE domain_id = $domainID {$whereClause} ORDER BY parent_id, weight ASC";
198 $result = CRM_Core_DAO
::executeQuery($query);
200 $pidGroups = array();
201 while ($result->fetch()) {
202 $pidGroups[$result->parent_id
][$result->label
] = $result->id
;
205 foreach ($pidGroups[''] as $label => $val) {
206 $pidGroups[''][$label] = self
::_getNavigationValue($val, $pidGroups);
209 $navigations = array();
210 self
::_getNavigationLabel($pidGroups[''], $navigations);
212 CRM_Core_BAO_Cache
::setItem($navigations, 'navigation', $cacheKeyString);
218 * Helper function for getNavigationList().
222 * @param array $navigations
224 * @param string $separator
227 public static function _getNavigationLabel($list, &$navigations, $separator = '') {
228 $i18n = CRM_Core_I18n
::singleton();
229 foreach ($list as $label => $val) {
230 if ($label == 'navigation_id') {
233 $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
234 $navigations[is_array($val) ?
$val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
235 if (is_array($val)) {
236 self
::_getNavigationLabel($val, $navigations, $separator . ' ');
242 * Helper function for getNavigationList().
246 * @param array $pidGroups
251 public static function _getNavigationValue($val, &$pidGroups) {
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);
257 unset($pidGroups[$val]);
266 * Build navigation tree.
268 * @param array $navigationTree
269 * Nested array of menus.
270 * @param int $parentID
272 * @param bool $navigationMenu
273 * True when called for building top navigation menu.
276 * nested array of menus
278 public static function buildNavigationTree(&$navigationTree, $parentID, $navigationMenu = TRUE) {
279 $whereClause = " parent_id IS NULL";
282 $whereClause = " parent_id = {$parentID}";
285 $domainID = CRM_Core_Config
::domainID();
287 // get the list of menus
289 SELECT id, label, url, permission, permission_operator, has_separator, parent_id, is_active, name
290 FROM civicrm_navigation
292 AND domain_id = $domainID
293 ORDER BY parent_id, weight";
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, '"');
303 // for each menu get their children
304 $navigationTree[$navigation->id
] = array(
305 'attributes' => array(
307 'name' => $navigation->name
,
308 'url' => $navigation->url
,
309 'permission' => $navigation->permission
,
310 'operator' => $navigation->permission_operator
,
311 'separator' => $navigation->has_separator
,
312 'parentID' => $navigation->parent_id
,
313 'navID' => $navigation->id
,
314 'active' => $navigation->is_active
,
317 self
::buildNavigationTree($navigationTree[$navigation->id
]['child'], $navigation->id
, $navigationMenu);
320 return $navigationTree;
327 * By default output is html.
328 * @param bool $navigationMenu
329 * True when called for building top navigation menu.
332 * html or json string
334 public static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
335 $navigations = array();
336 self
::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
337 $navigationString = NULL;
339 // run the Navigation through a hook so users can modify it
340 CRM_Utils_Hook
::navigationMenu($navigations);
342 $i18n = CRM_Core_I18n
::singleton();
344 //skip children menu item if user don't have access to parent menu item
345 $skipMenuItems = array();
346 foreach ($navigations as $key => $value) {
348 if ($navigationString) {
349 $navigationString .= '},';
351 $data = $value['attributes']['label'];
353 if (!$value['attributes']['active']) {
354 $class = ', "attr": { "class" : "disabled"} ';
356 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
357 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
360 // Home is a special case
361 if ($value['attributes']['name'] != 'Home') {
362 $name = self
::getMenuName($value, $skipMenuItems);
365 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
366 $navigationString .= '<li class="menu-separator"></li>';
368 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
369 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
374 self
::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
378 $navigationString = '[' . $navigationString . '}]';
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);
386 return $navigationString;
390 * Recursively check child menus.
392 * @param array $value
393 * @param string $navigationString
395 * @param bool $skipMenuItems
399 public static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
401 if (!empty($value['child'])) {
402 $navigationString .= ', "children": [ ';
405 return $navigationString;
408 if (!empty($value['child'])) {
411 foreach ($value['child'] as $k => $val) {
412 if ($count == count($value['child'])) {
413 $appendComma = FALSE;
415 $data = $val['attributes']['label'];
417 if (!$val['attributes']['active']) {
418 $class = ', "attr": { "class" : "disabled"} ';
420 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
421 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
422 $navigationString .= $appendComma ?
' },' : ' }';
427 if (!empty($value['child'])) {
428 $navigationString .= ' ]';
432 if (!empty($value['child'])) {
433 $navigationString .= '<ul>';
436 $navigationString .= '</li>';
437 //locate separator after
438 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
439 $navigationString .= '<li class="menu-separator"></li>';
443 if (!empty($value['child'])) {
444 foreach ($value['child'] as $val) {
445 $name = self
::getMenuName($val, $skipMenuItems);
447 //locate separator before
448 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
449 $navigationString .= '<li class="menu-separator"></li>';
451 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
452 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
453 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
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>';
464 return $navigationString;
471 * @param array $skipMenuItems
473 * @return bool|string
475 public static function getMenuName(&$value, &$skipMenuItems) {
476 // we need to localise the menu labels (CRM-5456) and don’t
477 // want to use ts() as it would throw the ts-extractor off
478 $i18n = CRM_Core_I18n
::singleton();
480 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
481 $url = CRM_Utils_Array
::value('url', $value['attributes']);
482 $permission = CRM_Utils_Array
::value('permission', $value['attributes']);
483 $operator = CRM_Utils_Array
::value('operator', $value['attributes']);
484 $parentID = CRM_Utils_Array
::value('parentID', $value['attributes']);
485 $navID = CRM_Utils_Array
::value('navID', $value['attributes']);
486 $active = CRM_Utils_Array
::value('active', $value['attributes']);
487 $menuName = CRM_Utils_Array
::value('name', $value['attributes']);
488 $target = CRM_Utils_Array
::value('target', $value['attributes']);
490 if (in_array($parentID, $skipMenuItems) ||
!$active) {
491 $skipMenuItems[] = $navID;
495 //we need to check core view/edit or supported acls.
496 if (in_array($menuName, array(
500 if (!CRM_Core_Permission
::giveMeAllACLs()) {
501 $skipMenuItems[] = $navID;
506 $config = CRM_Core_Config
::singleton();
509 if (isset($url) && $url) {
510 if (substr($url, 0, 4) !== 'http') {
511 //CRM-7656 --make sure to separate out url path from url params,
512 //as we'r going to validate url path across cross-site scripting.
513 $urlParam = explode('?', $url);
514 if (empty($urlParam[1])) {
517 $url = CRM_Utils_System
::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
522 static $allComponents;
523 if (!$allComponents) {
524 $allComponents = CRM_Core_Component
::getNames();
527 if (isset($permission) && $permission) {
528 $permissions = explode(',', $permission);
530 $hasPermission = FALSE;
531 foreach ($permissions as $key) {
535 //get the component name from permission.
536 $componentName = CRM_Core_Permission
::getComponentName($key);
538 if ($componentName) {
539 if (!in_array($componentName, $config->enableComponents
) ||
540 !CRM_Core_Permission
::check($key)
543 if ($operator == 'AND') {
544 $skipMenuItems[] = $navID;
549 $hasPermission = TRUE;
552 elseif (!CRM_Core_Permission
::check($key)) {
554 if ($operator == 'AND') {
555 $skipMenuItems[] = $navID;
560 $hasPermission = TRUE;
564 if (!$showItem && !$hasPermission) {
565 $skipMenuItems[] = $navID;
572 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
575 $name = "<a href=\"{$url}\">{$name}</a>";
583 * Create navigation for CiviCRM Admin Menu.
585 * @param int $contactID
589 * returns navigation html
591 public static function createNavigation($contactID) {
592 $config = CRM_Core_Config
::singleton();
594 $navigation = self
::buildNavigation();
598 //add additional navigation items
599 $logoutURL = CRM_Utils_System
::url('civicrm/logout', 'reset=1');
601 // get home menu from db
602 $homeParams = array('name' => 'Home');
604 $homeIcon = '<span class="crm-logo-sm" ></span>';
605 self
::retrieve($homeParams, $homeNav);
607 list($path, $q) = explode('?', $homeNav['url']);
608 $homeURL = CRM_Utils_System
::url($path, $q);
609 $homeLabel = $homeNav['label'];
610 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
611 if ($homeLabel == 'Home') {
612 $homeLabel = ts('CiviCRM Home');
616 $homeURL = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
617 $homeLabel = ts('CiviCRM Home');
619 // Link to hide the menubar
620 $hideLabel = ts('Hide Menu');
623 <li class='menumain crm-link-home'>$homeIcon
624 <ul id='civicrm-home'>
625 <li><a href='$homeURL'>$homeLabel</a></li>
626 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
627 <li><a href='$logoutURL' class='crm-logout-link'>" . ts('Log out') . "</a></li>
629 // <li> tag doesn't need to be closed
631 return $prepandString . $navigation;
635 * Reset navigation for all contacts or a specified contact.
637 * @param int $contactID
638 * Reset only entries belonging to that contact ID.
642 public static function resetNavigation($contactID = NULL) {
643 $newKey = CRM_Utils_String
::createRandom(self
::CACHE_KEY_STRLEN
, CRM_Utils_String
::ALPHANUMERIC
);
645 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
646 CRM_Core_DAO
::executeQuery($query);
647 CRM_Core_BAO_Cache
::deleteGroup('navigation');
650 // before inserting check if contact id exists in db
651 // this is to handle weird case when contact id is in session but not in db
652 $contact = new CRM_Contact_DAO_Contact();
653 $contact->id
= $contactID;
654 if ($contact->find(TRUE)) {
655 CRM_Core_BAO_Setting
::setItem(
657 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
665 // also reset the dashlet cache in case permissions have changed etc
666 // FIXME: decouple this
667 CRM_Core_BAO_Dashboard
::resetDashletCache($contactID);
673 * Process navigation.
675 * @param array $params
676 * Associated array, $_GET.
678 public static function processNavigation(&$params) {
679 $nodeID = (int) str_replace("node_", "", $params['id']);
680 $referenceID = (int) str_replace("node_", "", $params['ref_id']);
681 $position = $params['ps'];
682 $type = $params['type'];
683 $label = CRM_Utils_Array
::value('data', $params);
687 self
::processMove($nodeID, $referenceID, $position);
691 self
::processRename($nodeID, $label);
695 self
::processDelete($nodeID);
699 //reset navigation menus
700 self
::resetNavigation();
701 CRM_Utils_System
::civiExit();
705 * Process move action.
708 * Node that is being moved.
709 * @param $referenceID
710 * Parent id where node is moved. 0 mean no parent.
712 * New position of the nod, it starts with 0 - n.
714 public static function processMove($nodeID, $referenceID, $position) {
715 // based on the new position we need to get the weight of the node after moved node
716 // 1. update the weight of $position + 1 nodes to weight + 1
717 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
719 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
720 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
721 // accordingly set the new parent_id
723 $newParentID = $referenceID;
724 $parentClause = "parent_id = {$referenceID} ";
727 $newParentID = 'NULL';
728 $parentClause = 'parent_id IS NULL';
731 $incrementOtherNodes = TRUE;
732 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
733 $params = array(1 => array($position, 'Positive'));
734 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
736 // this means node is moved to last position, so you need to get the weight of last element + 1
738 // If this is not the first item being added to a parent
740 $lastPosition = $position - 1;
741 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
742 $params = array(1 => array($lastPosition, 'Positive'));
743 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
745 // since last node increment + 1
746 $newWeight = $newWeight +
1;
752 // since this is a last node we don't need to increment other nodes
753 $incrementOtherNodes = FALSE;
756 $transaction = new CRM_Core_Transaction();
758 // now update the existing nodes to weight + 1, if required.
759 if ($incrementOtherNodes) {
760 $query = "UPDATE civicrm_navigation SET weight = weight + 1
761 WHERE {$parentClause} AND weight >= {$newWeight}";
763 CRM_Core_DAO
::executeQuery($query);
766 // finally set the weight of current node
767 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
768 CRM_Core_DAO
::executeQuery($query);
770 $transaction->commit();
774 * Function to process rename action for tree.
779 public static function processRename($nodeID, $label) {
780 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
784 * Process delete action for tree.
788 public static function processDelete($nodeID) {
789 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
790 CRM_Core_DAO
::executeQuery($query);
794 * Get the info on navigation item.
796 * @param int $navigationID
802 public static function getNavigationInfo($navigationID) {
803 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
804 $params = array($navigationID, 'Integer');
805 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => $params));
808 'parent_id' => $dao->parent_id
,
809 'weight' => $dao->weight
,
816 * @param array $params
817 * @param array $newParams
818 * New value of params.
820 public static function processUpdate($params, $newParams) {
821 $dao = new CRM_Core_DAO_Navigation();
822 $dao->copyValues($params);
823 if ($dao->find(TRUE)) {
824 $dao->copyValues($newParams);
834 * @return object|string
836 public static function getCacheKey($cid) {
837 $key = CRM_Core_BAO_Setting
::getItem(
838 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
844 if (strlen($key) !== self
::CACHE_KEY_STRLEN
) {
845 $key = self
::resetNavigation($cid);