]> git.mxchange.org Git - friendica.git/blob - src/Util/Network.php
Move post_url
[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
16 require_once 'library/slinky.php';
17
18 class Network
19 {
20         /**
21          * @brief 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          * @param string  $url            URL to fetch
28          * @param boolean $binary         default false
29          *                                TRUE if asked to return binary results (file download)
30          * @param integer $redirects      The recursion counter for internal use - default 0
31          * @param integer $timeout        Timeout in seconds, default system config value or 60 seconds
32          * @param string  $accept_content supply Accept: header with 'accept_content' as the value
33          * @param string  $cookiejar      Path to cookie jar file
34          *
35          * @return string The fetched content
36          */
37         public static function fetchURL($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = 0)
38         {
39                 $ret = self::zFetchURL(
40                         $url,
41                         $binary,
42                         $redirects,
43                         ['timeout'=>$timeout,
44                         'accept_content'=>$accept_content,
45                         'cookiejar'=>$cookiejar
46                         ]
47                 );
48
49                 return($ret['body']);
50         }
51
52         /**
53          * @brief fetches an URL.
54          *
55          * @param string  $url       URL to fetch
56          * @param boolean $binary    default false
57          *                           TRUE if asked to return binary results (file download)
58          * @param int     $redirects The recursion counter for internal use - default 0
59          * @param array   $opts      (optional parameters) assoziative array with:
60          *                           'accept_content' => supply Accept: header with 'accept_content' as the value
61          *                           'timeout' => int Timeout in seconds, default system config value or 60 seconds
62          *                           'http_auth' => username:password
63          *                           'novalidate' => do not validate SSL certs, default is to validate using our CA list
64          *                           'nobody' => only return the header
65          *                           'cookiejar' => path to cookie jar file
66          *
67          * @return array an assoziative array with:
68          *    int 'return_code' => HTTP return code or 0 if timeout or failure
69          *    boolean 'success' => boolean true (if HTTP 2xx result) or false
70          *    string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
71          *    string 'header' => HTTP headers
72          *    string 'body' => fetched content
73          */
74         public static function zFetchURL($url, $binary = false, &$redirects = 0, $opts = [])
75         {
76                 $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
77
78                 $stamp1 = microtime(true);
79
80                 $a = get_app();
81
82                 if (blocked_url($url)) {
83                         logger('z_fetch_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
84                         return $ret;
85                 }
86
87                 $ch = @curl_init($url);
88
89                 if (($redirects > 8) || (!$ch)) {
90                         return $ret;
91                 }
92
93                 @curl_setopt($ch, CURLOPT_HEADER, true);
94
95                 if (x($opts, "cookiejar")) {
96                         curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
97                         curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
98                 }
99
100                 // These settings aren't needed. We're following the location already.
101                 //      @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
102                 //      @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
103
104                 if (x($opts, 'accept_content')) {
105                         curl_setopt(
106                                 $ch,
107                                 CURLOPT_HTTPHEADER,
108                                 ['Accept: ' . $opts['accept_content']]
109                         );
110                 }
111
112                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
113                 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
114
115                 $range = intval(Config::get('system', 'curl_range_bytes', 0));
116
117                 if ($range > 0) {
118                         @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
119                 }
120
121                 // Without this setting it seems as if some webservers send compressed content
122                 // This seems to confuse curl so that it shows this uncompressed.
123                 /// @todo  We could possibly set this value to "gzip" or something similar
124                 curl_setopt($ch, CURLOPT_ENCODING, '');
125
126                 if (x($opts, 'headers')) {
127                         @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
128                 }
129
130                 if (x($opts, 'nobody')) {
131                         @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
132                 }
133
134                 if (x($opts, 'timeout')) {
135                         @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
136                 } else {
137                         $curl_time = Config::get('system', 'curl_timeout', 60);
138                         @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
139                 }
140
141                 // by default we will allow self-signed certs
142                 // but you can override this
143
144                 $check_cert = Config::get('system', 'verifyssl');
145                 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
146
147                 if ($check_cert) {
148                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
149                 }
150
151                 $proxy = Config::get('system', 'proxy');
152
153                 if (strlen($proxy)) {
154                         @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
155                         @curl_setopt($ch, CURLOPT_PROXY, $proxy);
156                         $proxyuser = @Config::get('system', 'proxyuser');
157
158                         if (strlen($proxyuser)) {
159                                 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
160                         }
161                 }
162
163                 if (Config::get('system', 'ipv4_resolve', false)) {
164                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
165                 }
166
167                 if ($binary) {
168                         @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
169                 }
170
171                 $a->set_curl_code(0);
172
173                 // don't let curl abort the entire application
174                 // if it throws any errors.
175
176                 $s = @curl_exec($ch);
177                 $curl_info = @curl_getinfo($ch);
178
179                 // Special treatment for HTTP Code 416
180                 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
181                 if (($curl_info['http_code'] == 416) && ($range > 0)) {
182                         @curl_setopt($ch, CURLOPT_RANGE, '');
183                         $s = @curl_exec($ch);
184                         $curl_info = @curl_getinfo($ch);
185                 }
186
187                 if (curl_errno($ch) !== CURLE_OK) {
188                         logger('fetch_url error fetching ' . $url . ': ' . curl_error($ch), LOGGER_NORMAL);
189                 }
190
191                 $ret['errno'] = curl_errno($ch);
192
193                 $base = $s;
194                 $ret['info'] = $curl_info;
195
196                 $http_code = $curl_info['http_code'];
197
198                 logger('fetch_url ' . $url . ': ' . $http_code . " " . $s, LOGGER_DATA);
199                 $header = '';
200
201                 // Pull out multiple headers, e.g. proxy and continuation headers
202                 // allow for HTTP/2.x without fixing code
203
204                 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
205                         $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
206                         $header .= $chunk;
207                         $base = substr($base, strlen($chunk));
208                 }
209
210                 $a->set_curl_code($http_code);
211                 $a->set_curl_content_type($curl_info['content_type']);
212                 $a->set_curl_headers($header);
213
214                 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
215                         $new_location_info = @parse_url($curl_info['redirect_url']);
216                         $old_location_info = @parse_url($curl_info['url']);
217
218                         $newurl = $curl_info['redirect_url'];
219
220                         if (($new_location_info['path'] == '') && ( $new_location_info['host'] != '')) {
221                                 $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
222                         }
223
224                         $matches = [];
225
226                         if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
227                                 $newurl = trim(array_pop($matches));
228                         }
229                         if (strpos($newurl, '/') === 0) {
230                                 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
231                         }
232
233                         if (filter_var($newurl, FILTER_VALIDATE_URL)) {
234                                 $redirects++;
235                                 @curl_close($ch);
236                                 return self::zFetchURL($newurl, $binary, $redirects, $opts);
237                         }
238                 }
239
240                 $a->set_curl_code($http_code);
241                 $a->set_curl_content_type($curl_info['content_type']);
242
243                 $rc = intval($http_code);
244                 $ret['return_code'] = $rc;
245                 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
246                 $ret['redirect_url'] = $url;
247
248                 if (!$ret['success']) {
249                         $ret['error'] = curl_error($ch);
250                         $ret['debug'] = $curl_info;
251                         logger('z_fetch_url: error: '.$url.': '.$ret['return_code'].' - '.$ret['error'], LOGGER_DEBUG);
252                         logger('z_fetch_url: debug: '.print_r($curl_info, true), LOGGER_DATA);
253                 }
254
255                 $ret['body'] = substr($s, strlen($header));
256                 $ret['header'] = $header;
257
258                 if (x($opts, 'debug')) {
259                         $ret['debug'] = $curl_info;
260                 }
261
262                 @curl_close($ch);
263
264                 $a->save_timestamp($stamp1, 'network');
265
266                 return($ret);
267         }
268
269         /**
270          * @brief Send POST request to $url
271          *
272          * @param string  $url       URL to post
273          * @param mixed   $params    array of POST variables
274          * @param string  $headers   HTTP headers
275          * @param integer $redirects Recursion counter for internal use - default = 0
276          * @param integer $timeout   The timeout in seconds, default system config value or 60 seconds
277          *
278          * @return string The content
279          */
280         public static function postURL($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
281         {
282                 $stamp1 = microtime(true);
283
284                 if (blocked_url($url)) {
285                         logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
286                         return false;
287                 }
288
289                 $a = get_app();
290                 $ch = curl_init($url);
291
292                 if (($redirects > 8) || (!$ch)) {
293                         return false;
294                 }
295
296                 logger('post_url: start ' . $url, LOGGER_DATA);
297
298                 curl_setopt($ch, CURLOPT_HEADER, true);
299                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
300                 curl_setopt($ch, CURLOPT_POST, 1);
301                 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
302                 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
303
304                 if (Config::get('system', 'ipv4_resolve', false)) {
305                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
306                 }
307
308                 if (intval($timeout)) {
309                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
310                 } else {
311                         $curl_time = Config::get('system', 'curl_timeout', 60);
312                         curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
313                 }
314
315                 if (defined('LIGHTTPD')) {
316                         if (!is_array($headers)) {
317                                 $headers = ['Expect:'];
318                         } else {
319                                 if (!in_array('Expect:', $headers)) {
320                                         array_push($headers, 'Expect:');
321                                 }
322                         }
323                 }
324
325                 if ($headers) {
326                         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
327                 }
328
329                 $check_cert = Config::get('system', 'verifyssl');
330                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
331
332                 if ($check_cert) {
333                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
334                 }
335
336                 $proxy = Config::get('system', 'proxy');
337
338                 if (strlen($proxy)) {
339                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
340                         curl_setopt($ch, CURLOPT_PROXY, $proxy);
341                         $proxyuser = Config::get('system', 'proxyuser');
342                         if (strlen($proxyuser)) {
343                                 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
344                         }
345                 }
346
347                 $a->set_curl_code(0);
348
349                 // don't let curl abort the entire application
350                 // if it throws any errors.
351
352                 $s = @curl_exec($ch);
353
354                 $base = $s;
355                 $curl_info = curl_getinfo($ch);
356                 $http_code = $curl_info['http_code'];
357
358                 logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
359
360                 $header = '';
361
362                 // Pull out multiple headers, e.g. proxy and continuation headers
363                 // allow for HTTP/2.x without fixing code
364
365                 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
366                         $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
367                         $header .= $chunk;
368                         $base = substr($base, strlen($chunk));
369                 }
370
371                 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
372                         $matches = [];
373                         preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
374                         $newurl = trim(array_pop($matches));
375
376                         if (strpos($newurl, '/') === 0) {
377                                 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
378                         }
379
380                         if (filter_var($newurl, FILTER_VALIDATE_URL)) {
381                                 $redirects++;
382                                 logger('post_url: redirect ' . $url . ' to ' . $newurl);
383                                 return self::postURL($newurl, $params, $headers, $redirects, $timeout);
384                         }
385                 }
386
387                 $a->set_curl_code($http_code);
388
389                 $body = substr($s, strlen($header));
390
391                 $a->set_curl_headers($header);
392
393                 curl_close($ch);
394
395                 $a->save_timestamp($stamp1, 'network');
396
397                 logger('post_url: end ' . $url, LOGGER_DATA);
398
399                 return $body;
400         }
401
402         /**
403          * Generic XML return
404          * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
405          * of $st and an optional text <message> of $message and terminates the current process.
406          */
407         public static function xmlStatus($st, $message = '')
408         {
409                 $result = ['status' => $st];
410
411                 if ($message != '') {
412                         $result['message'] = $message;
413                 }
414
415                 if ($st) {
416                         logger('xml_status returning non_zero: ' . $st . " message=" . $message);
417                 }
418
419                 header("Content-type: text/xml");
420
421                 $xmldata = ["result" => $result];
422
423                 echo XML::fromArray($xmldata, $xml);
424
425                 killme();
426         }
427
428         /**
429          * @brief Send HTTP status header and exit.
430          *
431          * @param integer $val         HTTP status result value
432          * @param array   $description optional message
433          *                             'title' => header title
434          *                             'description' => optional message
435          */
436         public static function httpStatusExit($val, $description = [])
437         {
438                 $err = '';
439                 if ($val >= 400) {
440                         $err = 'Error';
441                         if (!isset($description["title"])) {
442                                 $description["title"] = $err." ".$val;
443                         }
444                 }
445
446                 if ($val >= 200 && $val < 300) {
447                         $err = 'OK';
448                 }
449
450                 logger('http_status_exit ' . $val);
451                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
452
453                 if (isset($description["title"])) {
454                         $tpl = get_markup_template('http_status.tpl');
455                         echo replace_macros(
456                                 $tpl,
457                                 [
458                                         '$title' => $description["title"],
459                                         '$description' => $description["description"]]
460                         );
461                 }
462
463                 killme();
464         }
465
466         /**
467          * @brief Check URL to se if ts's real
468          *
469          * Take a URL from the wild, prepend http:// if necessary
470          * and check DNS to see if it's real (or check if is a valid IP address)
471          *
472          * @param string $url The URL to be validated
473          * @return string|boolean The actual working URL, false else
474          */
475         public static function validateURL($url)
476         {
477                 if (Config::get('system', 'disable_url_validation')) {
478                         return $url;
479                 }
480
481                 // no naked subdomains (allow localhost for tests)
482                 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
483                         return false;
484                 }
485
486                 if (substr($url, 0, 4) != 'http') {
487                         $url = 'http://' . $url;
488                 }
489
490                 /// @TODO Really suppress function outcomes? Why not find them + debug them?
491                 $h = @parse_url($url);
492
493                 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
494                         return $url;
495                 }
496
497                 return false;
498         }
499
500         /**
501          * @brief Checks that email is an actual resolvable internet address
502          *
503          * @param string $addr The email address
504          * @return boolean True if it's a valid email address, false if it's not
505          */
506         public static function validateEmail($addr)
507         {
508                 if (Config::get('system', 'disable_email_validation')) {
509                         return true;
510                 }
511
512                 if (! strpos($addr, '@')) {
513                         return false;
514                 }
515
516                 $h = substr($addr, strpos($addr, '@') + 1);
517
518                 if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
519                         return true;
520                 }
521                 return false;
522         }
523
524         /**
525          * @brief Check if URL is allowed
526          *
527          * Check $url against our list of allowed sites,
528          * wildcards allowed. If allowed_sites is unset return true;
529          *
530          * @param string $url URL which get tested
531          * @return boolean True if url is allowed otherwise return false
532          */
533         public static function allowedURL($url)
534         {
535                 $h = @parse_url($url);
536
537                 if (! $h) {
538                         return false;
539                 }
540
541                 $str_allowed = Config::get('system', 'allowed_sites');
542                 if (! $str_allowed) {
543                         return true;
544                 }
545
546                 $found = false;
547
548                 $host = strtolower($h['host']);
549
550                 // always allow our own site
551                 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
552                         return true;
553                 }
554
555                 $fnmatch = function_exists('fnmatch');
556                 $allowed = explode(',', $str_allowed);
557
558                 if (count($allowed)) {
559                         foreach ($allowed as $a) {
560                                 $pat = strtolower(trim($a));
561                                 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
562                                         $found = true;
563                                         break;
564                                 }
565                         }
566                 }
567                 return $found;
568         }
569
570         /**
571          * Checks if the provided url domain is on the domain blocklist.
572          * Returns true if it is or malformed URL, false if not.
573          *
574          * @param string $url The url to check the domain from
575          *
576          * @return boolean
577          */
578         public static function blockedURL($url)
579         {
580                 $h = @parse_url($url);
581
582                 if (! $h) {
583                         return true;
584                 }
585
586                 $domain_blocklist = Config::get('system', 'blocklist', []);
587                 if (! $domain_blocklist) {
588                         return false;
589                 }
590
591                 $host = strtolower($h['host']);
592
593                 foreach ($domain_blocklist as $domain_block) {
594                         if (strtolower($domain_block['domain']) == $host) {
595                                 return true;
596                         }
597                 }
598
599                 return false;
600         }
601
602         /**
603          * @brief Check if email address is allowed to register here.
604          *
605          * Compare against our list (wildcards allowed).
606          *
607          * @param  string $email email address
608          * @return boolean False if not allowed, true if allowed
609          *    or if allowed list is not configured
610          */
611         public static function allowedEmail($email)
612         {
613                 $domain = strtolower(substr($email, strpos($email, '@') + 1));
614                 if (!$domain) {
615                         return false;
616                 }
617
618                 $str_allowed = Config::get('system', 'allowed_email', '');
619                 if (!x($str_allowed)) {
620                         return true;
621                 }
622
623                 $allowed = explode(',', $str_allowed);
624
625                 return allowed_domain($domain, $allowed);
626         }
627
628         /**
629          * Checks for the existence of a domain in a domain list
630          *
631          * @brief Checks for the existence of a domain in a domain list
632          * @param string $domain
633          * @param array  $domain_list
634          * @return boolean
635          */
636         public static function allowedDomain($domain, array $domain_list)
637         {
638                 $found = false;
639
640                 foreach ($domain_list as $item) {
641                         $pat = strtolower(trim($item));
642                         if (fnmatch($pat, $domain) || ($pat == $domain)) {
643                                 $found = true;
644                                 break;
645                         }
646                 }
647
648                 return $found;
649         }
650
651         public static function avatarImg($email)
652         {
653                 $avatar['size'] = 175;
654                 $avatar['email'] = $email;
655                 $avatar['url'] = '';
656                 $avatar['success'] = false;
657
658                 Addon::callHooks('avatar_lookup', $avatar);
659
660                 if (! $avatar['success']) {
661                         $avatar['url'] = System::baseUrl() . '/images/person-175.jpg';
662                 }
663
664                 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
665                 return $avatar['url'];
666         }
667
668         public static function parseXmlString($s, $strict = true)
669         {
670                 // the "strict" parameter is deactivated
671
672                 /// @todo Move this function to the xml class
673                 libxml_use_internal_errors(true);
674
675                 $x = @simplexml_load_string($s);
676                 if (!$x) {
677                         logger('libxml: parse: error: ' . $s, LOGGER_DATA);
678                         foreach (libxml_get_errors() as $err) {
679                                 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
680                         }
681                         libxml_clear_errors();
682                 }
683                 return $x;
684         }
685
686         public static function scaleExternalImages($srctext, $include_link = true, $scale_replace = false)
687         {
688                 // Suppress "view full size"
689                 if (intval(Config::get('system', 'no_view_full_size'))) {
690                         $include_link = false;
691                 }
692
693                 // Picture addresses can contain special characters
694                 $s = htmlspecialchars_decode($srctext);
695
696                 $matches = null;
697                 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER);
698                 if ($c) {
699                         foreach ($matches as $mtch) {
700                                 logger('scale_external_image: ' . $mtch[1]);
701
702                                 $hostname = str_replace('www.', '', substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3));
703                                 if (stristr($mtch[1], $hostname)) {
704                                         continue;
705                                 }
706
707                                 // $scale_replace, if passed, is an array of two elements. The
708                                 // first is the name of the full-size image. The second is the
709                                 // name of a remote, scaled-down version of the full size image.
710                                 // This allows Friendica to display the smaller remote image if
711                                 // one exists, while still linking to the full-size image
712                                 if ($scale_replace) {
713                                         $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
714                                 } else {
715                                         $scaled = $mtch[1];
716                                 }
717                                 $i = self::fetchURL($scaled);
718                                 if (! $i) {
719                                         return $srctext;
720                                 }
721
722                                 // guess mimetype from headers or filename
723                                 $type = Image::guessType($mtch[1], true);
724
725                                 if ($i) {
726                                         $Image = new Image($i, $type);
727                                         if ($Image->isValid()) {
728                                                 $orig_width = $Image->getWidth();
729                                                 $orig_height = $Image->getHeight();
730
731                                                 if ($orig_width > 640 || $orig_height > 640) {
732                                                         $Image->scaleDown(640);
733                                                         $new_width = $Image->getWidth();
734                                                         $new_height = $Image->getHeight();
735                                                         logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
736                                                         $s = str_replace(
737                                                                 $mtch[0],
738                                                                 '[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
739                                                                 . "\n" . (($include_link)
740                                                                         ? '[url=' . $mtch[1] . ']' . L10n::t('view full size') . '[/url]' . "\n"
741                                                                         : ''),
742                                                                 $s
743                                                         );
744                                                         logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
745                                                 }
746                                         }
747                                 }
748                         }
749                 }
750
751                 // replace the special char encoding
752                 $s = htmlspecialchars($s, ENT_NOQUOTES, 'UTF-8');
753                 return $s;
754         }
755
756         public static function fixContactSslPolicy(&$contact, $new_policy)
757         {
758                 $ssl_changed = false;
759                 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
760                         $ssl_changed = true;
761                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
762                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
763                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
764                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
765                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
766                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
767                 }
768
769                 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
770                         $ssl_changed = true;
771                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
772                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
773                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
774                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
775                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
776                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
777                 }
778
779                 if ($ssl_changed) {
780                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
781                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
782                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
783                         dba::update('contact', $fields, ['id' => $contact['id']]);
784                 }
785         }
786
787         /**
788          * @brief Remove Google Analytics and other tracking platforms params from URL
789          *
790          * @param string $url Any user-submitted URL that may contain tracking params
791          * @return string The same URL stripped of tracking parameters
792          */
793         public static function stripTrackingQueryParams($url)
794         {
795                 $urldata = parse_url($url);
796                 if (is_string($urldata["query"])) {
797                         $query = $urldata["query"];
798                         parse_str($query, $querydata);
799
800                         if (is_array($querydata)) {
801                                 foreach ($querydata as $param => $value) {
802                                         if (in_array(
803                                                 $param,
804                                                 [
805                                                         "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
806                                                         "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
807                                                         "fb_action_ids", "fb_action_types", "fb_ref",
808                                                         "awesm", "wtrid",
809                                                         "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
810                                                 )
811                                         ) {
812                                                 $pair = $param . "=" . urlencode($value);
813                                                 $url = str_replace($pair, "", $url);
814
815                                                 // Second try: if the url isn't encoded completely
816                                                 $pair = $param . "=" . str_replace(" ", "+", $value);
817                                                 $url = str_replace($pair, "", $url);
818
819                                                 // Third try: Maybey the url isn't encoded at all
820                                                 $pair = $param . "=" . $value;
821                                                 $url = str_replace($pair, "", $url);
822
823                                                 $url = str_replace(["?&", "&&"], ["?", ""], $url);
824                                         }
825                                 }
826                         }
827
828                         if (substr($url, -1, 1) == "?") {
829                                 $url = substr($url, 0, -1);
830                         }
831                 }
832
833                 return $url;
834         }
835
836         /**
837          * @brief Returns the original URL of the provided URL
838          *
839          * This function strips tracking query params and follows redirections, either
840          * through HTTP code or meta refresh tags. Stops after 10 redirections.
841          *
842          * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
843          *
844          * @see ParseUrl::getSiteinfo
845          *
846          * @param string $url       A user-submitted URL
847          * @param int    $depth     The current redirection recursion level (internal)
848          * @param bool   $fetchbody Wether to fetch the body or not after the HEAD requests
849          * @return string A canonical URL
850          */
851         public static function originalURL($url, $depth = 1, $fetchbody = false)
852         {
853                 $a = get_app();
854
855                 $url = strip_tracking_query_params($url);
856
857                 if ($depth > 10) {
858                         return($url);
859                 }
860
861                 $url = trim($url, "'");
862
863                 $stamp1 = microtime(true);
864
865                 $ch = curl_init();
866                 curl_setopt($ch, CURLOPT_URL, $url);
867                 curl_setopt($ch, CURLOPT_HEADER, 1);
868                 curl_setopt($ch, CURLOPT_NOBODY, 1);
869                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
870                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
871                 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
872
873                 curl_exec($ch);
874                 $curl_info = @curl_getinfo($ch);
875                 $http_code = $curl_info['http_code'];
876                 curl_close($ch);
877
878                 $a->save_timestamp($stamp1, "network");
879
880                 if ($http_code == 0) {
881                         return($url);
882                 }
883
884                 if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302"))
885                         && (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))
886                 ) {
887                         if ($curl_info['redirect_url'] != "") {
888                                 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
889                         } else {
890                                 return(original_url($curl_info['location'], ++$depth, $fetchbody));
891                         }
892                 }
893
894                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
895                 if (!$fetchbody) {
896                         return(original_url($url, ++$depth, true));
897                 }
898
899                 // if the file is too large then exit
900                 if ($curl_info["download_content_length"] > 1000000) {
901                         return($url);
902                 }
903
904                 // if it isn't a HTML file then exit
905                 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
906                         return($url);
907                 }
908
909                 $stamp1 = microtime(true);
910
911                 $ch = curl_init();
912                 curl_setopt($ch, CURLOPT_URL, $url);
913                 curl_setopt($ch, CURLOPT_HEADER, 0);
914                 curl_setopt($ch, CURLOPT_NOBODY, 0);
915                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
916                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
917                 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
918
919                 $body = curl_exec($ch);
920                 curl_close($ch);
921
922                 $a->save_timestamp($stamp1, "network");
923
924                 if (trim($body) == "") {
925                         return($url);
926                 }
927
928                 // Check for redirect in meta elements
929                 $doc = new DOMDocument();
930                 @$doc->loadHTML($body);
931
932                 $xpath = new DomXPath($doc);
933
934                 $list = $xpath->query("//meta[@content]");
935                 foreach ($list as $node) {
936                         $attr = [];
937                         if ($node->attributes->length) {
938                                 foreach ($node->attributes as $attribute) {
939                                         $attr[$attribute->name] = $attribute->value;
940                                 }
941                         }
942
943                         if (@$attr["http-equiv"] == 'refresh') {
944                                 $path = $attr["content"];
945                                 $pathinfo = explode(";", $path);
946                                 foreach ($pathinfo as $value) {
947                                         if (substr(strtolower($value), 0, 4) == "url=") {
948                                                 return(original_url(substr($value, 4), ++$depth));
949                                         }
950                                 }
951                         }
952                 }
953
954                 return $url;
955         }
956
957         public static function shortLink($url)
958         {
959                 $slinky = new Slinky($url);
960                 $yourls_url = Config::get('yourls', 'url1');
961                 if ($yourls_url) {
962                         $yourls_username = Config::get('yourls', 'username1');
963                         $yourls_password = Config::get('yourls', 'password1');
964                         $yourls_ssl = Config::get('yourls', 'ssl1');
965                         $yourls = new Slinky_YourLS();
966                         $yourls->set('username', $yourls_username);
967                         $yourls->set('password', $yourls_password);
968                         $yourls->set('ssl', $yourls_ssl);
969                         $yourls->set('yourls-url', $yourls_url);
970                         $slinky->set_cascade([$yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()]);
971                 } else {
972                         // setup a cascade of shortening services
973                         // try to get a short link from these services
974                         // in the order ur1.ca, tinyurl
975                         $slinky->set_cascade([new Slinky_Ur1ca(), new Slinky_TinyURL()]);
976                 }
977                 return $slinky->short();
978         }
979
980         /**
981          * @brief Encodes content to json
982          *
983          * This function encodes an array to json format
984          * and adds an application/json HTTP header to the output.
985          * After finishing the process is getting killed.
986          *
987          * @param array $x The input content
988          */
989         public static function jsonReturnAndDie($x)
990         {
991                 header("content-type: application/json");
992                 echo json_encode($x);
993                 killme();
994         }
995
996         /**
997          * @brief Find the matching part between two url
998          *
999          * @param string $url1
1000          * @param string $url2
1001          * @return string The matching part
1002          */
1003         public static function matchingURL($url1, $url2)
1004         {
1005                 if (($url1 == "") || ($url2 == "")) {
1006                         return "";
1007                 }
1008
1009                 $url1 = normalise_link($url1);
1010                 $url2 = normalise_link($url2);
1011
1012                 $parts1 = parse_url($url1);
1013                 $parts2 = parse_url($url2);
1014
1015                 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
1016                         return "";
1017                 }
1018
1019                 if ($parts1["scheme"] != $parts2["scheme"]) {
1020                         return "";
1021                 }
1022
1023                 if ($parts1["host"] != $parts2["host"]) {
1024                         return "";
1025                 }
1026
1027                 if ($parts1["port"] != $parts2["port"]) {
1028                         return "";
1029                 }
1030
1031                 $match = $parts1["scheme"]."://".$parts1["host"];
1032
1033                 if ($parts1["port"]) {
1034                         $match .= ":".$parts1["port"];
1035                 }
1036
1037                 $pathparts1 = explode("/", $parts1["path"]);
1038                 $pathparts2 = explode("/", $parts2["path"]);
1039
1040                 $i = 0;
1041                 $path = "";
1042                 do {
1043                         $path1 = $pathparts1[$i];
1044                         $path2 = $pathparts2[$i];
1045
1046                         if ($path1 == $path2) {
1047                                 $path .= $path1."/";
1048                         }
1049                 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
1050
1051                 $match .= $path;
1052
1053                 return normalise_link($match);
1054         }
1055
1056         /**
1057          * @brief Glue url parts together
1058          *
1059          * @param array $parsed URL parts
1060          *
1061          * @return string The glued URL
1062          */
1063         public static function unParseURL($parsed)
1064         {
1065                 $get = function ($key) use ($parsed) {
1066                         return isset($parsed[$key]) ? $parsed[$key] : null;
1067                 };
1068
1069                 $pass      = $get('pass');
1070                 $user      = $get('user');
1071                 $userinfo  = $pass !== null ? "$user:$pass" : $user;
1072                 $port      = $get('port');
1073                 $scheme    = $get('scheme');
1074                 $query     = $get('query');
1075                 $fragment  = $get('fragment');
1076                 $authority = ($userinfo !== null ? $userinfo."@" : '') .
1077                                                 $get('host') .
1078                                                 ($port ? ":$port" : '');
1079
1080                 return  (strlen($scheme) ? $scheme.":" : '') .
1081                         (strlen($authority) ? "//".$authority : '') .
1082                         $get('path') .
1083                         (strlen($query) ? "?".$query : '') .
1084                         (strlen($fragment) ? "#".$fragment : '');
1085         }
1086 }