3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
35 class CRM_Core_BAO_Navigation
extends CRM_Core_DAO_Navigation
{
40 function __construct() {
41 parent
::__construct();
45 * update the is_active flag in the db
47 * @param int $id id of the database record
48 * @param boolean $is_active value we want to set the is_active field
50 * @return Object DAO object on sucess, null otherwise
55 static function setIsActive($id, $is_active) {
56 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $id, 'is_active', $is_active);
60 * Function to get existing / build navigation for CiviCRM Admin Menu
63 * @return array associated array
65 static function getMenus() {
68 $menu = new CRM_Core_DAO_Menu();
69 $menu->domain_id
= CRM_Core_Config
::domainID();
72 while ($menu->fetch()) {
74 $menus[$menu->path
] = $menu->title
;
81 * Function to add/update navigation record
83 * @param array associated array of submitted values
85 * @return object navigation object
88 static function add(&$params) {
89 $navigation = new CRM_Core_DAO_Navigation();
91 $params['is_active'] = CRM_Utils_Array
::value('is_active', $params, FALSE);
92 $params['has_separator'] = CRM_Utils_Array
::value('has_separator', $params, FALSE);
94 if (!isset($params['id']) ||
95 (CRM_Utils_Array
::value( 'parent_id', $params ) != CRM_Utils_Array
::value('current_parent_id', $params))
97 /* re/calculate the weight, if the Parent ID changed OR create new menu */
99 if ($navName = CRM_Utils_Array
::value('name', $params)) {
100 $params['name'] = $navName;
102 elseif ($navLabel = CRM_Utils_Array
::value('label', $params)) {
103 $params['name'] = $navLabel;
106 $params['weight'] = self
::calculateWeight(CRM_Utils_Array
::value('parent_id', $params));
109 if (array_key_exists('permission', $params) && is_array($params['permission'])) {
110 $params['permission'] = implode(',', $params['permission']);
113 $navigation->copyValues($params);
115 $navigation->domain_id
= CRM_Core_Config
::domainID();
122 * Takes a bunch of params that are needed to match certain criteria and
123 * retrieves the relevant objects. Typically the valid params are only
124 * contact_id. We'll tweak this function to be more full featured over a period
125 * of time. This is the inverse function of create. It also stores all the retrieved
126 * values in the default array
128 * @param array $params (reference ) an assoc array of name/value pairs
129 * @param array $defaults (reference ) an assoc array to hold the flattened values
131 * @return object CRM_Core_BAO_Navigation object on success, null otherwise
135 static function retrieve(&$params, &$defaults) {
136 $navigation = new CRM_Core_DAO_Navigation();
137 $navigation->copyValues($params);
139 $navigation->domain_id
= CRM_Core_Config
::domainID();
141 if ($navigation->find(TRUE)) {
142 CRM_Core_DAO
::storeValues($navigation, $defaults);
149 * Calculate navigation weight
151 * @param $parentID parent_id of a menu
152 * @param $menuID menu id
154 * @return $weight string
157 static function calculateWeight($parentID = NULL, $menuID = NULL) {
158 $domainID = CRM_Core_Config
::domainID();
161 // we reset weight for each parent, i.e we start from 1 to n
162 // calculate max weight for top level menus, if parent id is absent
164 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id IS NULL AND domain_id = $domainID";
167 // if parent is passed, we need to get max weight for that particular parent
168 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id = {$parentID} AND domain_id = $domainID";
171 $dao = CRM_Core_DAO
::executeQuery($query);
173 return $weight = $weight +
$dao->weight
;
177 * Get formatted menu list
179 * @return array $navigations returns associated array
182 static function getNavigationList() {
183 $cacheKeyString = "navigationList";
186 $config = CRM_Core_Config
::singleton();
188 // check if we can retrieve from database cache
189 $navigations = CRM_Core_BAO_Cache
::getItem('navigation', $cacheKeyString);
192 $domainID = CRM_Core_Config
::domainID();
194 SELECT id, label, parent_id, weight, is_active, name
195 FROM civicrm_navigation WHERE domain_id = $domainID {$whereClause} ORDER BY parent_id, weight ASC";
196 $result = CRM_Core_DAO
::executeQuery($query);
198 $pidGroups = array();
199 while ($result->fetch()) {
200 $pidGroups[$result->parent_id
][$result->label
] = $result->id
;
203 foreach ($pidGroups[''] as $label => $val) {
204 $pidGroups[''][$label] = self
::_getNavigationValue($val, $pidGroups);
207 $navigations = array();
208 self
::_getNavigationLabel($pidGroups[''], $navigations);
210 CRM_Core_BAO_Cache
::setItem($navigations, 'navigation', $cacheKeyString);
216 * helper function for getNavigationList( )
218 * @param array $list menu info
219 * @param array $navigations navigation menus
220 * @param string $separator menu separator
222 static function _getNavigationLabel($list, &$navigations, $separator = '') {
223 $i18n = CRM_Core_I18n
::singleton();
224 foreach ($list as $label => $val) {
225 if ($label == 'navigation_id') {
228 $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
229 $navigations[is_array($val) ?
$val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
230 if (is_array($val)) {
231 self
::_getNavigationLabel($val, $navigations, $separator . ' ');
237 * helper function for getNavigationList( )
239 * @param string $val menu name
240 * @param array $pidGroups parent menus
243 static function _getNavigationValue($val, &$pidGroups) {
244 if (array_key_exists($val, $pidGroups)) {
245 $list = array('navigation_id' => $val);
246 foreach ($pidGroups[$val] as $label => $id) {
247 $list[$label] = self
::_getNavigationValue($id, $pidGroups);
249 unset($pidGroups[$val]);
258 * Function to build navigation tree
260 * @param array $navigationTree nested array of menus
261 * @param int $parentID parent id
262 * @param boolean $navigationMenu true when called for building top navigation menu
264 * @return array $navigationTree nested array of menus
267 static function buildNavigationTree(&$navigationTree, $parentID, $navigationMenu = TRUE) {
268 $whereClause = " parent_id IS NULL";
271 $whereClause = " parent_id = {$parentID}";
274 $domainID = CRM_Core_Config
::domainID();
276 // get the list of menus
278 SELECT id, label, url, permission, permission_operator, has_separator, parent_id, is_active, name
279 FROM civicrm_navigation
281 AND domain_id = $domainID
282 ORDER BY parent_id, weight";
284 $navigation = CRM_Core_DAO
::executeQuery($query);
285 $config = CRM_Core_Config
::singleton();
286 while ($navigation->fetch()) {
287 $label = $navigation->label
;
288 if (!$navigationMenu) {
289 $label = addcslashes($label, '"');
292 // for each menu get their children
293 $navigationTree[$navigation->id
] = array(
294 'attributes' => array('label' => $label,
295 'name' => $navigation->name
,
296 'url' => $navigation->url
,
297 'permission' => $navigation->permission
,
298 'operator' => $navigation->permission_operator
,
299 'separator' => $navigation->has_separator
,
300 'parentID' => $navigation->parent_id
,
301 'navID' => $navigation->id
,
302 'active' => $navigation->is_active
,
304 self
::buildNavigationTree($navigationTree[$navigation->id
]['child'], $navigation->id
, $navigationMenu);
307 return $navigationTree;
311 * Function to build menu
313 * @param boolean $json by default output is html
314 * @param boolean $navigationMenu true when called for building top navigation menu
316 * @return returns html or json object
319 static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
320 $navigations = array();
321 self
::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
322 $navigationString = NULL;
324 // run the Navigation through a hook so users can modify it
325 CRM_Utils_Hook
::navigationMenu($navigations);
327 $i18n = CRM_Core_I18n
::singleton();
329 //skip children menu item if user don't have access to parent menu item
330 $skipMenuItems = array();
331 foreach ($navigations as $key => $value) {
333 if ($navigationString) {
334 $navigationString .= '},';
336 $data = $value['attributes']['label'];
338 if (!$value['attributes']['active']) {
339 $class = ', "attr": { "class" : "disabled"} ';
341 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
342 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
345 // Home is a special case
346 if ($value['attributes']['name'] != 'Home') {
347 $name = self
::getMenuName($value, $skipMenuItems);
350 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
351 $navigationString .= '<li class="menu-separator"></li>';
353 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
354 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
359 self
::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
363 $navigationString = '[' . $navigationString . '}]';
366 // clean up - Need to remove empty <ul>'s, this happens when user don't have
367 // permission to access parent
368 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
371 return $navigationString;
375 * Recursively check child menus
377 * @param array $value
378 * @param string $navigationString
379 * @param boolean $json
380 * @param boolean $skipMenuItems
383 static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
385 if (!empty($value['child'])) {
386 $navigationString .= ', "children": [ ';
389 return $navigationString;
392 if (!empty($value['child'])) {
395 foreach ($value['child'] as $k => $val) {
396 if ($count == count($value['child'])) {
397 $appendComma = FALSE;
399 $data = $val['attributes']['label'];
401 if (!$val['attributes']['active']) {
402 $class = ', "attr": { "class" : "disabled"} ';
404 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
405 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
406 $navigationString .= $appendComma ?
' },' : ' }';
411 if (!empty($value['child'])) {
412 $navigationString .= ' ]';
416 if (!empty($value['child'])) {
417 $navigationString .= '<ul>';
420 $navigationString .= '</li>';
421 //locate separator after
422 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
423 $navigationString .= '<li class="menu-separator"></li>';
427 if (!empty($value['child'])) {
428 foreach ($value['child'] as $val) {
429 $name = self
::getMenuName($val, $skipMenuItems);
431 //locate separator before
432 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
433 $navigationString .= '<li class="menu-separator"></li>';
435 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
436 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
437 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
441 if (!empty($value['child'])) {
442 $navigationString .= '</ul></li>';
443 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
444 $navigationString .= '<li class="menu-separator"></li>';
448 return $navigationString;
455 * @param $skipMenuItems
456 * @return bool|string
458 static function getMenuName(&$value, &$skipMenuItems) {
459 // we need to localise the menu labels (CRM-5456) and don’t
460 // want to use ts() as it would throw the ts-extractor off
461 $i18n = CRM_Core_I18n
::singleton();
463 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
464 $url = $value['attributes']['url'];
465 $permission = $value['attributes']['permission'];
466 $operator = $value['attributes']['operator'];
467 $parentID = $value['attributes']['parentID'];
468 $navID = $value['attributes']['navID'];
469 $active = $value['attributes']['active'];
470 $menuName = $value['attributes']['name'];
471 $target = CRM_Utils_Array
::value('target', $value['attributes']);
473 if (in_array($parentID, $skipMenuItems) ||
!$active) {
474 $skipMenuItems[] = $navID;
478 //we need to check core view/edit or supported acls.
479 if (in_array($menuName, array(
480 'Search...', 'Contacts'))) {
481 if (!CRM_Core_Permission
::giveMeAllACLs()) {
482 $skipMenuItems[] = $navID;
487 $config = CRM_Core_Config
::singleton();
490 if (isset($url) && $url) {
491 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 // if on frontend, do not create navigation menu items, CRM-5349
575 if ($config->userFrameworkFrontend
) {
576 return "<!-- $config->lcMessages -->";
579 $navParams = array('contact_id' => $contactID);
581 $navigation = CRM_Core_BAO_Setting
::getItem(
582 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
589 // FIXME: hack for CRM-5027: we need to prepend the navigation string with
590 // (HTML-commented-out) locale info so that we rebuild menu on locale changes
593 substr($navigation, 0, 14) != "<!-- $config->lcMessages -->"
595 //retrieve navigation if it's not cached.
596 $navigation = self
::buildNavigation();
598 //add additional navigation items
599 $logoutURL = CRM_Utils_System
::url('civicrm/logout', 'reset=1');
600 $appendSring = "<li id=\"menu-logout\" class=\"menumain\"><a href=\"{$logoutURL}\">" . ts('Logout') . "</a></li>";
602 // get home menu from db
603 $homeParams = array('name' => 'Home');
605 self
::retrieve($homeParams, $homeNav);
607 list($path, $q) = explode('&', $homeNav['url']);
608 $homeURL = CRM_Utils_System
::url($path, $q);
609 $homeLabel = $homeNav['label'];
610 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
611 if ($homeLabel == 'Home') {
612 $homeLabel = ts('Home');
616 $homeURL = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
617 $homeLabel = ts('Home');
621 ($config->userSystem
->is_drupal
) &&
622 ((module_exists('toolbar') && user_access('access toolbar')) ||
623 module_exists('admin_menu') && user_access('access administration menu')
626 $prepandString = "<li class=\"menumain crm-link-home\">" . $homeLabel . "<ul id=\"civicrm-home\"><li><a href=\"{$homeURL}\">" . $homeLabel . "</a></li><li><a href=\"#\" onclick=\"cj.Menu.closeAll( );cj('#civicrm-menu').toggle( );\">" . ts('Drupal Menu') . "</a></li></ul>";
628 elseif ($config->userSystem
->is_wordpress
) {
629 $prepandString = "<li class=\"menumain crm-link-home\">" . $homeLabel . "<ul id=\"civicrm-home\"><li><a href=\"{$homeURL}\">" . $homeLabel . "</a></li><li><a href=\"#\" onclick=\"cj.Menu.closeAll( );cj('#civicrm-menu').toggle( );\">" . ts('WordPress Menu') . "</a></li></ul>";
632 $prepandString = "<li class=\"menumain crm-link-home\"><a href=\"{$homeURL}\" title=\"" . $homeLabel . "\">" . $homeLabel . "</a>";
635 // prepend the navigation with locale info for CRM-5027
636 $navigation = "<!-- $config->lcMessages -->" . $prepandString . $navigation . $appendSring;
638 // before inserting check if contact id exists in db
639 // this is to handle wierd case when contact id is in session but not in db
640 $contact = new CRM_Contact_DAO_Contact();
641 $contact->id
= $contactID;
642 if ($contact->find(TRUE)) {
643 CRM_Core_BAO_Setting
::setItem(
645 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
657 * Reset navigation for all contacts
659 * @param integer $contactID - reset only entries belonging to that contact ID
661 static function resetNavigation($contactID = NULL) {
663 $query = "UPDATE civicrm_setting SET value = NULL WHERE name='navigation'";
665 $query .= " AND contact_id = %1";
666 $params[1] = array($contactID, 'Integer');
669 $query .= " AND contact_id IS NOT NULL";
672 CRM_Core_DAO
::executeQuery($query, $params);
673 CRM_Core_BAO_Cache
::deleteGroup('navigation');
675 // also reset the dashlet cache in case permissions have changed etc
676 CRM_Core_BAO_Dashboard
::resetDashletCache($contactID);
680 * Function to process navigation
682 * @param array $params associated array, $_GET
687 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 * Function to process move action
716 * @param $nodeID node that is being moved
717 * @param $referenceID parent id where node is moved. 0 mean no parent
718 * @param $position new position of the nod, it starts with 0 - n
723 static function processMove($nodeID, $referenceID, $position) {
724 // based on the new position we need to get the weight of the node after moved node
725 // 1. update the weight of $position + 1 nodes to weight + 1
726 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
728 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
729 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
730 // accordingly set the new parent_id
732 $newParentID = $referenceID;
733 $parentClause = "parent_id = {$referenceID} ";
736 $newParentID = 'NULL';
737 $parentClause = 'parent_id IS NULL';
740 $incrementOtherNodes = true;
741 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
742 $params = array(1 => array( $position, 'Positive'));
743 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
745 // this means node is moved to last position, so you need to get the weight of last element + 1
747 $lastPosition = $position - 1;
748 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
749 $params = array(1 => array($lastPosition, 'Positive'));
750 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
752 // since last node increment + 1
753 $newWeight = $newWeight +
1;
755 // since this is a last node we don't need to increment other nodes
756 $incrementOtherNodes = false;
759 $transaction = new CRM_Core_Transaction();
761 // now update the existing nodes to weight + 1, if required.
762 if ( $incrementOtherNodes ) {
763 $query = "UPDATE civicrm_navigation SET weight = weight + 1
764 WHERE {$parentClause} AND weight >= {$newWeight}";
766 CRM_Core_DAO
::executeQuery($query);
769 // finally set the weight of current node
770 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
771 CRM_Core_DAO
::executeQuery($query);
773 $transaction->commit();
777 * Function to process rename action for tree
782 static function processRename($nodeID, $label) {
783 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
787 * Function to process delete action for tree
791 static function processDelete($nodeID) {
792 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
793 CRM_Core_DAO
::executeQuery($query);
797 * Function to get the info on navigation item
799 * @param int $navigationID navigation id
801 * @return array associated array
804 static function getNavigationInfo($navigationID) {
805 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
806 $params = array($navigationID, 'Integer');
807 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => $params));
810 'parent_id' => $dao->parent_id
,
811 'weight' => $dao->weight
,
816 * Function to update menu
818 * @param array $params
819 * @param array $newParams new value of params
822 static function processUpdate($params, $newParams) {
823 $dao = new CRM_Core_DAO_Navigation();
824 $dao->copyValues($params);
825 if ($dao->find(TRUE)) {
826 $dao->copyValues($newParams);