You are here

function _shorten_get_url in Shorten URLs 8.2

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

Shortens URLs. Times out after three (3) seconds.

Parameters

$original: The URL of the page for which to retrieve the abbreviated URL.

$api: A string or array used to retrieve a shortened URL. If it is an array, it can have the elements 'custom,' 'url,' 'tag,' 'json,' and 'args.'

$service: The service to use to abbreviate the URL. For services available by default, see shorten_shorten_service().

Return value

An abbreviated URL.

1 call to _shorten_get_url()
shorten_url in ./shorten.module
Retrieves and beautifies the abbreviated URL. This is the main API function of this module.

File

./shorten.module, line 145

Code

function _shorten_get_url($original, $api, $service) {
  $method = mb_strtoupper(\Drupal::config('shorten.settings')
    ->get('shorten_method'));
  $service = t('an unknown service');
  if (is_string($api)) {
    $url = shorten_fetch($api . $original);
    $service = $api;
  }
  elseif (is_array($api)) {

    // Merge in defaults.
    $api += [
      'custom' => FALSE,
      'json' => FALSE,
    ];
    if (!empty($api['url'])) {
      $original = urlencode($original);

      // Typically $api['custom'] == 'xml' although it doesn't have to.
      if (!empty($api['tag'])) {
        $url = shorten_fetch($api['url'] . $original, $api['tag']);
      }
      elseif (!empty($api['json'])) {
        $url = shorten_fetch($api['url'] . $original, $api['json'], 'json');
      }
      elseif (!$api['custom']) {
        $url = shorten_fetch($api['url'] . $original);
      }
      $service = $api['url'];
    }
    elseif (is_string($api['custom']) && function_exists($api['custom'])) {
      $method = t('A custom method: @method()', [
        '@method' => $api['custom'],
      ]);
      if (!empty($api['args']) && is_array($api['args'])) {
        $args = $api['args'];
        array_unshift($args, $original);
        $url = call_user_func_array($api['custom'], $args);
      }
      else {
        $url = call_user_func($api['custom'], $original);
      }
    }
  }
  if (isset($url)) {
    if (mb_substr($url, 0, 7) == 'http://' || mb_substr($url, 0, 8) == 'https://') {
      return $url;
    }
  }
  \Drupal::logger('shorten')
    ->notice('%method failed to return an abbreviated URL from %service.', [
    '%method' => $method,
    '%service' => $service,
  ]);
  return FALSE;
}