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 />

The access whitelist<br />

The first check that node_access() makes is to see if the callback was<br />

invoked correctly:<br />

if (!$node || !in_array($op, array('view', 'update', 'delete',<br />

'create'), TRUE)) {<br />

// If there was no node to check against, or the $op was not one<br />

// of the supported ones, we return access denied.<br />

return FALSE;<br />

}<br />

This code displays a bit of paranoia not found in most of the <strong>Drupal</strong> API. Checking<br />

the validity of the inbound parameters ensures that access is never granted by accident.<br />

When dealing with access control, defaulting to FALSE (meaning "deny access") is<br />

the proper behavior.<br />

Caching the result for performance<br />

The next section of code performs three simple sanity checks, plus an optimization<br />

for the static cache:<br />

// If no user object is supplied, the access check is for the<br />

// current user.<br />

if (empty($account)) {<br />

$account = $user;<br />

}<br />

// $node may be either an object or a node type. Since node types<br />

// cannot be an integer, use either nid or type as the static<br />

// cache id.<br />

$cid = is_object($node) ? $node->nid : $node;<br />

// If we've already checked access for this node, user and op,<br />

// return from cache.<br />

if (isset($rights[$account->uid][$cid][$op])) {<br />

return $rights[$account->uid][$cid][$op];<br />

}<br />

if (user_access('bypass node access', $account)) {<br />

$rights[$account->uid][$cid][$op] = TRUE;<br />

return TRUE;<br />

}<br />

[ 246 ]

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

Saved successfully!

Ooh no, something went wrong!