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