]> git.mxchange.org Git - friendica.git/blob - include/network.php
breaking up boot file (part of zot refactor)
[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
185 // convert an XML document to a normalised, case-corrected array
186 // used by webfinger
187
188 if(! function_exists('convert_xml_element_to_array')) {
189 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
190
191         // If we're getting too deep, bail out
192         if ($recursion_depth > 512) {
193                 return(null);
194         }
195
196         if (!is_string($xml_element) &&
197         !is_array($xml_element) &&
198         (get_class($xml_element) == 'SimpleXMLElement')) {
199                 $xml_element_copy = $xml_element;
200                 $xml_element = get_object_vars($xml_element);
201         }
202
203         if (is_array($xml_element)) {
204                 $result_array = array();
205                 if (count($xml_element) <= 0) {
206                         return (trim(strval($xml_element_copy)));
207                 }
208
209                 foreach($xml_element as $key=>$value) {
210
211                         $recursion_depth++;
212                         $result_array[strtolower($key)] =
213                 convert_xml_element_to_array($value, $recursion_depth);
214                         $recursion_depth--;
215                 }
216                 if ($recursion_depth == 0) {
217                         $temp_array = $result_array;
218                         $result_array = array(
219                                 strtolower($xml_element_copy->getName()) => $temp_array,
220                         );
221                 }
222
223                 return ($result_array);
224
225         } else {
226                 return (trim(strval($xml_element)));
227         }
228 }}
229
230 // Given an email style address, perform webfinger lookup and 
231 // return the resulting DFRN profile URL, or if no DFRN profile URL
232 // is located, returns an OStatus subscription template (prefixed 
233 // with the string 'stat:' to identify it as on OStatus template).
234 // If this isn't an email style address just return $s.
235 // Return an empty string if email-style addresses but webfinger fails,
236 // or if the resultant personal XRD doesn't contain a supported 
237 // subscription/friend-request attribute.
238
239 if(! function_exists('webfinger_dfrn')) {
240 function webfinger_dfrn($s) {
241         if(! strstr($s,'@')) {
242                 return $s;
243         }
244         $links = webfinger($s);
245         logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
246         if(count($links)) {
247                 foreach($links as $link)
248                         if($link['@attributes']['rel'] === NAMESPACE_DFRN)
249                                 return $link['@attributes']['href'];
250                 foreach($links as $link)
251                         if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
252                                 return 'stat:' . $link['@attributes']['template'];              
253         }
254         return '';
255 }}
256
257 // Given an email style address, perform webfinger lookup and 
258 // return the array of link attributes from the personal XRD file.
259 // On error/failure return an empty array.
260
261
262 if(! function_exists('webfinger')) {
263 function webfinger($s) {
264         $host = '';
265         if(strstr($s,'@')) {
266                 $host = substr($s,strpos($s,'@') + 1);
267         }
268         if(strlen($host)) {
269                 $tpl = fetch_lrdd_template($host);
270                 logger('webfinger: lrdd template: ' . $tpl);
271                 if(strlen($tpl)) {
272                         $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
273                         logger('webfinger: pxrd: ' . $pxrd);
274                         $links = fetch_xrd_links($pxrd);
275                         if(! count($links)) {
276                                 // try with double slashes
277                                 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
278                                 logger('webfinger: pxrd: ' . $pxrd);
279                                 $links = fetch_xrd_links($pxrd);
280                         }
281                         return $links;
282                 }
283         }
284         return array();
285 }}
286
287 if(! function_exists('lrdd')) {
288 function lrdd($uri) {
289
290         $a = get_app();
291
292         // default priority is host priority, host-meta first
293
294         $priority = 'host';
295
296         // All we have is an email address. Resource-priority is irrelevant
297         // because our URI isn't directly resolvable.
298
299         if(strstr($uri,'@')) {  
300                 return(webfinger($uri));
301         }
302
303         // get the host meta file
304
305         $host = @parse_url($uri);
306
307         if($host) {
308                 $url  = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
309                 $url .= $host['host'] . '/.well-known/host-meta' ;
310         }
311         else
312                 return array();
313
314         logger('lrdd: constructed url: ' . $url);
315
316         $xml = fetch_url($url);
317         $headers = $a->get_curl_headers();
318
319         if (! $xml)
320                 return array();
321
322         logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
323
324         $h = parse_xml_string($xml);
325         if(! $h)
326                 return array();
327
328         $arr = convert_xml_element_to_array($h);
329
330         if(isset($arr['xrd']['property'])) {
331                 $property = $arr['crd']['property'];
332                 if(! isset($property[0]))
333                         $properties = array($property);
334                 else
335                         $properties = $property;
336                 foreach($properties as $prop)
337                         if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
338                                 $priority = 'resource';
339         } 
340
341         // save the links in case we need them
342
343         $links = array();
344
345         if(isset($arr['xrd']['link'])) {
346                 $link = $arr['xrd']['link'];
347                 if(! isset($link[0]))
348                         $links = array($link);
349                 else
350                         $links = $link;
351         }
352
353         // do we have a template or href?
354
355         if(count($links)) {
356                 foreach($links as $link) {
357                         if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
358                                 if(x($link['@attributes'],'template'))
359                                         $tpl = $link['@attributes']['template'];
360                                 elseif(x($link['@attributes'],'href'))
361                                         $href = $link['@attributes']['href'];
362                         }
363                 }               
364         }
365
366         if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
367                 $tpl = '';
368
369         if($priority === 'host') {
370                 if(strlen($tpl)) 
371                         $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
372                 elseif(isset($href))
373                         $pxrd = $href;
374                 if(isset($pxrd)) {
375                         logger('lrdd: (host priority) pxrd: ' . $pxrd);
376                         $links = fetch_xrd_links($pxrd);
377                         return $links;
378                 }
379
380                 $lines = explode("\n",$headers);
381                 if(count($lines)) {
382                         foreach($lines as $line) {                              
383                                 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
384                                         return(fetch_xrd_links($matches[1]));
385                                         break;
386                                 }
387                         }
388                 }
389         }
390
391
392         // priority 'resource'
393
394
395         $html = fetch_url($uri);
396         $headers = $a->get_curl_headers();
397         logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
398
399         // don't try and parse raw xml as html
400         if(! strstr($html,'<?xml')) {
401                 require_once('library/HTML5/Parser.php');
402                 $dom = @HTML5_Parser::parse($html);
403
404                 if($dom) {
405                         $items = $dom->getElementsByTagName('link');
406                         foreach($items as $item) {
407                                 $x = $item->getAttribute('rel');
408                                 if($x == "lrdd") {
409                                         $pagelink = $item->getAttribute('href');
410                                         break;
411                                 }
412                         }
413                 }
414         }
415
416         if(isset($pagelink))
417                 return(fetch_xrd_links($pagelink));
418
419         // next look in HTTP headers
420
421         $lines = explode("\n",$headers);
422         if(count($lines)) {
423                 foreach($lines as $line) {                              
424                         // TODO alter the following regex to support multiple relations (space separated)
425                         if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
426                                 $pagelink = $matches[1];
427                                 break;
428                         }
429                         // don't try and run feeds through the html5 parser
430                         if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
431                                 return array();
432                         if(stristr($html,'<rss') || stristr($html,'<feed'))
433                                 return array();
434                 }
435         }
436
437         if(isset($pagelink))
438                 return(fetch_xrd_links($pagelink));
439
440         // If we haven't found any links, return the host xrd links (which we have already fetched)
441
442         if(isset($links))
443                 return $links;
444
445         return array();
446
447 }}
448
449
450
451 // Given a host name, locate the LRDD template from that
452 // host. Returns the LRDD template or an empty string on
453 // error/failure.
454
455 if(! function_exists('fetch_lrdd_template')) {
456 function fetch_lrdd_template($host) {
457         $tpl = '';
458
459         $url1 = 'https://' . $host . '/.well-known/host-meta' ;
460         $url2 = 'http://' . $host . '/.well-known/host-meta' ;
461         $links = fetch_xrd_links($url1);
462         logger('fetch_lrdd_template from: ' . $url1);
463         logger('template (https): ' . print_r($links,true));
464         if(! count($links)) {
465                 logger('fetch_lrdd_template from: ' . $url2);
466                 $links = fetch_xrd_links($url2);
467                 logger('template (http): ' . print_r($links,true));
468         }
469         if(count($links)) {
470                 foreach($links as $link)
471                         if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
472                                 $tpl = $link['@attributes']['template'];
473         }
474         if(! strpos($tpl,'{uri}'))
475                 $tpl = '';
476         return $tpl;
477 }}
478
479 // Given a URL, retrieve the page as an XRD document.
480 // Return an array of links.
481 // on error/failure return empty array.
482
483 if(! function_exists('fetch_xrd_links')) {
484 function fetch_xrd_links($url) {
485
486
487         $xml = fetch_url($url);
488
489         logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
490
491         if ((! $xml) || (! stristr($xml,'<xrd')))
492                 return array();
493
494         $h = parse_xml_string($xml);
495         if(! $h)
496                 return array();
497
498         $arr = convert_xml_element_to_array($h);
499
500         $links = array();
501
502         if(isset($arr['xrd']['link'])) {
503                 $link = $arr['xrd']['link'];
504                 if(! isset($link[0]))
505                         $links = array($link);
506                 else
507                         $links = $link;
508         }
509         if(isset($arr['xrd']['alias'])) {
510                 $alias = $arr['xrd']['alias'];
511                 if(! isset($alias[0]))
512                         $aliases = array($alias);
513                 else
514                         $aliases = $alias;
515                 foreach($aliases as $alias) {
516                         $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
517                 }
518         }
519
520         logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
521
522         return $links;
523
524 }}
525
526
527 // Take a URL from the wild, prepend http:// if necessary
528 // and check DNS to see if it's real
529 // return true if it's OK, false if something is wrong with it
530
531 if(! function_exists('validate_url')) {
532 function validate_url(&$url) {
533         if(substr($url,0,4) != 'http')
534                 $url = 'http://' . $url;
535         $h = @parse_url($url);
536
537         if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
538                 return true;
539         }
540         return false;
541 }}
542
543 // checks that email is an actual resolvable internet address
544
545 if(! function_exists('validate_email')) {
546 function validate_email($addr) {
547
548         if(! strpos($addr,'@'))
549                 return false;
550         $h = substr($addr,strpos($addr,'@') + 1);
551
552         if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
553                 return true;
554         }
555         return false;
556 }}
557
558 // Check $url against our list of allowed sites,
559 // wildcards allowed. If allowed_sites is unset return true;
560 // If url is allowed, return true.
561 // otherwise, return false
562
563 if(! function_exists('allowed_url')) {
564 function allowed_url($url) {
565
566         $h = @parse_url($url);
567
568         if(! $h) {
569                 return false;
570         }
571
572         $str_allowed = get_config('system','allowed_sites');
573         if(! $str_allowed)
574                 return true;
575
576         $found = false;
577
578         $host = strtolower($h['host']);
579
580         // always allow our own site
581
582         if($host == strtolower($_SERVER['SERVER_NAME']))
583                 return true;
584
585         $fnmatch = function_exists('fnmatch');
586         $allowed = explode(',',$str_allowed);
587
588         if(count($allowed)) {
589                 foreach($allowed as $a) {
590                         $pat = strtolower(trim($a));
591                         if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
592                                 $found = true; 
593                                 break;
594                         }
595                 }
596         }
597         return $found;
598 }}
599
600 // check if email address is allowed to register here.
601 // Compare against our list (wildcards allowed).
602 // Returns false if not allowed, true if allowed or if
603 // allowed list is not configured.
604
605 if(! function_exists('allowed_email')) {
606 function allowed_email($email) {
607
608
609         $domain = strtolower(substr($email,strpos($email,'@') + 1));
610         if(! $domain)
611                 return false;
612
613         $str_allowed = get_config('system','allowed_email');
614         if(! $str_allowed)
615                 return true;
616
617         $found = false;
618
619         $fnmatch = function_exists('fnmatch');
620         $allowed = explode(',',$str_allowed);
621
622         if(count($allowed)) {
623                 foreach($allowed as $a) {
624                         $pat = strtolower(trim($a));
625                         if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
626                                 $found = true; 
627                                 break;
628                         }
629                 }
630         }
631         return $found;
632 }}
633
634
635 if(! function_exists('gravatar_img')) {
636 function gravatar_img($email) {
637         $size = 175;
638         $opt = 'identicon';   // psuedo-random geometric pattern if not found
639         $rating = 'pg';
640         $hash = md5(trim(strtolower($email)));
641         
642         $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg' 
643                 . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
644
645         logger('gravatar: ' . $email . ' ' . $url);
646         return $url;
647 }}
648
649
650 if(! function_exists('parse_xml_string')) {
651 function parse_xml_string($s,$strict = true) {
652         if($strict) {
653                 if(! strstr($s,'<?xml'))
654                         return false;
655                 $s2 = substr($s,strpos($s,'<?xml'));
656         }
657         else
658                 $s2 = $s;
659         libxml_use_internal_errors(true);
660
661         $x = @simplexml_load_string($s2);
662         if(! $x) {
663                 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
664                 foreach(libxml_get_errors() as $err)
665                         logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
666                 libxml_clear_errors();
667         }
668         return $x;
669 }}