Skip to content

Instantly share code, notes, and snippets.

@teknikqa
Created May 28, 2019 05:35
Show Gist options
  • Save teknikqa/068eb083e8cab4037a0fb5f5b71a177d to your computer and use it in GitHub Desktop.
Save teknikqa/068eb083e8cab4037a0fb5f5b71a177d to your computer and use it in GitHub Desktop.
Drupal code to restrict access to event nodes that are old and no longer valid.
<?php
/**
* @file
* Code for the Custom Events module.
*/
/**
* Implements hook_preprocess_node().
*
* Restrict access to events that more than a year old.
*/
function custom_events_preprocess_node(&$variables) {
if ($variables['type'] == 'event') {
$redirect = TRUE;
// Do not redirect for certain user roles.
if (!empty($variables['user'])) {
$user_roles = $variables['user']->roles;
if (in_array('Super admin', $user_roles) ||
in_array('Administrator', $user_roles) ||
in_array('Content admin', $user_roles) ||
in_array('Event manager', $user_roles)
) {
$redirect = FALSE;
}
}
// Get the end date to use for comparison.
$event_date = new DateTime($variables['field_event_date'][0]['value2']);
// Get the current date.
$date_to_check = new DateTime("now");
// Calculate one year back from current date.
$date_to_check->sub(new DateInterval('P1Y'));
// Redirect to the front page if the one year has passed since the event
// occured and if this is not a admin user viewing the event. This sets a
// 302 HTTP status response code in the HTTP header.
if ($event_date < $date_to_check && $redirect) {
drupal_goto('<front>');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment