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