]> git.mxchange.org Git - friendica.git/blob - src/Util/Network.php
c7e7c3c5ea68bf4af44b4acd27b66fc16762b981
[friendica.git] / src / Util / Network.php
1 <?php
2 /**
3  * @file src/Util/Network.php
4  */
5 namespace Friendica\Util;
6
7 use Friendica\Core\Hook;
8 use Friendica\Core\Logger;
9 use Friendica\Core\System;
10 use Friendica\Core\Config;
11 use Friendica\Network\CurlResult;
12 use DOMDocument;
13 use DomXPath;
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 boolean $binary         default false
27          *                                TRUE if asked to return binary results (file download)
28          * @param integer $redirects      The recursion counter for internal use - default 0
29          * @param integer $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          *
33          * @return string The fetched content
34          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
35          */
36         public static function fetchUrl($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = '')
37         {
38                 $ret = self::fetchUrlFull($url, $binary, $redirects, $timeout, $accept_content, $cookiejar);
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 boolean $binary         default false
52          *                                TRUE if asked to return binary results (file download)
53          * @param integer $redirects      The recursion counter for internal use - default 0
54          * @param integer $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          *
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($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = '')
62         {
63                 return self::curl(
64                         $url,
65                         $binary,
66                         $redirects,
67                         ['timeout'=>$timeout,
68                         'accept_content'=>$accept_content,
69                         'cookiejar'=>$cookiejar
70                         ]
71                 );
72         }
73
74         /**
75          * @brief fetches an URL.
76          *
77          * @param string  $url       URL to fetch
78          * @param boolean $binary    default false
79          *                           TRUE if asked to return binary results (file download)
80          * @param int     $redirects The recursion counter for internal use - default 0
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          *
90          * @return CurlResult
91          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
92          */
93         public static function curl($url, $binary = false, &$redirects = 0, $opts = [])
94         {
95                 $stamp1 = microtime(true);
96
97                 $a = \get_app();
98
99                 if (strlen($url) > 1000) {
100                         Logger::log('URL is longer than 1000 characters. Callstack: ' . System::callstack(20), Logger::DEBUG);
101                         return CurlResult::createErrorCurl(substr($url, 0, 200));
102                 }
103
104                 $parts = parse_url($url);
105                 $path_parts = explode('/', defaults($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(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 = 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 = 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 = 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 = @Config::get('system', 'proxyuser');
195
196                         if (strlen($proxyuser)) {
197                                 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
198                         }
199                 }
200
201                 if (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, $redirects, $opts);
230                 }
231
232                 @curl_close($ch);
233
234                 $a->saveTimestamp($stamp1, 'network');
235
236                 return $curlResponse;
237         }
238
239         /**
240          * @brief Send POST request to $url
241          *
242          * @param string  $url       URL to post
243          * @param mixed   $params    array of POST variables
244          * @param string  $headers   HTTP headers
245          * @param integer $redirects Recursion counter for internal use - default = 0
246          * @param integer $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($url, $params, $headers = null, &$redirects = 0, $timeout = 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 = \get_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 (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 = Config::get('system', 'curl_timeout', 60);
283                         curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
284                 }
285
286                 if (defined('LIGHTTPD')) {
287                         if (!is_array($headers)) {
288                                 $headers = ['Expect:'];
289                         } else {
290                                 if (!in_array('Expect:', $headers)) {
291                                         array_push($headers, 'Expect:');
292                                 }
293                         }
294                 }
295
296                 if ($headers) {
297                         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
298                 }
299
300                 $check_cert = Config::get('system', 'verifyssl');
301                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
302
303                 if ($check_cert) {
304                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
305                 }
306
307                 $proxy = Config::get('system', 'proxy');
308
309                 if (strlen($proxy)) {
310                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
311                         curl_setopt($ch, CURLOPT_PROXY, $proxy);
312                         $proxyuser = Config::get('system', 'proxyuser');
313                         if (strlen($proxyuser)) {
314                                 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
315                         }
316                 }
317
318                 // don't let curl abort the entire application
319                 // if it throws any errors.
320
321                 $s = @curl_exec($ch);
322
323                 $curl_info = curl_getinfo($ch);
324
325                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
326
327                 if ($curlResponse->isRedirectUrl()) {
328                         $redirects++;
329                         Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
330                         curl_close($ch);
331                         return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
332                 }
333
334                 curl_close($ch);
335
336                 $a->saveTimestamp($stamp1, 'network');
337
338                 Logger::log('post_url: end ' . $url, Logger::DATA);
339
340                 return $curlResponse;
341         }
342
343         /**
344          * @brief Check URL to see if it's real
345          *
346          * Take a URL from the wild, prepend http:// if necessary
347          * and check DNS to see if it's real (or check if is a valid IP address)
348          *
349          * @param string $url The URL to be validated
350          * @return string|boolean The actual working URL, false else
351          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
352          */
353         public static function isUrlValid($url)
354         {
355                 if (Config::get('system', 'disable_url_validation')) {
356                         return $url;
357                 }
358
359                 // no naked subdomains (allow localhost for tests)
360                 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
361                         return false;
362                 }
363
364                 if (substr($url, 0, 4) != 'http') {
365                         $url = 'http://' . $url;
366                 }
367
368                 /// @TODO Really suppress function outcomes? Why not find them + debug them?
369                 $h = @parse_url($url);
370
371                 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
372                         return $url;
373                 }
374
375                 return false;
376         }
377
378         /**
379          * @brief Checks that email is an actual resolvable internet address
380          *
381          * @param string $addr The email address
382          * @return boolean True if it's a valid email address, false if it's not
383          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
384          */
385         public static function isEmailDomainValid($addr)
386         {
387                 if (Config::get('system', 'disable_email_validation')) {
388                         return true;
389                 }
390
391                 if (! strpos($addr, '@')) {
392                         return false;
393                 }
394
395                 $h = substr($addr, strpos($addr, '@') + 1);
396
397                 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
398                 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
399                         return true;
400                 }
401                 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
402                         return true;
403                 }
404                 return false;
405         }
406
407         /**
408          * @brief Check if URL is allowed
409          *
410          * Check $url against our list of allowed sites,
411          * wildcards allowed. If allowed_sites is unset return true;
412          *
413          * @param string $url URL which get tested
414          * @return boolean True if url is allowed otherwise return false
415          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
416          */
417         public static function isUrlAllowed($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          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
462          */
463         public static function isUrlBlocked($url)
464         {
465                 $host = @parse_url($url, PHP_URL_HOST);
466                 if (!$host) {
467                         return false;
468                 }
469
470                 $domain_blocklist = Config::get('system', 'blocklist', []);
471                 if (!$domain_blocklist) {
472                         return false;
473                 }
474
475                 foreach ($domain_blocklist as $domain_block) {
476                         if (strcasecmp($domain_block['domain'], $host) === 0) {
477                                 return true;
478                         }
479                 }
480
481                 return false;
482         }
483
484         /**
485          * @brief Check if email address is allowed to register here.
486          *
487          * Compare against our list (wildcards allowed).
488          *
489          * @param  string $email email address
490          * @return boolean False if not allowed, true if allowed
491          *                       or if allowed list is not configured
492          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
493          */
494         public static function isEmailDomainAllowed($email)
495         {
496                 $domain = strtolower(substr($email, strpos($email, '@') + 1));
497                 if (!$domain) {
498                         return false;
499                 }
500
501                 $str_allowed = Config::get('system', 'allowed_email', '');
502                 if (empty($str_allowed)) {
503                         return true;
504                 }
505
506                 $allowed = explode(',', $str_allowed);
507
508                 return self::isDomainAllowed($domain, $allowed);
509         }
510
511         /**
512          * Checks for the existence of a domain in a domain list
513          *
514          * @brief Checks for the existence of a domain in a domain list
515          * @param string $domain
516          * @param array  $domain_list
517          * @return boolean
518          */
519         public static function isDomainAllowed($domain, array $domain_list)
520         {
521                 $found = false;
522
523                 foreach ($domain_list as $item) {
524                         $pat = strtolower(trim($item));
525                         if (fnmatch($pat, $domain) || ($pat == $domain)) {
526                                 $found = true;
527                                 break;
528                         }
529                 }
530
531                 return $found;
532         }
533
534         public static function lookupAvatarByEmail($email)
535         {
536                 $avatar['size'] = 300;
537                 $avatar['email'] = $email;
538                 $avatar['url'] = '';
539                 $avatar['success'] = false;
540
541                 Hook::callAll('avatar_lookup', $avatar);
542
543                 if (! $avatar['success']) {
544                         $avatar['url'] = System::baseUrl() . '/images/person-300.jpg';
545                 }
546
547                 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
548                 return $avatar['url'];
549         }
550
551         /**
552          * @brief Remove Google Analytics and other tracking platforms params from URL
553          *
554          * @param string $url Any user-submitted URL that may contain tracking params
555          * @return string The same URL stripped of tracking parameters
556          */
557         public static function stripTrackingQueryParams($url)
558         {
559                 $urldata = parse_url($url);
560                 if (!empty($urldata["query"])) {
561                         $query = $urldata["query"];
562                         parse_str($query, $querydata);
563
564                         if (is_array($querydata)) {
565                                 foreach ($querydata as $param => $value) {
566                                         if (in_array(
567                                                 $param,
568                                                 [
569                                                         "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
570                                                         "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
571                                                         "fb_action_ids", "fb_action_types", "fb_ref",
572                                                         "awesm", "wtrid",
573                                                         "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
574                                                 )
575                                         ) {
576                                                 $pair = $param . "=" . urlencode($value);
577                                                 $url = str_replace($pair, "", $url);
578
579                                                 // Second try: if the url isn't encoded completely
580                                                 $pair = $param . "=" . str_replace(" ", "+", $value);
581                                                 $url = str_replace($pair, "", $url);
582
583                                                 // Third try: Maybey the url isn't encoded at all
584                                                 $pair = $param . "=" . $value;
585                                                 $url = str_replace($pair, "", $url);
586
587                                                 $url = str_replace(["?&", "&&"], ["?", ""], $url);
588                                         }
589                                 }
590                         }
591
592                         if (substr($url, -1, 1) == "?") {
593                                 $url = substr($url, 0, -1);
594                         }
595                 }
596
597                 return $url;
598         }
599
600         /**
601          * @brief Returns the original URL of the provided URL
602          *
603          * This function strips tracking query params and follows redirections, either
604          * through HTTP code or meta refresh tags. Stops after 10 redirections.
605          *
606          * @todo  Remove the $fetchbody parameter that generates an extraneous HEAD request
607          *
608          * @see   ParseUrl::getSiteinfo
609          *
610          * @param string $url       A user-submitted URL
611          * @param int    $depth     The current redirection recursion level (internal)
612          * @param bool   $fetchbody Wether to fetch the body or not after the HEAD requests
613          * @return string A canonical URL
614          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
615          */
616         public static function finalUrl($url, $depth = 1, $fetchbody = false)
617         {
618                 $a = \get_app();
619
620                 $url = self::stripTrackingQueryParams($url);
621
622                 if ($depth > 10) {
623                         return $url;
624                 }
625
626                 $url = trim($url, "'");
627
628                 $stamp1 = microtime(true);
629
630                 $ch = curl_init();
631                 curl_setopt($ch, CURLOPT_URL, $url);
632                 curl_setopt($ch, CURLOPT_HEADER, 1);
633                 curl_setopt($ch, CURLOPT_NOBODY, 1);
634                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
635                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
636                 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
637
638                 curl_exec($ch);
639                 $curl_info = @curl_getinfo($ch);
640                 $http_code = $curl_info['http_code'];
641                 curl_close($ch);
642
643                 $a->saveTimestamp($stamp1, "network");
644
645                 if ($http_code == 0) {
646                         return $url;
647                 }
648
649                 if (in_array($http_code, ['301', '302'])) {
650                         if (!empty($curl_info['redirect_url'])) {
651                                 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
652                         } elseif (!empty($curl_info['location'])) {
653                                 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
654                         }
655                 }
656
657                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
658                 if (!$fetchbody) {
659                         return(self::finalUrl($url, ++$depth, true));
660                 }
661
662                 // if the file is too large then exit
663                 if ($curl_info["download_content_length"] > 1000000) {
664                         return $url;
665                 }
666
667                 // if it isn't a HTML file then exit
668                 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
669                         return $url;
670                 }
671
672                 $stamp1 = microtime(true);
673
674                 $ch = curl_init();
675                 curl_setopt($ch, CURLOPT_URL, $url);
676                 curl_setopt($ch, CURLOPT_HEADER, 0);
677                 curl_setopt($ch, CURLOPT_NOBODY, 0);
678                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
679                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
680                 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
681
682                 $body = curl_exec($ch);
683                 curl_close($ch);
684
685                 $a->saveTimestamp($stamp1, "network");
686
687                 if (trim($body) == "") {
688                         return $url;
689                 }
690
691                 // Check for redirect in meta elements
692                 $doc = new DOMDocument();
693                 @$doc->loadHTML($body);
694
695                 $xpath = new DomXPath($doc);
696
697                 $list = $xpath->query("//meta[@content]");
698                 foreach ($list as $node) {
699                         $attr = [];
700                         if ($node->attributes->length) {
701                                 foreach ($node->attributes as $attribute) {
702                                         $attr[$attribute->name] = $attribute->value;
703                                 }
704                         }
705
706                         if (@$attr["http-equiv"] == 'refresh') {
707                                 $path = $attr["content"];
708                                 $pathinfo = explode(";", $path);
709                                 foreach ($pathinfo as $value) {
710                                         if (substr(strtolower($value), 0, 4) == "url=") {
711                                                 return self::finalUrl(substr($value, 4), ++$depth);
712                                         }
713                                 }
714                         }
715                 }
716
717                 return $url;
718         }
719
720         /**
721          * @brief Find the matching part between two url
722          *
723          * @param string $url1
724          * @param string $url2
725          * @return string The matching part
726          */
727         public static function getUrlMatch($url1, $url2)
728         {
729                 if (($url1 == "") || ($url2 == "")) {
730                         return "";
731                 }
732
733                 $url1 = Strings::normaliseLink($url1);
734                 $url2 = Strings::normaliseLink($url2);
735
736                 $parts1 = parse_url($url1);
737                 $parts2 = parse_url($url2);
738
739                 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
740                         return "";
741                 }
742
743                 if (empty($parts1["scheme"])) {
744                         $parts1["scheme"] = '';
745                 }
746                 if (empty($parts2["scheme"])) {
747                         $parts2["scheme"] = '';
748                 }
749
750                 if ($parts1["scheme"] != $parts2["scheme"]) {
751                         return "";
752                 }
753
754                 if (empty($parts1["host"])) {
755                         $parts1["host"] = '';
756                 }
757                 if (empty($parts2["host"])) {
758                         $parts2["host"] = '';
759                 }
760
761                 if ($parts1["host"] != $parts2["host"]) {
762                         return "";
763                 }
764
765                 if (empty($parts1["port"])) {
766                         $parts1["port"] = '';
767                 }
768                 if (empty($parts2["port"])) {
769                         $parts2["port"] = '';
770                 }
771
772                 if ($parts1["port"] != $parts2["port"]) {
773                         return "";
774                 }
775
776                 $match = $parts1["scheme"]."://".$parts1["host"];
777
778                 if ($parts1["port"]) {
779                         $match .= ":".$parts1["port"];
780                 }
781
782                 if (empty($parts1["path"])) {
783                         $parts1["path"] = '';
784                 }
785                 if (empty($parts2["path"])) {
786                         $parts2["path"] = '';
787                 }
788
789                 $pathparts1 = explode("/", $parts1["path"]);
790                 $pathparts2 = explode("/", $parts2["path"]);
791
792                 $i = 0;
793                 $path = "";
794                 do {
795                         $path1 = defaults($pathparts1, $i, '');
796                         $path2 = defaults($pathparts2, $i, '');
797
798                         if ($path1 == $path2) {
799                                 $path .= $path1."/";
800                         }
801                 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
802
803                 $match .= $path;
804
805                 return Strings::normaliseLink($match);
806         }
807
808         /**
809          * @brief Glue url parts together
810          *
811          * @param array $parsed URL parts
812          *
813          * @return string The glued URL
814          */
815         public static function unparseURL($parsed)
816         {
817                 $get = function ($key) use ($parsed) {
818                         return isset($parsed[$key]) ? $parsed[$key] : null;
819                 };
820
821                 $pass      = $get('pass');
822                 $user      = $get('user');
823                 $userinfo  = $pass !== null ? "$user:$pass" : $user;
824                 $port      = $get('port');
825                 $scheme    = $get('scheme');
826                 $query     = $get('query');
827                 $fragment  = $get('fragment');
828                 $authority = ($userinfo !== null ? $userinfo."@" : '') .
829                                                 $get('host') .
830                                                 ($port ? ":$port" : '');
831
832                 return  (strlen($scheme) ? $scheme.":" : '') .
833                         (strlen($authority) ? "//".$authority : '') .
834                         $get('path') .
835                         (strlen($query) ? "?".$query : '') .
836                         (strlen($fragment) ? "#".$fragment : '');
837         }
838 }