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