]> git.mxchange.org Git - friendica.git/blob - src/Util/Network.php
Update function calls
[friendica.git] / src / Util / Network.php
1 <?php
2 /**
3  * @file src/Util/Network.php
4  */
5 namespace Friendica\Util;
6
7 use Friendica\Core\Addon;
8 use Friendica\Core\Logger;
9 use Friendica\Core\System;
10 use Friendica\Core\Config;
11 use Friendica\Network\CurlResult;
12 use DOMDocument;
13 use DomXPath;
14
15 class Network
16 {
17         /**
18          * Curl wrapper
19          *
20          * If binary flag is true, return binary results.
21          * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
22          * to preserve cookies from one request to the next.
23          *
24          * @brief Curl wrapper
25          * @param string  $url            URL to fetch
26          * @param boolean $binary         default false
27          *                                TRUE if asked to return binary results (file download)
28          * @param integer $redirects      The recursion counter for internal use - default 0
29          * @param integer $timeout        Timeout in seconds, default system config value or 60 seconds
30          * @param string  $accept_content supply Accept: header with 'accept_content' as the value
31          * @param string  $cookiejar      Path to cookie jar file
32          *
33          * @return string The fetched content
34          */
35         public static function fetchUrl($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = '')
36         {
37                 $ret = self::fetchUrlFull($url, $binary, $redirects, $timeout, $accept_content, $cookiejar);
38
39                 return $ret->getBody();
40         }
41
42         /**
43          * Curl wrapper with array of return values.
44          *
45          * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
46          * all the information collected during the fetch.
47          *
48          * @brief Curl wrapper with array of return values.
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
56          *
57          * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
58          */
59         public static function fetchUrlFull($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = '')
60         {
61                 return self::curl(
62                         $url,
63                         $binary,
64                         $redirects,
65                         ['timeout'=>$timeout,
66                         'accept_content'=>$accept_content,
67                         'cookiejar'=>$cookiejar
68                         ]
69                 );
70         }
71
72         /**
73          * @brief fetches an URL.
74          *
75          * @param string  $url       URL to fetch
76          * @param boolean $binary    default false
77          *                           TRUE if asked to return binary results (file download)
78          * @param int     $redirects The recursion counter for internal use - default 0
79          * @param array   $opts      (optional parameters) assoziative array with:
80          *                           'accept_content' => supply Accept: header with 'accept_content' as the value
81          *                           'timeout' => int Timeout in seconds, default system config value or 60 seconds
82          *                           'http_auth' => username:password
83          *                           'novalidate' => do not validate SSL certs, default is to validate using our CA list
84          *                           'nobody' => only return the header
85          *                           'cookiejar' => path to cookie jar file
86          *                           'header' => header array
87          *
88          * @return CurlResult
89          */
90         public static function curl($url, $binary = false, &$redirects = 0, $opts = [])
91         {
92                 $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
93
94                 $stamp1 = microtime(true);
95
96                 $a = get_app();
97
98                 $parts = parse_url($url);
99                 $path_parts = explode('/', defaults($parts, 'path', ''));
100                 foreach ($path_parts as $part) {
101                         if (strlen($part) <> mb_strlen($part)) {
102                                 $parts2[] = rawurlencode($part);
103                         } else {
104                                 $parts2[] = $part;
105                         }
106                 }
107                 $parts['path'] = implode('/', $parts2);
108                 $url = self::unparseURL($parts);
109
110                 if (self::isUrlBlocked($url)) {
111                         Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
112                         return CurlResult::createErrorCurl($url);
113                 }
114
115                 $ch = @curl_init($url);
116
117                 if (($redirects > 8) || (!$ch)) {
118                         return CurlResult::createErrorCurl($url);
119                 }
120
121                 @curl_setopt($ch, CURLOPT_HEADER, true);
122
123                 if (x($opts, "cookiejar")) {
124                         curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
125                         curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
126                 }
127
128                 // These settings aren't needed. We're following the location already.
129                 //      @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
130                 //      @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
131
132                 if (x($opts, 'accept_content')) {
133                         curl_setopt(
134                                 $ch,
135                                 CURLOPT_HTTPHEADER,
136                                 ['Accept: ' . $opts['accept_content']]
137                         );
138                 }
139
140                 if (!empty($opts['header'])) {
141                         curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
142                 }
143
144                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
145                 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
146
147                 $range = intval(Config::get('system', 'curl_range_bytes', 0));
148
149                 if ($range > 0) {
150                         @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
151                 }
152
153                 // Without this setting it seems as if some webservers send compressed content
154                 // This seems to confuse curl so that it shows this uncompressed.
155                 /// @todo  We could possibly set this value to "gzip" or something similar
156                 curl_setopt($ch, CURLOPT_ENCODING, '');
157
158                 if (x($opts, 'headers')) {
159                         @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
160                 }
161
162                 if (x($opts, 'nobody')) {
163                         @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
164                 }
165
166                 if (x($opts, 'timeout')) {
167                         @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
168                 } else {
169                         $curl_time = Config::get('system', 'curl_timeout', 60);
170                         @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
171                 }
172
173                 // by default we will allow self-signed certs
174                 // but you can override this
175
176                 $check_cert = Config::get('system', 'verifyssl');
177                 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
178
179                 if ($check_cert) {
180                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
181                 }
182
183                 $proxy = Config::get('system', 'proxy');
184
185                 if (strlen($proxy)) {
186                         @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
187                         @curl_setopt($ch, CURLOPT_PROXY, $proxy);
188                         $proxyuser = @Config::get('system', 'proxyuser');
189
190                         if (strlen($proxyuser)) {
191                                 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
192                         }
193                 }
194
195                 if (Config::get('system', 'ipv4_resolve', false)) {
196                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
197                 }
198
199                 if ($binary) {
200                         @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
201                 }
202
203                 // don't let curl abort the entire application
204                 // if it throws any errors.
205
206                 $s = @curl_exec($ch);
207                 $curl_info = @curl_getinfo($ch);
208
209                 // Special treatment for HTTP Code 416
210                 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
211                 if (($curl_info['http_code'] == 416) && ($range > 0)) {
212                         @curl_setopt($ch, CURLOPT_RANGE, '');
213                         $s = @curl_exec($ch);
214                         $curl_info = @curl_getinfo($ch);
215                 }
216
217                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
218
219                 if ($curlResponse->isRedirectUrl()) {
220                         $redirects++;
221                         Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
222                         @curl_close($ch);
223                         return self::curl($curlResponse->getRedirectUrl(), $binary, $redirects, $opts);
224                 }
225
226                 @curl_close($ch);
227
228                 $a->saveTimestamp($stamp1, 'network');
229
230                 return $curlResponse;
231         }
232
233         /**
234          * @brief Send POST request to $url
235          *
236          * @param string  $url       URL to post
237          * @param mixed   $params    array of POST variables
238          * @param string  $headers   HTTP headers
239          * @param integer $redirects Recursion counter for internal use - default = 0
240          * @param integer $timeout   The timeout in seconds, default system config value or 60 seconds
241          *
242          * @return CurlResult The content
243          */
244         public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
245         {
246                 $stamp1 = microtime(true);
247
248                 if (self::isUrlBlocked($url)) {
249                         Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
250                         return CurlResult::createErrorCurl($url);
251                 }
252
253                 $a = get_app();
254                 $ch = curl_init($url);
255
256                 if (($redirects > 8) || (!$ch)) {
257                         return CurlResult::createErrorCurl($url);
258                 }
259
260                 Logger::log('post_url: start ' . $url, Logger::DATA);
261
262                 curl_setopt($ch, CURLOPT_HEADER, true);
263                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
264                 curl_setopt($ch, CURLOPT_POST, 1);
265                 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
266                 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
267
268                 if (Config::get('system', 'ipv4_resolve', false)) {
269                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
270                 }
271
272                 if (intval($timeout)) {
273                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
274                 } else {
275                         $curl_time = Config::get('system', 'curl_timeout', 60);
276                         curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
277                 }
278
279                 if (defined('LIGHTTPD')) {
280                         if (!is_array($headers)) {
281                                 $headers = ['Expect:'];
282                         } else {
283                                 if (!in_array('Expect:', $headers)) {
284                                         array_push($headers, 'Expect:');
285                                 }
286                         }
287                 }
288
289                 if ($headers) {
290                         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
291                 }
292
293                 $check_cert = Config::get('system', 'verifyssl');
294                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
295
296                 if ($check_cert) {
297                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
298                 }
299
300                 $proxy = Config::get('system', 'proxy');
301
302                 if (strlen($proxy)) {
303                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
304                         curl_setopt($ch, CURLOPT_PROXY, $proxy);
305                         $proxyuser = Config::get('system', 'proxyuser');
306                         if (strlen($proxyuser)) {
307                                 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
308                         }
309                 }
310
311                 // don't let curl abort the entire application
312                 // if it throws any errors.
313
314                 $s = @curl_exec($ch);
315
316                 $base = $s;
317                 $curl_info = curl_getinfo($ch);
318
319                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
320
321                 if ($curlResponse->isRedirectUrl()) {
322                         $redirects++;
323                         Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
324                         curl_close($ch);
325                         return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
326                 }
327
328                 curl_close($ch);
329
330                 $a->saveTimestamp($stamp1, 'network');
331
332                 Logger::log('post_url: end ' . $url, Logger::DATA);
333
334                 return $curlResponse;
335         }
336
337         /**
338          * @brief Check URL to see if it's real
339          *
340          * Take a URL from the wild, prepend http:// if necessary
341          * and check DNS to see if it's real (or check if is a valid IP address)
342          *
343          * @param string $url The URL to be validated
344          * @return string|boolean The actual working URL, false else
345          */
346         public static function isUrlValid($url)
347         {
348                 if (Config::get('system', 'disable_url_validation')) {
349                         return $url;
350                 }
351
352                 // no naked subdomains (allow localhost for tests)
353                 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
354                         return false;
355                 }
356
357                 if (substr($url, 0, 4) != 'http') {
358                         $url = 'http://' . $url;
359                 }
360
361                 /// @TODO Really suppress function outcomes? Why not find them + debug them?
362                 $h = @parse_url($url);
363
364                 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
365                         return $url;
366                 }
367
368                 return false;
369         }
370
371         /**
372          * @brief Checks that email is an actual resolvable internet address
373          *
374          * @param string $addr The email address
375          * @return boolean True if it's a valid email address, false if it's not
376          */
377         public static function isEmailDomainValid($addr)
378         {
379                 if (Config::get('system', 'disable_email_validation')) {
380                         return true;
381                 }
382
383                 if (! strpos($addr, '@')) {
384                         return false;
385                 }
386
387                 $h = substr($addr, strpos($addr, '@') + 1);
388
389                 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
390                 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
391                         return true;
392                 }
393                 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
394                         return true;
395                 }
396                 return false;
397         }
398
399         /**
400          * @brief Check if URL is allowed
401          *
402          * Check $url against our list of allowed sites,
403          * wildcards allowed. If allowed_sites is unset return true;
404          *
405          * @param string $url URL which get tested
406          * @return boolean True if url is allowed otherwise return false
407          */
408         public static function isUrlAllowed($url)
409         {
410                 $h = @parse_url($url);
411
412                 if (! $h) {
413                         return false;
414                 }
415
416                 $str_allowed = Config::get('system', 'allowed_sites');
417                 if (! $str_allowed) {
418                         return true;
419                 }
420
421                 $found = false;
422
423                 $host = strtolower($h['host']);
424
425                 // always allow our own site
426                 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
427                         return true;
428                 }
429
430                 $fnmatch = function_exists('fnmatch');
431                 $allowed = explode(',', $str_allowed);
432
433                 if (count($allowed)) {
434                         foreach ($allowed as $a) {
435                                 $pat = strtolower(trim($a));
436                                 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
437                                         $found = true;
438                                         break;
439                                 }
440                         }
441                 }
442                 return $found;
443         }
444
445         /**
446          * Checks if the provided url domain is on the domain blocklist.
447          * Returns true if it is or malformed URL, false if not.
448          *
449          * @param string $url The url to check the domain from
450          *
451          * @return boolean
452          */
453         public static function isUrlBlocked($url)
454         {
455                 $host = @parse_url($url, PHP_URL_HOST);
456                 if (!$host) {
457                         return false;
458                 }
459
460                 $domain_blocklist = Config::get('system', 'blocklist', []);
461                 if (!$domain_blocklist) {
462                         return false;
463                 }
464
465                 foreach ($domain_blocklist as $domain_block) {
466                         if (strcasecmp($domain_block['domain'], $host) === 0) {
467                                 return true;
468                         }
469                 }
470
471                 return false;
472         }
473
474         /**
475          * @brief Check if email address is allowed to register here.
476          *
477          * Compare against our list (wildcards allowed).
478          *
479          * @param  string $email email address
480          * @return boolean False if not allowed, true if allowed
481          *    or if allowed list is not configured
482          */
483         public static function isEmailDomainAllowed($email)
484         {
485                 $domain = strtolower(substr($email, strpos($email, '@') + 1));
486                 if (!$domain) {
487                         return false;
488                 }
489
490                 $str_allowed = Config::get('system', 'allowed_email', '');
491                 if (!x($str_allowed)) {
492                         return true;
493                 }
494
495                 $allowed = explode(',', $str_allowed);
496
497                 return self::isDomainAllowed($domain, $allowed);
498         }
499
500         /**
501          * Checks for the existence of a domain in a domain list
502          *
503          * @brief Checks for the existence of a domain in a domain list
504          * @param string $domain
505          * @param array  $domain_list
506          * @return boolean
507          */
508         public static function isDomainAllowed($domain, array $domain_list)
509         {
510                 $found = false;
511
512                 foreach ($domain_list as $item) {
513                         $pat = strtolower(trim($item));
514                         if (fnmatch($pat, $domain) || ($pat == $domain)) {
515                                 $found = true;
516                                 break;
517                         }
518                 }
519
520                 return $found;
521         }
522
523         public static function lookupAvatarByEmail($email)
524         {
525                 $avatar['size'] = 300;
526                 $avatar['email'] = $email;
527                 $avatar['url'] = '';
528                 $avatar['success'] = false;
529
530                 Addon::callHooks('avatar_lookup', $avatar);
531
532                 if (! $avatar['success']) {
533                         $avatar['url'] = System::baseUrl() . '/images/person-300.jpg';
534                 }
535
536                 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
537                 return $avatar['url'];
538         }
539
540         /**
541          * @brief Remove Google Analytics and other tracking platforms params from URL
542          *
543          * @param string $url Any user-submitted URL that may contain tracking params
544          * @return string The same URL stripped of tracking parameters
545          */
546         public static function stripTrackingQueryParams($url)
547         {
548                 $urldata = parse_url($url);
549                 if (!empty($urldata["query"])) {
550                         $query = $urldata["query"];
551                         parse_str($query, $querydata);
552
553                         if (is_array($querydata)) {
554                                 foreach ($querydata as $param => $value) {
555                                         if (in_array(
556                                                 $param,
557                                                 [
558                                                         "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
559                                                         "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
560                                                         "fb_action_ids", "fb_action_types", "fb_ref",
561                                                         "awesm", "wtrid",
562                                                         "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
563                                                 )
564                                         ) {
565                                                 $pair = $param . "=" . urlencode($value);
566                                                 $url = str_replace($pair, "", $url);
567
568                                                 // Second try: if the url isn't encoded completely
569                                                 $pair = $param . "=" . str_replace(" ", "+", $value);
570                                                 $url = str_replace($pair, "", $url);
571
572                                                 // Third try: Maybey the url isn't encoded at all
573                                                 $pair = $param . "=" . $value;
574                                                 $url = str_replace($pair, "", $url);
575
576                                                 $url = str_replace(["?&", "&&"], ["?", ""], $url);
577                                         }
578                                 }
579                         }
580
581                         if (substr($url, -1, 1) == "?") {
582                                 $url = substr($url, 0, -1);
583                         }
584                 }
585
586                 return $url;
587         }
588
589         /**
590          * @brief Returns the original URL of the provided URL
591          *
592          * This function strips tracking query params and follows redirections, either
593          * through HTTP code or meta refresh tags. Stops after 10 redirections.
594          *
595          * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
596          *
597          * @see ParseUrl::getSiteinfo
598          *
599          * @param string $url       A user-submitted URL
600          * @param int    $depth     The current redirection recursion level (internal)
601          * @param bool   $fetchbody Wether to fetch the body or not after the HEAD requests
602          * @return string A canonical URL
603          */
604         public static function finalUrl($url, $depth = 1, $fetchbody = false)
605         {
606                 $a = get_app();
607
608                 $url = self::stripTrackingQueryParams($url);
609
610                 if ($depth > 10) {
611                         return $url;
612                 }
613
614                 $url = trim($url, "'");
615
616                 $stamp1 = microtime(true);
617
618                 $ch = curl_init();
619                 curl_setopt($ch, CURLOPT_URL, $url);
620                 curl_setopt($ch, CURLOPT_HEADER, 1);
621                 curl_setopt($ch, CURLOPT_NOBODY, 1);
622                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
623                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
624                 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
625
626                 curl_exec($ch);
627                 $curl_info = @curl_getinfo($ch);
628                 $http_code = $curl_info['http_code'];
629                 curl_close($ch);
630
631                 $a->saveTimestamp($stamp1, "network");
632
633                 if ($http_code == 0) {
634                         return $url;
635                 }
636
637                 if (in_array($http_code, ['301', '302'])) {
638                         if (!empty($curl_info['redirect_url'])) {
639                                 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
640                         } elseif (!empty($curl_info['location'])) {
641                                 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
642                         }
643                 }
644
645                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
646                 if (!$fetchbody) {
647                         return(self::finalUrl($url, ++$depth, true));
648                 }
649
650                 // if the file is too large then exit
651                 if ($curl_info["download_content_length"] > 1000000) {
652                         return $url;
653                 }
654
655                 // if it isn't a HTML file then exit
656                 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
657                         return $url;
658                 }
659
660                 $stamp1 = microtime(true);
661
662                 $ch = curl_init();
663                 curl_setopt($ch, CURLOPT_URL, $url);
664                 curl_setopt($ch, CURLOPT_HEADER, 0);
665                 curl_setopt($ch, CURLOPT_NOBODY, 0);
666                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
667                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
668                 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
669
670                 $body = curl_exec($ch);
671                 curl_close($ch);
672
673                 $a->saveTimestamp($stamp1, "network");
674
675                 if (trim($body) == "") {
676                         return $url;
677                 }
678
679                 // Check for redirect in meta elements
680                 $doc = new DOMDocument();
681                 @$doc->loadHTML($body);
682
683                 $xpath = new DomXPath($doc);
684
685                 $list = $xpath->query("//meta[@content]");
686                 foreach ($list as $node) {
687                         $attr = [];
688                         if ($node->attributes->length) {
689                                 foreach ($node->attributes as $attribute) {
690                                         $attr[$attribute->name] = $attribute->value;
691                                 }
692                         }
693
694                         if (@$attr["http-equiv"] == 'refresh') {
695                                 $path = $attr["content"];
696                                 $pathinfo = explode(";", $path);
697                                 foreach ($pathinfo as $value) {
698                                         if (substr(strtolower($value), 0, 4) == "url=") {
699                                                 return self::finalUrl(substr($value, 4), ++$depth);
700                                         }
701                                 }
702                         }
703                 }
704
705                 return $url;
706         }
707
708         /**
709          * @brief Find the matching part between two url
710          *
711          * @param string $url1
712          * @param string $url2
713          * @return string The matching part
714          */
715         public static function getUrlMatch($url1, $url2)
716         {
717                 if (($url1 == "") || ($url2 == "")) {
718                         return "";
719                 }
720
721                 $url1 = normalise_link($url1);
722                 $url2 = normalise_link($url2);
723
724                 $parts1 = parse_url($url1);
725                 $parts2 = parse_url($url2);
726
727                 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
728                         return "";
729                 }
730
731                 if (empty($parts1["scheme"])) {
732                         $parts1["scheme"] = '';
733                 }
734                 if (empty($parts2["scheme"])) {
735                         $parts2["scheme"] = '';
736                 }
737
738                 if ($parts1["scheme"] != $parts2["scheme"]) {
739                         return "";
740                 }
741
742                 if (empty($parts1["host"])) {
743                         $parts1["host"] = '';
744                 }
745                 if (empty($parts2["host"])) {
746                         $parts2["host"] = '';
747                 }
748
749                 if ($parts1["host"] != $parts2["host"]) {
750                         return "";
751                 }
752
753                 if (empty($parts1["port"])) {
754                         $parts1["port"] = '';
755                 }
756                 if (empty($parts2["port"])) {
757                         $parts2["port"] = '';
758                 }
759
760                 if ($parts1["port"] != $parts2["port"]) {
761                         return "";
762                 }
763
764                 $match = $parts1["scheme"]."://".$parts1["host"];
765
766                 if ($parts1["port"]) {
767                         $match .= ":".$parts1["port"];
768                 }
769
770                 if (empty($parts1["path"])) {
771                         $parts1["path"] = '';
772                 }
773                 if (empty($parts2["path"])) {
774                         $parts2["path"] = '';
775                 }
776
777                 $pathparts1 = explode("/", $parts1["path"]);
778                 $pathparts2 = explode("/", $parts2["path"]);
779
780                 $i = 0;
781                 $path = "";
782                 do {
783                         $path1 = defaults($pathparts1, $i, '');
784                         $path2 = defaults($pathparts2, $i, '');
785
786                         if ($path1 == $path2) {
787                                 $path .= $path1."/";
788                         }
789                 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
790
791                 $match .= $path;
792
793                 return normalise_link($match);
794         }
795
796         /**
797          * @brief Glue url parts together
798          *
799          * @param array $parsed URL parts
800          *
801          * @return string The glued URL
802          */
803         public static function unparseURL($parsed)
804         {
805                 $get = function ($key) use ($parsed) {
806                         return isset($parsed[$key]) ? $parsed[$key] : null;
807                 };
808
809                 $pass      = $get('pass');
810                 $user      = $get('user');
811                 $userinfo  = $pass !== null ? "$user:$pass" : $user;
812                 $port      = $get('port');
813                 $scheme    = $get('scheme');
814                 $query     = $get('query');
815                 $fragment  = $get('fragment');
816                 $authority = ($userinfo !== null ? $userinfo."@" : '') .
817                                                 $get('host') .
818                                                 ($port ? ":$port" : '');
819
820                 return  (strlen($scheme) ? $scheme.":" : '') .
821                         (strlen($authority) ? "//".$authority : '') .
822                         $get('path') .
823                         (strlen($query) ? "?".$query : '') .
824                         (strlen($fragment) ? "#".$fragment : '');
825         }
826 }