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.

376 lines
12 KiB

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