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