Attempts to get a file using Guzzle HTTP client and to store it locally.
$url: The URL of the file to grab.
$destination: Stream wrapper URI specifying where the file should be placed. If a directory path is provided, the file is saved into that directory under its original name. If the path contains a filename as well, that one will be used instead. If this value is omitted, the site's default files scheme will be used, usually "public://".
$managed boolean: If this is set to TRUE, the file API hooks will be invoked and the file is registered in the database.
$replace boolean: Replace behavior when the destination file already exists:
On success the location the file was saved to, FALSE on failure.
function system_retrieve_file($url, $destination = NULL, $managed = FALSE, $replace = FILE_EXISTS_RENAME) {
$parsed_url = parse_url($url);
if (!isset($destination)) {
$path = file_build_uri(drupal_basename($parsed_url['path']));
}
else {
if (is_dir(drupal_realpath($destination))) {
// Prevent URIs with triple slashes when glueing parts together.
$path = str_replace('///', '//', "{$destination}/") . drupal_basename($parsed_url['path']);
}
else {
$path = $destination;
}
}
try {
$data = Drupal::httpClient()
->get($url)
->send()
->getBody(TRUE);
$local = $managed ? file_save_data($data, $path, $replace) : file_unmanaged_save_data($data, $path, $replace);
} catch (BadResponseException $exception) {
$response = $exception
->getResponse();
drupal_set_message(t('Failed to fetch file due to HTTP error "%error"', array(
'%error' => $response
->getStatusCode() . ' ' . $response
->getReasonPhrase(),
)), 'error');
return FALSE;
} catch (RequestException $exception) {
drupal_set_message(t('Failed to fetch file due to error "%error"', array(
'%error' => $exception
->getMessage(),
)), 'error');
return FALSE;
}
if (!$local) {
drupal_set_message(t('@remote could not be saved to @path.', array(
'@remote' => $url,
'@path' => $path,
)), 'error');
}
return $local;
}