You are here

rel_to_abs.module in Relative Path to Absolute URLs 6

Same filename and directory in other branches
  1. 7 rel_to_abs.module

Relative Paths to Absolute URLs

Filter for converting relative paths to absolute URLs.

File

rel_to_abs.module
View source
<?php

/**
 * @file
 * Relative Paths to Absolute URLs
 *
 * Filter for converting relative paths to absolute URLs.
 *
 */

/**
 * Implementation of hook_filter().
 */
function rel_to_abs_filter($op, $delta = 0, $format = -1, $text = '', $cache_id = 0) {
  if ($op == 'prepare') {
    return $text;
  }
  elseif ($op == 'process' && $text != '') {
    $lang = language_default();
    $front = url('<front>', array(
      'absolute' => TRUE,
      'language' => $lang,
    ));
    $base_url = $front;
    $text = _absolute_url($text, $base_url);
    return $text;
  }
  elseif ($op === 'list') {
    return array(
      t('Relative Paths to Absolute URLs'),
    );
  }
  elseif ($op === 'description') {
    return t('Filter for conversion of relative paths to absolute URLs');
  }
  elseif ($op === 'settings') {
    return array();
  }
  return $text;
}

/**
 * Helper for filter processing.
 *
 * @param string $txt
 *   String to process on.
 * @param string $base_url
 *   Base Url string.
 *
 * @return string
 *   Processed string of source text.
 */
function _absolute_url($txt, $base_url) {
  $needles = array(
    'href="',
    'src="',
    'background="',
  );
  $new_txt = '';
  if (substr($base_url, -1) != '/') {
    $base_url .= '/';
  }
  $new_base_url = $base_url;
  foreach ($needles as $needle) {
    while ($pos = strpos($txt, $needle)) {
      $pos += strlen($needle);
      if (substr($txt, $pos, 7) != 'http://' && substr($txt, $pos, 8) != 'https://' && substr($txt, $pos, 6) != 'ftp://' && substr($txt, $pos, 7) != 'mailto:' && substr($txt, $pos, 2) != '//') {
        $last = substr($txt, $pos, 1);
        $new_txt .= substr($txt, 0, $pos) . ($last == '/' ? rtrim($new_base_url, '/') : $new_base_url);
      }
      else {
        $new_txt .= substr($txt, 0, $pos);
      }
      $txt = substr($txt, $pos);
    }
    $txt = $new_txt . $txt;
    $new_txt = '';
  }
  return $txt;
}

Functions

Namesort descending Description
rel_to_abs_filter Implementation of hook_filter().
_absolute_url Helper for filter processing.