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