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