3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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.
56 * DAO object on sucess, NULL otherwise
60 public static function setIsActive($id, $is_active) {
61 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $id, 'is_active', $is_active);
65 * Get existing / build navigation for CiviCRM Admin Menu
71 public static function getMenus() {
74 $menu = new CRM_Core_DAO_Menu();
75 $menu->domain_id
= CRM_Core_Config
::domainID();
78 while ($menu->fetch()) {
80 $menus[$menu->path
] = $menu->title
;
87 * Add/update navigation record
89 * @param array associated array of submitted values
95 public static function add(&$params) {
96 $navigation = new CRM_Core_DAO_Navigation();
98 $params['is_active'] = CRM_Utils_Array
::value('is_active', $params, FALSE);
99 $params['has_separator'] = CRM_Utils_Array
::value('has_separator', $params, FALSE);
101 if (!isset($params['id']) ||
102 (CRM_Utils_Array
::value('parent_id', $params) != CRM_Utils_Array
::value('current_parent_id', $params))
104 /* re/calculate the weight, if the Parent ID changed OR create new menu */
106 if ($navName = CRM_Utils_Array
::value('name', $params)) {
107 $params['name'] = $navName;
109 elseif ($navLabel = CRM_Utils_Array
::value('label', $params)) {
110 $params['name'] = $navLabel;
113 $params['weight'] = self
::calculateWeight(CRM_Utils_Array
::value('parent_id', $params));
116 if (array_key_exists('permission', $params) && is_array($params['permission'])) {
117 $params['permission'] = implode(',', $params['permission']);
120 $navigation->copyValues($params);
122 $navigation->domain_id
= CRM_Core_Config
::domainID();
129 * Fetch object based on array of properties
131 * @param array $params
132 * (reference ) an assoc array of name/value pairs.
133 * @param array $defaults
134 * (reference ) an assoc array to hold the flattened values.
136 * @return CRM_Core_BAO_Navigation|null
137 * object on success, NULL otherwise
140 public static function retrieve(&$params, &$defaults) {
141 $navigation = new CRM_Core_DAO_Navigation();
142 $navigation->copyValues($params);
144 $navigation->domain_id
= CRM_Core_Config
::domainID();
146 if ($navigation->find(TRUE)) {
147 CRM_Core_DAO
::storeValues($navigation, $defaults);
154 * Calculate navigation weight
156 * @param int $parentID
157 * Parent_id of a menu.
165 public static function calculateWeight($parentID = NULL, $menuID = NULL) {
166 $domainID = CRM_Core_Config
::domainID();
169 // we reset weight for each parent, i.e we start from 1 to n
170 // calculate max weight for top level menus, if parent id is absent
172 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id IS NULL AND domain_id = $domainID";
175 // if parent is passed, we need to get max weight for that particular parent
176 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id = {$parentID} AND domain_id = $domainID";
179 $dao = CRM_Core_DAO
::executeQuery($query);
181 return $weight = $weight +
$dao->weight
;
185 * Get formatted menu list
188 * returns associated array
191 public static function getNavigationList() {
192 $cacheKeyString = "navigationList";
195 $config = CRM_Core_Config
::singleton();
197 // check if we can retrieve from database cache
198 $navigations = CRM_Core_BAO_Cache
::getItem('navigation', $cacheKeyString);
201 $domainID = CRM_Core_Config
::domainID();
203 SELECT id, label, parent_id, weight, is_active, name
204 FROM civicrm_navigation WHERE domain_id = $domainID {$whereClause} ORDER BY parent_id, weight ASC";
205 $result = CRM_Core_DAO
::executeQuery($query);
207 $pidGroups = array();
208 while ($result->fetch()) {
209 $pidGroups[$result->parent_id
][$result->label
] = $result->id
;
212 foreach ($pidGroups[''] as $label => $val) {
213 $pidGroups[''][$label] = self
::_getNavigationValue($val, $pidGroups);
216 $navigations = array();
217 self
::_getNavigationLabel($pidGroups[''], $navigations);
219 CRM_Core_BAO_Cache
::setItem($navigations, 'navigation', $cacheKeyString);
225 * Helper function for getNavigationList( )
229 * @param array $navigations
231 * @param string $separator
234 public static function _getNavigationLabel($list, &$navigations, $separator = '') {
235 $i18n = CRM_Core_I18n
::singleton();
236 foreach ($list as $label => $val) {
237 if ($label == 'navigation_id') {
240 $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
241 $navigations[is_array($val) ?
$val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
242 if (is_array($val)) {
243 self
::_getNavigationLabel($val, $navigations, $separator . ' ');
249 * Helper function for getNavigationList( )
253 * @param array $pidGroups
257 public static function _getNavigationValue($val, &$pidGroups) {
258 if (array_key_exists($val, $pidGroups)) {
259 $list = array('navigation_id' => $val);
260 foreach ($pidGroups[$val] as $label => $id) {
261 $list[$label] = self
::_getNavigationValue($id, $pidGroups);
263 unset($pidGroups[$val]);
272 * Build navigation tree
274 * @param array $navigationTree
275 * Nested array of menus.
276 * @param int $parentID
278 * @param bool $navigationMenu
279 * True when called for building top navigation menu.
282 * nested array of menus
285 public static function buildNavigationTree(&$navigationTree, $parentID, $navigationMenu = TRUE) {
286 $whereClause = " parent_id IS NULL";
289 $whereClause = " parent_id = {$parentID}";
292 $domainID = CRM_Core_Config
::domainID();
294 // get the list of menus
296 SELECT id, label, url, permission, permission_operator, has_separator, parent_id, is_active, name
297 FROM civicrm_navigation
299 AND domain_id = $domainID
300 ORDER BY parent_id, weight";
302 $navigation = CRM_Core_DAO
::executeQuery($query);
303 $config = CRM_Core_Config
::singleton();
304 while ($navigation->fetch()) {
305 $label = $navigation->label
;
306 if (!$navigationMenu) {
307 $label = addcslashes($label, '"');
310 // for each menu get their children
311 $navigationTree[$navigation->id
] = array(
312 'attributes' => array(
314 'name' => $navigation->name
,
315 'url' => $navigation->url
,
316 'permission' => $navigation->permission
,
317 'operator' => $navigation->permission_operator
,
318 'separator' => $navigation->has_separator
,
319 'parentID' => $navigation->parent_id
,
320 'navID' => $navigation->id
,
321 'active' => $navigation->is_active
,
324 self
::buildNavigationTree($navigationTree[$navigation->id
]['child'], $navigation->id
, $navigationMenu);
327 return $navigationTree;
334 * By default output is html.
335 * @param bool $navigationMenu
336 * True when called for building top navigation menu.
339 * html or json string
342 public static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
343 $navigations = array();
344 self
::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
345 $navigationString = NULL;
347 // run the Navigation through a hook so users can modify it
348 CRM_Utils_Hook
::navigationMenu($navigations);
350 $i18n = CRM_Core_I18n
::singleton();
352 //skip children menu item if user don't have access to parent menu item
353 $skipMenuItems = array();
354 foreach ($navigations as $key => $value) {
356 if ($navigationString) {
357 $navigationString .= '},';
359 $data = $value['attributes']['label'];
361 if (!$value['attributes']['active']) {
362 $class = ', "attr": { "class" : "disabled"} ';
364 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
365 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
368 // Home is a special case
369 if ($value['attributes']['name'] != 'Home') {
370 $name = self
::getMenuName($value, $skipMenuItems);
373 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
374 $navigationString .= '<li class="menu-separator"></li>';
376 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
377 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
382 self
::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
386 $navigationString = '[' . $navigationString . '}]';
389 // clean up - Need to remove empty <ul>'s, this happens when user don't have
390 // permission to access parent
391 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
394 return $navigationString;
398 * Recursively check child menus
400 * @param array $value
401 * @param string $navigationString
403 * @param bool $skipMenuItems
406 public static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
408 if (!empty($value['child'])) {
409 $navigationString .= ', "children": [ ';
412 return $navigationString;
415 if (!empty($value['child'])) {
418 foreach ($value['child'] as $k => $val) {
419 if ($count == count($value['child'])) {
420 $appendComma = FALSE;
422 $data = $val['attributes']['label'];
424 if (!$val['attributes']['active']) {
425 $class = ', "attr": { "class" : "disabled"} ';
427 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
428 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
429 $navigationString .= $appendComma ?
' },' : ' }';
434 if (!empty($value['child'])) {
435 $navigationString .= ' ]';
439 if (!empty($value['child'])) {
440 $navigationString .= '<ul>';
443 $navigationString .= '</li>';
444 //locate separator after
445 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
446 $navigationString .= '<li class="menu-separator"></li>';
450 if (!empty($value['child'])) {
451 foreach ($value['child'] as $val) {
452 $name = self
::getMenuName($val, $skipMenuItems);
454 //locate separator before
455 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
456 $navigationString .= '<li class="menu-separator"></li>';
458 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
459 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
460 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
464 if (!empty($value['child'])) {
465 $navigationString .= '</ul></li>';
466 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
467 $navigationString .= '<li class="menu-separator"></li>';
471 return $navigationString;
478 * @param array $skipMenuItems
479 * @return bool|string
481 public static function getMenuName(&$value, &$skipMenuItems) {
482 // we need to localise the menu labels (CRM-5456) and don’t
483 // want to use ts() as it would throw the ts-extractor off
484 $i18n = CRM_Core_I18n
::singleton();
486 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
487 $url = $value['attributes']['url'];
488 $permission = $value['attributes']['permission'];
489 $operator = $value['attributes']['operator'];
490 $parentID = $value['attributes']['parentID'];
491 $navID = $value['attributes']['navID'];
492 $active = $value['attributes']['active'];
493 $menuName = $value['attributes']['name'];
494 $target = CRM_Utils_Array
::value('target', $value['attributes']);
496 if (in_array($parentID, $skipMenuItems) ||
!$active) {
497 $skipMenuItems[] = $navID;
501 //we need to check core view/edit or supported acls.
502 if (in_array($menuName, array(
506 if (!CRM_Core_Permission
::giveMeAllACLs()) {
507 $skipMenuItems[] = $navID;
512 $config = CRM_Core_Config
::singleton();
515 if (isset($url) && $url) {
516 if (substr($url, 0, 4) !== 'http') {
517 //CRM-7656 --make sure to separate out url path from url params,
518 //as we'r going to validate url path across cross-site scripting.
519 $urlParam = explode('?', $url);
520 if (empty($urlParam[1])) {
523 $url = CRM_Utils_System
::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
528 static $allComponents;
529 if (!$allComponents) {
530 $allComponents = CRM_Core_Component
::getNames();
533 if (isset($permission) && $permission) {
534 $permissions = explode(',', $permission);
536 $hasPermission = FALSE;
537 foreach ($permissions as $key) {
541 //get the component name from permission.
542 $componentName = CRM_Core_Permission
::getComponentName($key);
544 if ($componentName) {
545 if (!in_array($componentName, $config->enableComponents
) ||
546 !CRM_Core_Permission
::check($key)
549 if ($operator == 'AND') {
550 $skipMenuItems[] = $navID;
555 $hasPermission = TRUE;
558 elseif (!CRM_Core_Permission
::check($key)) {
560 if ($operator == 'AND') {
561 $skipMenuItems[] = $navID;
566 $hasPermission = TRUE;
570 if (!$showItem && !$hasPermission) {
571 $skipMenuItems[] = $navID;
578 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
581 $name = "<a href=\"{$url}\">{$name}</a>";
589 * Create navigation for CiviCRM Admin Menu
591 * @param int $contactID
595 * returns navigation html
598 public static function createNavigation($contactID) {
599 $config = CRM_Core_Config
::singleton();
601 $navigation = self
::buildNavigation();
605 //add additional navigation items
606 $logoutURL = CRM_Utils_System
::url('civicrm/logout', 'reset=1');
608 // get home menu from db
609 $homeParams = array('name' => 'Home');
611 $homeIcon = '<img src="' . $config->userFrameworkResourceURL
. 'i/logo16px.png" style="vertical-align:middle;" />';
612 self
::retrieve($homeParams, $homeNav);
614 list($path, $q) = explode('?', $homeNav['url']);
615 $homeURL = CRM_Utils_System
::url($path, $q);
616 $homeLabel = $homeNav['label'];
617 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
618 if ($homeLabel == 'Home') {
619 $homeLabel = ts('CiviCRM Home');
623 $homeURL = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
624 $homeLabel = ts('CiviCRM Home');
626 // Link to hide the menubar
628 ($config->userSystem
->is_drupal
) &&
629 ((module_exists('toolbar') && user_access('access toolbar')) ||
630 module_exists('admin_menu') && user_access('access administration menu')
633 $hideLabel = ts('Drupal Menu');
635 elseif ($config->userSystem
->is_wordpress
) {
636 $hideLabel = ts('WordPress Menu');
639 $hideLabel = ts('Hide Menu');
643 <li class='menumain crm-link-home'>$homeIcon
644 <ul id='civicrm-home'>
645 <li><a href='$homeURL'>$homeLabel</a></li>
646 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
647 <li><a href='$logoutURL' class='crm-logout-link'>" . ts('Log out') . "</a></li>
649 // <li> tag doesn't need to be closed
651 return $prepandString . $navigation;
655 * Reset navigation for all contacts or a specified contact
657 * @param int $contactID
658 * Reset only entries belonging to that contact ID.
661 public static function resetNavigation($contactID = NULL) {
662 $newKey = CRM_Utils_String
::createRandom(self
::CACHE_KEY_STRLEN
, CRM_Utils_String
::ALPHANUMERIC
);
664 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
665 CRM_Core_DAO
::executeQuery($query);
666 CRM_Core_BAO_Cache
::deleteGroup('navigation');
669 // before inserting check if contact id exists in db
670 // this is to handle weird case when contact id is in session but not in db
671 $contact = new CRM_Contact_DAO_Contact();
672 $contact->id
= $contactID;
673 if ($contact->find(TRUE)) {
674 CRM_Core_BAO_Setting
::setItem(
676 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
684 // also reset the dashlet cache in case permissions have changed etc
685 // FIXME: decouple this
686 CRM_Core_BAO_Dashboard
::resetDashletCache($contactID);
694 * @param array $params
695 * Associated array, $_GET.
700 public static function processNavigation(&$params) {
701 $nodeID = (int) str_replace("node_", "", $params['id']);
702 $referenceID = (int) str_replace("node_", "", $params['ref_id']);
703 $position = $params['ps'];
704 $type = $params['type'];
705 $label = CRM_Utils_Array
::value('data', $params);
709 self
::processMove($nodeID, $referenceID, $position);
713 self
::processRename($nodeID, $label);
717 self
::processDelete($nodeID);
721 //reset navigation menus
722 self
::resetNavigation();
723 CRM_Utils_System
::civiExit();
727 * Process move action
730 * Node that is being moved.
731 * @param $referenceID
732 * Parent id where node is moved. 0 mean no parent.
734 * New position of the nod, it starts with 0 - n.
739 public static function processMove($nodeID, $referenceID, $position) {
740 // based on the new position we need to get the weight of the node after moved node
741 // 1. update the weight of $position + 1 nodes to weight + 1
742 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
744 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
745 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
746 // accordingly set the new parent_id
748 $newParentID = $referenceID;
749 $parentClause = "parent_id = {$referenceID} ";
752 $newParentID = 'NULL';
753 $parentClause = 'parent_id IS NULL';
756 $incrementOtherNodes = TRUE;
757 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
758 $params = array(1 => array($position, 'Positive'));
759 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
761 // this means node is moved to last position, so you need to get the weight of last element + 1
763 $lastPosition = $position - 1;
764 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
765 $params = array(1 => array($lastPosition, 'Positive'));
766 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
768 // since last node increment + 1
769 $newWeight = $newWeight +
1;
771 // since this is a last node we don't need to increment other nodes
772 $incrementOtherNodes = FALSE;
775 $transaction = new CRM_Core_Transaction();
777 // now update the existing nodes to weight + 1, if required.
778 if ($incrementOtherNodes) {
779 $query = "UPDATE civicrm_navigation SET weight = weight + 1
780 WHERE {$parentClause} AND weight >= {$newWeight}";
782 CRM_Core_DAO
::executeQuery($query);
785 // finally set the weight of current node
786 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
787 CRM_Core_DAO
::executeQuery($query);
789 $transaction->commit();
793 * Function to process rename action for tree
798 public static function processRename($nodeID, $label) {
799 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
803 * Process delete action for tree
807 public static function processDelete($nodeID) {
808 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
809 CRM_Core_DAO
::executeQuery($query);
813 * Get the info on navigation item
815 * @param int $navigationID
822 public static function getNavigationInfo($navigationID) {
823 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
824 $params = array($navigationID, 'Integer');
825 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => $params));
828 'parent_id' => $dao->parent_id
,
829 'weight' => $dao->weight
,
836 * @param array $params
837 * @param array $newParams
838 * New value of params.
841 public static function processUpdate($params, $newParams) {
842 $dao = new CRM_Core_DAO_Navigation();
843 $dao->copyValues($params);
844 if ($dao->find(TRUE)) {
845 $dao->copyValues($newParams);
853 * @return object|string
855 public static function getCacheKey($cid) {
856 $key = CRM_Core_BAO_Setting
::getItem(
857 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
863 if (strlen($key) !== self
::CACHE_KEY_STRLEN
) {
864 $key = self
::resetNavigation($cid);