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.
55 * @return Object 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
67 * @return array associated array
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 array associated array of submitted values
89 * @return object navigation object
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 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
153 * Parent_id of a menu.
157 * @return int $weight string@static
159 public 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 public 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( )
222 * @param array $navigations
224 * @param string $separator
227 public static function _getNavigationLabel($list, &$navigations, $separator = '') {
228 $i18n = CRM_Core_I18n
::singleton();
229 foreach ($list as $label => $val) {
230 if ($label == 'navigation_id') {
233 $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
234 $navigations[is_array($val) ?
$val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
235 if (is_array($val)) {
236 self
::_getNavigationLabel($val, $navigations, $separator . ' ');
242 * Helper function for getNavigationList( )
246 * @param array $pidGroups
250 public static function _getNavigationValue($val, &$pidGroups) {
251 if (array_key_exists($val, $pidGroups)) {
252 $list = array('navigation_id' => $val);
253 foreach ($pidGroups[$val] as $label => $id) {
254 $list[$label] = self
::_getNavigationValue($id, $pidGroups);
256 unset($pidGroups[$val]);
265 * Build navigation tree
267 * @param array $navigationTree
268 * Nested array of menus.
269 * @param int $parentID
271 * @param bool $navigationMenu
272 * True when called for building top navigation menu.
274 * @return array $navigationTree nested array of menus
277 public static function buildNavigationTree(&$navigationTree, $parentID, $navigationMenu = TRUE) {
278 $whereClause = " parent_id IS NULL";
281 $whereClause = " parent_id = {$parentID}";
284 $domainID = CRM_Core_Config
::domainID();
286 // get the list of menus
288 SELECT id, label, url, permission, permission_operator, has_separator, parent_id, is_active, name
289 FROM civicrm_navigation
291 AND domain_id = $domainID
292 ORDER BY parent_id, weight";
294 $navigation = CRM_Core_DAO
::executeQuery($query);
295 $config = CRM_Core_Config
::singleton();
296 while ($navigation->fetch()) {
297 $label = $navigation->label
;
298 if (!$navigationMenu) {
299 $label = addcslashes($label, '"');
302 // for each menu get their children
303 $navigationTree[$navigation->id
] = array(
304 'attributes' => array('label' => $label,
305 'name' => $navigation->name
,
306 'url' => $navigation->url
,
307 'permission' => $navigation->permission
,
308 'operator' => $navigation->permission_operator
,
309 'separator' => $navigation->has_separator
,
310 'parentID' => $navigation->parent_id
,
311 'navID' => $navigation->id
,
312 'active' => $navigation->is_active
,
314 self
::buildNavigationTree($navigationTree[$navigation->id
]['child'], $navigation->id
, $navigationMenu);
317 return $navigationTree;
324 * By default output is html.
325 * @param bool $navigationMenu
326 * True when called for building top navigation menu.
328 * @return returns html or json object
331 public static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
332 $navigations = array();
333 self
::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
334 $navigationString = NULL;
336 // run the Navigation through a hook so users can modify it
337 CRM_Utils_Hook
::navigationMenu($navigations);
339 $i18n = CRM_Core_I18n
::singleton();
341 //skip children menu item if user don't have access to parent menu item
342 $skipMenuItems = array();
343 foreach ($navigations as $key => $value) {
345 if ($navigationString) {
346 $navigationString .= '},';
348 $data = $value['attributes']['label'];
350 if (!$value['attributes']['active']) {
351 $class = ', "attr": { "class" : "disabled"} ';
353 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
354 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
357 // Home is a special case
358 if ($value['attributes']['name'] != 'Home') {
359 $name = self
::getMenuName($value, $skipMenuItems);
362 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
363 $navigationString .= '<li class="menu-separator"></li>';
365 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
366 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
371 self
::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
375 $navigationString = '[' . $navigationString . '}]';
378 // clean up - Need to remove empty <ul>'s, this happens when user don't have
379 // permission to access parent
380 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
383 return $navigationString;
387 * Recursively check child menus
389 * @param array $value
390 * @param string $navigationString
392 * @param bool $skipMenuItems
395 public static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
397 if (!empty($value['child'])) {
398 $navigationString .= ', "children": [ ';
401 return $navigationString;
404 if (!empty($value['child'])) {
407 foreach ($value['child'] as $k => $val) {
408 if ($count == count($value['child'])) {
409 $appendComma = FALSE;
411 $data = $val['attributes']['label'];
413 if (!$val['attributes']['active']) {
414 $class = ', "attr": { "class" : "disabled"} ';
416 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
417 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
418 $navigationString .= $appendComma ?
' },' : ' }';
423 if (!empty($value['child'])) {
424 $navigationString .= ' ]';
428 if (!empty($value['child'])) {
429 $navigationString .= '<ul>';
432 $navigationString .= '</li>';
433 //locate separator after
434 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
435 $navigationString .= '<li class="menu-separator"></li>';
439 if (!empty($value['child'])) {
440 foreach ($value['child'] as $val) {
441 $name = self
::getMenuName($val, $skipMenuItems);
443 //locate separator before
444 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
445 $navigationString .= '<li class="menu-separator"></li>';
447 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
448 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
449 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
453 if (!empty($value['child'])) {
454 $navigationString .= '</ul></li>';
455 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
456 $navigationString .= '<li class="menu-separator"></li>';
460 return $navigationString;
467 * @param array $skipMenuItems
468 * @return bool|string
470 public static function getMenuName(&$value, &$skipMenuItems) {
471 // we need to localise the menu labels (CRM-5456) and don’t
472 // want to use ts() as it would throw the ts-extractor off
473 $i18n = CRM_Core_I18n
::singleton();
475 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
476 $url = $value['attributes']['url'];
477 $permission = $value['attributes']['permission'];
478 $operator = $value['attributes']['operator'];
479 $parentID = $value['attributes']['parentID'];
480 $navID = $value['attributes']['navID'];
481 $active = $value['attributes']['active'];
482 $menuName = $value['attributes']['name'];
483 $target = CRM_Utils_Array
::value('target', $value['attributes']);
485 if (in_array($parentID, $skipMenuItems) ||
!$active) {
486 $skipMenuItems[] = $navID;
490 //we need to check core view/edit or supported acls.
491 if (in_array($menuName, array(
492 'Search...', 'Contacts'))) {
493 if (!CRM_Core_Permission
::giveMeAllACLs()) {
494 $skipMenuItems[] = $navID;
499 $config = CRM_Core_Config
::singleton();
502 if (isset($url) && $url) {
503 if (substr($url, 0, 4) !== 'http') {
504 //CRM-7656 --make sure to separate out url path from url params,
505 //as we'r going to validate url path across cross-site scripting.
506 $urlParam = explode('?', $url);
507 if (empty($urlParam[1])) {
510 $url = CRM_Utils_System
::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
515 static $allComponents;
516 if (!$allComponents) {
517 $allComponents = CRM_Core_Component
::getNames();
520 if (isset($permission) && $permission) {
521 $permissions = explode(',', $permission);
523 $hasPermission = FALSE;
524 foreach ($permissions as $key) {
528 //get the component name from permission.
529 $componentName = CRM_Core_Permission
::getComponentName($key);
531 if ($componentName) {
532 if (!in_array($componentName, $config->enableComponents
) ||
533 !CRM_Core_Permission
::check($key)
536 if ($operator == 'AND') {
537 $skipMenuItems[] = $navID;
542 $hasPermission = TRUE;
545 elseif (!CRM_Core_Permission
::check($key)) {
547 if ($operator == 'AND') {
548 $skipMenuItems[] = $navID;
553 $hasPermission = TRUE;
557 if (!$showItem && !$hasPermission) {
558 $skipMenuItems[] = $navID;
565 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
568 $name = "<a href=\"{$url}\">{$name}</a>";
576 * Create navigation for CiviCRM Admin Menu
578 * @param int $contactID
581 * @return string $navigation returns navigation html
584 public static function createNavigation($contactID) {
585 $config = CRM_Core_Config
::singleton();
587 $navigation = self
::buildNavigation();
591 //add additional navigation items
592 $logoutURL = CRM_Utils_System
::url('civicrm/logout', 'reset=1');
594 // get home menu from db
595 $homeParams = array('name' => 'Home');
597 $homeIcon = '<img src="' . $config->userFrameworkResourceURL
. 'i/logo16px.png" style="vertical-align:middle;" />';
598 self
::retrieve($homeParams, $homeNav);
600 list($path, $q) = explode('?', $homeNav['url']);
601 $homeURL = CRM_Utils_System
::url($path, $q);
602 $homeLabel = $homeNav['label'];
603 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
604 if ($homeLabel == 'Home') {
605 $homeLabel = ts('CiviCRM Home');
609 $homeURL = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
610 $homeLabel = ts('CiviCRM Home');
612 // Link to hide the menubar
614 ($config->userSystem
->is_drupal
) &&
615 ((module_exists('toolbar') && user_access('access toolbar')) ||
616 module_exists('admin_menu') && user_access('access administration menu')
619 $hideLabel = ts('Drupal Menu');
621 elseif ($config->userSystem
->is_wordpress
) {
622 $hideLabel = ts('WordPress Menu');
625 $hideLabel = ts('Hide Menu');
629 <li class='menumain crm-link-home'>$homeIcon
630 <ul id='civicrm-home'>
631 <li><a href='$homeURL'>$homeLabel</a></li>
632 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
633 <li><a href='$logoutURL' class='crm-logout-link'>" . ts('Log out') . "</a></li>
635 // <li> tag doesn't need to be closed
637 return $prepandString . $navigation;
641 * Reset navigation for all contacts or a specified contact
643 * @param int $contactID
644 * Reset only entries belonging to that contact ID.
647 public static function resetNavigation($contactID = NULL) {
648 $newKey = CRM_Utils_String
::createRandom(self
::CACHE_KEY_STRLEN
, CRM_Utils_String
::ALPHANUMERIC
);
650 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
651 CRM_Core_DAO
::executeQuery($query);
652 CRM_Core_BAO_Cache
::deleteGroup('navigation');
655 // before inserting check if contact id exists in db
656 // this is to handle weird case when contact id is in session but not in db
657 $contact = new CRM_Contact_DAO_Contact();
658 $contact->id
= $contactID;
659 if ($contact->find(TRUE)) {
660 CRM_Core_BAO_Setting
::setItem(
662 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
670 // also reset the dashlet cache in case permissions have changed etc
671 // FIXME: decouple this
672 CRM_Core_BAO_Dashboard
::resetDashletCache($contactID);
680 * @param array $params
681 * Associated array, $_GET.
686 public static function processNavigation(&$params) {
687 $nodeID = (int)str_replace("node_", "", $params['id']);
688 $referenceID = (int)str_replace("node_", "", $params['ref_id']);
689 $position = $params['ps'];
690 $type = $params['type'];
691 $label = CRM_Utils_Array
::value('data', $params);
695 self
::processMove($nodeID, $referenceID, $position);
699 self
::processRename($nodeID, $label);
703 self
::processDelete($nodeID);
707 //reset navigation menus
708 self
::resetNavigation();
709 CRM_Utils_System
::civiExit();
713 * Process move action
716 * Node that is being moved.
717 * @param $referenceID
718 * Parent id where node is moved. 0 mean no parent.
720 * New position of the nod, it starts with 0 - n.
725 public static function processMove($nodeID, $referenceID, $position) {
726 // based on the new position we need to get the weight of the node after moved node
727 // 1. update the weight of $position + 1 nodes to weight + 1
728 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
730 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
731 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
732 // accordingly set the new parent_id
734 $newParentID = $referenceID;
735 $parentClause = "parent_id = {$referenceID} ";
738 $newParentID = 'NULL';
739 $parentClause = 'parent_id IS NULL';
742 $incrementOtherNodes = TRUE;
743 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
744 $params = array(1 => array($position, 'Positive'));
745 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
747 // this means node is moved to last position, so you need to get the weight of last element + 1
749 $lastPosition = $position - 1;
750 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
751 $params = array(1 => array($lastPosition, 'Positive'));
752 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
754 // since last node increment + 1
755 $newWeight = $newWeight +
1;
757 // since this is a last node we don't need to increment other nodes
758 $incrementOtherNodes = FALSE;
761 $transaction = new CRM_Core_Transaction();
763 // now update the existing nodes to weight + 1, if required.
764 if ($incrementOtherNodes) {
765 $query = "UPDATE civicrm_navigation SET weight = weight + 1
766 WHERE {$parentClause} AND weight >= {$newWeight}";
768 CRM_Core_DAO
::executeQuery($query);
771 // finally set the weight of current node
772 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
773 CRM_Core_DAO
::executeQuery($query);
775 $transaction->commit();
779 * Function to process rename action for tree
784 public static function processRename($nodeID, $label) {
785 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
789 * Process delete action for tree
793 public static function processDelete($nodeID) {
794 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
795 CRM_Core_DAO
::executeQuery($query);
799 * Get the info on navigation item
801 * @param int $navigationID
804 * @return array associated array
807 public static function getNavigationInfo($navigationID) {
808 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
809 $params = array($navigationID, 'Integer');
810 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => $params));
813 'parent_id' => $dao->parent_id
,
814 'weight' => $dao->weight
,
821 * @param array $params
822 * @param array $newParams
823 * New value of params.
826 public static function processUpdate($params, $newParams) {
827 $dao = new CRM_Core_DAO_Navigation();
828 $dao->copyValues($params);
829 if ($dao->find(TRUE)) {
830 $dao->copyValues($newParams);
838 * @return object|string
840 public static function getCacheKey($cid) {
841 $key = CRM_Core_BAO_Setting
::getItem(
842 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
848 if (strlen($key) !== self
::CACHE_KEY_STRLEN
) {
849 $key = self
::resetNavigation($cid);