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