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