4 // curl wrapper. If binary flag is true, return binary
7 // Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
8 // to preserve cookies from one request to the next.
9 if(! function_exists('fetch_url')) {
10 function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null, $cookiejar = 0) {
16 array('timeout'=>$timeout,
17 'accept_content'=>$accept_content,
18 'cookiejar'=>$cookiejar
24 if(!function_exists('z_fetch_url')){
26 * @brief fetches an URL.
30 * @param boolean $binary default false
31 * TRUE if asked to return binary results (file download)
32 * @param int $redirects default 0
33 * internal use, recursion counter
34 * @param array $opts (optional parameters) assoziative array with:
35 * * \b accept_content => supply Accept: header with 'accept_content' as the value
36 * * \b timeout => int seconds, default system config value or 60 seconds
37 * * \b http_auth => username:password
38 * * \b novalidate => do not validate SSL certs, default is to validate using our CA list
39 * * \b nobody => only return the header
40 * * \b cookiejar => path to cookie jar file
42 * @return array an assoziative array with:
43 * * \e int \b return_code => HTTP return code or 0 if timeout or failure
44 * * \e boolean \b success => boolean true (if HTTP 2xx result) or false
45 * * \e string \b header => HTTP headers
46 * * \e string \b body => fetched content
48 function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
50 $ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");
53 $stamp1 = microtime(true);
57 $ch = @curl_init($url);
58 if(($redirects > 8) || (! $ch))
61 @curl_setopt($ch, CURLOPT_HEADER, true);
63 if(x($opts,"cookiejar")) {
64 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
65 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
68 // These settings aren't needed. We're following the location already.
69 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
70 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
72 if (x($opts,'accept_content')){
73 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
74 "Accept: " . $opts['accept_content']
78 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
79 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
83 if(x($opts,'headers')){
84 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
86 if(x($opts,'nobody')){
87 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
89 if(intval($timeout)) {
90 @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
93 $curl_time = intval(get_config('system','curl_timeout'));
94 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
96 // by default we will allow self-signed certs
97 // but you can override this
99 $check_cert = get_config('system','verifyssl');
100 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
101 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
103 $prx = get_config('system','proxy');
105 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
106 @curl_setopt($ch, CURLOPT_PROXY, $prx);
107 $prxusr = @get_config('system','proxyuser');
109 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
112 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
114 $a->set_curl_code(0);
116 // don't let curl abort the entire application
117 // if it throws any errors.
119 $s = @curl_exec($ch);
122 $curl_info = @curl_getinfo($ch);
124 $http_code = $curl_info['http_code'];
125 logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
128 // Pull out multiple headers, e.g. proxy and continuation headers
129 // allow for HTTP/2.x without fixing code
131 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
132 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
134 $base = substr($base,strlen($chunk));
137 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
138 $new_location_info = @parse_url($curl_info["redirect_url"]);
139 $old_location_info = @parse_url($curl_info["url"]);
141 $newurl = $curl_info["redirect_url"];
143 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
144 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
147 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
148 $newurl = trim(array_pop($matches));
150 if(strpos($newurl,'/') === 0)
151 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
152 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
155 return z_fetch_url($newurl,$binary, $redirects, $opts);
160 $a->set_curl_code($http_code);
161 $a->set_curl_content_type($curl_info['content_type']);
163 $body = substr($s,strlen($header));
164 $a->set_curl_headers($header);
168 $rc = intval($http_code);
169 $ret['return_code'] = $rc;
170 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
171 if(! $ret['success']) {
172 $ret['error'] = curl_error($ch);
173 $ret['debug'] = $curl_info;
174 logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
175 logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
177 $ret['body'] = substr($s,strlen($header));
178 $ret['header'] = $header;
179 if(x($opts,'debug')) {
180 $ret['debug'] = $curl_info;
184 $a->save_timestamp($stamp1, "network");
190 // post request to $url. $params is an array of post variables.
192 if(! function_exists('post_url')) {
193 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
194 $stamp1 = microtime(true);
197 $ch = curl_init($url);
198 if(($redirects > 8) || (! $ch))
201 logger("post_url: start ".$url, LOGGER_DATA);
203 curl_setopt($ch, CURLOPT_HEADER, true);
204 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
205 curl_setopt($ch, CURLOPT_POST,1);
206 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
207 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
209 if(intval($timeout)) {
210 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
213 $curl_time = intval(get_config('system','curl_timeout'));
214 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
217 if(defined('LIGHTTPD')) {
218 if(!is_array($headers)) {
219 $headers = array('Expect:');
221 if(!in_array('Expect:', $headers)) {
222 array_push($headers, 'Expect:');
227 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
229 $check_cert = get_config('system','verifyssl');
230 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
231 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
232 $prx = get_config('system','proxy');
234 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
235 curl_setopt($ch, CURLOPT_PROXY, $prx);
236 $prxusr = get_config('system','proxyuser');
238 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
241 $a->set_curl_code(0);
243 // don't let curl abort the entire application
244 // if it throws any errors.
246 $s = @curl_exec($ch);
249 $curl_info = curl_getinfo($ch);
250 $http_code = $curl_info['http_code'];
252 logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
256 // Pull out multiple headers, e.g. proxy and continuation headers
257 // allow for HTTP/2.x without fixing code
259 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
260 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
262 $base = substr($base,strlen($chunk));
265 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
267 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
268 $newurl = trim(array_pop($matches));
269 if(strpos($newurl,'/') === 0)
270 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
271 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
273 logger("post_url: redirect ".$url." to ".$newurl);
274 return post_url($newurl,$params, $headers, $redirects, $timeout);
275 //return fetch_url($newurl,false,$redirects,$timeout);
278 $a->set_curl_code($http_code);
279 $body = substr($s,strlen($header));
281 $a->set_curl_headers($header);
285 $a->save_timestamp($stamp1, "network");
287 logger("post_url: end ".$url, LOGGER_DATA);
292 // Generic XML return
293 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
294 // of $st and an optional text <message> of $message and terminates the current process.
296 if(! function_exists('xml_status')) {
297 function xml_status($st, $message = '') {
299 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
302 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
304 header( "Content-type: text/xml" );
305 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
306 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
311 if(! function_exists('http_status_exit')) {
312 function http_status_exit($val) {
317 if($val >= 200 && $val < 300)
320 logger('http_status_exit ' . $val);
321 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
327 // convert an XML document to a normalised, case-corrected array
330 if(! function_exists('convert_xml_element_to_array')) {
331 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
333 // If we're getting too deep, bail out
334 if ($recursion_depth > 512) {
338 if (!is_string($xml_element) &&
339 !is_array($xml_element) &&
340 (get_class($xml_element) == 'SimpleXMLElement')) {
341 $xml_element_copy = $xml_element;
342 $xml_element = get_object_vars($xml_element);
345 if (is_array($xml_element)) {
346 $result_array = array();
347 if (count($xml_element) <= 0) {
348 return (trim(strval($xml_element_copy)));
351 foreach($xml_element as $key=>$value) {
354 $result_array[strtolower($key)] =
355 convert_xml_element_to_array($value, $recursion_depth);
358 if ($recursion_depth == 0) {
359 $temp_array = $result_array;
360 $result_array = array(
361 strtolower($xml_element_copy->getName()) => $temp_array,
365 return ($result_array);
368 return (trim(strval($xml_element)));
372 // Given an email style address, perform webfinger lookup and
373 // return the resulting DFRN profile URL, or if no DFRN profile URL
374 // is located, returns an OStatus subscription template (prefixed
375 // with the string 'stat:' to identify it as on OStatus template).
376 // If this isn't an email style address just return $s.
377 // Return an empty string if email-style addresses but webfinger fails,
378 // or if the resultant personal XRD doesn't contain a supported
379 // subscription/friend-request attribute.
381 // amended 7/9/2011 to return an hcard which could save potentially loading
382 // a lengthy content page to scrape dfrn attributes
384 if(! function_exists('webfinger_dfrn')) {
385 function webfinger_dfrn($s,&$hcard) {
386 if(! strstr($s,'@')) {
391 $links = webfinger($s);
392 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
394 foreach($links as $link) {
395 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
396 $profile_link = $link['@attributes']['href'];
397 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
398 $profile_link = 'stat:' . $link['@attributes']['template'];
399 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
400 $hcard = $link['@attributes']['href'];
403 return $profile_link;
406 // Given an email style address, perform webfinger lookup and
407 // return the array of link attributes from the personal XRD file.
408 // On error/failure return an empty array.
411 if(! function_exists('webfinger')) {
412 function webfinger($s, $debug = false) {
415 $host = substr($s,strpos($s,'@') + 1);
418 $tpl = fetch_lrdd_template($host);
419 logger('webfinger: lrdd template: ' . $tpl);
421 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
422 logger('webfinger: pxrd: ' . $pxrd);
423 $links = fetch_xrd_links($pxrd);
424 if(! count($links)) {
425 // try with double slashes
426 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
427 logger('webfinger: pxrd: ' . $pxrd);
428 $links = fetch_xrd_links($pxrd);
436 if(! function_exists('lrdd')) {
437 function lrdd($uri, $debug = false) {
441 // default priority is host priority, host-meta first
445 // All we have is an email address. Resource-priority is irrelevant
446 // because our URI isn't directly resolvable.
448 if(strstr($uri,'@')) {
449 return(webfinger($uri));
452 // get the host meta file
454 $host = @parse_url($uri);
457 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
458 $url .= $host['host'] . '/.well-known/host-meta' ;
463 logger('lrdd: constructed url: ' . $url);
465 $xml = fetch_url($url);
467 $headers = $a->get_curl_headers();
472 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
474 if(! stristr($xml,'<xrd'))
477 $h = parse_xml_string($xml);
481 $arr = convert_xml_element_to_array($h);
483 if(isset($arr['xrd']['property'])) {
484 $property = $arr['crd']['property'];
485 if(! isset($property[0]))
486 $properties = array($property);
488 $properties = $property;
489 foreach($properties as $prop)
490 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
491 $priority = 'resource';
494 // save the links in case we need them
498 if(isset($arr['xrd']['link'])) {
499 $link = $arr['xrd']['link'];
500 if(! isset($link[0]))
501 $links = array($link);
506 // do we have a template or href?
509 foreach($links as $link) {
510 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
511 if(x($link['@attributes'],'template'))
512 $tpl = $link['@attributes']['template'];
513 elseif(x($link['@attributes'],'href'))
514 $href = $link['@attributes']['href'];
519 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
522 if($priority === 'host') {
524 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
528 logger('lrdd: (host priority) pxrd: ' . $pxrd);
529 $links = fetch_xrd_links($pxrd);
533 $lines = explode("\n",$headers);
535 foreach($lines as $line) {
536 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
537 return(fetch_xrd_links($matches[1]));
545 // priority 'resource'
548 $html = fetch_url($uri);
549 $headers = $a->get_curl_headers();
550 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
552 // don't try and parse raw xml as html
553 if(! strstr($html,'<?xml')) {
554 require_once('library/HTML5/Parser.php');
557 $dom = HTML5_Parser::parse($html);
558 } catch (DOMException $e) {
559 logger('lrdd: parse error: ' . $e);
562 if(isset($dom) && $dom) {
563 $items = $dom->getElementsByTagName('link');
564 foreach($items as $item) {
565 $x = $item->getAttribute('rel');
567 $pagelink = $item->getAttribute('href');
575 return(fetch_xrd_links($pagelink));
577 // next look in HTTP headers
579 $lines = explode("\n",$headers);
581 foreach($lines as $line) {
582 // TODO alter the following regex to support multiple relations (space separated)
583 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
584 $pagelink = $matches[1];
587 // don't try and run feeds through the html5 parser
588 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
590 if(stristr($html,'<rss') || stristr($html,'<feed'))
596 return(fetch_xrd_links($pagelink));
598 // If we haven't found any links, return the host xrd links (which we have already fetched)
609 // Given a host name, locate the LRDD template from that
610 // host. Returns the LRDD template or an empty string on
613 if(! function_exists('fetch_lrdd_template')) {
614 function fetch_lrdd_template($host) {
617 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
618 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
619 $links = fetch_xrd_links($url1);
620 logger('fetch_lrdd_template from: ' . $url1);
621 logger('template (https): ' . print_r($links,true));
622 if(! count($links)) {
623 logger('fetch_lrdd_template from: ' . $url2);
624 $links = fetch_xrd_links($url2);
625 logger('template (http): ' . print_r($links,true));
628 foreach($links as $link)
629 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
630 $tpl = $link['@attributes']['template'];
632 if(! strpos($tpl,'{uri}'))
637 // Given a URL, retrieve the page as an XRD document.
638 // Return an array of links.
639 // on error/failure return empty array.
641 if(! function_exists('fetch_xrd_links')) {
642 function fetch_xrd_links($url) {
644 $xrd_timeout = intval(get_config('system','xrd_timeout'));
646 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20), "application/xrd+xml");
648 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
650 if ((! $xml) || (! stristr($xml,'<xrd')))
653 // fix diaspora's bad xml
654 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
656 $h = parse_xml_string($xml);
660 $arr = convert_xml_element_to_array($h);
664 if(isset($arr['xrd']['link'])) {
665 $link = $arr['xrd']['link'];
666 if(! isset($link[0]))
667 $links = array($link);
671 if(isset($arr['xrd']['alias'])) {
672 $alias = $arr['xrd']['alias'];
673 if(! isset($alias[0]))
674 $aliases = array($alias);
677 if(is_array($aliases) && count($aliases)) {
678 foreach($aliases as $alias) {
679 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
684 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
691 // Take a URL from the wild, prepend http:// if necessary
692 // and check DNS to see if it's real (or check if is a valid IP address)
693 // return true if it's OK, false if something is wrong with it
695 if(! function_exists('validate_url')) {
696 function validate_url(&$url) {
698 if(get_config('system','disable_url_validation'))
700 // no naked subdomains (allow localhost for tests)
701 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
703 if(substr($url,0,4) != 'http')
704 $url = 'http://' . $url;
705 $h = @parse_url($url);
707 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
713 // checks that email is an actual resolvable internet address
715 if(! function_exists('validate_email')) {
716 function validate_email($addr) {
718 if(get_config('system','disable_email_validation'))
721 if(! strpos($addr,'@'))
723 $h = substr($addr,strpos($addr,'@') + 1);
725 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
731 // Check $url against our list of allowed sites,
732 // wildcards allowed. If allowed_sites is unset return true;
733 // If url is allowed, return true.
734 // otherwise, return false
736 if(! function_exists('allowed_url')) {
737 function allowed_url($url) {
739 $h = @parse_url($url);
745 $str_allowed = get_config('system','allowed_sites');
751 $host = strtolower($h['host']);
753 // always allow our own site
755 if($host == strtolower($_SERVER['SERVER_NAME']))
758 $fnmatch = function_exists('fnmatch');
759 $allowed = explode(',',$str_allowed);
761 if(count($allowed)) {
762 foreach($allowed as $a) {
763 $pat = strtolower(trim($a));
764 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
773 // check if email address is allowed to register here.
774 // Compare against our list (wildcards allowed).
775 // Returns false if not allowed, true if allowed or if
776 // allowed list is not configured.
778 if(! function_exists('allowed_email')) {
779 function allowed_email($email) {
782 $domain = strtolower(substr($email,strpos($email,'@') + 1));
786 $str_allowed = get_config('system','allowed_email');
792 $fnmatch = function_exists('fnmatch');
793 $allowed = explode(',',$str_allowed);
795 if(count($allowed)) {
796 foreach($allowed as $a) {
797 $pat = strtolower(trim($a));
798 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
808 if(! function_exists('avatar_img')) {
809 function avatar_img($email) {
813 $avatar['size'] = 175;
814 $avatar['email'] = $email;
816 $avatar['success'] = false;
818 call_hooks('avatar_lookup', $avatar);
820 if(! $avatar['success'])
821 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
823 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
824 return $avatar['url'];
828 if(! function_exists('parse_xml_string')) {
829 function parse_xml_string($s,$strict = true) {
831 if(! strstr($s,'<?xml'))
833 $s2 = substr($s,strpos($s,'<?xml'));
837 libxml_use_internal_errors(true);
839 $x = @simplexml_load_string($s2);
841 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
842 foreach(libxml_get_errors() as $err)
843 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
844 libxml_clear_errors();
849 function add_fcontact($arr,$update = false) {
852 $r = q("UPDATE `fcontact` SET
865 WHERE `url` = '%s' AND `network` = '%s'",
867 dbesc($arr['photo']),
868 dbesc($arr['request']),
871 dbesc($arr['batch']),
872 dbesc($arr['notify']),
874 dbesc($arr['confirm']),
875 dbesc($arr['alias']),
876 dbesc($arr['pubkey']),
877 dbesc(datetime_convert()),
879 dbesc($arr['network'])
883 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
884 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
885 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
888 dbesc($arr['photo']),
889 dbesc($arr['request']),
892 dbesc($arr['batch']),
893 dbesc($arr['notify']),
895 dbesc($arr['confirm']),
896 dbesc($arr['network']),
897 dbesc($arr['alias']),
898 dbesc($arr['pubkey']),
899 dbesc(datetime_convert())
907 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
909 // Suppress "view full size"
910 if (intval(get_config('system','no_view_full_size')))
911 $include_link = false;
915 // Picture addresses can contain special characters
916 $s = htmlspecialchars_decode($srctext);
919 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
921 require_once('include/Photo.php');
922 foreach($matches as $mtch) {
923 logger('scale_external_image: ' . $mtch[1]);
925 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
926 if(stristr($mtch[1],$hostname))
929 // $scale_replace, if passed, is an array of two elements. The
930 // first is the name of the full-size image. The second is the
931 // name of a remote, scaled-down version of the full size image.
932 // This allows Friendica to display the smaller remote image if
933 // one exists, while still linking to the full-size image
935 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
938 $i = @fetch_url($scaled);
942 // guess mimetype from headers or filename
943 $type = guess_image_type($mtch[1],true);
946 $ph = new Photo($i, $type);
947 if($ph->is_valid()) {
948 $orig_width = $ph->getWidth();
949 $orig_height = $ph->getHeight();
951 if($orig_width > 640 || $orig_height > 640) {
953 $ph->scaleImage(640);
954 $new_width = $ph->getWidth();
955 $new_height = $ph->getHeight();
956 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
957 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
958 . "\n" . (($include_link)
959 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
961 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
968 // replace the special char encoding
969 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
974 function fix_contact_ssl_policy(&$contact,$new_policy) {
976 $ssl_changed = false;
977 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
979 $contact['url'] = str_replace('https:','http:',$contact['url']);
980 $contact['request'] = str_replace('https:','http:',$contact['request']);
981 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
982 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
983 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
984 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
987 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
989 $contact['url'] = str_replace('http:','https:',$contact['url']);
990 $contact['request'] = str_replace('http:','https:',$contact['request']);
991 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
992 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
993 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
994 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
998 q("update contact set
1005 where id = %d limit 1",
1006 dbesc($contact['url']),
1007 dbesc($contact['request']),
1008 dbesc($contact['notify']),
1009 dbesc($contact['poll']),
1010 dbesc($contact['confirm']),
1011 dbesc($contact['poco']),
1012 intval($contact['id'])
1020 * xml2array() will convert the given XML text to an array in the XML structure.
1021 * Link: http://www.bin-co.com/php/scripts/xml2array/
1022 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
1023 * Arguments : $contents - The XML text
1024 * $namespaces - true or false include namespace information in the returned array as array elements.
1025 * $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
1026 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
1027 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
1028 * Examples: $array = xml2array(file_get_contents('feed.xml'));
1029 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
1032 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
1033 if(!$contents) return array();
1035 if(!function_exists('xml_parser_create')) {
1036 logger('xml2array: parser function missing');
1041 libxml_use_internal_errors(true);
1042 libxml_clear_errors();
1045 $parser = @xml_parser_create_ns("UTF-8",':');
1047 $parser = @xml_parser_create();
1050 logger('xml2array: xml_parser_create: no resource');
1054 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
1055 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
1056 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1057 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
1058 @xml_parse_into_struct($parser, trim($contents), $xml_values);
1059 @xml_parser_free($parser);
1062 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
1063 foreach(libxml_get_errors() as $err)
1064 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
1065 libxml_clear_errors();
1070 $xml_array = array();
1072 $opened_tags = array();
1075 $current = &$xml_array; // Reference
1077 // Go through the tags.
1078 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
1079 foreach($xml_values as $data) {
1080 unset($attributes,$value); // Remove existing values, or there will be trouble
1082 // This command will extract these variables into the foreach scope
1083 // tag(string), type(string), level(int), attributes(array).
1084 extract($data); // We could use the array by itself, but this cooler.
1087 $attributes_data = array();
1090 if($priority == 'tag') $result = $value;
1091 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1094 //Set the attributes too.
1095 if(isset($attributes) and $get_attributes) {
1096 foreach($attributes as $attr => $val) {
1097 if($priority == 'tag') $attributes_data[$attr] = $val;
1098 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1102 // See tag status and do the needed.
1103 if($namespaces && strpos($tag,':')) {
1104 $namespc = substr($tag,0,strrpos($tag,':'));
1105 $tag = strtolower(substr($tag,strlen($namespc)+1));
1106 $result['@namespace'] = $namespc;
1108 $tag = strtolower($tag);
1110 if($type == "open") { // The starting of the tag '<tag>'
1111 $parent[$level-1] = &$current;
1112 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1113 $current[$tag] = $result;
1114 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1115 $repeated_tag_index[$tag.'_'.$level] = 1;
1117 $current = &$current[$tag];
1119 } else { // There was another element with the same tag name
1121 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1122 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1123 $repeated_tag_index[$tag.'_'.$level]++;
1124 } else { // This section will make the value an array if multiple tags with the same name appear together
1125 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1126 $repeated_tag_index[$tag.'_'.$level] = 2;
1128 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1129 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1130 unset($current[$tag.'_attr']);
1134 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1135 $current = &$current[$tag][$last_item_index];
1138 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1139 //See if the key is already taken.
1140 if(!isset($current[$tag])) { //New Key
1141 $current[$tag] = $result;
1142 $repeated_tag_index[$tag.'_'.$level] = 1;
1143 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1145 } else { // If taken, put all things inside a list(array)
1146 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1148 // ...push the new element into that array.
1149 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1151 if($priority == 'tag' and $get_attributes and $attributes_data) {
1152 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1154 $repeated_tag_index[$tag.'_'.$level]++;
1156 } else { // If it is not an array...
1157 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1158 $repeated_tag_index[$tag.'_'.$level] = 1;
1159 if($priority == 'tag' and $get_attributes) {
1160 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1162 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1163 unset($current[$tag.'_attr']);
1166 if($attributes_data) {
1167 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1170 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1174 } elseif($type == 'close') { // End of tag '</tag>'
1175 $current = &$parent[$level-1];
1182 function original_url($url, $depth=1, $fetchbody = false) {
1186 // Remove Analytics Data from Google and other tracking platforms
1187 $urldata = parse_url($url);
1188 if (is_string($urldata["query"])) {
1189 $query = $urldata["query"];
1190 parse_str($query, $querydata);
1192 if (is_array($querydata))
1193 foreach ($querydata AS $param=>$value)
1194 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
1195 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
1196 "fb_action_ids", "fb_action_types", "fb_ref",
1198 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
1200 $pair = $param."=".urlencode($value);
1201 $url = str_replace($pair, "", $url);
1203 // Second try: if the url isn't encoded completely
1204 $pair = $param."=".str_replace(" ", "+", $value);
1205 $url = str_replace($pair, "", $url);
1207 // Third try: Maybey the url isn't encoded at all
1208 $pair = $param."=".$value;
1209 $url = str_replace($pair, "", $url);
1211 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
1214 if (substr($url, -1, 1) == "?")
1215 $url = substr($url, 0, -1);
1221 $url = trim($url, "'");
1223 $stamp1 = microtime(true);
1225 $siteinfo = array();
1227 curl_setopt($ch, CURLOPT_URL, $url);
1228 curl_setopt($ch, CURLOPT_HEADER, 1);
1229 curl_setopt($ch, CURLOPT_NOBODY, 1);
1230 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1231 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1232 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1234 $header = curl_exec($ch);
1235 $curl_info = @curl_getinfo($ch);
1236 $http_code = $curl_info['http_code'];
1239 $a->save_timestamp($stamp1, "network");
1241 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
1242 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
1243 if ($curl_info['redirect_url'] != "")
1244 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
1246 return(original_url($curl_info['location'], ++$depth, $fetchbody));
1249 // Check for redirects in the meta elements of the body if there are no redirects in the header.
1251 return(original_url($url, ++$depth, true));
1253 // if the file is too large then exit
1254 if ($curl_info["download_content_length"] > 1000000)
1257 // if it isn't a HTML file then exit
1258 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
1261 $stamp1 = microtime(true);
1264 curl_setopt($ch, CURLOPT_URL, $url);
1265 curl_setopt($ch, CURLOPT_HEADER, 0);
1266 curl_setopt($ch, CURLOPT_NOBODY, 0);
1267 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1268 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1269 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1271 $body = curl_exec($ch);
1274 $a->save_timestamp($stamp1, "network");
1276 if (trim($body) == "")
1279 // Check for redirect in meta elements
1280 $doc = new DOMDocument();
1281 @$doc->loadHTML($body);
1283 $xpath = new DomXPath($doc);
1285 $list = $xpath->query("//meta[@content]");
1286 foreach ($list as $node) {
1288 if ($node->attributes->length)
1289 foreach ($node->attributes as $attribute)
1290 $attr[$attribute->name] = $attribute->value;
1292 if (@$attr["http-equiv"] == 'refresh') {
1293 $path = $attr["content"];
1294 $pathinfo = explode(";", $path);
1296 foreach ($pathinfo AS $value)
1297 if (substr(strtolower($value), 0, 4) == "url=")
1298 return(original_url(substr($value, 4), ++$depth));
1305 if (!function_exists('short_link')) {
1306 function short_link($url) {
1307 require_once('library/slinky.php');
1308 $slinky = new Slinky($url);
1309 $yourls_url = get_config('yourls','url1');
1311 $yourls_username = get_config('yourls','username1');
1312 $yourls_password = get_config('yourls', 'password1');
1313 $yourls_ssl = get_config('yourls', 'ssl1');
1314 $yourls = new Slinky_YourLS();
1315 $yourls->set('username', $yourls_username);
1316 $yourls->set('password', $yourls_password);
1317 $yourls->set('ssl', $yourls_ssl);
1318 $yourls->set('yourls-url', $yourls_url);
1319 $slinky->set_cascade( array($yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1321 // setup a cascade of shortening services
1322 // try to get a short link from these services
1323 // in the order ur1.ca, trim, id.gd, tinyurl
1324 $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1326 return $slinky->short();