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