3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 function __construct() {
44 parent
::__construct();
48 * Update the is_active flag in the db
50 * @param int $id id of the database record
51 * @param boolean $is_active value we want to set the is_active field
53 * @return Object DAO object on sucess, null otherwise
58 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
66 * @return array associated array
68 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 associated array of submitted values
88 * @return object navigation object
91 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 (reference ) an assoc array of name/value pairs
128 * @param array $defaults (reference ) an assoc array to hold the flattened values
130 * @return CRM_Core_BAO_Navigation object on success, null otherwise
134 static function retrieve(&$params, &$defaults) {
135 $navigation = new CRM_Core_DAO_Navigation();
136 $navigation->copyValues($params);
138 $navigation->domain_id
= CRM_Core_Config
::domainID();
140 if ($navigation->find(TRUE)) {
141 CRM_Core_DAO
::storeValues($navigation, $defaults);
148 * Calculate navigation weight
150 * @param $parentID parent_id of a menu
151 * @param $menuID menu id
153 * @return int $weight string@static
155 static function calculateWeight($parentID = NULL, $menuID = NULL) {
156 $domainID = CRM_Core_Config
::domainID();
159 // we reset weight for each parent, i.e we start from 1 to n
160 // calculate max weight for top level menus, if parent id is absent
162 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id IS NULL AND domain_id = $domainID";
165 // if parent is passed, we need to get max weight for that particular parent
166 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id = {$parentID} AND domain_id = $domainID";
169 $dao = CRM_Core_DAO
::executeQuery($query);
171 return $weight = $weight +
$dao->weight
;
175 * Get formatted menu list
177 * @return array $navigations returns associated array
180 static function getNavigationList() {
181 $cacheKeyString = "navigationList";
184 $config = CRM_Core_Config
::singleton();
186 // check if we can retrieve from database cache
187 $navigations = CRM_Core_BAO_Cache
::getItem('navigation', $cacheKeyString);
190 $domainID = CRM_Core_Config
::domainID();
192 SELECT id, label, parent_id, weight, is_active, name
193 FROM civicrm_navigation WHERE domain_id = $domainID {$whereClause} ORDER BY parent_id, weight ASC";
194 $result = CRM_Core_DAO
::executeQuery($query);
196 $pidGroups = array();
197 while ($result->fetch()) {
198 $pidGroups[$result->parent_id
][$result->label
] = $result->id
;
201 foreach ($pidGroups[''] as $label => $val) {
202 $pidGroups[''][$label] = self
::_getNavigationValue($val, $pidGroups);
205 $navigations = array();
206 self
::_getNavigationLabel($pidGroups[''], $navigations);
208 CRM_Core_BAO_Cache
::setItem($navigations, 'navigation', $cacheKeyString);
214 * Helper function for getNavigationList( )
216 * @param array $list menu info
217 * @param array $navigations navigation menus
218 * @param string $separator menu separator
220 static function _getNavigationLabel($list, &$navigations, $separator = '') {
221 $i18n = CRM_Core_I18n
::singleton();
222 foreach ($list as $label => $val) {
223 if ($label == 'navigation_id') {
226 $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
227 $navigations[is_array($val) ?
$val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
228 if (is_array($val)) {
229 self
::_getNavigationLabel($val, $navigations, $separator . ' ');
235 * Helper function for getNavigationList( )
237 * @param string $val menu name
238 * @param array $pidGroups parent menus
241 static function _getNavigationValue($val, &$pidGroups) {
242 if (array_key_exists($val, $pidGroups)) {
243 $list = array('navigation_id' => $val);
244 foreach ($pidGroups[$val] as $label => $id) {
245 $list[$label] = self
::_getNavigationValue($id, $pidGroups);
247 unset($pidGroups[$val]);
256 * Build navigation tree
258 * @param array $navigationTree nested array of menus
259 * @param int $parentID parent id
260 * @param boolean $navigationMenu true when called for building top navigation menu
262 * @return array $navigationTree nested array of menus
265 static function buildNavigationTree(&$navigationTree, $parentID, $navigationMenu = TRUE) {
266 $whereClause = " parent_id IS NULL";
269 $whereClause = " parent_id = {$parentID}";
272 $domainID = CRM_Core_Config
::domainID();
274 // get the list of menus
276 SELECT id, label, url, permission, permission_operator, has_separator, parent_id, is_active, name
277 FROM civicrm_navigation
279 AND domain_id = $domainID
280 ORDER BY parent_id, weight";
282 $navigation = CRM_Core_DAO
::executeQuery($query);
283 $config = CRM_Core_Config
::singleton();
284 while ($navigation->fetch()) {
285 $label = $navigation->label
;
286 if (!$navigationMenu) {
287 $label = addcslashes($label, '"');
290 // for each menu get their children
291 $navigationTree[$navigation->id
] = array(
292 'attributes' => array('label' => $label,
293 'name' => $navigation->name
,
294 'url' => $navigation->url
,
295 'permission' => $navigation->permission
,
296 'operator' => $navigation->permission_operator
,
297 'separator' => $navigation->has_separator
,
298 'parentID' => $navigation->parent_id
,
299 'navID' => $navigation->id
,
300 'active' => $navigation->is_active
,
302 self
::buildNavigationTree($navigationTree[$navigation->id
]['child'], $navigation->id
, $navigationMenu);
305 return $navigationTree;
311 * @param boolean $json by default output is html
312 * @param boolean $navigationMenu true when called for building top navigation menu
314 * @return returns html or json object
317 static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
318 $navigations = array();
319 self
::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
320 $navigationString = NULL;
322 // run the Navigation through a hook so users can modify it
323 CRM_Utils_Hook
::navigationMenu($navigations);
325 $i18n = CRM_Core_I18n
::singleton();
327 //skip children menu item if user don't have access to parent menu item
328 $skipMenuItems = array();
329 foreach ($navigations as $key => $value) {
331 if ($navigationString) {
332 $navigationString .= '},';
334 $data = $value['attributes']['label'];
336 if (!$value['attributes']['active']) {
337 $class = ', "attr": { "class" : "disabled"} ';
339 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
340 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
343 // Home is a special case
344 if ($value['attributes']['name'] != 'Home') {
345 $name = self
::getMenuName($value, $skipMenuItems);
348 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
349 $navigationString .= '<li class="menu-separator"></li>';
351 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
352 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
357 self
::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
361 $navigationString = '[' . $navigationString . '}]';
364 // clean up - Need to remove empty <ul>'s, this happens when user don't have
365 // permission to access parent
366 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
369 return $navigationString;
373 * Recursively check child menus
375 * @param array $value
376 * @param string $navigationString
377 * @param boolean $json
378 * @param boolean $skipMenuItems
381 static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
383 if (!empty($value['child'])) {
384 $navigationString .= ', "children": [ ';
387 return $navigationString;
390 if (!empty($value['child'])) {
393 foreach ($value['child'] as $k => $val) {
394 if ($count == count($value['child'])) {
395 $appendComma = FALSE;
397 $data = $val['attributes']['label'];
399 if (!$val['attributes']['active']) {
400 $class = ', "attr": { "class" : "disabled"} ';
402 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
403 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
404 $navigationString .= $appendComma ?
' },' : ' }';
409 if (!empty($value['child'])) {
410 $navigationString .= ' ]';
414 if (!empty($value['child'])) {
415 $navigationString .= '<ul>';
418 $navigationString .= '</li>';
419 //locate separator after
420 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
421 $navigationString .= '<li class="menu-separator"></li>';
425 if (!empty($value['child'])) {
426 foreach ($value['child'] as $val) {
427 $name = self
::getMenuName($val, $skipMenuItems);
429 //locate separator before
430 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
431 $navigationString .= '<li class="menu-separator"></li>';
433 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
434 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
435 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
439 if (!empty($value['child'])) {
440 $navigationString .= '</ul></li>';
441 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
442 $navigationString .= '<li class="menu-separator"></li>';
446 return $navigationString;
453 * @param array $skipMenuItems
454 * @return bool|string
456 static function getMenuName(&$value, &$skipMenuItems) {
457 // we need to localise the menu labels (CRM-5456) and don’t
458 // want to use ts() as it would throw the ts-extractor off
459 $i18n = CRM_Core_I18n
::singleton();
461 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
462 $url = $value['attributes']['url'];
463 $permission = $value['attributes']['permission'];
464 $operator = $value['attributes']['operator'];
465 $parentID = $value['attributes']['parentID'];
466 $navID = $value['attributes']['navID'];
467 $active = $value['attributes']['active'];
468 $menuName = $value['attributes']['name'];
469 $target = CRM_Utils_Array
::value('target', $value['attributes']);
471 if (in_array($parentID, $skipMenuItems) ||
!$active) {
472 $skipMenuItems[] = $navID;
476 //we need to check core view/edit or supported acls.
477 if (in_array($menuName, array(
478 'Search...', 'Contacts'))) {
479 if (!CRM_Core_Permission
::giveMeAllACLs()) {
480 $skipMenuItems[] = $navID;
485 $config = CRM_Core_Config
::singleton();
488 if (isset($url) && $url) {
489 if (substr($url, 0, 4) !== 'http') {
490 //CRM-7656 --make sure to separate out url path from url params,
491 //as we'r going to validate url path across cross-site scripting.
492 $urlParam = explode('?', $url);
493 if (empty($urlParam[1])) {
496 $url = CRM_Utils_System
::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
501 static $allComponents;
502 if (!$allComponents) {
503 $allComponents = CRM_Core_Component
::getNames();
506 if (isset($permission) && $permission) {
507 $permissions = explode(',', $permission);
509 $hasPermission = FALSE;
510 foreach ($permissions as $key) {
514 //get the component name from permission.
515 $componentName = CRM_Core_Permission
::getComponentName($key);
517 if ($componentName) {
518 if (!in_array($componentName, $config->enableComponents
) ||
519 !CRM_Core_Permission
::check($key)
522 if ($operator == 'AND') {
523 $skipMenuItems[] = $navID;
528 $hasPermission = TRUE;
531 elseif (!CRM_Core_Permission
::check($key)) {
533 if ($operator == 'AND') {
534 $skipMenuItems[] = $navID;
539 $hasPermission = TRUE;
543 if (!$showItem && !$hasPermission) {
544 $skipMenuItems[] = $navID;
551 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
554 $name = "<a href=\"{$url}\">{$name}</a>";
562 * Create navigation for CiviCRM Admin Menu
564 * @param int $contactID contact id
566 * @return string $navigation returns navigation html
569 static function createNavigation($contactID) {
570 $config = CRM_Core_Config
::singleton();
572 $navigation = self
::buildNavigation();
576 //add additional navigation items
577 $logoutURL = CRM_Utils_System
::url('civicrm/logout', 'reset=1');
579 // get home menu from db
580 $homeParams = array('name' => 'Home');
582 $homeIcon = '<img src="' . $config->userFrameworkResourceURL
. 'i/logo16px.png" style="vertical-align:middle;" />';
583 self
::retrieve($homeParams, $homeNav);
585 list($path, $q) = explode('?', $homeNav['url']);
586 $homeURL = CRM_Utils_System
::url($path, $q);
587 $homeLabel = $homeNav['label'];
588 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
589 if ($homeLabel == 'Home') {
590 $homeLabel = ts('CiviCRM Home');
594 $homeURL = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
595 $homeLabel = ts('CiviCRM Home');
597 // Link to hide the menubar
599 ($config->userSystem
->is_drupal
) &&
600 ((module_exists('toolbar') && user_access('access toolbar')) ||
601 module_exists('admin_menu') && user_access('access administration menu')
604 $hideLabel = ts('Drupal Menu');
606 elseif ($config->userSystem
->is_wordpress
) {
607 $hideLabel = ts('WordPress Menu');
610 $hideLabel = ts('Hide Menu');
614 <li class='menumain crm-link-home'>$homeIcon
615 <ul id='civicrm-home'>
616 <li><a href='$homeURL'>$homeLabel</a></li>
617 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
618 <li><a href='$logoutURL' class='crm-logout-link'>". ts('Log out') ."</a></li>
620 // <li> tag doesn't need to be closed
622 return $prepandString . $navigation;
626 * Reset navigation for all contacts or a specified contact
628 * @param integer $contactID - reset only entries belonging to that contact ID
631 static function resetNavigation($contactID = NULL) {
632 $newKey = CRM_Utils_String
::createRandom(self
::CACHE_KEY_STRLEN
, CRM_Utils_String
::ALPHANUMERIC
);
634 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
635 CRM_Core_DAO
::executeQuery($query);
636 CRM_Core_BAO_Cache
::deleteGroup('navigation');
639 // before inserting check if contact id exists in db
640 // this is to handle weird case when contact id is in session but not in db
641 $contact = new CRM_Contact_DAO_Contact();
642 $contact->id
= $contactID;
643 if ($contact->find(TRUE)) {
644 CRM_Core_BAO_Setting
::setItem(
646 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
654 // also reset the dashlet cache in case permissions have changed etc
655 // FIXME: decouple this
656 CRM_Core_BAO_Dashboard
::resetDashletCache($contactID);
664 * @param array $params associated array, $_GET
669 static function processNavigation(&$params) {
670 $nodeID = (int)str_replace("node_", "", $params['id']);
671 $referenceID = (int)str_replace("node_", "", $params['ref_id']);
672 $position = $params['ps'];
673 $type = $params['type'];
674 $label = CRM_Utils_Array
::value('data', $params);
678 self
::processMove($nodeID, $referenceID, $position);
682 self
::processRename($nodeID, $label);
686 self
::processDelete($nodeID);
690 //reset navigation menus
691 self
::resetNavigation();
692 CRM_Utils_System
::civiExit();
696 * Process move action
698 * @param $nodeID node that is being moved
699 * @param $referenceID parent id where node is moved. 0 mean no parent
700 * @param $position new position of the nod, it starts with 0 - n
705 static function processMove($nodeID, $referenceID, $position) {
706 // based on the new position we need to get the weight of the node after moved node
707 // 1. update the weight of $position + 1 nodes to weight + 1
708 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
710 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
711 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
712 // accordingly set the new parent_id
714 $newParentID = $referenceID;
715 $parentClause = "parent_id = {$referenceID} ";
718 $newParentID = 'NULL';
719 $parentClause = 'parent_id IS NULL';
722 $incrementOtherNodes = true;
723 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
724 $params = array(1 => array( $position, 'Positive'));
725 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
727 // this means node is moved to last position, so you need to get the weight of last element + 1
729 $lastPosition = $position - 1;
730 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
731 $params = array(1 => array($lastPosition, 'Positive'));
732 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
734 // since last node increment + 1
735 $newWeight = $newWeight +
1;
737 // since this is a last node we don't need to increment other nodes
738 $incrementOtherNodes = false;
741 $transaction = new CRM_Core_Transaction();
743 // now update the existing nodes to weight + 1, if required.
744 if ( $incrementOtherNodes ) {
745 $query = "UPDATE civicrm_navigation SET weight = weight + 1
746 WHERE {$parentClause} AND weight >= {$newWeight}";
748 CRM_Core_DAO
::executeQuery($query);
751 // finally set the weight of current node
752 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
753 CRM_Core_DAO
::executeQuery($query);
755 $transaction->commit();
759 * Function to process rename action for tree
764 static function processRename($nodeID, $label) {
765 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
769 * Process delete action for tree
773 static function processDelete($nodeID) {
774 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
775 CRM_Core_DAO
::executeQuery($query);
779 * Get the info on navigation item
781 * @param int $navigationID navigation id
783 * @return array associated array
786 static function getNavigationInfo($navigationID) {
787 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
788 $params = array($navigationID, 'Integer');
789 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => $params));
792 'parent_id' => $dao->parent_id
,
793 'weight' => $dao->weight
,
800 * @param array $params
801 * @param array $newParams new value of params
804 static function processUpdate($params, $newParams) {
805 $dao = new CRM_Core_DAO_Navigation();
806 $dao->copyValues($params);
807 if ($dao->find(TRUE)) {
808 $dao->copyValues($newParams);
816 * @return object|string
818 static function getCacheKey($cid) {
819 $key = CRM_Core_BAO_Setting
::getItem(
820 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
826 if (strlen($key) !== self
::CACHE_KEY_STRLEN
) {
827 $key = self
::resetNavigation($cid);