]> git.mxchange.org Git - friendica.git/blob - src/Util/Network.php
Profile update and some more is now added
[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          * 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          * @brief Curl wrapper
28          * @param string  $url            URL to fetch
29          * @param boolean $binary         default false
30          *                                TRUE if asked to return binary results (file download)
31          * @param integer $redirects      The recursion counter for internal use - default 0
32          * @param integer $timeout        Timeout in seconds, default system config value or 60 seconds
33          * @param string  $accept_content supply Accept: header with 'accept_content' as the value
34          * @param string  $cookiejar      Path to cookie jar file
35          *
36          * @return string The fetched content
37          */
38         public static function fetchUrl($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = 0)
39         {
40                 $ret = self::fetchUrlFull($url, $binary, $redirects, $timeout, $accept_content, $cookiejar);
41
42                 return $ret['body'];
43         }
44
45         /**
46          * Curl wrapper with array of return values.
47          *
48          * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
49          * all the information collected during the fetch.
50          *
51          * @brief Curl wrapper with array of return values.
52          * @param string  $url            URL to fetch
53          * @param boolean $binary         default false
54          *                                TRUE if asked to return binary results (file download)
55          * @param integer $redirects      The recursion counter for internal use - default 0
56          * @param integer $timeout        Timeout in seconds, default system config value or 60 seconds
57          * @param string  $accept_content supply Accept: header with 'accept_content' as the value
58          * @param string  $cookiejar      Path to cookie jar file
59          *
60          * @return array With all relevant information, 'body' contains the actual fetched content.
61          */
62         public static function fetchUrlFull($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = 0)
63         {
64                 return self::curl(
65                         $url,
66                         $binary,
67                         $redirects,
68                         ['timeout'=>$timeout,
69                         'accept_content'=>$accept_content,
70                         'cookiejar'=>$cookiejar
71                         ]
72                 );
73         }
74
75         /**
76          * @brief fetches an URL.
77          *
78          * @param string  $url       URL to fetch
79          * @param boolean $binary    default false
80          *                           TRUE if asked to return binary results (file download)
81          * @param int     $redirects The recursion counter for internal use - default 0
82          * @param array   $opts      (optional parameters) assoziative array with:
83          *                           'accept_content' => supply Accept: header with 'accept_content' as the value
84          *                           'timeout' => int Timeout in seconds, default system config value or 60 seconds
85          *                           'http_auth' => username:password
86          *                           'novalidate' => do not validate SSL certs, default is to validate using our CA list
87          *                           'nobody' => only return the header
88          *                           'cookiejar' => path to cookie jar file
89          *
90          * @return array an assoziative array with:
91          *    int 'return_code' => HTTP return code or 0 if timeout or failure
92          *    boolean 'success' => boolean true (if HTTP 2xx result) or false
93          *    string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
94          *    string 'header' => HTTP headers
95          *    string 'body' => fetched content
96          */
97         public static function curl($url, $binary = false, &$redirects = 0, $opts = [])
98         {
99                 $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
100
101                 $stamp1 = microtime(true);
102
103                 $a = get_app();
104
105                 $parts = parse_url($url);
106                 $path_parts = explode('/', defaults($parts, 'path', ''));
107                 foreach ($path_parts as $part) {
108                         if (strlen($part) <> mb_strlen($part)) {
109                                 $parts2[] = rawurlencode($part);
110                         } else {
111                                 $parts2[] = $part;
112                         }
113                 }
114                 $parts['path'] =  implode('/', $parts2);
115                 $url = self::unparseURL($parts);
116
117                 if (self::isUrlBlocked($url)) {
118                         logger('domain of ' . $url . ' is blocked', LOGGER_DATA);
119                         return $ret;
120                 }
121
122                 $ch = @curl_init($url);
123
124                 if (($redirects > 8) || (!$ch)) {
125                         return $ret;
126                 }
127
128                 @curl_setopt($ch, CURLOPT_HEADER, true);
129
130                 if (x($opts, "cookiejar")) {
131                         curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
132                         curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
133                 }
134
135                 // These settings aren't needed. We're following the location already.
136                 //      @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
137                 //      @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
138
139                 if (x($opts, 'accept_content')) {
140                         curl_setopt(
141                                 $ch,
142                                 CURLOPT_HTTPHEADER,
143                                 ['Accept: ' . $opts['accept_content']]
144                         );
145                 }
146
147                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
148                 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
149
150                 $range = intval(Config::get('system', 'curl_range_bytes', 0));
151
152                 if ($range > 0) {
153                         @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
154                 }
155
156                 // Without this setting it seems as if some webservers send compressed content
157                 // This seems to confuse curl so that it shows this uncompressed.
158                 /// @todo  We could possibly set this value to "gzip" or something similar
159                 curl_setopt($ch, CURLOPT_ENCODING, '');
160
161                 if (x($opts, 'headers')) {
162                         @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
163                 }
164
165                 if (x($opts, 'nobody')) {
166                         @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
167                 }
168
169                 if (x($opts, 'timeout')) {
170                         @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
171                 } else {
172                         $curl_time = Config::get('system', 'curl_timeout', 60);
173                         @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
174                 }
175
176                 // by default we will allow self-signed certs
177                 // but you can override this
178
179                 $check_cert = Config::get('system', 'verifyssl');
180                 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
181
182                 if ($check_cert) {
183                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
184                 }
185
186                 $proxy = Config::get('system', 'proxy');
187
188                 if (strlen($proxy)) {
189                         @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
190                         @curl_setopt($ch, CURLOPT_PROXY, $proxy);
191                         $proxyuser = @Config::get('system', 'proxyuser');
192
193                         if (strlen($proxyuser)) {
194                                 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
195                         }
196                 }
197
198                 if (Config::get('system', 'ipv4_resolve', false)) {
199                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
200                 }
201
202                 if ($binary) {
203                         @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
204                 }
205
206                 $a->set_curl_code(0);
207
208                 // don't let curl abort the entire application
209                 // if it throws any errors.
210
211                 $s = @curl_exec($ch);
212                 $curl_info = @curl_getinfo($ch);
213
214                 // Special treatment for HTTP Code 416
215                 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
216                 if (($curl_info['http_code'] == 416) && ($range > 0)) {
217                         @curl_setopt($ch, CURLOPT_RANGE, '');
218                         $s = @curl_exec($ch);
219                         $curl_info = @curl_getinfo($ch);
220                 }
221
222                 if (curl_errno($ch) !== CURLE_OK) {
223                         logger('error fetching ' . $url . ': ' . curl_error($ch), LOGGER_INFO);
224                 }
225
226                 $ret['errno'] = curl_errno($ch);
227
228                 $base = $s;
229                 $ret['info'] = $curl_info;
230
231                 $http_code = $curl_info['http_code'];
232
233                 logger($url . ': ' . $http_code . " " . $s, LOGGER_DATA);
234                 $header = '';
235
236                 // Pull out multiple headers, e.g. proxy and continuation headers
237                 // allow for HTTP/2.x without fixing code
238
239                 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
240                         $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
241                         $header .= $chunk;
242                         $base = substr($base, strlen($chunk));
243                 }
244
245                 $a->set_curl_code($http_code);
246                 $a->set_curl_content_type($curl_info['content_type']);
247                 $a->set_curl_headers($header);
248
249                 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
250                         $new_location_info = @parse_url($curl_info['redirect_url']);
251                         $old_location_info = @parse_url($curl_info['url']);
252
253                         $newurl = $curl_info['redirect_url'];
254
255                         if (empty($new_location_info['path']) && !empty($new_location_info['host'])) {
256                                 $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
257                         }
258
259                         $matches = [];
260
261                         if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
262                                 $newurl = trim(array_pop($matches));
263                         }
264                         if (strpos($newurl, '/') === 0) {
265                                 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
266                         }
267                         $old_location_query = @parse_url($url, PHP_URL_QUERY);
268
269                         if ($old_location_query != '') {
270                                 $newurl .= '?' . $old_location_query;
271                         }
272
273                         if (filter_var($newurl, FILTER_VALIDATE_URL)) {
274                                 $redirects++;
275                                 @curl_close($ch);
276                                 return self::curl($newurl, $binary, $redirects, $opts);
277                         }
278                 }
279
280                 $a->set_curl_code($http_code);
281                 $a->set_curl_content_type($curl_info['content_type']);
282
283                 $rc = intval($http_code);
284                 $ret['return_code'] = $rc;
285                 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
286                 $ret['redirect_url'] = $url;
287
288                 if (!$ret['success']) {
289                         $ret['error'] = curl_error($ch);
290                         $ret['debug'] = $curl_info;
291                         logger('error: '.$url.': '.$ret['return_code'].' - '.$ret['error'], LOGGER_DEBUG);
292                         logger('debug: '.print_r($curl_info, true), LOGGER_DATA);
293                 }
294
295                 $ret['body'] = substr($s, strlen($header));
296                 $ret['header'] = $header;
297
298                 if (x($opts, 'debug')) {
299                         $ret['debug'] = $curl_info;
300                 }
301
302                 @curl_close($ch);
303
304                 $a->save_timestamp($stamp1, 'network');
305
306                 return($ret);
307         }
308
309         /**
310          * @brief Send POST request to $url
311          *
312          * @param string  $url       URL to post
313          * @param mixed   $params    array of POST variables
314          * @param string  $headers   HTTP headers
315          * @param integer $redirects Recursion counter for internal use - default = 0
316          * @param integer $timeout   The timeout in seconds, default system config value or 60 seconds
317          *
318          * @return string The content
319          */
320         public static function post($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
321         {
322                 $stamp1 = microtime(true);
323
324                 if (self::isUrlBlocked($url)) {
325                         logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
326                         return false;
327                 }
328
329                 $a = get_app();
330                 $ch = curl_init($url);
331
332                 if (($redirects > 8) || (!$ch)) {
333                         return false;
334                 }
335
336                 logger('post_url: start ' . $url, LOGGER_DATA);
337
338                 curl_setopt($ch, CURLOPT_HEADER, true);
339                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
340                 curl_setopt($ch, CURLOPT_POST, 1);
341                 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
342                 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
343
344                 if (Config::get('system', 'ipv4_resolve', false)) {
345                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
346                 }
347
348                 if (intval($timeout)) {
349                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
350                 } else {
351                         $curl_time = Config::get('system', 'curl_timeout', 60);
352                         curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
353                 }
354
355                 if (defined('LIGHTTPD')) {
356                         if (!is_array($headers)) {
357                                 $headers = ['Expect:'];
358                         } else {
359                                 if (!in_array('Expect:', $headers)) {
360                                         array_push($headers, 'Expect:');
361                                 }
362                         }
363                 }
364
365                 if ($headers) {
366                         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
367                 }
368
369                 $check_cert = Config::get('system', 'verifyssl');
370                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
371
372                 if ($check_cert) {
373                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
374                 }
375
376                 $proxy = Config::get('system', 'proxy');
377
378                 if (strlen($proxy)) {
379                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
380                         curl_setopt($ch, CURLOPT_PROXY, $proxy);
381                         $proxyuser = Config::get('system', 'proxyuser');
382                         if (strlen($proxyuser)) {
383                                 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
384                         }
385                 }
386
387                 $a->set_curl_code(0);
388
389                 // don't let curl abort the entire application
390                 // if it throws any errors.
391
392                 $s = @curl_exec($ch);
393
394                 $base = $s;
395                 $curl_info = curl_getinfo($ch);
396                 $http_code = $curl_info['http_code'];
397
398                 logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
399
400                 $header = '';
401
402                 // Pull out multiple headers, e.g. proxy and continuation headers
403                 // allow for HTTP/2.x without fixing code
404
405                 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
406                         $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
407                         $header .= $chunk;
408                         $base = substr($base, strlen($chunk));
409                 }
410
411                 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
412                         $matches = [];
413                         $new_location_info = @parse_url($curl_info['redirect_url']);
414                         $old_location_info = @parse_url($curl_info['url']);
415
416                         preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
417                         $newurl = trim(array_pop($matches));
418
419                         if (strpos($newurl, '/') === 0) {
420                                 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
421                         }
422
423                         if (filter_var($newurl, FILTER_VALIDATE_URL)) {
424                                 $redirects++;
425                                 logger('post_url: redirect ' . $url . ' to ' . $newurl);
426                                 return self::post($newurl, $params, $headers, $redirects, $timeout);
427                         }
428                 }
429
430                 $a->set_curl_code($http_code);
431
432                 $body = substr($s, strlen($header));
433
434                 $a->set_curl_headers($header);
435
436                 curl_close($ch);
437
438                 $a->save_timestamp($stamp1, 'network');
439
440                 logger('post_url: end ' . $url, LOGGER_DATA);
441
442                 return $body;
443         }
444
445         /**
446          * @brief Check URL to see if it's real
447          *
448          * Take a URL from the wild, prepend http:// if necessary
449          * and check DNS to see if it's real (or check if is a valid IP address)
450          *
451          * @param string $url The URL to be validated
452          * @return string|boolean The actual working URL, false else
453          */
454         public static function isUrlValid($url)
455         {
456                 if (Config::get('system', 'disable_url_validation')) {
457                         return $url;
458                 }
459
460                 // no naked subdomains (allow localhost for tests)
461                 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
462                         return false;
463                 }
464
465                 if (substr($url, 0, 4) != 'http') {
466                         $url = 'http://' . $url;
467                 }
468
469                 /// @TODO Really suppress function outcomes? Why not find them + debug them?
470                 $h = @parse_url($url);
471
472                 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
473                         return $url;
474                 }
475
476                 return false;
477         }
478
479         /**
480          * @brief Checks that email is an actual resolvable internet address
481          *
482          * @param string $addr The email address
483          * @return boolean True if it's a valid email address, false if it's not
484          */
485         public static function isEmailDomainValid($addr)
486         {
487                 if (Config::get('system', 'disable_email_validation')) {
488                         return true;
489                 }
490
491                 if (! strpos($addr, '@')) {
492                         return false;
493                 }
494
495                 $h = substr($addr, strpos($addr, '@') + 1);
496
497                 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
498                 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
499                         return true;
500                 }
501                 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
502                         return true;
503                 }
504                 return false;
505         }
506
507         /**
508          * @brief Check if URL is allowed
509          *
510          * Check $url against our list of allowed sites,
511          * wildcards allowed. If allowed_sites is unset return true;
512          *
513          * @param string $url URL which get tested
514          * @return boolean True if url is allowed otherwise return false
515          */
516         public static function isUrlAllowed($url)
517         {
518                 $h = @parse_url($url);
519
520                 if (! $h) {
521                         return false;
522                 }
523
524                 $str_allowed = Config::get('system', 'allowed_sites');
525                 if (! $str_allowed) {
526                         return true;
527                 }
528
529                 $found = false;
530
531                 $host = strtolower($h['host']);
532
533                 // always allow our own site
534                 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
535                         return true;
536                 }
537
538                 $fnmatch = function_exists('fnmatch');
539                 $allowed = explode(',', $str_allowed);
540
541                 if (count($allowed)) {
542                         foreach ($allowed as $a) {
543                                 $pat = strtolower(trim($a));
544                                 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
545                                         $found = true;
546                                         break;
547                                 }
548                         }
549                 }
550                 return $found;
551         }
552
553         /**
554          * Checks if the provided url domain is on the domain blocklist.
555          * Returns true if it is or malformed URL, false if not.
556          *
557          * @param string $url The url to check the domain from
558          *
559          * @return boolean
560          */
561         public static function isUrlBlocked($url)
562         {
563                 $host = @parse_url($url, PHP_URL_HOST);
564                 if (!$host) {
565                         return false;
566                 }
567
568                 $domain_blocklist = Config::get('system', 'blocklist', []);
569                 if (!$domain_blocklist) {
570                         return false;
571                 }
572
573                 foreach ($domain_blocklist as $domain_block) {
574                         if (strcasecmp($domain_block['domain'], $host) === 0) {
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 (!empty($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 (in_array($http_code, ['301', '302'])) {
746                         if (!empty($curl_info['redirect_url'])) {
747                                 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
748                         } elseif (!empty($curl_info['location'])) {
749                                 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
750                         }
751                 }
752
753                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
754                 if (!$fetchbody) {
755                         return(self::finalUrl($url, ++$depth, true));
756                 }
757
758                 // if the file is too large then exit
759                 if ($curl_info["download_content_length"] > 1000000) {
760                         return $url;
761                 }
762
763                 // if it isn't a HTML file then exit
764                 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
765                         return $url;
766                 }
767
768                 $stamp1 = microtime(true);
769
770                 $ch = curl_init();
771                 curl_setopt($ch, CURLOPT_URL, $url);
772                 curl_setopt($ch, CURLOPT_HEADER, 0);
773                 curl_setopt($ch, CURLOPT_NOBODY, 0);
774                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
775                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
776                 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
777
778                 $body = curl_exec($ch);
779                 curl_close($ch);
780
781                 $a->save_timestamp($stamp1, "network");
782
783                 if (trim($body) == "") {
784                         return $url;
785                 }
786
787                 // Check for redirect in meta elements
788                 $doc = new DOMDocument();
789                 @$doc->loadHTML($body);
790
791                 $xpath = new DomXPath($doc);
792
793                 $list = $xpath->query("//meta[@content]");
794                 foreach ($list as $node) {
795                         $attr = [];
796                         if ($node->attributes->length) {
797                                 foreach ($node->attributes as $attribute) {
798                                         $attr[$attribute->name] = $attribute->value;
799                                 }
800                         }
801
802                         if (@$attr["http-equiv"] == 'refresh') {
803                                 $path = $attr["content"];
804                                 $pathinfo = explode(";", $path);
805                                 foreach ($pathinfo as $value) {
806                                         if (substr(strtolower($value), 0, 4) == "url=") {
807                                                 return self::finalUrl(substr($value, 4), ++$depth);
808                                         }
809                                 }
810                         }
811                 }
812
813                 return $url;
814         }
815
816         /**
817          * @brief Find the matching part between two url
818          *
819          * @param string $url1
820          * @param string $url2
821          * @return string The matching part
822          */
823         public static function getUrlMatch($url1, $url2)
824         {
825                 if (($url1 == "") || ($url2 == "")) {
826                         return "";
827                 }
828
829                 $url1 = normalise_link($url1);
830                 $url2 = normalise_link($url2);
831
832                 $parts1 = parse_url($url1);
833                 $parts2 = parse_url($url2);
834
835                 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
836                         return "";
837                 }
838
839                 if (empty($parts1["scheme"])) {
840                         $parts1["scheme"] = '';
841                 }
842                 if (empty($parts2["scheme"])) {
843                         $parts2["scheme"] = '';
844                 }
845
846                 if ($parts1["scheme"] != $parts2["scheme"]) {
847                         return "";
848                 }
849
850                 if (empty($parts1["host"])) {
851                         $parts1["host"] = '';
852                 }
853                 if (empty($parts2["host"])) {
854                         $parts2["host"] = '';
855                 }
856
857                 if ($parts1["host"] != $parts2["host"]) {
858                         return "";
859                 }
860
861                 if (empty($parts1["port"])) {
862                         $parts1["port"] = '';
863                 }
864                 if (empty($parts2["port"])) {
865                         $parts2["port"] = '';
866                 }
867
868                 if ($parts1["port"] != $parts2["port"]) {
869                         return "";
870                 }
871
872                 $match = $parts1["scheme"]."://".$parts1["host"];
873
874                 if ($parts1["port"]) {
875                         $match .= ":".$parts1["port"];
876                 }
877
878                 if (empty($parts1["path"])) {
879                         $parts1["path"] = '';
880                 }
881                 if (empty($parts2["path"])) {
882                         $parts2["path"] = '';
883                 }
884
885                 $pathparts1 = explode("/", $parts1["path"]);
886                 $pathparts2 = explode("/", $parts2["path"]);
887
888                 $i = 0;
889                 $path = "";
890                 do {
891                         $path1 = defaults($pathparts1, $i, '');
892                         $path2 = defaults($pathparts2, $i, '');
893
894                         if ($path1 == $path2) {
895                                 $path .= $path1."/";
896                         }
897                 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
898
899                 $match .= $path;
900
901                 return normalise_link($match);
902         }
903
904         /**
905          * @brief Glue url parts together
906          *
907          * @param array $parsed URL parts
908          *
909          * @return string The glued URL
910          */
911         public static function unparseURL($parsed)
912         {
913                 $get = function ($key) use ($parsed) {
914                         return isset($parsed[$key]) ? $parsed[$key] : null;
915                 };
916
917                 $pass      = $get('pass');
918                 $user      = $get('user');
919                 $userinfo  = $pass !== null ? "$user:$pass" : $user;
920                 $port      = $get('port');
921                 $scheme    = $get('scheme');
922                 $query     = $get('query');
923                 $fragment  = $get('fragment');
924                 $authority = ($userinfo !== null ? $userinfo."@" : '') .
925                                                 $get('host') .
926                                                 ($port ? ":$port" : '');
927
928                 return  (strlen($scheme) ? $scheme.":" : '') .
929                         (strlen($authority) ? "//".$authority : '') .
930                         $get('path') .
931                         (strlen($query) ? "?".$query : '') .
932                         (strlen($fragment) ? "#".$fragment : '');
933         }
934 }