]> git.mxchange.org Git - friendica.git/blobdiff - src/Util/XML.php
Use direct logic
[friendica.git] / src / Util / XML.php
index bfd1b8bf5966ffb919e121c7e7484e1230b6dcc6..4dd6d84ecbefea7d50a2c24e21a8b934402ddbbd 100644 (file)
@@ -4,7 +4,9 @@
  */
 namespace Friendica\Util;
 
+use Friendica\Core\Logger;
 use DOMXPath;
+use Friendica\Core\System;
 use SimpleXMLElement;
 
 /**
@@ -23,7 +25,7 @@ class XML
         *
         * @return string The created XML
         */
-       public static function fromArray($array, &$xml, $remove_header = false, $namespaces = array(), $root = true)
+       public static function fromArray($array, &$xml, $remove_header = false, $namespaces = [], $root = true)
        {
                if ($root) {
                        foreach ($array as $key => $value) {
@@ -35,7 +37,7 @@ class XML
                                        $root = new SimpleXMLElement("<".$key."/>");
                                        self::fromArray($value, $root, $remove_header, $namespaces, false);
                                } else {
-                                       $root = new SimpleXMLElement("<".$key.">".xmlify($value)."</".$key.">");
+                                       $root = new SimpleXMLElement("<".$key.">".self::escape($value)."</".$key.">");
                                }
 
                                $dom = dom_import_simplexml($root)->ownerDocument;
@@ -52,6 +54,7 @@ class XML
                        }
                }
 
+               $element = null;
                foreach ($array as $key => $value) {
                        if (!isset($element) && isset($xml)) {
                                $element = $xml;
@@ -102,7 +105,7 @@ class XML
                        }
 
                        if (!is_array($value)) {
-                               $element = $xml->addChild($key, xmlify($value), $namespace);
+                               $element = $xml->addChild($key, self::escape($value), $namespace);
                        } elseif (is_array($value)) {
                                $element = $xml->addChild($key, null, $namespace);
                                self::fromArray($value, $element, $remove_header, $namespaces, false);
@@ -121,7 +124,7 @@ class XML
        public static function copy(&$source, &$target, $elementname)
        {
                if (count($source->children()) == 0) {
-                       $target->addChild($elementname, xmlify($source));
+                       $target->addChild($elementname, self::escape($source));
                } else {
                        $child = $target->addChild($elementname);
                        foreach ($source->children() as $childfield => $childentry) {
@@ -133,20 +136,20 @@ class XML
        /**
         * @brief Create an XML element
         *
-        * @param object $doc        XML root
-        * @param string $element    XML element name
-        * @param string $value      XML value
-        * @param array  $attributes array containing the attributes
+        * @param \DOMDocument $doc        XML root
+        * @param string       $element    XML element name
+        * @param string       $value      XML value
+        * @param array        $attributes array containing the attributes
         *
-        * @return object XML element object
+        * @return \DOMElement XML element object
         */
-       public static function createElement($doc, $element, $value = "", $attributes = array())
+       public static function createElement(\DOMDocument $doc, $element, $value = "", $attributes = [])
        {
-               $element = $doc->createElement($element, xmlify($value));
+               $element = $doc->createElement($element, self::escape($value));
 
                foreach ($attributes as $key => $value) {
                        $attribute = $doc->createAttribute($key);
-                       $attribute->value = xmlify($value);
+                       $attribute->value = self::escape($value);
                        $element->appendChild($attribute);
                }
                return $element;
@@ -155,14 +158,14 @@ class XML
        /**
         * @brief Create an XML and append it to the parent object
         *
-        * @param object $doc        XML root
+        * @param \DOMDocument $doc        XML root
         * @param object $parent     parent object
         * @param string $element    XML element name
         * @param string $value      XML value
         * @param array  $attributes array containing the attributes
         * @return void
         */
-       public static function addElement($doc, $parent, $element, $value = "", $attributes = array())
+       public static function addElement(\DOMDocument $doc, $parent, $element, $value = "", $attributes = [])
        {
                $element = self::createElement($doc, $element, $value, $attributes);
                $parent->appendChild($element);
@@ -185,16 +188,17 @@ class XML
                        return(null);
                }
 
+               $xml_element_copy = '';
                if (!is_string($xml_element)
                        && !is_array($xml_element)
                        && (get_class($xml_element) == 'SimpleXMLElement')
                ) {
-                               $xml_element_copy = $xml_element;
-                               $xml_element = get_object_vars($xml_element);
+                       $xml_element_copy = $xml_element;
+                       $xml_element = get_object_vars($xml_element);
                }
 
                if (is_array($xml_element)) {
-                       $result_array = array();
+                       $result_array = [];
                        if (count($xml_element) <= 0) {
                                return (trim(strval($xml_element_copy)));
                        }
@@ -207,9 +211,9 @@ class XML
 
                        if ($recursion_depth == 0) {
                                $temp_array = $result_array;
-                               $result_array = array(
+                               $result_array = [
                                        strtolower($xml_element_copy->getName()) => $temp_array,
-                               );
+                               ];
                        }
 
                        return ($result_array);
@@ -227,27 +231,28 @@ class XML
         * (namespaces, lowercase tags, get_attribute default changed, more...)
         *
         * Examples: $array =  Xml::toArray(file_get_contents('feed.xml'));
-        *              $array =  Xml::toArray(file_get_contents('feed.xml', true, 1, 'attribute'));
+        *        $array =  Xml::toArray(file_get_contents('feed.xml', true, 1, 'attribute'));
         *
-        * @param object  $contents       The XML text
-        * @param boolean $namespaces     True or false include namespace information
-        *                                    in the returned array as array elements.
-        * @param integer $get_attributes 1 or 0. If this is 1 the function will get the attributes as well as the tag values -
-        *                                    this results in a different array structure in the return value.
-        * @param string  $priority       Can be 'tag' or 'attribute'. This will change the way the resulting
-        *                                    array sturcture. For 'tag', the tags are given more importance.
+        * @param object  $contents         The XML text
+        * @param boolean $namespaces       True or false include namespace information
+        *                                  in the returned array as array elements.
+        * @param integer $get_attributes   1 or 0. If this is 1 the function will get the attributes as well as the tag values -
+        *                                  this results in a different array structure in the return value.
+        * @param string  $priority         Can be 'tag' or 'attribute'. This will change the way the resulting
+        *                                  array sturcture. For 'tag', the tags are given more importance.
         *
         * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
+        * @throws \Exception
         */
        public static function toArray($contents, $namespaces = true, $get_attributes = 1, $priority = 'attribute')
        {
                if (!$contents) {
-                       return array();
+                       return [];
                }
 
                if (!function_exists('xml_parser_create')) {
-                       logger('Xml::toArray: parser function missing');
-                       return array();
+                       Logger::log('Xml::toArray: parser function missing');
+                       return [];
                }
 
 
@@ -261,8 +266,8 @@ class XML
                }
 
                if (! $parser) {
-                       logger('Xml::toArray: xml_parser_create: no resource');
-                       return array();
+                       Logger::log('Xml::toArray: xml_parser_create: no resource');
+                       return [];
                }
 
                xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
@@ -273,33 +278,30 @@ class XML
                @xml_parser_free($parser);
 
                if (! $xml_values) {
-                       logger('Xml::toArray: libxml: parse error: ' . $contents, LOGGER_DATA);
+                       Logger::log('Xml::toArray: libxml: parse error: ' . $contents, Logger::DATA);
                        foreach (libxml_get_errors() as $err) {
-                               logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
+                               Logger::log('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, Logger::DATA);
                        }
                        libxml_clear_errors();
                        return;
                }
 
                //Initializations
-               $xml_array = array();
-               $parents = array();
-               $opened_tags = array();
-               $arr = array();
+               $xml_array = [];
 
                $current = &$xml_array; // Reference
 
                // Go through the tags.
-               $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
+               $repeated_tag_index = []; // Multiple tags with same name will be turned into an array
                foreach ($xml_values as $data) {
-                       unset($attributes, $value); // Remove existing values, or there will be trouble
+                       $tag        = $data['tag'];
+                       $type       = $data['type'];
+                       $level      = $data['level'];
+                       $attributes = isset($data['attributes']) ? $data['attributes'] : null;
+                       $value      = isset($data['value']) ? $data['value'] : null;
 
-                       // This command will extract these variables into the foreach scope
-                       // tag(string), type(string), level(int), attributes(array).
-                       extract($data); // We could use the array by itself, but this cooler.
-
-                       $result = array();
-                       $attributes_data = array();
+                       $result = [];
+                       $attributes_data = [];
 
                        if (isset($value)) {
                                if ($priority == 'tag') {
@@ -344,7 +346,7 @@ class XML
                                                $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
                                                $repeated_tag_index[$tag.'_'.$level]++;
                                        } else { // This section will make the value an array if multiple tags with the same name appear together
-                                               $current[$tag] = array($current[$tag], $result); // This will combine the existing item and the new item together to make an array
+                                               $current[$tag] = [$current[$tag], $result]; // This will combine the existing item and the new item together to make an array
                                                $repeated_tag_index[$tag.'_'.$level] = 2;
 
                                                if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
@@ -374,7 +376,7 @@ class XML
                                                }
                                                $repeated_tag_index[$tag.'_'.$level]++;
                                        } else { // If it is not an array...
-                                               $current[$tag] = array($current[$tag], $result); //...Make it an array using using the existing value and the new value
+                                               $current[$tag] = [$current[$tag], $result]; //...Make it an array using using the existing value and the new value
                                                $repeated_tag_index[$tag.'_'.$level] = 1;
                                                if ($priority == 'tag' and $get_attributes) {
                                                        if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
@@ -401,11 +403,11 @@ class XML
        /**
         * @brief Delete a node in a XML object
         *
-        * @param object $doc  XML document
+        * @param \DOMDocument $doc  XML document
         * @param string $node Node name
         * @return void
         */
-       public static function deleteNode(&$doc, $node)
+       public static function deleteNode(\DOMDocument $doc, $node)
        {
                $xpath = new DOMXPath($doc);
                $list = $xpath->query("//".$node);
@@ -413,4 +415,90 @@ class XML
                        $child->parentNode->removeChild($child);
                }
        }
+
+       public static function parseString($s, $strict = true)
+       {
+               // the "strict" parameter is deactivated
+               libxml_use_internal_errors(true);
+
+               $x = @simplexml_load_string($s);
+               if (!$x) {
+                       Logger::error('Error(s) while parsing XML string.', ['callstack' => System::callstack()]);
+                       foreach (libxml_get_errors() as $err) {
+                               Logger::info('libxml error', ['code' => $err->code, 'position' => $err->line . ":" . $err->column, 'message' => $err->message]);
+                       }
+                       Logger::debug('Erroring XML string', ['xml' => $s]);
+                       libxml_clear_errors();
+               }
+               return $x;
+       }
+
+       public static function getFirstNodeValue(DOMXPath $xpath, $element, $context = null)
+       {
+               $result = $xpath->evaluate($element, $context);
+               if (!is_object($result)) {
+                       return '';
+               }
+
+               $first_item = $result->item(0);
+               if (!is_object($first_item)) {
+                       return '';
+               }
+
+               return $first_item->nodeValue;
+       }
+
+       public static function getFirstAttributes(DOMXPath $xpath, $element, $context = null)
+       {
+               $result = $xpath->query($element, $context);
+               if (!is_object($result)) {
+                       return false;
+               }
+
+               $first_item = $result->item(0);
+               if (!is_object($first_item)) {
+                       return false;
+               }
+
+               return $first_item->attributes;
+       }
+
+       /**
+        * escape text ($str) for XML transport
+        * @param string $str
+        * @return string Escaped text.
+        */
+       public static function escape($str)
+       {
+               $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
+               $buffer = trim($buffer);
+
+               return $buffer;
+       }
+
+       /**
+        * undo an escape
+        * @param string $s xml escaped text
+        * @return string unescaped text
+        */
+       public static function unescape($s)
+       {
+               $ret = htmlspecialchars_decode($s, ENT_QUOTES);
+               return $ret;
+       }
+
+       /**
+        * apply escape() to all values of array $val, recursively
+        * @param array $val
+        * @return array
+        */
+       public static function arrayEscape($val)
+       {
+               if (is_bool($val)) {
+                       return $val?"true":"false";
+               } elseif (is_array($val)) {
+                       return array_map('XML::arrayEscape', $val);
+               }
+               return self::escape((string) $val);
+       }
 }