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.

Node Access<br />

Using hook_node_access()<br />

<strong>Drupal</strong> 7 replaces the old hook_access() function with hook_node_access().<br />

This change was one of the many improvements to come from a work session<br />

at <strong>Drupal</strong>CON Szeged in 2008, and credit goes to Larry Garfield (Crell) for<br />

implementing these changes.<br />

hook_node_access() allows any module to have a say in how node access is<br />

handled. It does not require database storage, or the use of the rest of the Node<br />

Access API. Further, it may be applied to any of the four basic CRUD operations.<br />

The hook passes three parameters:<br />

• $node, the complete node object being acted upon, or a node type string in<br />

the case of the Create operation.<br />

• $op, the operation being performed.<br />

• $account, the user requesting access to the node for this action.<br />

All three of these parameters will always be populated, and your hook should<br />

respond according to the specific operation being performed. There are three<br />

possible return values for each request:<br />

• NODE_ACCESS_ALLOW<br />

Indicates that the operation should be permitted. This is an explicit allow,<br />

and at least one module must return this value for the operation to be<br />

validated by hook_node_access().<br />

• NODE_ACCESS_DENY<br />

Indicates that the operation should not be permitted. This is an explicit deny,<br />

and if issued, it will cancel any NODE_ACCESS_ALLOW directives issued by<br />

other modules.<br />

• NODE_ACCESS_IGNORE<br />

The default return statement. This value indicates that your module has no<br />

stake in whether to allow or deny the operation being requested.<br />

A sample access control module<br />

For example, suppose we have the following editorial rule on our site: Any<br />

authenticated user may post Articles provided he or she has been a member of the site for more<br />

than two days. (This rule prevents people from creating an account just to post spam<br />

the site; it also might afford a "cooling" off period before people reply to other posts.)<br />

[ 254 ]

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

Saved successfully!

Ooh no, something went wrong!