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