4.3. Defining Permissions: hook_perm

In Chapter 3 you learned about the permissions page and how an errant click on that page could allow a typical user to perform actions she shouldn't be allowed to do. Let's dig into how that page is constructed and how the permissions are checked.

The hook hook_perm() is a function that any module can implement to add more permissions to the list at Administer User Management Permissions. Here is an example usage of the function from the Drupal core blog module:

function blog_perm() {
  return array('create blog entries', 'delete own blog entries', 'delete
any blog entry', 'edit own blog entries', 'edit any blog entry');
}

That's it! Creating a new permission for your module is as simple as adding a new entry in the array that is returned.

Let's take a look at the implementation of this function in the Node module:

function node_perm() { $perms = array('administer content types', 'administer nodes', 'access content', 'view revisions', 'revert revisions', 'delete revisions'); foreach (node_get_types() as $type) { if ($type->module == 'node') { $name = check_plain($type->type); $perms[] = 'create '. $name .' content'; $perms[] = 'delete own '. $name .' content'; $perms[] = 'delete any '. $name .' content'; $perms[] = 'edit own '. $name .' content'; ...

Get Cracking Drupal®: A Drop in the Bucket now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.