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