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