3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Util;
28 use Friendica\Core\Logger;
29 use Friendica\Core\System;
33 * This class contain methods to work with XML data
38 * Creates an XML structure out of a given array
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.
48 public static function fromArray(array $array, object &$xml = null, bool $remove_header = false, array $namespaces = [], bool $root = true): string
51 foreach ($array as $key => $value) {
52 foreach ($namespaces as $nskey => $nsvalue) {
53 $key .= ' xmlns' . ($nskey == '' ? '' : ':') . $nskey . '="' . $nsvalue . '"';
56 if (is_array($value)) {
57 $root = new SimpleXMLElement('<' . $key . '/>');
58 self::fromArray($value, $root, $remove_header, $namespaces, false);
60 $root = new SimpleXMLElement('<' . $key . '>' . self::escape($value ?? '') . '</' . $key . '>');
63 $dom = dom_import_simplexml($root)->ownerDocument;
64 $dom->formatOutput = true;
67 $xml_text = $dom->saveXML();
70 $xml_text = trim(substr($xml_text, 21));
78 foreach ($array as $key => $value) {
79 if (!isset($element) && isset($xml)) {
83 if (is_integer($key)) {
84 if (isset($element)) {
85 if (is_scalar($value)) {
88 /// @todo: handle nested array values
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[''];
103 // Remove undefined namespaces from the key
104 if ((count($element_parts) > 1) && is_null($namespace)) {
105 $key = $element_parts[1];
108 if (substr($key, 0, 11) == '@attributes') {
109 if (!isset($element) || !is_array($value)) {
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]];
121 $element->addAttribute($attr_key, $attr_value, $namespace);
127 if (!is_array($value)) {
128 $element = $xml->addChild($key, self::escape($value ?? ''), $namespace);
130 $element = $xml->addChild($key, null, $namespace);
131 self::fromArray($value, $element, $remove_header, $namespaces, false);
138 * Copies an XML object
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
145 public static function copy(&$source, &$target, $elementname)
147 if (count($source->children()) == 0) {
148 $target->addChild($elementname, self::escape($source));
150 $child = $target->addChild($elementname);
151 foreach ($source->children() as $childfield => $childentry) {
152 self::copy($childentry, $child, $childfield);
158 * Create an XML element
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
165 * @return \DOMElement XML element object
167 public static function createElement(DOMDocument $doc, string $element, string $value = '', array $attributes = []): DOMElement
169 $element = $doc->createElement($element, self::escape($value));
171 foreach ($attributes as $key => $value) {
172 $attribute = $doc->createAttribute($key);
173 $attribute->value = self::escape($value ?? '');
174 $element->appendChild($attribute);
180 * Create an XML and append it to the parent object
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
189 public static function addElement(DOMDocument $doc, DOMElement &$parent, string $element, string $value = null, array $attributes = [])
191 $element = self::createElement($doc, $element, $value ?? '', $attributes);
192 $parent->appendChild($element);
196 * Convert an XML document to a normalised, case-corrected array used by webfinger
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
202 * @return array | string The array from the xml element or the string
204 public static function elementToArray($xml_element, int &$recursion_depth = 0)
206 // If we're getting too deep, bail out
207 if ($recursion_depth > 512) {
211 $xml_element_copy = '';
212 if (!is_string($xml_element)
213 && !is_array($xml_element)
214 && (get_class($xml_element) == 'SimpleXMLElement')
216 $xml_element_copy = $xml_element;
217 $xml_element = get_object_vars($xml_element);
220 if (is_array($xml_element)) {
222 if (count($xml_element) <= 0) {
223 return trim(strval($xml_element_copy));
226 foreach ($xml_element as $key => $value) {
228 $result_array[strtolower($key)] = self::elementToArray($value, $recursion_depth);
232 if ($recursion_depth == 0) {
233 $temp_array = $result_array;
235 strtolower($xml_element_copy->getName()) => $temp_array,
239 return $result_array;
241 return trim(strval($xml_element));
246 * Convert the given XML text to an array in the XML structure.
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...)
253 * Examples: $array = Xml::toArray(file_get_contents('feed.xml'));
254 * $array = Xml::toArray(file_get_contents('feed.xml', true, 1, 'attribute'));
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.
264 * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
267 public static function toArray(string $contents, bool $namespaces = true, int $get_attributes = 1, string $priority = 'attribute'): array
273 if (!function_exists('xml_parser_create')) {
274 Logger::error('Xml::toArray: parser function missing');
280 libxml_use_internal_errors(true);
281 libxml_clear_errors();
284 $parser = @xml_parser_create_ns("UTF-8", ':');
286 $parser = @xml_parser_create();
290 Logger::warning('Xml::toArray: xml_parser_create: no resource');
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);
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);
306 libxml_clear_errors();
313 $current = &$xml_array; // Reference
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) {
319 $type = $data['type'];
320 $level = $data['level'];
321 $attributes = isset($data['attributes']) ? $data['attributes'] : null;
322 $value = isset($data['value']) ? $data['value'] : null;
325 $attributes_data = [];
328 if ($priority == 'tag') {
331 $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
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;
341 $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
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;
352 $tag = strtolower($tag);
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;
361 $repeated_tag_index[$tag . '_' . $level] = 1;
363 $current = &$current[$tag];
364 } else { // There was another element with the same tag name
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;
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']);
378 $last_item_index = $repeated_tag_index[$tag . '_' . $level]-1;
379 $current = &$current[$tag][$last_item_index];
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;
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...
392 // ...push the new element into that array.
393 $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
395 if ($priority == 'tag' and $get_attributes and $attributes_data) {
396 $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
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 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
405 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
406 unset($current[$tag.'_attr']);
409 if ($attributes_data) {
410 $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
413 $repeated_tag_index[$tag . '_' . $level]++; // 0 and 1 indexes are already taken
416 } elseif ($type == 'close') { // End of tag '</tag>'
417 $current = &$parent[$level-1];
425 * Delete a node in a XML object
427 * @param DOMDocument $doc XML document
428 * @param string $node Node name
431 public static function deleteNode(DOMDocument $doc, string $node)
433 $xpath = new DOMXPath($doc);
434 $list = $xpath->query('//' . $node);
435 foreach ($list as $child) {
436 $child->parentNode->removeChild($child);
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
447 public static function parseString(string $s, bool $suppress_log = false)
449 libxml_use_internal_errors(true);
451 $x = @simplexml_load_string($s);
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]);
458 Logger::debug('Erroring XML string', ['xml' => $s]);
460 libxml_clear_errors();
466 * Gets first node value
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
473 public static function getFirstNodeValue(DOMXPath $xpath, string $element, DOMNode $context = null)
475 $result = @$xpath->evaluate($element, $context);
476 if (!is_object($result)) {
480 $first_item = $result->item(0);
481 if (!is_object($first_item)) {
485 return $first_item->nodeValue;
489 * Gets first attributes
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
496 public static function getFirstAttributes(DOMXPath $xpath, string $element, DOMNode $context = null)
498 $result = @$xpath->query($element, $context);
499 if (!is_object($result)) {
503 $first_item = $result->item(0);
504 if (!is_object($first_item)) {
508 return $first_item->attributes;
512 * Gets first node's value
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
519 public static function getFirstValue(DOMXPath $xpath, string $element, DOMNode $context = null): string
521 $result = @$xpath->query($element, $context);
522 if (!is_object($result)) {
526 $first_item = $result->item(0);
527 if (!is_object($first_item)) {
531 return $first_item->nodeValue;
535 * escape text ($str) for XML transport
538 * @return string Escaped text.
539 * @todo Move this generic method to Util\Strings and also rewrite all other occurrences
541 public static function escape(string $str): string
543 return trim(htmlspecialchars($str, ENT_QUOTES, 'UTF-8'));
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
553 public static function unescape(string $s): string
555 return htmlspecialchars_decode($s, ENT_QUOTES);
559 * Apply escape() to all values of array $val, recursively
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
565 public static function arrayEscape($val)
568 return $val ? 'true' : 'false';
569 } elseif (is_array($val)) {
570 return array_map('XML::arrayEscape', $val);
573 return self::escape((string) $val);