You are here

function stage_file_proxy_fetch_file in Stage File Proxy 7

Downloads a public file from the origin site.

Parameters

string $relative_path: The path to the requested resource relative to the files directory.

array $options: Additional options to pass through to url().

Return value

string|bool Returns the local path if the remote file was downloaded successfully, or FALSE otherwise.

2 calls to stage_file_proxy_fetch_file()
stage_file_proxy_process_file_uri in ./stage_file_proxy.module
Checks to see if a file should be downloaded from the origin site.
_stage_file_proxy_fetch in ./stage_file_proxy.module
Downloads a remote file and saves it to the local files directory.

File

./stage_file_proxy.module, line 319
Stage File Proxy Module.

Code

function stage_file_proxy_fetch_file($relative_path, array $options = array()) {
  $failures =& drupal_static(__FUNCTION__);
  if (!isset($failures)) {
    $failures = array();
    if ($cache = cache_get('stage_file_proxy_fetch_url_failures')) {
      $failures = $cache->data;
    }
  }
  $excluded_extensions = array_map('trim', explode(',', variable_get('stage_file_proxy_excluded_extensions', '')));
  $path_info = pathinfo($relative_path);
  $ext = $path_info['extension'];
  if (in_array($ext, $excluded_extensions)) {
    return FALSE;
  }
  $url = stage_file_proxy_get_file_remote_url($relative_path, $options);
  if (!empty($failures[$url])) {
    return FALSE;
  }
  $headers = _stage_file_proxy_create_headers_array(variable_get('stage_file_proxy_headers', ''));
  $result = drupal_http_request($url, array(
    'headers' => $headers,
  ));
  if ($result->code != 200) {
    watchdog('stage_file_proxy', 'HTTP error @errorcode occurred when trying to fetch @remote.', array(
      '@errorcode' => $result->code,
      '@remote' => $url,
    ), WATCHDOG_ERROR);
    $failures[$url] = TRUE;
    cache_set('stage_file_proxy_fetch_url_failures', $failures, 'cache', CACHE_TEMPORARY);
    return FALSE;
  }
  $destination = _stage_file_proxy_file_dir();
  if (($dirname = dirname($relative_path)) !== '.') {
    $destination = $destination . '/' . $dirname;
  }
  if (!file_prepare_directory($destination, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
    watchdog('stage_file_proxy', 'Unable to prepare local directory @path.', array(
      '@path' => $destination,
    ), WATCHDOG_ERROR);
    return FALSE;
  }
  $destination = str_replace('///', '//', "{$destination}/") . drupal_basename($relative_path);
  $local = file_unmanaged_save_data($result->data, $destination, FILE_EXISTS_REPLACE);
  if (!$local) {
    watchdog('stage_file_proxy', '@remote could not be saved to @path.', array(
      '@remote' => $url,
      '@path' => $destination,
    ), WATCHDOG_ERROR);
    return FALSE;
  }
  return $local;
}