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 @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
19 @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
21 if (!is_null($accept_content)){
22 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
23 "Accept: " . $accept_content
27 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
28 //@curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
29 @curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Friendica)");
32 if(intval($timeout)) {
33 @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
36 $curl_time = intval(get_config('system','curl_timeout'));
37 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
39 // by default we will allow self-signed certs
40 // but you can override this
42 $check_cert = get_config('system','verifyssl');
43 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
45 $prx = get_config('system','proxy');
47 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
48 @curl_setopt($ch, CURLOPT_PROXY, $prx);
49 $prxusr = @get_config('system','proxyuser');
51 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
54 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
58 // don't let curl abort the entire application
59 // if it throws any errors.
64 $curl_info = @curl_getinfo($ch);
65 $http_code = $curl_info['http_code'];
66 // logger('fetch_url:' . $http_code . ' data: ' . $s);
69 // Pull out multiple headers, e.g. proxy and continuation headers
70 // allow for HTTP/2.x without fixing code
72 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
73 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
75 $base = substr($base,strlen($chunk));
78 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
79 $new_location_info = @parse_url($curl_info["redirect_url"]);
80 $old_location_info = @parse_url($curl_info["url"]);
82 $newurl = $curl_info["redirect_url"];
84 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
85 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
88 //preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
89 //$newurl = trim(array_pop($matches));
90 if(strpos($newurl,'/') === 0)
91 $newurl = $url . $newurl;
92 $url_parsed = @parse_url($newurl);
93 if (isset($url_parsed)) {
95 return fetch_url($newurl,$binary,$redirects,$timeout);
99 $a->set_curl_code($http_code);
101 $body = substr($s,strlen($header));
102 $a->set_curl_headers($header);
107 // post request to $url. $params is an array of post variables.
109 if(! function_exists('post_url')) {
110 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
112 $ch = curl_init($url);
113 if(($redirects > 8) || (! $ch))
116 curl_setopt($ch, CURLOPT_HEADER, true);
117 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
118 curl_setopt($ch, CURLOPT_POST,1);
119 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
120 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
122 if(intval($timeout)) {
123 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
126 $curl_time = intval(get_config('system','curl_timeout'));
127 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
130 if(defined('LIGHTTPD')) {
131 if(!is_array($headers)) {
132 $headers = array('Expect:');
134 if(!in_array('Expect:', $headers)) {
135 array_push($headers, 'Expect:');
140 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
142 $check_cert = get_config('system','verifyssl');
143 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
144 $prx = get_config('system','proxy');
146 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
147 curl_setopt($ch, CURLOPT_PROXY, $prx);
148 $prxusr = get_config('system','proxyuser');
150 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
153 $a->set_curl_code(0);
155 // don't let curl abort the entire application
156 // if it throws any errors.
158 $s = @curl_exec($ch);
161 $curl_info = curl_getinfo($ch);
162 $http_code = $curl_info['http_code'];
166 // Pull out multiple headers, e.g. proxy and continuation headers
167 // allow for HTTP/2.x without fixing code
169 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
170 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
172 $base = substr($base,strlen($chunk));
175 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
177 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
178 $newurl = trim(array_pop($matches));
179 if(strpos($newurl,'/') === 0)
180 $newurl = $url . $newurl;
181 $url_parsed = @parse_url($newurl);
182 if (isset($url_parsed)) {
184 return fetch_url($newurl,false,$redirects,$timeout);
187 $a->set_curl_code($http_code);
188 $body = substr($s,strlen($header));
190 $a->set_curl_headers($header);
196 // Generic XML return
197 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
198 // of $st and an optional text <message> of $message and terminates the current process.
200 if(! function_exists('xml_status')) {
201 function xml_status($st, $message = '') {
203 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
206 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
208 header( "Content-type: text/xml" );
209 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
210 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
215 if(! function_exists('http_status_exit')) {
216 function http_status_exit($val) {
221 if($val >= 200 && $val < 300)
224 logger('http_status_exit ' . $val);
225 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
231 // convert an XML document to a normalised, case-corrected array
234 if(! function_exists('convert_xml_element_to_array')) {
235 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
237 // If we're getting too deep, bail out
238 if ($recursion_depth > 512) {
242 if (!is_string($xml_element) &&
243 !is_array($xml_element) &&
244 (get_class($xml_element) == 'SimpleXMLElement')) {
245 $xml_element_copy = $xml_element;
246 $xml_element = get_object_vars($xml_element);
249 if (is_array($xml_element)) {
250 $result_array = array();
251 if (count($xml_element) <= 0) {
252 return (trim(strval($xml_element_copy)));
255 foreach($xml_element as $key=>$value) {
258 $result_array[strtolower($key)] =
259 convert_xml_element_to_array($value, $recursion_depth);
262 if ($recursion_depth == 0) {
263 $temp_array = $result_array;
264 $result_array = array(
265 strtolower($xml_element_copy->getName()) => $temp_array,
269 return ($result_array);
272 return (trim(strval($xml_element)));
276 // Given an email style address, perform webfinger lookup and
277 // return the resulting DFRN profile URL, or if no DFRN profile URL
278 // is located, returns an OStatus subscription template (prefixed
279 // with the string 'stat:' to identify it as on OStatus template).
280 // If this isn't an email style address just return $s.
281 // Return an empty string if email-style addresses but webfinger fails,
282 // or if the resultant personal XRD doesn't contain a supported
283 // subscription/friend-request attribute.
285 // amended 7/9/2011 to return an hcard which could save potentially loading
286 // a lengthy content page to scrape dfrn attributes
288 if(! function_exists('webfinger_dfrn')) {
289 function webfinger_dfrn($s,&$hcard) {
290 if(! strstr($s,'@')) {
295 $links = webfinger($s);
296 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
298 foreach($links as $link) {
299 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
300 $profile_link = $link['@attributes']['href'];
301 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
302 $profile_link = 'stat:' . $link['@attributes']['template'];
303 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
304 $hcard = $link['@attributes']['href'];
307 return $profile_link;
310 // Given an email style address, perform webfinger lookup and
311 // return the array of link attributes from the personal XRD file.
312 // On error/failure return an empty array.
315 if(! function_exists('webfinger')) {
316 function webfinger($s, $debug = false) {
319 $host = substr($s,strpos($s,'@') + 1);
322 $tpl = fetch_lrdd_template($host);
323 logger('webfinger: lrdd template: ' . $tpl);
325 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
326 logger('webfinger: pxrd: ' . $pxrd);
327 $links = fetch_xrd_links($pxrd);
328 if(! count($links)) {
329 // try with double slashes
330 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
331 logger('webfinger: pxrd: ' . $pxrd);
332 $links = fetch_xrd_links($pxrd);
340 if(! function_exists('lrdd')) {
341 function lrdd($uri, $debug = false) {
345 // default priority is host priority, host-meta first
349 // All we have is an email address. Resource-priority is irrelevant
350 // because our URI isn't directly resolvable.
352 if(strstr($uri,'@')) {
353 return(webfinger($uri));
356 // get the host meta file
358 $host = @parse_url($uri);
361 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
362 $url .= $host['host'] . '/.well-known/host-meta' ;
367 logger('lrdd: constructed url: ' . $url);
369 $xml = fetch_url($url);
370 $headers = $a->get_curl_headers();
375 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
377 if(! stristr($xml,'<xrd'))
380 $h = parse_xml_string($xml);
384 $arr = convert_xml_element_to_array($h);
386 if(isset($arr['xrd']['property'])) {
387 $property = $arr['crd']['property'];
388 if(! isset($property[0]))
389 $properties = array($property);
391 $properties = $property;
392 foreach($properties as $prop)
393 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
394 $priority = 'resource';
397 // save the links in case we need them
401 if(isset($arr['xrd']['link'])) {
402 $link = $arr['xrd']['link'];
403 if(! isset($link[0]))
404 $links = array($link);
409 // do we have a template or href?
412 foreach($links as $link) {
413 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
414 if(x($link['@attributes'],'template'))
415 $tpl = $link['@attributes']['template'];
416 elseif(x($link['@attributes'],'href'))
417 $href = $link['@attributes']['href'];
422 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
425 if($priority === 'host') {
427 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
431 logger('lrdd: (host priority) pxrd: ' . $pxrd);
432 $links = fetch_xrd_links($pxrd);
436 $lines = explode("\n",$headers);
438 foreach($lines as $line) {
439 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
440 return(fetch_xrd_links($matches[1]));
448 // priority 'resource'
451 $html = fetch_url($uri);
452 $headers = $a->get_curl_headers();
453 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
455 // don't try and parse raw xml as html
456 if(! strstr($html,'<?xml')) {
457 require_once('library/HTML5/Parser.php');
460 $dom = HTML5_Parser::parse($html);
461 } catch (DOMException $e) {
462 logger('lrdd: parse error: ' . $e);
465 if(isset($dom) && $dom) {
466 $items = $dom->getElementsByTagName('link');
467 foreach($items as $item) {
468 $x = $item->getAttribute('rel');
470 $pagelink = $item->getAttribute('href');
478 return(fetch_xrd_links($pagelink));
480 // next look in HTTP headers
482 $lines = explode("\n",$headers);
484 foreach($lines as $line) {
485 // TODO alter the following regex to support multiple relations (space separated)
486 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
487 $pagelink = $matches[1];
490 // don't try and run feeds through the html5 parser
491 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
493 if(stristr($html,'<rss') || stristr($html,'<feed'))
499 return(fetch_xrd_links($pagelink));
501 // If we haven't found any links, return the host xrd links (which we have already fetched)
512 // Given a host name, locate the LRDD template from that
513 // host. Returns the LRDD template or an empty string on
516 if(! function_exists('fetch_lrdd_template')) {
517 function fetch_lrdd_template($host) {
520 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
521 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
522 $links = fetch_xrd_links($url1);
523 logger('fetch_lrdd_template from: ' . $url1);
524 logger('template (https): ' . print_r($links,true));
525 if(! count($links)) {
526 logger('fetch_lrdd_template from: ' . $url2);
527 $links = fetch_xrd_links($url2);
528 logger('template (http): ' . print_r($links,true));
531 foreach($links as $link)
532 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
533 $tpl = $link['@attributes']['template'];
535 if(! strpos($tpl,'{uri}'))
540 // Given a URL, retrieve the page as an XRD document.
541 // Return an array of links.
542 // on error/failure return empty array.
544 if(! function_exists('fetch_xrd_links')) {
545 function fetch_xrd_links($url) {
547 $xrd_timeout = intval(get_config('system','xrd_timeout'));
549 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
551 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
553 if ((! $xml) || (! stristr($xml,'<xrd')))
556 // fix diaspora's bad xml
557 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
559 $h = parse_xml_string($xml);
563 $arr = convert_xml_element_to_array($h);
567 if(isset($arr['xrd']['link'])) {
568 $link = $arr['xrd']['link'];
569 if(! isset($link[0]))
570 $links = array($link);
574 if(isset($arr['xrd']['alias'])) {
575 $alias = $arr['xrd']['alias'];
576 if(! isset($alias[0]))
577 $aliases = array($alias);
580 if(is_array($aliases) && count($aliases)) {
581 foreach($aliases as $alias) {
582 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
587 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
594 // Take a URL from the wild, prepend http:// if necessary
595 // and check DNS to see if it's real (or check if is a valid IP address)
596 // return true if it's OK, false if something is wrong with it
598 if(! function_exists('validate_url')) {
599 function validate_url(&$url) {
601 // no naked subdomains (allow localhost for tests)
602 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
604 if(substr($url,0,4) != 'http')
605 $url = 'http://' . $url;
606 $h = @parse_url($url);
608 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
614 // checks that email is an actual resolvable internet address
616 if(! function_exists('validate_email')) {
617 function validate_email($addr) {
619 if(get_config('system','disable_email_validation'))
622 if(! strpos($addr,'@'))
624 $h = substr($addr,strpos($addr,'@') + 1);
626 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
632 // Check $url against our list of allowed sites,
633 // wildcards allowed. If allowed_sites is unset return true;
634 // If url is allowed, return true.
635 // otherwise, return false
637 if(! function_exists('allowed_url')) {
638 function allowed_url($url) {
640 $h = @parse_url($url);
646 $str_allowed = get_config('system','allowed_sites');
652 $host = strtolower($h['host']);
654 // always allow our own site
656 if($host == strtolower($_SERVER['SERVER_NAME']))
659 $fnmatch = function_exists('fnmatch');
660 $allowed = explode(',',$str_allowed);
662 if(count($allowed)) {
663 foreach($allowed as $a) {
664 $pat = strtolower(trim($a));
665 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
674 // check if email address is allowed to register here.
675 // Compare against our list (wildcards allowed).
676 // Returns false if not allowed, true if allowed or if
677 // allowed list is not configured.
679 if(! function_exists('allowed_email')) {
680 function allowed_email($email) {
683 $domain = strtolower(substr($email,strpos($email,'@') + 1));
687 $str_allowed = get_config('system','allowed_email');
693 $fnmatch = function_exists('fnmatch');
694 $allowed = explode(',',$str_allowed);
696 if(count($allowed)) {
697 foreach($allowed as $a) {
698 $pat = strtolower(trim($a));
699 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
709 if(! function_exists('avatar_img')) {
710 function avatar_img($email) {
714 $avatar['size'] = 175;
715 $avatar['email'] = $email;
717 $avatar['success'] = false;
719 call_hooks('avatar_lookup', $avatar);
721 if(! $avatar['success'])
722 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
724 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
725 return $avatar['url'];
729 if(! function_exists('parse_xml_string')) {
730 function parse_xml_string($s,$strict = true) {
732 if(! strstr($s,'<?xml'))
734 $s2 = substr($s,strpos($s,'<?xml'));
738 libxml_use_internal_errors(true);
740 $x = @simplexml_load_string($s2);
742 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
743 foreach(libxml_get_errors() as $err)
744 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
745 libxml_clear_errors();
750 function add_fcontact($arr,$update = false) {
753 $r = q("UPDATE `fcontact` SET
766 WHERE `url` = '%s' AND `network` = '%s' LIMIT 1",
768 dbesc($arr['photo']),
769 dbesc($arr['request']),
772 dbesc($arr['batch']),
773 dbesc($arr['notify']),
775 dbesc($arr['confirm']),
776 dbesc($arr['alias']),
777 dbesc($arr['pubkey']),
778 dbesc(datetime_convert()),
780 dbesc($arr['network'])
784 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
785 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
786 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
789 dbesc($arr['photo']),
790 dbesc($arr['request']),
793 dbesc($arr['batch']),
794 dbesc($arr['notify']),
796 dbesc($arr['confirm']),
797 dbesc($arr['network']),
798 dbesc($arr['alias']),
799 dbesc($arr['pubkey']),
800 dbesc(datetime_convert())
808 function scale_external_images($s, $include_link = true, $scale_replace = false) {
812 // Picture addresses can contain special characters
813 $s = htmlspecialchars_decode($s);
816 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
818 require_once('include/Photo.php');
819 foreach($matches as $mtch) {
820 logger('scale_external_image: ' . $mtch[1]);
822 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
823 if(stristr($mtch[1],$hostname))
826 // $scale_replace, if passed, is an array of two elements. The
827 // first is the name of the full-size image. The second is the
828 // name of a remote, scaled-down version of the full size image.
829 // This allows Friendica to display the smaller remote image if
830 // one exists, while still linking to the full-size image
832 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
835 $i = fetch_url($scaled);
837 $cachefile = get_cachefile(hash("md5", $scaled));
838 if ($cachefile != '')
839 file_put_contents($cachefile, $i);
841 // guess mimetype from headers or filename
842 $type = guess_image_type($mtch[1],true);
845 $ph = new Photo($i, $type);
846 if($ph->is_valid()) {
847 $orig_width = $ph->getWidth();
848 $orig_height = $ph->getHeight();
850 if($orig_width > 640 || $orig_height > 640) {
852 $ph->scaleImage(640);
853 $new_width = $ph->getWidth();
854 $new_height = $ph->getHeight();
855 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
856 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
857 . "\n" . (($include_link)
858 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
860 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
867 // replace the special char encoding
868 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
873 function fix_contact_ssl_policy(&$contact,$new_policy) {
875 $ssl_changed = false;
876 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
878 $contact['url'] = str_replace('https:','http:',$contact['url']);
879 $contact['request'] = str_replace('https:','http:',$contact['request']);
880 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
881 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
882 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
883 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
886 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
888 $contact['url'] = str_replace('http:','https:',$contact['url']);
889 $contact['request'] = str_replace('http:','https:',$contact['request']);
890 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
891 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
892 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
893 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
897 q("update contact set
904 where id = %d limit 1",
905 dbesc($contact['url']),
906 dbesc($contact['request']),
907 dbesc($contact['notify']),
908 dbesc($contact['poll']),
909 dbesc($contact['confirm']),
910 dbesc($contact['poco']),
911 intval($contact['id'])
919 * xml2array() will convert the given XML text to an array in the XML structure.
920 * Link: http://www.bin-co.com/php/scripts/xml2array/
921 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
922 * Arguments : $contents - The XML text
923 * $namespaces - true or false include namespace information in the returned array as array elements.
924 * $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.
925 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
926 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
927 * Examples: $array = xml2array(file_get_contents('feed.xml'));
928 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
931 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
932 if(!$contents) return array();
934 if(!function_exists('xml_parser_create')) {
935 logger('xml2array: parser function missing');
940 libxml_use_internal_errors(true);
941 libxml_clear_errors();
944 $parser = @xml_parser_create_ns("UTF-8",':');
946 $parser = @xml_parser_create();
949 logger('xml2array: xml_parser_create: no resource');
953 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
954 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
955 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
956 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
957 @xml_parse_into_struct($parser, trim($contents), $xml_values);
958 @xml_parser_free($parser);
961 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
962 foreach(libxml_get_errors() as $err)
963 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
964 libxml_clear_errors();
969 $xml_array = array();
971 $opened_tags = array();
974 $current = &$xml_array; // Reference
976 // Go through the tags.
977 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
978 foreach($xml_values as $data) {
979 unset($attributes,$value); // Remove existing values, or there will be trouble
981 // This command will extract these variables into the foreach scope
982 // tag(string), type(string), level(int), attributes(array).
983 extract($data); // We could use the array by itself, but this cooler.
986 $attributes_data = array();
989 if($priority == 'tag') $result = $value;
990 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
993 //Set the attributes too.
994 if(isset($attributes) and $get_attributes) {
995 foreach($attributes as $attr => $val) {
996 if($priority == 'tag') $attributes_data[$attr] = $val;
997 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1001 // See tag status and do the needed.
1002 if($namespaces && strpos($tag,':')) {
1003 $namespc = substr($tag,0,strrpos($tag,':'));
1004 $tag = strtolower(substr($tag,strlen($namespc)+1));
1005 $result['@namespace'] = $namespc;
1007 $tag = strtolower($tag);
1009 if($type == "open") { // The starting of the tag '<tag>'
1010 $parent[$level-1] = &$current;
1011 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1012 $current[$tag] = $result;
1013 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1014 $repeated_tag_index[$tag.'_'.$level] = 1;
1016 $current = &$current[$tag];
1018 } else { // There was another element with the same tag name
1020 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1021 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1022 $repeated_tag_index[$tag.'_'.$level]++;
1023 } else { // This section will make the value an array if multiple tags with the same name appear together
1024 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1025 $repeated_tag_index[$tag.'_'.$level] = 2;
1027 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1028 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1029 unset($current[$tag.'_attr']);
1033 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1034 $current = &$current[$tag][$last_item_index];
1037 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1038 //See if the key is already taken.
1039 if(!isset($current[$tag])) { //New Key
1040 $current[$tag] = $result;
1041 $repeated_tag_index[$tag.'_'.$level] = 1;
1042 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1044 } else { // If taken, put all things inside a list(array)
1045 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1047 // ...push the new element into that array.
1048 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1050 if($priority == 'tag' and $get_attributes and $attributes_data) {
1051 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1053 $repeated_tag_index[$tag.'_'.$level]++;
1055 } else { // If it is not an array...
1056 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1057 $repeated_tag_index[$tag.'_'.$level] = 1;
1058 if($priority == 'tag' and $get_attributes) {
1059 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1061 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1062 unset($current[$tag.'_attr']);
1065 if($attributes_data) {
1066 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1069 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1073 } elseif($type == 'close') { // End of tag '</tag>'
1074 $current = &$parent[$level-1];