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