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,false,$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) {
212 if($val >= 200 && $val < 300)
215 logger('http_status_exit ' . $val);
216 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
222 // convert an XML document to a normalised, case-corrected array
225 if(! function_exists('convert_xml_element_to_array')) {
226 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
228 // If we're getting too deep, bail out
229 if ($recursion_depth > 512) {
233 if (!is_string($xml_element) &&
234 !is_array($xml_element) &&
235 (get_class($xml_element) == 'SimpleXMLElement')) {
236 $xml_element_copy = $xml_element;
237 $xml_element = get_object_vars($xml_element);
240 if (is_array($xml_element)) {
241 $result_array = array();
242 if (count($xml_element) <= 0) {
243 return (trim(strval($xml_element_copy)));
246 foreach($xml_element as $key=>$value) {
249 $result_array[strtolower($key)] =
250 convert_xml_element_to_array($value, $recursion_depth);
253 if ($recursion_depth == 0) {
254 $temp_array = $result_array;
255 $result_array = array(
256 strtolower($xml_element_copy->getName()) => $temp_array,
260 return ($result_array);
263 return (trim(strval($xml_element)));
267 // Given an email style address, perform webfinger lookup and
268 // return the resulting DFRN profile URL, or if no DFRN profile URL
269 // is located, returns an OStatus subscription template (prefixed
270 // with the string 'stat:' to identify it as on OStatus template).
271 // If this isn't an email style address just return $s.
272 // Return an empty string if email-style addresses but webfinger fails,
273 // or if the resultant personal XRD doesn't contain a supported
274 // subscription/friend-request attribute.
276 // amended 7/9/2011 to return an hcard which could save potentially loading
277 // a lengthy content page to scrape dfrn attributes
279 if(! function_exists('webfinger_dfrn')) {
280 function webfinger_dfrn($s,&$hcard) {
281 if(! strstr($s,'@')) {
286 $links = webfinger($s);
287 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
289 foreach($links as $link) {
290 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
291 $profile_link = $link['@attributes']['href'];
292 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
293 $profile_link = 'stat:' . $link['@attributes']['template'];
294 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
295 $hcard = $link['@attributes']['href'];
298 return $profile_link;
301 // Given an email style address, perform webfinger lookup and
302 // return the array of link attributes from the personal XRD file.
303 // On error/failure return an empty array.
306 if(! function_exists('webfinger')) {
307 function webfinger($s, $debug = false) {
310 $host = substr($s,strpos($s,'@') + 1);
313 $tpl = fetch_lrdd_template($host);
314 logger('webfinger: lrdd template: ' . $tpl);
316 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
317 logger('webfinger: pxrd: ' . $pxrd);
318 $links = fetch_xrd_links($pxrd);
319 if(! count($links)) {
320 // try with double slashes
321 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
322 logger('webfinger: pxrd: ' . $pxrd);
323 $links = fetch_xrd_links($pxrd);
331 if(! function_exists('lrdd')) {
332 function lrdd($uri, $debug = false) {
336 // default priority is host priority, host-meta first
340 // All we have is an email address. Resource-priority is irrelevant
341 // because our URI isn't directly resolvable.
343 if(strstr($uri,'@')) {
344 return(webfinger($uri));
347 // get the host meta file
349 $host = @parse_url($uri);
352 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
353 $url .= $host['host'] . '/.well-known/host-meta' ;
358 logger('lrdd: constructed url: ' . $url);
360 $xml = fetch_url($url);
361 $headers = $a->get_curl_headers();
366 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
368 if(! stristr($xml,'<xrd'))
371 $h = parse_xml_string($xml);
375 $arr = convert_xml_element_to_array($h);
377 if(isset($arr['xrd']['property'])) {
378 $property = $arr['crd']['property'];
379 if(! isset($property[0]))
380 $properties = array($property);
382 $properties = $property;
383 foreach($properties as $prop)
384 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
385 $priority = 'resource';
388 // save the links in case we need them
392 if(isset($arr['xrd']['link'])) {
393 $link = $arr['xrd']['link'];
394 if(! isset($link[0]))
395 $links = array($link);
400 // do we have a template or href?
403 foreach($links as $link) {
404 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
405 if(x($link['@attributes'],'template'))
406 $tpl = $link['@attributes']['template'];
407 elseif(x($link['@attributes'],'href'))
408 $href = $link['@attributes']['href'];
413 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
416 if($priority === 'host') {
418 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
422 logger('lrdd: (host priority) pxrd: ' . $pxrd);
423 $links = fetch_xrd_links($pxrd);
427 $lines = explode("\n",$headers);
429 foreach($lines as $line) {
430 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
431 return(fetch_xrd_links($matches[1]));
439 // priority 'resource'
442 $html = fetch_url($uri);
443 $headers = $a->get_curl_headers();
444 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
446 // don't try and parse raw xml as html
447 if(! strstr($html,'<?xml')) {
448 require_once('library/HTML5/Parser.php');
451 $dom = HTML5_Parser::parse($html);
452 } catch (DOMException $e) {
453 logger('lrdd: parse error: ' . $e);
456 if(isset($dom) && $dom) {
457 $items = $dom->getElementsByTagName('link');
458 foreach($items as $item) {
459 $x = $item->getAttribute('rel');
461 $pagelink = $item->getAttribute('href');
469 return(fetch_xrd_links($pagelink));
471 // next look in HTTP headers
473 $lines = explode("\n",$headers);
475 foreach($lines as $line) {
476 // TODO alter the following regex to support multiple relations (space separated)
477 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
478 $pagelink = $matches[1];
481 // don't try and run feeds through the html5 parser
482 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
484 if(stristr($html,'<rss') || stristr($html,'<feed'))
490 return(fetch_xrd_links($pagelink));
492 // If we haven't found any links, return the host xrd links (which we have already fetched)
503 // Given a host name, locate the LRDD template from that
504 // host. Returns the LRDD template or an empty string on
507 if(! function_exists('fetch_lrdd_template')) {
508 function fetch_lrdd_template($host) {
511 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
512 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
513 $links = fetch_xrd_links($url1);
514 logger('fetch_lrdd_template from: ' . $url1);
515 logger('template (https): ' . print_r($links,true));
516 if(! count($links)) {
517 logger('fetch_lrdd_template from: ' . $url2);
518 $links = fetch_xrd_links($url2);
519 logger('template (http): ' . print_r($links,true));
522 foreach($links as $link)
523 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
524 $tpl = $link['@attributes']['template'];
526 if(! strpos($tpl,'{uri}'))
531 // Given a URL, retrieve the page as an XRD document.
532 // Return an array of links.
533 // on error/failure return empty array.
535 if(! function_exists('fetch_xrd_links')) {
536 function fetch_xrd_links($url) {
538 $xrd_timeout = intval(get_config('system','xrd_timeout'));
540 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
542 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
544 if ((! $xml) || (! stristr($xml,'<xrd')))
547 // fix diaspora's bad xml
548 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
550 $h = parse_xml_string($xml);
554 $arr = convert_xml_element_to_array($h);
558 if(isset($arr['xrd']['link'])) {
559 $link = $arr['xrd']['link'];
560 if(! isset($link[0]))
561 $links = array($link);
565 if(isset($arr['xrd']['alias'])) {
566 $alias = $arr['xrd']['alias'];
567 if(! isset($alias[0]))
568 $aliases = array($alias);
571 if(is_array($aliases) && count($aliases)) {
572 foreach($aliases as $alias) {
573 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
578 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
585 // Take a URL from the wild, prepend http:// if necessary
586 // and check DNS to see if it's real
587 // return true if it's OK, false if something is wrong with it
589 if(! function_exists('validate_url')) {
590 function validate_url(&$url) {
592 // no naked subdomains (allow localhost for tests)
593 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
595 if(substr($url,0,4) != 'http')
596 $url = 'http://' . $url;
597 $h = @parse_url($url);
599 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
605 // checks that email is an actual resolvable internet address
607 if(! function_exists('validate_email')) {
608 function validate_email($addr) {
610 if(! strpos($addr,'@'))
612 $h = substr($addr,strpos($addr,'@') + 1);
614 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
620 // Check $url against our list of allowed sites,
621 // wildcards allowed. If allowed_sites is unset return true;
622 // If url is allowed, return true.
623 // otherwise, return false
625 if(! function_exists('allowed_url')) {
626 function allowed_url($url) {
628 $h = @parse_url($url);
634 $str_allowed = get_config('system','allowed_sites');
640 $host = strtolower($h['host']);
642 // always allow our own site
644 if($host == strtolower($_SERVER['SERVER_NAME']))
647 $fnmatch = function_exists('fnmatch');
648 $allowed = explode(',',$str_allowed);
650 if(count($allowed)) {
651 foreach($allowed as $a) {
652 $pat = strtolower(trim($a));
653 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
662 // check if email address is allowed to register here.
663 // Compare against our list (wildcards allowed).
664 // Returns false if not allowed, true if allowed or if
665 // allowed list is not configured.
667 if(! function_exists('allowed_email')) {
668 function allowed_email($email) {
671 $domain = strtolower(substr($email,strpos($email,'@') + 1));
675 $str_allowed = get_config('system','allowed_email');
681 $fnmatch = function_exists('fnmatch');
682 $allowed = explode(',',$str_allowed);
684 if(count($allowed)) {
685 foreach($allowed as $a) {
686 $pat = strtolower(trim($a));
687 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
697 if(! function_exists('avatar_img')) {
698 function avatar_img($email) {
702 $avatar['size'] = 175;
703 $avatar['email'] = $email;
705 $avatar['success'] = false;
707 call_hooks('avatar_lookup', $avatar);
709 if(! $avatar['success'])
710 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
712 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
713 return $avatar['url'];
717 if(! function_exists('parse_xml_string')) {
718 function parse_xml_string($s,$strict = true) {
720 if(! strstr($s,'<?xml'))
722 $s2 = substr($s,strpos($s,'<?xml'));
726 libxml_use_internal_errors(true);
728 $x = @simplexml_load_string($s2);
730 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
731 foreach(libxml_get_errors() as $err)
732 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
733 libxml_clear_errors();
738 function add_fcontact($arr,$update = false) {
741 $r = q("UPDATE `fcontact` SET
754 WHERE `url` = '%s' AND `network` = '%s' LIMIT 1",
756 dbesc($arr['photo']),
757 dbesc($arr['request']),
760 dbesc($arr['batch']),
761 dbesc($arr['notify']),
763 dbesc($arr['confirm']),
764 dbesc($arr['alias']),
765 dbesc($arr['pubkey']),
766 dbesc(datetime_convert()),
768 dbesc($arr['network'])
772 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
773 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
774 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
777 dbesc($arr['photo']),
778 dbesc($arr['request']),
781 dbesc($arr['batch']),
782 dbesc($arr['notify']),
784 dbesc($arr['confirm']),
785 dbesc($arr['network']),
786 dbesc($arr['alias']),
787 dbesc($arr['pubkey']),
788 dbesc(datetime_convert())
796 function scale_external_images($s,$include_link = true) {
801 $c = preg_match_all('/\[img\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
803 require_once('include/Photo.php');
804 foreach($matches as $mtch) {
805 logger('scale_external_image: ' . $mtch[1]);
806 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
807 if(stristr($mtch[1],$hostname))
809 $i = fetch_url($mtch[1]);
812 if($ph->is_valid()) {
813 $orig_width = $ph->getWidth();
814 $orig_height = $ph->getHeight();
816 if($orig_width > 640 || $orig_height > 640) {
818 $ph->scaleImage(640);
819 $new_width = $ph->getWidth();
820 $new_height = $ph->getHeight();
821 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
822 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $mtch[1] . '[/img]'
823 . "\n" . (($include_link)
824 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
826 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
836 function fix_contact_ssl_policy(&$contact,$new_policy) {
838 $ssl_changed = false;
839 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
841 $contact['url'] = str_replace('https:','http:',$contact['url']);
842 $contact['request'] = str_replace('https:','http:',$contact['request']);
843 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
844 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
845 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
846 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
849 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
851 $contact['url'] = str_replace('http:','https:',$contact['url']);
852 $contact['request'] = str_replace('http:','https:',$contact['request']);
853 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
854 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
855 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
856 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
860 q("update contact set
867 where id = %d limit 1",
868 dbesc($contact['url']),
869 dbesc($contact['request']),
870 dbesc($contact['notify']),
871 dbesc($contact['poll']),
872 dbesc($contact['confirm']),
873 dbesc($contact['poco']),
874 intval($contact['id'])