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
59 public static function setIsActive($id, $is_active) {
60 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $id, 'is_active', $is_active);
64 * Get existing / build navigation for CiviCRM Admin Menu
69 public static function getMenus() {
72 $menu = new CRM_Core_DAO_Menu();
73 $menu->domain_id
= CRM_Core_Config
::domainID();
76 while ($menu->fetch()) {
78 $menus[$menu->path
] = $menu->title
;
85 * Add/update navigation record
87 * @param $params associated array of submitted values
92 public static function add(&$params) {
93 $navigation = new CRM_Core_DAO_Navigation();
95 $params['is_active'] = CRM_Utils_Array
::value('is_active', $params, FALSE);
96 $params['has_separator'] = CRM_Utils_Array
::value('has_separator', $params, FALSE);
98 if (!isset($params['id']) ||
99 (CRM_Utils_Array
::value('parent_id', $params) != CRM_Utils_Array
::value('current_parent_id', $params))
101 /* re/calculate the weight, if the Parent ID changed OR create new menu */
103 if ($navName = CRM_Utils_Array
::value('name', $params)) {
104 $params['name'] = $navName;
106 elseif ($navLabel = CRM_Utils_Array
::value('label', $params)) {
107 $params['name'] = $navLabel;
110 $params['weight'] = self
::calculateWeight(CRM_Utils_Array
::value('parent_id', $params));
113 if (array_key_exists('permission', $params) && is_array($params['permission'])) {
114 $params['permission'] = implode(',', $params['permission']);
117 $navigation->copyValues($params);
119 $navigation->domain_id
= CRM_Core_Config
::domainID();
126 * Fetch object based on array of properties.
128 * @param array $params
129 * (reference ) an assoc array of name/value pairs.
130 * @param array $defaults
131 * (reference ) an assoc array to hold the flattened values.
133 * @return CRM_Core_BAO_Navigation|null
134 * object on success, NULL otherwise
136 public static function retrieve(&$params, &$defaults) {
137 $navigation = new CRM_Core_DAO_Navigation();
138 $navigation->copyValues($params);
140 $navigation->domain_id
= CRM_Core_Config
::domainID();
142 if ($navigation->find(TRUE)) {
143 CRM_Core_DAO
::storeValues($navigation, $defaults);
150 * Calculate navigation weight.
152 * @param int $parentID
153 * Parent_id of a menu.
160 public static function calculateWeight($parentID = NULL, $menuID = NULL) {
161 $domainID = CRM_Core_Config
::domainID();
164 // we reset weight for each parent, i.e we start from 1 to n
165 // calculate max weight for top level menus, if parent id is absent
167 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id IS NULL AND domain_id = $domainID";
170 // if parent is passed, we need to get max weight for that particular parent
171 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id = {$parentID} AND domain_id = $domainID";
174 $dao = CRM_Core_DAO
::executeQuery($query);
176 return $weight = $weight +
$dao->weight
;
180 * Get formatted menu list.
183 * returns associated array
185 public static function getNavigationList() {
186 $cacheKeyString = "navigationList";
189 $config = CRM_Core_Config
::singleton();
191 // check if we can retrieve from database cache
192 $navigations = CRM_Core_BAO_Cache
::getItem('navigation', $cacheKeyString);
195 $domainID = CRM_Core_Config
::domainID();
197 SELECT id, label, parent_id, weight, is_active, name
198 FROM civicrm_navigation WHERE domain_id = $domainID {$whereClause} ORDER BY parent_id, weight ASC";
199 $result = CRM_Core_DAO
::executeQuery($query);
201 $pidGroups = array();
202 while ($result->fetch()) {
203 $pidGroups[$result->parent_id
][$result->label
] = $result->id
;
206 foreach ($pidGroups[''] as $label => $val) {
207 $pidGroups[''][$label] = self
::_getNavigationValue($val, $pidGroups);
210 $navigations = array();
211 self
::_getNavigationLabel($pidGroups[''], $navigations);
213 CRM_Core_BAO_Cache
::setItem($navigations, 'navigation', $cacheKeyString);
219 * Helper function for getNavigationList( )
223 * @param array $navigations
225 * @param string $separator
228 public static function _getNavigationLabel($list, &$navigations, $separator = '') {
229 $i18n = CRM_Core_I18n
::singleton();
230 foreach ($list as $label => $val) {
231 if ($label == 'navigation_id') {
234 $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
235 $navigations[is_array($val) ?
$val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
236 if (is_array($val)) {
237 self
::_getNavigationLabel($val, $navigations, $separator . ' ');
243 * Helper function for getNavigationList( )
247 * @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
398 public static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
400 if (!empty($value['child'])) {
401 $navigationString .= ', "children": [ ';
404 return $navigationString;
407 if (!empty($value['child'])) {
410 foreach ($value['child'] as $k => $val) {
411 if ($count == count($value['child'])) {
412 $appendComma = FALSE;
414 $data = $val['attributes']['label'];
416 if (!$val['attributes']['active']) {
417 $class = ', "attr": { "class" : "disabled"} ';
419 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
420 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
421 $navigationString .= $appendComma ?
' },' : ' }';
426 if (!empty($value['child'])) {
427 $navigationString .= ' ]';
431 if (!empty($value['child'])) {
432 $navigationString .= '<ul>';
435 $navigationString .= '</li>';
436 //locate separator after
437 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
438 $navigationString .= '<li class="menu-separator"></li>';
442 if (!empty($value['child'])) {
443 foreach ($value['child'] as $val) {
444 $name = self
::getMenuName($val, $skipMenuItems);
446 //locate separator before
447 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
448 $navigationString .= '<li class="menu-separator"></li>';
450 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
451 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
452 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
456 if (!empty($value['child'])) {
457 $navigationString .= '</ul></li>';
458 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
459 $navigationString .= '<li class="menu-separator"></li>';
463 return $navigationString;
470 * @param array $skipMenuItems
471 * @return bool|string
473 public static function getMenuName(&$value, &$skipMenuItems) {
474 // we need to localise the menu labels (CRM-5456) and don’t
475 // want to use ts() as it would throw the ts-extractor off
476 $i18n = CRM_Core_I18n
::singleton();
478 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
479 $url = $value['attributes']['url'];
480 $permission = $value['attributes']['permission'];
481 $operator = $value['attributes']['operator'];
482 $parentID = $value['attributes']['parentID'];
483 $navID = $value['attributes']['navID'];
484 $active = $value['attributes']['active'];
485 $menuName = $value['attributes']['name'];
486 $target = CRM_Utils_Array
::value('target', $value['attributes']);
488 if (in_array($parentID, $skipMenuItems) ||
!$active) {
489 $skipMenuItems[] = $navID;
493 //we need to check core view/edit or supported acls.
494 if (in_array($menuName, array(
498 if (!CRM_Core_Permission
::giveMeAllACLs()) {
499 $skipMenuItems[] = $navID;
504 $config = CRM_Core_Config
::singleton();
507 if (isset($url) && $url) {
508 if (substr($url, 0, 4) !== 'http') {
509 //CRM-7656 --make sure to separate out url path from url params,
510 //as we'r going to validate url path across cross-site scripting.
511 $urlParam = explode('?', $url);
512 if (empty($urlParam[1])) {
515 $url = CRM_Utils_System
::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
520 static $allComponents;
521 if (!$allComponents) {
522 $allComponents = CRM_Core_Component
::getNames();
525 if (isset($permission) && $permission) {
526 $permissions = explode(',', $permission);
528 $hasPermission = FALSE;
529 foreach ($permissions as $key) {
533 //get the component name from permission.
534 $componentName = CRM_Core_Permission
::getComponentName($key);
536 if ($componentName) {
537 if (!in_array($componentName, $config->enableComponents
) ||
538 !CRM_Core_Permission
::check($key)
541 if ($operator == 'AND') {
542 $skipMenuItems[] = $navID;
547 $hasPermission = TRUE;
550 elseif (!CRM_Core_Permission
::check($key)) {
552 if ($operator == 'AND') {
553 $skipMenuItems[] = $navID;
558 $hasPermission = TRUE;
562 if (!$showItem && !$hasPermission) {
563 $skipMenuItems[] = $navID;
570 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
573 $name = "<a href=\"{$url}\">{$name}</a>";
581 * Create navigation for CiviCRM Admin Menu.
583 * @param int $contactID
587 * returns navigation html
589 public static function createNavigation($contactID) {
590 $config = CRM_Core_Config
::singleton();
592 $navigation = self
::buildNavigation();
596 //add additional navigation items
597 $logoutURL = CRM_Utils_System
::url('civicrm/logout', 'reset=1');
599 // get home menu from db
600 $homeParams = array('name' => 'Home');
602 $homeIcon = '<img src="' . $config->userFrameworkResourceURL
. 'i/logo16px.png" style="vertical-align:middle;" />';
603 self
::retrieve($homeParams, $homeNav);
605 list($path, $q) = explode('?', $homeNav['url']);
606 $homeURL = CRM_Utils_System
::url($path, $q);
607 $homeLabel = $homeNav['label'];
608 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
609 if ($homeLabel == 'Home') {
610 $homeLabel = ts('CiviCRM Home');
614 $homeURL = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
615 $homeLabel = ts('CiviCRM Home');
617 // Link to hide the menubar
619 ($config->userSystem
->is_drupal
) &&
620 ((module_exists('toolbar') && user_access('access toolbar')) ||
621 module_exists('admin_menu') && user_access('access administration menu')
624 $hideLabel = ts('Drupal Menu');
626 elseif ($config->userSystem
->is_wordpress
) {
627 $hideLabel = ts('WordPress Menu');
630 $hideLabel = ts('Hide Menu');
634 <li class='menumain crm-link-home'>$homeIcon
635 <ul id='civicrm-home'>
636 <li><a href='$homeURL'>$homeLabel</a></li>
637 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
638 <li><a href='$logoutURL' class='crm-logout-link'>" . ts('Log out') . "</a></li>
640 // <li> tag doesn't need to be closed
642 return $prepandString . $navigation;
646 * Reset navigation for all contacts or a specified contact.
648 * @param int $contactID
649 * Reset only entries belonging to that contact ID.
652 public static function resetNavigation($contactID = NULL) {
653 $newKey = CRM_Utils_String
::createRandom(self
::CACHE_KEY_STRLEN
, CRM_Utils_String
::ALPHANUMERIC
);
655 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
656 CRM_Core_DAO
::executeQuery($query);
657 CRM_Core_BAO_Cache
::deleteGroup('navigation');
660 // before inserting check if contact id exists in db
661 // this is to handle weird case when contact id is in session but not in db
662 $contact = new CRM_Contact_DAO_Contact();
663 $contact->id
= $contactID;
664 if ($contact->find(TRUE)) {
665 CRM_Core_BAO_Setting
::setItem(
667 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
675 // also reset the dashlet cache in case permissions have changed etc
676 // FIXME: decouple this
677 CRM_Core_BAO_Dashboard
::resetDashletCache($contactID);
683 * Process navigation.
685 * @param array $params
686 * Associated array, $_GET.
690 public static function processNavigation(&$params) {
691 $nodeID = (int) str_replace("node_", "", $params['id']);
692 $referenceID = (int) str_replace("node_", "", $params['ref_id']);
693 $position = $params['ps'];
694 $type = $params['type'];
695 $label = CRM_Utils_Array
::value('data', $params);
699 self
::processMove($nodeID, $referenceID, $position);
703 self
::processRename($nodeID, $label);
707 self
::processDelete($nodeID);
711 //reset navigation menus
712 self
::resetNavigation();
713 CRM_Utils_System
::civiExit();
717 * Process move action.
720 * Node that is being moved.
721 * @param $referenceID
722 * Parent id where node is moved. 0 mean no parent.
724 * New position of the nod, it starts with 0 - n.
728 public static function processMove($nodeID, $referenceID, $position) {
729 // based on the new position we need to get the weight of the node after moved node
730 // 1. update the weight of $position + 1 nodes to weight + 1
731 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
733 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
734 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
735 // accordingly set the new parent_id
737 $newParentID = $referenceID;
738 $parentClause = "parent_id = {$referenceID} ";
741 $newParentID = 'NULL';
742 $parentClause = 'parent_id IS NULL';
745 $incrementOtherNodes = TRUE;
746 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
747 $params = array(1 => array($position, 'Positive'));
748 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
750 // this means node is moved to last position, so you need to get the weight of last element + 1
752 $lastPosition = $position - 1;
753 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
754 $params = array(1 => array($lastPosition, 'Positive'));
755 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
757 // since last node increment + 1
758 $newWeight = $newWeight +
1;
760 // since this is a last node we don't need to increment other nodes
761 $incrementOtherNodes = FALSE;
764 $transaction = new CRM_Core_Transaction();
766 // now update the existing nodes to weight + 1, if required.
767 if ($incrementOtherNodes) {
768 $query = "UPDATE civicrm_navigation SET weight = weight + 1
769 WHERE {$parentClause} AND weight >= {$newWeight}";
771 CRM_Core_DAO
::executeQuery($query);
774 // finally set the weight of current node
775 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
776 CRM_Core_DAO
::executeQuery($query);
778 $transaction->commit();
782 * Function to process rename action for tree.
787 public static function processRename($nodeID, $label) {
788 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
792 * Process delete action for tree.
796 public static function processDelete($nodeID) {
797 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
798 CRM_Core_DAO
::executeQuery($query);
802 * Get the info on navigation item.
804 * @param int $navigationID
810 public static function getNavigationInfo($navigationID) {
811 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
812 $params = array($navigationID, 'Integer');
813 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => $params));
816 'parent_id' => $dao->parent_id
,
817 'weight' => $dao->weight
,
824 * @param array $params
825 * @param array $newParams
826 * New value of params.
828 public static function processUpdate($params, $newParams) {
829 $dao = new CRM_Core_DAO_Navigation();
830 $dao->copyValues($params);
831 if ($dao->find(TRUE)) {
832 $dao->copyValues($newParams);
840 * @return object|string
842 public static function getCacheKey($cid) {
843 $key = CRM_Core_BAO_Setting
::getItem(
844 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
850 if (strlen($key) !== self
::CACHE_KEY_STRLEN
) {
851 $key = self
::resetNavigation($cid);