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