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) {
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) {
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 $h = parse_xml_string($xml);
371 $arr = convert_xml_element_to_array($h);
373 if(isset($arr['xrd']['property'])) {
374 $property = $arr['crd']['property'];
375 if(! isset($property[0]))
376 $properties = array($property);
378 $properties = $property;
379 foreach($properties as $prop)
380 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
381 $priority = 'resource';
384 // save the links in case we need them
388 if(isset($arr['xrd']['link'])) {
389 $link = $arr['xrd']['link'];
390 if(! isset($link[0]))
391 $links = array($link);
396 // do we have a template or href?
399 foreach($links as $link) {
400 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
401 if(x($link['@attributes'],'template'))
402 $tpl = $link['@attributes']['template'];
403 elseif(x($link['@attributes'],'href'))
404 $href = $link['@attributes']['href'];
409 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
412 if($priority === 'host') {
414 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
418 logger('lrdd: (host priority) pxrd: ' . $pxrd);
419 $links = fetch_xrd_links($pxrd);
423 $lines = explode("\n",$headers);
425 foreach($lines as $line) {
426 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
427 return(fetch_xrd_links($matches[1]));
435 // priority 'resource'
438 $html = fetch_url($uri);
439 $headers = $a->get_curl_headers();
440 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
442 // don't try and parse raw xml as html
443 if(! strstr($html,'<?xml')) {
444 require_once('library/HTML5/Parser.php');
447 $dom = HTML5_Parser::parse($html);
448 } catch (DOMException $e) {
449 logger('lrdd: parse error: ' . $e);
453 $items = $dom->getElementsByTagName('link');
454 foreach($items as $item) {
455 $x = $item->getAttribute('rel');
457 $pagelink = $item->getAttribute('href');
465 return(fetch_xrd_links($pagelink));
467 // next look in HTTP headers
469 $lines = explode("\n",$headers);
471 foreach($lines as $line) {
472 // TODO alter the following regex to support multiple relations (space separated)
473 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
474 $pagelink = $matches[1];
477 // don't try and run feeds through the html5 parser
478 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
480 if(stristr($html,'<rss') || stristr($html,'<feed'))
486 return(fetch_xrd_links($pagelink));
488 // If we haven't found any links, return the host xrd links (which we have already fetched)
499 // Given a host name, locate the LRDD template from that
500 // host. Returns the LRDD template or an empty string on
503 if(! function_exists('fetch_lrdd_template')) {
504 function fetch_lrdd_template($host) {
507 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
508 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
509 $links = fetch_xrd_links($url1);
510 logger('fetch_lrdd_template from: ' . $url1);
511 logger('template (https): ' . print_r($links,true));
512 if(! count($links)) {
513 logger('fetch_lrdd_template from: ' . $url2);
514 $links = fetch_xrd_links($url2);
515 logger('template (http): ' . print_r($links,true));
518 foreach($links as $link)
519 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
520 $tpl = $link['@attributes']['template'];
522 if(! strpos($tpl,'{uri}'))
527 // Given a URL, retrieve the page as an XRD document.
528 // Return an array of links.
529 // on error/failure return empty array.
531 if(! function_exists('fetch_xrd_links')) {
532 function fetch_xrd_links($url) {
534 $xrd_timeout = intval(get_config('system','xrd_timeout'));
536 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
538 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
540 if ((! $xml) || (! stristr($xml,'<xrd')))
543 // fix diaspora's bad xml
544 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
546 $h = parse_xml_string($xml);
550 $arr = convert_xml_element_to_array($h);
554 if(isset($arr['xrd']['link'])) {
555 $link = $arr['xrd']['link'];
556 if(! isset($link[0]))
557 $links = array($link);
561 if(isset($arr['xrd']['alias'])) {
562 $alias = $arr['xrd']['alias'];
563 if(! isset($alias[0]))
564 $aliases = array($alias);
567 if(is_array($aliases) && count($aliases)) {
568 foreach($aliases as $alias) {
569 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
574 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
581 // Take a URL from the wild, prepend http:// if necessary
582 // and check DNS to see if it's real
583 // return true if it's OK, false if something is wrong with it
585 if(! function_exists('validate_url')) {
586 function validate_url(&$url) {
587 // no naked subdomains
588 if(strpos($url,'.') === false)
590 if(substr($url,0,4) != 'http')
591 $url = 'http://' . $url;
592 $h = @parse_url($url);
594 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
600 // checks that email is an actual resolvable internet address
602 if(! function_exists('validate_email')) {
603 function validate_email($addr) {
605 if(! strpos($addr,'@'))
607 $h = substr($addr,strpos($addr,'@') + 1);
609 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
615 // Check $url against our list of allowed sites,
616 // wildcards allowed. If allowed_sites is unset return true;
617 // If url is allowed, return true.
618 // otherwise, return false
620 if(! function_exists('allowed_url')) {
621 function allowed_url($url) {
623 $h = @parse_url($url);
629 $str_allowed = get_config('system','allowed_sites');
635 $host = strtolower($h['host']);
637 // always allow our own site
639 if($host == strtolower($_SERVER['SERVER_NAME']))
642 $fnmatch = function_exists('fnmatch');
643 $allowed = explode(',',$str_allowed);
645 if(count($allowed)) {
646 foreach($allowed as $a) {
647 $pat = strtolower(trim($a));
648 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
657 // check if email address is allowed to register here.
658 // Compare against our list (wildcards allowed).
659 // Returns false if not allowed, true if allowed or if
660 // allowed list is not configured.
662 if(! function_exists('allowed_email')) {
663 function allowed_email($email) {
666 $domain = strtolower(substr($email,strpos($email,'@') + 1));
670 $str_allowed = get_config('system','allowed_email');
676 $fnmatch = function_exists('fnmatch');
677 $allowed = explode(',',$str_allowed);
679 if(count($allowed)) {
680 foreach($allowed as $a) {
681 $pat = strtolower(trim($a));
682 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
692 if(! function_exists('gravatar_img')) {
693 function gravatar_img($email) {
695 $opt = 'identicon'; // psuedo-random geometric pattern if not found
697 $hash = md5(trim(strtolower($email)));
699 $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg'
700 . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
702 logger('gravatar: ' . $email . ' ' . $url);
707 if(! function_exists('parse_xml_string')) {
708 function parse_xml_string($s,$strict = true) {
710 if(! strstr($s,'<?xml'))
712 $s2 = substr($s,strpos($s,'<?xml'));
716 libxml_use_internal_errors(true);
718 $x = @simplexml_load_string($s2);
720 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
721 foreach(libxml_get_errors() as $err)
722 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
723 libxml_clear_errors();
728 function add_fcontact($arr,$update = false) {
731 $r = q("UPDATE `fcontact` SET
744 WHERE `url` = '%s' AND `network` = '%s' LIMIT 1",
746 dbesc($arr['photo']),
747 dbesc($arr['request']),
750 dbesc($arr['batch']),
751 dbesc($arr['notify']),
753 dbesc($arr['confirm']),
754 dbesc($arr['alias']),
755 dbesc($arr['pubkey']),
756 dbesc(datetime_convert()),
758 dbesc($arr['network'])
762 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
763 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
764 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
767 dbesc($arr['photo']),
768 dbesc($arr['request']),
771 dbesc($arr['batch']),
772 dbesc($arr['notify']),
774 dbesc($arr['confirm']),
775 dbesc($arr['network']),
776 dbesc($arr['alias']),
777 dbesc($arr['pubkey']),
778 dbesc(datetime_convert())
786 function scale_external_images($s,$include_link = true) {
791 $c = preg_match_all('/\[img\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
793 require_once('include/Photo.php');
794 foreach($matches as $mtch) {
795 logger('scale_external_image: ' . $mtch[1]);
796 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
797 if(stristr($mtch[1],$hostname))
799 $i = fetch_url($mtch[1]);
802 if($ph->is_valid()) {
803 $orig_width = $ph->getWidth();
804 $orig_height = $ph->getHeight();
806 if($orig_width > 640 || $orig_height > 640) {
808 $ph->scaleImage(640);
809 $new_width = $ph->getWidth();
810 $new_height = $ph->getHeight();
811 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
812 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $mtch[1] . '[/img]'
813 . "\n" . (($include_link)
814 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
816 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);