]> git.mxchange.org Git - friendica.git/blob - src/Util/XML.php
spelling: associative
[friendica.git] / src / Util / XML.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Util;
23
24 use DOMDocument;
25 use DOMElement;
26 use DOMNode;
27 use DOMXPath;
28 use Friendica\Core\Logger;
29 use Friendica\Core\System;
30 use SimpleXMLElement;
31
32 /**
33  * This class contain methods to work with XML data
34  */
35 class XML
36 {
37         /**
38          * Creates an XML structure out of a given array
39          *
40          * @param array       $array         The array of the XML structure that will be generated
41          * @param object|null $xml           The created XML will be returned by reference
42          * @param bool        $remove_header Should the XML header be removed or not?
43          * @param array       $namespaces    List of namespaces
44          * @param bool        $root          interally used parameter. Mustn't be used from outside.
45          * @return string
46          * @throws \Exception
47          */
48         public static function fromArray(array $array, object &$xml = null, bool $remove_header = false, array $namespaces = [], bool $root = true): string
49         {
50                 if ($root) {
51                         foreach ($array as $key => $value) {
52                                 foreach ($namespaces as $nskey => $nsvalue) {
53                                         $key .= ' xmlns' . ($nskey == '' ? '' : ':') . $nskey . '="' . $nsvalue . '"';
54                                 }
55
56                                 if (is_array($value)) {
57                                         $root = new SimpleXMLElement('<' . $key . '/>');
58                                         self::fromArray($value, $root, $remove_header, $namespaces, false);
59                                 } else {
60                                         $root = new SimpleXMLElement('<' . $key . '>' . self::escape($value ?? '') . '</' . $key . '>');
61                                 }
62
63                                 $dom = dom_import_simplexml($root)->ownerDocument;
64                                 $dom->formatOutput = true;
65                                 $xml = $dom;
66
67                                 $xml_text = $dom->saveXML();
68
69                                 if ($remove_header) {
70                                         $xml_text = trim(substr($xml_text, 21));
71                                 }
72
73                                 return $xml_text;
74                         }
75                 }
76
77                 $element = null;
78                 foreach ($array as $key => $value) {
79                         if (!isset($element) && isset($xml)) {
80                                 $element = $xml;
81                         }
82
83                         if (is_integer($key)) {
84                                 if (isset($element)) {
85                                         if (is_scalar($value)) {
86                                                 $element[0] = $value;
87                                         } else {
88                                                 /// @todo: handle nested array values
89                                         }
90                                 }
91                                 continue;
92                         }
93
94                         $element_parts = explode(':', $key);
95                         if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) {
96                                 $namespace = $namespaces[$element_parts[0]];
97                         } elseif (isset($namespaces[''])) {
98                                 $namespace = $namespaces[''];
99                         } else {
100                                 $namespace = null;
101                         }
102
103                         // Remove undefined namespaces from the key
104                         if ((count($element_parts) > 1) && is_null($namespace)) {
105                                 $key = $element_parts[1];
106                         }
107
108                         if (substr($key, 0, 11) == '@attributes') {
109                                 if (!isset($element) || !is_array($value)) {
110                                         continue;
111                                 }
112
113                                 foreach ($value as $attr_key => $attr_value) {
114                                         $element_parts = explode(':', $attr_key);
115                                         if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) {
116                                                 $namespace = $namespaces[$element_parts[0]];
117                                         } else {
118                                                 $namespace = null;
119                                         }
120
121                                         $element->addAttribute($attr_key, $attr_value, $namespace);
122                                 }
123
124                                 continue;
125                         }
126
127                         if (!is_array($value)) {
128                                 $element = $xml->addChild($key, self::escape($value ?? ''), $namespace);
129                         } else {
130                                 $element = $xml->addChild($key, null, $namespace);
131                                 self::fromArray($value, $element, $remove_header, $namespaces, false);
132                         }
133                 }
134                 return '';
135         }
136
137         /**
138          * Copies an XML object
139          *
140          * @param object|string $source      The XML source
141          * @param object        $target      The XML target
142          * @param string        $elementname Name of the XML element of the target
143          * @return void
144          */
145         public static function copy(&$source, &$target, $elementname)
146         {
147                 if (count($source->children()) == 0) {
148                         $target->addChild($elementname, self::escape($source));
149                 } else {
150                         $child = $target->addChild($elementname);
151                         foreach ($source->children() as $childfield => $childentry) {
152                                 self::copy($childentry, $child, $childfield);
153                         }
154                 }
155         }
156
157         /**
158          * Create an XML element
159          *
160          * @param DOMDocument $doc        XML root
161          * @param string       $element    XML element name
162          * @param string       $value      XML value
163          * @param array        $attributes array containing the attributes
164          *
165          * @return \DOMElement XML element object
166          */
167         public static function createElement(DOMDocument $doc, string $element, string $value = '', array $attributes = []): DOMElement
168         {
169                 $element = $doc->createElement($element, self::escape($value));
170
171                 foreach ($attributes as $key => $value) {
172                         $attribute = $doc->createAttribute($key);
173                         $attribute->value = self::escape($value ?? '');
174                         $element->appendChild($attribute);
175                 }
176                 return $element;
177         }
178
179         /**
180          * Create an XML and append it to the parent object
181          *
182          * @param DOMDocument $doc        XML root
183          * @param DOMElement  $parent     parent object
184          * @param string      $element    XML element name
185          * @param string      $value      XML value
186          * @param array       $attributes Array containing the attributes
187          * @return void
188          */
189         public static function addElement(DOMDocument $doc, DOMElement &$parent, string $element, string $value = null, array $attributes = [])
190         {
191                 $element = self::createElement($doc, $element, $value ?? '', $attributes);
192                 $parent->appendChild($element);
193         }
194
195         /**
196          * Convert an XML document to a normalised, case-corrected array used by webfinger
197          *
198          * @param object  $xml_element     The XML document
199          * @param integer $recursion_depth recursion counter for internal use - default 0
200          *                                 internal use, recursion counter
201          *
202          * @return array | string The array from the xml element or the string
203          */
204         public static function elementToArray($xml_element, int &$recursion_depth = 0)
205         {
206                 // If we're getting too deep, bail out
207                 if ($recursion_depth > 512) {
208                         return null;
209                 }
210
211                 $xml_element_copy = '';
212                 if (!is_string($xml_element)
213                         && !is_array($xml_element)
214                         && (get_class($xml_element) == 'SimpleXMLElement')
215                 ) {
216                         $xml_element_copy = $xml_element;
217                         $xml_element = get_object_vars($xml_element);
218                 }
219
220                 if (is_array($xml_element)) {
221                         $result_array = [];
222                         if (count($xml_element) <= 0) {
223                                 return trim(strval($xml_element_copy));
224                         }
225
226                         foreach ($xml_element as $key => $value) {
227                                 $recursion_depth++;
228                                 $result_array[strtolower($key)] = self::elementToArray($value, $recursion_depth);
229                                 $recursion_depth--;
230                         }
231
232                         if ($recursion_depth == 0) {
233                                 $temp_array = $result_array;
234                                 $result_array = [
235                                         strtolower($xml_element_copy->getName()) => $temp_array,
236                                 ];
237                         }
238
239                         return $result_array;
240                 } else {
241                         return trim(strval($xml_element));
242                 }
243         }
244
245         /**
246          * Convert the given XML text to an array in the XML structure.
247          *
248          * Xml::toArray() will convert the given XML text to an array in the XML structure.
249          * Link: http://www.bin-co.com/php/scripts/xml2array/
250          * Portions significantly re-written by mike@macgirvin.com for Friendica
251          * (namespaces, lowercase tags, get_attribute default changed, more...)
252          *
253          * Examples: $array =  Xml::toArray(file_get_contents('feed.xml'));
254          *        $array =  Xml::toArray(file_get_contents('feed.xml', true, 1, 'attribute'));
255          *
256          * @param string  $contents         The XML text
257          * @param boolean $namespaces       True or false include namespace information
258          *                                  in the returned array as array elements.
259          * @param integer $get_attributes   1 or 0. If this is 1 the function will get the attributes as well as the tag values -
260          *                                  this results in a different array structure in the return value.
261          * @param string  $priority         Can be 'tag' or 'attribute'. This will change the way the resulting
262          *                                  array structure. For 'tag', the tags are given more importance.
263          *
264          * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
265          * @throws \Exception
266          */
267         public static function toArray(string $contents, bool $namespaces = true, int $get_attributes = 1, string $priority = 'attribute'): array
268         {
269                 if (!$contents) {
270                         return [];
271                 }
272
273                 if (!function_exists('xml_parser_create')) {
274                         Logger::error('Xml::toArray: parser function missing');
275                         return [];
276                 }
277
278                 $parent = [];
279
280                 libxml_use_internal_errors(true);
281                 libxml_clear_errors();
282
283                 if ($namespaces) {
284                         $parser = @xml_parser_create_ns("UTF-8", ':');
285                 } else {
286                         $parser = @xml_parser_create();
287                 }
288
289                 if (!$parser) {
290                         Logger::warning('Xml::toArray: xml_parser_create: no resource');
291                         return [];
292                 }
293
294                 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
295                 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
296                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
297                 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
298                 @xml_parse_into_struct($parser, trim($contents), $xml_values);
299                 @xml_parser_free($parser);
300
301                 if (! $xml_values) {
302                         Logger::debug('Xml::toArray: libxml: parse error: ' . $contents);
303                         foreach (libxml_get_errors() as $err) {
304                                 Logger::debug('libxml: parse: ' . $err->code . ' at ' . $err->line . ':' . $err->column . ' : ' . $err->message);
305                         }
306                         libxml_clear_errors();
307                         return [];
308                 }
309
310                 //Initializations
311                 $xml_array = [];
312
313                 $current = &$xml_array; // Reference
314
315                 // Go through the tags.
316                 $repeated_tag_index = []; // Multiple tags with same name will be turned into an array
317                 foreach ($xml_values as $data) {
318                         $tag        = $data['tag'];
319                         $type       = $data['type'];
320                         $level      = $data['level'];
321                         $attributes = isset($data['attributes']) ? $data['attributes'] : null;
322                         $value      = isset($data['value']) ? $data['value'] : null;
323
324                         $result = [];
325                         $attributes_data = [];
326
327                         if (isset($value)) {
328                                 if ($priority == 'tag') {
329                                         $result = $value;
330                                 } else {
331                                         $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
332                                 }
333                         }
334
335                         //Set the attributes too.
336                         if (isset($attributes) and $get_attributes) {
337                                 foreach ($attributes as $attr => $val) {
338                                         if ($priority == 'tag') {
339                                                 $attributes_data[$attr] = $val;
340                                         } else {
341                                                 $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
342                                         }
343                                 }
344                         }
345
346                         // See tag status and do the needed.
347                         if ($namespaces && strpos($tag, ':')) {
348                                 $namespc = substr($tag, 0, strrpos($tag, ':'));
349                                 $tag = strtolower(substr($tag, strlen($namespc)+1));
350                                 $result['@namespace'] = $namespc;
351                         }
352                         $tag = strtolower($tag);
353
354                         if ($type == 'open') {   // The starting of the tag '<tag>'
355                                 $parent[$level-1] = &$current;
356                                 if (!is_array($current) || (!in_array($tag, array_keys($current)))) { // Insert New tag
357                                         $current[$tag] = $result;
358                                         if ($attributes_data) {
359                                                 $current[$tag. '_attr'] = $attributes_data;
360                                         }
361                                         $repeated_tag_index[$tag . '_' . $level] = 1;
362
363                                         $current = &$current[$tag];
364                                 } else { // There was another element with the same tag name
365
366                                         if (isset($current[$tag][0])) { // If there is a 0th element it is already an array
367                                                 $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
368                                                 $repeated_tag_index[$tag . '_' . $level]++;
369                                         } else { // This section will make the value an array if multiple tags with the same name appear together
370                                                 $current[$tag] = [$current[$tag], $result]; // This will combine the existing item and the new item together to make an array
371                                                 $repeated_tag_index[$tag . '_' . $level] = 2;
372
373                                                 if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
374                                                         $current[$tag]['0_attr'] = $current[$tag.'_attr'];
375                                                         unset($current[$tag.'_attr']);
376                                                 }
377                                         }
378                                         $last_item_index = $repeated_tag_index[$tag . '_' . $level]-1;
379                                         $current = &$current[$tag][$last_item_index];
380                                 }
381                         } elseif ($type == 'complete') { // Tags that ends in 1 line '<tag />'
382                                 //See if the key is already taken.
383                                 if (!isset($current[$tag])) { //New Key
384                                         $current[$tag] = $result;
385                                         $repeated_tag_index[$tag . '_' . $level] = 1;
386                                         if ($priority == 'tag' and $attributes_data) {
387                                                 $current[$tag. '_attr'] = $attributes_data;
388                                         }
389                                 } else { // If taken, put all things inside a list(array)
390                                         if (isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
391
392                                                 // ...push the new element into that array.
393                                                 $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
394
395                                                 if ($priority == 'tag' and $get_attributes and $attributes_data) {
396                                                         $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
397                                                 }
398                                                 $repeated_tag_index[$tag . '_' . $level]++;
399                                         } else { // If it is not an array...
400                                                 $current[$tag] = [$current[$tag], $result]; //...Make it an array using the existing value and the new value
401                                                 $repeated_tag_index[$tag . '_' . $level] = 1;
402                                                 if ($priority == 'tag' and $get_attributes) {
403                                                         if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
404
405                                                                 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
406                                                                 unset($current[$tag.'_attr']);
407                                                         }
408
409                                                         if ($attributes_data) {
410                                                                 $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
411                                                         }
412                                                 }
413                                                 $repeated_tag_index[$tag . '_' . $level]++; // 0 and 1 indexes are already taken
414                                         }
415                                 }
416                         } elseif ($type == 'close') { // End of tag '</tag>'
417                                 $current = &$parent[$level-1];
418                         }
419                 }
420
421                 return $xml_array;
422         }
423
424         /**
425          * Delete a node in a XML object
426          *
427          * @param DOMDocument $doc  XML document
428          * @param string $node Node name
429          * @return void
430          */
431         public static function deleteNode(DOMDocument $doc, string $node)
432         {
433                 $xpath = new DOMXPath($doc);
434                 $list = $xpath->query('//' . $node);
435                 foreach ($list as $child) {
436                         $child->parentNode->removeChild($child);
437                 }
438         }
439
440         /**
441          * Parse XML string
442          *
443          * @param string  $s XML string to parse into object
444          * @param boolean $suppress_log Whether to suppressing logging
445          * @return SimpleXMLElement|bool SimpleXMLElement or false on failure
446          */
447         public static function parseString(string $s, bool $suppress_log = false)
448         {
449                 libxml_use_internal_errors(true);
450
451                 $x = @simplexml_load_string($s);
452                 if (!$x) {
453                         if (!$suppress_log) {
454                                 Logger::error('Error(s) while parsing XML string.', ['callstack' => System::callstack()]);
455                                 foreach (libxml_get_errors() as $err) {
456                                         Logger::info('libxml error', ['code' => $err->code, 'position' => $err->line . ':' . $err->column, 'message' => $err->message]);
457                                 }
458                                 Logger::debug('Erroring XML string', ['xml' => $s]);
459                         }
460                         libxml_clear_errors();
461                 }
462                 return $x;
463         }
464
465         /**
466          * Gets first node value
467          *
468          * @param DOMXPath $xpath XPath object
469          * @param string $element Element name
470          * @param DOMNode $context Context object or NULL
471          * @return string XML node value or empty string on failure
472          */
473         public static function getFirstNodeValue(DOMXPath $xpath, string $element, DOMNode $context = null)
474         {
475                 $result = @$xpath->evaluate($element, $context);
476                 if (!is_object($result)) {
477                         return '';
478                 }
479
480                 $first_item = $result->item(0);
481                 if (!is_object($first_item)) {
482                         return '';
483                 }
484
485                 return $first_item->nodeValue;
486         }
487
488         /**
489          * Gets first attributes
490          *
491          * @param DOMXPath $xpath XPath object
492          * @param string $element Element name
493          * @param DOMNode $context Context object or NULL
494          * @return ???|bool First element's attributes field or false on failure
495          */
496         public static function getFirstAttributes(DOMXPath $xpath, string $element, DOMNode $context = null)
497         {
498                 $result = @$xpath->query($element, $context);
499                 if (!is_object($result)) {
500                         return false;
501                 }
502
503                 $first_item = $result->item(0);
504                 if (!is_object($first_item)) {
505                         return false;
506                 }
507
508                 return $first_item->attributes;
509         }
510
511         /**
512          * Gets first node's value
513          *
514          * @param DOMXPath $xpath XPath object
515          * @param string $element Element name
516          * @param DOMNode $context Context object or NULL
517          * @return string First value or empty string on failure
518          */
519         public static function getFirstValue(DOMXPath $xpath, string $element, DOMNode $context = null): string
520         {
521                 $result = @$xpath->query($element, $context);
522                 if (!is_object($result)) {
523                         return '';
524                 }
525
526                 $first_item = $result->item(0);
527                 if (!is_object($first_item)) {
528                         return '';
529                 }
530
531                 return $first_item->nodeValue;
532         }
533
534         /**
535          * escape text ($str) for XML transport
536          *
537          * @param string $str
538          * @return string Escaped text.
539          * @todo Move this generic method to Util\Strings and also rewrite all other occurrences
540          */
541         public static function escape(string $str): string
542         {
543                 return trim(htmlspecialchars($str, ENT_QUOTES, 'UTF-8'));
544         }
545
546         /**
547          * Undo an escape
548          *
549          * @param string $s xml escaped text
550          * @return string unescaped text
551          * @todo Move this generic method to Util\Strings and also rewrite all other occurrences
552          */
553         public static function unescape(string $s): string
554         {
555                 return htmlspecialchars_decode($s, ENT_QUOTES);
556         }
557
558         /**
559          * Apply escape() to all values of array $val, recursively
560          *
561          * @param array|bool|string $val Value of type bool, array or string
562          * @return array|string Returns array if array provided or string in other cases
563          * @todo Move this generic method to Util\Strings
564          */
565         public static function arrayEscape($val)
566         {
567                 if (is_bool($val)) {
568                         return $val ? 'true' : 'false';
569                 } elseif (is_array($val)) {
570                         return array_map('XML::arrayEscape', $val);
571                 }
572
573                 return self::escape((string) $val);
574         }
575 }