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