You are here

public function TFTController::downloadFile in Taxonomy File Tree 8

Same name and namespace in other branches
  1. 3.x src/Controller/TFTController.php \Drupal\tft\Controller\TFTController::downloadFile()

Downloads file.

Parameters

\Drupal\media\MediaInterface $media: Media entity.

Return value

\Drupal\Core\Routing\TrustedRedirectResponse|\Symfony\Component\HttpFoundation\BinaryFileResponse Response.

1 string reference to 'TFTController::downloadFile'
tft.routing.yml in ./tft.routing.yml
tft.routing.yml

File

src/Controller/TFTController.php, line 506

Class

TFTController
Class TFTController.

Namespace

Drupal\tft\Controller

Code

public function downloadFile(MediaInterface $media) {

  // Check if the user has access to group entity.
  if (!empty($media->tft_folder)) {
    $tid = $media
      ->get('tft_folder')
      ->getString();
    if (!empty($tid) && !_tft_term_access($tid)) {
      throw new AccessDeniedHttpException();
    }
  }
  $fids = $media
    ->get('tft_file')
    ->getValue();
  if (!empty($fids)) {
    $fid = reset($fids)['target_id'];
    $file = File::load($fid);
    if (!$file) {
      throw new NotFoundHttpException();
    }
    if (!($file
      ->access('view') && $file
      ->access('download'))) {
      throw new AccessDeniedHttpException();
    }

    // Let other modules provide headers and control access to the file.
    $headers = $this
      ->moduleHandler()
      ->invokeAll('file_download', [
      $file
        ->getFileUri(),
    ]);
    if (in_array(-1, $headers) || empty($headers)) {
      throw new AccessDeniedHttpException();
    }
    $file_name = $file
      ->getFilename();
    $headers = [
      'Content-Type' => $file
        ->getMimeType(),
      'Content-Disposition' => 'attachment; filename="' . $file_name . '"',
    ];
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
      $headers['Cache-Control'] = 'must-revalidate, post-check=0, pre-check=0';
      $headers['Pragma'] = 'public';
    }
    else {
      $headers['Pragma'] = 'no-cache';
    }
    return new BinaryFileResponse($file
      ->getFileUri(), 200, $headers);
  }
  elseif (!empty($link = $media
    ->get('opigno_moxtra_recording_link')
    ->getValue())) {
    if (\Drupal::hasService('opigno_moxtra.connector')) {

      /** @var \Drupal\opigno_moxtra\MoxtraConnector $opigno_api */
      $opigno_api = \Drupal::service('opigno_moxtra.connector');
      $token = $opigno_api
        ->getToken($media
        ->getOwnerId());
      $url = $link[0]['uri'] . "&access_token={$token}";
      return new TrustedRedirectResponse($url);
    }
  }
  throw new NotFoundHttpException();
}