]> git.mxchange.org Git - friendica.git/blob - src/Util/Network.php
Merge remote-tracking branch 'upstream/develop' into http-417
[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 Logger::info('Blubb', ['code' => $curlResponse->getReturnCode()]);
340                 // Some servers don't like the "Expect" header, so we remove it when needed
341                 if ($curlResponse->getReturnCode() == 417) {
342                         $redirects++;
343
344                         if (empty($headers)) {
345                                 $headers = ['Expect:'];
346                         } else {
347                                 if (!in_array('Expect:', $headers)) {
348                                         array_push($headers, 'Expect:');
349                                 }
350                         }
351                         Logger::info('Server responds with 417, applying workaround', ['url' => $url]);
352                         return self::post($url, $params, $headers, $redirects, $timeout);
353                 }
354
355                 Logger::log('post_url: end ' . $url, Logger::DATA);
356
357                 return $curlResponse;
358         }
359
360         /**
361          * Return raw post data from a post request
362          *
363          * @return string post data
364          */
365         public static function postdata()
366         {
367                 return file_get_contents('php://input');
368         }
369
370         /**
371          * @brief Check URL to see if it's real
372          *
373          * Take a URL from the wild, prepend http:// if necessary
374          * and check DNS to see if it's real (or check if is a valid IP address)
375          *
376          * @param string $url The URL to be validated
377          * @return string|boolean The actual working URL, false else
378          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
379          */
380         public static function isUrlValid(string $url)
381         {
382                 if (Config::get('system', 'disable_url_validation')) {
383                         return $url;
384                 }
385
386                 // no naked subdomains (allow localhost for tests)
387                 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
388                         return false;
389                 }
390
391                 if (substr($url, 0, 4) != 'http') {
392                         $url = 'http://' . $url;
393                 }
394
395                 /// @TODO Really suppress function outcomes? Why not find them + debug them?
396                 $h = @parse_url($url);
397
398                 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP))) {
399                         return $url;
400                 }
401
402                 return false;
403         }
404
405         /**
406          * @brief Checks that email is an actual resolvable internet address
407          *
408          * @param string $addr The email address
409          * @return boolean True if it's a valid email address, false if it's not
410          */
411         public static function isEmailDomainValid(string $addr)
412         {
413                 if (Config::get('system', 'disable_email_validation')) {
414                         return true;
415                 }
416
417                 if (! strpos($addr, '@')) {
418                         return false;
419                 }
420
421                 $h = substr($addr, strpos($addr, '@') + 1);
422
423                 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
424                 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP))) {
425                         return true;
426                 }
427                 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
428                         return true;
429                 }
430                 return false;
431         }
432
433         /**
434          * @brief Check if URL is allowed
435          *
436          * Check $url against our list of allowed sites,
437          * wildcards allowed. If allowed_sites is unset return true;
438          *
439          * @param string $url URL which get tested
440          * @return boolean True if url is allowed otherwise return false
441          */
442         public static function isUrlAllowed(string $url)
443         {
444                 $h = @parse_url($url);
445
446                 if (! $h) {
447                         return false;
448                 }
449
450                 $str_allowed = Config::get('system', 'allowed_sites');
451                 if (! $str_allowed) {
452                         return true;
453                 }
454
455                 $found = false;
456
457                 $host = strtolower($h['host']);
458
459                 // always allow our own site
460                 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
461                         return true;
462                 }
463
464                 $fnmatch = function_exists('fnmatch');
465                 $allowed = explode(',', $str_allowed);
466
467                 if (count($allowed)) {
468                         foreach ($allowed as $a) {
469                                 $pat = strtolower(trim($a));
470                                 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
471                                         $found = true;
472                                         break;
473                                 }
474                         }
475                 }
476                 return $found;
477         }
478
479         /**
480          * Checks if the provided url domain is on the domain blocklist.
481          * Returns true if it is or malformed URL, false if not.
482          *
483          * @param string $url The url to check the domain from
484          *
485          * @return boolean
486          */
487         public static function isUrlBlocked(string $url)
488         {
489                 $host = @parse_url($url, PHP_URL_HOST);
490                 if (!$host) {
491                         return false;
492                 }
493
494                 $domain_blocklist = Config::get('system', 'blocklist', []);
495                 if (!$domain_blocklist) {
496                         return false;
497                 }
498
499                 foreach ($domain_blocklist as $domain_block) {
500                         if (fnmatch(strtolower($domain_block['domain']), strtolower($host))) {
501                                 return true;
502                         }
503                 }
504
505                 return false;
506         }
507
508         /**
509          * @brief Check if email address is allowed to register here.
510          *
511          * Compare against our list (wildcards allowed).
512          *
513          * @param  string $email email address
514          * @return boolean False if not allowed, true if allowed
515          *                       or if allowed list is not configured
516          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
517          */
518         public static function isEmailDomainAllowed(string $email)
519         {
520                 $domain = strtolower(substr($email, strpos($email, '@') + 1));
521                 if (!$domain) {
522                         return false;
523                 }
524
525                 $str_allowed = Config::get('system', 'allowed_email', '');
526                 if (empty($str_allowed)) {
527                         return true;
528                 }
529
530                 $allowed = explode(',', $str_allowed);
531
532                 return self::isDomainAllowed($domain, $allowed);
533         }
534
535         /**
536          * Checks for the existence of a domain in a domain list
537          *
538          * @brief Checks for the existence of a domain in a domain list
539          * @param string $domain
540          * @param array  $domain_list
541          * @return boolean
542          */
543         public static function isDomainAllowed(string $domain, array $domain_list)
544         {
545                 $found = false;
546
547                 foreach ($domain_list as $item) {
548                         $pat = strtolower(trim($item));
549                         if (fnmatch($pat, $domain) || ($pat == $domain)) {
550                                 $found = true;
551                                 break;
552                         }
553                 }
554
555                 return $found;
556         }
557
558         public static function lookupAvatarByEmail(string $email)
559         {
560                 $avatar['size'] = 300;
561                 $avatar['email'] = $email;
562                 $avatar['url'] = '';
563                 $avatar['success'] = false;
564
565                 Hook::callAll('avatar_lookup', $avatar);
566
567                 if (! $avatar['success']) {
568                         $avatar['url'] = System::baseUrl() . '/images/person-300.jpg';
569                 }
570
571                 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
572                 return $avatar['url'];
573         }
574
575         /**
576          * @brief Remove Google Analytics and other tracking platforms params from URL
577          *
578          * @param string $url Any user-submitted URL that may contain tracking params
579          * @return string The same URL stripped of tracking parameters
580          */
581         public static function stripTrackingQueryParams(string $url)
582         {
583                 $urldata = parse_url($url);
584                 if (!empty($urldata["query"])) {
585                         $query = $urldata["query"];
586                         parse_str($query, $querydata);
587
588                         if (is_array($querydata)) {
589                                 foreach ($querydata as $param => $value) {
590                                         if (in_array(
591                                                 $param,
592                                                 [
593                                                         "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
594                                                         "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
595                                                         "fb_action_ids", "fb_action_types", "fb_ref",
596                                                         "awesm", "wtrid",
597                                                         "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
598                                                 )
599                                         ) {
600                                                 $pair = $param . "=" . urlencode($value);
601                                                 $url = str_replace($pair, "", $url);
602
603                                                 // Second try: if the url isn't encoded completely
604                                                 $pair = $param . "=" . str_replace(" ", "+", $value);
605                                                 $url = str_replace($pair, "", $url);
606
607                                                 // Third try: Maybey the url isn't encoded at all
608                                                 $pair = $param . "=" . $value;
609                                                 $url = str_replace($pair, "", $url);
610
611                                                 $url = str_replace(["?&", "&&"], ["?", ""], $url);
612                                         }
613                                 }
614                         }
615
616                         if (substr($url, -1, 1) == "?") {
617                                 $url = substr($url, 0, -1);
618                         }
619                 }
620
621                 return $url;
622         }
623
624         /**
625          * @brief Returns the original URL of the provided URL
626          *
627          * This function strips tracking query params and follows redirections, either
628          * through HTTP code or meta refresh tags. Stops after 10 redirections.
629          *
630          * @todo  Remove the $fetchbody parameter that generates an extraneous HEAD request
631          *
632          * @see   ParseUrl::getSiteinfo
633          *
634          * @param string $url       A user-submitted URL
635          * @param int    $depth     The current redirection recursion level (internal)
636          * @param bool   $fetchbody Wether to fetch the body or not after the HEAD requests
637          * @return string A canonical URL
638          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
639          */
640         public static function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
641         {
642                 $a = \get_app();
643
644                 $url = self::stripTrackingQueryParams($url);
645
646                 if ($depth > 10) {
647                         return $url;
648                 }
649
650                 $url = trim($url, "'");
651
652                 $stamp1 = microtime(true);
653
654                 $ch = curl_init();
655                 curl_setopt($ch, CURLOPT_URL, $url);
656                 curl_setopt($ch, CURLOPT_HEADER, 1);
657                 curl_setopt($ch, CURLOPT_NOBODY, 1);
658                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
659                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
660                 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
661
662                 curl_exec($ch);
663                 $curl_info = @curl_getinfo($ch);
664                 $http_code = $curl_info['http_code'];
665                 curl_close($ch);
666
667                 $a->getProfiler()->saveTimestamp($stamp1, "network", System::callstack());
668
669                 if ($http_code == 0) {
670                         return $url;
671                 }
672
673                 if (in_array($http_code, ['301', '302'])) {
674                         if (!empty($curl_info['redirect_url'])) {
675                                 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
676                         } elseif (!empty($curl_info['location'])) {
677                                 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
678                         }
679                 }
680
681                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
682                 if (!$fetchbody) {
683                         return(self::finalUrl($url, ++$depth, true));
684                 }
685
686                 // if the file is too large then exit
687                 if ($curl_info["download_content_length"] > 1000000) {
688                         return $url;
689                 }
690
691                 // if it isn't a HTML file then exit
692                 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
693                         return $url;
694                 }
695
696                 $stamp1 = microtime(true);
697
698                 $ch = curl_init();
699                 curl_setopt($ch, CURLOPT_URL, $url);
700                 curl_setopt($ch, CURLOPT_HEADER, 0);
701                 curl_setopt($ch, CURLOPT_NOBODY, 0);
702                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
703                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
704                 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
705
706                 $body = curl_exec($ch);
707                 curl_close($ch);
708
709                 $a->getProfiler()->saveTimestamp($stamp1, "network", System::callstack());
710
711                 if (trim($body) == "") {
712                         return $url;
713                 }
714
715                 // Check for redirect in meta elements
716                 $doc = new DOMDocument();
717                 @$doc->loadHTML($body);
718
719                 $xpath = new DomXPath($doc);
720
721                 $list = $xpath->query("//meta[@content]");
722                 foreach ($list as $node) {
723                         $attr = [];
724                         if ($node->attributes->length) {
725                                 foreach ($node->attributes as $attribute) {
726                                         $attr[$attribute->name] = $attribute->value;
727                                 }
728                         }
729
730                         if (@$attr["http-equiv"] == 'refresh') {
731                                 $path = $attr["content"];
732                                 $pathinfo = explode(";", $path);
733                                 foreach ($pathinfo as $value) {
734                                         if (substr(strtolower($value), 0, 4) == "url=") {
735                                                 return self::finalUrl(substr($value, 4), ++$depth);
736                                         }
737                                 }
738                         }
739                 }
740
741                 return $url;
742         }
743
744         /**
745          * @brief Find the matching part between two url
746          *
747          * @param string $url1
748          * @param string $url2
749          * @return string The matching part
750          */
751         public static function getUrlMatch(string $url1, string $url2)
752         {
753                 if (($url1 == "") || ($url2 == "")) {
754                         return "";
755                 }
756
757                 $url1 = Strings::normaliseLink($url1);
758                 $url2 = Strings::normaliseLink($url2);
759
760                 $parts1 = parse_url($url1);
761                 $parts2 = parse_url($url2);
762
763                 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
764                         return "";
765                 }
766
767                 if (empty($parts1["scheme"])) {
768                         $parts1["scheme"] = '';
769                 }
770                 if (empty($parts2["scheme"])) {
771                         $parts2["scheme"] = '';
772                 }
773
774                 if ($parts1["scheme"] != $parts2["scheme"]) {
775                         return "";
776                 }
777
778                 if (empty($parts1["host"])) {
779                         $parts1["host"] = '';
780                 }
781                 if (empty($parts2["host"])) {
782                         $parts2["host"] = '';
783                 }
784
785                 if ($parts1["host"] != $parts2["host"]) {
786                         return "";
787                 }
788
789                 if (empty($parts1["port"])) {
790                         $parts1["port"] = '';
791                 }
792                 if (empty($parts2["port"])) {
793                         $parts2["port"] = '';
794                 }
795
796                 if ($parts1["port"] != $parts2["port"]) {
797                         return "";
798                 }
799
800                 $match = $parts1["scheme"]."://".$parts1["host"];
801
802                 if ($parts1["port"]) {
803                         $match .= ":".$parts1["port"];
804                 }
805
806                 if (empty($parts1["path"])) {
807                         $parts1["path"] = '';
808                 }
809                 if (empty($parts2["path"])) {
810                         $parts2["path"] = '';
811                 }
812
813                 $pathparts1 = explode("/", $parts1["path"]);
814                 $pathparts2 = explode("/", $parts2["path"]);
815
816                 $i = 0;
817                 $path = "";
818                 do {
819                         $path1 = $pathparts1[$i] ?? '';
820                         $path2 = $pathparts2[$i] ?? '';
821
822                         if ($path1 == $path2) {
823                                 $path .= $path1."/";
824                         }
825                 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
826
827                 $match .= $path;
828
829                 return Strings::normaliseLink($match);
830         }
831
832         /**
833          * @brief Glue url parts together
834          *
835          * @param array $parsed URL parts
836          *
837          * @return string The glued URL
838          */
839         public static function unparseURL(array $parsed)
840         {
841                 $get = function ($key) use ($parsed) {
842                         return isset($parsed[$key]) ? $parsed[$key] : null;
843                 };
844
845                 $pass      = $get('pass');
846                 $user      = $get('user');
847                 $userinfo  = $pass !== null ? "$user:$pass" : $user;
848                 $port      = $get('port');
849                 $scheme    = $get('scheme');
850                 $query     = $get('query');
851                 $fragment  = $get('fragment');
852                 $authority = ($userinfo !== null ? $userinfo."@" : '') .
853                                                 $get('host') .
854                                                 ($port ? ":$port" : '');
855
856                 return  (strlen($scheme) ? $scheme.":" : '') .
857                         (strlen($authority) ? "//".$authority : '') .
858                         $get('path') .
859                         (strlen($query) ? "?".$query : '') .
860                         (strlen($fragment) ? "#".$fragment : '');
861         }
862
863
864         /**
865          * Switch the scheme of an url between http and https
866          *
867          * @param string $url URL
868          *
869          * @return string switched URL
870          */
871         public static function switchScheme(string $url)
872         {
873                 $scheme = parse_url($url, PHP_URL_SCHEME);
874                 if (empty($scheme)) {
875                         return $url;
876                 }
877
878                 if ($scheme === 'http') {
879                         $url = str_replace('http://', 'https://', $url);
880                 } elseif ($scheme === 'https') {
881                         $url = str_replace('https://', 'http://', $url);
882                 }
883
884                 return $url;
885         }
886 }