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