Last active
January 15, 2018 13:02
-
-
Save jorislucius/5a4c5518337c84e84ee137a1fc7ad75d to your computer and use it in GitHub Desktop.
Snippet from Drupal Lus distribution, to handle private files in channels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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