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