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