Url.php 11.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
<?php

/**
 * @file
 * Contains \Drupal\Component\Utility\Url.
 */

namespace Drupal\Component\Utility;

/**
 * Helper class URL based methods.
 */
class Url {

  /**
   * The list of allowed protocols.
   *
   * @var array
   */
  protected static $allowedProtocols = array('http', 'https');

  /**
   * Parses an array into a valid, rawurlencoded query string.
   *
   *
   * rawurlencode() is RFC3986 compliant, and as a consequence RFC3987
   * compliant. The latter defines the required format of "URLs" in HTML5.
   * urlencode() is almost the same as rawurlencode(), except that it encodes
   * spaces as "+" instead of "%20". This makes its result non compliant to
   * RFC3986 and as a consequence non compliant to RFC3987 and as a consequence
   * not valid as a "URL" in HTML5.
   *
   * @todo Remove this function once PHP 5.4 is required as we can use just
   *   http_build_query() directly.
   *
   * @param array $query
   *   The query parameter array to be processed, e.g. $_GET.
   * @param string $parent
   *   Internal use only. Used to build the $query array key for nested items.
   *
   * @return string
   *   A rawurlencoded string which can be used as or appended to the URL query
   *   string.
   *
   * @ingroup php_wrappers
   */
  public static function buildQuery(array $query, $parent = '') {
    $params = array();

    foreach ($query as $key => $value) {
      $key = ($parent ? $parent . '[' . rawurlencode($key) . ']' : rawurlencode($key));

      // Recurse into children.
      if (is_array($value)) {
        $params[] = static::buildQuery($value, $key);
      }
      // If a query parameter value is NULL, only append its key.
      elseif (!isset($value)) {
        $params[] = $key;
      }
      else {
        // For better readability of paths in query strings, we decode slashes.
        $params[] = $key . '=' . str_replace('%2F', '/', rawurlencode($value));
      }
    }

    return implode('&', $params);
  }

  /**
   * Filters a URL query parameter array to remove unwanted elements.
   *
   * @param array $query
   *   An array to be processed.
   * @param array $exclude
   *   (optional) A list of $query array keys to remove. Use "parent[child]" to
   *   exclude nested items.
   * @param string $parent
   *   Internal use only. Used to build the $query array key for nested items.
   *
   * @return
   *   An array containing query parameters.
   */
  public static function filterQueryParameters(array $query, array $exclude = array(), $parent = '') {
    // If $exclude is empty, there is nothing to filter.
    if (empty($exclude)) {
      return $query;
    }
    elseif (!$parent) {
      $exclude = array_flip($exclude);
    }

    $params = array();
    foreach ($query as $key => $value) {
      $string_key = ($parent ? $parent . '[' . $key . ']' : $key);
      if (isset($exclude[$string_key])) {
        continue;
      }

      if (is_array($value)) {
        $params[$key] = static::filterQueryParameters($value, $exclude, $string_key);
      }
      else {
        $params[$key] = $value;
      }
    }

    return $params;
  }

  /**
   * Parses a system URL string into an associative array.
   *
   * This function should only be used for URLs that have been generated by the
   * system. It should not be used for URLs that come from external sources, or
   * URLs that link to external resources.
   *
   * The returned array contains a 'path' that may be passed separately to url().
   * For example:
   * @code
   *   $options = Url::parse($_GET['destination']);
   *   $my_url = url($options['path'], $options);
   *   $my_link = l('Example link', $options['path'], $options);
   * @endcode
   *
   * @param string $url
   *   The URL string to parse, f.e. $_GET['destination'].
   *
   * @return
   *   An associative array containing the keys:
   *   - 'path': The path of the URL. If the given $url is external, this includes
   *     the scheme and host.
   *   - 'query': An array of query parameters of $url, if existent.
   *   - 'fragment': The fragment of $url, if existent.
   *
   * @ingroup php_wrappers
   */
  public static function parse($url) {
    $options = array(
      'path' => NULL,
      'query' => array(),
      'fragment' => '',
    );

    // External URLs: not using parse_url() here, so we do not have to rebuild
    // the scheme, host, and path without having any use for it.
    if (strpos($url, '://') !== FALSE) {
      // Split off everything before the query string into 'path'.
      $parts = explode('?', $url);
      $options['path'] = $parts[0];
      // If there is a query string, transform it into keyed query parameters.
      if (isset($parts[1])) {
        $query_parts = explode('#', $parts[1]);
        parse_str($query_parts[0], $options['query']);
        // Take over the fragment, if there is any.
        if (isset($query_parts[1])) {
          $options['fragment'] = $query_parts[1];
        }
      }
    }
    // Internal URLs.
    else {
      // parse_url() does not support relative URLs, so make it absolute. E.g. the
      // relative URL "foo/bar:1" isn't properly parsed.
      $parts = parse_url('http://example.com/' . $url);
      // Strip the leading slash that was just added.
      $options['path'] = substr($parts['path'], 1);
      if (isset($parts['query'])) {
        parse_str($parts['query'], $options['query']);
      }
      if (isset($parts['fragment'])) {
        $options['fragment'] = $parts['fragment'];
      }
    }

    return $options;
  }

  /**
   * Encodes a Drupal path for use in a URL.
   *
   * For aesthetic reasons slashes are not escaped.
   *
   * @param string $path
   *   The Drupal path to encode.
   *
   * @return string
   *   The encoded path.
   */
  public static function encodePath($path) {
    return str_replace('%2F', '/', rawurlencode($path));
  }

  /**
   * Returns whether a path is external to Drupal (e.g. http://example.com).
   *
   * If a path cannot be assessed by Drupal's menu handler, then we must
   * treat it as potentially insecure.
   *
   * @param string $path
   *   The internal path or external URL being linked to, such as "node/34" or
   *   "http://example.com/foo".
   *
   * @return bool
   *   TRUE or FALSE, where TRUE indicates an external path.
   */
  public static function isExternal($path) {
    $colonpos = strpos($path, ':');
    // Avoid calling stripDangerousProtocols() if there is any
    // slash (/), hash (#) or question_mark (?) before the colon (:)
    // occurrence - if any - as this would clearly mean it is not a URL.
    return $colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && static::stripDangerousProtocols($path) == $path;
  }

  /**
   * Determines if an external URL points to this installation.
   *
   * @param string $url
   *   A string containing an external URL, such as "http://example.com/foo".
   * @param string $base_url
   *   The base URL string to check against, such as "http://example.com/"
   *
   * @return
   *   TRUE if the URL has the same domain and base path.
   */
  public static function externalIsLocal($url, $base_url) {
    $url_parts = parse_url($url);
    $base_host = parse_url($base_url, PHP_URL_HOST);

    if (!isset($url_parts['path'])) {
      return ($url_parts['host'] == $base_host);
    }
    else {
      // When comparing base paths, we need a trailing slash to make sure a
235 236
      // partial URL match isn't occurring. Since base_path() always returns
      // with a trailing slash, we don't need to add the trailing slash here.
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
      return ($url_parts['host'] == $base_host && stripos($url_parts['path'], $base_url) === 0);
    }
  }

  /**
   * Processes an HTML attribute value and strips dangerous protocols from URLs.
   *
   * @param string $string
   *   The string with the attribute value.
   *
   * @return string
   *   Cleaned up and HTML-escaped version of $string.
   */
  public static function filterBadProtocol($string) {
    // Get the plain text representation of the attribute value (i.e. its
    // meaning).
    $string = String::decodeEntities($string);
    return String::checkPlain(static::stripDangerousProtocols($string));
  }

  /**
   * Sets the allowed protocols.
   *
   * @param array $protocols
   *   An array of protocols, for example http, https and irc.
   */
  public static function setAllowedProtocols(array $protocols = array()) {
    static::$allowedProtocols = $protocols;
  }

  /**
   * Strips dangerous protocols (e.g. 'javascript:') from a URI.
   *
   * This function must be called for all URIs within user-entered input prior
   * to being output to an HTML attribute value. It is often called as part of
   * check_url() or Drupal\Component\Utility\Xss::filter(), but those functions
   * return an HTML-encoded string, so this function can be called independently
   * when the output needs to be a plain-text string for passing to t(), l(),
   * Drupal\Core\Template\Attribute, or another function that will call
   * \Drupal\Component\Utility\String::checkPlain() separately.
   *
   * @param string $uri
   *   A plain-text URI that might contain dangerous protocols.
   *
   * @return string
   *   A plain-text URI stripped of dangerous protocols. As with all plain-text
   *   strings, this return value must not be output to an HTML page without
   *   being sanitized first. However, it can be passed to functions
   *   expecting plain-text strings.
   */
  public static function stripDangerousProtocols($uri) {
    $allowed_protocols = array_flip(static::$allowedProtocols);

    // Iteratively remove any invalid protocol found.
    do {
      $before = $uri;
      $colonpos = strpos($uri, ':');
      if ($colonpos > 0) {
        // We found a colon, possibly a protocol. Verify.
        $protocol = substr($uri, 0, $colonpos);
        // If a colon is preceded by a slash, question mark or hash, it cannot
        // possibly be part of the URL scheme. This must be a relative URL, which
        // inherits the (safe) protocol of the base document.
        if (preg_match('![/?#]!', $protocol)) {
          break;
        }
        // Check if this is a disallowed protocol. Per RFC2616, section 3.2.3
        // (URI Comparison) scheme comparison must be case-insensitive.
        if (!isset($allowed_protocols[strtolower($protocol)])) {
          $uri = substr($uri, $colonpos + 1);
        }
      }
    } while ($before != $uri);

    return $uri;
  }

  /**
   * Verifies the syntax of the given URL.
   *
   * This function should only be used on actual URLs. It should not be used for
   * Drupal menu paths, which can contain arbitrary characters.
   * Valid values per RFC 3986.
   *
   * @param string $url
   *   The URL to verify.
   * @param bool $absolute
   *   Whether the URL is absolute (beginning with a scheme such as "http:").
   *
   * @return bool
   *   TRUE if the URL is in a valid format, FALSE otherwise.
   */
  public static function isValid($url, $absolute = FALSE) {
    if ($absolute) {
      return (bool) preg_match("
        /^                                                      # Start at the beginning of the text
        (?:ftp|https?|feed):\/\/                                # Look for ftp, http, https or feed schemes
        (?:                                                     # Userinfo (optional) which is typically
          (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)*      # a username or a username and password
          (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@          # combination
        )?
        (?:
          (?:[a-z0-9\-\.]|%[0-9a-f]{2})+                        # A domain name or a IPv4 address
          |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\])         # or a well formed IPv6 address
        )
        (?::[0-9]+)?                                            # Server port number (optional)
        (?:[\/|\?]
          (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})   # The path and query (optional)
        *)?
      $/xi", $url);
    }
    else {
      return (bool) preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
    }
  }

}