Restricting Time-sensistive Access Using hook_node_access() and MYSQL Date and Time Functions

In this scenario I needed to prevent a user from creating more than one report per month. This was accomplished by creating a module and using hook_node_access along with MYSQL Date and Time functions.

Example


/**
* Implements hook_node_access()
**/
function sqc_permissions_node_access($node, $op, $account) {

switch ($op) {
case 'create':
// Allow creation of an SQC report only if no report already exists for this month already.
if ($node != 'monthly_user_report') return NODE_ACCESS_IGNORE;
global $user;
// Count how many SQC reports have already been created this month for the current user.
$num_rows = db_query('SELECT COUNT(nid) FROM {node} WHERE uid = :uid AND type = :type AND YEAR(FROM_UNIXTIME(created)) = YEAR(CURDATE()) AND MONTH(FROM_UNIXTIME(created)) = MONTH(CURDATE())', array(':uid'=> $user->uid, ':type' => 'monthly_user_report'))->fetchField();
if ($num_rows > 0) {
drupal_set_message(t('An SQC Report already exists for this month. Please edit that one rather than create a new one.'), 'error');
drupal_goto('/sqc_report'); // Send the user back to SQC report list.
return NODE_ACCESS_DENY;
}
return NODE_ACCESS_IGNORE;
case 'update':
$is_author = $account->uid == $node->uid;
// Allow updating only in the same month it was created in.
if (date("M") != date("M", $node->created) || date("Y") != date("Y", $node->created) || !$is_author)
if ($node->type == 'monthly_user_report')
return NODE_ACCESS_DENY;
case 'delete':
// Do not allow deleting.
return NODE_ACCESS_IGNORE;
case 'view':
// Do not allow viewing
return NODE_ACCESS_IGNORE;
} // End of switch
}

For more information, see Chapter 5 on Working with Databases in Pro Drupal 7 Development.