ImportMediawiki.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * MediaWiki import plugin for phpMyAdmin
  5. *
  6. * @package PhpMyAdmin-Import
  7. * @subpackage MediaWiki
  8. */
  9. namespace PhpMyAdmin\Plugins\Import;
  10. use PhpMyAdmin\Import;
  11. use PhpMyAdmin\Message;
  12. use PhpMyAdmin\Plugins\ImportPlugin;
  13. use PhpMyAdmin\Properties\Plugins\ImportPluginProperties;
  14. /**
  15. * Handles the import for the MediaWiki format
  16. *
  17. * @package PhpMyAdmin-Import
  18. * @subpackage MediaWiki
  19. */
  20. class ImportMediawiki extends ImportPlugin
  21. {
  22. /**
  23. * Whether to analyze tables
  24. *
  25. * @var bool
  26. */
  27. private $_analyze;
  28. /**
  29. * Constructor
  30. */
  31. public function __construct()
  32. {
  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. $this->_setAnalyze(false);
  44. if ($GLOBALS['plugin_param'] !== 'table') {
  45. $this->_setAnalyze(true);
  46. }
  47. $importPluginProperties = new ImportPluginProperties();
  48. $importPluginProperties->setText(__('MediaWiki Table'));
  49. $importPluginProperties->setExtension('txt');
  50. $importPluginProperties->setMimeType('text/plain');
  51. $importPluginProperties->setOptions(array());
  52. $importPluginProperties->setOptionsText(__('Options'));
  53. $this->properties = $importPluginProperties;
  54. }
  55. /**
  56. * Handles the whole import logic
  57. *
  58. * @param array &$sql_data 2-element array with sql data
  59. *
  60. * @return void
  61. */
  62. public function doImport(array &$sql_data = array())
  63. {
  64. global $error, $timeout_passed, $finished;
  65. // Defaults for parser
  66. // The buffer that will be used to store chunks read from the imported file
  67. $buffer = '';
  68. // Used as storage for the last part of the current chunk data
  69. // Will be appended to the first line of the next chunk, if there is one
  70. $last_chunk_line = '';
  71. // Remembers whether the current buffer line is part of a comment
  72. $inside_comment = false;
  73. // Remembers whether the current buffer line is part of a data comment
  74. $inside_data_comment = false;
  75. // Remembers whether the current buffer line is part of a structure comment
  76. $inside_structure_comment = false;
  77. // MediaWiki only accepts "\n" as row terminator
  78. $mediawiki_new_line = "\n";
  79. // Initialize the name of the current table
  80. $cur_table_name = "";
  81. while (!$finished && !$error && !$timeout_passed) {
  82. $data = Import::getNextChunk();
  83. if ($data === false) {
  84. // Subtract data we didn't handle yet and stop processing
  85. $GLOBALS['offset'] -= mb_strlen($buffer);
  86. break;
  87. } elseif ($data === true) {
  88. // Handle rest of buffer
  89. } else {
  90. // Append new data to buffer
  91. $buffer = $data;
  92. unset($data);
  93. // Don't parse string if we're not at the end
  94. // and don't have a new line inside
  95. if (mb_strpos($buffer, $mediawiki_new_line) === false) {
  96. continue;
  97. }
  98. }
  99. // Because of reading chunk by chunk, the first line from the buffer
  100. // contains only a portion of an actual line from the imported file.
  101. // Therefore, we have to append it to the last line from the previous
  102. // chunk. If we are at the first chunk, $last_chunk_line should be empty.
  103. $buffer = $last_chunk_line . $buffer;
  104. // Process the buffer line by line
  105. $buffer_lines = explode($mediawiki_new_line, $buffer);
  106. $full_buffer_lines_count = count($buffer_lines);
  107. // If the reading is not finalised, the final line of the current chunk
  108. // will not be complete
  109. if (! $finished) {
  110. $last_chunk_line = $buffer_lines[--$full_buffer_lines_count];
  111. }
  112. for ($line_nr = 0; $line_nr < $full_buffer_lines_count; ++$line_nr) {
  113. $cur_buffer_line = trim($buffer_lines[$line_nr]);
  114. // If the line is empty, go to the next one
  115. if ($cur_buffer_line === '') {
  116. continue;
  117. }
  118. $first_character = $cur_buffer_line[0];
  119. $matches = array();
  120. // Check beginning of comment
  121. if (!strcmp(mb_substr($cur_buffer_line, 0, 4), "<!--")) {
  122. $inside_comment = true;
  123. continue;
  124. } elseif ($inside_comment) {
  125. // Check end of comment
  126. if (!strcmp(mb_substr($cur_buffer_line, 0, 4), "-->")
  127. ) {
  128. // Only data comments are closed. The structure comments
  129. // will be closed when a data comment begins (in order to
  130. // skip structure tables)
  131. if ($inside_data_comment) {
  132. $inside_data_comment = false;
  133. }
  134. // End comments that are not related to table structure
  135. if (!$inside_structure_comment) {
  136. $inside_comment = false;
  137. }
  138. } else {
  139. // Check table name
  140. $match_table_name = array();
  141. if (preg_match(
  142. "/^Table data for `(.*)`$/",
  143. $cur_buffer_line,
  144. $match_table_name
  145. )
  146. ) {
  147. $cur_table_name = $match_table_name[1];
  148. $inside_data_comment = true;
  149. $inside_structure_comment
  150. = $this->_mngInsideStructComm(
  151. $inside_structure_comment
  152. );
  153. } elseif (preg_match(
  154. "/^Table structure for `(.*)`$/",
  155. $cur_buffer_line,
  156. $match_table_name
  157. )
  158. ) {
  159. // The structure comments will be ignored
  160. $inside_structure_comment = true;
  161. }
  162. }
  163. continue;
  164. } elseif (preg_match('/^\{\|(.*)$/', $cur_buffer_line, $matches)) {
  165. // Check start of table
  166. // This will store all the column info on all rows from
  167. // the current table read from the buffer
  168. $cur_temp_table = array();
  169. // Will be used as storage for the current row in the buffer
  170. // Once all its columns are read, it will be added to
  171. // $cur_temp_table and then it will be emptied
  172. $cur_temp_line = array();
  173. // Helps us differentiate the header columns
  174. // from the normal columns
  175. $in_table_header = false;
  176. // End processing because the current line does not
  177. // contain any column information
  178. } elseif (mb_substr($cur_buffer_line, 0, 2) === '|-'
  179. || mb_substr($cur_buffer_line, 0, 2) === '|+'
  180. || mb_substr($cur_buffer_line, 0, 2) === '|}'
  181. ) {
  182. // Check begin row or end table
  183. // Add current line to the values storage
  184. if (!empty($cur_temp_line)) {
  185. // If the current line contains header cells
  186. // ( marked with '!' ),
  187. // it will be marked as table header
  188. if ($in_table_header) {
  189. // Set the header columns
  190. $cur_temp_table_headers = $cur_temp_line;
  191. } else {
  192. // Normal line, add it to the table
  193. $cur_temp_table [] = $cur_temp_line;
  194. }
  195. }
  196. // Empty the temporary buffer
  197. $cur_temp_line = array();
  198. // No more processing required at the end of the table
  199. if (mb_substr($cur_buffer_line, 0, 2) === '|}') {
  200. $current_table = array(
  201. $cur_table_name,
  202. $cur_temp_table_headers,
  203. $cur_temp_table,
  204. );
  205. // Import the current table data into the database
  206. $this->_importDataOneTable($current_table, $sql_data);
  207. // Reset table name
  208. $cur_table_name = "";
  209. }
  210. // What's after the row tag is now only attributes
  211. } elseif (($first_character === '|') || ($first_character === '!')) {
  212. // Check cell elements
  213. // Header cells
  214. if ($first_character === '!') {
  215. // Mark as table header, but treat as normal row
  216. $cur_buffer_line = str_replace('!!', '||', $cur_buffer_line);
  217. // Will be used to set $cur_temp_line as table header
  218. $in_table_header = true;
  219. } else {
  220. $in_table_header = false;
  221. }
  222. // Loop through each table cell
  223. $cells = $this->_explodeMarkup($cur_buffer_line);
  224. foreach ($cells as $cell) {
  225. $cell = $this->_getCellData($cell);
  226. // Delete the beginning of the column, if there is one
  227. $cell = trim($cell);
  228. $col_start_chars = array("|", "!");
  229. foreach ($col_start_chars as $col_start_char) {
  230. $cell = $this->_getCellContent($cell, $col_start_char);
  231. }
  232. // Add the cell to the row
  233. $cur_temp_line [] = $cell;
  234. } // foreach $cells
  235. } else {
  236. // If it's none of the above, then the current line has a bad
  237. // format
  238. $message = Message::error(
  239. __('Invalid format of mediawiki input on line: <br />%s.')
  240. );
  241. $message->addParam($cur_buffer_line);
  242. $error = true;
  243. }
  244. } // End treating full buffer lines
  245. } // while - finished parsing buffer
  246. }
  247. /**
  248. * Imports data from a single table
  249. *
  250. * @param array $table containing all table info:
  251. * <code>
  252. * $table[0] - string containing table name
  253. * $table[1] - array[] of table headers
  254. * $table[2] - array[][] of table content rows
  255. * </code>
  256. *
  257. * @param array &$sql_data 2-element array with sql data
  258. *
  259. * @global bool $analyze whether to scan for column types
  260. *
  261. * @return void
  262. */
  263. private function _importDataOneTable(array $table, array &$sql_data)
  264. {
  265. $analyze = $this->_getAnalyze();
  266. if ($analyze) {
  267. // Set the table name
  268. $this->_setTableName($table[0]);
  269. // Set generic names for table headers if they don't exist
  270. $this->_setTableHeaders($table[1], $table[2][0]);
  271. // Create the tables array to be used in Import::buildSql()
  272. $tables = array();
  273. $tables [] = array($table[0], $table[1], $table[2]);
  274. // Obtain the best-fit MySQL types for each column
  275. $analyses = array();
  276. $analyses [] = Import::analyzeTable($tables[0]);
  277. $this->_executeImportTables($tables, $analyses, $sql_data);
  278. }
  279. // Commit any possible data in buffers
  280. Import::runQuery('', '', $sql_data);
  281. }
  282. /**
  283. * Sets the table name
  284. *
  285. * @param string &$table_name reference to the name of the table
  286. *
  287. * @return void
  288. */
  289. private function _setTableName(&$table_name)
  290. {
  291. if (empty($table_name)) {
  292. $result = $GLOBALS['dbi']->fetchResult('SHOW TABLES');
  293. // todo check if the name below already exists
  294. $table_name = 'TABLE ' . (count($result) + 1);
  295. }
  296. }
  297. /**
  298. * Set generic names for table headers, if they don't exist
  299. *
  300. * @param array &$table_headers reference to the array containing the headers
  301. * of a table
  302. * @param array $table_row array containing the first content row
  303. *
  304. * @return void
  305. */
  306. private function _setTableHeaders(array &$table_headers, array $table_row)
  307. {
  308. if (empty($table_headers)) {
  309. // The first table row should contain the number of columns
  310. // If they are not set, generic names will be given (COL 1, COL 2, etc)
  311. $num_cols = count($table_row);
  312. for ($i = 0; $i < $num_cols; ++$i) {
  313. $table_headers [$i] = 'COL ' . ($i + 1);
  314. }
  315. }
  316. }
  317. /**
  318. * Sets the database name and additional options and calls Import::buildSql()
  319. * Used in PMA_importDataAllTables() and $this->_importDataOneTable()
  320. *
  321. * @param array &$tables structure:
  322. * array(
  323. * array(table_name, array() column_names, array()()
  324. * rows)
  325. * )
  326. * @param array &$analyses structure:
  327. * $analyses = array(
  328. * array(array() column_types, array() column_sizes)
  329. * )
  330. * @param array &$sql_data 2-element array with sql data
  331. *
  332. * @global string $db name of the database to import in
  333. *
  334. * @return void
  335. */
  336. private function _executeImportTables(array &$tables, array &$analyses, array &$sql_data)
  337. {
  338. global $db;
  339. // $db_name : The currently selected database name, if applicable
  340. // No backquotes
  341. // $options : An associative array of options
  342. list($db_name, $options) = $this->getDbnameAndOptions($db, 'mediawiki_DB');
  343. // Array of SQL strings
  344. // Non-applicable parameters
  345. $create = null;
  346. // Create and execute necessary SQL statements from data
  347. Import::buildSql($db_name, $tables, $analyses, $create, $options, $sql_data);
  348. unset($tables);
  349. unset($analyses);
  350. }
  351. /**
  352. * Replaces all instances of the '||' separator between delimiters
  353. * in a given string
  354. *
  355. * @param string $replace the string to be replaced with
  356. * @param string $subject the text to be replaced
  357. *
  358. * @return string with replacements
  359. */
  360. private function _delimiterReplace($replace, $subject)
  361. {
  362. // String that will be returned
  363. $cleaned = "";
  364. // Possible states of current character
  365. $inside_tag = false;
  366. $inside_attribute = false;
  367. // Attributes can be declared with either " or '
  368. $start_attribute_character = false;
  369. // The full separator is "||";
  370. // This remembers if the previous character was '|'
  371. $partial_separator = false;
  372. // Parse text char by char
  373. for ($i = 0; $i < strlen($subject); $i++) {
  374. $cur_char = $subject[$i];
  375. // Check for separators
  376. if ($cur_char == '|') {
  377. // If we're not inside a tag, then this is part of a real separator,
  378. // so we append it to the current segment
  379. if (!$inside_attribute) {
  380. $cleaned .= $cur_char;
  381. if ($partial_separator) {
  382. $inside_tag = false;
  383. $inside_attribute = false;
  384. }
  385. } elseif ($partial_separator) {
  386. // If we are inside a tag, we replace the current char with
  387. // the placeholder and append that to the current segment
  388. $cleaned .= $replace;
  389. }
  390. // If the previous character was also '|', then this ends a
  391. // full separator. If not, this may be the beginning of one
  392. $partial_separator = !$partial_separator;
  393. } else {
  394. // If we're inside a tag attribute and the current character is
  395. // not '|', but the previous one was, it means that the single '|'
  396. // was not appended, so we append it now
  397. if ($partial_separator && $inside_attribute) {
  398. $cleaned .= "|";
  399. }
  400. // If the char is different from "|", no separator can be formed
  401. $partial_separator = false;
  402. // any other character should be appended to the current segment
  403. $cleaned .= $cur_char;
  404. if ($cur_char == '<' && !$inside_attribute) {
  405. // start of a tag
  406. $inside_tag = true;
  407. } elseif ($cur_char == '>' && !$inside_attribute) {
  408. // end of a tag
  409. $inside_tag = false;
  410. } elseif (($cur_char == '"' || $cur_char == "'") && $inside_tag) {
  411. // start or end of an attribute
  412. if (!$inside_attribute) {
  413. $inside_attribute = true;
  414. // remember the attribute`s declaration character (" or ')
  415. $start_attribute_character = $cur_char;
  416. } else {
  417. if ($cur_char == $start_attribute_character) {
  418. $inside_attribute = false;
  419. // unset attribute declaration character
  420. $start_attribute_character = false;
  421. }
  422. }
  423. }
  424. }
  425. } // end for each character in $subject
  426. return $cleaned;
  427. }
  428. /**
  429. * Separates a string into items, similarly to explode
  430. * Uses the '||' separator (which is standard in the mediawiki format)
  431. * and ignores any instances of it inside markup tags
  432. * Used in parsing buffer lines containing data cells
  433. *
  434. * @param string $text text to be split
  435. *
  436. * @return array
  437. */
  438. private function _explodeMarkup($text)
  439. {
  440. $separator = "||";
  441. $placeholder = "\x00";
  442. // Remove placeholder instances
  443. $text = str_replace($placeholder, '', $text);
  444. // Replace instances of the separator inside HTML-like
  445. // tags with the placeholder
  446. $cleaned = $this->_delimiterReplace($placeholder, $text);
  447. // Explode, then put the replaced separators back in
  448. $items = explode($separator, $cleaned);
  449. foreach ($items as $i => $str) {
  450. $items[$i] = str_replace($placeholder, $separator, $str);
  451. }
  452. return $items;
  453. }
  454. /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */
  455. /**
  456. * Returns true if the table should be analyzed, false otherwise
  457. *
  458. * @return bool
  459. */
  460. private function _getAnalyze()
  461. {
  462. return $this->_analyze;
  463. }
  464. /**
  465. * Sets to true if the table should be analyzed, false otherwise
  466. *
  467. * @param bool $analyze status
  468. *
  469. * @return void
  470. */
  471. private function _setAnalyze($analyze)
  472. {
  473. $this->_analyze = $analyze;
  474. }
  475. /**
  476. * Get cell
  477. *
  478. * @param string $cell Cell
  479. *
  480. * @return mixed
  481. */
  482. private function _getCellData($cell)
  483. {
  484. // A cell could contain both parameters and data
  485. $cell_data = explode('|', $cell, 2);
  486. // A '|' inside an invalid link should not
  487. // be mistaken as delimiting cell parameters
  488. if (mb_strpos($cell_data[0], '[[') === false) {
  489. return $cell;
  490. }
  491. if (count($cell_data) == 1) {
  492. return $cell_data[0];
  493. }
  494. return $cell_data[1];
  495. }
  496. /**
  497. * Manage $inside_structure_comment
  498. *
  499. * @param boolean $inside_structure_comment Value to test
  500. *
  501. * @return bool
  502. */
  503. private function _mngInsideStructComm($inside_structure_comment)
  504. {
  505. // End ignoring structure rows
  506. if ($inside_structure_comment) {
  507. $inside_structure_comment = false;
  508. }
  509. return $inside_structure_comment;
  510. }
  511. /**
  512. * Get cell content
  513. *
  514. * @param string $cell Cell
  515. * @param string $col_start_char Start char
  516. *
  517. * @return string
  518. */
  519. private function _getCellContent($cell, $col_start_char)
  520. {
  521. if (mb_strpos($cell, $col_start_char) === 0) {
  522. $cell = trim(mb_substr($cell, 1));
  523. }
  524. return $cell;
  525. }
  526. }