You are here

function panopoly_media_duplicate_files in Panopoly 8.2

Determines if a file is or if set of files has a duplicate.

Parameters

\Drupal\file\FileInterface|\Drupal\file\FileInterface[] $files: The file or files.

bool $new_only: Optional. Indicates if only new files should be checked for duplicity.

Return value

bool Indicates if there is a duplicate.

1 call to panopoly_media_duplicate_files()
panopoly_media_field_widget_process in modules/panopoly/panopoly_media/panopoly_media.module
Process callback for file and image widgets to add duplicate acknowledgement.

File

modules/panopoly/panopoly_media/panopoly_media.module, line 172
Hook implementations for Panopoly Media.

Code

function panopoly_media_duplicate_files($files, $new_only = FALSE) {

  // Soft dependency on filehash.
  if (!\Drupal::moduleHandler()
    ->moduleExists('filehash')) {
    return FALSE;
  }

  // Normalize into an array.
  if (!is_array($files)) {
    $files = [
      $files,
    ];
  }

  // Check only newly-created files.
  if ($new_only) {
    $files = array_filter($files, function ($file) {

      /** @var \Drupal\file\FileInterface $file */
      return $file
        ->isTemporary();
    });
  }

  // If no files, we've got nothing to do.
  if (empty($files)) {
    return FALSE;
  }

  // Gather file IDs.
  $fids = array_map(function ($file) {

    /** @var \Drupal\file\FileInterface $file */
    return $file
      ->id();
  }, $files);

  // Check each used algorithm for duplicate.
  foreach (filehash_algos() as $algo) {
    $hashes = array_map(function ($file) use ($algo) {
      return $file->filehash[$algo];
    }, $files);
    if (!$hashes) {
      break;
    }

    // Query for duplicates.
    $query = \Drupal::database()
      ->select('filehash');
    $query
      ->addField('filehash', 'fid');
    $query
      ->condition('fid', $fids, 'NOT IN');
    $query
      ->condition($algo, $hashes, 'IN');
    $query
      ->range(0, 1);
    if ($fid = $query
      ->execute()
      ->fetchField()) {
      return TRUE;
    }
  }
  return FALSE;
}