menu_per_role.module in Menu Per Role 5
Same filename and directory in other branches
Allows restricting access to menu items per role
File
menu_per_role.moduleView source
<?php
/**
* @file
* Allows restricting access to menu items per role
*/
/*
* Determines access for a give menu item id
*/
function menu_per_role_access($mid) {
global $user;
$rids = menu_per_role_get_roles($mid);
if (user_access('administer')) {
// Super admin can always access
return 1;
}
//NULL means inherit access from parent item
return count($rids) ? count(array_intersect($rids, array_keys($user->roles))) : NULL;
}
/*
* Gets all roles with access to the menu item
* No roles mean that access should be inherited from the parent menu item
*/
function menu_per_role_get_roles($mid) {
$result = db_query("SELECT rid FROM {menu_per_role} WHERE mid = %d", $mid);
$rids = array();
while ($row = db_fetch_object($result)) {
$rids[] = $row->rid;
}
return $rids;
}
/*
* Implementation of hook_form_alter().
*/
function menu_per_role_form_alter($form_id, &$form) {
if ($form_id == 'menu_edit_item_form') {
$form['menu_per_role'] = array(
'#type' => 'fieldset',
'#title' => t('Restrict access permission'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#weight' => 5,
);
$form['menu_per_role']['roles'] = array(
'#type' => 'checkboxes',
'#title' => t('Restrict access to only these roles'),
'#options' => user_roles(),
'#default_value' => $form['mid']['#value'] ? menu_per_role_get_roles($form['mid']['#value']) : array(),
'#description' => t('Check no role to leave the access permission to the default.'),
);
$form['submit']['#weight'] = 10;
$form['#submit']['menu_per_role_form_submit'] = array();
}
}
function menu_per_role_form_submit($form_id, $form_values) {
if ($form_values['mid']) {
db_query("DELETE FROM {menu_per_role} WHERE mid = %d", $form_values['mid']);
}
else {
//a new item has been added, try to determine the mid
$form_values['mid'] = db_result(db_query("SELECT id FROM {sequences} WHERE name = '{menu}_mid'"));
}
foreach ($form_values['roles'] as $rid => $checked) {
if ($checked) {
db_query("INSERT INTO {menu_per_role} (mid, rid) VALUES(%d, %d)", $form_values['mid'], $rid);
}
}
}