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