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