Skip to content

Instantly share code, notes, and snippets.

@jorislucius
Last active January 15, 2018 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorislucius/5a4c5518337c84e84ee137a1fc7ad75d to your computer and use it in GitHub Desktop.
Save jorislucius/5a4c5518337c84e84ee137a1fc7ad75d to your computer and use it in GitHub Desktop.
Snippet from Drupal Lus distribution, to handle private files in channels
<?php
/**
* Implements hook_file_download().
*
* @param $uri
*
* @return array
*/
function lus_file_download($uri) {
$user = Drupal::currentUser();
// Get the cid.
$query = \Drupal::database()->select('file_managed', 'file');
$query->fields('cf', ['cid']);
$query->join('ol_channel_files', 'cf', 'cf.fid = file.fid');
$query->condition('file.uri', $uri);
$cid = $query->execute()->fetchField();
// Check if file is not a profile picture.
if ($cid) {
// Check if user has access to the channel.
$query = \Drupal::database()->select('ol_user_channel', 'ouc');
$query->fields('ouc', ['cid', 'uid']);
$query->condition('cid', $cid);
$query->condition('uid', $user->id());
$query->range(0, 1);
$access = $query->execute()->fetchAssoc();
}
else {
$query = \Drupal::database()->select('file_managed', 'file');
$query->fields('fu', ['type']);
$query->join('file_usage', 'fu', 'fu.fid = file.fid');
$query->condition('file.uri', $uri);
$access = $query->execute()->fetchField();
}
if(!$access){
$query = \Drupal::database()->select('file_managed', 'file');
$query->fields('file', ['status']);
$query->condition('file.uri', $uri);
$status = $query->execute()->fetchField();
if ($status == 0) {
$access = TRUE;
}
}
if ($access) {
$files = \Drupal::entityTypeManager()
->getStorage('file')
->loadByProperties(array('uri' => $uri));
$file = reset($files);
return file_get_content_headers($file);
}
else {
throw new NotFoundHttpException();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment