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