]> git.mxchange.org Git - friendica.git/blob - include/network.php
The url detection in BBCode is too greedy
[friendica.git] / include / network.php
1 <?php
2 /**
3  * @file include/network.php
4  */
5 use Friendica\App;
6 use Friendica\Core\Addon;
7 use Friendica\Core\System;
8 use Friendica\Core\Config;
9 use Friendica\Network\Probe;
10 use Friendica\Object\Image;
11 use Friendica\Util\XML;
12
13 /**
14  * @brief Curl wrapper
15  *
16  * If binary flag is true, return binary results.
17  * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
18  * to preserve cookies from one request to the next.
19  *
20  * @param string  $url            URL to fetch
21  * @param boolean $binary         default false
22  *                                TRUE if asked to return binary results (file download)
23  * @param integer $redirects      The recursion counter for internal use - default 0
24  * @param integer $timeout        Timeout in seconds, default system config value or 60 seconds
25  * @param string  $accept_content supply Accept: header with 'accept_content' as the value
26  * @param string  $cookiejar      Path to cookie jar file
27  *
28  * @return string The fetched content
29  */
30 function fetch_url($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = 0)
31 {
32         $ret = z_fetch_url(
33                 $url,
34                 $binary,
35                 $redirects,
36                 ['timeout'=>$timeout,
37                 'accept_content'=>$accept_content,
38                 'cookiejar'=>$cookiejar
39                 ]
40         );
41
42         return($ret['body']);
43 }
44
45 /**
46  * @brief fetches an URL.
47  *
48  * @param string  $url       URL to fetch
49  * @param boolean $binary    default false
50  *                           TRUE if asked to return binary results (file download)
51  * @param int     $redirects The recursion counter for internal use - default 0
52  * @param array   $opts      (optional parameters) assoziative array with:
53  *                           'accept_content' => supply Accept: header with 'accept_content' as the value
54  *                           'timeout' => int Timeout in seconds, default system config value or 60 seconds
55  *                           'http_auth' => username:password
56  *                           'novalidate' => do not validate SSL certs, default is to validate using our CA list
57  *                           'nobody' => only return the header
58  *                           'cookiejar' => path to cookie jar file
59  *
60  * @return array an assoziative array with:
61  *    int 'return_code' => HTTP return code or 0 if timeout or failure
62  *    boolean 'success' => boolean true (if HTTP 2xx result) or false
63  *    string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
64  *    string 'header' => HTTP headers
65  *    string 'body' => fetched content
66  */
67 function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = [])
68 {
69         $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
70
71         $stamp1 = microtime(true);
72
73         $a = get_app();
74
75         if (blocked_url($url)) {
76                 logger('z_fetch_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
77                 return $ret;
78         }
79
80         $ch = @curl_init($url);
81
82         if (($redirects > 8) || (!$ch)) {
83                 return $ret;
84         }
85
86         @curl_setopt($ch, CURLOPT_HEADER, true);
87
88         if (x($opts, "cookiejar")) {
89                 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
90                 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
91         }
92
93         // These settings aren't needed. We're following the location already.
94         //      @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
95         //      @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
96
97         if (x($opts, 'accept_content')) {
98                 curl_setopt(
99                         $ch,
100                         CURLOPT_HTTPHEADER,
101                         ['Accept: ' . $opts['accept_content']]
102                 );
103         }
104
105         @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
106         @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
107
108         $range = intval(Config::get('system', 'curl_range_bytes', 0));
109
110         if ($range > 0) {
111                 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
112         }
113
114         // Without this setting it seems as if some webservers send compressed content
115         // This seems to confuse curl so that it shows this uncompressed.
116         /// @todo  We could possibly set this value to "gzip" or something similar
117         curl_setopt($ch, CURLOPT_ENCODING, '');
118
119         if (x($opts, 'headers')) {
120                 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
121         }
122
123         if (x($opts, 'nobody')) {
124                 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
125         }
126
127         if (x($opts, 'timeout')) {
128                 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
129         } else {
130                 $curl_time = Config::get('system', 'curl_timeout', 60);
131                 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
132         }
133
134         // by default we will allow self-signed certs
135         // but you can override this
136
137         $check_cert = Config::get('system', 'verifyssl');
138         @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
139
140         if ($check_cert) {
141                 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
142         }
143
144         $proxy = Config::get('system', 'proxy');
145
146         if (strlen($proxy)) {
147                 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
148                 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
149                 $proxyuser = @Config::get('system', 'proxyuser');
150
151                 if (strlen($proxyuser)) {
152                         @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
153                 }
154         }
155
156         if (Config::get('system', 'ipv4_resolve', false)) {
157                 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
158         }
159
160         if ($binary) {
161                 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
162         }
163
164         $a->set_curl_code(0);
165
166         // don't let curl abort the entire application
167         // if it throws any errors.
168
169         $s = @curl_exec($ch);
170         $curl_info = @curl_getinfo($ch);
171
172         // Special treatment for HTTP Code 416
173         // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
174         if (($curl_info['http_code'] == 416) && ($range > 0)) {
175                 @curl_setopt($ch, CURLOPT_RANGE, '');
176                 $s = @curl_exec($ch);
177                 $curl_info = @curl_getinfo($ch);
178         }
179
180         if (curl_errno($ch) !== CURLE_OK) {
181                 logger('fetch_url error fetching ' . $url . ': ' . curl_error($ch), LOGGER_NORMAL);
182         }
183
184         $ret['errno'] = curl_errno($ch);
185
186         $base = $s;
187         $ret['info'] = $curl_info;
188
189         $http_code = $curl_info['http_code'];
190
191         logger('fetch_url ' . $url . ': ' . $http_code . " " . $s, LOGGER_DATA);
192         $header = '';
193
194         // Pull out multiple headers, e.g. proxy and continuation headers
195         // allow for HTTP/2.x without fixing code
196
197         while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
198                 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
199                 $header .= $chunk;
200                 $base = substr($base, strlen($chunk));
201         }
202
203         $a->set_curl_code($http_code);
204         $a->set_curl_content_type($curl_info['content_type']);
205         $a->set_curl_headers($header);
206
207         if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
208                 $new_location_info = @parse_url($curl_info['redirect_url']);
209                 $old_location_info = @parse_url($curl_info['url']);
210
211                 $newurl = $curl_info['redirect_url'];
212
213                 if (($new_location_info['path'] == '') && ( $new_location_info['host'] != '')) {
214                         $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
215                 }
216
217                 $matches = [];
218
219                 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
220                         $newurl = trim(array_pop($matches));
221                 }
222                 if (strpos($newurl, '/') === 0) {
223                         $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
224                 }
225
226                 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
227                         $redirects++;
228                         @curl_close($ch);
229                         return z_fetch_url($newurl, $binary, $redirects, $opts);
230                 }
231         }
232
233         $a->set_curl_code($http_code);
234         $a->set_curl_content_type($curl_info['content_type']);
235
236         $rc = intval($http_code);
237         $ret['return_code'] = $rc;
238         $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
239         $ret['redirect_url'] = $url;
240
241         if (!$ret['success']) {
242                 $ret['error'] = curl_error($ch);
243                 $ret['debug'] = $curl_info;
244                 logger('z_fetch_url: error: '.$url.': '.$ret['return_code'].' - '.$ret['error'], LOGGER_DEBUG);
245                 logger('z_fetch_url: debug: '.print_r($curl_info, true), LOGGER_DATA);
246         }
247
248         $ret['body'] = substr($s, strlen($header));
249         $ret['header'] = $header;
250
251         if (x($opts, 'debug')) {
252                 $ret['debug'] = $curl_info;
253         }
254
255         @curl_close($ch);
256
257         $a->save_timestamp($stamp1, 'network');
258
259         return($ret);
260 }
261
262 /**
263  * @brief Send POST request to $url
264  *
265  * @param string  $url       URL to post
266  * @param mixed   $params    array of POST variables
267  * @param string  $headers   HTTP headers
268  * @param integer $redirects Recursion counter for internal use - default = 0
269  * @param integer $timeout   The timeout in seconds, default system config value or 60 seconds
270  *
271  * @return string The content
272  */
273 function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
274 {
275         $stamp1 = microtime(true);
276
277         if (blocked_url($url)) {
278                 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
279                 return false;
280         }
281
282         $a = get_app();
283         $ch = curl_init($url);
284
285         if (($redirects > 8) || (!$ch)) {
286                 return false;
287         }
288
289         logger('post_url: start ' . $url, LOGGER_DATA);
290
291         curl_setopt($ch, CURLOPT_HEADER, true);
292         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
293         curl_setopt($ch, CURLOPT_POST, 1);
294         curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
295         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
296
297         if (Config::get('system', 'ipv4_resolve', false)) {
298                 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
299         }
300
301         if (intval($timeout)) {
302                 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
303         } else {
304                 $curl_time = Config::get('system', 'curl_timeout', 60);
305                 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
306         }
307
308         if (defined('LIGHTTPD')) {
309                 if (!is_array($headers)) {
310                         $headers = ['Expect:'];
311                 } else {
312                         if (!in_array('Expect:', $headers)) {
313                                 array_push($headers, 'Expect:');
314                         }
315                 }
316         }
317
318         if ($headers) {
319                 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
320         }
321
322         $check_cert = Config::get('system', 'verifyssl');
323         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
324
325         if ($check_cert) {
326                 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
327         }
328
329         $proxy = Config::get('system', 'proxy');
330
331         if (strlen($proxy)) {
332                 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
333                 curl_setopt($ch, CURLOPT_PROXY, $proxy);
334                 $proxyuser = Config::get('system', 'proxyuser');
335                 if (strlen($proxyuser)) {
336                         curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
337                 }
338         }
339
340         $a->set_curl_code(0);
341
342         // don't let curl abort the entire application
343         // if it throws any errors.
344
345         $s = @curl_exec($ch);
346
347         $base = $s;
348         $curl_info = curl_getinfo($ch);
349         $http_code = $curl_info['http_code'];
350
351         logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
352
353         $header = '';
354
355         // Pull out multiple headers, e.g. proxy and continuation headers
356         // allow for HTTP/2.x without fixing code
357
358         while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
359                 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
360                 $header .= $chunk;
361                 $base = substr($base, strlen($chunk));
362         }
363
364         if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
365                 $matches = [];
366                 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
367                 $newurl = trim(array_pop($matches));
368
369                 if (strpos($newurl, '/') === 0) {
370                         $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
371                 }
372
373                 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
374                         $redirects++;
375                         logger('post_url: redirect ' . $url . ' to ' . $newurl);
376                         return post_url($newurl, $params, $headers, $redirects, $timeout);
377                 }
378         }
379
380         $a->set_curl_code($http_code);
381
382         $body = substr($s, strlen($header));
383
384         $a->set_curl_headers($header);
385
386         curl_close($ch);
387
388         $a->save_timestamp($stamp1, 'network');
389
390         logger('post_url: end ' . $url, LOGGER_DATA);
391
392         return $body;
393 }
394
395 // Generic XML return
396 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
397 // of $st and an optional text <message> of $message and terminates the current process.
398
399 function xml_status($st, $message = '')
400 {
401         $result = ['status' => $st];
402
403         if ($message != '') {
404                 $result['message'] = $message;
405         }
406
407         if ($st) {
408                 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
409         }
410
411         header("Content-type: text/xml");
412
413         $xmldata = ["result" => $result];
414
415         echo XML::fromArray($xmldata, $xml);
416
417         killme();
418 }
419
420 /**
421  * @brief Send HTTP status header and exit.
422  *
423  * @param integer $val HTTP status result value
424  * @param array $description optional message
425  *    'title' => header title
426  *    'description' => optional message
427  */
428
429 /**
430  * @brief Send HTTP status header and exit.
431  *
432  * @param integer $val         HTTP status result value
433  * @param array   $description optional message
434  *                             'title' => header title
435  *                             'description' => optional message
436  */
437 function http_status_exit($val, $description = [])
438 {
439         $err = '';
440         if ($val >= 400) {
441                 $err = 'Error';
442                 if (!isset($description["title"])) {
443                         $description["title"] = $err." ".$val;
444                 }
445         }
446         if ($val >= 200 && $val < 300)
447                 $err = 'OK';
448
449         logger('http_status_exit ' . $val);
450         header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
451
452         if (isset($description["title"])) {
453                 $tpl = get_markup_template('http_status.tpl');
454                 echo replace_macros(
455                         $tpl,
456                         [
457                                 '$title' => $description["title"],
458                                 '$description' => $description["description"]]
459                 );
460         }
461
462         killme();
463 }
464
465 /**
466  * @brief Check URL to se if ts's real
467  *
468  * Take a URL from the wild, prepend http:// if necessary
469  * and check DNS to see if it's real (or check if is a valid IP address)
470  *
471  * @param string $url The URL to be validated
472  * @return string|boolean The actual working URL, false else
473  */
474 function validate_url($url)
475 {
476         if (Config::get('system', 'disable_url_validation')) {
477                 return $url;
478         }
479
480         // no naked subdomains (allow localhost for tests)
481         if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
482                 return false;
483         }
484
485         if (substr($url, 0, 4) != 'http') {
486                 $url = 'http://' . $url;
487         }
488
489         /// @TODO Really suppress function outcomes? Why not find them + debug them?
490         $h = @parse_url($url);
491
492         if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
493                 return $url;
494         }
495
496         return false;
497 }
498
499 /**
500  * @brief Checks that email is an actual resolvable internet address
501  *
502  * @param string $addr The email address
503  * @return boolean True if it's a valid email address, false if it's not
504  */
505 function validate_email($addr)
506 {
507         if (Config::get('system', 'disable_email_validation')) {
508                 return true;
509         }
510
511         if (! strpos($addr, '@')) {
512                 return false;
513         }
514
515         $h = substr($addr, strpos($addr, '@') + 1);
516
517         if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
518                 return true;
519         }
520         return false;
521 }
522
523 /**
524  * @brief Check if URL is allowed
525  *
526  * Check $url against our list of allowed sites,
527  * wildcards allowed. If allowed_sites is unset return true;
528  *
529  * @param string $url URL which get tested
530  * @return boolean True if url is allowed otherwise return false
531  */
532 function allowed_url($url)
533 {
534         $h = @parse_url($url);
535
536         if (! $h) {
537                 return false;
538         }
539
540         $str_allowed = Config::get('system', 'allowed_sites');
541         if (! $str_allowed) {
542                 return true;
543         }
544
545         $found = false;
546
547         $host = strtolower($h['host']);
548
549         // always allow our own site
550         if ($host == strtolower($_SERVER['SERVER_NAME'])) {
551                 return true;
552         }
553
554         $fnmatch = function_exists('fnmatch');
555         $allowed = explode(',', $str_allowed);
556
557         if (count($allowed)) {
558                 foreach ($allowed as $a) {
559                         $pat = strtolower(trim($a));
560                         if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
561                                 $found = true;
562                                 break;
563                         }
564                 }
565         }
566         return $found;
567 }
568
569 /**
570  * Checks if the provided url domain is on the domain blocklist.
571  * Returns true if it is or malformed URL, false if not.
572  *
573  * @param string $url The url to check the domain from
574  *
575  * @return boolean
576  */
577 function blocked_url($url)
578 {
579         $h = @parse_url($url);
580
581         if (! $h) {
582                 return true;
583         }
584
585         $domain_blocklist = Config::get('system', 'blocklist', []);
586         if (! $domain_blocklist) {
587                 return false;
588         }
589
590         $host = strtolower($h['host']);
591
592         foreach ($domain_blocklist as $domain_block) {
593                 if (strtolower($domain_block['domain']) == $host) {
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 function allowed_email($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 allowed_domain($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 function allowed_domain($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 function avatar_img($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 function parse_xml_string($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 function scale_external_images($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 = fetch_url($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] . ']' . 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
757 function fix_contact_ssl_policy(&$contact, $new_policy)
758 {
759         $ssl_changed = false;
760         if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
761                 $ssl_changed = true;
762                 $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
763                 $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
764                 $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
765                 $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
766                 $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
767                 $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
768         }
769
770         if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
771                 $ssl_changed = true;
772                 $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
773                 $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
774                 $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
775                 $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
776                 $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
777                 $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
778         }
779
780         if ($ssl_changed) {
781                 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
782                                 'notify' => $contact['notify'], 'poll' => $contact['poll'],
783                                 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
784                 dba::update('contact', $fields, ['id' => $contact['id']]);
785         }
786 }
787
788 /**
789  * @brief Remove Google Analytics and other tracking platforms params from URL
790  *
791  * @param string $url Any user-submitted URL that may contain tracking params
792  * @return string The same URL stripped of tracking parameters
793  */
794 function strip_tracking_query_params($url)
795 {
796         $urldata = parse_url($url);
797         if (is_string($urldata["query"])) {
798                 $query = $urldata["query"];
799                 parse_str($query, $querydata);
800
801                 if (is_array($querydata)) {
802                         foreach ($querydata as $param => $value) {
803                                 if (in_array(
804                                         $param,
805                                         [
806                                                 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
807                                                 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
808                                                 "fb_action_ids", "fb_action_types", "fb_ref",
809                                                 "awesm", "wtrid",
810                                                 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
811                                         )
812                                 ) {
813                                         $pair = $param . "=" . urlencode($value);
814                                         $url = str_replace($pair, "", $url);
815
816                                         // Second try: if the url isn't encoded completely
817                                         $pair = $param . "=" . str_replace(" ", "+", $value);
818                                         $url = str_replace($pair, "", $url);
819
820                                         // Third try: Maybey the url isn't encoded at all
821                                         $pair = $param . "=" . $value;
822                                         $url = str_replace($pair, "", $url);
823
824                                         $url = str_replace(["?&", "&&"], ["?", ""], $url);
825                                 }
826                         }
827                 }
828
829                 if (substr($url, -1, 1) == "?") {
830                         $url = substr($url, 0, -1);
831                 }
832         }
833
834         return $url;
835 }
836
837 /**
838  * @brief Returns the original URL of the provided URL
839  *
840  * This function strips tracking query params and follows redirections, either
841  * through HTTP code or meta refresh tags. Stops after 10 redirections.
842  *
843  * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
844  *
845  * @see ParseUrl::getSiteinfo
846  *
847  * @param string $url       A user-submitted URL
848  * @param int    $depth     The current redirection recursion level (internal)
849  * @param bool   $fetchbody Wether to fetch the body or not after the HEAD requests
850  * @return string A canonical URL
851  */
852 function original_url($url, $depth = 1, $fetchbody = false)
853 {
854         $a = get_app();
855
856         $url = strip_tracking_query_params($url);
857
858         if ($depth > 10) {
859                 return($url);
860         }
861
862         $url = trim($url, "'");
863
864         $stamp1 = microtime(true);
865
866         $ch = curl_init();
867         curl_setopt($ch, CURLOPT_URL, $url);
868         curl_setopt($ch, CURLOPT_HEADER, 1);
869         curl_setopt($ch, CURLOPT_NOBODY, 1);
870         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
871         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
872         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
873
874         curl_exec($ch);
875         $curl_info = @curl_getinfo($ch);
876         $http_code = $curl_info['http_code'];
877         curl_close($ch);
878
879         $a->save_timestamp($stamp1, "network");
880
881         if ($http_code == 0)
882                 return($url);
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 function short_link($url)
958 {
959         require_once 'library/slinky.php';
960         $slinky = new Slinky($url);
961         $yourls_url = Config::get('yourls', 'url1');
962         if ($yourls_url) {
963                 $yourls_username = Config::get('yourls', 'username1');
964                 $yourls_password = Config::get('yourls', 'password1');
965                 $yourls_ssl = Config::get('yourls', 'ssl1');
966                 $yourls = new Slinky_YourLS();
967                 $yourls->set('username', $yourls_username);
968                 $yourls->set('password', $yourls_password);
969                 $yourls->set('ssl', $yourls_ssl);
970                 $yourls->set('yourls-url', $yourls_url);
971                 $slinky->set_cascade([$yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()]);
972         } else {
973                 // setup a cascade of shortening services
974                 // try to get a short link from these services
975                 // in the order ur1.ca, tinyurl
976                 $slinky->set_cascade([new Slinky_Ur1ca(), new Slinky_TinyURL()]);
977         }
978         return $slinky->short();
979 }
980
981 /**
982  * @brief Encodes content to json
983  *
984  * This function encodes an array to json format
985  * and adds an application/json HTTP header to the output.
986  * After finishing the process is getting killed.
987  *
988  * @param array $x The input content
989  */
990 function json_return_and_die($x)
991 {
992         header("content-type: application/json");
993         echo json_encode($x);
994         killme();
995 }
996
997 /**
998  * @brief Find the matching part between two url
999  *
1000  * @param string $url1
1001  * @param string $url2
1002  * @return string The matching part
1003  */
1004 function matching_url($url1, $url2)
1005 {
1006         if (($url1 == "") || ($url2 == "")) {
1007                 return "";
1008         }
1009
1010         $url1 = normalise_link($url1);
1011         $url2 = normalise_link($url2);
1012
1013         $parts1 = parse_url($url1);
1014         $parts2 = parse_url($url2);
1015
1016         if (!isset($parts1["host"]) || !isset($parts2["host"])) {
1017                 return "";
1018         }
1019
1020         if ($parts1["scheme"] != $parts2["scheme"]) {
1021                 return "";
1022         }
1023
1024         if ($parts1["host"] != $parts2["host"]) {
1025                 return "";
1026         }
1027
1028         if ($parts1["port"] != $parts2["port"]) {
1029                 return "";
1030         }
1031
1032         $match = $parts1["scheme"]."://".$parts1["host"];
1033
1034         if ($parts1["port"]) {
1035                 $match .= ":".$parts1["port"];
1036         }
1037
1038         $pathparts1 = explode("/", $parts1["path"]);
1039         $pathparts2 = explode("/", $parts2["path"]);
1040
1041         $i = 0;
1042         $path = "";
1043         do {
1044                 $path1 = $pathparts1[$i];
1045                 $path2 = $pathparts2[$i];
1046
1047                 if ($path1 == $path2) {
1048                         $path .= $path1."/";
1049                 }
1050         } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
1051
1052         $match .= $path;
1053
1054         return normalise_link($match);
1055 }
1056
1057 /**
1058  * @brief Glue url parts together
1059  *
1060  * @param array $parsed URL parts
1061  *
1062  * @return string The glued URL
1063  */
1064 function unParseUrl($parsed)
1065 {
1066         $get = function ($key) use ($parsed) {
1067                 return isset($parsed[$key]) ? $parsed[$key] : null;
1068         };
1069
1070         $pass      = $get('pass');
1071         $user      = $get('user');
1072         $userinfo  = $pass !== null ? "$user:$pass" : $user;
1073         $port      = $get('port');
1074         $scheme    = $get('scheme');
1075         $query     = $get('query');
1076         $fragment  = $get('fragment');
1077         $authority = ($userinfo !== null ? $userinfo."@" : '') .
1078                                         $get('host') .
1079                                         ($port ? ":$port" : '');
1080
1081         return  (strlen($scheme) ? $scheme.":" : '') .
1082                 (strlen($authority) ? "//".$authority : '') .
1083                 $get('path') .
1084                 (strlen($query) ? "?".$query : '') .
1085                 (strlen($fragment) ? "#".$fragment : '');
1086 }