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'];
63 // logger('fetch_url:' . $http_code . ' data: ' . $s);
66 // Pull out multiple headers, e.g. proxy and continuation headers
67 // allow for HTTP/2.x without fixing code
69 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
70 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
72 $base = substr($base,strlen($chunk));
75 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
77 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
78 $newurl = trim(array_pop($matches));
79 if(strpos($newurl,'/') === 0)
80 $newurl = $url . $newurl;
81 $url_parsed = @parse_url($newurl);
82 if (isset($url_parsed)) {
84 return fetch_url($newurl,$binary,$redirects,$timeout);
88 $a->set_curl_code($http_code);
90 $body = substr($s,strlen($header));
92 $a->set_curl_headers($header);
98 // post request to $url. $params is an array of post variables.
100 if(! function_exists('post_url')) {
101 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
103 $ch = curl_init($url);
104 if(($redirects > 8) || (! $ch))
107 curl_setopt($ch, CURLOPT_HEADER, true);
108 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
109 curl_setopt($ch, CURLOPT_POST,1);
110 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
111 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
113 if(intval($timeout)) {
114 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
117 $curl_time = intval(get_config('system','curl_timeout'));
118 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
121 if(defined('LIGHTTPD')) {
122 if(!is_array($headers)) {
123 $headers = array('Expect:');
125 if(!in_array('Expect:', $headers)) {
126 array_push($headers, 'Expect:');
131 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
133 $check_cert = get_config('system','verifyssl');
134 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
135 $prx = get_config('system','proxy');
137 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
138 curl_setopt($ch, CURLOPT_PROXY, $prx);
139 $prxusr = get_config('system','proxyuser');
141 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
144 $a->set_curl_code(0);
146 // don't let curl abort the entire application
147 // if it throws any errors.
149 $s = @curl_exec($ch);
152 $curl_info = curl_getinfo($ch);
153 $http_code = $curl_info['http_code'];
157 // Pull out multiple headers, e.g. proxy and continuation headers
158 // allow for HTTP/2.x without fixing code
160 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
161 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
163 $base = substr($base,strlen($chunk));
166 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
168 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
169 $newurl = trim(array_pop($matches));
170 if(strpos($newurl,'/') === 0)
171 $newurl = $url . $newurl;
172 $url_parsed = @parse_url($newurl);
173 if (isset($url_parsed)) {
175 return fetch_url($newurl,$binary,$redirects,$timeout);
178 $a->set_curl_code($http_code);
179 $body = substr($s,strlen($header));
181 $a->set_curl_headers($header);
187 // Generic XML return
188 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
189 // of $st and an optional text <message> of $message and terminates the current process.
191 if(! function_exists('xml_status')) {
192 function xml_status($st, $message = '') {
194 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
197 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
199 header( "Content-type: text/xml" );
200 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
201 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
206 if(! function_exists('http_status_exit')) {
207 function http_status_exit($val) {
211 if($val >= 200 && $val < 300)
214 logger('http_status_exit ' . $val);
215 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
221 // convert an XML document to a normalised, case-corrected array
224 if(! function_exists('convert_xml_element_to_array')) {
225 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
227 // If we're getting too deep, bail out
228 if ($recursion_depth > 512) {
232 if (!is_string($xml_element) &&
233 !is_array($xml_element) &&
234 (get_class($xml_element) == 'SimpleXMLElement')) {
235 $xml_element_copy = $xml_element;
236 $xml_element = get_object_vars($xml_element);
239 if (is_array($xml_element)) {
240 $result_array = array();
241 if (count($xml_element) <= 0) {
242 return (trim(strval($xml_element_copy)));
245 foreach($xml_element as $key=>$value) {
248 $result_array[strtolower($key)] =
249 convert_xml_element_to_array($value, $recursion_depth);
252 if ($recursion_depth == 0) {
253 $temp_array = $result_array;
254 $result_array = array(
255 strtolower($xml_element_copy->getName()) => $temp_array,
259 return ($result_array);
262 return (trim(strval($xml_element)));
266 // Given an email style address, perform webfinger lookup and
267 // return the resulting DFRN profile URL, or if no DFRN profile URL
268 // is located, returns an OStatus subscription template (prefixed
269 // with the string 'stat:' to identify it as on OStatus template).
270 // If this isn't an email style address just return $s.
271 // Return an empty string if email-style addresses but webfinger fails,
272 // or if the resultant personal XRD doesn't contain a supported
273 // subscription/friend-request attribute.
275 // amended 7/9/2011 to return an hcard which could save potentially loading
276 // a lengthy content page to scrape dfrn attributes
278 if(! function_exists('webfinger_dfrn')) {
279 function webfinger_dfrn($s,&$hcard) {
280 if(! strstr($s,'@')) {
285 $links = webfinger($s);
286 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
288 foreach($links as $link) {
289 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
290 $profile_link = $link['@attributes']['href'];
291 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
292 $profile_link = 'stat:' . $link['@attributes']['template'];
293 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
294 $hcard = $link['@attributes']['href'];
297 return $profile_link;
300 // Given an email style address, perform webfinger lookup and
301 // return the array of link attributes from the personal XRD file.
302 // On error/failure return an empty array.
305 if(! function_exists('webfinger')) {
306 function webfinger($s, $debug = false) {
309 $host = substr($s,strpos($s,'@') + 1);
312 $tpl = fetch_lrdd_template($host);
313 logger('webfinger: lrdd template: ' . $tpl);
315 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
316 logger('webfinger: pxrd: ' . $pxrd);
317 $links = fetch_xrd_links($pxrd);
318 if(! count($links)) {
319 // try with double slashes
320 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
321 logger('webfinger: pxrd: ' . $pxrd);
322 $links = fetch_xrd_links($pxrd);
330 if(! function_exists('lrdd')) {
331 function lrdd($uri, $debug = false) {
335 // default priority is host priority, host-meta first
339 // All we have is an email address. Resource-priority is irrelevant
340 // because our URI isn't directly resolvable.
342 if(strstr($uri,'@')) {
343 return(webfinger($uri));
346 // get the host meta file
348 $host = @parse_url($uri);
351 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
352 $url .= $host['host'] . '/.well-known/host-meta' ;
357 logger('lrdd: constructed url: ' . $url);
359 $xml = fetch_url($url);
360 $headers = $a->get_curl_headers();
365 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
367 if(! stristr($xml,'<xrd'))
370 $h = parse_xml_string($xml);
374 $arr = convert_xml_element_to_array($h);
376 if(isset($arr['xrd']['property'])) {
377 $property = $arr['crd']['property'];
378 if(! isset($property[0]))
379 $properties = array($property);
381 $properties = $property;
382 foreach($properties as $prop)
383 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
384 $priority = 'resource';
387 // save the links in case we need them
391 if(isset($arr['xrd']['link'])) {
392 $link = $arr['xrd']['link'];
393 if(! isset($link[0]))
394 $links = array($link);
399 // do we have a template or href?
402 foreach($links as $link) {
403 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
404 if(x($link['@attributes'],'template'))
405 $tpl = $link['@attributes']['template'];
406 elseif(x($link['@attributes'],'href'))
407 $href = $link['@attributes']['href'];
412 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
415 if($priority === 'host') {
417 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
421 logger('lrdd: (host priority) pxrd: ' . $pxrd);
422 $links = fetch_xrd_links($pxrd);
426 $lines = explode("\n",$headers);
428 foreach($lines as $line) {
429 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
430 return(fetch_xrd_links($matches[1]));
438 // priority 'resource'
441 $html = fetch_url($uri);
442 $headers = $a->get_curl_headers();
443 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
445 // don't try and parse raw xml as html
446 if(! strstr($html,'<?xml')) {
447 require_once('library/HTML5/Parser.php');
450 $dom = HTML5_Parser::parse($html);
451 } catch (DOMException $e) {
452 logger('lrdd: parse error: ' . $e);
456 $items = $dom->getElementsByTagName('link');
457 foreach($items as $item) {
458 $x = $item->getAttribute('rel');
460 $pagelink = $item->getAttribute('href');
468 return(fetch_xrd_links($pagelink));
470 // next look in HTTP headers
472 $lines = explode("\n",$headers);
474 foreach($lines as $line) {
475 // TODO alter the following regex to support multiple relations (space separated)
476 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
477 $pagelink = $matches[1];
480 // don't try and run feeds through the html5 parser
481 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
483 if(stristr($html,'<rss') || stristr($html,'<feed'))
489 return(fetch_xrd_links($pagelink));
491 // If we haven't found any links, return the host xrd links (which we have already fetched)
502 // Given a host name, locate the LRDD template from that
503 // host. Returns the LRDD template or an empty string on
506 if(! function_exists('fetch_lrdd_template')) {
507 function fetch_lrdd_template($host) {
510 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
511 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
512 $links = fetch_xrd_links($url1);
513 logger('fetch_lrdd_template from: ' . $url1);
514 logger('template (https): ' . print_r($links,true));
515 if(! count($links)) {
516 logger('fetch_lrdd_template from: ' . $url2);
517 $links = fetch_xrd_links($url2);
518 logger('template (http): ' . print_r($links,true));
521 foreach($links as $link)
522 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
523 $tpl = $link['@attributes']['template'];
525 if(! strpos($tpl,'{uri}'))
530 // Given a URL, retrieve the page as an XRD document.
531 // Return an array of links.
532 // on error/failure return empty array.
534 if(! function_exists('fetch_xrd_links')) {
535 function fetch_xrd_links($url) {
537 $xrd_timeout = intval(get_config('system','xrd_timeout'));
539 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
541 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
543 if ((! $xml) || (! stristr($xml,'<xrd')))
546 // fix diaspora's bad xml
547 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
549 $h = parse_xml_string($xml);
553 $arr = convert_xml_element_to_array($h);
557 if(isset($arr['xrd']['link'])) {
558 $link = $arr['xrd']['link'];
559 if(! isset($link[0]))
560 $links = array($link);
564 if(isset($arr['xrd']['alias'])) {
565 $alias = $arr['xrd']['alias'];
566 if(! isset($alias[0]))
567 $aliases = array($alias);
570 if(is_array($aliases) && count($aliases)) {
571 foreach($aliases as $alias) {
572 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
577 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
584 // Take a URL from the wild, prepend http:// if necessary
585 // and check DNS to see if it's real
586 // return true if it's OK, false if something is wrong with it
588 if(! function_exists('validate_url')) {
589 function validate_url(&$url) {
590 // no naked subdomains
591 if(strpos($url,'.') === false)
593 if(substr($url,0,4) != 'http')
594 $url = 'http://' . $url;
595 $h = @parse_url($url);
597 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
603 // checks that email is an actual resolvable internet address
605 if(! function_exists('validate_email')) {
606 function validate_email($addr) {
608 if(! strpos($addr,'@'))
610 $h = substr($addr,strpos($addr,'@') + 1);
612 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
618 // Check $url against our list of allowed sites,
619 // wildcards allowed. If allowed_sites is unset return true;
620 // If url is allowed, return true.
621 // otherwise, return false
623 if(! function_exists('allowed_url')) {
624 function allowed_url($url) {
626 $h = @parse_url($url);
632 $str_allowed = get_config('system','allowed_sites');
638 $host = strtolower($h['host']);
640 // always allow our own site
642 if($host == strtolower($_SERVER['SERVER_NAME']))
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,$host)) || ($pat == $host)) {
660 // check if email address is allowed to register here.
661 // Compare against our list (wildcards allowed).
662 // Returns false if not allowed, true if allowed or if
663 // allowed list is not configured.
665 if(! function_exists('allowed_email')) {
666 function allowed_email($email) {
669 $domain = strtolower(substr($email,strpos($email,'@') + 1));
673 $str_allowed = get_config('system','allowed_email');
679 $fnmatch = function_exists('fnmatch');
680 $allowed = explode(',',$str_allowed);
682 if(count($allowed)) {
683 foreach($allowed as $a) {
684 $pat = strtolower(trim($a));
685 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
695 if(! function_exists('gravatar_img')) {
696 function gravatar_img($email) {
698 $opt = 'identicon'; // psuedo-random geometric pattern if not found
700 $hash = md5(trim(strtolower($email)));
702 $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg'
703 . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
705 logger('gravatar: ' . $email . ' ' . $url);
710 if(! function_exists('parse_xml_string')) {
711 function parse_xml_string($s,$strict = true) {
713 if(! strstr($s,'<?xml'))
715 $s2 = substr($s,strpos($s,'<?xml'));
719 libxml_use_internal_errors(true);
721 $x = @simplexml_load_string($s2);
723 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
724 foreach(libxml_get_errors() as $err)
725 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
726 libxml_clear_errors();
731 function add_fcontact($arr,$update = false) {
734 $r = q("UPDATE `fcontact` SET
747 WHERE `url` = '%s' AND `network` = '%s' LIMIT 1",
749 dbesc($arr['photo']),
750 dbesc($arr['request']),
753 dbesc($arr['batch']),
754 dbesc($arr['notify']),
756 dbesc($arr['confirm']),
757 dbesc($arr['alias']),
758 dbesc($arr['pubkey']),
759 dbesc(datetime_convert()),
761 dbesc($arr['network'])
765 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
766 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
767 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
770 dbesc($arr['photo']),
771 dbesc($arr['request']),
774 dbesc($arr['batch']),
775 dbesc($arr['notify']),
777 dbesc($arr['confirm']),
778 dbesc($arr['network']),
779 dbesc($arr['alias']),
780 dbesc($arr['pubkey']),
781 dbesc(datetime_convert())
789 function scale_external_images($s,$include_link = true) {
794 $c = preg_match_all('/\[img\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
796 require_once('include/Photo.php');
797 foreach($matches as $mtch) {
798 logger('scale_external_image: ' . $mtch[1]);
799 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
800 if(stristr($mtch[1],$hostname))
802 $i = fetch_url($mtch[1]);
805 if($ph->is_valid()) {
806 $orig_width = $ph->getWidth();
807 $orig_height = $ph->getHeight();
809 if($orig_width > 640 || $orig_height > 640) {
811 $ph->scaleImage(640);
812 $new_width = $ph->getWidth();
813 $new_height = $ph->getHeight();
814 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
815 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $mtch[1] . '[/img]'
816 . "\n" . (($include_link)
817 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
819 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);