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