18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Node Access<br />

When executed, the following query is passed to the database:<br />

SELECT n.nid FROM node n WHERE n.promote = 1 AND n.status = 1 ORDER BY<br />

n.sticky DESC, n.created DESC LIMIT 0, 10;<br />

The above query means:<br />

Select the first ten distinct node ids for published and promoted nodes, ordered by<br />

"stickiness" and age.<br />

If we have a node access module enabled, however, hook_query_alter() will fire<br />

the node_query_node_access_alter() function, which will rewrite the query by<br />

adding a conditional JOIN to the node access table.<br />

<strong>Drupal</strong> 7's database API uses the add_tag() method to register<br />

hook functions. The value passed to the method – here node_access<br />

– informs the name of the alter hook. Query alters take the format<br />

hook_query_TAG_NAME_alter().<br />

Our sample node access query looks like so after it has been processed by<br />

node_query_node_access _alter():<br />

SELECT DISTINCT(n.nid) FROM node n INNER JOIN node_access na ON n.nid<br />

= na.nid WHERE (n.promote = 1) AND (n.status = 1) AND (((na.gid =<br />

0) AND (na.realm = 'all')) OR (((na.gid = 2) AND (na.realm = 'role_<br />

access'))) AND na.grant_view >= 1) ORDER BY n.sticky DESC, n.created<br />

DESC LIMIT 0, 10;<br />

In plain English, here's what it means:<br />

Select the first ten distinct node ids for published and promoted nodes, ordered by<br />

"stickiness" and age, provided that one of the following conditions is true: 1) The<br />

default 'all users may view all nodes' rule is still in effect; or, 2) At least one of the<br />

current user's access grants allows access to view the node.<br />

That's a whole lot to take in, so we'll unpack it some more.<br />

When node_query_node_access_alter() runs, it asks a few basic questions before<br />

altering the query. These are:<br />

• Can this user access all content?<br />

This request is carried out by the node_access_view_all_nodes() function,<br />

which checks to see if any node access modules are enabled, what the user's<br />

permissions are, and if access is granted by the default 'view all content'<br />

record. If TRUE, then the alter query exits without changing the query.<br />

[ 262 ]

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

Saved successfully!

Ooh no, something went wrong!