You are here

function shorten_fetch in Shorten URLs 6

Same name and namespace in other branches
  1. 8.2 shorten.module \shorten_fetch()
  2. 8 shorten.module \shorten_fetch()
  3. 7.2 shorten.module \shorten_fetch()
  4. 7 shorten.module \shorten_fetch()

Downloads the response of the URL abbreviation service.

Parameters

$url: The URL which will return an abbreviated URL from any service. Includes both the service and the URL to be shortened.

$tag: If the response is XML, the tag within which to look for the shortened URL.

$special: A special format the service will return. Currently only supports 'json.'

Return value

An abbreviated URL or FALSE if fetching the abbreviated URL fails.

1 call to shorten_fetch()
_shorten_get_url in ./shorten.module
Shortens URLs. Times out after three (3) seconds.

File

./shorten.module, line 337
Shortens URLs via external services.

Code

function shorten_fetch($url, $tag = '', $special = '') {

  //drupal_http_request() does not offer a reliable way to time out.
  if (variable_get('shorten_method', _shorten_method_default()) == 'php') {
    $context = stream_context_create(array(
      'http' => array(
        'timeout' => variable_get('shorten_timeout', 3),
      ),
    ));
    $contents = file_get_contents($url, 0, $context);
  }
  elseif (variable_get('shorten_method', _shorten_method_default()) == 'curl') {
    $c = curl_init();
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($c, CURLOPT_CONNECTTIMEOUT, variable_get('shorten_timeout', 3));
    curl_setopt($c, CURLOPT_URL, $url);
    $contents = curl_exec($c);
    curl_close($c);
  }
  else {
    return FALSE;
  }
  if (!$contents) {
    return FALSE;
  }
  if ($tag) {
    if (!$special) {
      $contents = _shorten_xml($contents, $tag);
    }
    elseif ($special == 'json') {
      $contents = json_decode($contents, TRUE);
      $contents = $contents[$tag];
    }
  }
  if (!$contents || $contents == $url) {
    return FALSE;
  }
  return $contents;
}