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