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.

Chapter 9<br />

We may alter any element of this array, adding or removing items that suit our<br />

business rules. Remember, however, that the resulting array will be used to write a<br />

JOIN query to the {node_access} table. It may help to read the above array in that<br />

context. A standard node query might run a simple SELECT:<br />

SELECT title, nid FROM node WHERE status > 0 ORDER BY sticky, created<br />

LIMIT 10;<br />

When the node access grants are applied, the query will be executed as:<br />

SELECT n.title, n.nid FROM node n INNER JOIN node_access na ON n.nid =<br />

na.nid WHERE (na.realm = 'role_access' AND na.gid = 2) AND n.status ><br />

0 ORDER BY sticky, created LIMIT 10;<br />

As a module author, it is your responsibility to understand how these queries will be<br />

rewritten so that your code can produce the desired results.<br />

Remember that the grant ids are the array values, not the array<br />

keys for your node access realm!<br />

Now that we know how the query will be affected, we can write the code to add the<br />

grant necessary to make anonymous users act like authenticated users.<br />

/**<br />

* Implement hook_node_grants_alter().<br />

*/<br />

function role_access_extend_node_grants_alter(&$grants, $account, $op)<br />

{<br />

// We only act on the 'view' operation.<br />

// If our grant is not present, do nothing.<br />

if ($op != 'view' || !isset($grants['role_access'])) {<br />

return;<br />

}<br />

}<br />

// Get the defined role id for 'authenticated user'.<br />

$rid = DRUPAL_AUTHENTICATED_RID;<br />

// Check the permission and set the grant.<br />

if (user_access('view role access as authenticated user')) {<br />

$grants['role_access'][] = $rid;<br />

}<br />

[ 277 ]

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

Saved successfully!

Ooh no, something went wrong!