You are here

function oembedcore_oembed_fetch in oEmbed 6.0

2 calls to oembedcore_oembed_fetch()
oembedcore_oembed_data in ./oembedcore.module
Fetch data for an embeddable URL.
_oembedprovider_handle_request in ./oembedprovider.inc
Callback handler for oembed requests.

File

./oembedcore.module, line 265
Core functionality for oEmbed

Code

function oembedcore_oembed_fetch($provider, $url, $matches, $attributes = array()) {
  $embed = FALSE;
  $attributes['url'] = $url;
  $query = http_build_query($attributes, NULL, '&');
  $source = isset($provider['callback']) ? $provider['callback'] : $provider['endpoint'];
  $cache_key = 'oembedcore:embed:' . md5($source . $url . $query);
  $cache = cache_get($cache_key);
  if ($cache && isset($cache->data)) {
    $embed = $cache->data;
  }
  else {
    if (!empty($provider['callback'])) {
      $embed = call_user_func($provider['callback'], $provider, $url, $matches, $attributes);
      if ($embed) {
        $embed = (object) $embed;
      }
    }
    else {
      $fetch_url = $provider['endpoint'] . '?' . $query;

      //TODO: Add alternative ways of fetching the content - like http client?
      $response = drupal_http_request($fetch_url);
      if (!isset($response->error)) {
        $embed = json_decode($response->data);
        if (!is_object($embed)) {
          try {
            $embed = @new SimpleXMLElement($response->data);
            $embed = (object) get_object_vars($embed);
            if (!is_string($embed->title)) {
              $embed->title = '';
            }
          } catch (Exception $e) {
            watchdog('oembed', 'Could not parse response from %url.', array(
              '%url' => $fetch_url,
            ), WATCHDOG_ERROR);
          }
        }
        if (empty($embed->version) || empty($embed->type) || intval($embed->version) != 1) {
          $embed = FALSE;
          watchdog('oembed', 'Response from %url not a valid oEmbed response.', array(
            '%url' => $fetch_url,
          ), WATCHDOG_ERROR);
        }
      }
      else {
        watchdog('oembed', 'Error fetching data from %url.', array(
          '%url' => $fetch_url,
        ), WATCHDOG_ERROR);
      }
    }
    if ($embed) {
      $embed->original_url = $url;
    }
    $max_age = isset($embed->cache_age) ? intval($embed->cache_age) : empty($provider['callback']) ? 600 : 60;
    cache_set($cache_key, $embed, 'cache', time() + $max_age);
  }
  return $embed;
}