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 object on success, NULL otherwise
139 public static function retrieve(&$params, &$defaults) {
140 $navigation = new CRM_Core_DAO_Navigation();
141 $navigation->copyValues($params);
143 $navigation->domain_id
= CRM_Core_Config
::domainID();
145 if ($navigation->find(TRUE)) {
146 CRM_Core_DAO
::storeValues($navigation, $defaults);
153 * Calculate navigation weight
155 * @param int $parentID
156 * Parent_id of a menu.
164 public static function calculateWeight($parentID = NULL, $menuID = NULL) {
165 $domainID = CRM_Core_Config
::domainID();
168 // we reset weight for each parent, i.e we start from 1 to n
169 // calculate max weight for top level menus, if parent id is absent
171 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id IS NULL AND domain_id = $domainID";
174 // if parent is passed, we need to get max weight for that particular parent
175 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id = {$parentID} AND domain_id = $domainID";
178 $dao = CRM_Core_DAO
::executeQuery($query);
180 return $weight = $weight +
$dao->weight
;
184 * Get formatted menu list
187 * returns associated array
190 public static function getNavigationList() {
191 $cacheKeyString = "navigationList";
194 $config = CRM_Core_Config
::singleton();
196 // check if we can retrieve from database cache
197 $navigations = CRM_Core_BAO_Cache
::getItem('navigation', $cacheKeyString);
200 $domainID = CRM_Core_Config
::domainID();
202 SELECT id, label, parent_id, weight, is_active, name
203 FROM civicrm_navigation WHERE domain_id = $domainID {$whereClause} ORDER BY parent_id, weight ASC";
204 $result = CRM_Core_DAO
::executeQuery($query);
206 $pidGroups = array();
207 while ($result->fetch()) {
208 $pidGroups[$result->parent_id
][$result->label
] = $result->id
;
211 foreach ($pidGroups[''] as $label => $val) {
212 $pidGroups[''][$label] = self
::_getNavigationValue($val, $pidGroups);
215 $navigations = array();
216 self
::_getNavigationLabel($pidGroups[''], $navigations);
218 CRM_Core_BAO_Cache
::setItem($navigations, 'navigation', $cacheKeyString);
224 * Helper function for getNavigationList( )
228 * @param array $navigations
230 * @param string $separator
233 public static function _getNavigationLabel($list, &$navigations, $separator = '') {
234 $i18n = CRM_Core_I18n
::singleton();
235 foreach ($list as $label => $val) {
236 if ($label == 'navigation_id') {
239 $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
240 $navigations[is_array($val) ?
$val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
241 if (is_array($val)) {
242 self
::_getNavigationLabel($val, $navigations, $separator . ' ');
248 * Helper function for getNavigationList( )
252 * @param array $pidGroups
256 public static function _getNavigationValue($val, &$pidGroups) {
257 if (array_key_exists($val, $pidGroups)) {
258 $list = array('navigation_id' => $val);
259 foreach ($pidGroups[$val] as $label => $id) {
260 $list[$label] = self
::_getNavigationValue($id, $pidGroups);
262 unset($pidGroups[$val]);
271 * Build navigation tree
273 * @param array $navigationTree
274 * Nested array of menus.
275 * @param int $parentID
277 * @param bool $navigationMenu
278 * True when called for building top navigation menu.
281 * nested array of menus
284 public static function buildNavigationTree(&$navigationTree, $parentID, $navigationMenu = TRUE) {
285 $whereClause = " parent_id IS NULL";
288 $whereClause = " parent_id = {$parentID}";
291 $domainID = CRM_Core_Config
::domainID();
293 // get the list of menus
295 SELECT id, label, url, permission, permission_operator, has_separator, parent_id, is_active, name
296 FROM civicrm_navigation
298 AND domain_id = $domainID
299 ORDER BY parent_id, weight";
301 $navigation = CRM_Core_DAO
::executeQuery($query);
302 $config = CRM_Core_Config
::singleton();
303 while ($navigation->fetch()) {
304 $label = $navigation->label
;
305 if (!$navigationMenu) {
306 $label = addcslashes($label, '"');
309 // for each menu get their children
310 $navigationTree[$navigation->id
] = array(
311 'attributes' => array(
313 'name' => $navigation->name
,
314 'url' => $navigation->url
,
315 'permission' => $navigation->permission
,
316 'operator' => $navigation->permission_operator
,
317 'separator' => $navigation->has_separator
,
318 'parentID' => $navigation->parent_id
,
319 'navID' => $navigation->id
,
320 'active' => $navigation->is_active
,
322 self
::buildNavigationTree($navigationTree[$navigation->id
]['child'], $navigation->id
, $navigationMenu);
325 return $navigationTree;
332 * By default output is html.
333 * @param bool $navigationMenu
334 * True when called for building top navigation menu.
336 * @return returns html or json object
339 public static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
340 $navigations = array();
341 self
::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
342 $navigationString = NULL;
344 // run the Navigation through a hook so users can modify it
345 CRM_Utils_Hook
::navigationMenu($navigations);
347 $i18n = CRM_Core_I18n
::singleton();
349 //skip children menu item if user don't have access to parent menu item
350 $skipMenuItems = array();
351 foreach ($navigations as $key => $value) {
353 if ($navigationString) {
354 $navigationString .= '},';
356 $data = $value['attributes']['label'];
358 if (!$value['attributes']['active']) {
359 $class = ', "attr": { "class" : "disabled"} ';
361 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
362 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
365 // Home is a special case
366 if ($value['attributes']['name'] != 'Home') {
367 $name = self
::getMenuName($value, $skipMenuItems);
370 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
371 $navigationString .= '<li class="menu-separator"></li>';
373 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
374 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
379 self
::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
383 $navigationString = '[' . $navigationString . '}]';
386 // clean up - Need to remove empty <ul>'s, this happens when user don't have
387 // permission to access parent
388 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
391 return $navigationString;
395 * Recursively check child menus
397 * @param array $value
398 * @param string $navigationString
400 * @param bool $skipMenuItems
403 public static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
405 if (!empty($value['child'])) {
406 $navigationString .= ', "children": [ ';
409 return $navigationString;
412 if (!empty($value['child'])) {
415 foreach ($value['child'] as $k => $val) {
416 if ($count == count($value['child'])) {
417 $appendComma = FALSE;
419 $data = $val['attributes']['label'];
421 if (!$val['attributes']['active']) {
422 $class = ', "attr": { "class" : "disabled"} ';
424 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
425 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
426 $navigationString .= $appendComma ?
' },' : ' }';
431 if (!empty($value['child'])) {
432 $navigationString .= ' ]';
436 if (!empty($value['child'])) {
437 $navigationString .= '<ul>';
440 $navigationString .= '</li>';
441 //locate separator after
442 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
443 $navigationString .= '<li class="menu-separator"></li>';
447 if (!empty($value['child'])) {
448 foreach ($value['child'] as $val) {
449 $name = self
::getMenuName($val, $skipMenuItems);
451 //locate separator before
452 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
453 $navigationString .= '<li class="menu-separator"></li>';
455 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
456 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
457 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
461 if (!empty($value['child'])) {
462 $navigationString .= '</ul></li>';
463 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
464 $navigationString .= '<li class="menu-separator"></li>';
468 return $navigationString;
475 * @param array $skipMenuItems
476 * @return bool|string
478 public static function getMenuName(&$value, &$skipMenuItems) {
479 // we need to localise the menu labels (CRM-5456) and don’t
480 // want to use ts() as it would throw the ts-extractor off
481 $i18n = CRM_Core_I18n
::singleton();
483 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
484 $url = $value['attributes']['url'];
485 $permission = $value['attributes']['permission'];
486 $operator = $value['attributes']['operator'];
487 $parentID = $value['attributes']['parentID'];
488 $navID = $value['attributes']['navID'];
489 $active = $value['attributes']['active'];
490 $menuName = $value['attributes']['name'];
491 $target = CRM_Utils_Array
::value('target', $value['attributes']);
493 if (in_array($parentID, $skipMenuItems) ||
!$active) {
494 $skipMenuItems[] = $navID;
498 //we need to check core view/edit or supported acls.
499 if (in_array($menuName, array(
500 'Search...', 'Contacts'))) {
501 if (!CRM_Core_Permission
::giveMeAllACLs()) {
502 $skipMenuItems[] = $navID;
507 $config = CRM_Core_Config
::singleton();
510 if (isset($url) && $url) {
511 if (substr($url, 0, 4) !== 'http') {
512 //CRM-7656 --make sure to separate out url path from url params,
513 //as we'r going to validate url path across cross-site scripting.
514 $urlParam = explode('?', $url);
515 if (empty($urlParam[1])) {
518 $url = CRM_Utils_System
::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
523 static $allComponents;
524 if (!$allComponents) {
525 $allComponents = CRM_Core_Component
::getNames();
528 if (isset($permission) && $permission) {
529 $permissions = explode(',', $permission);
531 $hasPermission = FALSE;
532 foreach ($permissions as $key) {
536 //get the component name from permission.
537 $componentName = CRM_Core_Permission
::getComponentName($key);
539 if ($componentName) {
540 if (!in_array($componentName, $config->enableComponents
) ||
541 !CRM_Core_Permission
::check($key)
544 if ($operator == 'AND') {
545 $skipMenuItems[] = $navID;
550 $hasPermission = TRUE;
553 elseif (!CRM_Core_Permission
::check($key)) {
555 if ($operator == 'AND') {
556 $skipMenuItems[] = $navID;
561 $hasPermission = TRUE;
565 if (!$showItem && !$hasPermission) {
566 $skipMenuItems[] = $navID;
573 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
576 $name = "<a href=\"{$url}\">{$name}</a>";
584 * Create navigation for CiviCRM Admin Menu
586 * @param int $contactID
590 * returns navigation html
593 public static function createNavigation($contactID) {
594 $config = CRM_Core_Config
::singleton();
596 $navigation = self
::buildNavigation();
600 //add additional navigation items
601 $logoutURL = CRM_Utils_System
::url('civicrm/logout', 'reset=1');
603 // get home menu from db
604 $homeParams = array('name' => 'Home');
606 $homeIcon = '<img src="' . $config->userFrameworkResourceURL
. 'i/logo16px.png" style="vertical-align:middle;" />';
607 self
::retrieve($homeParams, $homeNav);
609 list($path, $q) = explode('?', $homeNav['url']);
610 $homeURL = CRM_Utils_System
::url($path, $q);
611 $homeLabel = $homeNav['label'];
612 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
613 if ($homeLabel == 'Home') {
614 $homeLabel = ts('CiviCRM Home');
618 $homeURL = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
619 $homeLabel = ts('CiviCRM Home');
621 // Link to hide the menubar
623 ($config->userSystem
->is_drupal
) &&
624 ((module_exists('toolbar') && user_access('access toolbar')) ||
625 module_exists('admin_menu') && user_access('access administration menu')
628 $hideLabel = ts('Drupal Menu');
630 elseif ($config->userSystem
->is_wordpress
) {
631 $hideLabel = ts('WordPress Menu');
634 $hideLabel = ts('Hide Menu');
638 <li class='menumain crm-link-home'>$homeIcon
639 <ul id='civicrm-home'>
640 <li><a href='$homeURL'>$homeLabel</a></li>
641 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
642 <li><a href='$logoutURL' class='crm-logout-link'>" . ts('Log out') . "</a></li>
644 // <li> tag doesn't need to be closed
646 return $prepandString . $navigation;
650 * Reset navigation for all contacts or a specified contact
652 * @param int $contactID
653 * Reset only entries belonging to that contact ID.
656 public static function resetNavigation($contactID = NULL) {
657 $newKey = CRM_Utils_String
::createRandom(self
::CACHE_KEY_STRLEN
, CRM_Utils_String
::ALPHANUMERIC
);
659 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
660 CRM_Core_DAO
::executeQuery($query);
661 CRM_Core_BAO_Cache
::deleteGroup('navigation');
664 // before inserting check if contact id exists in db
665 // this is to handle weird case when contact id is in session but not in db
666 $contact = new CRM_Contact_DAO_Contact();
667 $contact->id
= $contactID;
668 if ($contact->find(TRUE)) {
669 CRM_Core_BAO_Setting
::setItem(
671 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
679 // also reset the dashlet cache in case permissions have changed etc
680 // FIXME: decouple this
681 CRM_Core_BAO_Dashboard
::resetDashletCache($contactID);
689 * @param array $params
690 * Associated array, $_GET.
695 public static function processNavigation(&$params) {
696 $nodeID = (int)str_replace("node_", "", $params['id']);
697 $referenceID = (int)str_replace("node_", "", $params['ref_id']);
698 $position = $params['ps'];
699 $type = $params['type'];
700 $label = CRM_Utils_Array
::value('data', $params);
704 self
::processMove($nodeID, $referenceID, $position);
708 self
::processRename($nodeID, $label);
712 self
::processDelete($nodeID);
716 //reset navigation menus
717 self
::resetNavigation();
718 CRM_Utils_System
::civiExit();
722 * Process move action
725 * Node that is being moved.
726 * @param $referenceID
727 * Parent id where node is moved. 0 mean no parent.
729 * New position of the nod, it starts with 0 - n.
734 public static function processMove($nodeID, $referenceID, $position) {
735 // based on the new position we need to get the weight of the node after moved node
736 // 1. update the weight of $position + 1 nodes to weight + 1
737 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
739 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
740 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
741 // accordingly set the new parent_id
743 $newParentID = $referenceID;
744 $parentClause = "parent_id = {$referenceID} ";
747 $newParentID = 'NULL';
748 $parentClause = 'parent_id IS NULL';
751 $incrementOtherNodes = TRUE;
752 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
753 $params = array(1 => array($position, 'Positive'));
754 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
756 // this means node is moved to last position, so you need to get the weight of last element + 1
758 $lastPosition = $position - 1;
759 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
760 $params = array(1 => array($lastPosition, 'Positive'));
761 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
763 // since last node increment + 1
764 $newWeight = $newWeight +
1;
766 // since this is a last node we don't need to increment other nodes
767 $incrementOtherNodes = FALSE;
770 $transaction = new CRM_Core_Transaction();
772 // now update the existing nodes to weight + 1, if required.
773 if ($incrementOtherNodes) {
774 $query = "UPDATE civicrm_navigation SET weight = weight + 1
775 WHERE {$parentClause} AND weight >= {$newWeight}";
777 CRM_Core_DAO
::executeQuery($query);
780 // finally set the weight of current node
781 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
782 CRM_Core_DAO
::executeQuery($query);
784 $transaction->commit();
788 * Function to process rename action for tree
793 public static function processRename($nodeID, $label) {
794 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
798 * Process delete action for tree
802 public static function processDelete($nodeID) {
803 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
804 CRM_Core_DAO
::executeQuery($query);
808 * Get the info on navigation item
810 * @param int $navigationID
817 public static function getNavigationInfo($navigationID) {
818 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
819 $params = array($navigationID, 'Integer');
820 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => $params));
823 'parent_id' => $dao->parent_id
,
824 'weight' => $dao->weight
,
831 * @param array $params
832 * @param array $newParams
833 * New value of params.
836 public static function processUpdate($params, $newParams) {
837 $dao = new CRM_Core_DAO_Navigation();
838 $dao->copyValues($params);
839 if ($dao->find(TRUE)) {
840 $dao->copyValues($newParams);
848 * @return object|string
850 public static function getCacheKey($cid) {
851 $key = CRM_Core_BAO_Setting
::getItem(
852 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
858 if (strlen($key) !== self
::CACHE_KEY_STRLEN
) {
859 $key = self
::resetNavigation($cid);