URIUtil.php
1 <?php
2 /**
3  * wCMF - wemove Content Management Framework
4  * Copyright (C) 2005-2015 wemove digital solutions GmbH
5  *
6  * Licensed under the terms of the MIT License.
7  *
8  * See the LICENSE file distributed with this work for
9  * additional information.
10  */
11 namespace wcmf\lib\util;
12 
13 /**
14  * URIUtil provides support for uri manipulation.
15  *
16  * @author ingo herwig <ingo@wemove.com>
17  */
18 class URIUtil {
19 
20  /**
21  * Convert an absolute URI to a relative
22  * code from http://www.webmasterworld.com/forum88/334.htm
23  * @param $abs_uri Absolute URI to convert, may have a trailing filename
24  * @param $base Base URI
25  */
26  public static function makeRelative($abs_uri, $base) {
27  // normalize slashes and remove drive names
28  list($abs_uri, $base) = self::normalize(array($abs_uri, $base));
29 
30  // add slash to base if missing
31  if (!preg_match('/\/$/', $base)) {
32  $base .= '/';
33  }
34  $abs_array = explode('/', $abs_uri);
35  $base_array = explode('/', $base);
36 
37  // remove trailing file names
38  $fileName = '';
39  if (strrpos($abs_uri, '/') !== strlen($abs_uri)) {
40  $fileName = array_pop($abs_array);
41  }
42  if (strrpos($base, '/') !== strlen($base)) {
43  array_pop($base_array);
44  }
45 
46  // ignore common path
47  while (sizeof($abs_array) > 0 && sizeof($base_array) > 0 && $abs_array[0] == $base_array[0]) {
48  array_shift($abs_array);
49  array_shift($base_array);
50  }
51 
52  // construct connecting path
53  $rel_uri = str_repeat('../', sizeof($base_array)).join('/', $abs_array).'/'.$fileName;
54  return $rel_uri;
55  }
56 
57  /**
58  * Convert a relative URI to an absolute
59  * code from http://99webtools.com/relative-path-into-absolute-url.php
60  * @param $rel_uri Relative URI to convert
61  * @param $base Base URI
62  */
63  public static function makeAbsolute($rel_uri, $base) {
64  list($rel_uri, $base) = self::normalize(array($rel_uri, $base));
65 
66  if(strpos($rel_uri, "//") === 0) {
67  return "http:".$rel_uri;
68  }
69  // return if already absolute URL
70  if (parse_url($rel_uri, PHP_URL_SCHEME) != '') {
71  return $rel_uri;
72  }
73  // add slash to base if missing
74  if (!preg_match('/\/$/', $base)) {
75  $base .= '/';
76  }
77  $firstChar = (strlen($rel_uri) > 0) ? substr($rel_uri, 0, 1) : '';
78  // queries and anchors
79  if ($firstChar == '#' || $firstChar == '?') {
80  return $base.$rel_uri;
81  }
82  // parse base URL and convert to local variables: $scheme, $host, $path
83  extract(parse_url($base));
84  $scheme = !isset($scheme) ? 'http' : $scheme;
85  $host = !isset($host) ? '' : $host;
86  $path = !isset($path) ? '' : $path;
87  // remove non-directory element from path
88  $path = preg_replace('#/[^/]*$#', '', $path);
89  // destroy path if relative url points to root
90  if ($firstChar == '/') {
91  $path = '';
92  }
93  // dirty absolute URL
94  $abs = "$host$path/$rel_uri";
95  // replace '//' or '/./' or '/foo/../' with '/'
96  $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
97  for ($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
98  // absolute URL is ready!
99  return $scheme.'://'.$abs;
100  }
101 
102  /**
103  * Translate a relative URI from one location to the script location.
104  * For example if a file path is stored relative to location A and should be
105  * translated to the script URI (location B), use
106  * URIUtil::translate($filepathAsSeenFromA, $pathFromBtoA)
107  * @param $rel_uri Relative URI to translate as seen from base
108  * @param $base Base URI
109  * @return An associtative array with keys 'absolute' and 'relative'
110  * and the absolute and relative URI (as seen from the executed script) as values
111  */
112  public static function translate($rel_uri, $base) {
113  list($rel_uri, $base) = self::normalize(array($rel_uri, $base));
114 
115  $self = self::getProtocolStr().$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
116  $path = dirname($self).'/';
117  $absUrl = self::makeAbsolute($rel_uri, $path.$base);
118  $relUrl = self::makeRelative($absUrl, $path);
119 
120  return array('absolute' => $absUrl, 'relative' => $relUrl);
121  }
122 
123  /**
124  * Check if an url is available (HTTP-Code: 200)
125  * @note requires cURL library
126  * @param $url The url to check
127  * @param $timeout The timeout in seconds (default: 5)
128  * @return Boolean whether the url is available
129  */
130  public static function validateUrl($url, $timeout=5) {
131  $url_parts = @parse_url($url);
132  // check local relative url
133  if (empty($url_parts["host"])) {
134  $fh = @fopen($url, "r");
135  return ($fh !== false);
136  }
137 
138  // check remote url
139  $ch = curl_init();
140  curl_setopt($ch, CURLOPT_URL, $url);
141  curl_setopt($ch, CURLOPT_HEADER, true);
142  curl_setopt($ch, CURLOPT_NOBODY, true);
143  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
144  curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
145  $r = curl_exec($ch);
146  $headers = split("\n", $r);
147 
148  preg_match('/.+ ([0-9]{3}) .+/', $headers[0], $matches);
149  return (intval($matches[1]) < 400);
150  }
151 
152  /*
153  * Get the protocol string (http:// or https://)
154  * @return The protocol string
155  */
156  public static function getProtocolStr() {
157  if (isset($_SERVER['HTTPS']) && strlen($_SERVER['HTTPS']) > 0 && $_SERVER['HTTPS'] != 'off') {
158  return 'https://';
159  }
160  else {
161  return 'http://';
162  }
163  }
164 
165  /**
166  * Get the current page url
167  * @return The url of the page
168  */
169  public static function getPageURL() {
170  $pageURL = self::getProtocolStr();
171  if ($_SERVER["SERVER_PORT"] != "80") {
172  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
173  }
174  else {
175  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
176  }
177  return $pageURL;
178  }
179 
180  /**
181  * Normalize slashes and remove drive names
182  * @param $paths Path to normalize or array of paths
183  */
184  public static function normalize($paths) {
185  return preg_replace(
186  array("/\\\\/", "/^[^:]{1}:/", ), array('/', ''),
187  $paths);
188  }
189 }
190 ?>
static translate($rel_uri, $base)
Translate a relative URI from one location to the script location.
Definition: URIUtil.php:112
static validateUrl($url, $timeout=5)
Check if an url is available (HTTP-Code: 200)
Definition: URIUtil.php:130
Utility classes.
Definition: namespaces.php:97
static getPageURL()
Get the current page url.
Definition: URIUtil.php:169
static getProtocolStr()
Definition: URIUtil.php:156
static makeRelative($abs_uri, $base)
Convert an absolute URI to a relative code from http://www.webmasterworld.com/forum88/334.htm.
Definition: URIUtil.php:26
static normalize($paths)
Normalize slashes and remove drive names.
Definition: URIUtil.php:184
static makeAbsolute($rel_uri, $base)
Convert a relative URI to an absolute code from http://99webtools.com/relative-path-into-absolute-url...
Definition: URIUtil.php:63
URIUtil provides support for uri manipulation.
Definition: URIUtil.php:18