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 // amended 7/9/2011 to return an hcard which could save potentially loading
263 // a lengthy content page to scrape dfrn attributes
265 if(! function_exists('webfinger_dfrn')) {
266 function webfinger_dfrn($s,&$hcard) {
267 if(! strstr($s,'@')) {
272 $links = webfinger($s);
273 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
275 foreach($links as $link) {
276 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
277 $profile_link = $link['@attributes']['href'];
278 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
279 $profile_link = 'stat:' . $link['@attributes']['template'];
280 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
281 $hcard = $link['@attributes']['href'];
284 return $profile_link;
287 // Given an email style address, perform webfinger lookup and
288 // return the array of link attributes from the personal XRD file.
289 // On error/failure return an empty array.
292 if(! function_exists('webfinger')) {
293 function webfinger($s) {
296 $host = substr($s,strpos($s,'@') + 1);
299 $tpl = fetch_lrdd_template($host);
300 logger('webfinger: lrdd template: ' . $tpl);
302 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
303 logger('webfinger: pxrd: ' . $pxrd);
304 $links = fetch_xrd_links($pxrd);
305 if(! count($links)) {
306 // try with double slashes
307 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
308 logger('webfinger: pxrd: ' . $pxrd);
309 $links = fetch_xrd_links($pxrd);
317 if(! function_exists('lrdd')) {
318 function lrdd($uri) {
322 // default priority is host priority, host-meta first
326 // All we have is an email address. Resource-priority is irrelevant
327 // because our URI isn't directly resolvable.
329 if(strstr($uri,'@')) {
330 return(webfinger($uri));
333 // get the host meta file
335 $host = @parse_url($uri);
338 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
339 $url .= $host['host'] . '/.well-known/host-meta' ;
344 logger('lrdd: constructed url: ' . $url);
346 $xml = fetch_url($url);
347 $headers = $a->get_curl_headers();
352 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
354 $h = parse_xml_string($xml);
358 $arr = convert_xml_element_to_array($h);
360 if(isset($arr['xrd']['property'])) {
361 $property = $arr['crd']['property'];
362 if(! isset($property[0]))
363 $properties = array($property);
365 $properties = $property;
366 foreach($properties as $prop)
367 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
368 $priority = 'resource';
371 // save the links in case we need them
375 if(isset($arr['xrd']['link'])) {
376 $link = $arr['xrd']['link'];
377 if(! isset($link[0]))
378 $links = array($link);
383 // do we have a template or href?
386 foreach($links as $link) {
387 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
388 if(x($link['@attributes'],'template'))
389 $tpl = $link['@attributes']['template'];
390 elseif(x($link['@attributes'],'href'))
391 $href = $link['@attributes']['href'];
396 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
399 if($priority === 'host') {
401 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
405 logger('lrdd: (host priority) pxrd: ' . $pxrd);
406 $links = fetch_xrd_links($pxrd);
410 $lines = explode("\n",$headers);
412 foreach($lines as $line) {
413 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
414 return(fetch_xrd_links($matches[1]));
422 // priority 'resource'
425 $html = fetch_url($uri);
426 $headers = $a->get_curl_headers();
427 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
429 // don't try and parse raw xml as html
430 if(! strstr($html,'<?xml')) {
431 require_once('library/HTML5/Parser.php');
432 $dom = @HTML5_Parser::parse($html);
435 $items = $dom->getElementsByTagName('link');
436 foreach($items as $item) {
437 $x = $item->getAttribute('rel');
439 $pagelink = $item->getAttribute('href');
447 return(fetch_xrd_links($pagelink));
449 // next look in HTTP headers
451 $lines = explode("\n",$headers);
453 foreach($lines as $line) {
454 // TODO alter the following regex to support multiple relations (space separated)
455 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
456 $pagelink = $matches[1];
459 // don't try and run feeds through the html5 parser
460 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
462 if(stristr($html,'<rss') || stristr($html,'<feed'))
468 return(fetch_xrd_links($pagelink));
470 // If we haven't found any links, return the host xrd links (which we have already fetched)
481 // Given a host name, locate the LRDD template from that
482 // host. Returns the LRDD template or an empty string on
485 if(! function_exists('fetch_lrdd_template')) {
486 function fetch_lrdd_template($host) {
489 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
490 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
491 $links = fetch_xrd_links($url1);
492 logger('fetch_lrdd_template from: ' . $url1);
493 logger('template (https): ' . print_r($links,true));
494 if(! count($links)) {
495 logger('fetch_lrdd_template from: ' . $url2);
496 $links = fetch_xrd_links($url2);
497 logger('template (http): ' . print_r($links,true));
500 foreach($links as $link)
501 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
502 $tpl = $link['@attributes']['template'];
504 if(! strpos($tpl,'{uri}'))
509 // Given a URL, retrieve the page as an XRD document.
510 // Return an array of links.
511 // on error/failure return empty array.
513 if(! function_exists('fetch_xrd_links')) {
514 function fetch_xrd_links($url) {
516 $xrd_timeout = intval(get_config('system','xrd_timeout'));
518 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
520 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
522 if ((! $xml) || (! stristr($xml,'<xrd')))
525 $h = parse_xml_string($xml);
529 $arr = convert_xml_element_to_array($h);
533 if(isset($arr['xrd']['link'])) {
534 $link = $arr['xrd']['link'];
535 if(! isset($link[0]))
536 $links = array($link);
540 if(isset($arr['xrd']['alias'])) {
541 $alias = $arr['xrd']['alias'];
542 if(! isset($alias[0]))
543 $aliases = array($alias);
546 if(is_array($aliases) && count($aliases)) {
547 foreach($aliases as $alias) {
548 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
553 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
560 // Take a URL from the wild, prepend http:// if necessary
561 // and check DNS to see if it's real
562 // return true if it's OK, false if something is wrong with it
564 if(! function_exists('validate_url')) {
565 function validate_url(&$url) {
566 if(substr($url,0,4) != 'http')
567 $url = 'http://' . $url;
568 $h = @parse_url($url);
570 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
576 // checks that email is an actual resolvable internet address
578 if(! function_exists('validate_email')) {
579 function validate_email($addr) {
581 if(! strpos($addr,'@'))
583 $h = substr($addr,strpos($addr,'@') + 1);
585 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
591 // Check $url against our list of allowed sites,
592 // wildcards allowed. If allowed_sites is unset return true;
593 // If url is allowed, return true.
594 // otherwise, return false
596 if(! function_exists('allowed_url')) {
597 function allowed_url($url) {
599 $h = @parse_url($url);
605 $str_allowed = get_config('system','allowed_sites');
611 $host = strtolower($h['host']);
613 // always allow our own site
615 if($host == strtolower($_SERVER['SERVER_NAME']))
618 $fnmatch = function_exists('fnmatch');
619 $allowed = explode(',',$str_allowed);
621 if(count($allowed)) {
622 foreach($allowed as $a) {
623 $pat = strtolower(trim($a));
624 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
633 // check if email address is allowed to register here.
634 // Compare against our list (wildcards allowed).
635 // Returns false if not allowed, true if allowed or if
636 // allowed list is not configured.
638 if(! function_exists('allowed_email')) {
639 function allowed_email($email) {
642 $domain = strtolower(substr($email,strpos($email,'@') + 1));
646 $str_allowed = get_config('system','allowed_email');
652 $fnmatch = function_exists('fnmatch');
653 $allowed = explode(',',$str_allowed);
655 if(count($allowed)) {
656 foreach($allowed as $a) {
657 $pat = strtolower(trim($a));
658 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
668 if(! function_exists('gravatar_img')) {
669 function gravatar_img($email) {
671 $opt = 'identicon'; // psuedo-random geometric pattern if not found
673 $hash = md5(trim(strtolower($email)));
675 $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg'
676 . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
678 logger('gravatar: ' . $email . ' ' . $url);
683 if(! function_exists('parse_xml_string')) {
684 function parse_xml_string($s,$strict = true) {
686 if(! strstr($s,'<?xml'))
688 $s2 = substr($s,strpos($s,'<?xml'));
692 libxml_use_internal_errors(true);
694 $x = @simplexml_load_string($s2);
696 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
697 foreach(libxml_get_errors() as $err)
698 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
699 libxml_clear_errors();
704 function add_fcontact($arr,$update = false) {
707 $r = q("UPDATE `fcontact` SET
720 WHERE `url` = '%s' AND `network` = '%s' LIMIT 1",
722 dbesc($arr['photo']),
723 dbesc($arr['request']),
726 dbesc($arr['batch']),
727 dbesc($arr['notify']),
729 dbesc($arr['confirm']),
730 dbesc($arr['network']),
731 dbesc($arr['alias']),
732 dbesc($arr['pubkey']),
733 dbesc(datetime_convert()),
735 dbesc($arr['network'])
739 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
740 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
741 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
744 dbesc($arr['photo']),
745 dbesc($arr['request']),
748 dbesc($arr['batch']),
749 dbesc($arr['notify']),
751 dbesc($arr['confirm']),
752 dbesc($arr['network']),
753 dbesc($arr['alias']),
754 dbesc($arr['pubkey']),
755 dbesc(datetime_convert())