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