Same name and namespace in other branches
  1. 4.6.x developer/examples/node_access_example.module \node_access_example_nodeapi()
  2. 5.x developer/examples/node_access_example.module \node_access_example_nodeapi()

Implementation of hook_nodeapi().

Most of a node access module's work will be done via this hook. Several values of $op will require responses:

  • "delete", "insert", and "update": The module must take care of updating the node_access table appropriately when nodes are modified, probably using the form element mentioned above. Only the realm(s) handled by the module should be affected, so that multiple node access modules can peacefully coexist.
  • "validate": Depending on the user interface provided in the node form, the selection may need to be verified and validated here.

File

developer/examples/node_access_example.module, line 123
This is an example illustrating how to restrict access to nodes based on some criterion associated with the user.

Code

function node_access_example_nodeapi(&$node, $op, $arg = 0) {
  switch ($op) {
    case 'delete':

      // When a node is deleted, delete any relevant grants.
      db_query('DELETE FROM {node_access} WHERE nid = %d AND realm = \'example\'', $node->nid);
      break;
    case 'insert':
    case 'update':

      // Clear out any existing grants for the node, and set new ones.
      db_query('DELETE FROM {node_access} WHERE nid = %d AND realm = \'example\'', $node->nid);
      $node->access_example = isset($node->access_example) ? $node->access_example : 0;
      if ($node->access_example == 0) {

        // If the node is public, we need to grant access to everyone.
        db_query('INSERT INTO {node_access} (nid, gid, realm, grant_view, grant_update, grant_delete) VALUES (%d, %d, \'example\', %d, %d, %d)', $node->nid, 0, 1, 0, 0);
      }
      break;
  }
}