You are here

function protected_pages_file_download in Protected Pages 8

Implements hook_file_download().

File

./protected_pages.module, line 45
This module allows you to protect any page of the website by secure password.

Code

function protected_pages_file_download($uri) {
  $account = \Drupal::currentUser();
  if ($account
    ->hasPermission('bypass pages password protection')) {
    return;
  }
  $target = StreamWrapperManager::getTarget($uri);
  $file_path = '/system/files/' . $target;
  $fields = [
    'pid',
  ];
  $conditions = [];
  $conditions['general'][] = [
    'field' => 'path',
    'value' => $file_path,
    'operator' => '=',
  ];
  $protected_pages_storage = \Drupal::service('protected_pages.storage');
  $pid = $protected_pages_storage
    ->loadProtectedPage($fields, $conditions, TRUE);
  if (isset($_SESSION['_protected_page']['passwords'][$pid]['expire_time'])) {
    if (time() >= $_SESSION['_protected_page']['passwords'][$pid]['expire_time']) {
      unset($_SESSION['_protected_page']['passwords'][$pid]['request_time']);
      unset($_SESSION['_protected_page']['passwords'][$pid]['expire_time']);
    }
  }
  if (isset($_SESSION['_protected_page']['passwords'][$pid]['request_time'])) {
    return NULL;
  }
  if ($pid) {
    $destination_path_array = \Drupal::destination()
      ->getAsArray();
    $destination_path_array['destination'] = $destination_path_array['destination'] . '/' . $target;
    $destination_path_array['protected_page'] = $pid;
    $response = new RedirectResponse(Url::fromUri('internal:/protected-page', [
      'query' => $destination_path_array,
    ])
      ->toString());
    $response
      ->send();
    return;
  }
  else {
    return NULL;
  }
}