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
26 if(!function_exists('z_fetch_url')){
28 * @brief fetches an URL.
32 * @param boolean $binary default false
33 * TRUE if asked to return binary results (file download)
34 * @param int $redirects default 0
35 * internal use, recursion counter
36 * @param array $opts (optional parameters) assoziative array with:
37 * * \b accept_content => supply Accept: header with 'accept_content' as the value
38 * * \b timeout => int seconds, default system config value or 60 seconds
39 * * \b http_auth => username:password
40 * * \b novalidate => do not validate SSL certs, default is to validate using our CA list
41 * * \b nobody => only return the header
42 * * \b cookiejar => path to cookie jar file
44 * @return array an assoziative array with:
45 * * \e int \b return_code => HTTP return code or 0 if timeout or failure
46 * * \e boolean \b success => boolean true (if HTTP 2xx result) or false
47 * * \e string \b header => HTTP headers
48 * * \e string \b body => fetched content
50 function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
52 $ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");
55 $stamp1 = microtime(true);
59 $ch = @curl_init($url);
60 if(($redirects > 8) || (! $ch))
63 @curl_setopt($ch, CURLOPT_HEADER, true);
65 if(x($opts,"cookiejar")) {
66 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
67 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
70 // These settings aren't needed. We're following the location already.
71 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
72 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
74 if (x($opts,'accept_content')){
75 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
76 "Accept: " . $opts['accept_content']
80 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
81 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
85 if(x($opts,'headers')){
86 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
88 if(x($opts,'nobody')){
89 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
91 if(intval($timeout)) {
92 @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
95 $curl_time = intval(get_config('system','curl_timeout'));
96 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
98 // by default we will allow self-signed certs
99 // but you can override this
101 $check_cert = get_config('system','verifyssl');
102 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
103 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
105 $prx = get_config('system','proxy');
107 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
108 @curl_setopt($ch, CURLOPT_PROXY, $prx);
109 $prxusr = @get_config('system','proxyuser');
111 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
114 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
116 $a->set_curl_code(0);
118 // don't let curl abort the entire application
119 // if it throws any errors.
121 $s = @curl_exec($ch);
124 $curl_info = @curl_getinfo($ch);
126 $http_code = $curl_info['http_code'];
127 logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
130 // Pull out multiple headers, e.g. proxy and continuation headers
131 // allow for HTTP/2.x without fixing code
133 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
134 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
136 $base = substr($base,strlen($chunk));
139 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
140 $new_location_info = @parse_url($curl_info["redirect_url"]);
141 $old_location_info = @parse_url($curl_info["url"]);
143 $newurl = $curl_info["redirect_url"];
145 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
146 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
149 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
150 $newurl = trim(array_pop($matches));
152 if(strpos($newurl,'/') === 0)
153 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
154 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
157 return fetch_url($newurl,$binary,$redirects,$timeout,$accept_content,$cookiejar);
162 $a->set_curl_code($http_code);
163 $a->set_curl_content_type($curl_info['content_type']);
165 $body = substr($s,strlen($header));
166 $a->set_curl_headers($header);
170 $rc = intval($http_code);
171 $ret['return_code'] = $rc;
172 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
173 if(! $ret['success']) {
174 $ret['error'] = curl_error($ch);
175 $ret['debug'] = $curl_info;
176 logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
177 logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
179 $ret['body'] = substr($s,strlen($header));
180 $ret['header'] = $header;
181 if(x($opts,'debug')) {
182 $ret['debug'] = $curl_info;
186 $a->save_timestamp($stamp1, "network");
192 // post request to $url. $params is an array of post variables.
194 if(! function_exists('post_url')) {
195 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
196 $stamp1 = microtime(true);
199 $ch = curl_init($url);
200 if(($redirects > 8) || (! $ch))
203 logger("post_url: start ".$url, LOGGER_DATA);
205 curl_setopt($ch, CURLOPT_HEADER, true);
206 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
207 curl_setopt($ch, CURLOPT_POST,1);
208 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
209 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
211 if(intval($timeout)) {
212 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
215 $curl_time = intval(get_config('system','curl_timeout'));
216 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
219 if(defined('LIGHTTPD')) {
220 if(!is_array($headers)) {
221 $headers = array('Expect:');
223 if(!in_array('Expect:', $headers)) {
224 array_push($headers, 'Expect:');
229 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
231 $check_cert = get_config('system','verifyssl');
232 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
233 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
234 $prx = get_config('system','proxy');
236 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
237 curl_setopt($ch, CURLOPT_PROXY, $prx);
238 $prxusr = get_config('system','proxyuser');
240 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
243 $a->set_curl_code(0);
245 // don't let curl abort the entire application
246 // if it throws any errors.
248 $s = @curl_exec($ch);
251 $curl_info = curl_getinfo($ch);
252 $http_code = $curl_info['http_code'];
254 logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
258 // Pull out multiple headers, e.g. proxy and continuation headers
259 // allow for HTTP/2.x without fixing code
261 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
262 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
264 $base = substr($base,strlen($chunk));
267 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
269 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
270 $newurl = trim(array_pop($matches));
271 if(strpos($newurl,'/') === 0)
272 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
273 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
275 logger("post_url: redirect ".$url." to ".$newurl);
276 return post_url($newurl,$params, $headers, $redirects, $timeout);
277 //return fetch_url($newurl,false,$redirects,$timeout);
280 $a->set_curl_code($http_code);
281 $body = substr($s,strlen($header));
283 $a->set_curl_headers($header);
287 $a->save_timestamp($stamp1, "network");
289 logger("post_url: end ".$url, LOGGER_DATA);
294 // Generic XML return
295 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
296 // of $st and an optional text <message> of $message and terminates the current process.
298 if(! function_exists('xml_status')) {
299 function xml_status($st, $message = '') {
301 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
304 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
306 header( "Content-type: text/xml" );
307 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
308 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
313 if(! function_exists('http_status_exit')) {
314 function http_status_exit($val) {
319 if($val >= 200 && $val < 300)
322 logger('http_status_exit ' . $val);
323 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
329 // convert an XML document to a normalised, case-corrected array
332 if(! function_exists('convert_xml_element_to_array')) {
333 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
335 // If we're getting too deep, bail out
336 if ($recursion_depth > 512) {
340 if (!is_string($xml_element) &&
341 !is_array($xml_element) &&
342 (get_class($xml_element) == 'SimpleXMLElement')) {
343 $xml_element_copy = $xml_element;
344 $xml_element = get_object_vars($xml_element);
347 if (is_array($xml_element)) {
348 $result_array = array();
349 if (count($xml_element) <= 0) {
350 return (trim(strval($xml_element_copy)));
353 foreach($xml_element as $key=>$value) {
356 $result_array[strtolower($key)] =
357 convert_xml_element_to_array($value, $recursion_depth);
360 if ($recursion_depth == 0) {
361 $temp_array = $result_array;
362 $result_array = array(
363 strtolower($xml_element_copy->getName()) => $temp_array,
367 return ($result_array);
370 return (trim(strval($xml_element)));
374 // Given an email style address, perform webfinger lookup and
375 // return the resulting DFRN profile URL, or if no DFRN profile URL
376 // is located, returns an OStatus subscription template (prefixed
377 // with the string 'stat:' to identify it as on OStatus template).
378 // If this isn't an email style address just return $s.
379 // Return an empty string if email-style addresses but webfinger fails,
380 // or if the resultant personal XRD doesn't contain a supported
381 // subscription/friend-request attribute.
383 // amended 7/9/2011 to return an hcard which could save potentially loading
384 // a lengthy content page to scrape dfrn attributes
386 if(! function_exists('webfinger_dfrn')) {
387 function webfinger_dfrn($s,&$hcard) {
388 if(! strstr($s,'@')) {
393 $links = webfinger($s);
394 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
396 foreach($links as $link) {
397 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
398 $profile_link = $link['@attributes']['href'];
399 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
400 $profile_link = 'stat:' . $link['@attributes']['template'];
401 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
402 $hcard = $link['@attributes']['href'];
405 return $profile_link;
408 // Given an email style address, perform webfinger lookup and
409 // return the array of link attributes from the personal XRD file.
410 // On error/failure return an empty array.
413 if(! function_exists('webfinger')) {
414 function webfinger($s, $debug = false) {
417 $host = substr($s,strpos($s,'@') + 1);
420 $tpl = fetch_lrdd_template($host);
421 logger('webfinger: lrdd template: ' . $tpl);
423 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
424 logger('webfinger: pxrd: ' . $pxrd);
425 $links = fetch_xrd_links($pxrd);
426 if(! count($links)) {
427 // try with double slashes
428 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
429 logger('webfinger: pxrd: ' . $pxrd);
430 $links = fetch_xrd_links($pxrd);
438 if(! function_exists('lrdd')) {
439 function lrdd($uri, $debug = false) {
443 // default priority is host priority, host-meta first
447 // All we have is an email address. Resource-priority is irrelevant
448 // because our URI isn't directly resolvable.
450 if(strstr($uri,'@')) {
451 return(webfinger($uri));
454 // get the host meta file
456 $host = @parse_url($uri);
459 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
460 $url .= $host['host'] . '/.well-known/host-meta' ;
465 logger('lrdd: constructed url: ' . $url);
467 $xml = fetch_url($url);
469 $headers = $a->get_curl_headers();
474 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
476 if(! stristr($xml,'<xrd'))
479 $h = parse_xml_string($xml);
483 $arr = convert_xml_element_to_array($h);
485 if(isset($arr['xrd']['property'])) {
486 $property = $arr['crd']['property'];
487 if(! isset($property[0]))
488 $properties = array($property);
490 $properties = $property;
491 foreach($properties as $prop)
492 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
493 $priority = 'resource';
496 // save the links in case we need them
500 if(isset($arr['xrd']['link'])) {
501 $link = $arr['xrd']['link'];
502 if(! isset($link[0]))
503 $links = array($link);
508 // do we have a template or href?
511 foreach($links as $link) {
512 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
513 if(x($link['@attributes'],'template'))
514 $tpl = $link['@attributes']['template'];
515 elseif(x($link['@attributes'],'href'))
516 $href = $link['@attributes']['href'];
521 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
524 if($priority === 'host') {
526 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
530 logger('lrdd: (host priority) pxrd: ' . $pxrd);
531 $links = fetch_xrd_links($pxrd);
535 $lines = explode("\n",$headers);
537 foreach($lines as $line) {
538 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
539 return(fetch_xrd_links($matches[1]));
547 // priority 'resource'
550 $html = fetch_url($uri);
551 $headers = $a->get_curl_headers();
552 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
554 // don't try and parse raw xml as html
555 if(! strstr($html,'<?xml')) {
556 require_once('library/HTML5/Parser.php');
559 $dom = HTML5_Parser::parse($html);
560 } catch (DOMException $e) {
561 logger('lrdd: parse error: ' . $e);
564 if(isset($dom) && $dom) {
565 $items = $dom->getElementsByTagName('link');
566 foreach($items as $item) {
567 $x = $item->getAttribute('rel');
569 $pagelink = $item->getAttribute('href');
577 return(fetch_xrd_links($pagelink));
579 // next look in HTTP headers
581 $lines = explode("\n",$headers);
583 foreach($lines as $line) {
584 // TODO alter the following regex to support multiple relations (space separated)
585 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
586 $pagelink = $matches[1];
589 // don't try and run feeds through the html5 parser
590 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
592 if(stristr($html,'<rss') || stristr($html,'<feed'))
598 return(fetch_xrd_links($pagelink));
600 // If we haven't found any links, return the host xrd links (which we have already fetched)
611 // Given a host name, locate the LRDD template from that
612 // host. Returns the LRDD template or an empty string on
615 if(! function_exists('fetch_lrdd_template')) {
616 function fetch_lrdd_template($host) {
619 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
620 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
621 $links = fetch_xrd_links($url1);
622 logger('fetch_lrdd_template from: ' . $url1);
623 logger('template (https): ' . print_r($links,true));
624 if(! count($links)) {
625 logger('fetch_lrdd_template from: ' . $url2);
626 $links = fetch_xrd_links($url2);
627 logger('template (http): ' . print_r($links,true));
630 foreach($links as $link)
631 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
632 $tpl = $link['@attributes']['template'];
634 if(! strpos($tpl,'{uri}'))
639 // Given a URL, retrieve the page as an XRD document.
640 // Return an array of links.
641 // on error/failure return empty array.
643 if(! function_exists('fetch_xrd_links')) {
644 function fetch_xrd_links($url) {
646 $xrd_timeout = intval(get_config('system','xrd_timeout'));
648 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20), "application/xrd+xml");
650 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
652 if ((! $xml) || (! stristr($xml,'<xrd')))
655 // fix diaspora's bad xml
656 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
658 $h = parse_xml_string($xml);
662 $arr = convert_xml_element_to_array($h);
666 if(isset($arr['xrd']['link'])) {
667 $link = $arr['xrd']['link'];
668 if(! isset($link[0]))
669 $links = array($link);
673 if(isset($arr['xrd']['alias'])) {
674 $alias = $arr['xrd']['alias'];
675 if(! isset($alias[0]))
676 $aliases = array($alias);
679 if(is_array($aliases) && count($aliases)) {
680 foreach($aliases as $alias) {
681 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
686 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
693 // Take a URL from the wild, prepend http:// if necessary
694 // and check DNS to see if it's real (or check if is a valid IP address)
695 // return true if it's OK, false if something is wrong with it
697 if(! function_exists('validate_url')) {
698 function validate_url(&$url) {
700 if(get_config('system','disable_url_validation'))
702 // no naked subdomains (allow localhost for tests)
703 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
705 if(substr($url,0,4) != 'http')
706 $url = 'http://' . $url;
707 $h = @parse_url($url);
709 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
715 // checks that email is an actual resolvable internet address
717 if(! function_exists('validate_email')) {
718 function validate_email($addr) {
720 if(get_config('system','disable_email_validation'))
723 if(! strpos($addr,'@'))
725 $h = substr($addr,strpos($addr,'@') + 1);
727 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
733 // Check $url against our list of allowed sites,
734 // wildcards allowed. If allowed_sites is unset return true;
735 // If url is allowed, return true.
736 // otherwise, return false
738 if(! function_exists('allowed_url')) {
739 function allowed_url($url) {
741 $h = @parse_url($url);
747 $str_allowed = get_config('system','allowed_sites');
753 $host = strtolower($h['host']);
755 // always allow our own site
757 if($host == strtolower($_SERVER['SERVER_NAME']))
760 $fnmatch = function_exists('fnmatch');
761 $allowed = explode(',',$str_allowed);
763 if(count($allowed)) {
764 foreach($allowed as $a) {
765 $pat = strtolower(trim($a));
766 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
775 // check if email address is allowed to register here.
776 // Compare against our list (wildcards allowed).
777 // Returns false if not allowed, true if allowed or if
778 // allowed list is not configured.
780 if(! function_exists('allowed_email')) {
781 function allowed_email($email) {
784 $domain = strtolower(substr($email,strpos($email,'@') + 1));
788 $str_allowed = get_config('system','allowed_email');
794 $fnmatch = function_exists('fnmatch');
795 $allowed = explode(',',$str_allowed);
797 if(count($allowed)) {
798 foreach($allowed as $a) {
799 $pat = strtolower(trim($a));
800 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
810 if(! function_exists('avatar_img')) {
811 function avatar_img($email) {
815 $avatar['size'] = 175;
816 $avatar['email'] = $email;
818 $avatar['success'] = false;
820 call_hooks('avatar_lookup', $avatar);
822 if(! $avatar['success'])
823 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
825 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
826 return $avatar['url'];
830 if(! function_exists('parse_xml_string')) {
831 function parse_xml_string($s,$strict = true) {
833 if(! strstr($s,'<?xml'))
835 $s2 = substr($s,strpos($s,'<?xml'));
839 libxml_use_internal_errors(true);
841 $x = @simplexml_load_string($s2);
843 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
844 foreach(libxml_get_errors() as $err)
845 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
846 libxml_clear_errors();
851 function add_fcontact($arr,$update = false) {
854 $r = q("UPDATE `fcontact` SET
867 WHERE `url` = '%s' AND `network` = '%s'",
869 dbesc($arr['photo']),
870 dbesc($arr['request']),
873 dbesc($arr['batch']),
874 dbesc($arr['notify']),
876 dbesc($arr['confirm']),
877 dbesc($arr['alias']),
878 dbesc($arr['pubkey']),
879 dbesc(datetime_convert()),
881 dbesc($arr['network'])
885 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
886 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
887 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
890 dbesc($arr['photo']),
891 dbesc($arr['request']),
894 dbesc($arr['batch']),
895 dbesc($arr['notify']),
897 dbesc($arr['confirm']),
898 dbesc($arr['network']),
899 dbesc($arr['alias']),
900 dbesc($arr['pubkey']),
901 dbesc(datetime_convert())
909 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
911 // Suppress "view full size"
912 if (intval(get_config('system','no_view_full_size')))
913 $include_link = false;
917 // Picture addresses can contain special characters
918 $s = htmlspecialchars_decode($srctext);
921 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
923 require_once('include/Photo.php');
924 foreach($matches as $mtch) {
925 logger('scale_external_image: ' . $mtch[1]);
927 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
928 if(stristr($mtch[1],$hostname))
931 // $scale_replace, if passed, is an array of two elements. The
932 // first is the name of the full-size image. The second is the
933 // name of a remote, scaled-down version of the full size image.
934 // This allows Friendica to display the smaller remote image if
935 // one exists, while still linking to the full-size image
937 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
940 $i = @fetch_url($scaled);
944 // guess mimetype from headers or filename
945 $type = guess_image_type($mtch[1],true);
948 $ph = new Photo($i, $type);
949 if($ph->is_valid()) {
950 $orig_width = $ph->getWidth();
951 $orig_height = $ph->getHeight();
953 if($orig_width > 640 || $orig_height > 640) {
955 $ph->scaleImage(640);
956 $new_width = $ph->getWidth();
957 $new_height = $ph->getHeight();
958 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
959 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
960 . "\n" . (($include_link)
961 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
963 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
970 // replace the special char encoding
971 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
976 function fix_contact_ssl_policy(&$contact,$new_policy) {
978 $ssl_changed = false;
979 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
981 $contact['url'] = str_replace('https:','http:',$contact['url']);
982 $contact['request'] = str_replace('https:','http:',$contact['request']);
983 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
984 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
985 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
986 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
989 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
991 $contact['url'] = str_replace('http:','https:',$contact['url']);
992 $contact['request'] = str_replace('http:','https:',$contact['request']);
993 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
994 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
995 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
996 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
1000 q("update contact set
1007 where id = %d limit 1",
1008 dbesc($contact['url']),
1009 dbesc($contact['request']),
1010 dbesc($contact['notify']),
1011 dbesc($contact['poll']),
1012 dbesc($contact['confirm']),
1013 dbesc($contact['poco']),
1014 intval($contact['id'])
1022 * xml2array() will convert the given XML text to an array in the XML structure.
1023 * Link: http://www.bin-co.com/php/scripts/xml2array/
1024 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
1025 * Arguments : $contents - The XML text
1026 * $namespaces - true or false include namespace information in the returned array as array elements.
1027 * $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.
1028 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
1029 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
1030 * Examples: $array = xml2array(file_get_contents('feed.xml'));
1031 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
1034 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
1035 if(!$contents) return array();
1037 if(!function_exists('xml_parser_create')) {
1038 logger('xml2array: parser function missing');
1043 libxml_use_internal_errors(true);
1044 libxml_clear_errors();
1047 $parser = @xml_parser_create_ns("UTF-8",':');
1049 $parser = @xml_parser_create();
1052 logger('xml2array: xml_parser_create: no resource');
1056 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
1057 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
1058 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1059 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
1060 @xml_parse_into_struct($parser, trim($contents), $xml_values);
1061 @xml_parser_free($parser);
1064 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
1065 foreach(libxml_get_errors() as $err)
1066 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
1067 libxml_clear_errors();
1072 $xml_array = array();
1074 $opened_tags = array();
1077 $current = &$xml_array; // Reference
1079 // Go through the tags.
1080 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
1081 foreach($xml_values as $data) {
1082 unset($attributes,$value); // Remove existing values, or there will be trouble
1084 // This command will extract these variables into the foreach scope
1085 // tag(string), type(string), level(int), attributes(array).
1086 extract($data); // We could use the array by itself, but this cooler.
1089 $attributes_data = array();
1092 if($priority == 'tag') $result = $value;
1093 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1096 //Set the attributes too.
1097 if(isset($attributes) and $get_attributes) {
1098 foreach($attributes as $attr => $val) {
1099 if($priority == 'tag') $attributes_data[$attr] = $val;
1100 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1104 // See tag status and do the needed.
1105 if($namespaces && strpos($tag,':')) {
1106 $namespc = substr($tag,0,strrpos($tag,':'));
1107 $tag = strtolower(substr($tag,strlen($namespc)+1));
1108 $result['@namespace'] = $namespc;
1110 $tag = strtolower($tag);
1112 if($type == "open") { // The starting of the tag '<tag>'
1113 $parent[$level-1] = &$current;
1114 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1115 $current[$tag] = $result;
1116 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1117 $repeated_tag_index[$tag.'_'.$level] = 1;
1119 $current = &$current[$tag];
1121 } else { // There was another element with the same tag name
1123 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1124 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1125 $repeated_tag_index[$tag.'_'.$level]++;
1126 } else { // This section will make the value an array if multiple tags with the same name appear together
1127 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1128 $repeated_tag_index[$tag.'_'.$level] = 2;
1130 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1131 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1132 unset($current[$tag.'_attr']);
1136 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1137 $current = &$current[$tag][$last_item_index];
1140 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1141 //See if the key is already taken.
1142 if(!isset($current[$tag])) { //New Key
1143 $current[$tag] = $result;
1144 $repeated_tag_index[$tag.'_'.$level] = 1;
1145 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1147 } else { // If taken, put all things inside a list(array)
1148 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1150 // ...push the new element into that array.
1151 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1153 if($priority == 'tag' and $get_attributes and $attributes_data) {
1154 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1156 $repeated_tag_index[$tag.'_'.$level]++;
1158 } else { // If it is not an array...
1159 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1160 $repeated_tag_index[$tag.'_'.$level] = 1;
1161 if($priority == 'tag' and $get_attributes) {
1162 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1164 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1165 unset($current[$tag.'_attr']);
1168 if($attributes_data) {
1169 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1172 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1176 } elseif($type == 'close') { // End of tag '</tag>'
1177 $current = &$parent[$level-1];
1184 function original_url($url, $depth=1, $fetchbody = false) {
1188 // Remove Analytics Data from Google and other tracking platforms
1189 $urldata = parse_url($url);
1190 if (is_string($urldata["query"])) {
1191 $query = $urldata["query"];
1192 parse_str($query, $querydata);
1194 if (is_array($querydata))
1195 foreach ($querydata AS $param=>$value)
1196 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
1197 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
1198 "fb_action_ids", "fb_action_types", "fb_ref",
1200 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
1202 $pair = $param."=".urlencode($value);
1203 $url = str_replace($pair, "", $url);
1205 // Second try: if the url isn't encoded completely
1206 $pair = $param."=".str_replace(" ", "+", $value);
1207 $url = str_replace($pair, "", $url);
1209 // Third try: Maybey the url isn't encoded at all
1210 $pair = $param."=".$value;
1211 $url = str_replace($pair, "", $url);
1213 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
1216 if (substr($url, -1, 1) == "?")
1217 $url = substr($url, 0, -1);
1223 $url = trim($url, "'");
1225 $stamp1 = microtime(true);
1227 $siteinfo = array();
1229 curl_setopt($ch, CURLOPT_URL, $url);
1230 curl_setopt($ch, CURLOPT_HEADER, 1);
1231 curl_setopt($ch, CURLOPT_NOBODY, 1);
1232 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1233 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1234 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1236 $header = curl_exec($ch);
1237 $curl_info = @curl_getinfo($ch);
1238 $http_code = $curl_info['http_code'];
1241 $a->save_timestamp($stamp1, "network");
1243 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
1244 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
1245 if ($curl_info['redirect_url'] != "")
1246 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
1248 return(original_url($curl_info['location'], ++$depth, $fetchbody));
1251 // Check for redirects in the meta elements of the body if there are no redirects in the header.
1253 return(original_url($url, ++$depth, true));
1255 // if the file is too large then exit
1256 if ($curl_info["download_content_length"] > 1000000)
1259 // if it isn't a HTML file then exit
1260 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
1263 $stamp1 = microtime(true);
1266 curl_setopt($ch, CURLOPT_URL, $url);
1267 curl_setopt($ch, CURLOPT_HEADER, 0);
1268 curl_setopt($ch, CURLOPT_NOBODY, 0);
1269 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1270 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1271 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1273 $body = curl_exec($ch);
1276 $a->save_timestamp($stamp1, "network");
1278 if (trim($body) == "")
1281 // Check for redirect in meta elements
1282 $doc = new DOMDocument();
1283 @$doc->loadHTML($body);
1285 $xpath = new DomXPath($doc);
1287 $list = $xpath->query("//meta[@content]");
1288 foreach ($list as $node) {
1290 if ($node->attributes->length)
1291 foreach ($node->attributes as $attribute)
1292 $attr[$attribute->name] = $attribute->value;
1294 if (@$attr["http-equiv"] == 'refresh') {
1295 $path = $attr["content"];
1296 $pathinfo = explode(";", $path);
1298 foreach ($pathinfo AS $value)
1299 if (substr(strtolower($value), 0, 4) == "url=")
1300 return(original_url(substr($value, 4), ++$depth));
1307 if (!function_exists('short_link')) {
1308 function short_link($url) {
1309 require_once('library/slinky.php');
1310 $slinky = new Slinky($url);
1311 $yourls_url = get_config('yourls','url1');
1313 $yourls_username = get_config('yourls','username1');
1314 $yourls_password = get_config('yourls', 'password1');
1315 $yourls_ssl = get_config('yourls', 'ssl1');
1316 $yourls = new Slinky_YourLS();
1317 $yourls->set('username', $yourls_username);
1318 $yourls->set('password', $yourls_password);
1319 $yourls->set('ssl', $yourls_ssl);
1320 $yourls->set('yourls-url', $yourls_url);
1321 $slinky->set_cascade( array($yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1323 // setup a cascade of shortening services
1324 // try to get a short link from these services
1325 // in the order ur1.ca, trim, id.gd, tinyurl
1326 $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1328 return $slinky->short();