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