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