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) {
80 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
81 $newurl = trim(array_pop($matches));
82 if(strpos($newurl,'/') === 0)
83 $newurl = $url . $newurl;
84 $url_parsed = @parse_url($newurl);
85 if (isset($url_parsed)) {
87 return fetch_url($newurl,$binary,$redirects,$timeout);
91 $a->set_curl_code($http_code);
93 $body = substr($s,strlen($header));
94 $a->set_curl_headers($header);
99 // post request to $url. $params is an array of post variables.
101 if(! function_exists('post_url')) {
102 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
104 $ch = curl_init($url);
105 if(($redirects > 8) || (! $ch))
108 curl_setopt($ch, CURLOPT_HEADER, true);
109 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
110 curl_setopt($ch, CURLOPT_POST,1);
111 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
112 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
114 if(intval($timeout)) {
115 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
118 $curl_time = intval(get_config('system','curl_timeout'));
119 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
122 if(defined('LIGHTTPD')) {
123 if(!is_array($headers)) {
124 $headers = array('Expect:');
126 if(!in_array('Expect:', $headers)) {
127 array_push($headers, 'Expect:');
132 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
134 $check_cert = get_config('system','verifyssl');
135 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
136 $prx = get_config('system','proxy');
138 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
139 curl_setopt($ch, CURLOPT_PROXY, $prx);
140 $prxusr = get_config('system','proxyuser');
142 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
145 $a->set_curl_code(0);
147 // don't let curl abort the entire application
148 // if it throws any errors.
150 $s = @curl_exec($ch);
153 $curl_info = curl_getinfo($ch);
154 $http_code = $curl_info['http_code'];
158 // Pull out multiple headers, e.g. proxy and continuation headers
159 // allow for HTTP/2.x without fixing code
161 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
162 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
164 $base = substr($base,strlen($chunk));
167 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
169 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
170 $newurl = trim(array_pop($matches));
171 if(strpos($newurl,'/') === 0)
172 $newurl = $url . $newurl;
173 $url_parsed = @parse_url($newurl);
174 if (isset($url_parsed)) {
176 return fetch_url($newurl,false,$redirects,$timeout);
179 $a->set_curl_code($http_code);
180 $body = substr($s,strlen($header));
182 $a->set_curl_headers($header);
188 // Generic XML return
189 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
190 // of $st and an optional text <message> of $message and terminates the current process.
192 if(! function_exists('xml_status')) {
193 function xml_status($st, $message = '') {
195 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
198 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
200 header( "Content-type: text/xml" );
201 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
202 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
207 if(! function_exists('http_status_exit')) {
208 function http_status_exit($val) {
213 if($val >= 200 && $val < 300)
216 logger('http_status_exit ' . $val);
217 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
223 // convert an XML document to a normalised, case-corrected array
226 if(! function_exists('convert_xml_element_to_array')) {
227 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
229 // If we're getting too deep, bail out
230 if ($recursion_depth > 512) {
234 if (!is_string($xml_element) &&
235 !is_array($xml_element) &&
236 (get_class($xml_element) == 'SimpleXMLElement')) {
237 $xml_element_copy = $xml_element;
238 $xml_element = get_object_vars($xml_element);
241 if (is_array($xml_element)) {
242 $result_array = array();
243 if (count($xml_element) <= 0) {
244 return (trim(strval($xml_element_copy)));
247 foreach($xml_element as $key=>$value) {
250 $result_array[strtolower($key)] =
251 convert_xml_element_to_array($value, $recursion_depth);
254 if ($recursion_depth == 0) {
255 $temp_array = $result_array;
256 $result_array = array(
257 strtolower($xml_element_copy->getName()) => $temp_array,
261 return ($result_array);
264 return (trim(strval($xml_element)));
268 // Given an email style address, perform webfinger lookup and
269 // return the resulting DFRN profile URL, or if no DFRN profile URL
270 // is located, returns an OStatus subscription template (prefixed
271 // with the string 'stat:' to identify it as on OStatus template).
272 // If this isn't an email style address just return $s.
273 // Return an empty string if email-style addresses but webfinger fails,
274 // or if the resultant personal XRD doesn't contain a supported
275 // subscription/friend-request attribute.
277 // amended 7/9/2011 to return an hcard which could save potentially loading
278 // a lengthy content page to scrape dfrn attributes
280 if(! function_exists('webfinger_dfrn')) {
281 function webfinger_dfrn($s,&$hcard) {
282 if(! strstr($s,'@')) {
287 $links = webfinger($s);
288 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
290 foreach($links as $link) {
291 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
292 $profile_link = $link['@attributes']['href'];
293 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
294 $profile_link = 'stat:' . $link['@attributes']['template'];
295 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
296 $hcard = $link['@attributes']['href'];
299 return $profile_link;
302 // Given an email style address, perform webfinger lookup and
303 // return the array of link attributes from the personal XRD file.
304 // On error/failure return an empty array.
307 if(! function_exists('webfinger')) {
308 function webfinger($s, $debug = false) {
311 $host = substr($s,strpos($s,'@') + 1);
314 $tpl = fetch_lrdd_template($host);
315 logger('webfinger: lrdd template: ' . $tpl);
317 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
318 logger('webfinger: pxrd: ' . $pxrd);
319 $links = fetch_xrd_links($pxrd);
320 if(! count($links)) {
321 // try with double slashes
322 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
323 logger('webfinger: pxrd: ' . $pxrd);
324 $links = fetch_xrd_links($pxrd);
332 if(! function_exists('lrdd')) {
333 function lrdd($uri, $debug = false) {
337 // default priority is host priority, host-meta first
341 // All we have is an email address. Resource-priority is irrelevant
342 // because our URI isn't directly resolvable.
344 if(strstr($uri,'@')) {
345 return(webfinger($uri));
348 // get the host meta file
350 $host = @parse_url($uri);
353 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
354 $url .= $host['host'] . '/.well-known/host-meta' ;
359 logger('lrdd: constructed url: ' . $url);
361 $xml = fetch_url($url);
362 $headers = $a->get_curl_headers();
367 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
369 if(! stristr($xml,'<xrd'))
372 $h = parse_xml_string($xml);
376 $arr = convert_xml_element_to_array($h);
378 if(isset($arr['xrd']['property'])) {
379 $property = $arr['crd']['property'];
380 if(! isset($property[0]))
381 $properties = array($property);
383 $properties = $property;
384 foreach($properties as $prop)
385 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
386 $priority = 'resource';
389 // save the links in case we need them
393 if(isset($arr['xrd']['link'])) {
394 $link = $arr['xrd']['link'];
395 if(! isset($link[0]))
396 $links = array($link);
401 // do we have a template or href?
404 foreach($links as $link) {
405 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
406 if(x($link['@attributes'],'template'))
407 $tpl = $link['@attributes']['template'];
408 elseif(x($link['@attributes'],'href'))
409 $href = $link['@attributes']['href'];
414 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
417 if($priority === 'host') {
419 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
423 logger('lrdd: (host priority) pxrd: ' . $pxrd);
424 $links = fetch_xrd_links($pxrd);
428 $lines = explode("\n",$headers);
430 foreach($lines as $line) {
431 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
432 return(fetch_xrd_links($matches[1]));
440 // priority 'resource'
443 $html = fetch_url($uri);
444 $headers = $a->get_curl_headers();
445 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
447 // don't try and parse raw xml as html
448 if(! strstr($html,'<?xml')) {
449 require_once('library/HTML5/Parser.php');
452 $dom = HTML5_Parser::parse($html);
453 } catch (DOMException $e) {
454 logger('lrdd: parse error: ' . $e);
457 if(isset($dom) && $dom) {
458 $items = $dom->getElementsByTagName('link');
459 foreach($items as $item) {
460 $x = $item->getAttribute('rel');
462 $pagelink = $item->getAttribute('href');
470 return(fetch_xrd_links($pagelink));
472 // next look in HTTP headers
474 $lines = explode("\n",$headers);
476 foreach($lines as $line) {
477 // TODO alter the following regex to support multiple relations (space separated)
478 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
479 $pagelink = $matches[1];
482 // don't try and run feeds through the html5 parser
483 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
485 if(stristr($html,'<rss') || stristr($html,'<feed'))
491 return(fetch_xrd_links($pagelink));
493 // If we haven't found any links, return the host xrd links (which we have already fetched)
504 // Given a host name, locate the LRDD template from that
505 // host. Returns the LRDD template or an empty string on
508 if(! function_exists('fetch_lrdd_template')) {
509 function fetch_lrdd_template($host) {
512 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
513 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
514 $links = fetch_xrd_links($url1);
515 logger('fetch_lrdd_template from: ' . $url1);
516 logger('template (https): ' . print_r($links,true));
517 if(! count($links)) {
518 logger('fetch_lrdd_template from: ' . $url2);
519 $links = fetch_xrd_links($url2);
520 logger('template (http): ' . print_r($links,true));
523 foreach($links as $link)
524 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
525 $tpl = $link['@attributes']['template'];
527 if(! strpos($tpl,'{uri}'))
532 // Given a URL, retrieve the page as an XRD document.
533 // Return an array of links.
534 // on error/failure return empty array.
536 if(! function_exists('fetch_xrd_links')) {
537 function fetch_xrd_links($url) {
539 $xrd_timeout = intval(get_config('system','xrd_timeout'));
541 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
543 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
545 if ((! $xml) || (! stristr($xml,'<xrd')))
548 // fix diaspora's bad xml
549 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
551 $h = parse_xml_string($xml);
555 $arr = convert_xml_element_to_array($h);
559 if(isset($arr['xrd']['link'])) {
560 $link = $arr['xrd']['link'];
561 if(! isset($link[0]))
562 $links = array($link);
566 if(isset($arr['xrd']['alias'])) {
567 $alias = $arr['xrd']['alias'];
568 if(! isset($alias[0]))
569 $aliases = array($alias);
572 if(is_array($aliases) && count($aliases)) {
573 foreach($aliases as $alias) {
574 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
579 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
586 // Take a URL from the wild, prepend http:// if necessary
587 // and check DNS to see if it's real (or check if is a valid IP address)
588 // return true if it's OK, false if something is wrong with it
590 if(! function_exists('validate_url')) {
591 function validate_url(&$url) {
593 // no naked subdomains (allow localhost for tests)
594 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
596 if(substr($url,0,4) != 'http')
597 $url = 'http://' . $url;
598 $h = @parse_url($url);
600 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
606 // checks that email is an actual resolvable internet address
608 if(! function_exists('validate_email')) {
609 function validate_email($addr) {
611 if(get_config('system','disable_email_validation'))
614 if(! strpos($addr,'@'))
616 $h = substr($addr,strpos($addr,'@') + 1);
618 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
624 // Check $url against our list of allowed sites,
625 // wildcards allowed. If allowed_sites is unset return true;
626 // If url is allowed, return true.
627 // otherwise, return false
629 if(! function_exists('allowed_url')) {
630 function allowed_url($url) {
632 $h = @parse_url($url);
638 $str_allowed = get_config('system','allowed_sites');
644 $host = strtolower($h['host']);
646 // always allow our own site
648 if($host == strtolower($_SERVER['SERVER_NAME']))
651 $fnmatch = function_exists('fnmatch');
652 $allowed = explode(',',$str_allowed);
654 if(count($allowed)) {
655 foreach($allowed as $a) {
656 $pat = strtolower(trim($a));
657 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
666 // check if email address is allowed to register here.
667 // Compare against our list (wildcards allowed).
668 // Returns false if not allowed, true if allowed or if
669 // allowed list is not configured.
671 if(! function_exists('allowed_email')) {
672 function allowed_email($email) {
675 $domain = strtolower(substr($email,strpos($email,'@') + 1));
679 $str_allowed = get_config('system','allowed_email');
685 $fnmatch = function_exists('fnmatch');
686 $allowed = explode(',',$str_allowed);
688 if(count($allowed)) {
689 foreach($allowed as $a) {
690 $pat = strtolower(trim($a));
691 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
701 if(! function_exists('avatar_img')) {
702 function avatar_img($email) {
706 $avatar['size'] = 175;
707 $avatar['email'] = $email;
709 $avatar['success'] = false;
711 call_hooks('avatar_lookup', $avatar);
713 if(! $avatar['success'])
714 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
716 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
717 return $avatar['url'];
721 if(! function_exists('parse_xml_string')) {
722 function parse_xml_string($s,$strict = true) {
724 if(! strstr($s,'<?xml'))
726 $s2 = substr($s,strpos($s,'<?xml'));
730 libxml_use_internal_errors(true);
732 $x = @simplexml_load_string($s2);
734 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
735 foreach(libxml_get_errors() as $err)
736 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
737 libxml_clear_errors();
742 function add_fcontact($arr,$update = false) {
745 $r = q("UPDATE `fcontact` SET
758 WHERE `url` = '%s' AND `network` = '%s' LIMIT 1",
760 dbesc($arr['photo']),
761 dbesc($arr['request']),
764 dbesc($arr['batch']),
765 dbesc($arr['notify']),
767 dbesc($arr['confirm']),
768 dbesc($arr['alias']),
769 dbesc($arr['pubkey']),
770 dbesc(datetime_convert()),
772 dbesc($arr['network'])
776 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
777 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
778 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
781 dbesc($arr['photo']),
782 dbesc($arr['request']),
785 dbesc($arr['batch']),
786 dbesc($arr['notify']),
788 dbesc($arr['confirm']),
789 dbesc($arr['network']),
790 dbesc($arr['alias']),
791 dbesc($arr['pubkey']),
792 dbesc(datetime_convert())
800 function scale_external_images($s, $include_link = true, $scale_replace = false) {
804 // Picture addresses can contain special characters
805 $s = htmlspecialchars_decode($s);
808 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
810 require_once('include/Photo.php');
811 foreach($matches as $mtch) {
812 logger('scale_external_image: ' . $mtch[1]);
814 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
815 if(stristr($mtch[1],$hostname))
818 // $scale_replace, if passed, is an array of two elements. The
819 // first is the name of the full-size image. The second is the
820 // name of a remote, scaled-down version of the full size image.
821 // This allows Friendica to display the smaller remote image if
822 // one exists, while still linking to the full-size image
824 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
827 $i = fetch_url($scaled);
829 $cachefile = get_cachefile(hash("md5", $scaled));
830 if ($cachefile != '')
831 file_put_contents($cachefile, $i);
833 // guess mimetype from headers or filename
834 $type = guess_image_type($mtch[1],true);
837 $ph = new Photo($i, $type);
838 if($ph->is_valid()) {
839 $orig_width = $ph->getWidth();
840 $orig_height = $ph->getHeight();
842 if($orig_width > 640 || $orig_height > 640) {
844 $ph->scaleImage(640);
845 $new_width = $ph->getWidth();
846 $new_height = $ph->getHeight();
847 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
848 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
849 . "\n" . (($include_link)
850 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
852 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
859 // replace the special char encoding
860 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
865 function fix_contact_ssl_policy(&$contact,$new_policy) {
867 $ssl_changed = false;
868 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
870 $contact['url'] = str_replace('https:','http:',$contact['url']);
871 $contact['request'] = str_replace('https:','http:',$contact['request']);
872 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
873 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
874 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
875 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
878 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
880 $contact['url'] = str_replace('http:','https:',$contact['url']);
881 $contact['request'] = str_replace('http:','https:',$contact['request']);
882 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
883 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
884 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
885 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
889 q("update contact set
896 where id = %d limit 1",
897 dbesc($contact['url']),
898 dbesc($contact['request']),
899 dbesc($contact['notify']),
900 dbesc($contact['poll']),
901 dbesc($contact['confirm']),
902 dbesc($contact['poco']),
903 intval($contact['id'])
911 * xml2array() will convert the given XML text to an array in the XML structure.
912 * Link: http://www.bin-co.com/php/scripts/xml2array/
913 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
914 * Arguments : $contents - The XML text
915 * $namespaces - true or false include namespace information in the returned array as array elements.
916 * $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.
917 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
918 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
919 * Examples: $array = xml2array(file_get_contents('feed.xml'));
920 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
923 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
924 if(!$contents) return array();
926 if(!function_exists('xml_parser_create')) {
927 logger('xml2array: parser function missing');
932 libxml_use_internal_errors(true);
933 libxml_clear_errors();
936 $parser = @xml_parser_create_ns("UTF-8",':');
938 $parser = @xml_parser_create();
941 logger('xml2array: xml_parser_create: no resource');
945 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
946 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
947 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
948 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
949 @xml_parse_into_struct($parser, trim($contents), $xml_values);
950 @xml_parser_free($parser);
953 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
954 foreach(libxml_get_errors() as $err)
955 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
956 libxml_clear_errors();
961 $xml_array = array();
963 $opened_tags = array();
966 $current = &$xml_array; // Reference
968 // Go through the tags.
969 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
970 foreach($xml_values as $data) {
971 unset($attributes,$value); // Remove existing values, or there will be trouble
973 // This command will extract these variables into the foreach scope
974 // tag(string), type(string), level(int), attributes(array).
975 extract($data); // We could use the array by itself, but this cooler.
978 $attributes_data = array();
981 if($priority == 'tag') $result = $value;
982 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
985 //Set the attributes too.
986 if(isset($attributes) and $get_attributes) {
987 foreach($attributes as $attr => $val) {
988 if($priority == 'tag') $attributes_data[$attr] = $val;
989 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
993 // See tag status and do the needed.
994 if($namespaces && strpos($tag,':')) {
995 $namespc = substr($tag,0,strrpos($tag,':'));
996 $tag = strtolower(substr($tag,strlen($namespc)+1));
997 $result['@namespace'] = $namespc;
999 $tag = strtolower($tag);
1001 if($type == "open") { // The starting of the tag '<tag>'
1002 $parent[$level-1] = &$current;
1003 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1004 $current[$tag] = $result;
1005 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1006 $repeated_tag_index[$tag.'_'.$level] = 1;
1008 $current = &$current[$tag];
1010 } else { // There was another element with the same tag name
1012 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1013 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1014 $repeated_tag_index[$tag.'_'.$level]++;
1015 } else { // This section will make the value an array if multiple tags with the same name appear together
1016 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1017 $repeated_tag_index[$tag.'_'.$level] = 2;
1019 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1020 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1021 unset($current[$tag.'_attr']);
1025 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1026 $current = &$current[$tag][$last_item_index];
1029 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1030 //See if the key is already taken.
1031 if(!isset($current[$tag])) { //New Key
1032 $current[$tag] = $result;
1033 $repeated_tag_index[$tag.'_'.$level] = 1;
1034 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1036 } else { // If taken, put all things inside a list(array)
1037 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1039 // ...push the new element into that array.
1040 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1042 if($priority == 'tag' and $get_attributes and $attributes_data) {
1043 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1045 $repeated_tag_index[$tag.'_'.$level]++;
1047 } else { // If it is not an array...
1048 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1049 $repeated_tag_index[$tag.'_'.$level] = 1;
1050 if($priority == 'tag' and $get_attributes) {
1051 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1053 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1054 unset($current[$tag.'_attr']);
1057 if($attributes_data) {
1058 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1061 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1065 } elseif($type == 'close') { // End of tag '</tag>'
1066 $current = &$parent[$level-1];