1

I'm building a page with different download buttons linked to private zip files. Users have to log in to download. I am using module Permissions by Term to manage who can see which button.
I added a field to user entity to log each download. In hook_file_download() I check, if and how often this file is already downloaded by this user. Up to here everything works fine.
I want to stop or block the download and show a message to the user, if download counter reaches 5 or 10. Is hook_file_download the right hook to achieve this?

  • 2
    Check the hook documentation. If you return -1, it won’t serve the file. – Kevin Oct 31 '19 at 1:49
  • Thanks, but @STF solution is cleaner for me. Actually I can omit the message and redirect the user to a page with some explanation. – krabbe Oct 31 '19 at 16:42
1

I have this to check that the users has remaining downloads or redirect them to an upgrade page.

/**
 * Implements hook_file_download().
 */
function mymodule_file_download($uri) {
  // Check if user is logged in
  if (\Drupal::currentUser()->isAuthenticated()) {
    // Load entity of current user
    $current_user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

    // Check if current user is: access || student || (professional && trial_actived)
    $download_control = $current_user->hasRole('professional') && $current_user->field_user_free_trial->value == 'trial_actived' ? TRUE : FALSE;
    $download_control = $download_control || $current_user->hasRole('access') || $current_user->hasRole('student') ? TRUE : FALSE;

if ($download_control) {

  // Declare files that decrease the counter
  $controlled_uris = [
    'private://mechanisms/files',
  ];

  // Check if requested uri matches with controlled uris
  foreach ($controlled_uris as $c_uri) {
    if (strpos($uri, $c_uri) !== FALSE) {

      // Check if user still has remaining downloads
      if ($current_user->field_user_download_counter->value > 0) {

        // Decrease user downloads counter
        $current_user->field_user_download_counter->value--;
        $current_user->save();
      }
      else {
        // Prepare redirect url to the prices page
        $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => 39])->toString();

        // Set message
        $message = t('Your account has reached the maximum limit of downloads.');
        \Drupal::messenger()->addWarning($message);

        // Send response to url
        $response = new \Symfony\Component\HttpFoundation\RedirectResponse($url);
        $response->send();
      }
    }
  }
}
  }
}
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.