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