3 * @file src/Util/Network.php
5 namespace Friendica\Util;
8 use Friendica\Core\Addon;
9 use Friendica\Core\L10n;
10 use Friendica\Core\System;
11 use Friendica\Core\Config;
12 use Friendica\Network\Curl;
13 use Friendica\Network\HTTPException\InternalServerErrorException;
14 use Friendica\Network\Probe;
15 use Friendica\Object\Image;
16 use Friendica\Util\XML;
23 * @var Curl The latest Curl output
28 * Returns the latest Curl output
30 * @return Curl The latest Curl output
32 public static function getCurl()
34 if (empty(self::$curl)) {
35 self::$curl = new Curl();
44 * If binary flag is true, return binary results.
45 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
46 * to preserve cookies from one request to the next.
49 * @param string $url URL to fetch
50 * @param boolean $binary default false
51 * TRUE if asked to return binary results (file download)
52 * @param integer $redirects The recursion counter for internal use - default 0
53 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
54 * @param string $accept_content supply Accept: header with 'accept_content' as the value
55 * @param string $cookiejar Path to cookie jar file
57 * @return string The fetched content
59 public static function fetchUrl($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = '')
61 $ret = self::fetchUrlFull($url, $binary, $redirects, $timeout, $accept_content, $cookiejar);
67 * Curl wrapper with array of return values.
69 * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
70 * all the information collected during the fetch.
72 * @brief Curl wrapper with array of return values.
73 * @param string $url URL to fetch
74 * @param boolean $binary default false
75 * TRUE if asked to return binary results (file download)
76 * @param integer $redirects The recursion counter for internal use - default 0
77 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
78 * @param string $accept_content supply Accept: header with 'accept_content' as the value
79 * @param string $cookiejar Path to cookie jar file
81 * @return array With all relevant information, 'body' contains the actual fetched content.
83 public static function fetchUrlFull($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = '')
90 'accept_content'=>$accept_content,
91 'cookiejar'=>$cookiejar
97 * @brief fetches an URL.
99 * @param string $url URL to fetch
100 * @param boolean $binary default false
101 * TRUE if asked to return binary results (file download)
102 * @param int $redirects The recursion counter for internal use - default 0
103 * @param array $opts (optional parameters) assoziative array with:
104 * 'accept_content' => supply Accept: header with 'accept_content' as the value
105 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
106 * 'http_auth' => username:password
107 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
108 * 'nobody' => only return the header
109 * 'cookiejar' => path to cookie jar file
111 * @return array an assoziative array with:
112 * int 'return_code' => HTTP return code or 0 if timeout or failure
113 * boolean 'success' => boolean true (if HTTP 2xx result) or false
114 * string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
115 * string 'header' => HTTP headers
116 * string 'body' => fetched content
118 public static function curl($url, $binary = false, &$redirects = 0, $opts = [])
120 $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
122 $stamp1 = microtime(true);
126 $parts = parse_url($url);
127 $path_parts = explode('/', defaults($parts, 'path', ''));
128 foreach ($path_parts as $part) {
129 if (strlen($part) <> mb_strlen($part)) {
130 $parts2[] = rawurlencode($part);
135 $parts['path'] = implode('/', $parts2);
136 $url = self::unparseURL($parts);
138 if (self::isUrlBlocked($url)) {
139 logger('domain of ' . $url . ' is blocked', LOGGER_DATA);
143 $ch = @curl_init($url);
145 if (($redirects > 8) || (!$ch)) {
149 @curl_setopt($ch, CURLOPT_HEADER, true);
151 if (x($opts, "cookiejar")) {
152 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
153 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
156 // These settings aren't needed. We're following the location already.
157 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
158 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
160 if (x($opts, 'accept_content')) {
164 ['Accept: ' . $opts['accept_content']]
168 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
169 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
171 $range = intval(Config::get('system', 'curl_range_bytes', 0));
174 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
177 // Without this setting it seems as if some webservers send compressed content
178 // This seems to confuse curl so that it shows this uncompressed.
179 /// @todo We could possibly set this value to "gzip" or something similar
180 curl_setopt($ch, CURLOPT_ENCODING, '');
182 if (x($opts, 'headers')) {
183 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
186 if (x($opts, 'nobody')) {
187 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
190 if (x($opts, 'timeout')) {
191 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
193 $curl_time = Config::get('system', 'curl_timeout', 60);
194 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
197 // by default we will allow self-signed certs
198 // but you can override this
200 $check_cert = Config::get('system', 'verifyssl');
201 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
204 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
207 $proxy = Config::get('system', 'proxy');
209 if (strlen($proxy)) {
210 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
211 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
212 $proxyuser = @Config::get('system', 'proxyuser');
214 if (strlen($proxyuser)) {
215 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
219 if (Config::get('system', 'ipv4_resolve', false)) {
220 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
224 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
227 // don't let curl abort the entire application
228 // if it throws any errors.
230 $s = @curl_exec($ch);
231 $curl_info = @curl_getinfo($ch);
233 // Special treatment for HTTP Code 416
234 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
235 if (($curl_info['http_code'] == 416) && ($range > 0)) {
236 @curl_setopt($ch, CURLOPT_RANGE, '');
237 $s = @curl_exec($ch);
238 $curl_info = @curl_getinfo($ch);
241 if (curl_errno($ch) !== CURLE_OK) {
242 logger('error fetching ' . $url . ': ' . curl_error($ch), LOGGER_INFO);
245 $ret['errno'] = curl_errno($ch);
248 $ret['info'] = $curl_info;
250 $http_code = $curl_info['http_code'];
252 logger($url . ': ' . $http_code . " " . $s, LOGGER_DATA);
255 // Pull out multiple headers, e.g. proxy and continuation headers
256 // allow for HTTP/2.x without fixing code
258 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
259 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
261 $base = substr($base, strlen($chunk));
264 self::$curl = new Curl($http_code, (isset($curl_info['content_type']) ? $curl_info['content_type'] : ''), $header);
266 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
267 $new_location_info = @parse_url($curl_info['redirect_url']);
268 $old_location_info = @parse_url($curl_info['url']);
270 $newurl = $curl_info['redirect_url'];
272 if (empty($new_location_info['path']) && !empty($new_location_info['host'])) {
273 $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
278 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
279 $newurl = trim(array_pop($matches));
281 if (strpos($newurl, '/') === 0) {
282 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
284 $old_location_query = @parse_url($url, PHP_URL_QUERY);
286 if ($old_location_query != '') {
287 $newurl .= '?' . $old_location_query;
290 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
293 return self::curl($newurl, $binary, $redirects, $opts);
297 self::$curl->setCode($http_code);
298 if (isset($curl_info['content_type'])) {
299 self::$curl->setContentType($curl_info['content_type']);
302 $rc = intval($http_code);
303 $ret['return_code'] = $rc;
304 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
305 $ret['redirect_url'] = $url;
307 if (!$ret['success']) {
308 $ret['error'] = curl_error($ch);
309 $ret['debug'] = $curl_info;
310 logger('error: '.$url.': '.$ret['return_code'].' - '.$ret['error'], LOGGER_DEBUG);
311 logger('debug: '.print_r($curl_info, true), LOGGER_DATA);
314 $ret['body'] = substr($s, strlen($header));
315 $ret['header'] = $header;
317 if (x($opts, 'debug')) {
318 $ret['debug'] = $curl_info;
323 $a->saveTimestamp($stamp1, 'network');
329 * @brief Send POST request to $url
331 * @param string $url URL to post
332 * @param mixed $params array of POST variables
333 * @param string $headers HTTP headers
334 * @param integer $redirects Recursion counter for internal use - default = 0
335 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
337 * @return string The content
339 public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
341 $stamp1 = microtime(true);
343 if (self::isUrlBlocked($url)) {
344 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
349 $ch = curl_init($url);
351 if (($redirects > 8) || (!$ch)) {
355 logger('post_url: start ' . $url, LOGGER_DATA);
357 curl_setopt($ch, CURLOPT_HEADER, true);
358 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
359 curl_setopt($ch, CURLOPT_POST, 1);
360 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
361 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
363 if (Config::get('system', 'ipv4_resolve', false)) {
364 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
367 if (intval($timeout)) {
368 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
370 $curl_time = Config::get('system', 'curl_timeout', 60);
371 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
374 if (defined('LIGHTTPD')) {
375 if (!is_array($headers)) {
376 $headers = ['Expect:'];
378 if (!in_array('Expect:', $headers)) {
379 array_push($headers, 'Expect:');
385 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
388 $check_cert = Config::get('system', 'verifyssl');
389 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
392 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
395 $proxy = Config::get('system', 'proxy');
397 if (strlen($proxy)) {
398 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
399 curl_setopt($ch, CURLOPT_PROXY, $proxy);
400 $proxyuser = Config::get('system', 'proxyuser');
401 if (strlen($proxyuser)) {
402 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
406 self::getCurl()->setCode(0);
408 // don't let curl abort the entire application
409 // if it throws any errors.
411 $s = @curl_exec($ch);
414 $curl_info = curl_getinfo($ch);
415 $http_code = $curl_info['http_code'];
417 logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
421 // Pull out multiple headers, e.g. proxy and continuation headers
422 // allow for HTTP/2.x without fixing code
424 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
425 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
427 $base = substr($base, strlen($chunk));
430 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
432 $new_location_info = @parse_url($curl_info['redirect_url']);
433 $old_location_info = @parse_url($curl_info['url']);
435 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
436 $newurl = trim(array_pop($matches));
438 if (strpos($newurl, '/') === 0) {
439 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
442 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
444 logger('post_url: redirect ' . $url . ' to ' . $newurl);
445 return self::post($newurl, $params, $headers, $redirects, $timeout);
449 self::getCurl()->setCode($http_code);
451 $body = substr($s, strlen($header));
453 self::getCurl()->setHeaders($header);
457 $a->saveTimestamp($stamp1, 'network');
459 logger('post_url: end ' . $url, LOGGER_DATA);
465 * @brief Check URL to see if it's real
467 * Take a URL from the wild, prepend http:// if necessary
468 * and check DNS to see if it's real (or check if is a valid IP address)
470 * @param string $url The URL to be validated
471 * @return string|boolean The actual working URL, false else
473 public static function isUrlValid($url)
475 if (Config::get('system', 'disable_url_validation')) {
479 // no naked subdomains (allow localhost for tests)
480 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
484 if (substr($url, 0, 4) != 'http') {
485 $url = 'http://' . $url;
488 /// @TODO Really suppress function outcomes? Why not find them + debug them?
489 $h = @parse_url($url);
491 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
499 * @brief Checks that email is an actual resolvable internet address
501 * @param string $addr The email address
502 * @return boolean True if it's a valid email address, false if it's not
504 public static function isEmailDomainValid($addr)
506 if (Config::get('system', 'disable_email_validation')) {
510 if (! strpos($addr, '@')) {
514 $h = substr($addr, strpos($addr, '@') + 1);
516 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
517 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
520 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
527 * @brief Check if URL is allowed
529 * Check $url against our list of allowed sites,
530 * wildcards allowed. If allowed_sites is unset return true;
532 * @param string $url URL which get tested
533 * @return boolean True if url is allowed otherwise return false
535 public static function isUrlAllowed($url)
537 $h = @parse_url($url);
543 $str_allowed = Config::get('system', 'allowed_sites');
544 if (! $str_allowed) {
550 $host = strtolower($h['host']);
552 // always allow our own site
553 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
557 $fnmatch = function_exists('fnmatch');
558 $allowed = explode(',', $str_allowed);
560 if (count($allowed)) {
561 foreach ($allowed as $a) {
562 $pat = strtolower(trim($a));
563 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
573 * Checks if the provided url domain is on the domain blocklist.
574 * Returns true if it is or malformed URL, false if not.
576 * @param string $url The url to check the domain from
580 public static function isUrlBlocked($url)
582 $host = @parse_url($url, PHP_URL_HOST);
587 $domain_blocklist = Config::get('system', 'blocklist', []);
588 if (!$domain_blocklist) {
592 foreach ($domain_blocklist as $domain_block) {
593 if (strcasecmp($domain_block['domain'], $host) === 0) {
602 * @brief Check if email address is allowed to register here.
604 * Compare against our list (wildcards allowed).
606 * @param string $email email address
607 * @return boolean False if not allowed, true if allowed
608 * or if allowed list is not configured
610 public static function isEmailDomainAllowed($email)
612 $domain = strtolower(substr($email, strpos($email, '@') + 1));
617 $str_allowed = Config::get('system', 'allowed_email', '');
618 if (!x($str_allowed)) {
622 $allowed = explode(',', $str_allowed);
624 return self::isDomainAllowed($domain, $allowed);
628 * Checks for the existence of a domain in a domain list
630 * @brief Checks for the existence of a domain in a domain list
631 * @param string $domain
632 * @param array $domain_list
635 public static function isDomainAllowed($domain, array $domain_list)
639 foreach ($domain_list as $item) {
640 $pat = strtolower(trim($item));
641 if (fnmatch($pat, $domain) || ($pat == $domain)) {
650 public static function lookupAvatarByEmail($email)
652 $avatar['size'] = 175;
653 $avatar['email'] = $email;
655 $avatar['success'] = false;
657 Addon::callHooks('avatar_lookup', $avatar);
659 if (! $avatar['success']) {
660 $avatar['url'] = System::baseUrl() . '/images/person-175.jpg';
663 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
664 return $avatar['url'];
668 * @brief Remove Google Analytics and other tracking platforms params from URL
670 * @param string $url Any user-submitted URL that may contain tracking params
671 * @return string The same URL stripped of tracking parameters
673 public static function stripTrackingQueryParams($url)
675 $urldata = parse_url($url);
676 if (!empty($urldata["query"])) {
677 $query = $urldata["query"];
678 parse_str($query, $querydata);
680 if (is_array($querydata)) {
681 foreach ($querydata as $param => $value) {
685 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
686 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
687 "fb_action_ids", "fb_action_types", "fb_ref",
689 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
692 $pair = $param . "=" . urlencode($value);
693 $url = str_replace($pair, "", $url);
695 // Second try: if the url isn't encoded completely
696 $pair = $param . "=" . str_replace(" ", "+", $value);
697 $url = str_replace($pair, "", $url);
699 // Third try: Maybey the url isn't encoded at all
700 $pair = $param . "=" . $value;
701 $url = str_replace($pair, "", $url);
703 $url = str_replace(["?&", "&&"], ["?", ""], $url);
708 if (substr($url, -1, 1) == "?") {
709 $url = substr($url, 0, -1);
717 * @brief Returns the original URL of the provided URL
719 * This function strips tracking query params and follows redirections, either
720 * through HTTP code or meta refresh tags. Stops after 10 redirections.
722 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
724 * @see ParseUrl::getSiteinfo
726 * @param string $url A user-submitted URL
727 * @param int $depth The current redirection recursion level (internal)
728 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
729 * @return string A canonical URL
731 public static function finalUrl($url, $depth = 1, $fetchbody = false)
735 $url = self::stripTrackingQueryParams($url);
741 $url = trim($url, "'");
743 $stamp1 = microtime(true);
746 curl_setopt($ch, CURLOPT_URL, $url);
747 curl_setopt($ch, CURLOPT_HEADER, 1);
748 curl_setopt($ch, CURLOPT_NOBODY, 1);
749 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
750 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
751 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
754 $curl_info = @curl_getinfo($ch);
755 $http_code = $curl_info['http_code'];
758 $a->saveTimestamp($stamp1, "network");
760 if ($http_code == 0) {
764 if (in_array($http_code, ['301', '302'])) {
765 if (!empty($curl_info['redirect_url'])) {
766 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
767 } elseif (!empty($curl_info['location'])) {
768 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
772 // Check for redirects in the meta elements of the body if there are no redirects in the header.
774 return(self::finalUrl($url, ++$depth, true));
777 // if the file is too large then exit
778 if ($curl_info["download_content_length"] > 1000000) {
782 // if it isn't a HTML file then exit
783 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
787 $stamp1 = microtime(true);
790 curl_setopt($ch, CURLOPT_URL, $url);
791 curl_setopt($ch, CURLOPT_HEADER, 0);
792 curl_setopt($ch, CURLOPT_NOBODY, 0);
793 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
794 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
795 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
797 $body = curl_exec($ch);
800 $a->saveTimestamp($stamp1, "network");
802 if (trim($body) == "") {
806 // Check for redirect in meta elements
807 $doc = new DOMDocument();
808 @$doc->loadHTML($body);
810 $xpath = new DomXPath($doc);
812 $list = $xpath->query("//meta[@content]");
813 foreach ($list as $node) {
815 if ($node->attributes->length) {
816 foreach ($node->attributes as $attribute) {
817 $attr[$attribute->name] = $attribute->value;
821 if (@$attr["http-equiv"] == 'refresh') {
822 $path = $attr["content"];
823 $pathinfo = explode(";", $path);
824 foreach ($pathinfo as $value) {
825 if (substr(strtolower($value), 0, 4) == "url=") {
826 return self::finalUrl(substr($value, 4), ++$depth);
836 * @brief Find the matching part between two url
838 * @param string $url1
839 * @param string $url2
840 * @return string The matching part
842 public static function getUrlMatch($url1, $url2)
844 if (($url1 == "") || ($url2 == "")) {
848 $url1 = normalise_link($url1);
849 $url2 = normalise_link($url2);
851 $parts1 = parse_url($url1);
852 $parts2 = parse_url($url2);
854 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
858 if (empty($parts1["scheme"])) {
859 $parts1["scheme"] = '';
861 if (empty($parts2["scheme"])) {
862 $parts2["scheme"] = '';
865 if ($parts1["scheme"] != $parts2["scheme"]) {
869 if (empty($parts1["host"])) {
870 $parts1["host"] = '';
872 if (empty($parts2["host"])) {
873 $parts2["host"] = '';
876 if ($parts1["host"] != $parts2["host"]) {
880 if (empty($parts1["port"])) {
881 $parts1["port"] = '';
883 if (empty($parts2["port"])) {
884 $parts2["port"] = '';
887 if ($parts1["port"] != $parts2["port"]) {
891 $match = $parts1["scheme"]."://".$parts1["host"];
893 if ($parts1["port"]) {
894 $match .= ":".$parts1["port"];
897 if (empty($parts1["path"])) {
898 $parts1["path"] = '';
900 if (empty($parts2["path"])) {
901 $parts2["path"] = '';
904 $pathparts1 = explode("/", $parts1["path"]);
905 $pathparts2 = explode("/", $parts2["path"]);
910 $path1 = defaults($pathparts1, $i, '');
911 $path2 = defaults($pathparts2, $i, '');
913 if ($path1 == $path2) {
916 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
920 return normalise_link($match);
924 * @brief Glue url parts together
926 * @param array $parsed URL parts
928 * @return string The glued URL
930 public static function unparseURL($parsed)
932 $get = function ($key) use ($parsed) {
933 return isset($parsed[$key]) ? $parsed[$key] : null;
936 $pass = $get('pass');
937 $user = $get('user');
938 $userinfo = $pass !== null ? "$user:$pass" : $user;
939 $port = $get('port');
940 $scheme = $get('scheme');
941 $query = $get('query');
942 $fragment = $get('fragment');
943 $authority = ($userinfo !== null ? $userinfo."@" : '') .
945 ($port ? ":$port" : '');
947 return (strlen($scheme) ? $scheme.":" : '') .
948 (strlen($authority) ? "//".$authority : '') .
950 (strlen($query) ? "?".$query : '') .
951 (strlen($fragment) ? "#".$fragment : '');