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