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

->limit(variable_get('default_nodes_main', 10))<br />

->addTag('node_access');<br />

$nids = $select->execute()->fetchCol();<br />

This select statement uses <strong>Drupal</strong> 7's query builder to fetch a list of published nodes<br />

which have been promoted to the front page, ordered by "stickiness" and age. Notice,<br />

however, the final element of the query: ->addTag('node_access').<br />

This directive invokes the node_query_node_access_alter() function which<br />

allows node access rules to be applied before the query is sent to the database.<br />

Failure to use the dynamic query builder and the node_access tag will mean that<br />

your select statement will bypass <strong>Drupal</strong>'s built-in security features. Doing so may<br />

grant unwanted access to view, edit, or delete content by ignoring the permissions<br />

defined for the site.<br />

We won't go into the inner workings of node_query_node_access_alter() yet.<br />

Simply put, it ensures that any query to the {node} table properly enforces the node<br />

access rules defined for the site.<br />

Because of how this enforcement is handled, however, module developers have a<br />

near-infinite capacity to modify how <strong>Drupal</strong> handles access to nodes. The purpose<br />

of the rest of this chapter is to explain how this system is designed and the best ways<br />

for you to leverage the Node Access API to meet your specific needs.<br />

The node_access() function<br />

node_access() is the primary access callback for node operations. It is defined in<br />

node_menu() as the access callback for any attempt to create, view, edit or delete<br />

a node. The function itself is one of the more complex in <strong>Drupal</strong> core by virtue of<br />

the eight separate return statements within the function. Understanding the logic<br />

behind these returns is the key to using Node Access correctly.<br />

To begin, let's examine the documentation and initial lines of the<br />

node_access() function:<br />

/**<br />

* Determine whether the current user may perform the given operation<br />

* on the specified node.<br />

*<br />

* @param $op<br />

* The operation to be performed on the node. Possible values are:<br />

* - "view"<br />

* - "update"<br />

[ 244 ]

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

Saved successfully!

Ooh no, something went wrong!