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