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
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
57 public static function setIsActive($id, $is_active) {
58 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $id, 'is_active', $is_active);
62 * Get existing / build navigation for CiviCRM Admin Menu
65 * @return array associated array
67 public static function getMenus() {
70 $menu = new CRM_Core_DAO_Menu();
71 $menu->domain_id
= CRM_Core_Config
::domainID();
74 while ($menu->fetch()) {
76 $menus[$menu->path
] = $menu->title
;
83 * Add/update navigation record
85 * @param array associated array of submitted values
87 * @return object navigation object
90 public static function add(&$params) {
91 $navigation = new CRM_Core_DAO_Navigation();
93 $params['is_active'] = CRM_Utils_Array
::value('is_active', $params, FALSE);
94 $params['has_separator'] = CRM_Utils_Array
::value('has_separator', $params, FALSE);
96 if (!isset($params['id']) ||
97 (CRM_Utils_Array
::value( 'parent_id', $params ) != CRM_Utils_Array
::value('current_parent_id', $params))
99 /* re/calculate the weight, if the Parent ID changed OR create new menu */
101 if ($navName = CRM_Utils_Array
::value('name', $params)) {
102 $params['name'] = $navName;
104 elseif ($navLabel = CRM_Utils_Array
::value('label', $params)) {
105 $params['name'] = $navLabel;
108 $params['weight'] = self
::calculateWeight(CRM_Utils_Array
::value('parent_id', $params));
111 if (array_key_exists('permission', $params) && is_array($params['permission'])) {
112 $params['permission'] = implode(',', $params['permission']);
115 $navigation->copyValues($params);
117 $navigation->domain_id
= CRM_Core_Config
::domainID();
124 * Fetch object based on array of properties
126 * @param array $params (reference ) an assoc array of name/value pairs
127 * @param array $defaults (reference ) an assoc array to hold the flattened values
129 * @return CRM_Core_BAO_Navigation object on success, null otherwise
132 public static function retrieve(&$params, &$defaults) {
133 $navigation = new CRM_Core_DAO_Navigation();
134 $navigation->copyValues($params);
136 $navigation->domain_id
= CRM_Core_Config
::domainID();
138 if ($navigation->find(TRUE)) {
139 CRM_Core_DAO
::storeValues($navigation, $defaults);
146 * Calculate navigation weight
148 * @param $parentID parent_id of a menu
149 * @param $menuID menu id
151 * @return int $weight string@static
153 public static function calculateWeight($parentID = NULL, $menuID = NULL) {
154 $domainID = CRM_Core_Config
::domainID();
157 // we reset weight for each parent, i.e we start from 1 to n
158 // calculate max weight for top level menus, if parent id is absent
160 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id IS NULL AND domain_id = $domainID";
163 // if parent is passed, we need to get max weight for that particular parent
164 $query = "SELECT max(weight) as weight FROM civicrm_navigation WHERE parent_id = {$parentID} AND domain_id = $domainID";
167 $dao = CRM_Core_DAO
::executeQuery($query);
169 return $weight = $weight +
$dao->weight
;
173 * Get formatted menu list
175 * @return array $navigations returns associated array
178 public static function getNavigationList() {
179 $cacheKeyString = "navigationList";
182 $config = CRM_Core_Config
::singleton();
184 // check if we can retrieve from database cache
185 $navigations = CRM_Core_BAO_Cache
::getItem('navigation', $cacheKeyString);
188 $domainID = CRM_Core_Config
::domainID();
190 SELECT id, label, parent_id, weight, is_active, name
191 FROM civicrm_navigation WHERE domain_id = $domainID {$whereClause} ORDER BY parent_id, weight ASC";
192 $result = CRM_Core_DAO
::executeQuery($query);
194 $pidGroups = array();
195 while ($result->fetch()) {
196 $pidGroups[$result->parent_id
][$result->label
] = $result->id
;
199 foreach ($pidGroups[''] as $label => $val) {
200 $pidGroups[''][$label] = self
::_getNavigationValue($val, $pidGroups);
203 $navigations = array();
204 self
::_getNavigationLabel($pidGroups[''], $navigations);
206 CRM_Core_BAO_Cache
::setItem($navigations, 'navigation', $cacheKeyString);
212 * Helper function for getNavigationList( )
214 * @param array $list menu info
215 * @param array $navigations navigation menus
216 * @param string $separator menu separator
218 public static function _getNavigationLabel($list, &$navigations, $separator = '') {
219 $i18n = CRM_Core_I18n
::singleton();
220 foreach ($list as $label => $val) {
221 if ($label == 'navigation_id') {
224 $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
225 $navigations[is_array($val) ?
$val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
226 if (is_array($val)) {
227 self
::_getNavigationLabel($val, $navigations, $separator . ' ');
233 * Helper function for getNavigationList( )
235 * @param string $val menu name
236 * @param array $pidGroups parent menus
239 public static function _getNavigationValue($val, &$pidGroups) {
240 if (array_key_exists($val, $pidGroups)) {
241 $list = array('navigation_id' => $val);
242 foreach ($pidGroups[$val] as $label => $id) {
243 $list[$label] = self
::_getNavigationValue($id, $pidGroups);
245 unset($pidGroups[$val]);
254 * Build navigation tree
256 * @param array $navigationTree nested array of menus
257 * @param int $parentID parent id
258 * @param boolean $navigationMenu true when called for building top navigation menu
260 * @return array $navigationTree nested array of menus
263 public static function buildNavigationTree(&$navigationTree, $parentID, $navigationMenu = TRUE) {
264 $whereClause = " parent_id IS NULL";
267 $whereClause = " parent_id = {$parentID}";
270 $domainID = CRM_Core_Config
::domainID();
272 // get the list of menus
274 SELECT id, label, url, permission, permission_operator, has_separator, parent_id, is_active, name
275 FROM civicrm_navigation
277 AND domain_id = $domainID
278 ORDER BY parent_id, weight";
280 $navigation = CRM_Core_DAO
::executeQuery($query);
281 $config = CRM_Core_Config
::singleton();
282 while ($navigation->fetch()) {
283 $label = $navigation->label
;
284 if (!$navigationMenu) {
285 $label = addcslashes($label, '"');
288 // for each menu get their children
289 $navigationTree[$navigation->id
] = array(
290 'attributes' => array('label' => $label,
291 'name' => $navigation->name
,
292 'url' => $navigation->url
,
293 'permission' => $navigation->permission
,
294 'operator' => $navigation->permission_operator
,
295 'separator' => $navigation->has_separator
,
296 'parentID' => $navigation->parent_id
,
297 'navID' => $navigation->id
,
298 'active' => $navigation->is_active
,
300 self
::buildNavigationTree($navigationTree[$navigation->id
]['child'], $navigation->id
, $navigationMenu);
303 return $navigationTree;
309 * @param boolean $json by default output is html
310 * @param boolean $navigationMenu true when called for building top navigation menu
312 * @return returns html or json object
315 public static function buildNavigation($json = FALSE, $navigationMenu = TRUE) {
316 $navigations = array();
317 self
::buildNavigationTree($navigations, $parent = NULL, $navigationMenu);
318 $navigationString = NULL;
320 // run the Navigation through a hook so users can modify it
321 CRM_Utils_Hook
::navigationMenu($navigations);
323 $i18n = CRM_Core_I18n
::singleton();
325 //skip children menu item if user don't have access to parent menu item
326 $skipMenuItems = array();
327 foreach ($navigations as $key => $value) {
329 if ($navigationString) {
330 $navigationString .= '},';
332 $data = $value['attributes']['label'];
334 if (!$value['attributes']['active']) {
335 $class = ', "attr": { "class" : "disabled"} ';
337 $l10nName = $i18n->crm_translate($data, array('context' => 'menu'));
338 $navigationString .= ' { "attr": { "id" : "node_' . $key . '"}, "data": { "title":"' . $l10nName . '"' . $class . '}';
341 // Home is a special case
342 if ($value['attributes']['name'] != 'Home') {
343 $name = self
::getMenuName($value, $skipMenuItems);
346 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
347 $navigationString .= '<li class="menu-separator"></li>';
349 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
350 $navigationString .= '<li class="menumain crm-' . str_replace($removeCharacters, '_', $value['attributes']['label']) . '">' . $name;
355 self
::recurseNavigation($value, $navigationString, $json, $skipMenuItems);
359 $navigationString = '[' . $navigationString . '}]';
362 // clean up - Need to remove empty <ul>'s, this happens when user don't have
363 // permission to access parent
364 $navigationString = str_replace('<ul></ul></li>', '', $navigationString);
367 return $navigationString;
371 * Recursively check child menus
373 * @param array $value
374 * @param string $navigationString
375 * @param boolean $json
376 * @param boolean $skipMenuItems
379 public static function recurseNavigation(&$value, &$navigationString, $json, $skipMenuItems) {
381 if (!empty($value['child'])) {
382 $navigationString .= ', "children": [ ';
385 return $navigationString;
388 if (!empty($value['child'])) {
391 foreach ($value['child'] as $k => $val) {
392 if ($count == count($value['child'])) {
393 $appendComma = FALSE;
395 $data = $val['attributes']['label'];
397 if (!$val['attributes']['active']) {
398 $class = ', "attr": { "class" : "disabled"} ';
400 $navigationString .= ' { "attr": { "id" : "node_' . $k . '"}, "data": { "title":"' . $data . '"' . $class . '}';
401 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
402 $navigationString .= $appendComma ?
' },' : ' }';
407 if (!empty($value['child'])) {
408 $navigationString .= ' ]';
412 if (!empty($value['child'])) {
413 $navigationString .= '<ul>';
416 $navigationString .= '</li>';
417 //locate separator after
418 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
419 $navigationString .= '<li class="menu-separator"></li>';
423 if (!empty($value['child'])) {
424 foreach ($value['child'] as $val) {
425 $name = self
::getMenuName($val, $skipMenuItems);
427 //locate separator before
428 if (isset($val['attributes']['separator']) && $val['attributes']['separator'] == 2) {
429 $navigationString .= '<li class="menu-separator"></li>';
431 $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
432 $navigationString .= '<li class="crm-' . str_replace($removeCharacters, '_', $val['attributes']['label']) . '">' . $name;
433 self
::recurseNavigation($val, $navigationString, $json, $skipMenuItems);
437 if (!empty($value['child'])) {
438 $navigationString .= '</ul></li>';
439 if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 1) {
440 $navigationString .= '<li class="menu-separator"></li>';
444 return $navigationString;
451 * @param array $skipMenuItems
452 * @return bool|string
454 public static function getMenuName(&$value, &$skipMenuItems) {
455 // we need to localise the menu labels (CRM-5456) and don’t
456 // want to use ts() as it would throw the ts-extractor off
457 $i18n = CRM_Core_I18n
::singleton();
459 $name = $i18n->crm_translate($value['attributes']['label'], array('context' => 'menu'));
460 $url = $value['attributes']['url'];
461 $permission = $value['attributes']['permission'];
462 $operator = $value['attributes']['operator'];
463 $parentID = $value['attributes']['parentID'];
464 $navID = $value['attributes']['navID'];
465 $active = $value['attributes']['active'];
466 $menuName = $value['attributes']['name'];
467 $target = CRM_Utils_Array
::value('target', $value['attributes']);
469 if (in_array($parentID, $skipMenuItems) ||
!$active) {
470 $skipMenuItems[] = $navID;
474 //we need to check core view/edit or supported acls.
475 if (in_array($menuName, array(
476 'Search...', 'Contacts'))) {
477 if (!CRM_Core_Permission
::giveMeAllACLs()) {
478 $skipMenuItems[] = $navID;
483 $config = CRM_Core_Config
::singleton();
486 if (isset($url) && $url) {
487 if (substr($url, 0, 4) !== 'http') {
488 //CRM-7656 --make sure to separate out url path from url params,
489 //as we'r going to validate url path across cross-site scripting.
490 $urlParam = explode('?', $url);
491 if (empty($urlParam[1])) {
494 $url = CRM_Utils_System
::url($urlParam[0], $urlParam[1], FALSE, NULL, TRUE);
499 static $allComponents;
500 if (!$allComponents) {
501 $allComponents = CRM_Core_Component
::getNames();
504 if (isset($permission) && $permission) {
505 $permissions = explode(',', $permission);
507 $hasPermission = FALSE;
508 foreach ($permissions as $key) {
512 //get the component name from permission.
513 $componentName = CRM_Core_Permission
::getComponentName($key);
515 if ($componentName) {
516 if (!in_array($componentName, $config->enableComponents
) ||
517 !CRM_Core_Permission
::check($key)
520 if ($operator == 'AND') {
521 $skipMenuItems[] = $navID;
526 $hasPermission = TRUE;
529 elseif (!CRM_Core_Permission
::check($key)) {
531 if ($operator == 'AND') {
532 $skipMenuItems[] = $navID;
537 $hasPermission = TRUE;
541 if (!$showItem && !$hasPermission) {
542 $skipMenuItems[] = $navID;
549 $name = "<a href=\"{$url}\" target=\"{$target}\">{$name}</a>";
552 $name = "<a href=\"{$url}\">{$name}</a>";
560 * Create navigation for CiviCRM Admin Menu
562 * @param int $contactID contact id
564 * @return string $navigation returns navigation html
567 public static function createNavigation($contactID) {
568 $config = CRM_Core_Config
::singleton();
570 $navigation = self
::buildNavigation();
574 //add additional navigation items
575 $logoutURL = CRM_Utils_System
::url('civicrm/logout', 'reset=1');
577 // get home menu from db
578 $homeParams = array('name' => 'Home');
580 $homeIcon = '<img src="' . $config->userFrameworkResourceURL
. 'i/logo16px.png" style="vertical-align:middle;" />';
581 self
::retrieve($homeParams, $homeNav);
583 list($path, $q) = explode('?', $homeNav['url']);
584 $homeURL = CRM_Utils_System
::url($path, $q);
585 $homeLabel = $homeNav['label'];
586 // CRM-6804 (we need to special-case this as we don’t ts()-tag variables)
587 if ($homeLabel == 'Home') {
588 $homeLabel = ts('CiviCRM Home');
592 $homeURL = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
593 $homeLabel = ts('CiviCRM Home');
595 // Link to hide the menubar
597 ($config->userSystem
->is_drupal
) &&
598 ((module_exists('toolbar') && user_access('access toolbar')) ||
599 module_exists('admin_menu') && user_access('access administration menu')
602 $hideLabel = ts('Drupal Menu');
604 elseif ($config->userSystem
->is_wordpress
) {
605 $hideLabel = ts('WordPress Menu');
608 $hideLabel = ts('Hide Menu');
612 <li class='menumain crm-link-home'>$homeIcon
613 <ul id='civicrm-home'>
614 <li><a href='$homeURL'>$homeLabel</a></li>
615 <li><a href='#' class='crm-hidemenu'>$hideLabel</a></li>
616 <li><a href='$logoutURL' class='crm-logout-link'>". ts('Log out') ."</a></li>
618 // <li> tag doesn't need to be closed
620 return $prepandString . $navigation;
624 * Reset navigation for all contacts or a specified contact
626 * @param integer $contactID - reset only entries belonging to that contact ID
629 public static function resetNavigation($contactID = NULL) {
630 $newKey = CRM_Utils_String
::createRandom(self
::CACHE_KEY_STRLEN
, CRM_Utils_String
::ALPHANUMERIC
);
632 $query = "UPDATE civicrm_setting SET value = '$newKey' WHERE name='navigation' AND contact_id IS NOT NULL";
633 CRM_Core_DAO
::executeQuery($query);
634 CRM_Core_BAO_Cache
::deleteGroup('navigation');
637 // before inserting check if contact id exists in db
638 // this is to handle weird case when contact id is in session but not in db
639 $contact = new CRM_Contact_DAO_Contact();
640 $contact->id
= $contactID;
641 if ($contact->find(TRUE)) {
642 CRM_Core_BAO_Setting
::setItem(
644 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
652 // also reset the dashlet cache in case permissions have changed etc
653 // FIXME: decouple this
654 CRM_Core_BAO_Dashboard
::resetDashletCache($contactID);
662 * @param array $params associated array, $_GET
667 public static function processNavigation(&$params) {
668 $nodeID = (int)str_replace("node_", "", $params['id']);
669 $referenceID = (int)str_replace("node_", "", $params['ref_id']);
670 $position = $params['ps'];
671 $type = $params['type'];
672 $label = CRM_Utils_Array
::value('data', $params);
676 self
::processMove($nodeID, $referenceID, $position);
680 self
::processRename($nodeID, $label);
684 self
::processDelete($nodeID);
688 //reset navigation menus
689 self
::resetNavigation();
690 CRM_Utils_System
::civiExit();
694 * Process move action
696 * @param $nodeID node that is being moved
697 * @param $referenceID parent id where node is moved. 0 mean no parent
698 * @param $position new position of the nod, it starts with 0 - n
703 public static function processMove($nodeID, $referenceID, $position) {
704 // based on the new position we need to get the weight of the node after moved node
705 // 1. update the weight of $position + 1 nodes to weight + 1
706 // 2. weight of the ( $position -1 ) node - 1 is the new weight of the node being moved
708 // check if there is parent id, which means node is moved inside existing parent container, so use parent id
709 // to find the correct position else use NULL to get the weights of parent ( $position - 1 )
710 // accordingly set the new parent_id
712 $newParentID = $referenceID;
713 $parentClause = "parent_id = {$referenceID} ";
716 $newParentID = 'NULL';
717 $parentClause = 'parent_id IS NULL';
720 $incrementOtherNodes = true;
721 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
722 $params = array(1 => array( $position, 'Positive'));
723 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
725 // this means node is moved to last position, so you need to get the weight of last element + 1
727 $lastPosition = $position - 1;
728 $sql = "SELECT weight from civicrm_navigation WHERE {$parentClause} ORDER BY weight LIMIT %1, 1";
729 $params = array(1 => array($lastPosition, 'Positive'));
730 $newWeight = CRM_Core_DAO
::singleValueQuery($sql, $params);
732 // since last node increment + 1
733 $newWeight = $newWeight +
1;
735 // since this is a last node we don't need to increment other nodes
736 $incrementOtherNodes = false;
739 $transaction = new CRM_Core_Transaction();
741 // now update the existing nodes to weight + 1, if required.
742 if ( $incrementOtherNodes ) {
743 $query = "UPDATE civicrm_navigation SET weight = weight + 1
744 WHERE {$parentClause} AND weight >= {$newWeight}";
746 CRM_Core_DAO
::executeQuery($query);
749 // finally set the weight of current node
750 $query = "UPDATE civicrm_navigation SET weight = {$newWeight}, parent_id = {$newParentID} WHERE id = {$nodeID}";
751 CRM_Core_DAO
::executeQuery($query);
753 $transaction->commit();
757 * Function to process rename action for tree
762 public static function processRename($nodeID, $label) {
763 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_Navigation', $nodeID, 'label', $label);
767 * Process delete action for tree
771 public static function processDelete($nodeID) {
772 $query = "DELETE FROM civicrm_navigation WHERE id = {$nodeID}";
773 CRM_Core_DAO
::executeQuery($query);
777 * Get the info on navigation item
779 * @param int $navigationID navigation id
781 * @return array associated array
784 public static function getNavigationInfo($navigationID) {
785 $query = "SELECT parent_id, weight FROM civicrm_navigation WHERE id = %1";
786 $params = array($navigationID, 'Integer');
787 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => $params));
790 'parent_id' => $dao->parent_id
,
791 'weight' => $dao->weight
,
798 * @param array $params
799 * @param array $newParams new value of params
802 public static function processUpdate($params, $newParams) {
803 $dao = new CRM_Core_DAO_Navigation();
804 $dao->copyValues($params);
805 if ($dao->find(TRUE)) {
806 $dao->copyValues($newParams);
814 * @return object|string
816 public static function getCacheKey($cid) {
817 $key = CRM_Core_BAO_Setting
::getItem(
818 CRM_Core_BAO_Setting
::PERSONAL_PREFERENCES_NAME
,
824 if (strlen($key) !== self
::CACHE_KEY_STRLEN
) {
825 $key = self
::resetNavigation($cid);