4 // curl wrapper. If binary flag is true, return binary
7 if(! function_exists('fetch_url')) {
8 function fetch_url($url,$binary = false, &$redirects = 0) {
12 $ch = curl_init($url);
13 if(($redirects > 8) || (! $ch))
16 curl_setopt($ch, CURLOPT_HEADER, true);
17 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
18 curl_setopt($ch, CURLOPT_USERAGENT, "Friendika");
20 $curl_time = intval(get_config('system','curl_timeout'));
21 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
23 // by default we will allow self-signed certs
24 // but you can override this
26 $check_cert = get_config('system','verifyssl');
27 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
29 $prx = get_config('system','proxy');
31 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
32 curl_setopt($ch, CURLOPT_PROXY, $prx);
33 $prxusr = get_config('system','proxyuser');
35 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
38 curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
42 // don't let curl abort the entire application
43 // if it throws any errors.
48 $curl_info = curl_getinfo($ch);
49 $http_code = $curl_info['http_code'];
53 // Pull out multiple headers, e.g. proxy and continuation headers
54 // allow for HTTP/2.x without fixing code
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);
59 $base = substr($base,strlen($chunk));
62 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
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)) {
69 return fetch_url($url,$binary,$redirects);
73 $a->set_curl_code($http_code);
75 $body = substr($s,strlen($header));
77 $a->set_curl_headers($header);
83 // post request to $url. $params is an array of post variables.
85 if(! function_exists('post_url')) {
86 function post_url($url,$params, $headers = null, &$redirects = 0) {
88 $ch = curl_init($url);
89 if(($redirects > 8) || (! $ch))
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");
98 $curl_time = intval(get_config('system','curl_timeout'));
99 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
101 if(defined('LIGHTTPD')) {
102 if(!is_array($headers)) {
103 $headers = array('Expect:');
105 if(!in_array('Expect:', $headers)) {
106 array_push($headers, 'Expect:');
111 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
113 $check_cert = get_config('system','verifyssl');
114 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
115 $prx = get_config('system','proxy');
117 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
118 curl_setopt($ch, CURLOPT_PROXY, $prx);
119 $prxusr = get_config('system','proxyuser');
121 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
124 $a->set_curl_code(0);
126 // don't let curl abort the entire application
127 // if it throws any errors.
129 $s = @curl_exec($ch);
132 $curl_info = curl_getinfo($ch);
133 $http_code = $curl_info['http_code'];
137 // Pull out multiple headers, e.g. proxy and continuation headers
138 // allow for HTTP/2.x without fixing code
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);
143 $base = substr($base,strlen($chunk));
146 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
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)) {
153 return post_url($url,$binary,$headers,$redirects);
156 $a->set_curl_code($http_code);
157 $body = substr($s,strlen($header));
159 $a->set_curl_headers($header);
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.
169 if(! function_exists('xml_status')) {
170 function xml_status($st, $message = '') {
172 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
175 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
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";
184 if(! function_exists('http_status_exit')) {
185 function http_status_exit($val) {
189 if($val >= 200 && $val < 300)
192 logger('http_status_exit ' . $val);
193 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
199 // convert an XML document to a normalised, case-corrected array
202 if(! function_exists('convert_xml_element_to_array')) {
203 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
205 // If we're getting too deep, bail out
206 if ($recursion_depth > 512) {
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);
217 if (is_array($xml_element)) {
218 $result_array = array();
219 if (count($xml_element) <= 0) {
220 return (trim(strval($xml_element_copy)));
223 foreach($xml_element as $key=>$value) {
226 $result_array[strtolower($key)] =
227 convert_xml_element_to_array($value, $recursion_depth);
230 if ($recursion_depth == 0) {
231 $temp_array = $result_array;
232 $result_array = array(
233 strtolower($xml_element_copy->getName()) => $temp_array,
237 return ($result_array);
240 return (trim(strval($xml_element)));
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.
253 if(! function_exists('webfinger_dfrn')) {
254 function webfinger_dfrn($s) {
255 if(! strstr($s,'@')) {
258 $links = webfinger($s);
259 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
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'];
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.
276 if(! function_exists('webfinger')) {
277 function webfinger($s) {
280 $host = substr($s,strpos($s,'@') + 1);
283 $tpl = fetch_lrdd_template($host);
284 logger('webfinger: lrdd template: ' . $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);
301 if(! function_exists('lrdd')) {
302 function lrdd($uri) {
306 // default priority is host priority, host-meta first
310 // All we have is an email address. Resource-priority is irrelevant
311 // because our URI isn't directly resolvable.
313 if(strstr($uri,'@')) {
314 return(webfinger($uri));
317 // get the host meta file
319 $host = @parse_url($uri);
322 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
323 $url .= $host['host'] . '/.well-known/host-meta' ;
328 logger('lrdd: constructed url: ' . $url);
330 $xml = fetch_url($url);
331 $headers = $a->get_curl_headers();
336 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
338 $h = parse_xml_string($xml);
342 $arr = convert_xml_element_to_array($h);
344 if(isset($arr['xrd']['property'])) {
345 $property = $arr['crd']['property'];
346 if(! isset($property[0]))
347 $properties = array($property);
349 $properties = $property;
350 foreach($properties as $prop)
351 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
352 $priority = 'resource';
355 // save the links in case we need them
359 if(isset($arr['xrd']['link'])) {
360 $link = $arr['xrd']['link'];
361 if(! isset($link[0]))
362 $links = array($link);
367 // do we have a template or href?
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'];
380 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
383 if($priority === 'host') {
385 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
389 logger('lrdd: (host priority) pxrd: ' . $pxrd);
390 $links = fetch_xrd_links($pxrd);
394 $lines = explode("\n",$headers);
396 foreach($lines as $line) {
397 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
398 return(fetch_xrd_links($matches[1]));
406 // priority 'resource'
409 $html = fetch_url($uri);
410 $headers = $a->get_curl_headers();
411 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
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);
419 $items = $dom->getElementsByTagName('link');
420 foreach($items as $item) {
421 $x = $item->getAttribute('rel');
423 $pagelink = $item->getAttribute('href');
431 return(fetch_xrd_links($pagelink));
433 // next look in HTTP headers
435 $lines = explode("\n",$headers);
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];
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'))))
446 if(stristr($html,'<rss') || stristr($html,'<feed'))
452 return(fetch_xrd_links($pagelink));
454 // If we haven't found any links, return the host xrd links (which we have already fetched)
465 // Given a host name, locate the LRDD template from that
466 // host. Returns the LRDD template or an empty string on
469 if(! function_exists('fetch_lrdd_template')) {
470 function fetch_lrdd_template($host) {
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));
484 foreach($links as $link)
485 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
486 $tpl = $link['@attributes']['template'];
488 if(! strpos($tpl,'{uri}'))
493 // Given a URL, retrieve the page as an XRD document.
494 // Return an array of links.
495 // on error/failure return empty array.
497 if(! function_exists('fetch_xrd_links')) {
498 function fetch_xrd_links($url) {
501 $xml = fetch_url($url);
503 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
505 if ((! $xml) || (! stristr($xml,'<xrd')))
508 $h = parse_xml_string($xml);
512 $arr = convert_xml_element_to_array($h);
516 if(isset($arr['xrd']['link'])) {
517 $link = $arr['xrd']['link'];
518 if(! isset($link[0]))
519 $links = array($link);
523 if(isset($arr['xrd']['alias'])) {
524 $alias = $arr['xrd']['alias'];
525 if(! isset($alias[0]))
526 $aliases = array($alias);
529 foreach($aliases as $alias) {
530 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
534 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
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
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);
551 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
557 // checks that email is an actual resolvable internet address
559 if(! function_exists('validate_email')) {
560 function validate_email($addr) {
562 if(! strpos($addr,'@'))
564 $h = substr($addr,strpos($addr,'@') + 1);
566 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
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
577 if(! function_exists('allowed_url')) {
578 function allowed_url($url) {
580 $h = @parse_url($url);
586 $str_allowed = get_config('system','allowed_sites');
592 $host = strtolower($h['host']);
594 // always allow our own site
596 if($host == strtolower($_SERVER['SERVER_NAME']))
599 $fnmatch = function_exists('fnmatch');
600 $allowed = explode(',',$str_allowed);
602 if(count($allowed)) {
603 foreach($allowed as $a) {
604 $pat = strtolower(trim($a));
605 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
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.
619 if(! function_exists('allowed_email')) {
620 function allowed_email($email) {
623 $domain = strtolower(substr($email,strpos($email,'@') + 1));
627 $str_allowed = get_config('system','allowed_email');
633 $fnmatch = function_exists('fnmatch');
634 $allowed = explode(',',$str_allowed);
636 if(count($allowed)) {
637 foreach($allowed as $a) {
638 $pat = strtolower(trim($a));
639 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
649 if(! function_exists('gravatar_img')) {
650 function gravatar_img($email) {
652 $opt = 'identicon'; // psuedo-random geometric pattern if not found
654 $hash = md5(trim(strtolower($email)));
656 $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg'
657 . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
659 logger('gravatar: ' . $email . ' ' . $url);
664 if(! function_exists('parse_xml_string')) {
665 function parse_xml_string($s,$strict = true) {
667 if(! strstr($s,'<?xml'))
669 $s2 = substr($s,strpos($s,'<?xml'));
673 libxml_use_internal_errors(true);
675 $x = @simplexml_load_string($s2);
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();