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) {
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 if(intval($timeout)) {
21 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
24 $curl_time = intval(get_config('system','curl_timeout'));
25 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
27 // by default we will allow self-signed certs
28 // but you can override this
30 $check_cert = get_config('system','verifyssl');
31 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
33 $prx = get_config('system','proxy');
35 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
36 curl_setopt($ch, CURLOPT_PROXY, $prx);
37 $prxusr = get_config('system','proxyuser');
39 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
42 curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
46 // don't let curl abort the entire application
47 // if it throws any errors.
52 $curl_info = curl_getinfo($ch);
53 $http_code = $curl_info['http_code'];
57 // Pull out multiple headers, e.g. proxy and continuation headers
58 // allow for HTTP/2.x without fixing code
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);
63 $base = substr($base,strlen($chunk));
66 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
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)) {
73 return fetch_url($url,$binary,$redirects,$timeout);
77 $a->set_curl_code($http_code);
79 $body = substr($s,strlen($header));
81 $a->set_curl_headers($header);
87 // post request to $url. $params is an array of post variables.
89 if(! function_exists('post_url')) {
90 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
92 $ch = curl_init($url);
93 if(($redirects > 8) || (! $ch))
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");
102 if(intval($timeout)) {
103 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
106 $curl_time = intval(get_config('system','curl_timeout'));
107 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
110 if(defined('LIGHTTPD')) {
111 if(!is_array($headers)) {
112 $headers = array('Expect:');
114 if(!in_array('Expect:', $headers)) {
115 array_push($headers, 'Expect:');
120 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
122 $check_cert = get_config('system','verifyssl');
123 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
124 $prx = get_config('system','proxy');
126 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
127 curl_setopt($ch, CURLOPT_PROXY, $prx);
128 $prxusr = get_config('system','proxyuser');
130 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
133 $a->set_curl_code(0);
135 // don't let curl abort the entire application
136 // if it throws any errors.
138 $s = @curl_exec($ch);
141 $curl_info = curl_getinfo($ch);
142 $http_code = $curl_info['http_code'];
146 // Pull out multiple headers, e.g. proxy and continuation headers
147 // allow for HTTP/2.x without fixing code
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);
152 $base = substr($base,strlen($chunk));
155 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
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)) {
162 return post_url($url,$params,$headers,$redirects,$timeout);
165 $a->set_curl_code($http_code);
166 $body = substr($s,strlen($header));
168 $a->set_curl_headers($header);
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.
178 if(! function_exists('xml_status')) {
179 function xml_status($st, $message = '') {
181 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
184 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
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";
193 if(! function_exists('http_status_exit')) {
194 function http_status_exit($val) {
198 if($val >= 200 && $val < 300)
201 logger('http_status_exit ' . $val);
202 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
208 // convert an XML document to a normalised, case-corrected array
211 if(! function_exists('convert_xml_element_to_array')) {
212 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
214 // If we're getting too deep, bail out
215 if ($recursion_depth > 512) {
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);
226 if (is_array($xml_element)) {
227 $result_array = array();
228 if (count($xml_element) <= 0) {
229 return (trim(strval($xml_element_copy)));
232 foreach($xml_element as $key=>$value) {
235 $result_array[strtolower($key)] =
236 convert_xml_element_to_array($value, $recursion_depth);
239 if ($recursion_depth == 0) {
240 $temp_array = $result_array;
241 $result_array = array(
242 strtolower($xml_element_copy->getName()) => $temp_array,
246 return ($result_array);
249 return (trim(strval($xml_element)));
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.
262 if(! function_exists('webfinger_dfrn')) {
263 function webfinger_dfrn($s) {
264 if(! strstr($s,'@')) {
267 $links = webfinger($s);
268 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
270 foreach($links as $link)
271 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
272 return $link['@attributes']['href'];
273 foreach($links as $link)
274 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
275 return 'stat:' . $link['@attributes']['template'];
280 // Given an email style address, perform webfinger lookup and
281 // return the array of link attributes from the personal XRD file.
282 // On error/failure return an empty array.
285 if(! function_exists('webfinger')) {
286 function webfinger($s) {
289 $host = substr($s,strpos($s,'@') + 1);
292 $tpl = fetch_lrdd_template($host);
293 logger('webfinger: lrdd template: ' . $tpl);
295 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
296 logger('webfinger: pxrd: ' . $pxrd);
297 $links = fetch_xrd_links($pxrd);
298 if(! count($links)) {
299 // try with double slashes
300 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
301 logger('webfinger: pxrd: ' . $pxrd);
302 $links = fetch_xrd_links($pxrd);
310 if(! function_exists('lrdd')) {
311 function lrdd($uri) {
315 // default priority is host priority, host-meta first
319 // All we have is an email address. Resource-priority is irrelevant
320 // because our URI isn't directly resolvable.
322 if(strstr($uri,'@')) {
323 return(webfinger($uri));
326 // get the host meta file
328 $host = @parse_url($uri);
331 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
332 $url .= $host['host'] . '/.well-known/host-meta' ;
337 logger('lrdd: constructed url: ' . $url);
339 $xml = fetch_url($url);
340 $headers = $a->get_curl_headers();
345 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
347 $h = parse_xml_string($xml);
351 $arr = convert_xml_element_to_array($h);
353 if(isset($arr['xrd']['property'])) {
354 $property = $arr['crd']['property'];
355 if(! isset($property[0]))
356 $properties = array($property);
358 $properties = $property;
359 foreach($properties as $prop)
360 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
361 $priority = 'resource';
364 // save the links in case we need them
368 if(isset($arr['xrd']['link'])) {
369 $link = $arr['xrd']['link'];
370 if(! isset($link[0]))
371 $links = array($link);
376 // do we have a template or href?
379 foreach($links as $link) {
380 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
381 if(x($link['@attributes'],'template'))
382 $tpl = $link['@attributes']['template'];
383 elseif(x($link['@attributes'],'href'))
384 $href = $link['@attributes']['href'];
389 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
392 if($priority === 'host') {
394 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
398 logger('lrdd: (host priority) pxrd: ' . $pxrd);
399 $links = fetch_xrd_links($pxrd);
403 $lines = explode("\n",$headers);
405 foreach($lines as $line) {
406 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
407 return(fetch_xrd_links($matches[1]));
415 // priority 'resource'
418 $html = fetch_url($uri);
419 $headers = $a->get_curl_headers();
420 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
422 // don't try and parse raw xml as html
423 if(! strstr($html,'<?xml')) {
424 require_once('library/HTML5/Parser.php');
425 $dom = @HTML5_Parser::parse($html);
428 $items = $dom->getElementsByTagName('link');
429 foreach($items as $item) {
430 $x = $item->getAttribute('rel');
432 $pagelink = $item->getAttribute('href');
440 return(fetch_xrd_links($pagelink));
442 // next look in HTTP headers
444 $lines = explode("\n",$headers);
446 foreach($lines as $line) {
447 // TODO alter the following regex to support multiple relations (space separated)
448 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
449 $pagelink = $matches[1];
452 // don't try and run feeds through the html5 parser
453 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
455 if(stristr($html,'<rss') || stristr($html,'<feed'))
461 return(fetch_xrd_links($pagelink));
463 // If we haven't found any links, return the host xrd links (which we have already fetched)
474 // Given a host name, locate the LRDD template from that
475 // host. Returns the LRDD template or an empty string on
478 if(! function_exists('fetch_lrdd_template')) {
479 function fetch_lrdd_template($host) {
482 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
483 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
484 $links = fetch_xrd_links($url1);
485 logger('fetch_lrdd_template from: ' . $url1);
486 logger('template (https): ' . print_r($links,true));
487 if(! count($links)) {
488 logger('fetch_lrdd_template from: ' . $url2);
489 $links = fetch_xrd_links($url2);
490 logger('template (http): ' . print_r($links,true));
493 foreach($links as $link)
494 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
495 $tpl = $link['@attributes']['template'];
497 if(! strpos($tpl,'{uri}'))
502 // Given a URL, retrieve the page as an XRD document.
503 // Return an array of links.
504 // on error/failure return empty array.
506 if(! function_exists('fetch_xrd_links')) {
507 function fetch_xrd_links($url) {
509 $xrd_timeout = intval(get_config('system','xrd_timeout'));
511 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
513 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
515 if ((! $xml) || (! stristr($xml,'<xrd')))
518 $h = parse_xml_string($xml);
522 $arr = convert_xml_element_to_array($h);
526 if(isset($arr['xrd']['link'])) {
527 $link = $arr['xrd']['link'];
528 if(! isset($link[0]))
529 $links = array($link);
533 if(isset($arr['xrd']['alias'])) {
534 $alias = $arr['xrd']['alias'];
535 if(! isset($alias[0]))
536 $aliases = array($alias);
539 if(is_array($aliases) && count($aliases)) {
540 foreach($aliases as $alias) {
541 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
546 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
553 // Take a URL from the wild, prepend http:// if necessary
554 // and check DNS to see if it's real
555 // return true if it's OK, false if something is wrong with it
557 if(! function_exists('validate_url')) {
558 function validate_url(&$url) {
559 if(substr($url,0,4) != 'http')
560 $url = 'http://' . $url;
561 $h = @parse_url($url);
563 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
569 // checks that email is an actual resolvable internet address
571 if(! function_exists('validate_email')) {
572 function validate_email($addr) {
574 if(! strpos($addr,'@'))
576 $h = substr($addr,strpos($addr,'@') + 1);
578 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
584 // Check $url against our list of allowed sites,
585 // wildcards allowed. If allowed_sites is unset return true;
586 // If url is allowed, return true.
587 // otherwise, return false
589 if(! function_exists('allowed_url')) {
590 function allowed_url($url) {
592 $h = @parse_url($url);
598 $str_allowed = get_config('system','allowed_sites');
604 $host = strtolower($h['host']);
606 // always allow our own site
608 if($host == strtolower($_SERVER['SERVER_NAME']))
611 $fnmatch = function_exists('fnmatch');
612 $allowed = explode(',',$str_allowed);
614 if(count($allowed)) {
615 foreach($allowed as $a) {
616 $pat = strtolower(trim($a));
617 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
626 // check if email address is allowed to register here.
627 // Compare against our list (wildcards allowed).
628 // Returns false if not allowed, true if allowed or if
629 // allowed list is not configured.
631 if(! function_exists('allowed_email')) {
632 function allowed_email($email) {
635 $domain = strtolower(substr($email,strpos($email,'@') + 1));
639 $str_allowed = get_config('system','allowed_email');
645 $fnmatch = function_exists('fnmatch');
646 $allowed = explode(',',$str_allowed);
648 if(count($allowed)) {
649 foreach($allowed as $a) {
650 $pat = strtolower(trim($a));
651 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
661 if(! function_exists('gravatar_img')) {
662 function gravatar_img($email) {
664 $opt = 'identicon'; // psuedo-random geometric pattern if not found
666 $hash = md5(trim(strtolower($email)));
668 $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg'
669 . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
671 logger('gravatar: ' . $email . ' ' . $url);
676 if(! function_exists('parse_xml_string')) {
677 function parse_xml_string($s,$strict = true) {
679 if(! strstr($s,'<?xml'))
681 $s2 = substr($s,strpos($s,'<?xml'));
685 libxml_use_internal_errors(true);
687 $x = @simplexml_load_string($s2);
689 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
690 foreach(libxml_get_errors() as $err)
691 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
692 libxml_clear_errors();
697 function add_fcontact($arr) {
699 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
700 `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
701 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
704 dbesc($arr['photo']),
705 dbesc($arr['request']),
708 dbesc($arr['notify']),
710 dbesc($arr['confirm']),
711 dbesc($arr['network']),
712 dbesc($arr['alias']),
713 dbesc($arr['pubkey']),
714 dbesc(datetime_convert())