You are here

function filehash_validate_dedupe in File Hash 8

Checks that file is not a duplicate.

1 call to filehash_validate_dedupe()
filehash_file_validate in ./filehash.module
Implements hook_file_validate().

File

./filehash.module, line 114
Generate hashes for each uploaded file.

Code

function filehash_validate_dedupe(FileInterface $file) {
  $errors = [];

  // We only run the dedupe check on initial file creation.
  if (!$file
    ->id()) {
    foreach (filehash_algos() as $algo) {
      $query = \Drupal::database()
        ->select('filehash');
      $query
        ->addField('filehash', 'fid');
      $query
        ->condition($algo, $file->filehash[$algo]);
      $query
        ->range(0, 1);
      if ($fid = $query
        ->execute()
        ->fetchField()) {
        $error = t('Sorry, duplicate files are not permitted.');
        if (\Drupal::currentUser()
          ->hasPermission('access files overview')) {
          try {
            $url = Url::fromRoute('view.files.page_2', [
              'arg_0' => $fid,
            ], [
              'attributes' => [
                'target' => '_blank',
              ],
            ]);
            $error = t('This file has already been uploaded as %filename.', [
              '%filename' => Link::fromTextAndUrl(File::load($fid)
                ->label(), $url)
                ->toString(),
            ]);
          } catch (Exception $e) {

            // Maybe the view was disabled?
          }
        }
        $errors[] = $error;
        break;
      }
    }
  }
  return $errors;
}