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