]> git.mxchange.org Git - friendica.git/blob - src/Util/XML.php
Add tests for BBCode::fetchShareAttributes
[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 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 DOMElement  $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, DOMElement &$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 used by webfinger
195          *
196          * @param object  $xml_element     The XML document
197          * @param integer $recursion_depth recursion counter for internal use - default 0
198          *                                 internal use, recursion counter
199          *
200          * @return array | string The array from the xml element or the string
201          */
202         public static function elementToArray($xml_element, int &$recursion_depth = 0)
203         {
204                 // If we're getting too deep, bail out
205                 if ($recursion_depth > 512) {
206                         return null;
207                 }
208
209                 $xml_element_copy = '';
210                 if (!is_string($xml_element)
211                         && !is_array($xml_element)
212                         && (get_class($xml_element) == 'SimpleXMLElement')
213                 ) {
214                         $xml_element_copy = $xml_element;
215                         $xml_element = get_object_vars($xml_element);
216                 }
217
218                 if (is_array($xml_element)) {
219                         $result_array = [];
220                         if (count($xml_element) <= 0) {
221                                 return trim(strval($xml_element_copy));
222                         }
223
224                         foreach ($xml_element as $key => $value) {
225                                 $recursion_depth++;
226                                 $result_array[strtolower($key)] = self::elementToArray($value, $recursion_depth);
227                                 $recursion_depth--;
228                         }
229
230                         if ($recursion_depth == 0) {
231                                 $temp_array = $result_array;
232                                 $result_array = [
233                                         strtolower($xml_element_copy->getName()) => $temp_array,
234                                 ];
235                         }
236
237                         return $result_array;
238                 } else {
239                         return trim(strval($xml_element));
240                 }
241         }
242
243         /**
244          * Convert the given XML text to an array in the XML structure.
245          *
246          * Xml::toArray() will convert the given XML text to an array in the XML structure.
247          * Link: http://www.bin-co.com/php/scripts/xml2array/
248          * Portions significantly re-written by mike@macgirvin.com for Friendica
249          * (namespaces, lowercase tags, get_attribute default changed, more...)
250          *
251          * Examples: $array =  Xml::toArray(file_get_contents('feed.xml'));
252          *        $array =  Xml::toArray(file_get_contents('feed.xml', true, 1, 'attribute'));
253          *
254          * @param string  $contents         The XML text
255          * @param boolean $namespaces       True or false include namespace information
256          *                                  in the returned array as array elements.
257          * @param integer $get_attributes   1 or 0. If this is 1 the function will get the attributes as well as the tag values -
258          *                                  this results in a different array structure in the return value.
259          * @param string  $priority         Can be 'tag' or 'attribute'. This will change the way the resulting
260          *                                  array sturcture. For 'tag', the tags are given more importance.
261          *
262          * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
263          * @throws \Exception
264          */
265         public static function toArray(string $contents, bool $namespaces = true, int $get_attributes = 1, string $priority = 'attribute'): array
266         {
267                 if (!$contents) {
268                         return [];
269                 }
270
271                 if (!function_exists('xml_parser_create')) {
272                         Logger::notice('Xml::toArray: parser function missing');
273                         return [];
274                 }
275
276
277                 libxml_use_internal_errors(true);
278                 libxml_clear_errors();
279
280                 if ($namespaces) {
281                         $parser = @xml_parser_create_ns("UTF-8", ':');
282                 } else {
283                         $parser = @xml_parser_create();
284                 }
285
286                 if (! $parser) {
287                         Logger::notice('Xml::toArray: xml_parser_create: no resource');
288                         return [];
289                 }
290
291                 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
292                 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
293                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
294                 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
295                 @xml_parse_into_struct($parser, trim($contents), $xml_values);
296                 @xml_parser_free($parser);
297
298                 if (! $xml_values) {
299                         Logger::debug('Xml::toArray: libxml: parse error: ' . $contents);
300                         foreach (libxml_get_errors() as $err) {
301                                 Logger::debug('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message);
302                         }
303                         libxml_clear_errors();
304                         return [];
305                 }
306
307                 //Initializations
308                 $xml_array = [];
309
310                 $current = &$xml_array; // Reference
311
312                 // Go through the tags.
313                 $repeated_tag_index = []; // Multiple tags with same name will be turned into an array
314                 foreach ($xml_values as $data) {
315                         $tag        = $data['tag'];
316                         $type       = $data['type'];
317                         $level      = $data['level'];
318                         $attributes = isset($data['attributes']) ? $data['attributes'] : null;
319                         $value      = isset($data['value']) ? $data['value'] : null;
320
321                         $result = [];
322                         $attributes_data = [];
323
324                         if (isset($value)) {
325                                 if ($priority == 'tag') {
326                                         $result = $value;
327                                 } else {
328                                         $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
329                                 }
330                         }
331
332                         //Set the attributes too.
333                         if (isset($attributes) and $get_attributes) {
334                                 foreach ($attributes as $attr => $val) {
335                                         if ($priority == 'tag') {
336                                                 $attributes_data[$attr] = $val;
337                                         } else {
338                                                 $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
339                                         }
340                                 }
341                         }
342
343                         // See tag status and do the needed.
344                         if ($namespaces && strpos($tag, ':')) {
345                                 $namespc = substr($tag, 0, strrpos($tag, ':'));
346                                 $tag = strtolower(substr($tag, strlen($namespc)+1));
347                                 $result['@namespace'] = $namespc;
348                         }
349                         $tag = strtolower($tag);
350
351                         if ($type == "open") {   // The starting of the tag '<tag>'
352                                 $parent[$level-1] = &$current;
353                                 if (!is_array($current) || (!in_array($tag, array_keys($current)))) { // Insert New tag
354                                         $current[$tag] = $result;
355                                         if ($attributes_data) {
356                                                 $current[$tag. '_attr'] = $attributes_data;
357                                         }
358                                         $repeated_tag_index[$tag.'_'.$level] = 1;
359
360                                         $current = &$current[$tag];
361                                 } else { // There was another element with the same tag name
362
363                                         if (isset($current[$tag][0])) { // If there is a 0th element it is already an array
364                                                 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
365                                                 $repeated_tag_index[$tag.'_'.$level]++;
366                                         } else { // This section will make the value an array if multiple tags with the same name appear together
367                                                 $current[$tag] = [$current[$tag], $result]; // This will combine the existing item and the new item together to make an array
368                                                 $repeated_tag_index[$tag.'_'.$level] = 2;
369
370                                                 if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
371                                                         $current[$tag]['0_attr'] = $current[$tag.'_attr'];
372                                                         unset($current[$tag.'_attr']);
373                                                 }
374                                         }
375                                         $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
376                                         $current = &$current[$tag][$last_item_index];
377                                 }
378                         } elseif ($type == "complete") { // Tags that ends in 1 line '<tag />'
379                                 //See if the key is already taken.
380                                 if (!isset($current[$tag])) { //New Key
381                                         $current[$tag] = $result;
382                                         $repeated_tag_index[$tag.'_'.$level] = 1;
383                                         if ($priority == 'tag' and $attributes_data) {
384                                                 $current[$tag. '_attr'] = $attributes_data;
385                                         }
386                                 } else { // If taken, put all things inside a list(array)
387                                         if (isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
388
389                                                 // ...push the new element into that array.
390                                                 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
391
392                                                 if ($priority == 'tag' and $get_attributes and $attributes_data) {
393                                                         $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
394                                                 }
395                                                 $repeated_tag_index[$tag.'_'.$level]++;
396                                         } else { // If it is not an array...
397                                                 $current[$tag] = [$current[$tag], $result]; //...Make it an array using using the existing value and the new value
398                                                 $repeated_tag_index[$tag.'_'.$level] = 1;
399                                                 if ($priority == 'tag' and $get_attributes) {
400                                                         if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
401
402                                                                 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
403                                                                 unset($current[$tag.'_attr']);
404                                                         }
405
406                                                         if ($attributes_data) {
407                                                                 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
408                                                         }
409                                                 }
410                                                 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
411                                         }
412                                 }
413                         } elseif ($type == 'close') { // End of tag '</tag>'
414                                 $current = &$parent[$level-1];
415                         }
416                 }
417
418                 return $xml_array;
419         }
420
421         /**
422          * Delete a node in a XML object
423          *
424          * @param DOMDocument $doc  XML document
425          * @param string $node Node name
426          * @return void
427          */
428         public static function deleteNode(DOMDocument $doc, string $node)
429         {
430                 $xpath = new DOMXPath($doc);
431                 $list = $xpath->query('//' . $node);
432                 foreach ($list as $child) {
433                         $child->parentNode->removeChild($child);
434                 }
435         }
436
437         /**
438          * Parse XML string
439          *
440          * @param string  $s XML string to parse into object
441          * @param boolean $suppress_log Whether to supressing logging
442          * @return SimpleXMLElement|bool SimpleXMLElement or false on failure
443          */
444         public static function parseString(string $s, bool $suppress_log = false)
445         {
446                 libxml_use_internal_errors(true);
447
448                 $x = @simplexml_load_string($s);
449                 if (!$x) {
450                         if (!$suppress_log) {
451                                 Logger::error('Error(s) while parsing XML string.', ['callstack' => System::callstack()]);
452                                 foreach (libxml_get_errors() as $err) {
453                                         Logger::info('libxml error', ['code' => $err->code, 'position' => $err->line . ":" . $err->column, 'message' => $err->message]);
454                                 }
455                                 Logger::debug('Erroring XML string', ['xml' => $s]);
456                         }
457                         libxml_clear_errors();
458                 }
459                 return $x;
460         }
461
462         /**
463          * Gets first node value
464          *
465          * @param DOMXPath $xpath XPath object
466          * @param string $element Element name
467          * @param DOMNode $context Context object or NULL
468          * @return string XML node value or empty string on failure
469          */
470         public static function getFirstNodeValue(DOMXPath $xpath, string $element, DOMNode $context = null)
471         {
472                 $result = @$xpath->evaluate($element, $context);
473                 if (!is_object($result)) {
474                         return '';
475                 }
476
477                 $first_item = $result->item(0);
478                 if (!is_object($first_item)) {
479                         return '';
480                 }
481
482                 return $first_item->nodeValue;
483         }
484
485         /**
486          * Gets first attributes
487          *
488          * @param DOMXPath $xpath XPath object
489          * @param string $element Element name
490          * @param DOMNode $context Context object or NULL
491          * @return ???|bool First element's attributes field or false on failure
492          */
493         public static function getFirstAttributes(DOMXPath $xpath, string $element, DOMNode $context = null)
494         {
495                 $result = @$xpath->query($element, $context);
496                 if (!is_object($result)) {
497                         return false;
498                 }
499
500                 $first_item = $result->item(0);
501                 if (!is_object($first_item)) {
502                         return false;
503                 }
504
505                 return $first_item->attributes;
506         }
507
508         /**
509          * Gets first node's value
510          *
511          * @param DOMXPath $xpath XPath object
512          * @param string $element Element name
513          * @param DOMNode $context Context object or NULL
514          * @return string First value or empty string on failure
515          */
516         public static function getFirstValue(DOMXPath $xpath, string $element, DOMNode $context = null): string
517         {
518                 $result = @$xpath->query($element, $context);
519                 if (!is_object($result)) {
520                         return '';
521                 }
522
523                 $first_item = $result->item(0);
524                 if (!is_object($first_item)) {
525                         return '';
526                 }
527
528                 return $first_item->nodeValue;
529         }
530
531         /**
532          * escape text ($str) for XML transport
533          *
534          * @param string $str
535          * @return string Escaped text.
536          * @todo Move this generic method to Util\Strings and also rewrite all other findingd
537          */
538         public static function escape(string $str): string
539         {
540                 return trim(htmlspecialchars($str, ENT_QUOTES, 'UTF-8'));
541         }
542
543         /**
544          * Undo an escape
545          *
546          * @param string $s xml escaped text
547          * @return string unescaped text
548          * @todo Move this generic method to Util\Strings and also rewrite all other findingd
549          */
550         public static function unescape(string $s): string
551         {
552                 return htmlspecialchars_decode($s, ENT_QUOTES);
553         }
554
555         /**
556          * Apply escape() to all values of array $val, recursively
557          *
558          * @param array|bool|string $val Value of type bool, array or string
559          * @return array|string Returns array if array provided or string in other cases
560          * @todo Move this generic method to Util\Strings
561          */
562         public static function arrayEscape($val)
563         {
564                 if (is_bool($val)) {
565                         return $val ? 'true' : 'false';
566                 } elseif (is_array($val)) {
567                         return array_map('XML::arrayEscape', $val);
568                 }
569
570                 return self::escape((string) $val);
571         }
572 }