]> git.mxchange.org Git - friendica.git/blob - include/network.php
diaspora admin toggle, update install guide
[friendica.git] / include / network.php
1 <?php
2
3
4 // curl wrapper. If binary flag is true, return binary
5 // results. 
6
7 if(! function_exists('fetch_url')) {
8 function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0) {
9
10         $a = get_app();
11
12         $ch = curl_init($url);
13         if(($redirects > 8) || (! $ch)) 
14                 return false;
15
16         curl_setopt($ch, CURLOPT_HEADER, true);
17         curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
18         curl_setopt($ch, CURLOPT_USERAGENT, "Friendika");
19
20         if(intval($timeout)) {
21                 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
22         }
23         else {
24                 $curl_time = intval(get_config('system','curl_timeout'));
25                 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
26         }
27         // by default we will allow self-signed certs
28         // but you can override this
29
30         $check_cert = get_config('system','verifyssl');
31         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
32
33         $prx = get_config('system','proxy');
34         if(strlen($prx)) {
35                 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
36                 curl_setopt($ch, CURLOPT_PROXY, $prx);
37                 $prxusr = get_config('system','proxyuser');
38                 if(strlen($prxusr))
39                         curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
40         }
41         if($binary)
42                 curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
43
44         $a->set_curl_code(0);
45
46         // don't let curl abort the entire application
47         // if it throws any errors.
48
49         $s = @curl_exec($ch);
50
51         $base = $s;
52         $curl_info = curl_getinfo($ch);
53         $http_code = $curl_info['http_code'];
54
55         $header = '';
56
57         // Pull out multiple headers, e.g. proxy and continuation headers
58         // allow for HTTP/2.x without fixing code
59
60         while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
61                 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
62                 $header .= $chunk;
63                 $base = substr($base,strlen($chunk));
64         }
65
66         if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
67         $matches = array();
68         preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
69         $url = trim(array_pop($matches));
70         $url_parsed = @parse_url($url);
71         if (isset($url_parsed)) {
72             $redirects++;
73             return fetch_url($url,$binary,$redirects,$timeout);
74         }
75     }
76
77         $a->set_curl_code($http_code);
78
79         $body = substr($s,strlen($header));
80
81         $a->set_curl_headers($header);
82
83         curl_close($ch);
84         return($body);
85 }}
86
87 // post request to $url. $params is an array of post variables.
88
89 if(! function_exists('post_url')) {
90 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
91         $a = get_app();
92         $ch = curl_init($url);
93         if(($redirects > 8) || (! $ch)) 
94                 return false;
95
96         curl_setopt($ch, CURLOPT_HEADER, true);
97         curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
98         curl_setopt($ch, CURLOPT_POST,1);
99         curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
100         curl_setopt($ch, CURLOPT_USERAGENT, "Friendika");
101
102         if(intval($timeout)) {
103                 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
104         }
105         else {
106                 $curl_time = intval(get_config('system','curl_timeout'));
107                 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
108         }
109
110         if(defined('LIGHTTPD')) {
111                 if(!is_array($headers)) {
112                         $headers = array('Expect:');
113                 } else {
114                         if(!in_array('Expect:', $headers)) {
115                                 array_push($headers, 'Expect:');
116                         }
117                 }
118         }
119         if($headers)
120                 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
121
122         $check_cert = get_config('system','verifyssl');
123         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
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
133         $a->set_curl_code(0);
134
135         // don't let curl abort the entire application
136         // if it throws any errors.
137
138         $s = @curl_exec($ch);
139
140         $base = $s;
141         $curl_info = curl_getinfo($ch);
142         $http_code = $curl_info['http_code'];
143
144         $header = '';
145
146         // Pull out multiple headers, e.g. proxy and continuation headers
147         // allow for HTTP/2.x without fixing code
148
149         while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
150                 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
151                 $header .= $chunk;
152                 $base = substr($base,strlen($chunk));
153         }
154
155         if($http_code == 301 || $http_code == 302 || $http_code == 303) {
156         $matches = array();
157         preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
158         $url = trim(array_pop($matches));
159         $url_parsed = @parse_url($url);
160         if (isset($url_parsed)) {
161             $redirects++;
162             return post_url($url,$params,$headers,$redirects,$timeout);
163         }
164     }
165         $a->set_curl_code($http_code);
166         $body = substr($s,strlen($header));
167
168         $a->set_curl_headers($header);
169
170         curl_close($ch);
171         return($body);
172 }}
173
174 // Generic XML return
175 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable 
176 // of $st and an optional text <message> of $message and terminates the current process. 
177
178 if(! function_exists('xml_status')) {
179 function xml_status($st, $message = '') {
180
181         $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
182
183         if($st)
184                 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
185
186         header( "Content-type: text/xml" );
187         echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
188         echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
189         killme();
190 }}
191
192
193 if(! function_exists('http_status_exit')) {
194 function http_status_exit($val) {
195
196         if($val >= 400)
197                 $err = 'Error';
198         if($val >= 200 && $val < 300)
199                 $err = 'OK';
200
201         logger('http_status_exit ' . $val);     
202         header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
203         killme();
204
205 }}
206
207
208 // convert an XML document to a normalised, case-corrected array
209 // used by webfinger
210
211 if(! function_exists('convert_xml_element_to_array')) {
212 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
213
214         // If we're getting too deep, bail out
215         if ($recursion_depth > 512) {
216                 return(null);
217         }
218
219         if (!is_string($xml_element) &&
220         !is_array($xml_element) &&
221         (get_class($xml_element) == 'SimpleXMLElement')) {
222                 $xml_element_copy = $xml_element;
223                 $xml_element = get_object_vars($xml_element);
224         }
225
226         if (is_array($xml_element)) {
227                 $result_array = array();
228                 if (count($xml_element) <= 0) {
229                         return (trim(strval($xml_element_copy)));
230                 }
231
232                 foreach($xml_element as $key=>$value) {
233
234                         $recursion_depth++;
235                         $result_array[strtolower($key)] =
236                 convert_xml_element_to_array($value, $recursion_depth);
237                         $recursion_depth--;
238                 }
239                 if ($recursion_depth == 0) {
240                         $temp_array = $result_array;
241                         $result_array = array(
242                                 strtolower($xml_element_copy->getName()) => $temp_array,
243                         );
244                 }
245
246                 return ($result_array);
247
248         } else {
249                 return (trim(strval($xml_element)));
250         }
251 }}
252
253 // Given an email style address, perform webfinger lookup and 
254 // return the resulting DFRN profile URL, or if no DFRN profile URL
255 // is located, returns an OStatus subscription template (prefixed 
256 // with the string 'stat:' to identify it as on OStatus template).
257 // If this isn't an email style address just return $s.
258 // Return an empty string if email-style addresses but webfinger fails,
259 // or if the resultant personal XRD doesn't contain a supported 
260 // subscription/friend-request attribute.
261
262 if(! function_exists('webfinger_dfrn')) {
263 function webfinger_dfrn($s) {
264         if(! strstr($s,'@')) {
265                 return $s;
266         }
267         $links = webfinger($s);
268         logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
269         if(count($links)) {
270                 foreach($links as $link)
271                         if($link['@attributes']['rel'] === NAMESPACE_DFRN)
272                                 return $link['@attributes']['href'];
273                 foreach($links as $link)
274                         if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
275                                 return 'stat:' . $link['@attributes']['template'];              
276         }
277         return '';
278 }}
279
280 // Given an email style address, perform webfinger lookup and 
281 // return the array of link attributes from the personal XRD file.
282 // On error/failure return an empty array.
283
284
285 if(! function_exists('webfinger')) {
286 function webfinger($s) {
287         $host = '';
288         if(strstr($s,'@')) {
289                 $host = substr($s,strpos($s,'@') + 1);
290         }
291         if(strlen($host)) {
292                 $tpl = fetch_lrdd_template($host);
293                 logger('webfinger: lrdd template: ' . $tpl);
294                 if(strlen($tpl)) {
295                         $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
296                         logger('webfinger: pxrd: ' . $pxrd);
297                         $links = fetch_xrd_links($pxrd);
298                         if(! count($links)) {
299                                 // try with double slashes
300                                 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
301                                 logger('webfinger: pxrd: ' . $pxrd);
302                                 $links = fetch_xrd_links($pxrd);
303                         }
304                         return $links;
305                 }
306         }
307         return array();
308 }}
309
310 if(! function_exists('lrdd')) {
311 function lrdd($uri) {
312
313         $a = get_app();
314
315         // default priority is host priority, host-meta first
316
317         $priority = 'host';
318
319         // All we have is an email address. Resource-priority is irrelevant
320         // because our URI isn't directly resolvable.
321
322         if(strstr($uri,'@')) {  
323                 return(webfinger($uri));
324         }
325
326         // get the host meta file
327
328         $host = @parse_url($uri);
329
330         if($host) {
331                 $url  = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
332                 $url .= $host['host'] . '/.well-known/host-meta' ;
333         }
334         else
335                 return array();
336
337         logger('lrdd: constructed url: ' . $url);
338
339         $xml = fetch_url($url);
340         $headers = $a->get_curl_headers();
341
342         if (! $xml)
343                 return array();
344
345         logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
346
347         $h = parse_xml_string($xml);
348         if(! $h)
349                 return array();
350
351         $arr = convert_xml_element_to_array($h);
352
353         if(isset($arr['xrd']['property'])) {
354                 $property = $arr['crd']['property'];
355                 if(! isset($property[0]))
356                         $properties = array($property);
357                 else
358                         $properties = $property;
359                 foreach($properties as $prop)
360                         if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
361                                 $priority = 'resource';
362         } 
363
364         // save the links in case we need them
365
366         $links = array();
367
368         if(isset($arr['xrd']['link'])) {
369                 $link = $arr['xrd']['link'];
370                 if(! isset($link[0]))
371                         $links = array($link);
372                 else
373                         $links = $link;
374         }
375
376         // do we have a template or href?
377
378         if(count($links)) {
379                 foreach($links as $link) {
380                         if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
381                                 if(x($link['@attributes'],'template'))
382                                         $tpl = $link['@attributes']['template'];
383                                 elseif(x($link['@attributes'],'href'))
384                                         $href = $link['@attributes']['href'];
385                         }
386                 }               
387         }
388
389         if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
390                 $tpl = '';
391
392         if($priority === 'host') {
393                 if(strlen($tpl)) 
394                         $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
395                 elseif(isset($href))
396                         $pxrd = $href;
397                 if(isset($pxrd)) {
398                         logger('lrdd: (host priority) pxrd: ' . $pxrd);
399                         $links = fetch_xrd_links($pxrd);
400                         return $links;
401                 }
402
403                 $lines = explode("\n",$headers);
404                 if(count($lines)) {
405                         foreach($lines as $line) {                              
406                                 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
407                                         return(fetch_xrd_links($matches[1]));
408                                         break;
409                                 }
410                         }
411                 }
412         }
413
414
415         // priority 'resource'
416
417
418         $html = fetch_url($uri);
419         $headers = $a->get_curl_headers();
420         logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
421
422         // don't try and parse raw xml as html
423         if(! strstr($html,'<?xml')) {
424                 require_once('library/HTML5/Parser.php');
425                 $dom = @HTML5_Parser::parse($html);
426
427                 if($dom) {
428                         $items = $dom->getElementsByTagName('link');
429                         foreach($items as $item) {
430                                 $x = $item->getAttribute('rel');
431                                 if($x == "lrdd") {
432                                         $pagelink = $item->getAttribute('href');
433                                         break;
434                                 }
435                         }
436                 }
437         }
438
439         if(isset($pagelink))
440                 return(fetch_xrd_links($pagelink));
441
442         // next look in HTTP headers
443
444         $lines = explode("\n",$headers);
445         if(count($lines)) {
446                 foreach($lines as $line) {                              
447                         // TODO alter the following regex to support multiple relations (space separated)
448                         if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
449                                 $pagelink = $matches[1];
450                                 break;
451                         }
452                         // don't try and run feeds through the html5 parser
453                         if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
454                                 return array();
455                         if(stristr($html,'<rss') || stristr($html,'<feed'))
456                                 return array();
457                 }
458         }
459
460         if(isset($pagelink))
461                 return(fetch_xrd_links($pagelink));
462
463         // If we haven't found any links, return the host xrd links (which we have already fetched)
464
465         if(isset($links))
466                 return $links;
467
468         return array();
469
470 }}
471
472
473
474 // Given a host name, locate the LRDD template from that
475 // host. Returns the LRDD template or an empty string on
476 // error/failure.
477
478 if(! function_exists('fetch_lrdd_template')) {
479 function fetch_lrdd_template($host) {
480         $tpl = '';
481
482         $url1 = 'https://' . $host . '/.well-known/host-meta' ;
483         $url2 = 'http://' . $host . '/.well-known/host-meta' ;
484         $links = fetch_xrd_links($url1);
485         logger('fetch_lrdd_template from: ' . $url1);
486         logger('template (https): ' . print_r($links,true));
487         if(! count($links)) {
488                 logger('fetch_lrdd_template from: ' . $url2);
489                 $links = fetch_xrd_links($url2);
490                 logger('template (http): ' . print_r($links,true));
491         }
492         if(count($links)) {
493                 foreach($links as $link)
494                         if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
495                                 $tpl = $link['@attributes']['template'];
496         }
497         if(! strpos($tpl,'{uri}'))
498                 $tpl = '';
499         return $tpl;
500 }}
501
502 // Given a URL, retrieve the page as an XRD document.
503 // Return an array of links.
504 // on error/failure return empty array.
505
506 if(! function_exists('fetch_xrd_links')) {
507 function fetch_xrd_links($url) {
508
509         $xrd_timeout = intval(get_config('system','xrd_timeout'));
510         $redirects = 0;
511         $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
512
513         logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
514
515         if ((! $xml) || (! stristr($xml,'<xrd')))
516                 return array();
517
518         $h = parse_xml_string($xml);
519         if(! $h)
520                 return array();
521
522         $arr = convert_xml_element_to_array($h);
523
524         $links = array();
525
526         if(isset($arr['xrd']['link'])) {
527                 $link = $arr['xrd']['link'];
528                 if(! isset($link[0]))
529                         $links = array($link);
530                 else
531                         $links = $link;
532         }
533         if(isset($arr['xrd']['alias'])) {
534                 $alias = $arr['xrd']['alias'];
535                 if(! isset($alias[0]))
536                         $aliases = array($alias);
537                 else
538                         $aliases = $alias;
539                 if($aliases && count($aliases)) {
540                         foreach($aliases as $alias) {
541                                 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
542                         }
543                 }
544         }
545
546         logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
547
548         return $links;
549
550 }}
551
552
553 // Take a URL from the wild, prepend http:// if necessary
554 // and check DNS to see if it's real
555 // return true if it's OK, false if something is wrong with it
556
557 if(! function_exists('validate_url')) {
558 function validate_url(&$url) {
559         if(substr($url,0,4) != 'http')
560                 $url = 'http://' . $url;
561         $h = @parse_url($url);
562
563         if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
564                 return true;
565         }
566         return false;
567 }}
568
569 // checks that email is an actual resolvable internet address
570
571 if(! function_exists('validate_email')) {
572 function validate_email($addr) {
573
574         if(! strpos($addr,'@'))
575                 return false;
576         $h = substr($addr,strpos($addr,'@') + 1);
577
578         if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
579                 return true;
580         }
581         return false;
582 }}
583
584 // Check $url against our list of allowed sites,
585 // wildcards allowed. If allowed_sites is unset return true;
586 // If url is allowed, return true.
587 // otherwise, return false
588
589 if(! function_exists('allowed_url')) {
590 function allowed_url($url) {
591
592         $h = @parse_url($url);
593
594         if(! $h) {
595                 return false;
596         }
597
598         $str_allowed = get_config('system','allowed_sites');
599         if(! $str_allowed)
600                 return true;
601
602         $found = false;
603
604         $host = strtolower($h['host']);
605
606         // always allow our own site
607
608         if($host == strtolower($_SERVER['SERVER_NAME']))
609                 return true;
610
611         $fnmatch = function_exists('fnmatch');
612         $allowed = explode(',',$str_allowed);
613
614         if(count($allowed)) {
615                 foreach($allowed as $a) {
616                         $pat = strtolower(trim($a));
617                         if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
618                                 $found = true; 
619                                 break;
620                         }
621                 }
622         }
623         return $found;
624 }}
625
626 // check if email address is allowed to register here.
627 // Compare against our list (wildcards allowed).
628 // Returns false if not allowed, true if allowed or if
629 // allowed list is not configured.
630
631 if(! function_exists('allowed_email')) {
632 function allowed_email($email) {
633
634
635         $domain = strtolower(substr($email,strpos($email,'@') + 1));
636         if(! $domain)
637                 return false;
638
639         $str_allowed = get_config('system','allowed_email');
640         if(! $str_allowed)
641                 return true;
642
643         $found = false;
644
645         $fnmatch = function_exists('fnmatch');
646         $allowed = explode(',',$str_allowed);
647
648         if(count($allowed)) {
649                 foreach($allowed as $a) {
650                         $pat = strtolower(trim($a));
651                         if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
652                                 $found = true; 
653                                 break;
654                         }
655                 }
656         }
657         return $found;
658 }}
659
660
661 if(! function_exists('gravatar_img')) {
662 function gravatar_img($email) {
663         $size = 175;
664         $opt = 'identicon';   // psuedo-random geometric pattern if not found
665         $rating = 'pg';
666         $hash = md5(trim(strtolower($email)));
667         
668         $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg' 
669                 . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
670
671         logger('gravatar: ' . $email . ' ' . $url);
672         return $url;
673 }}
674
675
676 if(! function_exists('parse_xml_string')) {
677 function parse_xml_string($s,$strict = true) {
678         if($strict) {
679                 if(! strstr($s,'<?xml'))
680                         return false;
681                 $s2 = substr($s,strpos($s,'<?xml'));
682         }
683         else
684                 $s2 = $s;
685         libxml_use_internal_errors(true);
686
687         $x = @simplexml_load_string($s2);
688         if(! $x) {
689                 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
690                 foreach(libxml_get_errors() as $err)
691                         logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
692                 libxml_clear_errors();
693         }
694         return $x;
695 }}
696
697 function add_fcontact($arr) {
698
699         $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
700                 `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
701                 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
702                 dbesc($arr['url']),
703                 dbesc($arr['name']),
704                 dbesc($arr['photo']),
705                 dbesc($arr['request']),
706                 dbesc($arr['nick']),
707                 dbesc($arr['addr']),
708                 dbesc($arr['notify']),
709                 dbesc($arr['poll']),
710                 dbesc($arr['confirm']),
711                 dbesc($arr['network']),
712                 dbesc($arr['alias']),
713                 dbesc($arr['pubkey']),
714                 dbesc(datetime_convert())
715         );
716         return $r;
717 }