You are here

public function views_xml_backend_plugin_query_xml::fetch_file in Views XML Backend 7

Same name and namespace in other branches
  1. 6 views_xml_backend_plugin_query_xml.inc \views_xml_backend_plugin_query_xml::fetch_file()
1 call to views_xml_backend_plugin_query_xml::fetch_file()
views_xml_backend_plugin_query_xml::execute in ./views_xml_backend_plugin_query_xml.inc
Executes the query and fills the associated view object with according values.

File

./views_xml_backend_plugin_query_xml.inc, line 77
Contains views_xml_backend_plugin_query_xml.

Class

views_xml_backend_plugin_query_xml
@file Contains views_xml_backend_plugin_query_xml.

Code

public function fetch_file($uri) {
  $parsed = parse_url($uri);

  // Check for local file.
  if (empty($parsed['host'])) {
    if (!file_exists($uri)) {
      throw new Exception(t('Local file not found.'));
    }
    return file_get_contents($uri);
  }
  $destination = 'public://views_xml_backend';
  if (!file_prepare_directory($destination, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
    throw new Exception(t('Files directory either cannot be created or is not writable.'));
  }
  $headers = array();
  $cache_file = 'views_xml_backend_' . md5($uri);
  if ($cache = cache_get($cache_file)) {
    $last_headers = $cache->data;
    if (!empty($last_headers['etag'])) {
      $headers['If-None-Match'] = $last_headers['etag'];
    }
    if (!empty($last_headers['last-modified'])) {
      $headers['If-Modified-Since'] = $last_headers['last-modified'];
    }
  }
  if (empty($headers['Accept'])) {

    // Tell the sever we're looking for XML.
    $headers['Accept'] = 'application/xml';
  }
  $result = drupal_http_request($uri, array(
    'headers' => $headers,
  ));
  if (isset($result->error)) {
    if ($this->options['show_errors']) {
      $message = format_string('HTTP response: %error. URI: %uri', array(
        '%error' => $result->error,
        '%uri' => $uri,
      ));
      throw new Exception($message);
    }
    return;
  }
  $cache_file_uri = "{$destination}/{$cache_file}";
  if ($result->code == 304) {
    if (file_exists($cache_file_uri)) {
      return file_get_contents($cache_file_uri);
    }

    // We have the headers but no cache file. :(
    // Run it back.
    cache_clear_all($cache_file, 'cache');
    return $this
      ->fetch_file($uri);
  }

  // Cache data to a file.
  file_unmanaged_save_data($result->data, $cache_file_uri, FILE_EXISTS_REPLACE);
  cache_set($cache_file, $result->headers);
  return $result->data;
}