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, $timeout = 0, $accept_content=Null) {
12 $ch = @curl_init($url);
13 if(($redirects > 8) || (! $ch))
16 @curl_setopt($ch, CURLOPT_HEADER, true);
18 if (!is_null($accept_content)){
19 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
20 "Accept: "+$accept_content
24 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
25 @curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
28 if(intval($timeout)) {
29 @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
32 $curl_time = intval(get_config('system','curl_timeout'));
33 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
35 // by default we will allow self-signed certs
36 // but you can override this
38 $check_cert = get_config('system','verifyssl');
39 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
41 $prx = get_config('system','proxy');
43 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
44 @curl_setopt($ch, CURLOPT_PROXY, $prx);
45 $prxusr = @get_config('system','proxyuser');
47 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
50 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
54 // don't let curl abort the entire application
55 // if it throws any errors.
60 $curl_info = @curl_getinfo($ch);
61 $http_code = $curl_info['http_code'];
65 // Pull out multiple headers, e.g. proxy and continuation headers
66 // allow for HTTP/2.x without fixing code
68 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
69 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
71 $base = substr($base,strlen($chunk));
74 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
76 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
77 $url = trim(array_pop($matches));
78 $url_parsed = @parse_url($url);
79 if (isset($url_parsed)) {
81 return fetch_url($url,$binary,$redirects,$timeout);
85 $a->set_curl_code($http_code);
87 $body = substr($s,strlen($header));
89 $a->set_curl_headers($header);
95 // post request to $url. $params is an array of post variables.
97 if(! function_exists('post_url')) {
98 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
100 $ch = curl_init($url);
101 if(($redirects > 8) || (! $ch))
104 curl_setopt($ch, CURLOPT_HEADER, true);
105 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
106 curl_setopt($ch, CURLOPT_POST,1);
107 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
108 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
110 if(intval($timeout)) {
111 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
114 $curl_time = intval(get_config('system','curl_timeout'));
115 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
118 if(defined('LIGHTTPD')) {
119 if(!is_array($headers)) {
120 $headers = array('Expect:');
122 if(!in_array('Expect:', $headers)) {
123 array_push($headers, 'Expect:');
128 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
130 $check_cert = get_config('system','verifyssl');
131 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
132 $prx = get_config('system','proxy');
134 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
135 curl_setopt($ch, CURLOPT_PROXY, $prx);
136 $prxusr = get_config('system','proxyuser');
138 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
141 $a->set_curl_code(0);
143 // don't let curl abort the entire application
144 // if it throws any errors.
146 $s = @curl_exec($ch);
149 $curl_info = curl_getinfo($ch);
150 $http_code = $curl_info['http_code'];
154 // Pull out multiple headers, e.g. proxy and continuation headers
155 // allow for HTTP/2.x without fixing code
157 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
158 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
160 $base = substr($base,strlen($chunk));
163 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
165 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
166 $url = trim(array_pop($matches));
167 $url_parsed = @parse_url($url);
168 if (isset($url_parsed)) {
170 return post_url($url,$params,$headers,$redirects,$timeout);
173 $a->set_curl_code($http_code);
174 $body = substr($s,strlen($header));
176 $a->set_curl_headers($header);
182 // Generic XML return
183 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
184 // of $st and an optional text <message> of $message and terminates the current process.
186 if(! function_exists('xml_status')) {
187 function xml_status($st, $message = '') {
189 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
192 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
194 header( "Content-type: text/xml" );
195 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
196 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
201 if(! function_exists('http_status_exit')) {
202 function http_status_exit($val) {
206 if($val >= 200 && $val < 300)
209 logger('http_status_exit ' . $val);
210 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
216 // convert an XML document to a normalised, case-corrected array
219 if(! function_exists('convert_xml_element_to_array')) {
220 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
222 // If we're getting too deep, bail out
223 if ($recursion_depth > 512) {
227 if (!is_string($xml_element) &&
228 !is_array($xml_element) &&
229 (get_class($xml_element) == 'SimpleXMLElement')) {
230 $xml_element_copy = $xml_element;
231 $xml_element = get_object_vars($xml_element);
234 if (is_array($xml_element)) {
235 $result_array = array();
236 if (count($xml_element) <= 0) {
237 return (trim(strval($xml_element_copy)));
240 foreach($xml_element as $key=>$value) {
243 $result_array[strtolower($key)] =
244 convert_xml_element_to_array($value, $recursion_depth);
247 if ($recursion_depth == 0) {
248 $temp_array = $result_array;
249 $result_array = array(
250 strtolower($xml_element_copy->getName()) => $temp_array,
254 return ($result_array);
257 return (trim(strval($xml_element)));
261 // Given an email style address, perform webfinger lookup and
262 // return the resulting DFRN profile URL, or if no DFRN profile URL
263 // is located, returns an OStatus subscription template (prefixed
264 // with the string 'stat:' to identify it as on OStatus template).
265 // If this isn't an email style address just return $s.
266 // Return an empty string if email-style addresses but webfinger fails,
267 // or if the resultant personal XRD doesn't contain a supported
268 // subscription/friend-request attribute.
270 // amended 7/9/2011 to return an hcard which could save potentially loading
271 // a lengthy content page to scrape dfrn attributes
273 if(! function_exists('webfinger_dfrn')) {
274 function webfinger_dfrn($s,&$hcard) {
275 if(! strstr($s,'@')) {
280 $links = webfinger($s);
281 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
283 foreach($links as $link) {
284 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
285 $profile_link = $link['@attributes']['href'];
286 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
287 $profile_link = 'stat:' . $link['@attributes']['template'];
288 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
289 $hcard = $link['@attributes']['href'];
292 return $profile_link;
295 // Given an email style address, perform webfinger lookup and
296 // return the array of link attributes from the personal XRD file.
297 // On error/failure return an empty array.
300 if(! function_exists('webfinger')) {
301 function webfinger($s) {
304 $host = substr($s,strpos($s,'@') + 1);
307 $tpl = fetch_lrdd_template($host);
308 logger('webfinger: lrdd template: ' . $tpl);
310 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
311 logger('webfinger: pxrd: ' . $pxrd);
312 $links = fetch_xrd_links($pxrd);
313 if(! count($links)) {
314 // try with double slashes
315 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
316 logger('webfinger: pxrd: ' . $pxrd);
317 $links = fetch_xrd_links($pxrd);
325 if(! function_exists('lrdd')) {
326 function lrdd($uri) {
330 // default priority is host priority, host-meta first
334 // All we have is an email address. Resource-priority is irrelevant
335 // because our URI isn't directly resolvable.
337 if(strstr($uri,'@')) {
338 return(webfinger($uri));
341 // get the host meta file
343 $host = @parse_url($uri);
346 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
347 $url .= $host['host'] . '/.well-known/host-meta' ;
352 logger('lrdd: constructed url: ' . $url);
354 $xml = fetch_url($url);
355 $headers = $a->get_curl_headers();
360 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
362 $h = parse_xml_string($xml);
366 $arr = convert_xml_element_to_array($h);
368 if(isset($arr['xrd']['property'])) {
369 $property = $arr['crd']['property'];
370 if(! isset($property[0]))
371 $properties = array($property);
373 $properties = $property;
374 foreach($properties as $prop)
375 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
376 $priority = 'resource';
379 // save the links in case we need them
383 if(isset($arr['xrd']['link'])) {
384 $link = $arr['xrd']['link'];
385 if(! isset($link[0]))
386 $links = array($link);
391 // do we have a template or href?
394 foreach($links as $link) {
395 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
396 if(x($link['@attributes'],'template'))
397 $tpl = $link['@attributes']['template'];
398 elseif(x($link['@attributes'],'href'))
399 $href = $link['@attributes']['href'];
404 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
407 if($priority === 'host') {
409 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
413 logger('lrdd: (host priority) pxrd: ' . $pxrd);
414 $links = fetch_xrd_links($pxrd);
418 $lines = explode("\n",$headers);
420 foreach($lines as $line) {
421 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
422 return(fetch_xrd_links($matches[1]));
430 // priority 'resource'
433 $html = fetch_url($uri);
434 $headers = $a->get_curl_headers();
435 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
437 // don't try and parse raw xml as html
438 if(! strstr($html,'<?xml')) {
439 require_once('library/HTML5/Parser.php');
442 $dom = HTML5_Parser::parse($html);
443 } catch (DOMException $e) {
444 logger('lrdd: parse error: ' . $e);
448 $items = $dom->getElementsByTagName('link');
449 foreach($items as $item) {
450 $x = $item->getAttribute('rel');
452 $pagelink = $item->getAttribute('href');
460 return(fetch_xrd_links($pagelink));
462 // next look in HTTP headers
464 $lines = explode("\n",$headers);
466 foreach($lines as $line) {
467 // TODO alter the following regex to support multiple relations (space separated)
468 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
469 $pagelink = $matches[1];
472 // don't try and run feeds through the html5 parser
473 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
475 if(stristr($html,'<rss') || stristr($html,'<feed'))
481 return(fetch_xrd_links($pagelink));
483 // If we haven't found any links, return the host xrd links (which we have already fetched)
494 // Given a host name, locate the LRDD template from that
495 // host. Returns the LRDD template or an empty string on
498 if(! function_exists('fetch_lrdd_template')) {
499 function fetch_lrdd_template($host) {
502 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
503 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
504 $links = fetch_xrd_links($url1);
505 logger('fetch_lrdd_template from: ' . $url1);
506 logger('template (https): ' . print_r($links,true));
507 if(! count($links)) {
508 logger('fetch_lrdd_template from: ' . $url2);
509 $links = fetch_xrd_links($url2);
510 logger('template (http): ' . print_r($links,true));
513 foreach($links as $link)
514 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
515 $tpl = $link['@attributes']['template'];
517 if(! strpos($tpl,'{uri}'))
522 // Given a URL, retrieve the page as an XRD document.
523 // Return an array of links.
524 // on error/failure return empty array.
526 if(! function_exists('fetch_xrd_links')) {
527 function fetch_xrd_links($url) {
529 $xrd_timeout = intval(get_config('system','xrd_timeout'));
531 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
533 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
535 if ((! $xml) || (! stristr($xml,'<xrd')))
538 // fix diaspora's bad xml
539 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
541 $h = parse_xml_string($xml);
545 $arr = convert_xml_element_to_array($h);
549 if(isset($arr['xrd']['link'])) {
550 $link = $arr['xrd']['link'];
551 if(! isset($link[0]))
552 $links = array($link);
556 if(isset($arr['xrd']['alias'])) {
557 $alias = $arr['xrd']['alias'];
558 if(! isset($alias[0]))
559 $aliases = array($alias);
562 if(is_array($aliases) && count($aliases)) {
563 foreach($aliases as $alias) {
564 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
569 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
576 // Take a URL from the wild, prepend http:// if necessary
577 // and check DNS to see if it's real
578 // return true if it's OK, false if something is wrong with it
580 if(! function_exists('validate_url')) {
581 function validate_url(&$url) {
582 if(substr($url,0,4) != 'http')
583 $url = 'http://' . $url;
584 $h = @parse_url($url);
586 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
592 // checks that email is an actual resolvable internet address
594 if(! function_exists('validate_email')) {
595 function validate_email($addr) {
597 if(! strpos($addr,'@'))
599 $h = substr($addr,strpos($addr,'@') + 1);
601 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
607 // Check $url against our list of allowed sites,
608 // wildcards allowed. If allowed_sites is unset return true;
609 // If url is allowed, return true.
610 // otherwise, return false
612 if(! function_exists('allowed_url')) {
613 function allowed_url($url) {
615 $h = @parse_url($url);
621 $str_allowed = get_config('system','allowed_sites');
627 $host = strtolower($h['host']);
629 // always allow our own site
631 if($host == strtolower($_SERVER['SERVER_NAME']))
634 $fnmatch = function_exists('fnmatch');
635 $allowed = explode(',',$str_allowed);
637 if(count($allowed)) {
638 foreach($allowed as $a) {
639 $pat = strtolower(trim($a));
640 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
649 // check if email address is allowed to register here.
650 // Compare against our list (wildcards allowed).
651 // Returns false if not allowed, true if allowed or if
652 // allowed list is not configured.
654 if(! function_exists('allowed_email')) {
655 function allowed_email($email) {
658 $domain = strtolower(substr($email,strpos($email,'@') + 1));
662 $str_allowed = get_config('system','allowed_email');
668 $fnmatch = function_exists('fnmatch');
669 $allowed = explode(',',$str_allowed);
671 if(count($allowed)) {
672 foreach($allowed as $a) {
673 $pat = strtolower(trim($a));
674 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
684 if(! function_exists('gravatar_img')) {
685 function gravatar_img($email) {
687 $opt = 'identicon'; // psuedo-random geometric pattern if not found
689 $hash = md5(trim(strtolower($email)));
691 $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg'
692 . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
694 logger('gravatar: ' . $email . ' ' . $url);
699 if(! function_exists('parse_xml_string')) {
700 function parse_xml_string($s,$strict = true) {
702 if(! strstr($s,'<?xml'))
704 $s2 = substr($s,strpos($s,'<?xml'));
708 libxml_use_internal_errors(true);
710 $x = @simplexml_load_string($s2);
712 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
713 foreach(libxml_get_errors() as $err)
714 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
715 libxml_clear_errors();
720 function add_fcontact($arr,$update = false) {
723 $r = q("UPDATE `fcontact` SET
736 WHERE `url` = '%s' AND `network` = '%s' LIMIT 1",
738 dbesc($arr['photo']),
739 dbesc($arr['request']),
742 dbesc($arr['batch']),
743 dbesc($arr['notify']),
745 dbesc($arr['confirm']),
746 dbesc($arr['alias']),
747 dbesc($arr['pubkey']),
748 dbesc(datetime_convert()),
750 dbesc($arr['network'])
754 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
755 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
756 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
759 dbesc($arr['photo']),
760 dbesc($arr['request']),
763 dbesc($arr['batch']),
764 dbesc($arr['notify']),
766 dbesc($arr['confirm']),
767 dbesc($arr['network']),
768 dbesc($arr['alias']),
769 dbesc($arr['pubkey']),
770 dbesc(datetime_convert())