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";
185 // convert an XML document to a normalised, case-corrected array
188 if(! function_exists('convert_xml_element_to_array')) {
189 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
191 // If we're getting too deep, bail out
192 if ($recursion_depth > 512) {
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);
203 if (is_array($xml_element)) {
204 $result_array = array();
205 if (count($xml_element) <= 0) {
206 return (trim(strval($xml_element_copy)));
209 foreach($xml_element as $key=>$value) {
212 $result_array[strtolower($key)] =
213 convert_xml_element_to_array($value, $recursion_depth);
216 if ($recursion_depth == 0) {
217 $temp_array = $result_array;
218 $result_array = array(
219 strtolower($xml_element_copy->getName()) => $temp_array,
223 return ($result_array);
226 return (trim(strval($xml_element)));
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.
239 if(! function_exists('webfinger_dfrn')) {
240 function webfinger_dfrn($s) {
241 if(! strstr($s,'@')) {
244 $links = webfinger($s);
245 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
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'];
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.
262 if(! function_exists('webfinger')) {
263 function webfinger($s) {
266 $host = substr($s,strpos($s,'@') + 1);
269 $tpl = fetch_lrdd_template($host);
270 logger('webfinger: lrdd template: ' . $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);
287 if(! function_exists('lrdd')) {
288 function lrdd($uri) {
292 // default priority is host priority, host-meta first
296 // All we have is an email address. Resource-priority is irrelevant
297 // because our URI isn't directly resolvable.
299 if(strstr($uri,'@')) {
300 return(webfinger($uri));
303 // get the host meta file
305 $host = @parse_url($uri);
308 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
309 $url .= $host['host'] . '/.well-known/host-meta' ;
314 logger('lrdd: constructed url: ' . $url);
316 $xml = fetch_url($url);
317 $headers = $a->get_curl_headers();
322 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
324 $h = parse_xml_string($xml);
328 $arr = convert_xml_element_to_array($h);
330 if(isset($arr['xrd']['property'])) {
331 $property = $arr['crd']['property'];
332 if(! isset($property[0]))
333 $properties = array($property);
335 $properties = $property;
336 foreach($properties as $prop)
337 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
338 $priority = 'resource';
341 // save the links in case we need them
345 if(isset($arr['xrd']['link'])) {
346 $link = $arr['xrd']['link'];
347 if(! isset($link[0]))
348 $links = array($link);
353 // do we have a template or href?
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'];
366 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
369 if($priority === 'host') {
371 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
375 logger('lrdd: (host priority) pxrd: ' . $pxrd);
376 $links = fetch_xrd_links($pxrd);
380 $lines = explode("\n",$headers);
382 foreach($lines as $line) {
383 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
384 return(fetch_xrd_links($matches[1]));
392 // priority 'resource'
395 $html = fetch_url($uri);
396 $headers = $a->get_curl_headers();
397 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
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);
405 $items = $dom->getElementsByTagName('link');
406 foreach($items as $item) {
407 $x = $item->getAttribute('rel');
409 $pagelink = $item->getAttribute('href');
417 return(fetch_xrd_links($pagelink));
419 // next look in HTTP headers
421 $lines = explode("\n",$headers);
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];
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'))))
432 if(stristr($html,'<rss') || stristr($html,'<feed'))
438 return(fetch_xrd_links($pagelink));
440 // If we haven't found any links, return the host xrd links (which we have already fetched)
451 // Given a host name, locate the LRDD template from that
452 // host. Returns the LRDD template or an empty string on
455 if(! function_exists('fetch_lrdd_template')) {
456 function fetch_lrdd_template($host) {
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));
470 foreach($links as $link)
471 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
472 $tpl = $link['@attributes']['template'];
474 if(! strpos($tpl,'{uri}'))
479 // Given a URL, retrieve the page as an XRD document.
480 // Return an array of links.
481 // on error/failure return empty array.
483 if(! function_exists('fetch_xrd_links')) {
484 function fetch_xrd_links($url) {
487 $xml = fetch_url($url);
489 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
491 if ((! $xml) || (! stristr($xml,'<xrd')))
494 $h = parse_xml_string($xml);
498 $arr = convert_xml_element_to_array($h);
502 if(isset($arr['xrd']['link'])) {
503 $link = $arr['xrd']['link'];
504 if(! isset($link[0]))
505 $links = array($link);
509 if(isset($arr['xrd']['alias'])) {
510 $alias = $arr['xrd']['alias'];
511 if(! isset($alias[0]))
512 $aliases = array($alias);
515 foreach($aliases as $alias) {
516 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
520 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
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
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);
537 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
543 // checks that email is an actual resolvable internet address
545 if(! function_exists('validate_email')) {
546 function validate_email($addr) {
548 if(! strpos($addr,'@'))
550 $h = substr($addr,strpos($addr,'@') + 1);
552 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
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
563 if(! function_exists('allowed_url')) {
564 function allowed_url($url) {
566 $h = @parse_url($url);
572 $str_allowed = get_config('system','allowed_sites');
578 $host = strtolower($h['host']);
580 // always allow our own site
582 if($host == strtolower($_SERVER['SERVER_NAME']))
585 $fnmatch = function_exists('fnmatch');
586 $allowed = explode(',',$str_allowed);
588 if(count($allowed)) {
589 foreach($allowed as $a) {
590 $pat = strtolower(trim($a));
591 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
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.
605 if(! function_exists('allowed_email')) {
606 function allowed_email($email) {
609 $domain = strtolower(substr($email,strpos($email,'@') + 1));
613 $str_allowed = get_config('system','allowed_email');
619 $fnmatch = function_exists('fnmatch');
620 $allowed = explode(',',$str_allowed);
622 if(count($allowed)) {
623 foreach($allowed as $a) {
624 $pat = strtolower(trim($a));
625 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
635 if(! function_exists('gravatar_img')) {
636 function gravatar_img($email) {
638 $opt = 'identicon'; // psuedo-random geometric pattern if not found
640 $hash = md5(trim(strtolower($email)));
642 $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg'
643 . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
645 logger('gravatar: ' . $email . ' ' . $url);
650 if(! function_exists('parse_xml_string')) {
651 function parse_xml_string($s,$strict = true) {
653 if(! strstr($s,'<?xml'))
655 $s2 = substr($s,strpos($s,'<?xml'));
659 libxml_use_internal_errors(true);
661 $x = @simplexml_load_string($s2);
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();