]> git.mxchange.org Git - friendica.git/blob - include/network.php
Move xml to namespace
[friendica.git] / include / network.php
1 <?php
2
3 /**
4  * @file include/network.php
5  */
6
7 use Friendica\App;
8 use Friendica\Core\System;
9 use Friendica\Core\Config;
10 use Friendica\Network\Probe;
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                 array('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 = array())
68 {
69         $ret = array('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                         array('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 = intval(Config::get('system', 'curl_timeout'));
131                 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
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 = array();
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         $body = substr($s, strlen($header));
237
238         $rc = intval($http_code);
239         $ret['return_code'] = $rc;
240         $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
241         $ret['redirect_url'] = $url;
242
243         if (!$ret['success']) {
244                 $ret['error'] = curl_error($ch);
245                 $ret['debug'] = $curl_info;
246                 logger('z_fetch_url: error: '.$url.': '.$ret['return_code'].' - '.$ret['error'], LOGGER_DEBUG);
247                 logger('z_fetch_url: debug: '.print_r($curl_info, true), LOGGER_DATA);
248         }
249
250         $ret['body'] = substr($s, strlen($header));
251         $ret['header'] = $header;
252
253         if (x($opts, 'debug')) {
254                 $ret['debug'] = $curl_info;
255         }
256
257         @curl_close($ch);
258
259         $a->save_timestamp($stamp1, 'network');
260
261         return($ret);
262 }
263
264 /**
265  * @brief Send POST request to $url
266  *
267  * @param string  $url       URL to post
268  * @param mixed   $params    array of POST variables
269  * @param string  $headers   HTTP headers
270  * @param integer $redirects Recursion counter for internal use - default = 0
271  * @param integer $timeout   The timeout in seconds, default system config value or 60 seconds
272  *
273  * @return string The content
274  */
275 function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
276 {
277         $stamp1 = microtime(true);
278
279         if (blocked_url($url)) {
280                 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
281                 return false;
282         }
283
284         $a = get_app();
285         $ch = curl_init($url);
286
287         if (($redirects > 8) || (!$ch)) {
288                 return false;
289         }
290
291         logger('post_url: start ' . $url, LOGGER_DATA);
292
293         curl_setopt($ch, CURLOPT_HEADER, true);
294         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
295         curl_setopt($ch, CURLOPT_POST, 1);
296         curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
297         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
298
299         if (Config::get('system', 'ipv4_resolve', false)) {
300                 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
301         }
302
303         if (intval($timeout)) {
304                 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
305         } else {
306                 $curl_time = intval(Config::get('system', 'curl_timeout'));
307                 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
308         }
309
310         if (defined('LIGHTTPD')) {
311                 if (!is_array($headers)) {
312                         $headers = array('Expect:');
313                 } else {
314                         if (!in_array('Expect:', $headers)) {
315                                 array_push($headers, 'Expect:');
316                         }
317                 }
318         }
319
320         if ($headers) {
321                 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
322         }
323
324         $check_cert = Config::get('system', 'verifyssl');
325         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
326
327         if ($check_cert) {
328                 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
329         }
330
331         $proxy = Config::get('system', 'proxy');
332
333         if (strlen($proxy)) {
334                 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
335                 curl_setopt($ch, CURLOPT_PROXY, $proxy);
336                 $proxyuser = Config::get('system', 'proxyuser');
337                 if (strlen($proxyuser)) {
338                         curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
339                 }
340         }
341
342         $a->set_curl_code(0);
343
344         // don't let curl abort the entire application
345         // if it throws any errors.
346
347         $s = @curl_exec($ch);
348
349         $base = $s;
350         $curl_info = curl_getinfo($ch);
351         $http_code = $curl_info['http_code'];
352
353         logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
354
355         $header = '';
356
357         // Pull out multiple headers, e.g. proxy and continuation headers
358         // allow for HTTP/2.x without fixing code
359
360         while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
361                 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
362                 $header .= $chunk;
363                 $base = substr($base, strlen($chunk));
364         }
365
366         if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
367                 $matches = array();
368                 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
369                 $newurl = trim(array_pop($matches));
370
371                 if (strpos($newurl, '/') === 0) {
372                         $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
373                 }
374
375                 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
376                         $redirects++;
377                         logger('post_url: redirect ' . $url . ' to ' . $newurl);
378                         return post_url($newurl, $params, $headers, $redirects, $timeout);
379                 }
380         }
381
382         $a->set_curl_code($http_code);
383
384         $body = substr($s, strlen($header));
385
386         $a->set_curl_headers($header);
387
388         curl_close($ch);
389
390         $a->save_timestamp($stamp1, 'network');
391
392         logger('post_url: end ' . $url, LOGGER_DATA);
393
394         return $body;
395 }
396
397 // Generic XML return
398 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
399 // of $st and an optional text <message> of $message and terminates the current process.
400
401 function xml_status($st, $message = '')
402 {
403         $result = array('status' => $st);
404
405         if ($message != '') {
406                 $result['message'] = $message;
407         }
408
409         if ($st) {
410                 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
411         }
412
413         header("Content-type: text/xml");
414
415         $xmldata = array("result" => $result);
416
417         echo Xml::from_array($xmldata, $xml);
418
419         killme();
420 }
421
422 /**
423  * @brief Send HTTP status header and exit.
424  *
425  * @param integer $val HTTP status result value
426  * @param array $description optional message
427  *    'title' => header title
428  *    'description' => optional message
429  */
430
431 /**
432  * @brief Send HTTP status header and exit.
433  *
434  * @param integer $val         HTTP status result value
435  * @param array   $description optional message
436  *                             'title' => header title
437  *                             'description' => optional message
438  */
439 function http_status_exit($val, $description = array())
440 {
441         $err = '';
442         if ($val >= 400) {
443                 $err = 'Error';
444                 if (!isset($description["title"])) {
445                         $description["title"] = $err." ".$val;
446                 }
447         }
448         if ($val >= 200 && $val < 300)
449                 $err = 'OK';
450
451         logger('http_status_exit ' . $val);
452         header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
453
454         if (isset($description["title"])) {
455                 $tpl = get_markup_template('http_status.tpl');
456                 echo replace_macros(
457                         $tpl,
458                         array(
459                                 '$title' => $description["title"],
460                                 '$description' => $description["description"])
461                 );
462         }
463
464         killme();
465 }
466
467 /**
468  * @brief Check URL to se if ts's real
469  *
470  * Take a URL from the wild, prepend http:// if necessary
471  * and check DNS to see if it's real (or check if is a valid IP address)
472  *
473  * @param string $url The URL to be validated
474  * @return boolean True if it's a valid URL, fals if something wrong with it
475  */
476 function validate_url(&$url)
477 {
478         if (Config::get('system', 'disable_url_validation')) {
479                 return true;
480         }
481
482         // no naked subdomains (allow localhost for tests)
483         if (strpos($url, '.') === false && strpos($url, '/localhost/') === false)
484                 return false;
485
486         if (substr($url, 0, 4) != 'http')
487                 $url = 'http://' . $url;
488
489         /// @TODO Really supress 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 true;
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  * @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         $a = get_app();
682
683         // Picture addresses can contain special characters
684         $s = htmlspecialchars_decode($srctext);
685
686         $matches = null;
687         $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER);
688         if ($c) {
689                 require_once 'include/Photo.php';
690                 foreach ($matches as $mtch) {
691                         logger('scale_external_image: ' . $mtch[1]);
692
693                         $hostname = str_replace('www.', '', substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3));
694                         if (stristr($mtch[1], $hostname)) {
695                                 continue;
696                         }
697
698                         // $scale_replace, if passed, is an array of two elements. The
699                         // first is the name of the full-size image. The second is the
700                         // name of a remote, scaled-down version of the full size image.
701                         // This allows Friendica to display the smaller remote image if
702                         // one exists, while still linking to the full-size image
703                         if ($scale_replace) {
704                                 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
705                         } else {
706                                 $scaled = $mtch[1];
707                         }
708                         $i = fetch_url($scaled);
709                         if (! $i) {
710                                 return $srctext;
711                         }
712
713                         // guess mimetype from headers or filename
714                         $type = guess_image_type($mtch[1], true);
715
716                         if ($i) {
717                                 $ph = new Photo($i, $type);
718                                 if ($ph->is_valid()) {
719                                         $orig_width = $ph->getWidth();
720                                         $orig_height = $ph->getHeight();
721
722                                         if ($orig_width > 640 || $orig_height > 640) {
723                                                 $ph->scaleImage(640);
724                                                 $new_width = $ph->getWidth();
725                                                 $new_height = $ph->getHeight();
726                                                 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
727                                                 $s = str_replace(
728                                                         $mtch[0],
729                                                         '[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
730                                                         . "\n" . (($include_link)
731                                                                 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
732                                                                 : ''),
733                                                         $s
734                                                 );
735                                                 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
736                                         }
737                                 }
738                         }
739                 }
740         }
741
742         // replace the special char encoding
743         $s = htmlspecialchars($s, ENT_NOQUOTES, 'UTF-8');
744         return $s;
745 }
746
747
748 function fix_contact_ssl_policy(&$contact, $new_policy)
749 {
750         $ssl_changed = false;
751         if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
752                 $ssl_changed = true;
753                 $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
754                 $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
755                 $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
756                 $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
757                 $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
758                 $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
759         }
760
761         if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
762                 $ssl_changed = true;
763                 $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
764                 $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
765                 $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
766                 $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
767                 $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
768                 $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
769         }
770
771         if ($ssl_changed) {
772                 $fields = array('url' => $contact['url'], 'request' => $contact['request'],
773                                 'notify' => $contact['notify'], 'poll' => $contact['poll'],
774                                 'confirm' => $contact['confirm'], 'poco' => $contact['poco']);
775                 dba::update('contact', $fields, array('id' => $contact['id']));
776         }
777 }
778
779 /**
780  * @brief Remove Google Analytics and other tracking platforms params from URL
781  *
782  * @param string $url Any user-submitted URL that may contain tracking params
783  * @return string The same URL stripped of tracking parameters
784  */
785 function strip_tracking_query_params($url)
786 {
787         $urldata = parse_url($url);
788         if (is_string($urldata["query"])) {
789                 $query = $urldata["query"];
790                 parse_str($query, $querydata);
791
792                 if (is_array($querydata)) {
793                         foreach ($querydata as $param => $value) {
794                                 if (in_array(
795                                         $param,
796                                         array(
797                                                 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
798                                                 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
799                                                 "fb_action_ids", "fb_action_types", "fb_ref",
800                                                 "awesm", "wtrid",
801                                                 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term")
802                                         )
803                                 ) {
804                                         $pair = $param . "=" . urlencode($value);
805                                         $url = str_replace($pair, "", $url);
806
807                                         // Second try: if the url isn't encoded completely
808                                         $pair = $param . "=" . str_replace(" ", "+", $value);
809                                         $url = str_replace($pair, "", $url);
810
811                                         // Third try: Maybey the url isn't encoded at all
812                                         $pair = $param . "=" . $value;
813                                         $url = str_replace($pair, "", $url);
814
815                                         $url = str_replace(array("?&", "&&"), array("?", ""), $url);
816                                 }
817                         }
818                 }
819
820                 if (substr($url, -1, 1) == "?") {
821                         $url = substr($url, 0, -1);
822                 }
823         }
824
825         return $url;
826 }
827
828 /**
829  * @brief Returns the original URL of the provided URL
830  *
831  * This function strips tracking query params and follows redirections, either
832  * through HTTP code or meta refresh tags. Stops after 10 redirections.
833  *
834  * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
835  *
836  * @see ParseUrl::getSiteinfo
837  *
838  * @param string $url       A user-submitted URL
839  * @param int    $depth     The current redirection recursion level (internal)
840  * @param bool   $fetchbody Wether to fetch the body or not after the HEAD requests
841  * @return string A canonical URL
842  */
843 function original_url($url, $depth = 1, $fetchbody = false)
844 {
845         $a = get_app();
846
847         $url = strip_tracking_query_params($url);
848
849         if ($depth > 10) {
850                 return($url);
851         }
852
853         $url = trim($url, "'");
854
855         $stamp1 = microtime(true);
856
857         $siteinfo = array();
858         $ch = curl_init();
859         curl_setopt($ch, CURLOPT_URL, $url);
860         curl_setopt($ch, CURLOPT_HEADER, 1);
861         curl_setopt($ch, CURLOPT_NOBODY, 1);
862         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
863         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
864         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
865
866         $header = curl_exec($ch);
867         $curl_info = @curl_getinfo($ch);
868         $http_code = $curl_info['http_code'];
869         curl_close($ch);
870
871         $a->save_timestamp($stamp1, "network");
872
873         if ($http_code == 0)
874                 return($url);
875
876         if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302"))
877                 && (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))
878         ) {
879                 if ($curl_info['redirect_url'] != "") {
880                         return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
881                 } else {
882                         return(original_url($curl_info['location'], ++$depth, $fetchbody));
883                 }
884         }
885
886         // Check for redirects in the meta elements of the body if there are no redirects in the header.
887         if (!$fetchbody) {
888                 return(original_url($url, ++$depth, true));
889         }
890
891         // if the file is too large then exit
892         if ($curl_info["download_content_length"] > 1000000) {
893                 return($url);
894         }
895
896         // if it isn't a HTML file then exit
897         if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
898                 return($url);
899         }
900
901         $stamp1 = microtime(true);
902
903         $ch = curl_init();
904         curl_setopt($ch, CURLOPT_URL, $url);
905         curl_setopt($ch, CURLOPT_HEADER, 0);
906         curl_setopt($ch, CURLOPT_NOBODY, 0);
907         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
908         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
909         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
910
911         $body = curl_exec($ch);
912         curl_close($ch);
913
914         $a->save_timestamp($stamp1, "network");
915
916         if (trim($body) == "") {
917                 return($url);
918         }
919
920         // Check for redirect in meta elements
921         $doc = new DOMDocument();
922         @$doc->loadHTML($body);
923
924         $xpath = new DomXPath($doc);
925
926         $list = $xpath->query("//meta[@content]");
927         foreach ($list as $node) {
928                 $attr = array();
929                 if ($node->attributes->length) {
930                         foreach ($node->attributes as $attribute) {
931                                 $attr[$attribute->name] = $attribute->value;
932                         }
933                 }
934
935                 if (@$attr["http-equiv"] == 'refresh') {
936                         $path = $attr["content"];
937                         $pathinfo = explode(";", $path);
938                         $content = "";
939                         foreach ($pathinfo as $value) {
940                                 if (substr(strtolower($value), 0, 4) == "url=") {
941                                         return(original_url(substr($value, 4), ++$depth));
942                                 }
943                         }
944                 }
945         }
946
947         return($url);
948 }
949
950 function short_link($url)
951 {
952         require_once 'library/slinky.php';
953         $slinky = new Slinky($url);
954         $yourls_url = Config::get('yourls', 'url1');
955         if ($yourls_url) {
956                 $yourls_username = Config::get('yourls', 'username1');
957                 $yourls_password = Config::get('yourls', 'password1');
958                 $yourls_ssl = Config::get('yourls', 'ssl1');
959                 $yourls = new Slinky_YourLS();
960                 $yourls->set('username', $yourls_username);
961                 $yourls->set('password', $yourls_password);
962                 $yourls->set('ssl', $yourls_ssl);
963                 $yourls->set('yourls-url', $yourls_url);
964                 $slinky->set_cascade(array($yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()));
965         } else {
966                 // setup a cascade of shortening services
967                 // try to get a short link from these services
968                 // in the order ur1.ca, tinyurl
969                 $slinky->set_cascade(array(new Slinky_Ur1ca(), new Slinky_TinyURL()));
970         }
971         return $slinky->short();
972 }
973
974 /**
975  * @brief Encodes content to json
976  *
977  * This function encodes an array to json format
978  * and adds an application/json HTTP header to the output.
979  * After finishing the process is getting killed.
980  *
981  * @param array $x The input content
982  */
983 function json_return_and_die($x)
984 {
985         header("content-type: application/json");
986         echo json_encode($x);
987         killme();
988 }
989
990 /**
991  * @brief Find the matching part between two url
992  *
993  * @param string $url1
994  * @param string $url2
995  * @return string The matching part
996  */
997 function matching_url($url1, $url2)
998 {
999         if (($url1 == "") || ($url2 == "")) {
1000                 return "";
1001         }
1002
1003         $url1 = normalise_link($url1);
1004         $url2 = normalise_link($url2);
1005
1006         $parts1 = parse_url($url1);
1007         $parts2 = parse_url($url2);
1008
1009         if (!isset($parts1["host"]) || !isset($parts2["host"])) {
1010                 return "";
1011         }
1012
1013         if ($parts1["scheme"] != $parts2["scheme"]) {
1014                 return "";
1015         }
1016
1017         if ($parts1["host"] != $parts2["host"]) {
1018                 return "";
1019         }
1020
1021         if ($parts1["port"] != $parts2["port"]) {
1022                 return "";
1023         }
1024
1025         $match = $parts1["scheme"]."://".$parts1["host"];
1026
1027         if ($parts1["port"]) {
1028                 $match .= ":".$parts1["port"];
1029         }
1030
1031         $pathparts1 = explode("/", $parts1["path"]);
1032         $pathparts2 = explode("/", $parts2["path"]);
1033
1034         $i = 0;
1035         $path = "";
1036         do {
1037                 $path1 = $pathparts1[$i];
1038                 $path2 = $pathparts2[$i];
1039
1040                 if ($path1 == $path2) {
1041                         $path .= $path1."/";
1042                 }
1043         } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
1044
1045         $match .= $path;
1046
1047         return normalise_link($match);
1048 }
1049
1050 /**
1051  * @brief Glue url parts together
1052  *
1053  * @param array $parsed URL parts
1054  *
1055  * @return string The glued URL
1056  */
1057 function unParseUrl($parsed)
1058 {
1059         $get = function ($key) use ($parsed) {
1060                 return isset($parsed[$key]) ? $parsed[$key] : null;
1061         };
1062
1063         $pass      = $get('pass');
1064         $user      = $get('user');
1065         $userinfo  = $pass !== null ? "$user:$pass" : $user;
1066         $port      = $get('port');
1067         $scheme    = $get('scheme');
1068         $query     = $get('query');
1069         $fragment  = $get('fragment');
1070         $authority = ($userinfo !== null ? $userinfo."@" : '') .
1071                                         $get('host') .
1072                                         ($port ? ":$port" : '');
1073
1074         return  (strlen($scheme) ? $scheme.":" : '') .
1075                 (strlen($authority) ? "//".$authority : '') .
1076                 $get('path') .
1077                 (strlen($query) ? "?".$query : '') .
1078                 (strlen($fragment) ? "#".$fragment : '');
1079 }