You are here

function nodeaccess_nodeapi in Nodeaccess 6

Same name and namespace in other branches
  1. 5 nodeaccess.module \nodeaccess_nodeapi()
  2. 6.2 nodeaccess.module \nodeaccess_nodeapi()

Implementation of hook_nodeapi().

File

./nodeaccess.module, line 652

Code

function nodeaccess_nodeapi(&$node, $op) {
  switch ($op) {
    case 'insert':

      // New node, write default permissions.
      $grants = nodeaccess_node_access_records($node);
      foreach (array(
        'uid',
        'rid',
        'author',
      ) as $type) {
        $realm = 'nodeaccess_' . $type;
        node_access_write_grants($node, $grants, $realm);
      }
      if (module_exists('userreference')) {
        $fields = variable_get('nodeaccess_' . $node->type . '_userreference', array());
        foreach (array_keys($fields) as $field_name) {
          if (isset($node->{$field_name})) {
            nodeaccess_insert_userreference($node);
            break;
          }
        }
      }

      // Done, default permissions are not written into nodeaccess.
      break;
    case 'update':

      // Node author may have changed, overwrite old record.
      $author_prefs = variable_get('nodeaccess_authors', array());

      // Array is prepopulated with grant values.
      $grant = $author_prefs[$node->type];
      $grant['gid'] = $node->uid;
      $grant['realm'] = 'nodeaccess_author';
      $grants = array();
      $grants[] = $grant;
      node_access_write_grants($node, $grants, 'nodeaccess_author');
      if (module_exists('userreference')) {
        $fields = variable_get('nodeaccess_' . $node->type . '_userreference', array());
        foreach (array_keys($fields) as $field_name) {
          if (isset($node->{$field_name})) {
            $old_node = node_load($node->nid);

            // Delete the old user as it's changed.
            if ($node->{$field_name} != $old_node->{$field_name}) {
              nodeaccess_delete_userreference($old_node);
              nodeaccess_insert_userreference($node);
            }
            break;
          }
        }
      }

      // Done, author permissions are not written into nodeaccess.
      break;
    case 'delete':

      // Deleting node, delete related permissions.
      db_query('DELETE FROM {nodeaccess} WHERE nid = %d', $node->nid);
      foreach (array(
        'uid',
        'rid',
        'author',
      ) as $type) {
        $realm = 'nodeaccess_' . $type;
        node_access_write_grants($node, array(), $realm);
      }
      break;
  }
}