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