]> git.mxchange.org Git - friendica.git/blob - include/xml.php
d2a0f7655bf2af66d7fc2e86297868e0df3aad8d
[friendica.git] / include / xml.php
1 <?php
2 /**
3  * @file include/xml.php
4  */
5
6
7 /**
8  * @brief This class contain functions to work with XML data
9  *
10  */
11 class xml {
12         /**
13          * @brief Creates an XML structure out of a given array
14          *
15          * @param array $array The array of the XML structure that will be generated
16          * @param object $xml The createdXML will be returned by reference
17          * @param bool $remove_header Should the XML header be removed or not?
18          * @param array $namespaces List of namespaces
19          * @param bool $root - interally used parameter. Mustn't be used from outside.
20          *
21          * @return string The created XML
22          */
23         public static function from_array($array, &$xml, $remove_header = false, $namespaces = array(), $root = true) {
24
25                 if ($root) {
26                         foreach($array as $key => $value) {
27                                 foreach ($namespaces AS $nskey => $nsvalue)
28                                         $key .= " xmlns".($nskey == "" ? "":":").$nskey.'="'.$nsvalue.'"';
29
30                                 if (is_array($value)) {
31                                         $root = new SimpleXMLElement("<".$key."/>");
32                                         self::from_array($value, $root, $remove_header, $namespaces, false);
33                                 } else
34                                         $root = new SimpleXMLElement("<".$key.">".xmlify($value)."</".$key.">");
35
36                                 $dom = dom_import_simplexml($root)->ownerDocument;
37                                 $dom->formatOutput = true;
38                                 $xml = $dom;
39
40                                 $xml_text = $dom->saveXML();
41
42                                 if ($remove_header)
43                                         $xml_text = trim(substr($xml_text, 21));
44
45                                 return $xml_text;
46                         }
47                 }
48
49                 foreach($array as $key => $value) {
50                         if (!isset($element) AND isset($xml))
51                                 $element = $xml;
52
53                         if (is_integer($key)) {
54                                 if (isset($element))
55                                         $element[0] = $value;
56                                 continue;
57                         }
58
59                         if (substr($key, 0, 11) == "@attributes") {
60                                 if (!isset($element) OR !is_array($value))
61                                         continue;
62
63                                 foreach ($value as $attr_key => $attr_value) {
64                                         $element_parts = explode(":", $attr_key);
65                                         if ((count($element_parts) > 1) AND isset($namespaces[$element_parts[0]]))
66                                                 $namespace = $namespaces[$element_parts[0]];
67                                         elseif (isset($namespaces[""]))
68                                                 $namespace = $namespaces[""];
69                                         else
70                                                 $namespace = NULL;
71
72                                         $element->addAttribute($attr_key, $attr_value, $namespace);
73                                 }
74
75                                 continue;
76                         }
77
78                         $element_parts = explode(":", $key);
79                         if ((count($element_parts) > 1) AND isset($namespaces[$element_parts[0]]))
80                                 $namespace = $namespaces[$element_parts[0]];
81                         elseif (isset($namespaces[""]))
82                                 $namespace = $namespaces[""];
83                         else
84                                 $namespace = NULL;
85
86                         if (!is_array($value))
87                                 $element = $xml->addChild($key, xmlify($value), $namespace);
88                         elseif (is_array($value)) {
89                                 $element = $xml->addChild($key, NULL, $namespace);
90                                 self::from_array($value, $element, $remove_header, $namespaces, false);
91                         }
92                 }
93         }
94
95         /**
96          * @brief Copies an XML object
97          *
98          * @param object $source The XML source
99          * @param object $target The XML target
100          * @param string $elementname Name of the XML element of the target
101          */
102         public static function copy(&$source, &$target, $elementname) {
103                 if (count($source->children()) == 0)
104                         $target->addChild($elementname, xmlify($source));
105                 else {
106                         $child = $target->addChild($elementname);
107                         foreach ($source->children() AS $childfield => $childentry)
108                                 self::copy($childentry, $child, $childfield);
109                 }
110         }
111
112         /**
113          * @brief Create an XML element
114          *
115          * @param object $doc XML root
116          * @param string $element XML element name
117          * @param string $value XML value
118          * @param array $attributes array containing the attributes
119          *
120          * @return object XML element object
121          */
122         public static function create_element($doc, $element, $value = "", $attributes = array()) {
123                 $element = $doc->createElement($element, xmlify($value));
124
125                 foreach ($attributes AS $key => $value) {
126                         $attribute = $doc->createAttribute($key);
127                         $attribute->value = xmlify($value);
128                         $element->appendChild($attribute);
129                 }
130                 return $element;
131         }
132
133         /**
134          * @brief Create an XML and append it to the parent object
135          *
136          * @param object $doc XML root
137          * @param object $parent parent object
138          * @param string $element XML element name
139          * @param string $value XML value
140          * @param array $attributes array containing the attributes
141          */
142         public static function add_element($doc, $parent, $element, $value = "", $attributes = array()) {
143                 $element = self::create_element($doc, $element, $value, $attributes);
144                 $parent->appendChild($element);
145         }
146
147         /**
148          * @brief Convert an XML document to a normalised, case-corrected array
149          *   used by webfinger
150          * 
151          * @param object $xml_element The XML document
152          * @param integer $recursion_depth recursion counter for internal use - default 0 
153          *    internal use, recursion counter
154          * 
155          * @return array | sring The array from the xml element or the string
156          */
157         public static function element_to_array($xml_element, &$recursion_depth=0) {
158
159                 // If we're getting too deep, bail out
160                 if ($recursion_depth > 512) {
161                         return(null);
162                 }
163
164                 if (!is_string($xml_element) &&
165                 !is_array($xml_element) &&
166                 (get_class($xml_element) == 'SimpleXMLElement')) {
167                         $xml_element_copy = $xml_element;
168                         $xml_element = get_object_vars($xml_element);
169                 }
170
171                 if (is_array($xml_element)) {
172                         $result_array = array();
173                         if (count($xml_element) <= 0) {
174                                 return (trim(strval($xml_element_copy)));
175                         }
176
177                         foreach($xml_element as $key=>$value) {
178
179                                 $recursion_depth++;
180                                 $result_array[strtolower($key)] =
181                                         self::element_to_array($value, $recursion_depth);
182                                 $recursion_depth--;
183                         }
184                         if ($recursion_depth == 0) {
185                                 $temp_array = $result_array;
186                                 $result_array = array(
187                                         strtolower($xml_element_copy->getName()) => $temp_array,
188                                 );
189                         }
190
191                         return ($result_array);
192
193                 } else {
194                         return (trim(strval($xml_element)));
195                 }
196         }
197
198         /**
199          * @brief Convert the given XML text to an array in the XML structure.
200          * 
201          * xml::to_array() will convert the given XML text to an array in the XML structure.
202          * Link: http://www.bin-co.com/php/scripts/xml2array/
203          * Portions significantly re-written by mike@macgirvin.com for Friendica
204          * (namespaces, lowercase tags, get_attribute default changed, more...)
205          * 
206          * Examples: $array =  xml::to_array(file_get_contents('feed.xml'));
207          *              $array =  xml::to_array(file_get_contents('feed.xml', true, 1, 'attribute'));
208          * 
209          * @param object $contents The XML text
210          * @param boolean $namespaces True or false include namespace information
211          *      in the returned array as array elements.
212          * @param integer $get_attributes 1 or 0. If this is 1 the function will get the attributes as well as the tag values - 
213          *      this results in a different array structure in the return value.
214          * @param string $priority Can be 'tag' or 'attribute'. This will change the way the resulting
215          *       array sturcture. For 'tag', the tags are given more importance.
216          * 
217          * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
218          */
219         public static function to_array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
220                 if(!$contents) return array();
221
222                 if(!function_exists('xml_parser_create')) {
223                         logger('xml::to_array: parser function missing');
224                         return array();
225                 }
226
227
228                 libxml_use_internal_errors(true);
229                 libxml_clear_errors();
230
231                 if($namespaces)
232                         $parser = @xml_parser_create_ns("UTF-8",':');
233                 else
234                         $parser = @xml_parser_create();
235
236                 if(! $parser) {
237                         logger('xml::to_array: xml_parser_create: no resource');
238                         return array();
239                 }
240
241                 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
242                 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
243                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
244                 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
245                 @xml_parse_into_struct($parser, trim($contents), $xml_values);
246                 @xml_parser_free($parser);
247
248                 if(! $xml_values) {
249                         logger('xml::to_array: libxml: parse error: ' . $contents, LOGGER_DATA);
250                         foreach(libxml_get_errors() as $err)
251                                 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
252                         libxml_clear_errors();
253                         return;
254                 }
255
256                 //Initializations
257                 $xml_array = array();
258                 $parents = array();
259                 $opened_tags = array();
260                 $arr = array();
261
262                 $current = &$xml_array; // Reference
263
264                 // Go through the tags.
265                 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
266                 foreach($xml_values as $data) {
267                         unset($attributes,$value); // Remove existing values, or there will be trouble
268
269                         // This command will extract these variables into the foreach scope
270                         // tag(string), type(string), level(int), attributes(array).
271                         extract($data); // We could use the array by itself, but this cooler.
272
273                         $result = array();
274                         $attributes_data = array();
275
276                         if(isset($value)) {
277                                 if($priority == 'tag') $result = $value;
278                                 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
279                         }
280
281                         //Set the attributes too.
282                         if(isset($attributes) and $get_attributes) {
283                                 foreach($attributes as $attr => $val) {
284                                         if($priority == 'tag') $attributes_data[$attr] = $val;
285                                         else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
286                                 }
287                         }
288
289                         // See tag status and do the needed.
290                         if($namespaces && strpos($tag,':')) {
291                                 $namespc = substr($tag,0,strrpos($tag,':'));
292                                 $tag = strtolower(substr($tag,strlen($namespc)+1));
293                                 $result['@namespace'] = $namespc;
294                         }
295                         $tag = strtolower($tag);
296
297                         if($type == "open") {   // The starting of the tag '<tag>'
298                                 $parent[$level-1] = &$current;
299                                 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
300                                         $current[$tag] = $result;
301                                         if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
302                                         $repeated_tag_index[$tag.'_'.$level] = 1;
303
304                                         $current = &$current[$tag];
305
306                                 } else { // There was another element with the same tag name
307
308                                         if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
309                                                 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
310                                                 $repeated_tag_index[$tag.'_'.$level]++;
311                                         } else { // This section will make the value an array if multiple tags with the same name appear together
312                                                 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
313                                                 $repeated_tag_index[$tag.'_'.$level] = 2;
314
315                                                 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
316                                                         $current[$tag]['0_attr'] = $current[$tag.'_attr'];
317                                                         unset($current[$tag.'_attr']);
318                                                 }
319
320                                         }
321                                         $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
322                                         $current = &$current[$tag][$last_item_index];
323                                 }
324
325                         } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
326                                 //See if the key is already taken.
327                                 if(!isset($current[$tag])) { //New Key
328                                         $current[$tag] = $result;
329                                         $repeated_tag_index[$tag.'_'.$level] = 1;
330                                         if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
331
332                                 } else { // If taken, put all things inside a list(array)
333                                         if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
334
335                                                 // ...push the new element into that array.
336                                                 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
337
338                                                 if($priority == 'tag' and $get_attributes and $attributes_data) {
339                                                         $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
340                                                 }
341                                                 $repeated_tag_index[$tag.'_'.$level]++;
342
343                                         } else { // If it is not an array...
344                                                 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
345                                                 $repeated_tag_index[$tag.'_'.$level] = 1;
346                                                 if($priority == 'tag' and $get_attributes) {
347                                                         if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
348
349                                                                 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
350                                                                 unset($current[$tag.'_attr']);
351                                                         }
352
353                                                         if($attributes_data) {
354                                                                 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
355                                                         }
356                                                 }
357                                                 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
358                                         }
359                                 }
360
361                         } elseif($type == 'close') { // End of tag '</tag>'
362                                 $current = &$parent[$level-1];
363                         }
364                 }
365
366                 return($xml_array);
367         }
368 }
369 ?>