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