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