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 $weight string
160 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 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( )
221 * @param array $list menu info
222 * @param array $navigations navigation menus
223 * @param string $separator menu separator
225 static function _getNavigationLabel($list, &$navigations, $separator = '') {
226 $i18n = CRM_Core_I18n
::singleton();
227 foreach ($list as $label => $val) {
228 if ($label == 'navigation_id') {
231 $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
232 $navigations[is_array($val) ?
$val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
233 if (is_array($val)) {
234 self
::_getNavigationLabel($val, $navigations, $separator . ' ');
240 * helper function for getNavigationList( )
242 * @param string $val menu name
243 * @param array $pidGroups parent menus
246 static function _getNavigationValue($val, &$pidGroups) {
247 if (array_key_exists($val, $pidGroups)) {
248 $list = array('navigation_id' => $val);
249 foreach ($pidGroups[$val] as $label => $id) {
250 $list[$label] = self
::_getNavigationValue($id, $pidGroups);
252 unset($pidGroups[$val]);
261 * Function to build navigation tree
263 * @param array $navigationTree nested array of menus
264 * @param int $parentID parent id
265 * @param boolean $navigationMenu true when called for building top navigation menu
267 * @return array $navigationTree nested array of menus
270 static function buildNavigationTree(&$navigationTree, $parentID, $navigationMenu = TRUE) {
271 $whereClause = " parent_id IS NULL";
274 $whereClause = " parent_id = {$parentID}";
277 $domainID = CRM_Core_Config
::domainID();
279 // get the list of menus
281 SELECT id, label, url, permission, permission_operator, has_separator, parent_id, is_active, name
282 FROM civicrm_navigation
284 AND domain_id = $domainID
285 ORDER BY parent_id, weight";
287 $navigation = CRM_Core_DAO
::executeQuery($query);
288 $config = CRM_Core_Config
::singleton();
289 while ($navigation->fetch()) {
290 $label = $navigation->label
;
291 if (!$navigationMenu) {
292 $label = addcslashes($label, '"');
295 // for each menu get their children
296 $navigationTree[$navigation->id
] = array(
297 'attributes' => array('label' => $label,
298 'name' => $navigation->name
,
299 'url' => $navigation->url
,
300 'permission' => $navigation->permission
,
301 'operator' => $navigation->permission_operator
,
302 'separator' => $navigation->has_separator
,
303 'parentID' => $navigation->parent_id
,
304 'navID' => $navigation->id
,
305 'active' => $navigation->is_active
,
307 self
::buildNavigationTree($navigationTree[$navigation->id
]['child'], $navigation->id
, $navigationMenu);
310 return $navigationTree;
314 * Function to build menu
316 * @param boolean $json by default output is html
317 * @param boolean $navigationMenu true when called for building top navigation menu
319 * @return returns html or json object
322 static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
323 $navigations = array();
324 self
::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
325 $navigationString = NULL;
327 // run the Navigation through a hook so users can modify it
328 CRM_Utils_Hook
::navigationMenu($navigations);
330 $i18n = CRM_Core_I18n
::singleton();
332 //skip children menu item if user don't have access to parent menu item
333 $skipMenuItems = array();
334 foreach ($navigations as $key => $value) {
336 if ($navigationString) {
337 $navigationString .= '},';
339 $data = $value['attributes']['label'];
341 if (!$value['attributes']['active']) {
342 $class = ', "attr": { "class" : "disabled"} ';
344 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
345 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
348 // Home is a special case
349 if ($value['attributes']['name'] != 'Home') {
350 $name = self
::getMenuName($value, $skipMenuItems);
353 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
354 $navigationString .= '<li class="menu-separator"></li>';
356 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
357 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
362 self
::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
366 $navigationString = '[' . $navigationString . '}]';
369 // clean up - Need to remove empty <ul>'s, this happens when user don't have
370 // permission to access parent
371 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
374 return $navigationString;
378 * Recursively check child menus
380 * @param array $value
381 * @param string $navigationString
382 * @param boolean $json
383 * @param boolean $skipMenuItems
386 static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
388 if (!empty($value['child'])) {
389 $navigationString .= ', "children": [ ';
392 return $navigationString;
395 if (!empty($value['child'])) {
398 foreach ($value['child'] as $k => $val) {
399 if ($count == count($value['child'])) {
400 $appendComma = FALSE;
402 $data = $val['attributes']['label'];
404 if (!$val['attributes']['active']) {
405 $class = ', "attr": { "class" : "disabled"} ';
407 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
408 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
409 $navigationString .= $appendComma ?
' },' : ' }';
414 if (!empty($value['child'])) {
415 $navigationString .= ' ]';
419 if (!empty($value['child'])) {
420 $navigationString .= '<ul>';
423 $navigationString .= '</li>';
424 //locate separator after
425 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
426 $navigationString .= '<li class="menu-separator"></li>';
430 if (!empty($value['child'])) {
431 foreach ($value['child'] as $val) {
432 $name = self
::getMenuName($val, $skipMenuItems);
434 //locate separator before
435 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
436 $navigationString .= '<li class="menu-separator"></li>';
438 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
439 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
440 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
444 if (!empty($value['child'])) {
445 $navigationString .= '</ul></li>';
446 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
447 $navigationString .= '<li class="menu-separator"></li>';
451 return $navigationString;
458 * @param $skipMenuItems
459 * @return bool|string
461 static function getMenuName(&$value, &$skipMenuItems) {
462 // we need to localise the menu labels (CRM-5456) and don’t
463 // want to use ts() as it would throw the ts-extractor off
464 $i18n = CRM_Core_I18n
::singleton();
466 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
467 $url = $value['attributes']['url'];
468 $permission = $value['attributes']['permission'];
469 $operator = $value['attributes']['operator'];
470 $parentID = $value['attributes']['parentID'];
471 $navID = $value['attributes']['navID'];
472 $active = $value['attributes']['active'];
473 $menuName = $value['attributes']['name'];
474 $target = CRM_Utils_Array
::value('target', $value['attributes']);
476 if (in_array($parentID, $skipMenuItems) ||
!$active) {
477 $skipMenuItems[] = $navID;
481 //we need to check core view/edit or supported acls.
482 if (in_array($menuName, array(
483 'Search...', 'Contacts'))) {
484 if (!CRM_Core_Permission
::giveMeAllACLs()) {
485 $skipMenuItems[] = $navID;
490 $config = CRM_Core_Config
::singleton();
493 if (isset($url) && $url) {
494 if (substr($url, 0, 4) !== 'http') {
495 //CRM-7656 --make sure to separate out url path from url params,
496 //as we'r going to validate url path across cross-site scripting.
497 $urlParam = CRM_Utils_System
::explode('&', str_replace('?', '&', $url), 2);
498 $url = CRM_Utils_System
::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
503 static $allComponents;
504 if (!$allComponents) {
505 $allComponents = CRM_Core_Component
::getNames();
508 if (isset($permission) && $permission) {
509 $permissions = explode(',', $permission);
511 $hasPermission = FALSE;
512 foreach ($permissions as $key) {
516 //get the component name from permission.
517 $componentName = CRM_Core_Permission
::getComponentName($key);
519 if ($componentName) {
520 if (!in_array($componentName, $config->enableComponents
) ||
521 !CRM_Core_Permission
::check($key)
524 if ($operator == 'AND') {
525 $skipMenuItems[] = $navID;
530 $hasPermission = TRUE;
533 elseif (!CRM_Core_Permission
::check($key)) {
535 if ($operator == 'AND') {
536 $skipMenuItems[] = $navID;
541 $hasPermission = TRUE;
545 if (!$showItem && !$hasPermission) {
546 $skipMenuItems[] = $navID;
553 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
556 $name = "<a href=\"{$url}\">{$name}</a>";
564 * Function to create navigation for CiviCRM Admin Menu
566 * @param int $contactID contact id
568 * @return string $navigation returns navigation html
571 static function createNavigation($contactID) {
572 $config = CRM_Core_Config
::singleton();
574 $navigation = self
::buildNavigation();
578 //add additional navigation items
579 $logoutURL = CRM_Utils_System
::url('civicrm/logout', 'reset=1');
581 // get home menu from db
582 $homeParams = array('name' => 'Home');
584 $homeIcon = '<img src="' . $config->userFrameworkResourceURL
. 'i/logo16px.png" style="vertical-align:middle;" />';
585 self
::retrieve($homeParams, $homeNav);
587 list($path, $q) = explode('&', $homeNav['url']);
588 $homeURL = CRM_Utils_System
::url($path, $q);
589 $homeLabel = $homeNav['label'];
590 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
591 if ($homeLabel == 'Home') {
592 $homeLabel = ts('CiviCRM Home');
596 $homeURL = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
597 $homeLabel = ts('CiviCRM Home');
599 // Link to hide the menubar
601 ($config->userSystem
->is_drupal
) &&
602 ((module_exists('toolbar') && user_access('access toolbar')) ||
603 module_exists('admin_menu') && user_access('access administration menu')
606 $hideLabel = ts('Drupal Menu');
608 elseif ($config->userSystem
->is_wordpress
) {
609 $hideLabel = ts('WordPress Menu');
612 $hideLabel = ts('Hide Menu');
616 <li class='menumain crm-link-home'>$homeIcon
617 <ul id='civicrm-home'>
618 <li><a href='$homeURL'>$homeLabel</a></li>
619 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
620 <li><a href='$logoutURL' class='crm-logout-link'>". ts('Logout') ."</a></li>
622 // <li> tag doesn't need to be closed
624 return $prepandString . $navigation;
628 * Reset navigation for all contacts or a specified contact
630 * @param integer $contactID - reset only entries belonging to that contact ID
633 static function resetNavigation($contactID = NULL) {
634 $newKey = CRM_Utils_String
::createRandom(self
::CACHE_KEY_STRLEN
, CRM_Utils_String
::ALPHANUMERIC
);
636 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
637 CRM_Core_DAO
::executeQuery($query);
638 CRM_Core_BAO_Cache
::deleteGroup('navigation');
641 // before inserting check if contact id exists in db
642 // this is to handle weird case when contact id is in session but not in db
643 $contact = new CRM_Contact_DAO_Contact();
644 $contact->id
= $contactID;
645 if ($contact->find(TRUE)) {
646 CRM_Core_BAO_Setting
::setItem(
648 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
656 // also reset the dashlet cache in case permissions have changed etc
657 // FIXME: decouple this
658 CRM_Core_BAO_Dashboard
::resetDashletCache($contactID);
664 * Function to process navigation
666 * @param array $params associated array, $_GET
671 static function processNavigation(&$params) {
672 $nodeID = (int)str_replace("node_", "", $params['id']);
673 $referenceID = (int)str_replace("node_", "", $params['ref_id']);
674 $position = $params['ps'];
675 $type = $params['type'];
676 $label = CRM_Utils_Array
::value('data', $params);
680 self
::processMove($nodeID, $referenceID, $position);
684 self
::processRename($nodeID, $label);
688 self
::processDelete($nodeID);
692 //reset navigation menus
693 self
::resetNavigation();
694 CRM_Utils_System
::civiExit();
698 * Function to process move action
700 * @param $nodeID node that is being moved
701 * @param $referenceID parent id where node is moved. 0 mean no parent
702 * @param $position new position of the nod, it starts with 0 - n
707 static function processMove($nodeID, $referenceID, $position) {
708 // based on the new position we need to get the weight of the node after moved node
709 // 1. update the weight of $position + 1 nodes to weight + 1
710 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
712 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
713 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
714 // accordingly set the new parent_id
716 $newParentID = $referenceID;
717 $parentClause = "parent_id = {$referenceID} ";
720 $newParentID = 'NULL';
721 $parentClause = 'parent_id IS NULL';
724 $incrementOtherNodes = true;
725 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
726 $params = array(1 => array( $position, 'Positive'));
727 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
729 // this means node is moved to last position, so you need to get the weight of last element + 1
731 $lastPosition = $position - 1;
732 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
733 $params = array(1 => array($lastPosition, 'Positive'));
734 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
736 // since last node increment + 1
737 $newWeight = $newWeight +
1;
739 // since this is a last node we don't need to increment other nodes
740 $incrementOtherNodes = false;
743 $transaction = new CRM_Core_Transaction();
745 // now update the existing nodes to weight + 1, if required.
746 if ( $incrementOtherNodes ) {
747 $query = "UPDATE civicrm_navigation SET weight = weight + 1
748 WHERE {$parentClause} AND weight >= {$newWeight}";
750 CRM_Core_DAO
::executeQuery($query);
753 // finally set the weight of current node
754 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
755 CRM_Core_DAO
::executeQuery($query);
757 $transaction->commit();
761 * Function to process rename action for tree
766 static function processRename($nodeID, $label) {
767 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
771 * Function to process delete action for tree
775 static function processDelete($nodeID) {
776 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
777 CRM_Core_DAO
::executeQuery($query);
781 * Function to get the info on navigation item
783 * @param int $navigationID navigation id
785 * @return array associated array
788 static function getNavigationInfo($navigationID) {
789 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
790 $params = array($navigationID, 'Integer');
791 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => $params));
794 'parent_id' => $dao->parent_id
,
795 'weight' => $dao->weight
,
800 * Function to update menu
802 * @param array $params
803 * @param array $newParams new value of params
806 static function processUpdate($params, $newParams) {
807 $dao = new CRM_Core_DAO_Navigation();
808 $dao->copyValues($params);
809 if ($dao->find(TRUE)) {
810 $dao->copyValues($newParams);
815 static function getCacheKey($cid) {
816 $key = CRM_Core_BAO_Setting
::getItem(
817 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
823 if (strlen($key) !== self
::CACHE_KEY_STRLEN
) {
824 $key = self
::resetNavigation($cid);