3 * @copyright Copyright (C) 2010-2022, 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 $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.
47 public static function fromArray(array $array, &$xml, bool $remove_header = false, array $namespaces = [], bool $root = true): string
50 foreach ($array as $key => $value) {
51 foreach ($namespaces as $nskey => $nsvalue) {
52 $key .= ' xmlns' . ($nskey == '' ? '' : ':') . $nskey . '="' . $nsvalue . '"';
55 if (is_array($value)) {
56 $root = new SimpleXMLElement('<' . $key . '/>');
57 self::fromArray($value, $root, $remove_header, $namespaces, false);
59 $root = new SimpleXMLElement('<' . $key . '>' . self::escape($value ?? '') . '</' . $key . '>');
62 $dom = dom_import_simplexml($root)->ownerDocument;
63 $dom->formatOutput = true;
66 $xml_text = $dom->saveXML();
69 $xml_text = trim(substr($xml_text, 21));
77 foreach ($array as $key => $value) {
78 if (!isset($element) && isset($xml)) {
82 if (is_integer($key)) {
83 if (isset($element)) {
84 if (is_scalar($value)) {
87 /// @todo: handle nested array values
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[''];
102 // Remove undefined namespaces from the key
103 if ((count($element_parts) > 1) && is_null($namespace)) {
104 $key = $element_parts[1];
107 if (substr($key, 0, 11) == '@attributes') {
108 if (!isset($element) || !is_array($value)) {
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]];
120 $element->addAttribute($attr_key, $attr_value, $namespace);
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);
137 * Copies an XML object
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
144 public static function copy(&$source, &$target, $elementname)
146 if (count($source->children()) == 0) {
147 $target->addChild($elementname, self::escape($source));
149 $child = $target->addChild($elementname);
150 foreach ($source->children() as $childfield => $childentry) {
151 self::copy($childentry, $child, $childfield);
157 * Create an XML element
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
164 * @return \DOMElement XML element object
166 public static function createElement(DOMDocument $doc, string $element, string $value = '', array $attributes = []): DOMElement
168 $element = $doc->createElement($element, self::escape($value));
170 foreach ($attributes as $key => $value) {
171 $attribute = $doc->createAttribute($key);
172 $attribute->value = self::escape($value ?? '');
173 $element->appendChild($attribute);
179 * Create an XML and append it to the parent object
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
188 public static function addElement(DOMDocument $doc, DOMElement &$parent, string $element, string $value = null, array $attributes = [])
190 $element = self::createElement($doc, $element, $value ?? '', $attributes);
191 $parent->appendChild($element);
195 * Convert an XML document to a normalised, case-corrected array used by webfinger
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
201 * @return array | string The array from the xml element or the string
203 public static function elementToArray($xml_element, int &$recursion_depth = 0)
205 // If we're getting too deep, bail out
206 if ($recursion_depth > 512) {
210 $xml_element_copy = '';
211 if (!is_string($xml_element)
212 && !is_array($xml_element)
213 && (get_class($xml_element) == 'SimpleXMLElement')
215 $xml_element_copy = $xml_element;
216 $xml_element = get_object_vars($xml_element);
219 if (is_array($xml_element)) {
221 if (count($xml_element) <= 0) {
222 return trim(strval($xml_element_copy));
225 foreach ($xml_element as $key => $value) {
227 $result_array[strtolower($key)] = self::elementToArray($value, $recursion_depth);
231 if ($recursion_depth == 0) {
232 $temp_array = $result_array;
234 strtolower($xml_element_copy->getName()) => $temp_array,
238 return $result_array;
240 return trim(strval($xml_element));
245 * Convert the given XML text to an array in the XML structure.
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...)
252 * Examples: $array = Xml::toArray(file_get_contents('feed.xml'));
253 * $array = Xml::toArray(file_get_contents('feed.xml', true, 1, 'attribute'));
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.
263 * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
266 public static function toArray(string $contents, bool $namespaces = true, int $get_attributes = 1, string $priority = 'attribute'): array
272 if (!function_exists('xml_parser_create')) {
273 Logger::error('Xml::toArray: parser function missing');
279 libxml_use_internal_errors(true);
280 libxml_clear_errors();
283 $parser = @xml_parser_create_ns("UTF-8", ':');
285 $parser = @xml_parser_create();
289 Logger::warning('Xml::toArray: xml_parser_create: no resource');
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);
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);
305 libxml_clear_errors();
312 $current = &$xml_array; // Reference
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) {
318 $type = $data['type'];
319 $level = $data['level'];
320 $attributes = isset($data['attributes']) ? $data['attributes'] : null;
321 $value = isset($data['value']) ? $data['value'] : null;
324 $attributes_data = [];
327 if ($priority == 'tag') {
330 $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
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;
340 $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
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;
351 $tag = strtolower($tag);
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;
360 $repeated_tag_index[$tag . '_' . $level] = 1;
362 $current = &$current[$tag];
363 } else { // There was another element with the same tag name
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;
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']);
377 $last_item_index = $repeated_tag_index[$tag . '_' . $level]-1;
378 $current = &$current[$tag][$last_item_index];
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;
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...
391 // ...push the new element into that array.
392 $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
394 if ($priority == 'tag' and $get_attributes and $attributes_data) {
395 $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
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
404 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
405 unset($current[$tag.'_attr']);
408 if ($attributes_data) {
409 $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
412 $repeated_tag_index[$tag . '_' . $level]++; // 0 and 1 indexes are already taken
415 } elseif ($type == 'close') { // End of tag '</tag>'
416 $current = &$parent[$level-1];
424 * Delete a node in a XML object
426 * @param DOMDocument $doc XML document
427 * @param string $node Node name
430 public static function deleteNode(DOMDocument $doc, string $node)
432 $xpath = new DOMXPath($doc);
433 $list = $xpath->query('//' . $node);
434 foreach ($list as $child) {
435 $child->parentNode->removeChild($child);
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
446 public static function parseString(string $s, bool $suppress_log = false)
448 libxml_use_internal_errors(true);
450 $x = @simplexml_load_string($s);
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]);
457 Logger::debug('Erroring XML string', ['xml' => $s]);
459 libxml_clear_errors();
465 * Gets first node value
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
472 public static function getFirstNodeValue(DOMXPath $xpath, string $element, DOMNode $context = null)
474 $result = @$xpath->evaluate($element, $context);
475 if (!is_object($result)) {
479 $first_item = $result->item(0);
480 if (!is_object($first_item)) {
484 return $first_item->nodeValue;
488 * Gets first attributes
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
495 public static function getFirstAttributes(DOMXPath $xpath, string $element, DOMNode $context = null)
497 $result = @$xpath->query($element, $context);
498 if (!is_object($result)) {
502 $first_item = $result->item(0);
503 if (!is_object($first_item)) {
507 return $first_item->attributes;
511 * Gets first node's value
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
518 public static function getFirstValue(DOMXPath $xpath, string $element, DOMNode $context = null): string
520 $result = @$xpath->query($element, $context);
521 if (!is_object($result)) {
525 $first_item = $result->item(0);
526 if (!is_object($first_item)) {
530 return $first_item->nodeValue;
534 * escape text ($str) for XML transport
537 * @return string Escaped text.
538 * @todo Move this generic method to Util\Strings and also rewrite all other findingd
540 public static function escape(string $str): string
542 return trim(htmlspecialchars($str, ENT_QUOTES, 'UTF-8'));
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
552 public static function unescape(string $s): string
554 return htmlspecialchars_decode($s, ENT_QUOTES);
558 * Apply escape() to all values of array $val, recursively
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
564 public static function arrayEscape($val)
567 return $val ? 'true' : 'false';
568 } elseif (is_array($val)) {
569 return array_map('XML::arrayEscape', $val);
572 return self::escape((string) $val);