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