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