4 // curl wrapper. If binary flag is true, return binary
7 if(! function_exists('fetch_url')) {
8 function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null) {
12 $ch = @curl_init($url);
13 if(($redirects > 8) || (! $ch))
16 @curl_setopt($ch, CURLOPT_HEADER, true);
18 if (!is_null($accept_content)){
19 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
20 "Accept: " . $accept_content
24 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
25 @curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
28 if(intval($timeout)) {
29 @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
32 $curl_time = intval(get_config('system','curl_timeout'));
33 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
35 // by default we will allow self-signed certs
36 // but you can override this
38 $check_cert = get_config('system','verifyssl');
39 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
41 $prx = get_config('system','proxy');
43 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
44 @curl_setopt($ch, CURLOPT_PROXY, $prx);
45 $prxusr = @get_config('system','proxyuser');
47 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
50 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
54 // don't let curl abort the entire application
55 // if it throws any errors.
60 $curl_info = @curl_getinfo($ch);
61 $http_code = $curl_info['http_code'];
63 // logger('fetch_url:' . $http_code . ' data: ' . $s);
66 // Pull out multiple headers, e.g. proxy and continuation headers
67 // allow for HTTP/2.x without fixing code
69 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
70 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
72 $base = substr($base,strlen($chunk));
75 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
77 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
78 $newurl = trim(array_pop($matches));
79 if(strpos($newurl,'/') === 0)
80 $newurl = $url . $newurl;
81 $url_parsed = @parse_url($newurl);
82 if (isset($url_parsed)) {
84 return fetch_url($newurl,$binary,$redirects,$timeout);
88 $a->set_curl_code($http_code);
90 $body = substr($s,strlen($header));
92 $a->set_curl_headers($header);
98 // post request to $url. $params is an array of post variables.
100 if(! function_exists('post_url')) {
101 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
103 $ch = curl_init($url);
104 if(($redirects > 8) || (! $ch))
107 curl_setopt($ch, CURLOPT_HEADER, true);
108 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
109 curl_setopt($ch, CURLOPT_POST,1);
110 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
111 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
113 if(intval($timeout)) {
114 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
117 $curl_time = intval(get_config('system','curl_timeout'));
118 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
121 if(defined('LIGHTTPD')) {
122 if(!is_array($headers)) {
123 $headers = array('Expect:');
125 if(!in_array('Expect:', $headers)) {
126 array_push($headers, 'Expect:');
131 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
133 $check_cert = get_config('system','verifyssl');
134 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
135 $prx = get_config('system','proxy');
137 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
138 curl_setopt($ch, CURLOPT_PROXY, $prx);
139 $prxusr = get_config('system','proxyuser');
141 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
144 $a->set_curl_code(0);
146 // don't let curl abort the entire application
147 // if it throws any errors.
149 $s = @curl_exec($ch);
152 $curl_info = curl_getinfo($ch);
153 $http_code = $curl_info['http_code'];
157 // Pull out multiple headers, e.g. proxy and continuation headers
158 // allow for HTTP/2.x without fixing code
160 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
161 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
163 $base = substr($base,strlen($chunk));
166 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
168 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
169 $newurl = trim(array_pop($matches));
170 if(strpos($newurl,'/') === 0)
171 $newurl = $url . $newurl;
172 $url_parsed = @parse_url($newurl);
173 if (isset($url_parsed)) {
175 return fetch_url($newurl,false,$redirects,$timeout);
178 $a->set_curl_code($http_code);
179 $body = substr($s,strlen($header));
181 $a->set_curl_headers($header);
187 // Generic XML return
188 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
189 // of $st and an optional text <message> of $message and terminates the current process.
191 if(! function_exists('xml_status')) {
192 function xml_status($st, $message = '') {
194 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
197 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
199 header( "Content-type: text/xml" );
200 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
201 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
206 if(! function_exists('http_status_exit')) {
207 function http_status_exit($val) {
212 if($val >= 200 && $val < 300)
215 logger('http_status_exit ' . $val);
216 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
222 // convert an XML document to a normalised, case-corrected array
225 if(! function_exists('convert_xml_element_to_array')) {
226 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
228 // If we're getting too deep, bail out
229 if ($recursion_depth > 512) {
233 if (!is_string($xml_element) &&
234 !is_array($xml_element) &&
235 (get_class($xml_element) == 'SimpleXMLElement')) {
236 $xml_element_copy = $xml_element;
237 $xml_element = get_object_vars($xml_element);
240 if (is_array($xml_element)) {
241 $result_array = array();
242 if (count($xml_element) <= 0) {
243 return (trim(strval($xml_element_copy)));
246 foreach($xml_element as $key=>$value) {
249 $result_array[strtolower($key)] =
250 convert_xml_element_to_array($value, $recursion_depth);
253 if ($recursion_depth == 0) {
254 $temp_array = $result_array;
255 $result_array = array(
256 strtolower($xml_element_copy->getName()) => $temp_array,
260 return ($result_array);
263 return (trim(strval($xml_element)));
267 // Given an email style address, perform webfinger lookup and
268 // return the resulting DFRN profile URL, or if no DFRN profile URL
269 // is located, returns an OStatus subscription template (prefixed
270 // with the string 'stat:' to identify it as on OStatus template).
271 // If this isn't an email style address just return $s.
272 // Return an empty string if email-style addresses but webfinger fails,
273 // or if the resultant personal XRD doesn't contain a supported
274 // subscription/friend-request attribute.
276 // amended 7/9/2011 to return an hcard which could save potentially loading
277 // a lengthy content page to scrape dfrn attributes
279 if(! function_exists('webfinger_dfrn')) {
280 function webfinger_dfrn($s,&$hcard) {
281 if(! strstr($s,'@')) {
286 $links = webfinger($s);
287 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
289 foreach($links as $link) {
290 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
291 $profile_link = $link['@attributes']['href'];
292 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
293 $profile_link = 'stat:' . $link['@attributes']['template'];
294 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
295 $hcard = $link['@attributes']['href'];
298 return $profile_link;
301 // Given an email style address, perform webfinger lookup and
302 // return the array of link attributes from the personal XRD file.
303 // On error/failure return an empty array.
306 if(! function_exists('webfinger')) {
307 function webfinger($s, $debug = false) {
310 $host = substr($s,strpos($s,'@') + 1);
313 $tpl = fetch_lrdd_template($host);
314 logger('webfinger: lrdd template: ' . $tpl);
316 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
317 logger('webfinger: pxrd: ' . $pxrd);
318 $links = fetch_xrd_links($pxrd);
319 if(! count($links)) {
320 // try with double slashes
321 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
322 logger('webfinger: pxrd: ' . $pxrd);
323 $links = fetch_xrd_links($pxrd);
331 if(! function_exists('lrdd')) {
332 function lrdd($uri, $debug = false) {
336 // default priority is host priority, host-meta first
340 // All we have is an email address. Resource-priority is irrelevant
341 // because our URI isn't directly resolvable.
343 if(strstr($uri,'@')) {
344 return(webfinger($uri));
347 // get the host meta file
349 $host = @parse_url($uri);
352 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
353 $url .= $host['host'] . '/.well-known/host-meta' ;
358 logger('lrdd: constructed url: ' . $url);
360 $xml = fetch_url($url);
361 $headers = $a->get_curl_headers();
366 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
368 if(! stristr($xml,'<xrd'))
371 $h = parse_xml_string($xml);
375 $arr = convert_xml_element_to_array($h);
377 if(isset($arr['xrd']['property'])) {
378 $property = $arr['crd']['property'];
379 if(! isset($property[0]))
380 $properties = array($property);
382 $properties = $property;
383 foreach($properties as $prop)
384 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
385 $priority = 'resource';
388 // save the links in case we need them
392 if(isset($arr['xrd']['link'])) {
393 $link = $arr['xrd']['link'];
394 if(! isset($link[0]))
395 $links = array($link);
400 // do we have a template or href?
403 foreach($links as $link) {
404 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
405 if(x($link['@attributes'],'template'))
406 $tpl = $link['@attributes']['template'];
407 elseif(x($link['@attributes'],'href'))
408 $href = $link['@attributes']['href'];
413 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
416 if($priority === 'host') {
418 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
422 logger('lrdd: (host priority) pxrd: ' . $pxrd);
423 $links = fetch_xrd_links($pxrd);
427 $lines = explode("\n",$headers);
429 foreach($lines as $line) {
430 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
431 return(fetch_xrd_links($matches[1]));
439 // priority 'resource'
442 $html = fetch_url($uri);
443 $headers = $a->get_curl_headers();
444 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
446 // don't try and parse raw xml as html
447 if(! strstr($html,'<?xml')) {
448 require_once('library/HTML5/Parser.php');
451 $dom = HTML5_Parser::parse($html);
452 } catch (DOMException $e) {
453 logger('lrdd: parse error: ' . $e);
456 if(isset($dom) && $dom) {
457 $items = $dom->getElementsByTagName('link');
458 foreach($items as $item) {
459 $x = $item->getAttribute('rel');
461 $pagelink = $item->getAttribute('href');
469 return(fetch_xrd_links($pagelink));
471 // next look in HTTP headers
473 $lines = explode("\n",$headers);
475 foreach($lines as $line) {
476 // TODO alter the following regex to support multiple relations (space separated)
477 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
478 $pagelink = $matches[1];
481 // don't try and run feeds through the html5 parser
482 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
484 if(stristr($html,'<rss') || stristr($html,'<feed'))
490 return(fetch_xrd_links($pagelink));
492 // If we haven't found any links, return the host xrd links (which we have already fetched)
503 // Given a host name, locate the LRDD template from that
504 // host. Returns the LRDD template or an empty string on
507 if(! function_exists('fetch_lrdd_template')) {
508 function fetch_lrdd_template($host) {
511 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
512 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
513 $links = fetch_xrd_links($url1);
514 logger('fetch_lrdd_template from: ' . $url1);
515 logger('template (https): ' . print_r($links,true));
516 if(! count($links)) {
517 logger('fetch_lrdd_template from: ' . $url2);
518 $links = fetch_xrd_links($url2);
519 logger('template (http): ' . print_r($links,true));
522 foreach($links as $link)
523 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
524 $tpl = $link['@attributes']['template'];
526 if(! strpos($tpl,'{uri}'))
531 // Given a URL, retrieve the page as an XRD document.
532 // Return an array of links.
533 // on error/failure return empty array.
535 if(! function_exists('fetch_xrd_links')) {
536 function fetch_xrd_links($url) {
538 $xrd_timeout = intval(get_config('system','xrd_timeout'));
540 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
542 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
544 if ((! $xml) || (! stristr($xml,'<xrd')))
547 // fix diaspora's bad xml
548 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
550 $h = parse_xml_string($xml);
554 $arr = convert_xml_element_to_array($h);
558 if(isset($arr['xrd']['link'])) {
559 $link = $arr['xrd']['link'];
560 if(! isset($link[0]))
561 $links = array($link);
565 if(isset($arr['xrd']['alias'])) {
566 $alias = $arr['xrd']['alias'];
567 if(! isset($alias[0]))
568 $aliases = array($alias);
571 if(is_array($aliases) && count($aliases)) {
572 foreach($aliases as $alias) {
573 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
578 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
585 // Take a URL from the wild, prepend http:// if necessary
586 // and check DNS to see if it's real (or check if is a valid IP address)
587 // return true if it's OK, false if something is wrong with it
589 if(! function_exists('validate_url')) {
590 function validate_url(&$url) {
592 // no naked subdomains (allow localhost for tests)
593 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
595 if(substr($url,0,4) != 'http')
596 $url = 'http://' . $url;
597 $h = @parse_url($url);
599 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
605 // checks that email is an actual resolvable internet address
607 if(! function_exists('validate_email')) {
608 function validate_email($addr) {
610 if(! strpos($addr,'@'))
612 $h = substr($addr,strpos($addr,'@') + 1);
614 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
620 // Check $url against our list of allowed sites,
621 // wildcards allowed. If allowed_sites is unset return true;
622 // If url is allowed, return true.
623 // otherwise, return false
625 if(! function_exists('allowed_url')) {
626 function allowed_url($url) {
628 $h = @parse_url($url);
634 $str_allowed = get_config('system','allowed_sites');
640 $host = strtolower($h['host']);
642 // always allow our own site
644 if($host == strtolower($_SERVER['SERVER_NAME']))
647 $fnmatch = function_exists('fnmatch');
648 $allowed = explode(',',$str_allowed);
650 if(count($allowed)) {
651 foreach($allowed as $a) {
652 $pat = strtolower(trim($a));
653 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
662 // check if email address is allowed to register here.
663 // Compare against our list (wildcards allowed).
664 // Returns false if not allowed, true if allowed or if
665 // allowed list is not configured.
667 if(! function_exists('allowed_email')) {
668 function allowed_email($email) {
671 $domain = strtolower(substr($email,strpos($email,'@') + 1));
675 $str_allowed = get_config('system','allowed_email');
681 $fnmatch = function_exists('fnmatch');
682 $allowed = explode(',',$str_allowed);
684 if(count($allowed)) {
685 foreach($allowed as $a) {
686 $pat = strtolower(trim($a));
687 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
697 if(! function_exists('avatar_img')) {
698 function avatar_img($email) {
702 $avatar['size'] = 175;
703 $avatar['email'] = $email;
705 $avatar['success'] = false;
707 call_hooks('avatar_lookup', $avatar);
709 if(! $avatar['success'])
710 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
712 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
713 return $avatar['url'];
717 if(! function_exists('parse_xml_string')) {
718 function parse_xml_string($s,$strict = true) {
720 if(! strstr($s,'<?xml'))
722 $s2 = substr($s,strpos($s,'<?xml'));
726 libxml_use_internal_errors(true);
728 $x = @simplexml_load_string($s2);
730 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
731 foreach(libxml_get_errors() as $err)
732 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
733 libxml_clear_errors();
738 function add_fcontact($arr,$update = false) {
741 $r = q("UPDATE `fcontact` SET
754 WHERE `url` = '%s' AND `network` = '%s' LIMIT 1",
756 dbesc($arr['photo']),
757 dbesc($arr['request']),
760 dbesc($arr['batch']),
761 dbesc($arr['notify']),
763 dbesc($arr['confirm']),
764 dbesc($arr['alias']),
765 dbesc($arr['pubkey']),
766 dbesc(datetime_convert()),
768 dbesc($arr['network'])
772 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
773 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
774 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
777 dbesc($arr['photo']),
778 dbesc($arr['request']),
781 dbesc($arr['batch']),
782 dbesc($arr['notify']),
784 dbesc($arr['confirm']),
785 dbesc($arr['network']),
786 dbesc($arr['alias']),
787 dbesc($arr['pubkey']),
788 dbesc(datetime_convert())
796 function scale_external_images($s,$include_link = true) {
801 $c = preg_match_all('/\[img\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
803 require_once('include/Photo.php');
804 foreach($matches as $mtch) {
805 logger('scale_external_image: ' . $mtch[1]);
806 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
807 if(stristr($mtch[1],$hostname))
809 $i = fetch_url($mtch[1]);
810 // guess mimetype from headers or filename
811 $type = guess_image_type($mtch[1],true);
814 $ph = new Photo($i, $type);
815 if($ph->is_valid()) {
816 $orig_width = $ph->getWidth();
817 $orig_height = $ph->getHeight();
819 if($orig_width > 640 || $orig_height > 640) {
821 $ph->scaleImage(640);
822 $new_width = $ph->getWidth();
823 $new_height = $ph->getHeight();
824 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
825 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $mtch[1] . '[/img]'
826 . "\n" . (($include_link)
827 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
829 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
839 function fix_contact_ssl_policy(&$contact,$new_policy) {
841 $ssl_changed = false;
842 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
844 $contact['url'] = str_replace('https:','http:',$contact['url']);
845 $contact['request'] = str_replace('https:','http:',$contact['request']);
846 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
847 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
848 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
849 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
852 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
854 $contact['url'] = str_replace('http:','https:',$contact['url']);
855 $contact['request'] = str_replace('http:','https:',$contact['request']);
856 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
857 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
858 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
859 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
863 q("update contact set
870 where id = %d limit 1",
871 dbesc($contact['url']),
872 dbesc($contact['request']),
873 dbesc($contact['notify']),
874 dbesc($contact['poll']),
875 dbesc($contact['confirm']),
876 dbesc($contact['poco']),
877 intval($contact['id'])
885 * xml2array() will convert the given XML text to an array in the XML structure.
886 * Link: http://www.bin-co.com/php/scripts/xml2array/
887 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
888 * Arguments : $contents - The XML text
889 * $namespaces - true or false include namespace information in the returned array as array elements.
890 * $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.
891 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
892 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
893 * Examples: $array = xml2array(file_get_contents('feed.xml'));
894 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
897 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
898 if(!$contents) return array();
900 if(!function_exists('xml_parser_create')) {
901 logger('xml2array: parser function missing');
906 libxml_use_internal_errors(true);
907 libxml_clear_errors();
910 $parser = @xml_parser_create_ns("UTF-8",':');
912 $parser = @xml_parser_create();
915 logger('xml2array: xml_parser_create: no resource');
919 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
920 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
921 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
922 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
923 @xml_parse_into_struct($parser, trim($contents), $xml_values);
924 @xml_parser_free($parser);
927 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
928 foreach(libxml_get_errors() as $err)
929 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
930 libxml_clear_errors();
935 $xml_array = array();
937 $opened_tags = array();
940 $current = &$xml_array; // Reference
942 // Go through the tags.
943 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
944 foreach($xml_values as $data) {
945 unset($attributes,$value); // Remove existing values, or there will be trouble
947 // This command will extract these variables into the foreach scope
948 // tag(string), type(string), level(int), attributes(array).
949 extract($data); // We could use the array by itself, but this cooler.
952 $attributes_data = array();
955 if($priority == 'tag') $result = $value;
956 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
959 //Set the attributes too.
960 if(isset($attributes) and $get_attributes) {
961 foreach($attributes as $attr => $val) {
962 if($priority == 'tag') $attributes_data[$attr] = $val;
963 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
967 // See tag status and do the needed.
968 if($namespaces && strpos($tag,':')) {
969 $namespc = substr($tag,0,strrpos($tag,':'));
970 $tag = strtolower(substr($tag,strlen($namespc)+1));
971 $result['@namespace'] = $namespc;
973 $tag = strtolower($tag);
975 if($type == "open") { // The starting of the tag '<tag>'
976 $parent[$level-1] = &$current;
977 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
978 $current[$tag] = $result;
979 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
980 $repeated_tag_index[$tag.'_'.$level] = 1;
982 $current = &$current[$tag];
984 } else { // There was another element with the same tag name
986 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
987 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
988 $repeated_tag_index[$tag.'_'.$level]++;
989 } else { // This section will make the value an array if multiple tags with the same name appear together
990 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
991 $repeated_tag_index[$tag.'_'.$level] = 2;
993 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
994 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
995 unset($current[$tag.'_attr']);
999 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1000 $current = &$current[$tag][$last_item_index];
1003 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1004 //See if the key is already taken.
1005 if(!isset($current[$tag])) { //New Key
1006 $current[$tag] = $result;
1007 $repeated_tag_index[$tag.'_'.$level] = 1;
1008 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1010 } else { // If taken, put all things inside a list(array)
1011 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1013 // ...push the new element into that array.
1014 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1016 if($priority == 'tag' and $get_attributes and $attributes_data) {
1017 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1019 $repeated_tag_index[$tag.'_'.$level]++;
1021 } else { // If it is not an array...
1022 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1023 $repeated_tag_index[$tag.'_'.$level] = 1;
1024 if($priority == 'tag' and $get_attributes) {
1025 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1027 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1028 unset($current[$tag.'_attr']);
1031 if($attributes_data) {
1032 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1035 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1039 } elseif($type == 'close') { // End of tag '</tag>'
1040 $current = &$parent[$level-1];