Url.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. <?php
  2. /**
  3. * Converts an array-represented URL to a string
  4. *
  5. * Source: http://php.net/manual/en/function.parse-url.php#106731
  6. *
  7. * @see http://php.net/manual/en/function.parse-url.php
  8. *
  9. * @param array $parsedUrl an array-represented URL
  10. *
  11. * @return string the string representation of the URL
  12. */
  13. function unparse_url($parsedUrl)
  14. {
  15. $scheme = isset($parsedUrl['scheme']) ? $parsedUrl['scheme'].'://' : '';
  16. $host = isset($parsedUrl['host']) ? $parsedUrl['host'] : '';
  17. $port = isset($parsedUrl['port']) ? ':'.$parsedUrl['port'] : '';
  18. $user = isset($parsedUrl['user']) ? $parsedUrl['user'] : '';
  19. $pass = isset($parsedUrl['pass']) ? ':'.$parsedUrl['pass'] : '';
  20. $pass = ($user || $pass) ? "$pass@" : '';
  21. $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
  22. $query = isset($parsedUrl['query']) ? '?'.$parsedUrl['query'] : '';
  23. $fragment = isset($parsedUrl['fragment']) ? '#'.$parsedUrl['fragment'] : '';
  24. return "$scheme$user$pass$host$port$path$query$fragment";
  25. }
  26. /**
  27. * Removes undesired query parameters and fragments
  28. *
  29. * @param string url Url to be cleaned
  30. *
  31. * @return string the string representation of this URL after cleanup
  32. */
  33. function cleanup_url($url)
  34. {
  35. $obj_url = new Url($url);
  36. return $obj_url->cleanup();
  37. }
  38. /**
  39. * Get URL scheme.
  40. *
  41. * @param string url Url for which the scheme is requested
  42. *
  43. * @return mixed the URL scheme or false if none is provided.
  44. */
  45. function get_url_scheme($url)
  46. {
  47. $obj_url = new Url($url);
  48. return $obj_url->getScheme();
  49. }
  50. /**
  51. * Adds a trailing slash at the end of URL if necessary.
  52. *
  53. * @param string $url URL to check/edit.
  54. *
  55. * @return string $url URL with a end trailing slash.
  56. */
  57. function add_trailing_slash($url)
  58. {
  59. return $url . (!endsWith($url, '/') ? '/' : '');
  60. }
  61. /**
  62. * Replace not whitelisted protocols by 'http://' from given URL.
  63. *
  64. * @param string $url URL to clean
  65. * @param array $protocols List of allowed protocols (aside from http(s)).
  66. *
  67. * @return string URL with allowed protocol
  68. */
  69. function whitelist_protocols($url, $protocols)
  70. {
  71. if (startsWith($url, '?') || startsWith($url, '/')) {
  72. return $url;
  73. }
  74. $protocols = array_merge(['http', 'https'], $protocols);
  75. $protocol = preg_match('#^(\w+):/?/?#', $url, $match);
  76. // Protocol not allowed: we remove it and replace it with http
  77. if ($protocol === 1 && ! in_array($match[1], $protocols)) {
  78. $url = str_replace($match[0], 'http://', $url);
  79. } elseif ($protocol !== 1) {
  80. $url = 'http://' . $url;
  81. }
  82. return $url;
  83. }
  84. /**
  85. * URL representation and cleanup utilities
  86. *
  87. * Form
  88. * scheme://[username:password@]host[:port][/path][?query][#fragment]
  89. *
  90. * Examples
  91. * http://username:password@hostname:9090/path?arg1=value1&arg2=value2#anchor
  92. * https://host.name.tld
  93. * https://h2.g2/faq/?vendor=hitchhiker&item=guide&dest=galaxy#answer
  94. *
  95. * @see http://www.faqs.org/rfcs/rfc3986.html
  96. */
  97. class Url
  98. {
  99. private static $annoyingQueryParams = array(
  100. // Facebook
  101. 'action_object_map=',
  102. 'action_ref_map=',
  103. 'action_type_map=',
  104. 'fb_',
  105. 'fb=',
  106. 'PHPSESSID=',
  107. // Scoop.it
  108. '__scoop',
  109. // Google Analytics & FeedProxy
  110. 'utm_',
  111. // ATInternet
  112. 'xtor=',
  113. // Other
  114. 'campaign_'
  115. );
  116. private static $annoyingFragments = array(
  117. // ATInternet
  118. 'xtor=RSS-',
  119. // Misc.
  120. 'tk.rss_all'
  121. );
  122. /*
  123. * URL parts represented as an array
  124. *
  125. * @see http://php.net/parse_url
  126. */
  127. protected $parts;
  128. /**
  129. * Parses a string containing a URL
  130. *
  131. * @param string $url a string containing a URL
  132. */
  133. public function __construct($url)
  134. {
  135. $url = self::cleanupUnparsedUrl(trim($url));
  136. $this->parts = parse_url($url);
  137. if (!empty($url) && empty($this->parts['scheme'])) {
  138. $this->parts['scheme'] = 'http';
  139. }
  140. }
  141. /**
  142. * Clean up URL before it's parsed.
  143. * ie. handle urlencode, url prefixes, etc.
  144. *
  145. * @param string $url URL to clean.
  146. *
  147. * @return string cleaned URL.
  148. */
  149. protected static function cleanupUnparsedUrl($url)
  150. {
  151. return self::removeFirefoxAboutReader($url);
  152. }
  153. /**
  154. * Remove Firefox Reader prefix if it's present.
  155. *
  156. * @param string $input url
  157. *
  158. * @return string cleaned url
  159. */
  160. protected static function removeFirefoxAboutReader($input)
  161. {
  162. $firefoxPrefix = 'about://reader?url=';
  163. if (startsWith($input, $firefoxPrefix)) {
  164. return urldecode(ltrim($input, $firefoxPrefix));
  165. }
  166. return $input;
  167. }
  168. /**
  169. * Returns a string representation of this URL
  170. */
  171. public function toString()
  172. {
  173. return unparse_url($this->parts);
  174. }
  175. /**
  176. * Removes undesired query parameters
  177. */
  178. protected function cleanupQuery()
  179. {
  180. if (! isset($this->parts['query'])) {
  181. return;
  182. }
  183. $queryParams = explode('&', $this->parts['query']);
  184. foreach (self::$annoyingQueryParams as $annoying) {
  185. foreach ($queryParams as $param) {
  186. if (startsWith($param, $annoying)) {
  187. $queryParams = array_diff($queryParams, array($param));
  188. continue;
  189. }
  190. }
  191. }
  192. if (count($queryParams) == 0) {
  193. unset($this->parts['query']);
  194. return;
  195. }
  196. $this->parts['query'] = implode('&', $queryParams);
  197. }
  198. /**
  199. * Removes undesired fragments
  200. */
  201. protected function cleanupFragment()
  202. {
  203. if (! isset($this->parts['fragment'])) {
  204. return;
  205. }
  206. foreach (self::$annoyingFragments as $annoying) {
  207. if (startsWith($this->parts['fragment'], $annoying)) {
  208. unset($this->parts['fragment']);
  209. break;
  210. }
  211. }
  212. }
  213. /**
  214. * Removes undesired query parameters and fragments
  215. *
  216. * @return string the string representation of this URL after cleanup
  217. */
  218. public function cleanup()
  219. {
  220. $this->cleanupQuery();
  221. $this->cleanupFragment();
  222. return $this->toString();
  223. }
  224. /**
  225. * Converts an URL with an International Domain Name host to a ASCII one.
  226. * This requires PHP-intl. If it's not available, just returns this->cleanup().
  227. *
  228. * @return string converted cleaned up URL.
  229. */
  230. public function idnToAscii()
  231. {
  232. $out = $this->cleanup();
  233. if (! function_exists('idn_to_ascii') || ! isset($this->parts['host'])) {
  234. return $out;
  235. }
  236. $asciiHost = idn_to_ascii($this->parts['host'], 0, INTL_IDNA_VARIANT_UTS46);
  237. return str_replace($this->parts['host'], $asciiHost, $out);
  238. }
  239. /**
  240. * Get URL scheme.
  241. *
  242. * @return string the URL scheme or false if none is provided.
  243. */
  244. public function getScheme()
  245. {
  246. if (!isset($this->parts['scheme'])) {
  247. return false;
  248. }
  249. return $this->parts['scheme'];
  250. }
  251. /**
  252. * Get URL host.
  253. *
  254. * @return string the URL host or false if none is provided.
  255. */
  256. public function getHost()
  257. {
  258. if (empty($this->parts['host'])) {
  259. return false;
  260. }
  261. return $this->parts['host'];
  262. }
  263. /**
  264. * Test if the Url is an HTTP one.
  265. *
  266. * @return true is HTTP, false otherwise.
  267. */
  268. public function isHttp()
  269. {
  270. return strpos(strtolower($this->parts['scheme']), 'http') !== false;
  271. }
  272. }