18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

[ 227 ]<br />

Chapter 8<br />

Enabling permissions programmatically<br />

<strong>Drupal</strong> user roles and permissions are handled through configurations in the<br />

user interface. However, there may be use cases where your module needs to<br />

set or modify permissions. There is even a module called Secure Permissions<br />

(http://drupal.org/project/secure_permissions) which disables the UI for<br />

editing roles and permissions and forces all settings to be defined in code.<br />

If your module needs to define permissions in code, <strong>Drupal</strong> 7 provides some new<br />

hooks to make the task easier. Let's take a common example. Your module creates<br />

a page callback that should be visible by 'authenticated' but not 'anonymous' users.<br />

To activate this feature when the module is enabled, you can use hook_enable()<br />

as follows:<br />

function example_enable() {<br />

$permissions = array('view example page');<br />

user_role_change_permissions(DRUPAL_AUTHENTICATED_USER,<br />

$permissions);<br />

}<br />

This function goes into your module's .install file. When the module is enabled,<br />

<strong>Drupal</strong> will add the view example page permission to the authenticated user role.<br />

You can (and normally should) do the reverse when the module is disabled:<br />

function example_disable() {<br />

$permissions = array('view example page');<br />

$roles = user_roles();<br />

// Since permissions can be set per role, remove our permission from<br />

// each role.<br />

foreach ($roles as $rid => $name) {<br />

user_role_revoke_permissions($rid, $permissions);<br />

}<br />

}<br />

It is also possible to add/remove multiple permissions at the same time. To do<br />

so, we must build an array of permissions to be passed to user_role_change_<br />

permissions(). Suppose that our module wants to remove the default access<br />

content permission from the anonymous user role, while adding our new view<br />

example page permission. To do so, we build an array in the format 'permission<br />

name' => TRUE or FALSE, for each role.<br />

function example_enable() {<br />

$permissions = array(<br />

'access content' => FALSE,<br />

'view example page' => TRUE,<br />

);<br />

user_role_change_permissions(DRUPAL_ANONYMOUS_USER, $permissions);<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!