]> git.mxchange.org Git - friendica.git/blob - src/Util/XML.php
Merge pull request #11660 from Quix0r/fixes/more-type-hints-003
[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 createdXML 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 void
46          */
47         public static function fromArray(array $array, &$xml, bool $remove_header = false, array $namespaces = [], bool $root = true)
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         }
134
135         /**
136          * Copies an XML object
137          *
138          * @param object $source      The XML source
139          * @param object $target      The XML target
140          * @param string $elementname Name of the XML element of the target
141          * @return void
142          */
143         public static function copy(&$source, &$target, string $elementname)
144         {
145                 if (count($source->children()) == 0) {
146                         $target->addChild($elementname, self::escape($source));
147                 } else {
148                         $child = $target->addChild($elementname);
149                         foreach ($source->children() as $childfield => $childentry) {
150                                 self::copy($childentry, $child, $childfield);
151                         }
152                 }
153         }
154
155         /**
156          * Create an XML element
157          *
158          * @param DOMDocument $doc        XML root
159          * @param string       $element    XML element name
160          * @param string       $value      XML value
161          * @param array        $attributes array containing the attributes
162          *
163          * @return \DOMElement XML element object
164          */
165         public static function createElement(DOMDocument $doc, string $element, string $value = '', array $attributes = []): DOMElement
166         {
167                 $element = $doc->createElement($element, self::escape($value));
168
169                 foreach ($attributes as $key => $value) {
170                         $attribute = $doc->createAttribute($key);
171                         $attribute->value = self::escape($value);
172                         $element->appendChild($attribute);
173                 }
174                 return $element;
175         }
176
177         /**
178          * Create an XML and append it to the parent object
179          *
180          * @param DOMDocument $doc        XML root
181          * @param object $parent     parent object
182          * @param string $element    XML element name
183          * @param string $value      XML value
184          * @param array  $attributes array containing the attributes
185          * @return void
186          */
187         public static function addElement(DOMDocument $doc, $parent, string $element, string $value = '', array $attributes = [])
188         {
189                 $element = self::createElement($doc, $element, $value, $attributes);
190                 $parent->appendChild($element);
191         }
192
193         /**
194          * Convert an XML document to a normalised, case-corrected array
195          *   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
278                 libxml_use_internal_errors(true);
279                 libxml_clear_errors();
280
281                 if ($namespaces) {
282                         $parser = @xml_parser_create_ns("UTF-8", ':');
283                 } else {
284                         $parser = @xml_parser_create();
285                 }
286
287                 if (! $parser) {
288                         Logger::notice('Xml::toArray: xml_parser_create: no resource');
289                         return [];
290                 }
291
292                 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
293                 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
294                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
295                 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
296                 @xml_parse_into_struct($parser, trim($contents), $xml_values);
297                 @xml_parser_free($parser);
298
299                 if (! $xml_values) {
300                         Logger::debug('Xml::toArray: libxml: parse error: ' . $contents);
301                         foreach (libxml_get_errors() as $err) {
302                                 Logger::debug('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message);
303                         }
304                         libxml_clear_errors();
305                         return [];
306                 }
307
308                 //Initializations
309                 $xml_array = [];
310
311                 $current = &$xml_array; // Reference
312
313                 // Go through the tags.
314                 $repeated_tag_index = []; // Multiple tags with same name will be turned into an array
315                 foreach ($xml_values as $data) {
316                         $tag        = $data['tag'];
317                         $type       = $data['type'];
318                         $level      = $data['level'];
319                         $attributes = isset($data['attributes']) ? $data['attributes'] : null;
320                         $value      = isset($data['value']) ? $data['value'] : null;
321
322                         $result = [];
323                         $attributes_data = [];
324
325                         if (isset($value)) {
326                                 if ($priority == 'tag') {
327                                         $result = $value;
328                                 } else {
329                                         $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
330                                 }
331                         }
332
333                         //Set the attributes too.
334                         if (isset($attributes) and $get_attributes) {
335                                 foreach ($attributes as $attr => $val) {
336                                         if ($priority == 'tag') {
337                                                 $attributes_data[$attr] = $val;
338                                         } else {
339                                                 $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
340                                         }
341                                 }
342                         }
343
344                         // See tag status and do the needed.
345                         if ($namespaces && strpos($tag, ':')) {
346                                 $namespc = substr($tag, 0, strrpos($tag, ':'));
347                                 $tag = strtolower(substr($tag, strlen($namespc)+1));
348                                 $result['@namespace'] = $namespc;
349                         }
350                         $tag = strtolower($tag);
351
352                         if ($type == "open") {   // The starting of the tag '<tag>'
353                                 $parent[$level-1] = &$current;
354                                 if (!is_array($current) || (!in_array($tag, array_keys($current)))) { // Insert New tag
355                                         $current[$tag] = $result;
356                                         if ($attributes_data) {
357                                                 $current[$tag. '_attr'] = $attributes_data;
358                                         }
359                                         $repeated_tag_index[$tag.'_'.$level] = 1;
360
361                                         $current = &$current[$tag];
362                                 } else { // There was another element with the same tag name
363
364                                         if (isset($current[$tag][0])) { // If there is a 0th element it is already an array
365                                                 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
366                                                 $repeated_tag_index[$tag.'_'.$level]++;
367                                         } else { // This section will make the value an array if multiple tags with the same name appear together
368                                                 $current[$tag] = [$current[$tag], $result]; // This will combine the existing item and the new item together to make an array
369                                                 $repeated_tag_index[$tag.'_'.$level] = 2;
370
371                                                 if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
372                                                         $current[$tag]['0_attr'] = $current[$tag.'_attr'];
373                                                         unset($current[$tag.'_attr']);
374                                                 }
375                                         }
376                                         $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
377                                         $current = &$current[$tag][$last_item_index];
378                                 }
379                         } elseif ($type == "complete") { // Tags that ends in 1 line '<tag />'
380                                 //See if the key is already taken.
381                                 if (!isset($current[$tag])) { //New Key
382                                         $current[$tag] = $result;
383                                         $repeated_tag_index[$tag.'_'.$level] = 1;
384                                         if ($priority == 'tag' and $attributes_data) {
385                                                 $current[$tag. '_attr'] = $attributes_data;
386                                         }
387                                 } else { // If taken, put all things inside a list(array)
388                                         if (isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
389
390                                                 // ...push the new element into that array.
391                                                 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
392
393                                                 if ($priority == 'tag' and $get_attributes and $attributes_data) {
394                                                         $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
395                                                 }
396                                                 $repeated_tag_index[$tag.'_'.$level]++;
397                                         } else { // If it is not an array...
398                                                 $current[$tag] = [$current[$tag], $result]; //...Make it an array using using the existing value and the new value
399                                                 $repeated_tag_index[$tag.'_'.$level] = 1;
400                                                 if ($priority == 'tag' and $get_attributes) {
401                                                         if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
402
403                                                                 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
404                                                                 unset($current[$tag.'_attr']);
405                                                         }
406
407                                                         if ($attributes_data) {
408                                                                 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
409                                                         }
410                                                 }
411                                                 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
412                                         }
413                                 }
414                         } elseif ($type == 'close') { // End of tag '</tag>'
415                                 $current = &$parent[$level-1];
416                         }
417                 }
418
419                 return $xml_array;
420         }
421
422         /**
423          * Delete a node in a XML object
424          *
425          * @param DOMDocument $doc  XML document
426          * @param string $node Node name
427          * @return void
428          */
429         public static function deleteNode(DOMDocument $doc, string $node)
430         {
431                 $xpath = new DOMXPath($doc);
432                 $list = $xpath->query('//' . $node);
433                 foreach ($list as $child) {
434                         $child->parentNode->removeChild($child);
435                 }
436         }
437
438         /**
439          * Parse XML string
440          *
441          * @param string  $s XML string to parse into object
442          * @param boolean $suppress_log Whether to supressing logging
443          * @return SimpleXMLElement|bool SimpleXMLElement or false on failure
444          */
445         public static function parseString(string $s, bool $suppress_log = false)
446         {
447                 libxml_use_internal_errors(true);
448
449                 $x = @simplexml_load_string($s);
450                 if (!$x) {
451                         if (!$suppress_log) {
452                                 Logger::error('Error(s) while parsing XML string.', ['callstack' => System::callstack()]);
453                                 foreach (libxml_get_errors() as $err) {
454                                         Logger::info('libxml error', ['code' => $err->code, 'position' => $err->line . ":" . $err->column, 'message' => $err->message]);
455                                 }
456                                 Logger::debug('Erroring XML string', ['xml' => $s]);
457                         }
458                         libxml_clear_errors();
459                 }
460                 return $x;
461         }
462
463         /**
464          * Gets first node value
465          *
466          * @param DOMXPath $xpath XPath object
467          * @param string $element Element name
468          * @param DOMNode $context Context object or NULL
469          * @return string XML node value or empty string on failure
470          */
471         public static function getFirstNodeValue(DOMXPath $xpath, string $element, DOMNode $context = null)
472         {
473                 $result = @$xpath->evaluate($element, $context);
474                 if (!is_object($result)) {
475                         return '';
476                 }
477
478                 $first_item = $result->item(0);
479                 if (!is_object($first_item)) {
480                         return '';
481                 }
482
483                 return $first_item->nodeValue;
484         }
485
486         /**
487          * Gets first attributes
488          *
489          * @param DOMXPath $xpath XPath object
490          * @param string $element Element name
491          * @param DOMNode $context Context object or NULL
492          * @return ???|bool First element's attributes field or false on failure
493          */
494         public static function getFirstAttributes(DOMXPath $xpath, string $element, DOMNode $context = null)
495         {
496                 $result = @$xpath->query($element, $context);
497                 if (!is_object($result)) {
498                         return false;
499                 }
500
501                 $first_item = $result->item(0);
502                 if (!is_object($first_item)) {
503                         return false;
504                 }
505
506                 return $first_item->attributes;
507         }
508
509         /**
510          * Gets first node's value
511          *
512          * @param DOMXPath $xpath XPath object
513          * @param string $element Element name
514          * @param DOMNode $context Context object or NULL
515          * @return string First value or empty string on failure
516          */
517         public static function getFirstValue(DOMXPath $xpath, string $element, DOMNode $context = null): string
518         {
519                 $result = @$xpath->query($element, $context);
520                 if (!is_object($result)) {
521                         return '';
522                 }
523
524                 $first_item = $result->item(0);
525                 if (!is_object($first_item)) {
526                         return '';
527                 }
528
529                 return $first_item->nodeValue;
530         }
531
532         /**
533          * escape text ($str) for XML transport
534          *
535          * @param string $str
536          * @return string Escaped text.
537          * @todo Move this generic method to Util\Strings and also rewrite all other findingd
538          */
539         public static function escape(string $str): string
540         {
541                 return trim(htmlspecialchars($str, ENT_QUOTES, 'UTF-8'));
542         }
543
544         /**
545          * Undo an escape
546          *
547          * @param string $s xml escaped text
548          * @return string unescaped text
549          * @todo Move this generic method to Util\Strings and also rewrite all other findingd
550          */
551         public static function unescape(string $s): string
552         {
553                 return htmlspecialchars_decode($s, ENT_QUOTES);
554         }
555
556         /**
557          * Apply escape() to all values of array $val, recursively
558          *
559          * @param array|bool|string $val Value of type bool, array or string
560          * @return array|string Returns array if array provided or string in other cases
561          * @todo Move this generic method to Util\Strings
562          */
563         public static function arrayEscape($val)
564         {
565                 if (is_bool($val)) {
566                         return $val ? 'true' : 'false';
567                 } elseif (is_array($val)) {
568                         return array_map('XML::arrayEscape', $val);
569                 }
570
571                 return self::escape((string) $val);
572         }
573 }