]> git.mxchange.org Git - friendica.git/blob - include/network.php
Merge pull request #170 from fabrixxm/master
[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 // amended 7/9/2011 to return an hcard which could save potentially loading 
263 // a lengthy content page to scrape dfrn attributes
264
265 if(! function_exists('webfinger_dfrn')) {
266 function webfinger_dfrn($s,&$hcard) {
267         if(! strstr($s,'@')) {
268                 return $s;
269         }
270         $profile_link = '';
271
272         $links = webfinger($s);
273         logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
274         if(count($links)) {
275                 foreach($links as $link) {
276                         if($link['@attributes']['rel'] === NAMESPACE_DFRN)
277                                 $profile_link = $link['@attributes']['href'];
278                         if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
279                                 $profile_link = 'stat:' . $link['@attributes']['template'];     
280                         if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
281                                 $hcard = $link['@attributes']['href'];                          
282                 }
283         }
284         return $profile_link;
285 }}
286
287 // Given an email style address, perform webfinger lookup and 
288 // return the array of link attributes from the personal XRD file.
289 // On error/failure return an empty array.
290
291
292 if(! function_exists('webfinger')) {
293 function webfinger($s) {
294         $host = '';
295         if(strstr($s,'@')) {
296                 $host = substr($s,strpos($s,'@') + 1);
297         }
298         if(strlen($host)) {
299                 $tpl = fetch_lrdd_template($host);
300                 logger('webfinger: lrdd template: ' . $tpl);
301                 if(strlen($tpl)) {
302                         $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
303                         logger('webfinger: pxrd: ' . $pxrd);
304                         $links = fetch_xrd_links($pxrd);
305                         if(! count($links)) {
306                                 // try with double slashes
307                                 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
308                                 logger('webfinger: pxrd: ' . $pxrd);
309                                 $links = fetch_xrd_links($pxrd);
310                         }
311                         return $links;
312                 }
313         }
314         return array();
315 }}
316
317 if(! function_exists('lrdd')) {
318 function lrdd($uri) {
319
320         $a = get_app();
321
322         // default priority is host priority, host-meta first
323
324         $priority = 'host';
325
326         // All we have is an email address. Resource-priority is irrelevant
327         // because our URI isn't directly resolvable.
328
329         if(strstr($uri,'@')) {  
330                 return(webfinger($uri));
331         }
332
333         // get the host meta file
334
335         $host = @parse_url($uri);
336
337         if($host) {
338                 $url  = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
339                 $url .= $host['host'] . '/.well-known/host-meta' ;
340         }
341         else
342                 return array();
343
344         logger('lrdd: constructed url: ' . $url);
345
346         $xml = fetch_url($url);
347         $headers = $a->get_curl_headers();
348
349         if (! $xml)
350                 return array();
351
352         logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
353
354         $h = parse_xml_string($xml);
355         if(! $h)
356                 return array();
357
358         $arr = convert_xml_element_to_array($h);
359
360         if(isset($arr['xrd']['property'])) {
361                 $property = $arr['crd']['property'];
362                 if(! isset($property[0]))
363                         $properties = array($property);
364                 else
365                         $properties = $property;
366                 foreach($properties as $prop)
367                         if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
368                                 $priority = 'resource';
369         } 
370
371         // save the links in case we need them
372
373         $links = array();
374
375         if(isset($arr['xrd']['link'])) {
376                 $link = $arr['xrd']['link'];
377                 if(! isset($link[0]))
378                         $links = array($link);
379                 else
380                         $links = $link;
381         }
382
383         // do we have a template or href?
384
385         if(count($links)) {
386                 foreach($links as $link) {
387                         if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
388                                 if(x($link['@attributes'],'template'))
389                                         $tpl = $link['@attributes']['template'];
390                                 elseif(x($link['@attributes'],'href'))
391                                         $href = $link['@attributes']['href'];
392                         }
393                 }               
394         }
395
396         if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
397                 $tpl = '';
398
399         if($priority === 'host') {
400                 if(strlen($tpl)) 
401                         $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
402                 elseif(isset($href))
403                         $pxrd = $href;
404                 if(isset($pxrd)) {
405                         logger('lrdd: (host priority) pxrd: ' . $pxrd);
406                         $links = fetch_xrd_links($pxrd);
407                         return $links;
408                 }
409
410                 $lines = explode("\n",$headers);
411                 if(count($lines)) {
412                         foreach($lines as $line) {                              
413                                 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
414                                         return(fetch_xrd_links($matches[1]));
415                                         break;
416                                 }
417                         }
418                 }
419         }
420
421
422         // priority 'resource'
423
424
425         $html = fetch_url($uri);
426         $headers = $a->get_curl_headers();
427         logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
428
429         // don't try and parse raw xml as html
430         if(! strstr($html,'<?xml')) {
431                 require_once('library/HTML5/Parser.php');
432                 $dom = @HTML5_Parser::parse($html);
433
434                 if($dom) {
435                         $items = $dom->getElementsByTagName('link');
436                         foreach($items as $item) {
437                                 $x = $item->getAttribute('rel');
438                                 if($x == "lrdd") {
439                                         $pagelink = $item->getAttribute('href');
440                                         break;
441                                 }
442                         }
443                 }
444         }
445
446         if(isset($pagelink))
447                 return(fetch_xrd_links($pagelink));
448
449         // next look in HTTP headers
450
451         $lines = explode("\n",$headers);
452         if(count($lines)) {
453                 foreach($lines as $line) {                              
454                         // TODO alter the following regex to support multiple relations (space separated)
455                         if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
456                                 $pagelink = $matches[1];
457                                 break;
458                         }
459                         // don't try and run feeds through the html5 parser
460                         if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
461                                 return array();
462                         if(stristr($html,'<rss') || stristr($html,'<feed'))
463                                 return array();
464                 }
465         }
466
467         if(isset($pagelink))
468                 return(fetch_xrd_links($pagelink));
469
470         // If we haven't found any links, return the host xrd links (which we have already fetched)
471
472         if(isset($links))
473                 return $links;
474
475         return array();
476
477 }}
478
479
480
481 // Given a host name, locate the LRDD template from that
482 // host. Returns the LRDD template or an empty string on
483 // error/failure.
484
485 if(! function_exists('fetch_lrdd_template')) {
486 function fetch_lrdd_template($host) {
487         $tpl = '';
488
489         $url1 = 'https://' . $host . '/.well-known/host-meta' ;
490         $url2 = 'http://' . $host . '/.well-known/host-meta' ;
491         $links = fetch_xrd_links($url1);
492         logger('fetch_lrdd_template from: ' . $url1);
493         logger('template (https): ' . print_r($links,true));
494         if(! count($links)) {
495                 logger('fetch_lrdd_template from: ' . $url2);
496                 $links = fetch_xrd_links($url2);
497                 logger('template (http): ' . print_r($links,true));
498         }
499         if(count($links)) {
500                 foreach($links as $link)
501                         if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
502                                 $tpl = $link['@attributes']['template'];
503         }
504         if(! strpos($tpl,'{uri}'))
505                 $tpl = '';
506         return $tpl;
507 }}
508
509 // Given a URL, retrieve the page as an XRD document.
510 // Return an array of links.
511 // on error/failure return empty array.
512
513 if(! function_exists('fetch_xrd_links')) {
514 function fetch_xrd_links($url) {
515
516         $xrd_timeout = intval(get_config('system','xrd_timeout'));
517         $redirects = 0;
518         $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
519
520         logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
521
522         if ((! $xml) || (! stristr($xml,'<xrd')))
523                 return array();
524
525         $h = parse_xml_string($xml);
526         if(! $h)
527                 return array();
528
529         $arr = convert_xml_element_to_array($h);
530
531         $links = array();
532
533         if(isset($arr['xrd']['link'])) {
534                 $link = $arr['xrd']['link'];
535                 if(! isset($link[0]))
536                         $links = array($link);
537                 else
538                         $links = $link;
539         }
540         if(isset($arr['xrd']['alias'])) {
541                 $alias = $arr['xrd']['alias'];
542                 if(! isset($alias[0]))
543                         $aliases = array($alias);
544                 else
545                         $aliases = $alias;
546                 if(is_array($aliases) && count($aliases)) {
547                         foreach($aliases as $alias) {
548                                 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
549                         }
550                 }
551         }
552
553         logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
554
555         return $links;
556
557 }}
558
559
560 // Take a URL from the wild, prepend http:// if necessary
561 // and check DNS to see if it's real
562 // return true if it's OK, false if something is wrong with it
563
564 if(! function_exists('validate_url')) {
565 function validate_url(&$url) {
566         if(substr($url,0,4) != 'http')
567                 $url = 'http://' . $url;
568         $h = @parse_url($url);
569
570         if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
571                 return true;
572         }
573         return false;
574 }}
575
576 // checks that email is an actual resolvable internet address
577
578 if(! function_exists('validate_email')) {
579 function validate_email($addr) {
580
581         if(! strpos($addr,'@'))
582                 return false;
583         $h = substr($addr,strpos($addr,'@') + 1);
584
585         if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
586                 return true;
587         }
588         return false;
589 }}
590
591 // Check $url against our list of allowed sites,
592 // wildcards allowed. If allowed_sites is unset return true;
593 // If url is allowed, return true.
594 // otherwise, return false
595
596 if(! function_exists('allowed_url')) {
597 function allowed_url($url) {
598
599         $h = @parse_url($url);
600
601         if(! $h) {
602                 return false;
603         }
604
605         $str_allowed = get_config('system','allowed_sites');
606         if(! $str_allowed)
607                 return true;
608
609         $found = false;
610
611         $host = strtolower($h['host']);
612
613         // always allow our own site
614
615         if($host == strtolower($_SERVER['SERVER_NAME']))
616                 return true;
617
618         $fnmatch = function_exists('fnmatch');
619         $allowed = explode(',',$str_allowed);
620
621         if(count($allowed)) {
622                 foreach($allowed as $a) {
623                         $pat = strtolower(trim($a));
624                         if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
625                                 $found = true; 
626                                 break;
627                         }
628                 }
629         }
630         return $found;
631 }}
632
633 // check if email address is allowed to register here.
634 // Compare against our list (wildcards allowed).
635 // Returns false if not allowed, true if allowed or if
636 // allowed list is not configured.
637
638 if(! function_exists('allowed_email')) {
639 function allowed_email($email) {
640
641
642         $domain = strtolower(substr($email,strpos($email,'@') + 1));
643         if(! $domain)
644                 return false;
645
646         $str_allowed = get_config('system','allowed_email');
647         if(! $str_allowed)
648                 return true;
649
650         $found = false;
651
652         $fnmatch = function_exists('fnmatch');
653         $allowed = explode(',',$str_allowed);
654
655         if(count($allowed)) {
656                 foreach($allowed as $a) {
657                         $pat = strtolower(trim($a));
658                         if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
659                                 $found = true; 
660                                 break;
661                         }
662                 }
663         }
664         return $found;
665 }}
666
667
668 if(! function_exists('gravatar_img')) {
669 function gravatar_img($email) {
670         $size = 175;
671         $opt = 'identicon';   // psuedo-random geometric pattern if not found
672         $rating = 'pg';
673         $hash = md5(trim(strtolower($email)));
674         
675         $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg' 
676                 . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
677
678         logger('gravatar: ' . $email . ' ' . $url);
679         return $url;
680 }}
681
682
683 if(! function_exists('parse_xml_string')) {
684 function parse_xml_string($s,$strict = true) {
685         if($strict) {
686                 if(! strstr($s,'<?xml'))
687                         return false;
688                 $s2 = substr($s,strpos($s,'<?xml'));
689         }
690         else
691                 $s2 = $s;
692         libxml_use_internal_errors(true);
693
694         $x = @simplexml_load_string($s2);
695         if(! $x) {
696                 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
697                 foreach(libxml_get_errors() as $err)
698                         logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
699                 libxml_clear_errors();
700         }
701         return $x;
702 }}
703
704 function add_fcontact($arr) {
705
706         $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
707                 `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
708                 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
709                 dbesc($arr['url']),
710                 dbesc($arr['name']),
711                 dbesc($arr['photo']),
712                 dbesc($arr['request']),
713                 dbesc($arr['nick']),
714                 dbesc($arr['addr']),
715                 dbesc($arr['notify']),
716                 dbesc($arr['poll']),
717                 dbesc($arr['confirm']),
718                 dbesc($arr['network']),
719                 dbesc($arr['alias']),
720                 dbesc($arr['pubkey']),
721                 dbesc(datetime_convert())
722         );
723         return $r;
724 }