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