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 * Function to 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 * Function to 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 * Takes a bunch of params that are needed to match certain criteria and
126 * retrieves the relevant objects. Typically the valid params are only
127 * contact_id. We'll tweak this function to be more full featured over a period
128 * of time. This is the inverse function of create. It also stores all the retrieved
129 * values in the default array
131 * @param array $params (reference ) an assoc array of name/value pairs
132 * @param array $defaults (reference ) an assoc array to hold the flattened values
134 * @return object CRM_Core_BAO_Navigation object on success, null otherwise
138 static function retrieve(&$params, &$defaults) {
139 $navigation = new CRM_Core_DAO_Navigation();
140 $navigation->copyValues($params);
142 $navigation->domain_id
= CRM_Core_Config
::domainID();
144 if ($navigation->find(TRUE)) {
145 CRM_Core_DAO
::storeValues($navigation, $defaults);
152 * Calculate navigation weight
154 * @param $parentID parent_id of a menu
155 * @param $menuID menu id
157 * @return int $weight string@static
159 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
181 * @return array $navigations returns associated array
184 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( )
220 * @param array $list menu info
221 * @param array $navigations navigation menus
222 * @param string $separator menu separator
224 static function _getNavigationLabel($list, &$navigations, $separator = '') {
225 $i18n = CRM_Core_I18n
::singleton();
226 foreach ($list as $label => $val) {
227 if ($label == 'navigation_id') {
230 $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
231 $navigations[is_array($val) ?
$val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
232 if (is_array($val)) {
233 self
::_getNavigationLabel($val, $navigations, $separator . ' ');
239 * helper function for getNavigationList( )
241 * @param string $val menu name
242 * @param array $pidGroups parent menus
245 static function _getNavigationValue($val, &$pidGroups) {
246 if (array_key_exists($val, $pidGroups)) {
247 $list = array('navigation_id' => $val);
248 foreach ($pidGroups[$val] as $label => $id) {
249 $list[$label] = self
::_getNavigationValue($id, $pidGroups);
251 unset($pidGroups[$val]);
260 * Function to build navigation tree
262 * @param array $navigationTree nested array of menus
263 * @param int $parentID parent id
264 * @param boolean $navigationMenu true when called for building top navigation menu
266 * @return array $navigationTree nested array of menus
269 static function buildNavigationTree(&$navigationTree, $parentID, $navigationMenu = TRUE) {
270 $whereClause = " parent_id IS NULL";
273 $whereClause = " parent_id = {$parentID}";
276 $domainID = CRM_Core_Config
::domainID();
278 // get the list of menus
280 SELECT id, label, url, permission, permission_operator, has_separator, parent_id, is_active, name
281 FROM civicrm_navigation
283 AND domain_id = $domainID
284 ORDER BY parent_id, weight";
286 $navigation = CRM_Core_DAO
::executeQuery($query);
287 $config = CRM_Core_Config
::singleton();
288 while ($navigation->fetch()) {
289 $label = $navigation->label
;
290 if (!$navigationMenu) {
291 $label = addcslashes($label, '"');
294 // for each menu get their children
295 $navigationTree[$navigation->id
] = array(
296 'attributes' => array('label' => $label,
297 'name' => $navigation->name
,
298 'url' => $navigation->url
,
299 'permission' => $navigation->permission
,
300 'operator' => $navigation->permission_operator
,
301 'separator' => $navigation->has_separator
,
302 'parentID' => $navigation->parent_id
,
303 'navID' => $navigation->id
,
304 'active' => $navigation->is_active
,
306 self
::buildNavigationTree($navigationTree[$navigation->id
]['child'], $navigation->id
, $navigationMenu);
309 return $navigationTree;
313 * Function to build menu
315 * @param boolean $json by default output is html
316 * @param boolean $navigationMenu true when called for building top navigation menu
318 * @return returns html or json object
321 static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
322 $navigations = array();
323 self
::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
324 $navigationString = NULL;
326 // run the Navigation through a hook so users can modify it
327 CRM_Utils_Hook
::navigationMenu($navigations);
329 $i18n = CRM_Core_I18n
::singleton();
331 //skip children menu item if user don't have access to parent menu item
332 $skipMenuItems = array();
333 foreach ($navigations as $key => $value) {
335 if ($navigationString) {
336 $navigationString .= '},';
338 $data = $value['attributes']['label'];
340 if (!$value['attributes']['active']) {
341 $class = ', "attr": { "class" : "disabled"} ';
343 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
344 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
347 // Home is a special case
348 if ($value['attributes']['name'] != 'Home') {
349 $name = self
::getMenuName($value, $skipMenuItems);
352 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
353 $navigationString .= '<li class="menu-separator"></li>';
355 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
356 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
361 self
::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
365 $navigationString = '[' . $navigationString . '}]';
368 // clean up - Need to remove empty <ul>'s, this happens when user don't have
369 // permission to access parent
370 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
373 return $navigationString;
377 * Recursively check child menus
379 * @param array $value
380 * @param string $navigationString
381 * @param boolean $json
382 * @param boolean $skipMenuItems
385 static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
387 if (!empty($value['child'])) {
388 $navigationString .= ', "children": [ ';
391 return $navigationString;
394 if (!empty($value['child'])) {
397 foreach ($value['child'] as $k => $val) {
398 if ($count == count($value['child'])) {
399 $appendComma = FALSE;
401 $data = $val['attributes']['label'];
403 if (!$val['attributes']['active']) {
404 $class = ', "attr": { "class" : "disabled"} ';
406 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
407 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
408 $navigationString .= $appendComma ?
' },' : ' }';
413 if (!empty($value['child'])) {
414 $navigationString .= ' ]';
418 if (!empty($value['child'])) {
419 $navigationString .= '<ul>';
422 $navigationString .= '</li>';
423 //locate separator after
424 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
425 $navigationString .= '<li class="menu-separator"></li>';
429 if (!empty($value['child'])) {
430 foreach ($value['child'] as $val) {
431 $name = self
::getMenuName($val, $skipMenuItems);
433 //locate separator before
434 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
435 $navigationString .= '<li class="menu-separator"></li>';
437 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
438 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
439 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
443 if (!empty($value['child'])) {
444 $navigationString .= '</ul></li>';
445 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
446 $navigationString .= '<li class="menu-separator"></li>';
450 return $navigationString;
457 * @param $skipMenuItems
458 * @return bool|string
460 static function getMenuName(&$value, &$skipMenuItems) {
461 // we need to localise the menu labels (CRM-5456) and don’t
462 // want to use ts() as it would throw the ts-extractor off
463 $i18n = CRM_Core_I18n
::singleton();
465 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
466 $url = $value['attributes']['url'];
467 $permission = $value['attributes']['permission'];
468 $operator = $value['attributes']['operator'];
469 $parentID = $value['attributes']['parentID'];
470 $navID = $value['attributes']['navID'];
471 $active = $value['attributes']['active'];
472 $menuName = $value['attributes']['name'];
473 $target = CRM_Utils_Array
::value('target', $value['attributes']);
475 if (in_array($parentID, $skipMenuItems) ||
!$active) {
476 $skipMenuItems[] = $navID;
480 //we need to check core view/edit or supported acls.
481 if (in_array($menuName, array(
482 'Search...', 'Contacts'))) {
483 if (!CRM_Core_Permission
::giveMeAllACLs()) {
484 $skipMenuItems[] = $navID;
489 $config = CRM_Core_Config
::singleton();
492 if (isset($url) && $url) {
493 if (substr($url, 0, 4) !== 'http') {
494 //CRM-7656 --make sure to separate out url path from url params,
495 //as we'r going to validate url path across cross-site scripting.
496 $urlParam = explode('?', $url);
497 if (empty($urlParam[1])) {
500 $url = CRM_Utils_System
::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
505 static $allComponents;
506 if (!$allComponents) {
507 $allComponents = CRM_Core_Component
::getNames();
510 if (isset($permission) && $permission) {
511 $permissions = explode(',', $permission);
513 $hasPermission = FALSE;
514 foreach ($permissions as $key) {
518 //get the component name from permission.
519 $componentName = CRM_Core_Permission
::getComponentName($key);
521 if ($componentName) {
522 if (!in_array($componentName, $config->enableComponents
) ||
523 !CRM_Core_Permission
::check($key)
526 if ($operator == 'AND') {
527 $skipMenuItems[] = $navID;
532 $hasPermission = TRUE;
535 elseif (!CRM_Core_Permission
::check($key)) {
537 if ($operator == 'AND') {
538 $skipMenuItems[] = $navID;
543 $hasPermission = TRUE;
547 if (!$showItem && !$hasPermission) {
548 $skipMenuItems[] = $navID;
555 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
558 $name = "<a href=\"{$url}\">{$name}</a>";
566 * Function to create navigation for CiviCRM Admin Menu
568 * @param int $contactID contact id
570 * @return string $navigation returns navigation html
573 static function createNavigation($contactID) {
574 $config = CRM_Core_Config
::singleton();
576 $navigation = self
::buildNavigation();
580 //add additional navigation items
581 $logoutURL = CRM_Utils_System
::url('civicrm/logout', 'reset=1');
583 // get home menu from db
584 $homeParams = array('name' => 'Home');
586 $homeIcon = '<img src="' . $config->userFrameworkResourceURL
. 'i/logo16px.png" style="vertical-align:middle;" />';
587 self
::retrieve($homeParams, $homeNav);
589 list($path, $q) = explode('?', $homeNav['url']);
590 $homeURL = CRM_Utils_System
::url($path, $q);
591 $homeLabel = $homeNav['label'];
592 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
593 if ($homeLabel == 'Home') {
594 $homeLabel = ts('CiviCRM Home');
598 $homeURL = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
599 $homeLabel = ts('CiviCRM Home');
601 // Link to hide the menubar
603 ($config->userSystem
->is_drupal
) &&
604 ((module_exists('toolbar') && user_access('access toolbar')) ||
605 module_exists('admin_menu') && user_access('access administration menu')
608 $hideLabel = ts('Drupal Menu');
610 elseif ($config->userSystem
->is_wordpress
) {
611 $hideLabel = ts('WordPress Menu');
614 $hideLabel = ts('Hide Menu');
618 <li class='menumain crm-link-home'>$homeIcon
619 <ul id='civicrm-home'>
620 <li><a href='$homeURL'>$homeLabel</a></li>
621 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
622 <li><a href='$logoutURL' class='crm-logout-link'>". ts('Logout') ."</a></li>
624 // <li> tag doesn't need to be closed
626 return $prepandString . $navigation;
630 * Reset navigation for all contacts or a specified contact
632 * @param integer $contactID - reset only entries belonging to that contact ID
635 static function resetNavigation($contactID = NULL) {
636 $newKey = CRM_Utils_String
::createRandom(self
::CACHE_KEY_STRLEN
, CRM_Utils_String
::ALPHANUMERIC
);
638 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
639 CRM_Core_DAO
::executeQuery($query);
640 CRM_Core_BAO_Cache
::deleteGroup('navigation');
643 // before inserting check if contact id exists in db
644 // this is to handle weird case when contact id is in session but not in db
645 $contact = new CRM_Contact_DAO_Contact();
646 $contact->id
= $contactID;
647 if ($contact->find(TRUE)) {
648 CRM_Core_BAO_Setting
::setItem(
650 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
658 // also reset the dashlet cache in case permissions have changed etc
659 // FIXME: decouple this
660 CRM_Core_BAO_Dashboard
::resetDashletCache($contactID);
666 * Function to process navigation
668 * @param array $params associated array, $_GET
673 static function processNavigation(&$params) {
674 $nodeID = (int)str_replace("node_", "", $params['id']);
675 $referenceID = (int)str_replace("node_", "", $params['ref_id']);
676 $position = $params['ps'];
677 $type = $params['type'];
678 $label = CRM_Utils_Array
::value('data', $params);
682 self
::processMove($nodeID, $referenceID, $position);
686 self
::processRename($nodeID, $label);
690 self
::processDelete($nodeID);
694 //reset navigation menus
695 self
::resetNavigation();
696 CRM_Utils_System
::civiExit();
700 * Function to process move action
702 * @param $nodeID node that is being moved
703 * @param $referenceID parent id where node is moved. 0 mean no parent
704 * @param $position new position of the nod, it starts with 0 - n
709 static function processMove($nodeID, $referenceID, $position) {
710 // based on the new position we need to get the weight of the node after moved node
711 // 1. update the weight of $position + 1 nodes to weight + 1
712 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
714 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
715 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
716 // accordingly set the new parent_id
718 $newParentID = $referenceID;
719 $parentClause = "parent_id = {$referenceID} ";
722 $newParentID = 'NULL';
723 $parentClause = 'parent_id IS NULL';
726 $incrementOtherNodes = true;
727 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
728 $params = array(1 => array( $position, 'Positive'));
729 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
731 // this means node is moved to last position, so you need to get the weight of last element + 1
733 $lastPosition = $position - 1;
734 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
735 $params = array(1 => array($lastPosition, 'Positive'));
736 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
738 // since last node increment + 1
739 $newWeight = $newWeight +
1;
741 // since this is a last node we don't need to increment other nodes
742 $incrementOtherNodes = false;
745 $transaction = new CRM_Core_Transaction();
747 // now update the existing nodes to weight + 1, if required.
748 if ( $incrementOtherNodes ) {
749 $query = "UPDATE civicrm_navigation SET weight = weight + 1
750 WHERE {$parentClause} AND weight >= {$newWeight}";
752 CRM_Core_DAO
::executeQuery($query);
755 // finally set the weight of current node
756 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
757 CRM_Core_DAO
::executeQuery($query);
759 $transaction->commit();
763 * Function to process rename action for tree
768 static function processRename($nodeID, $label) {
769 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
773 * Function to process delete action for tree
777 static function processDelete($nodeID) {
778 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
779 CRM_Core_DAO
::executeQuery($query);
783 * Function to get the info on navigation item
785 * @param int $navigationID navigation id
787 * @return array associated array
790 static function getNavigationInfo($navigationID) {
791 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
792 $params = array($navigationID, 'Integer');
793 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => $params));
796 'parent_id' => $dao->parent_id
,
797 'weight' => $dao->weight
,
802 * Function to update menu
804 * @param array $params
805 * @param array $newParams new value of params
808 static function processUpdate($params, $newParams) {
809 $dao = new CRM_Core_DAO_Navigation();
810 $dao->copyValues($params);
811 if ($dao->find(TRUE)) {
812 $dao->copyValues($newParams);
820 * @return object|string
822 static function getCacheKey($cid) {
823 $key = CRM_Core_BAO_Setting
::getItem(
824 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
830 if (strlen($key) !== self
::CACHE_KEY_STRLEN
) {
831 $key = self
::resetNavigation($cid);