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