]> git.mxchange.org Git - friendica.git/blob - src/Util/Network.php
Merge pull request #5294 from annando/use-gravity
[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_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
496                         return true;
497                 }
498                 if (($h) && dns_get_record($h, DNS_CNAME + DNS_MX)) {
499                         return true;
500                 }
501                 return false;
502         }
503
504         /**
505          * @brief Check if URL is allowed
506          *
507          * Check $url against our list of allowed sites,
508          * wildcards allowed. If allowed_sites is unset return true;
509          *
510          * @param string $url URL which get tested
511          * @return boolean True if url is allowed otherwise return false
512          */
513         public static function isUrlAllowed($url)
514         {
515                 $h = @parse_url($url);
516
517                 if (! $h) {
518                         return false;
519                 }
520
521                 $str_allowed = Config::get('system', 'allowed_sites');
522                 if (! $str_allowed) {
523                         return true;
524                 }
525
526                 $found = false;
527
528                 $host = strtolower($h['host']);
529
530                 // always allow our own site
531                 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
532                         return true;
533                 }
534
535                 $fnmatch = function_exists('fnmatch');
536                 $allowed = explode(',', $str_allowed);
537
538                 if (count($allowed)) {
539                         foreach ($allowed as $a) {
540                                 $pat = strtolower(trim($a));
541                                 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
542                                         $found = true;
543                                         break;
544                                 }
545                         }
546                 }
547                 return $found;
548         }
549
550         /**
551          * Checks if the provided url domain is on the domain blocklist.
552          * Returns true if it is or malformed URL, false if not.
553          *
554          * @param string $url The url to check the domain from
555          *
556          * @return boolean
557          */
558         public static function isUrlBlocked($url)
559         {
560                 $h = @parse_url($url);
561
562                 if (! $h) {
563                         return true;
564                 }
565
566                 $domain_blocklist = Config::get('system', 'blocklist', []);
567                 if (! $domain_blocklist) {
568                         return false;
569                 }
570
571                 $host = strtolower($h['host']);
572
573                 foreach ($domain_blocklist as $domain_block) {
574                         if (strtolower($domain_block['domain']) == $host) {
575                                 return true;
576                         }
577                 }
578
579                 return false;
580         }
581
582         /**
583          * @brief Check if email address is allowed to register here.
584          *
585          * Compare against our list (wildcards allowed).
586          *
587          * @param  string $email email address
588          * @return boolean False if not allowed, true if allowed
589          *    or if allowed list is not configured
590          */
591         public static function isEmailDomainAllowed($email)
592         {
593                 $domain = strtolower(substr($email, strpos($email, '@') + 1));
594                 if (!$domain) {
595                         return false;
596                 }
597
598                 $str_allowed = Config::get('system', 'allowed_email', '');
599                 if (!x($str_allowed)) {
600                         return true;
601                 }
602
603                 $allowed = explode(',', $str_allowed);
604
605                 return self::isDomainAllowed($domain, $allowed);
606         }
607
608         /**
609          * Checks for the existence of a domain in a domain list
610          *
611          * @brief Checks for the existence of a domain in a domain list
612          * @param string $domain
613          * @param array  $domain_list
614          * @return boolean
615          */
616         public static function isDomainAllowed($domain, array $domain_list)
617         {
618                 $found = false;
619
620                 foreach ($domain_list as $item) {
621                         $pat = strtolower(trim($item));
622                         if (fnmatch($pat, $domain) || ($pat == $domain)) {
623                                 $found = true;
624                                 break;
625                         }
626                 }
627
628                 return $found;
629         }
630
631         public static function lookupAvatarByEmail($email)
632         {
633                 $avatar['size'] = 175;
634                 $avatar['email'] = $email;
635                 $avatar['url'] = '';
636                 $avatar['success'] = false;
637
638                 Addon::callHooks('avatar_lookup', $avatar);
639
640                 if (! $avatar['success']) {
641                         $avatar['url'] = System::baseUrl() . '/images/person-175.jpg';
642                 }
643
644                 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
645                 return $avatar['url'];
646         }
647
648         /**
649          * @brief Remove Google Analytics and other tracking platforms params from URL
650          *
651          * @param string $url Any user-submitted URL that may contain tracking params
652          * @return string The same URL stripped of tracking parameters
653          */
654         public static function stripTrackingQueryParams($url)
655         {
656                 $urldata = parse_url($url);
657                 if (is_string($urldata["query"])) {
658                         $query = $urldata["query"];
659                         parse_str($query, $querydata);
660
661                         if (is_array($querydata)) {
662                                 foreach ($querydata as $param => $value) {
663                                         if (in_array(
664                                                 $param,
665                                                 [
666                                                         "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
667                                                         "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
668                                                         "fb_action_ids", "fb_action_types", "fb_ref",
669                                                         "awesm", "wtrid",
670                                                         "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
671                                                 )
672                                         ) {
673                                                 $pair = $param . "=" . urlencode($value);
674                                                 $url = str_replace($pair, "", $url);
675
676                                                 // Second try: if the url isn't encoded completely
677                                                 $pair = $param . "=" . str_replace(" ", "+", $value);
678                                                 $url = str_replace($pair, "", $url);
679
680                                                 // Third try: Maybey the url isn't encoded at all
681                                                 $pair = $param . "=" . $value;
682                                                 $url = str_replace($pair, "", $url);
683
684                                                 $url = str_replace(["?&", "&&"], ["?", ""], $url);
685                                         }
686                                 }
687                         }
688
689                         if (substr($url, -1, 1) == "?") {
690                                 $url = substr($url, 0, -1);
691                         }
692                 }
693
694                 return $url;
695         }
696
697         /**
698          * @brief Returns the original URL of the provided URL
699          *
700          * This function strips tracking query params and follows redirections, either
701          * through HTTP code or meta refresh tags. Stops after 10 redirections.
702          *
703          * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
704          *
705          * @see ParseUrl::getSiteinfo
706          *
707          * @param string $url       A user-submitted URL
708          * @param int    $depth     The current redirection recursion level (internal)
709          * @param bool   $fetchbody Wether to fetch the body or not after the HEAD requests
710          * @return string A canonical URL
711          */
712         public static function finalUrl($url, $depth = 1, $fetchbody = false)
713         {
714                 $a = get_app();
715
716                 $url = self::stripTrackingQueryParams($url);
717
718                 if ($depth > 10) {
719                         return($url);
720                 }
721
722                 $url = trim($url, "'");
723
724                 $stamp1 = microtime(true);
725
726                 $ch = curl_init();
727                 curl_setopt($ch, CURLOPT_URL, $url);
728                 curl_setopt($ch, CURLOPT_HEADER, 1);
729                 curl_setopt($ch, CURLOPT_NOBODY, 1);
730                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
731                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
732                 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
733
734                 curl_exec($ch);
735                 $curl_info = @curl_getinfo($ch);
736                 $http_code = $curl_info['http_code'];
737                 curl_close($ch);
738
739                 $a->save_timestamp($stamp1, "network");
740
741                 if ($http_code == 0) {
742                         return($url);
743                 }
744
745                 if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302"))
746                         && (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))
747                 ) {
748                         if ($curl_info['redirect_url'] != "") {
749                                 return(self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody));
750                         } else {
751                                 return(self::finalUrl($curl_info['location'], ++$depth, $fetchbody));
752                         }
753                 }
754
755                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
756                 if (!$fetchbody) {
757                         return(self::finalUrl($url, ++$depth, true));
758                 }
759
760                 // if the file is too large then exit
761                 if ($curl_info["download_content_length"] > 1000000) {
762                         return($url);
763                 }
764
765                 // if it isn't a HTML file then exit
766                 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
767                         return($url);
768                 }
769
770                 $stamp1 = microtime(true);
771
772                 $ch = curl_init();
773                 curl_setopt($ch, CURLOPT_URL, $url);
774                 curl_setopt($ch, CURLOPT_HEADER, 0);
775                 curl_setopt($ch, CURLOPT_NOBODY, 0);
776                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
777                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
778                 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
779
780                 $body = curl_exec($ch);
781                 curl_close($ch);
782
783                 $a->save_timestamp($stamp1, "network");
784
785                 if (trim($body) == "") {
786                         return($url);
787                 }
788
789                 // Check for redirect in meta elements
790                 $doc = new DOMDocument();
791                 @$doc->loadHTML($body);
792
793                 $xpath = new DomXPath($doc);
794
795                 $list = $xpath->query("//meta[@content]");
796                 foreach ($list as $node) {
797                         $attr = [];
798                         if ($node->attributes->length) {
799                                 foreach ($node->attributes as $attribute) {
800                                         $attr[$attribute->name] = $attribute->value;
801                                 }
802                         }
803
804                         if (@$attr["http-equiv"] == 'refresh') {
805                                 $path = $attr["content"];
806                                 $pathinfo = explode(";", $path);
807                                 foreach ($pathinfo as $value) {
808                                         if (substr(strtolower($value), 0, 4) == "url=") {
809                                                 return(self::finalUrl(substr($value, 4), ++$depth));
810                                         }
811                                 }
812                         }
813                 }
814
815                 return $url;
816         }
817
818         /**
819          * @brief Find the matching part between two url
820          *
821          * @param string $url1
822          * @param string $url2
823          * @return string The matching part
824          */
825         public static function getUrlMatch($url1, $url2)
826         {
827                 if (($url1 == "") || ($url2 == "")) {
828                         return "";
829                 }
830
831                 $url1 = normalise_link($url1);
832                 $url2 = normalise_link($url2);
833
834                 $parts1 = parse_url($url1);
835                 $parts2 = parse_url($url2);
836
837                 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
838                         return "";
839                 }
840
841                 if ($parts1["scheme"] != $parts2["scheme"]) {
842                         return "";
843                 }
844
845                 if ($parts1["host"] != $parts2["host"]) {
846                         return "";
847                 }
848
849                 if ($parts1["port"] != $parts2["port"]) {
850                         return "";
851                 }
852
853                 $match = $parts1["scheme"]."://".$parts1["host"];
854
855                 if ($parts1["port"]) {
856                         $match .= ":".$parts1["port"];
857                 }
858
859                 $pathparts1 = explode("/", $parts1["path"]);
860                 $pathparts2 = explode("/", $parts2["path"]);
861
862                 $i = 0;
863                 $path = "";
864                 do {
865                         $path1 = $pathparts1[$i];
866                         $path2 = $pathparts2[$i];
867
868                         if ($path1 == $path2) {
869                                 $path .= $path1."/";
870                         }
871                 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
872
873                 $match .= $path;
874
875                 return normalise_link($match);
876         }
877
878         /**
879          * @brief Glue url parts together
880          *
881          * @param array $parsed URL parts
882          *
883          * @return string The glued URL
884          */
885         public static function unparseURL($parsed)
886         {
887                 $get = function ($key) use ($parsed) {
888                         return isset($parsed[$key]) ? $parsed[$key] : null;
889                 };
890
891                 $pass      = $get('pass');
892                 $user      = $get('user');
893                 $userinfo  = $pass !== null ? "$user:$pass" : $user;
894                 $port      = $get('port');
895                 $scheme    = $get('scheme');
896                 $query     = $get('query');
897                 $fragment  = $get('fragment');
898                 $authority = ($userinfo !== null ? $userinfo."@" : '') .
899                                                 $get('host') .
900                                                 ($port ? ":$port" : '');
901
902                 return  (strlen($scheme) ? $scheme.":" : '') .
903                         (strlen($authority) ? "//".$authority : '') .
904                         $get('path') .
905                         (strlen($query) ? "?".$query : '') .
906                         (strlen($fragment) ? "#".$fragment : '');
907         }
908 }