filefield_sources_jsonapi-8.x-1.0-beta9/src/RemoteFileController.php
src/RemoteFileController.php
<?php
namespace Drupal\filefield_sources_jsonapi;
use Drupal\Core\Controller\ControllerBase;
use GuzzleHttp\Exception\RequestException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
/**
* Retrieve file via curl call for filefield source JSON API.
*/
class RemoteFileController extends ControllerBase {
/**
* Get file via curl and return it.
*/
public static function getRemoteFile() {
$myConfig = \Drupal::config('filefield_sources_jsonapi');
$username = $myConfig->get('username');
$password = $myConfig->get('password');
$url = \Drupal::request()->query->get('url');
$temporary_directory = 'temporary://';
$url_info = parse_url($url);
$filename = rawurldecode(basename($url_info['path']));
$filepath = \Drupal::service('file_system')->createFilename($filename, $temporary_directory);
$client = \Drupal::httpClient();
try {
$fp = @fopen($filepath, 'w');
$authorization_options = [
'auth' => [
$username,
$password,
],
];
$request = $client->get($url, $authorization_options);
$file_contents = $request->getBody()->getContents();
fwrite($fp, $file_contents);
fclose($fp);
}
catch (RequestException $e) {
// An error happened.
\Drupal::logger('filefield_sources_jsonapi')
->log(E_ERROR, 'url %url could not be fetched', ['%url' => $url]);
switch ($e->getCode()) {
case 403:
\Drupal::logger('filefield_sources_jsonapi')->notice(t('The remote file could not be transferred because access to the file was denied.'));
break;
case 404:
\Drupal::logger('filefield_sources_jsonapi')->notice(t('The remote file could not be transferred because it was not found.'));
break;
default:
\Drupal::logger('filefield_sources_jsonapi')->notice(t('The remote file could not be transferred due to an HTTP error (@code).', ['@code' => $e->getCode()]));
}
return;
}
if ($file_contents !== NULL) {
$mime = \Drupal::service('file.mime_type.guesser')->guessMimeType($filepath);
$headers = [
'Content-Type' => $mime,
'Content-Length' => filesize($filepath),
'Cache-Control' => 'private',
];
return new BinaryFileResponse($filepath, 200, $headers, FALSE);
}
throw new NotFoundHttpException();
}
}
