node_access_example_nodeapi

Versions
4.6 – 6
node_access_example_nodeapi(&$node, $op, $arg = 0)

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:

  • "form admin", "form pre", and/or "form post": The module will need to provide some mechanism for the access rights of a node to be managed. Some sort of form element on the node editing form is a typical means to accomplish this.
  • "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.
  • "settings": Modules may wish to provide default grants per node type using this hook.

Code

developer/examples/node_access_example.module, line 85

<?php
function node_access_example_nodeapi(&$node, $op, $arg = 0) {
  switch ($op) {
    case 'form admin':
      // We present the selection for who can view the node in the administrative
      // block, so users with the "administer nodes" permission can view and edit
      // the settings.
      if (!isset($node->access_example)) {
        // Load the grants from the database.
        $result = db_query('SELECT na.gid FROM {node_access} na WHERE na.nid = %d AND na.realm = \'example\' AND na.grant_view = 1', $node->nid);
        $grant = db_fetch_object($result);
        if ($grant && $grant->gid == 0) {
          // The "public" grant was set.
          $node->access_example = 0;
        }
        else {
          $node->access_example = 1;
        }
      }
      $output = form_checkbox(t('private'), 'access_example', 1, $node->access_example);
      return $output;
    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;
  }
}
?>
Login or register to post comments
 
 

All source code and documentation on this site is released under the terms of the GNU General Public License, version 2 and later. Drupal is a registered trademark of Dries Buytaert.