function commerce_file_file_download in Commerce File 8.2
Same name and namespace in other branches
- 7.2 commerce_file.module \commerce_file_file_download()
- 7 commerce_file.module \commerce_file_file_download()
Implements hook_file_download().
File
- ./
commerce_file.module, line 91 - Extends Commerce License with the ability to sell access to files.
Code
function commerce_file_file_download($uri) {
$files = \Drupal::entityTypeManager()
->getStorage('file')
->loadByProperties([
'uri' => $uri,
]);
// No files matching the uri, nothing more we can do.
if (!$files) {
return;
}
/** @var \Drupal\file\FileInterface[] $files */
foreach ($files as $item) {
// Since some database servers sometimes use a case-insensitive comparison
// by default, double check that the filename is an exact match.
if ($item
->getFileUri() === $uri) {
$file = $item;
break;
}
}
// No file found, or a temporary file found, do nothing.
if (!isset($file) || !$file
->isPermanent()) {
return;
}
// Note that the file access is already checked by file_file_download(), so
// we don't have to worry about that here.
/** @var \Drupal\commerce_file\LicenseFileManagerInterface $license_file_manager */
$license_file_manager = \Drupal::service('commerce_file.license_file_manager');
// If the file is not licensable, no need to do anything.
if (!$license_file_manager
->isLicensable($file)) {
return;
}
$licenses = $license_file_manager
->getActiveLicenses($file);
// We don't need to return '-1' once again here, since file_file_download()
// will take care of that on our behalf after invoking our file access logic.
if (!$licenses) {
return;
}
// Use the first active license returned when recording file downloads, since
// we have no reliable way of knowing which license to use when logging
// file downloads.
$license = reset($licenses);
// Add custom headers that will be used by our file response subscriber
// to record file downloads on Kernel terminate.
// Unfortunately, the core File module doesn't dispatch an event right before
// a file is downloaded forcing us to go with that approach.
return [
'X-Commerce-File-ID' => $file
->id(),
'X-Commerce-License-ID' => $license
->id(),
];
}