<?php
// $Id: view_unpublished.module,v 1.2.4.1 2009/08/30 19:48:24 dsantangelo Exp $

/**
 * @file
 * Allow users to view all unpublished nodes, or unpublished nodes
 * of a specific type.
 */
 
/**
 * Implementation of hook_perm().
 *
 * Adds a global 'view all unpublished content' permission and also
 * a new permission for each content type.
 */
function view_unpublished_perm() {
  $perms = array('view all unpublished content');

  foreach (node_get_types() as $type => $name) {
    $perms[] = 'view unpublished ' . $type . ' content';
  }
 
  return $perms;
}

/**
 * Implementation of hook_menu_alter().
 *
 * Modifies the path node/nid to use our access callback.
 */
function view_unpublished_menu_alter(&$items) { 
  $items['node/%node']['access callback'] = '_view_unpublished_node_access';
  $items['node/%node']['access arguments'] = array(1);
}

/**
 * Returns true if the user has 'view all unpublished content' or if
 * they have the permission corresponding to the node's content type.
 */
function _view_unpublished_node_access($node) {
  // Only check permissions on nodes that are unpublished.
  if ($node->status == 0) {
    if (user_access('view all unpublished content')) {
      return TRUE;
    }

    if (user_access('view unpublished ' . $node->type . ' content')) {
      return TRUE;
    }
  }
  
  // If none of the above conditions were satisfied, then use node_access like normal.
  return node_access('view', $node);
}
