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
152 * @param int $parentID
153 * Parent_id of a menu.
157 * @return int $weight string
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
182 * @return array $navigations 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.
275 * @return array $navigationTree 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('label' => $label,
306 'name' => $navigation->name
,
307 'url' => $navigation->url
,
308 'permission' => $navigation->permission
,
309 'operator' => $navigation->permission_operator
,
310 'separator' => $navigation->has_separator
,
311 'parentID' => $navigation->parent_id
,
312 'navID' => $navigation->id
,
313 'active' => $navigation->is_active
,
315 self
::buildNavigationTree($navigationTree[$navigation->id
]['child'], $navigation->id
, $navigationMenu);
318 return $navigationTree;
325 * By default output is html.
326 * @param bool $navigationMenu
327 * True when called for building top navigation menu.
329 * @return returns html or json object
332 public static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
333 $navigations = array();
334 self
::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
335 $navigationString = NULL;
337 // run the Navigation through a hook so users can modify it
338 CRM_Utils_Hook
::navigationMenu($navigations);
340 $i18n = CRM_Core_I18n
::singleton();
342 //skip children menu item if user don't have access to parent menu item
343 $skipMenuItems = array();
344 foreach ($navigations as $key => $value) {
346 if ($navigationString) {
347 $navigationString .= '},';
349 $data = $value['attributes']['label'];
351 if (!$value['attributes']['active']) {
352 $class = ', "attr": { "class" : "disabled"} ';
354 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
355 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
358 // Home is a special case
359 if ($value['attributes']['name'] != 'Home') {
360 $name = self
::getMenuName($value, $skipMenuItems);
363 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
364 $navigationString .= '<li class="menu-separator"></li>';
366 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
367 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
372 self
::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
376 $navigationString = '[' . $navigationString . '}]';
379 // clean up - Need to remove empty <ul>'s, this happens when user don't have
380 // permission to access parent
381 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
384 return $navigationString;
388 * Recursively check child menus
390 * @param array $value
391 * @param string $navigationString
393 * @param bool $skipMenuItems
396 public static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
398 if (!empty($value['child'])) {
399 $navigationString .= ', "children": [ ';
402 return $navigationString;
405 if (!empty($value['child'])) {
408 foreach ($value['child'] as $k => $val) {
409 if ($count == count($value['child'])) {
410 $appendComma = FALSE;
412 $data = $val['attributes']['label'];
414 if (!$val['attributes']['active']) {
415 $class = ', "attr": { "class" : "disabled"} ';
417 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
418 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
419 $navigationString .= $appendComma ?
' },' : ' }';
424 if (!empty($value['child'])) {
425 $navigationString .= ' ]';
429 if (!empty($value['child'])) {
430 $navigationString .= '<ul>';
433 $navigationString .= '</li>';
434 //locate separator after
435 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
436 $navigationString .= '<li class="menu-separator"></li>';
440 if (!empty($value['child'])) {
441 foreach ($value['child'] as $val) {
442 $name = self
::getMenuName($val, $skipMenuItems);
444 //locate separator before
445 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
446 $navigationString .= '<li class="menu-separator"></li>';
448 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
449 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
450 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
454 if (!empty($value['child'])) {
455 $navigationString .= '</ul></li>';
456 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
457 $navigationString .= '<li class="menu-separator"></li>';
461 return $navigationString;
468 * @param array $skipMenuItems
469 * @return bool|string
471 public static function getMenuName(&$value, &$skipMenuItems) {
472 // we need to localise the menu labels (CRM-5456) and don’t
473 // want to use ts() as it would throw the ts-extractor off
474 $i18n = CRM_Core_I18n
::singleton();
476 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
477 $url = $value['attributes']['url'];
478 $permission = $value['attributes']['permission'];
479 $operator = $value['attributes']['operator'];
480 $parentID = $value['attributes']['parentID'];
481 $navID = $value['attributes']['navID'];
482 $active = $value['attributes']['active'];
483 $menuName = $value['attributes']['name'];
484 $target = CRM_Utils_Array
::value('target', $value['attributes']);
486 if (in_array($parentID, $skipMenuItems) ||
!$active) {
487 $skipMenuItems[] = $navID;
491 //we need to check core view/edit or supported acls.
492 if (in_array($menuName, array(
493 'Search...', 'Contacts'))) {
494 if (!CRM_Core_Permission
::giveMeAllACLs()) {
495 $skipMenuItems[] = $navID;
500 $config = CRM_Core_Config
::singleton();
503 if (isset($url) && $url) {
504 if (substr($url, 0, 4) !== 'http') {
505 //CRM-7656 --make sure to separate out url path from url params,
506 //as we'r going to validate url path across cross-site scripting.
507 $urlParam = explode('?', $url);
508 if (empty($urlParam[1])) {
511 $url = CRM_Utils_System
::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
516 static $allComponents;
517 if (!$allComponents) {
518 $allComponents = CRM_Core_Component
::getNames();
521 if (isset($permission) && $permission) {
522 $permissions = explode(',', $permission);
524 $hasPermission = FALSE;
525 foreach ($permissions as $key) {
529 //get the component name from permission.
530 $componentName = CRM_Core_Permission
::getComponentName($key);
532 if ($componentName) {
533 if (!in_array($componentName, $config->enableComponents
) ||
534 !CRM_Core_Permission
::check($key)
537 if ($operator == 'AND') {
538 $skipMenuItems[] = $navID;
543 $hasPermission = TRUE;
546 elseif (!CRM_Core_Permission
::check($key)) {
548 if ($operator == 'AND') {
549 $skipMenuItems[] = $navID;
554 $hasPermission = TRUE;
558 if (!$showItem && !$hasPermission) {
559 $skipMenuItems[] = $navID;
566 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
569 $name = "<a href=\"{$url}\">{$name}</a>";
577 * Create navigation for CiviCRM Admin Menu
579 * @param int $contactID
582 * @return string $navigation returns navigation html
585 public static function createNavigation($contactID) {
586 $config = CRM_Core_Config
::singleton();
588 $navigation = self
::buildNavigation();
592 //add additional navigation items
593 $logoutURL = CRM_Utils_System
::url('civicrm/logout', 'reset=1');
595 // get home menu from db
596 $homeParams = array('name' => 'Home');
598 $homeIcon = '<img src="' . $config->userFrameworkResourceURL
. 'i/logo16px.png" style="vertical-align:middle;" />';
599 self
::retrieve($homeParams, $homeNav);
601 list($path, $q) = explode('?', $homeNav['url']);
602 $homeURL = CRM_Utils_System
::url($path, $q);
603 $homeLabel = $homeNav['label'];
604 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
605 if ($homeLabel == 'Home') {
606 $homeLabel = ts('CiviCRM Home');
610 $homeURL = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
611 $homeLabel = ts('CiviCRM Home');
613 // Link to hide the menubar
615 ($config->userSystem
->is_drupal
) &&
616 ((module_exists('toolbar') && user_access('access toolbar')) ||
617 module_exists('admin_menu') && user_access('access administration menu')
620 $hideLabel = ts('Drupal Menu');
622 elseif ($config->userSystem
->is_wordpress
) {
623 $hideLabel = ts('WordPress Menu');
626 $hideLabel = ts('Hide Menu');
630 <li class='menumain crm-link-home'>$homeIcon
631 <ul id='civicrm-home'>
632 <li><a href='$homeURL'>$homeLabel</a></li>
633 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
634 <li><a href='$logoutURL' class='crm-logout-link'>" . ts('Log out') . "</a></li>
636 // <li> tag doesn't need to be closed
638 return $prepandString . $navigation;
642 * Reset navigation for all contacts or a specified contact
644 * @param int $contactID
645 * Reset only entries belonging to that contact ID.
648 public static function resetNavigation($contactID = NULL) {
649 $newKey = CRM_Utils_String
::createRandom(self
::CACHE_KEY_STRLEN
, CRM_Utils_String
::ALPHANUMERIC
);
651 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
652 CRM_Core_DAO
::executeQuery($query);
653 CRM_Core_BAO_Cache
::deleteGroup('navigation');
656 // before inserting check if contact id exists in db
657 // this is to handle weird case when contact id is in session but not in db
658 $contact = new CRM_Contact_DAO_Contact();
659 $contact->id
= $contactID;
660 if ($contact->find(TRUE)) {
661 CRM_Core_BAO_Setting
::setItem(
663 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
671 // also reset the dashlet cache in case permissions have changed etc
672 // FIXME: decouple this
673 CRM_Core_BAO_Dashboard
::resetDashletCache($contactID);
681 * @param array $params
682 * Associated array, $_GET.
687 public static function processNavigation(&$params) {
688 $nodeID = (int)str_replace("node_", "", $params['id']);
689 $referenceID = (int)str_replace("node_", "", $params['ref_id']);
690 $position = $params['ps'];
691 $type = $params['type'];
692 $label = CRM_Utils_Array
::value('data', $params);
696 self
::processMove($nodeID, $referenceID, $position);
700 self
::processRename($nodeID, $label);
704 self
::processDelete($nodeID);
708 //reset navigation menus
709 self
::resetNavigation();
710 CRM_Utils_System
::civiExit();
714 * Process move action
717 * Node that is being moved.
718 * @param $referenceID
719 * Parent id where node is moved. 0 mean no parent.
721 * New position of the nod, it starts with 0 - n.
726 public static function processMove($nodeID, $referenceID, $position) {
727 // based on the new position we need to get the weight of the node after moved node
728 // 1. update the weight of $position + 1 nodes to weight + 1
729 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
731 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
732 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
733 // accordingly set the new parent_id
735 $newParentID = $referenceID;
736 $parentClause = "parent_id = {$referenceID} ";
739 $newParentID = 'NULL';
740 $parentClause = 'parent_id IS NULL';
743 $incrementOtherNodes = TRUE;
744 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
745 $params = array(1 => array($position, 'Positive'));
746 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
748 // this means node is moved to last position, so you need to get the weight of last element + 1
750 $lastPosition = $position - 1;
751 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
752 $params = array(1 => array($lastPosition, 'Positive'));
753 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
755 // since last node increment + 1
756 $newWeight = $newWeight +
1;
758 // since this is a last node we don't need to increment other nodes
759 $incrementOtherNodes = FALSE;
762 $transaction = new CRM_Core_Transaction();
764 // now update the existing nodes to weight + 1, if required.
765 if ($incrementOtherNodes) {
766 $query = "UPDATE civicrm_navigation SET weight = weight + 1
767 WHERE {$parentClause} AND weight >= {$newWeight}";
769 CRM_Core_DAO
::executeQuery($query);
772 // finally set the weight of current node
773 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
774 CRM_Core_DAO
::executeQuery($query);
776 $transaction->commit();
780 * Function to process rename action for tree
785 public static function processRename($nodeID, $label) {
786 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
790 * Process delete action for tree
794 public static function processDelete($nodeID) {
795 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
796 CRM_Core_DAO
::executeQuery($query);
800 * Get the info on navigation item
802 * @param int $navigationID
805 * @return array associated array
808 public static function getNavigationInfo($navigationID) {
809 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
810 $params = array($navigationID, 'Integer');
811 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => $params));
814 'parent_id' => $dao->parent_id
,
815 'weight' => $dao->weight
,
822 * @param array $params
823 * @param array $newParams
824 * New value of params.
827 public static function processUpdate($params, $newParams) {
828 $dao = new CRM_Core_DAO_Navigation();
829 $dao->copyValues($params);
830 if ($dao->find(TRUE)) {
831 $dao->copyValues($newParams);
839 * @return object|string
841 public static function getCacheKey($cid) {
842 $key = CRM_Core_BAO_Setting
::getItem(
843 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
849 if (strlen($key) !== self
::CACHE_KEY_STRLEN
) {
850 $key = self
::resetNavigation($cid);