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