Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

414 lines
13KB

  1. <?php
  2. /**
  3. * @file include/xml.php
  4. */
  5. /**
  6. * @brief This class contain methods to work with XML data
  7. *
  8. */
  9. class xml {
  10. /**
  11. * @brief Creates an XML structure out of a given array
  12. *
  13. * @param array $array The array of the XML structure that will be generated
  14. * @param object $xml The createdXML will be returned by reference
  15. * @param bool $remove_header Should the XML header be removed or not?
  16. * @param array $namespaces List of namespaces
  17. * @param bool $root - interally used parameter. Mustn't be used from outside.
  18. *
  19. * @return string The created XML
  20. */
  21. public static function from_array($array, &$xml, $remove_header = false, $namespaces = array(), $root = true) {
  22. if ($root) {
  23. foreach ($array as $key => $value) {
  24. foreach ($namespaces AS $nskey => $nsvalue) {
  25. $key .= " xmlns".($nskey == "" ? "":":").$nskey.'="'.$nsvalue.'"';
  26. }
  27. if (is_array($value)) {
  28. $root = new SimpleXMLElement("<".$key."/>");
  29. self::from_array($value, $root, $remove_header, $namespaces, false);
  30. } else {
  31. $root = new SimpleXMLElement("<".$key.">".xmlify($value)."</".$key.">");
  32. }
  33. $dom = dom_import_simplexml($root)->ownerDocument;
  34. $dom->formatOutput = true;
  35. $xml = $dom;
  36. $xml_text = $dom->saveXML();
  37. if ($remove_header) {
  38. $xml_text = trim(substr($xml_text, 21));
  39. }
  40. return $xml_text;
  41. }
  42. }
  43. foreach($array as $key => $value) {
  44. if (!isset($element) && isset($xml)) {
  45. $element = $xml;
  46. }
  47. if (is_integer($key)) {
  48. if (isset($element)) {
  49. if (is_scalar($value)) {
  50. $element[0] = $value;
  51. } else {
  52. /// @todo: handle nested array values
  53. }
  54. }
  55. continue;
  56. }
  57. $element_parts = explode(":", $key);
  58. if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) {
  59. $namespace = $namespaces[$element_parts[0]];
  60. } elseif (isset($namespaces[""])) {
  61. $namespace = $namespaces[""];
  62. } else {
  63. $namespace = NULL;
  64. }
  65. // Remove undefined namespaces from the key
  66. if ((count($element_parts) > 1) && is_null($namespace)) {
  67. $key = $element_parts[1];
  68. }
  69. if (substr($key, 0, 11) == "@attributes") {
  70. if (!isset($element) || !is_array($value)) {
  71. continue;
  72. }
  73. foreach ($value as $attr_key => $attr_value) {
  74. $element_parts = explode(":", $attr_key);
  75. if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) {
  76. $namespace = $namespaces[$element_parts[0]];
  77. } else {
  78. $namespace = NULL;
  79. }
  80. $element->addAttribute($attr_key, $attr_value, $namespace);
  81. }
  82. continue;
  83. }
  84. if (!is_array($value)) {
  85. $element = $xml->addChild($key, xmlify($value), $namespace);
  86. } elseif (is_array($value)) {
  87. $element = $xml->addChild($key, NULL, $namespace);
  88. self::from_array($value, $element, $remove_header, $namespaces, false);
  89. }
  90. }
  91. }
  92. /**
  93. * @brief Copies an XML object
  94. *
  95. * @param object $source The XML source
  96. * @param object $target The XML target
  97. * @param string $elementname Name of the XML element of the target
  98. */
  99. public static function copy(&$source, &$target, $elementname) {
  100. if (count($source->children()) == 0)
  101. $target->addChild($elementname, xmlify($source));
  102. else {
  103. $child = $target->addChild($elementname);
  104. foreach ($source->children() AS $childfield => $childentry) {
  105. self::copy($childentry, $child, $childfield);
  106. }
  107. }
  108. }
  109. /**
  110. * @brief Create an XML element
  111. *
  112. * @param object $doc XML root
  113. * @param string $element XML element name
  114. * @param string $value XML value
  115. * @param array $attributes array containing the attributes
  116. *
  117. * @return object XML element object
  118. */
  119. public static function create_element($doc, $element, $value = "", $attributes = array()) {
  120. $element = $doc->createElement($element, xmlify($value));
  121. foreach ($attributes AS $key => $value) {
  122. $attribute = $doc->createAttribute($key);
  123. $attribute->value = xmlify($value);
  124. $element->appendChild($attribute);
  125. }
  126. return $element;
  127. }
  128. /**
  129. * @brief Create an XML and append it to the parent object
  130. *
  131. * @param object $doc XML root
  132. * @param object $parent parent object
  133. * @param string $element XML element name
  134. * @param string $value XML value
  135. * @param array $attributes array containing the attributes
  136. */
  137. public static function add_element($doc, $parent, $element, $value = "", $attributes = array()) {
  138. $element = self::create_element($doc, $element, $value, $attributes);
  139. $parent->appendChild($element);
  140. }
  141. /**
  142. * @brief Convert an XML document to a normalised, case-corrected array
  143. * used by webfinger
  144. *
  145. * @param object $xml_element The XML document
  146. * @param integer $recursion_depth recursion counter for internal use - default 0
  147. * internal use, recursion counter
  148. *
  149. * @return array | sring The array from the xml element or the string
  150. */
  151. public static function element_to_array($xml_element, &$recursion_depth=0) {
  152. // If we're getting too deep, bail out
  153. if ($recursion_depth > 512) {
  154. return(null);
  155. }
  156. if (!is_string($xml_element)
  157. && !is_array($xml_element)
  158. && (get_class($xml_element) == 'SimpleXMLElement')) {
  159. $xml_element_copy = $xml_element;
  160. $xml_element = get_object_vars($xml_element);
  161. }
  162. if (is_array($xml_element)) {
  163. $result_array = array();
  164. if (count($xml_element) <= 0) {
  165. return (trim(strval($xml_element_copy)));
  166. }
  167. foreach ($xml_element as $key => $value) {
  168. $recursion_depth++;
  169. $result_array[strtolower($key)] =
  170. self::element_to_array($value, $recursion_depth);
  171. $recursion_depth--;
  172. }
  173. if ($recursion_depth == 0) {
  174. $temp_array = $result_array;
  175. $result_array = array(
  176. strtolower($xml_element_copy->getName()) => $temp_array,
  177. );
  178. }
  179. return ($result_array);
  180. } else {
  181. return (trim(strval($xml_element)));
  182. }
  183. }
  184. /**
  185. * @brief Convert the given XML text to an array in the XML structure.
  186. *
  187. * xml::to_array() will convert the given XML text to an array in the XML structure.
  188. * Link: http://www.bin-co.com/php/scripts/xml2array/
  189. * Portions significantly re-written by mike@macgirvin.com for Friendica
  190. * (namespaces, lowercase tags, get_attribute default changed, more...)
  191. *
  192. * Examples: $array = xml::to_array(file_get_contents('feed.xml'));
  193. * $array = xml::to_array(file_get_contents('feed.xml', true, 1, 'attribute'));
  194. *
  195. * @param object $contents The XML text
  196. * @param boolean $namespaces True or false include namespace information
  197. * in the returned array as array elements.
  198. * @param integer $get_attributes 1 or 0. If this is 1 the function will get the attributes as well as the tag values -
  199. * this results in a different array structure in the return value.
  200. * @param string $priority Can be 'tag' or 'attribute'. This will change the way the resulting
  201. * array sturcture. For 'tag', the tags are given more importance.
  202. *
  203. * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
  204. */
  205. public static function to_array($contents, $namespaces = true, $get_attributes = 1, $priority = 'attribute') {
  206. if (!$contents) {
  207. return array();
  208. }
  209. if (!function_exists('xml_parser_create')) {
  210. logger('xml::to_array: parser function missing');
  211. return array();
  212. }
  213. libxml_use_internal_errors(true);
  214. libxml_clear_errors();
  215. if ($namespaces) {
  216. $parser = @xml_parser_create_ns("UTF-8",':');
  217. } else {
  218. $parser = @xml_parser_create();
  219. }
  220. if (! $parser) {
  221. logger('xml::to_array: xml_parser_create: no resource');
  222. return array();
  223. }
  224. xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
  225. // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
  226. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  227. xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  228. @xml_parse_into_struct($parser, trim($contents), $xml_values);
  229. @xml_parser_free($parser);
  230. if (! $xml_values) {
  231. logger('xml::to_array: libxml: parse error: ' . $contents, LOGGER_DATA);
  232. foreach (libxml_get_errors() as $err) {
  233. logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
  234. }
  235. libxml_clear_errors();
  236. return;
  237. }
  238. //Initializations
  239. $xml_array = array();
  240. $parents = array();
  241. $opened_tags = array();
  242. $arr = array();
  243. $current = &$xml_array; // Reference
  244. // Go through the tags.
  245. $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
  246. foreach ($xml_values as $data) {
  247. unset($attributes, $value); // Remove existing values, or there will be trouble
  248. // This command will extract these variables into the foreach scope
  249. // tag(string), type(string), level(int), attributes(array).
  250. extract($data); // We could use the array by itself, but this cooler.
  251. $result = array();
  252. $attributes_data = array();
  253. if (isset($value)) {
  254. if ($priority == 'tag') {
  255. $result = $value;
  256. } else {
  257. $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
  258. }
  259. }
  260. //Set the attributes too.
  261. if (isset($attributes) and $get_attributes) {
  262. foreach ($attributes as $attr => $val) {
  263. if($priority == 'tag') {
  264. $attributes_data[$attr] = $val;
  265. } else {
  266. $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
  267. }
  268. }
  269. }
  270. // See tag status and do the needed.
  271. if ($namespaces && strpos($tag, ':')) {
  272. $namespc = substr($tag, 0, strrpos($tag, ':'));
  273. $tag = strtolower(substr($tag, strlen($namespc)+1));
  274. $result['@namespace'] = $namespc;
  275. }
  276. $tag = strtolower($tag);
  277. if ($type == "open") { // The starting of the tag '<tag>'
  278. $parent[$level-1] = &$current;
  279. if (!is_array($current) || (!in_array($tag, array_keys($current)))) { // Insert New tag
  280. $current[$tag] = $result;
  281. if ($attributes_data) {
  282. $current[$tag. '_attr'] = $attributes_data;
  283. }
  284. $repeated_tag_index[$tag.'_'.$level] = 1;
  285. $current = &$current[$tag];
  286. } else { // There was another element with the same tag name
  287. if (isset($current[$tag][0])) { // If there is a 0th element it is already an array
  288. $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
  289. $repeated_tag_index[$tag.'_'.$level]++;
  290. } else { // This section will make the value an array if multiple tags with the same name appear together
  291. $current[$tag] = array($current[$tag], $result); // This will combine the existing item and the new item together to make an array
  292. $repeated_tag_index[$tag.'_'.$level] = 2;
  293. if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
  294. $current[$tag]['0_attr'] = $current[$tag.'_attr'];
  295. unset($current[$tag.'_attr']);
  296. }
  297. }
  298. $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
  299. $current = &$current[$tag][$last_item_index];
  300. }
  301. } elseif ($type == "complete") { // Tags that ends in 1 line '<tag />'
  302. //See if the key is already taken.
  303. if (!isset($current[$tag])) { //New Key
  304. $current[$tag] = $result;
  305. $repeated_tag_index[$tag.'_'.$level] = 1;
  306. if ($priority == 'tag' and $attributes_data) {
  307. $current[$tag. '_attr'] = $attributes_data;
  308. }
  309. } else { // If taken, put all things inside a list(array)
  310. if (isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
  311. // ...push the new element into that array.
  312. $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
  313. if ($priority == 'tag' and $get_attributes and $attributes_data) {
  314. $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
  315. }
  316. $repeated_tag_index[$tag.'_'.$level]++;
  317. } else { // If it is not an array...
  318. $current[$tag] = array($current[$tag], $result); //...Make it an array using using the existing value and the new value
  319. $repeated_tag_index[$tag.'_'.$level] = 1;
  320. if ($priority == 'tag' and $get_attributes) {
  321. if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
  322. $current[$tag]['0_attr'] = $current[$tag.'_attr'];
  323. unset($current[$tag.'_attr']);
  324. }
  325. if ($attributes_data) {
  326. $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
  327. }
  328. }
  329. $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
  330. }
  331. }
  332. } elseif ($type == 'close') { // End of tag '</tag>'
  333. $current = &$parent[$level-1];
  334. }
  335. }
  336. return($xml_array);
  337. }
  338. /**
  339. * @brief Delete a node in a XML object
  340. *
  341. * @param object $doc XML document
  342. * @param string $node Node name
  343. */
  344. public static function deleteNode(&$doc, $node) {
  345. $xpath = new DomXPath($doc);
  346. $list = $xpath->query("//".$node);
  347. foreach ($list as $child) {
  348. $child->parentNode->removeChild($child);
  349. }
  350. }
  351. }