ImportXml.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. <?php
  2. /**
  3. * XML import plugin for phpMyAdmin
  4. *
  5. * @todo Improve efficiency
  6. */
  7. declare(strict_types=1);
  8. namespace PhpMyAdmin\Plugins\Import;
  9. use PhpMyAdmin\File;
  10. use PhpMyAdmin\Import;
  11. use PhpMyAdmin\Message;
  12. use PhpMyAdmin\Plugins\ImportPlugin;
  13. use PhpMyAdmin\Properties\Plugins\ImportPluginProperties;
  14. use PhpMyAdmin\Util;
  15. use SimpleXMLElement;
  16. use const LIBXML_COMPACT;
  17. use function count;
  18. use function in_array;
  19. use function libxml_disable_entity_loader;
  20. use function simplexml_load_string;
  21. use function str_replace;
  22. use function strcmp;
  23. use function strlen;
  24. use const PHP_VERSION_ID;
  25. /**
  26. * Handles the import for the XML format
  27. */
  28. class ImportXml extends ImportPlugin
  29. {
  30. public function __construct()
  31. {
  32. parent::__construct();
  33. $this->setProperties();
  34. }
  35. /**
  36. * Sets the import plugin properties.
  37. * Called in the constructor.
  38. *
  39. * @return void
  40. */
  41. protected function setProperties()
  42. {
  43. $importPluginProperties = new ImportPluginProperties();
  44. $importPluginProperties->setText(__('XML'));
  45. $importPluginProperties->setExtension('xml');
  46. $importPluginProperties->setMimeType('text/xml');
  47. $importPluginProperties->setOptions([]);
  48. $importPluginProperties->setOptionsText(__('Options'));
  49. $this->properties = $importPluginProperties;
  50. }
  51. /**
  52. * Handles the whole import logic
  53. *
  54. * @param array $sql_data 2-element array with sql data
  55. *
  56. * @return void
  57. */
  58. public function doImport(?File $importHandle = null, array &$sql_data = [])
  59. {
  60. global $error, $timeout_passed, $finished, $db;
  61. $i = 0;
  62. $len = 0;
  63. $buffer = '';
  64. /**
  65. * Read in the file via Import::getNextChunk so that
  66. * it can process compressed files
  67. */
  68. while (! ($finished && $i >= $len) && ! $error && ! $timeout_passed) {
  69. $data = $this->import->getNextChunk($importHandle);
  70. if ($data === false) {
  71. /* subtract data we didn't handle yet and stop processing */
  72. $GLOBALS['offset'] -= strlen($buffer);
  73. break;
  74. }
  75. if ($data === true) {
  76. continue;
  77. }
  78. /* Append new data to buffer */
  79. $buffer .= $data;
  80. }
  81. /**
  82. * Disable loading of external XML entities for PHP versions below 8.0.
  83. */
  84. if (PHP_VERSION_ID < 80000) {
  85. // phpcs:ignore Generic.PHP.DeprecatedFunctions.Deprecated
  86. libxml_disable_entity_loader();
  87. }
  88. /**
  89. * Load the XML string
  90. *
  91. * The option LIBXML_COMPACT is specified because it can
  92. * result in increased performance without the need to
  93. * alter the code in any way. It's basically a freebee.
  94. */
  95. $xml = @simplexml_load_string($buffer, 'SimpleXMLElement', LIBXML_COMPACT);
  96. unset($buffer);
  97. /**
  98. * The XML was malformed
  99. */
  100. if ($xml === false) {
  101. echo Message::error(
  102. __(
  103. 'The XML file specified was either malformed or incomplete.'
  104. . ' Please correct the issue and try again.'
  105. )
  106. )->getDisplay();
  107. unset($xml);
  108. $GLOBALS['finished'] = false;
  109. return;
  110. }
  111. /**
  112. * Table accumulator
  113. */
  114. $tables = [];
  115. /**
  116. * Row accumulator
  117. */
  118. $rows = [];
  119. /**
  120. * Temp arrays
  121. */
  122. $tempRow = [];
  123. $tempCells = [];
  124. /**
  125. * CREATE code included (by default: no)
  126. */
  127. $struct_present = false;
  128. /**
  129. * Analyze the data in each table
  130. */
  131. $namespaces = $xml->getNamespaces(true);
  132. /**
  133. * Get the database name, collation and charset
  134. */
  135. $db_attr = $xml->children($namespaces['pma'] ?? null)
  136. ->{'structure_schemas'}->{'database'};
  137. if ($db_attr instanceof SimpleXMLElement) {
  138. $db_attr = $db_attr->attributes();
  139. $db_name = (string) $db_attr['name'];
  140. $collation = (string) $db_attr['collation'];
  141. $charset = (string) $db_attr['charset'];
  142. } else {
  143. /**
  144. * If the structure section is not present
  145. * get the database name from the data section
  146. */
  147. $db_attr = $xml->children()
  148. ->attributes();
  149. $db_name = (string) $db_attr['name'];
  150. $collation = null;
  151. $charset = null;
  152. }
  153. /**
  154. * The XML was malformed
  155. */
  156. if ($db_name === null) {
  157. echo Message::error(
  158. __(
  159. 'The XML file specified was either malformed or incomplete.'
  160. . ' Please correct the issue and try again.'
  161. )
  162. )->getDisplay();
  163. unset($xml);
  164. $GLOBALS['finished'] = false;
  165. return;
  166. }
  167. /**
  168. * Retrieve the structure information
  169. */
  170. if (isset($namespaces['pma'])) {
  171. /**
  172. * Get structures for all tables
  173. *
  174. * @var SimpleXMLElement $struct
  175. */
  176. $struct = $xml->children($namespaces['pma']);
  177. $create = [];
  178. /** @var SimpleXMLElement $val1 */
  179. foreach ($struct as $val1) {
  180. /** @var SimpleXMLElement $val2 */
  181. foreach ($val1 as $val2) {
  182. // Need to select the correct database for the creation of
  183. // tables, views, triggers, etc.
  184. /**
  185. * @todo Generating a USE here blocks importing of a table
  186. * into another database.
  187. */
  188. $attrs = $val2->attributes();
  189. $create[] = 'USE '
  190. . Util::backquote(
  191. $attrs['name']
  192. );
  193. foreach ($val2 as $val3) {
  194. /**
  195. * Remove the extra cosmetic spacing
  196. */
  197. $val3 = str_replace(' ', '', (string) $val3);
  198. $create[] = $val3;
  199. }
  200. }
  201. }
  202. $struct_present = true;
  203. }
  204. /**
  205. * Move down the XML tree to the actual data
  206. */
  207. $xml = $xml->children()
  208. ->children();
  209. $data_present = false;
  210. /**
  211. * Only attempt to analyze/collect data if there is data present
  212. */
  213. if ($xml && $xml->children()->count()) {
  214. $data_present = true;
  215. /**
  216. * Process all database content
  217. */
  218. foreach ($xml as $v1) {
  219. $tbl_attr = $v1->attributes();
  220. $isInTables = false;
  221. $num_tables = count($tables);
  222. for ($i = 0; $i < $num_tables; ++$i) {
  223. if (! strcmp($tables[$i][Import::TBL_NAME], (string) $tbl_attr['name'])) {
  224. $isInTables = true;
  225. break;
  226. }
  227. }
  228. if (! $isInTables) {
  229. $tables[] = [(string) $tbl_attr['name']];
  230. }
  231. foreach ($v1 as $v2) {
  232. $row_attr = $v2->attributes();
  233. if (! in_array((string) $row_attr['name'], $tempRow)) {
  234. $tempRow[] = (string) $row_attr['name'];
  235. }
  236. $tempCells[] = (string) $v2;
  237. }
  238. $rows[] = [
  239. (string) $tbl_attr['name'],
  240. $tempRow,
  241. $tempCells,
  242. ];
  243. $tempRow = [];
  244. $tempCells = [];
  245. }
  246. unset($tempRow, $tempCells, $xml);
  247. /**
  248. * Bring accumulated rows into the corresponding table
  249. */
  250. $num_tables = count($tables);
  251. for ($i = 0; $i < $num_tables; ++$i) {
  252. $num_rows = count($rows);
  253. for ($j = 0; $j < $num_rows; ++$j) {
  254. if (strcmp($tables[$i][Import::TBL_NAME], $rows[$j][Import::TBL_NAME])) {
  255. continue;
  256. }
  257. if (! isset($tables[$i][Import::COL_NAMES])) {
  258. $tables[$i][] = $rows[$j][Import::COL_NAMES];
  259. }
  260. $tables[$i][Import::ROWS][] = $rows[$j][Import::ROWS];
  261. }
  262. }
  263. unset($rows);
  264. if (! $struct_present) {
  265. $analyses = [];
  266. $len = count($tables);
  267. for ($i = 0; $i < $len; ++$i) {
  268. $analyses[] = $this->import->analyzeTable($tables[$i]);
  269. }
  270. }
  271. }
  272. unset($xml, $tempCells, $rows);
  273. /**
  274. * Only build SQL from data if there is data present
  275. */
  276. if ($data_present) {
  277. /**
  278. * Set values to NULL if they were not present
  279. * to maintain Import::buildSql() call integrity
  280. */
  281. if (! isset($analyses)) {
  282. $analyses = null;
  283. if (! $struct_present) {
  284. $create = null;
  285. }
  286. }
  287. }
  288. /**
  289. * string $db_name (no backquotes)
  290. *
  291. * array $table = array(table_name, array() column_names, array()() rows)
  292. * array $tables = array of "$table"s
  293. *
  294. * array $analysis = array(array() column_types, array() column_sizes)
  295. * array $analyses = array of "$analysis"s
  296. *
  297. * array $create = array of SQL strings
  298. *
  299. * array $options = an associative array of options
  300. */
  301. /* Set database name to the currently selected one, if applicable */
  302. if (strlen((string) $db)) {
  303. /* Override the database name in the XML file, if one is selected */
  304. $db_name = $db;
  305. $options = ['create_db' => false];
  306. } else {
  307. if ($db_name === null) {
  308. $db_name = 'XML_DB';
  309. }
  310. /* Set database collation/charset */
  311. $options = [
  312. 'db_collation' => $collation,
  313. 'db_charset' => $charset,
  314. ];
  315. }
  316. /* Created and execute necessary SQL statements from data */
  317. $this->import->buildSql($db_name, $tables, $analyses, $create, $options, $sql_data);
  318. unset($analyses, $tables, $create);
  319. /* Commit any possible data in buffers */
  320. $this->import->runQuery('', '', $sql_data);
  321. }
  322. }