Import.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545
  1. <?php
  2. declare(strict_types=1);
  3. namespace PhpMyAdmin;
  4. use PhpMyAdmin\SqlParser\Parser;
  5. use PhpMyAdmin\SqlParser\Statements\DeleteStatement;
  6. use PhpMyAdmin\SqlParser\Statements\InsertStatement;
  7. use PhpMyAdmin\SqlParser\Statements\ReplaceStatement;
  8. use PhpMyAdmin\SqlParser\Statements\UpdateStatement;
  9. use PhpMyAdmin\SqlParser\Utils\Query;
  10. use function __;
  11. use function abs;
  12. use function count;
  13. use function explode;
  14. use function function_exists;
  15. use function htmlspecialchars;
  16. use function implode;
  17. use function is_array;
  18. use function is_numeric;
  19. use function max;
  20. use function mb_chr;
  21. use function mb_ord;
  22. use function mb_stripos;
  23. use function mb_strlen;
  24. use function mb_strpos;
  25. use function mb_strtoupper;
  26. use function mb_substr;
  27. use function mb_substr_count;
  28. use function preg_match;
  29. use function preg_replace;
  30. use function sprintf;
  31. use function str_contains;
  32. use function str_starts_with;
  33. use function strcmp;
  34. use function strlen;
  35. use function strpos;
  36. use function substr;
  37. use function time;
  38. use function trim;
  39. /**
  40. * Library that provides common import functions that are used by import plugins
  41. */
  42. class Import
  43. {
  44. /* MySQL type defs */
  45. public const NONE = 0;
  46. public const VARCHAR = 1;
  47. public const INT = 2;
  48. public const DECIMAL = 3;
  49. public const BIGINT = 4;
  50. public const GEOMETRY = 5;
  51. /* Decimal size defs */
  52. public const M = 0;
  53. public const D = 1;
  54. public const FULL = 2;
  55. /* Table array defs */
  56. public const TBL_NAME = 0;
  57. public const COL_NAMES = 1;
  58. public const ROWS = 2;
  59. /* Analysis array defs */
  60. public const TYPES = 0;
  61. public const SIZES = 1;
  62. public const FORMATTEDSQL = 2;
  63. public function __construct()
  64. {
  65. global $dbi;
  66. $GLOBALS['cfg']['Server']['DisableIS'] = false;
  67. $checkUserPrivileges = new CheckUserPrivileges($dbi);
  68. $checkUserPrivileges->getPrivileges();
  69. }
  70. /**
  71. * Checks whether timeout is getting close
  72. */
  73. public function checkTimeout(): bool
  74. {
  75. global $timestamp, $maximum_time, $timeout_passed;
  76. if ($maximum_time == 0) {
  77. return false;
  78. }
  79. if ($timeout_passed) {
  80. return true;
  81. /* 5 in next row might be too much */
  82. }
  83. if (time() - $timestamp > $maximum_time - 5) {
  84. $timeout_passed = true;
  85. return true;
  86. }
  87. return false;
  88. }
  89. /**
  90. * Runs query inside import buffer. This is needed to allow displaying
  91. * of last SELECT, SHOW or HANDLER results and similar nice stuff.
  92. *
  93. * @param string $sql query to run
  94. * @param string $full query to display, this might be commented
  95. * @param array $sqlData SQL parse data storage
  96. */
  97. public function executeQuery(string $sql, string $full, array &$sqlData): void
  98. {
  99. global $sql_query, $my_die, $error, $reload, $result, $msg, $cfg, $sql_query_disabled, $db, $dbi;
  100. $result = $dbi->tryQuery($sql);
  101. // USE query changes the database, son need to track
  102. // while running multiple queries
  103. $isUseQuery = mb_stripos($sql, 'use ') !== false;
  104. $msg = '# ';
  105. if ($result === false) { // execution failed
  106. if (! isset($my_die)) {
  107. $my_die = [];
  108. }
  109. $my_die[] = [
  110. 'sql' => $full,
  111. 'error' => $dbi->getError(),
  112. ];
  113. $msg .= __('Error');
  114. if (! $cfg['IgnoreMultiSubmitErrors']) {
  115. $error = true;
  116. return;
  117. }
  118. } else {
  119. $aNumRows = (int) $result->numRows();
  120. $aAffectedRows = (int) @$dbi->affectedRows();
  121. if ($aNumRows > 0) {
  122. $msg .= __('Rows') . ': ' . $aNumRows;
  123. } elseif ($aAffectedRows > 0) {
  124. $message = Message::getMessageForAffectedRows($aAffectedRows);
  125. $msg .= $message->getMessage();
  126. } else {
  127. $msg .= __('MySQL returned an empty result set (i.e. zero rows).');
  128. }
  129. if (($aNumRows > 0) || $isUseQuery) {
  130. $sqlData['valid_sql'][] = $sql;
  131. if (! isset($sqlData['valid_queries'])) {
  132. $sqlData['valid_queries'] = 0;
  133. }
  134. $sqlData['valid_queries']++;
  135. }
  136. }
  137. if (! $sql_query_disabled) {
  138. $sql_query .= $msg . "\n";
  139. }
  140. // If a 'USE <db>' SQL-clause was found and the query
  141. // succeeded, set our current $db to the new one
  142. if ($result != false) {
  143. [$db, $reload] = $this->lookForUse($sql, $db, $reload);
  144. }
  145. $pattern = '@^[\s]*(DROP|CREATE)[\s]+(IF EXISTS[[:space:]]+)?(TABLE|DATABASE)[[:space:]]+(.+)@im';
  146. if ($result == false || ! preg_match($pattern, $sql)) {
  147. return;
  148. }
  149. $reload = true;
  150. }
  151. /**
  152. * Runs query inside import buffer. This is needed to allow displaying
  153. * of last SELECT, SHOW or HANDLER results and similar nice stuff.
  154. *
  155. * @param string $sql query to run
  156. * @param string $full query to display, this might be commented
  157. * @param array $sqlData SQL parse data storage
  158. */
  159. public function runQuery(
  160. string $sql = '',
  161. string $full = '',
  162. array &$sqlData = []
  163. ): void {
  164. global $import_run_buffer, $go_sql, $complete_query, $display_query, $sql_query, $msg,
  165. $skip_queries, $executed_queries, $max_sql_len, $read_multiply, $sql_query_disabled, $run_query;
  166. $read_multiply = 1;
  167. if (! isset($import_run_buffer)) {
  168. // Do we have something to push into buffer?
  169. $import_run_buffer = $this->runQueryPost($import_run_buffer, $sql, $full);
  170. return;
  171. }
  172. // Should we skip something?
  173. if ($skip_queries > 0) {
  174. $skip_queries--;
  175. // Do we have something to push into buffer?
  176. $import_run_buffer = $this->runQueryPost($import_run_buffer, $sql, $full);
  177. return;
  178. }
  179. if (! empty($import_run_buffer['sql']) && trim($import_run_buffer['sql']) != '') {
  180. $max_sql_len = max(
  181. $max_sql_len,
  182. mb_strlen($import_run_buffer['sql'])
  183. );
  184. if (! $sql_query_disabled) {
  185. $sql_query .= $import_run_buffer['full'];
  186. }
  187. $executed_queries++;
  188. if ($run_query && $executed_queries < 50) {
  189. $go_sql = true;
  190. if (! $sql_query_disabled) {
  191. $complete_query = $sql_query;
  192. $display_query = $sql_query;
  193. } else {
  194. $complete_query = '';
  195. $display_query = '';
  196. }
  197. $sql_query = $import_run_buffer['sql'];
  198. $sqlData['valid_sql'][] = $import_run_buffer['sql'];
  199. $sqlData['valid_full'][] = $import_run_buffer['full'];
  200. if (! isset($sqlData['valid_queries'])) {
  201. $sqlData['valid_queries'] = 0;
  202. }
  203. $sqlData['valid_queries']++;
  204. } elseif ($run_query) {
  205. /* Handle rollback from go_sql */
  206. if ($go_sql && isset($sqlData['valid_full'])) {
  207. $queries = $sqlData['valid_sql'];
  208. $fulls = $sqlData['valid_full'];
  209. $count = $sqlData['valid_queries'];
  210. $go_sql = false;
  211. $sqlData['valid_sql'] = [];
  212. $sqlData['valid_queries'] = 0;
  213. unset($sqlData['valid_full']);
  214. for ($i = 0; $i < $count; $i++) {
  215. $this->executeQuery($queries[$i], $fulls[$i], $sqlData);
  216. if ($GLOBALS['error']) {
  217. break;
  218. }
  219. }
  220. }
  221. if (! $GLOBALS['error']) {
  222. $this->executeQuery($import_run_buffer['sql'], $import_run_buffer['full'], $sqlData);
  223. }
  224. }
  225. } elseif (! empty($import_run_buffer['full'])) {
  226. if ($go_sql) {
  227. $complete_query .= $import_run_buffer['full'];
  228. $display_query .= $import_run_buffer['full'];
  229. } elseif (! $sql_query_disabled) {
  230. $sql_query .= $import_run_buffer['full'];
  231. }
  232. }
  233. // check length of query unless we decided to pass it to /sql
  234. // (if $run_query is false, we are just displaying so show
  235. // the complete query in the textarea)
  236. if (! $go_sql && $run_query && ! empty($sql_query)) {
  237. if (mb_strlen($sql_query) > 50000 || $executed_queries > 50 || $max_sql_len > 1000) {
  238. $sql_query = '';
  239. $sql_query_disabled = true;
  240. }
  241. }
  242. // Do we have something to push into buffer?
  243. $import_run_buffer = $this->runQueryPost($import_run_buffer, $sql, $full);
  244. // In case of ROLLBACK, notify the user.
  245. if (! isset($_POST['rollback_query'])) {
  246. return;
  247. }
  248. $msg .= __('[ROLLBACK occurred.]');
  249. }
  250. /**
  251. * Return import run buffer
  252. *
  253. * @param array $importRunBuffer Buffer of queries for import
  254. * @param string $sql SQL query
  255. * @param string $full Query to display
  256. *
  257. * @return array Buffer of queries for import
  258. */
  259. public function runQueryPost(
  260. ?array $importRunBuffer,
  261. string $sql,
  262. string $full
  263. ): ?array {
  264. if (! empty($sql) || ! empty($full)) {
  265. return [
  266. 'sql' => $sql . ';',
  267. 'full' => $full . ';',
  268. ];
  269. }
  270. unset($GLOBALS['import_run_buffer']);
  271. return $importRunBuffer;
  272. }
  273. /**
  274. * Looks for the presence of USE to possibly change current db
  275. *
  276. * @param string $buffer buffer to examine
  277. * @param string $db current db
  278. * @param bool $reload reload
  279. *
  280. * @return array (current or new db, whether to reload)
  281. */
  282. public function lookForUse(?string $buffer, ?string $db, ?bool $reload): array
  283. {
  284. if (preg_match('@^[\s]*USE[[:space:]]+([\S]+)@i', (string) $buffer, $match)) {
  285. $db = trim($match[1]);
  286. $db = trim($db, ';'); // for example, USE abc;
  287. // $db must not contain the escape characters generated by backquote()
  288. // ( used in buildSql() as: backquote($db_name), and then called
  289. // in runQuery() which in turn calls lookForUse() )
  290. $db = Util::unQuote($db);
  291. $reload = true;
  292. }
  293. return [
  294. $db,
  295. $reload,
  296. ];
  297. }
  298. /**
  299. * Returns next part of imported file/buffer
  300. *
  301. * @param int $size size of buffer to read (this is maximal size function will return)
  302. *
  303. * @return string|bool part of file/buffer
  304. */
  305. public function getNextChunk(?File $importHandle = null, int $size = 32768)
  306. {
  307. global $charset_conversion, $charset_of_file, $read_multiply;
  308. // Add some progression while reading large amount of data
  309. if ($read_multiply <= 8) {
  310. $size *= $read_multiply;
  311. } else {
  312. $size *= 8;
  313. }
  314. $read_multiply++;
  315. // We can not read too much
  316. if ($size > $GLOBALS['read_limit']) {
  317. $size = $GLOBALS['read_limit'];
  318. }
  319. if ($this->checkTimeout()) {
  320. return false;
  321. }
  322. if ($GLOBALS['finished']) {
  323. return true;
  324. }
  325. if ($GLOBALS['import_file'] === 'none') {
  326. // Well this is not yet supported and tested,
  327. // but should return content of textarea
  328. if (mb_strlen($GLOBALS['import_text']) < $size) {
  329. $GLOBALS['finished'] = true;
  330. return $GLOBALS['import_text'];
  331. }
  332. $r = mb_substr($GLOBALS['import_text'], 0, $size);
  333. $GLOBALS['offset'] += $size;
  334. $GLOBALS['import_text'] = mb_substr($GLOBALS['import_text'], $size);
  335. return $r;
  336. }
  337. if ($importHandle === null) {
  338. return false;
  339. }
  340. $result = $importHandle->read($size);
  341. $GLOBALS['finished'] = $importHandle->eof();
  342. $GLOBALS['offset'] += $size;
  343. if ($charset_conversion) {
  344. return Encoding::convertString($charset_of_file, 'utf-8', $result);
  345. }
  346. /**
  347. * Skip possible byte order marks (I do not think we need more
  348. * charsets, but feel free to add more, you can use wikipedia for
  349. * reference: <https://en.wikipedia.org/wiki/Byte_Order_Mark>)
  350. *
  351. * @todo BOM could be used for charset autodetection
  352. */
  353. if ($GLOBALS['offset'] == $size) {
  354. $result = $this->skipByteOrderMarksFromContents($result);
  355. }
  356. return $result;
  357. }
  358. /**
  359. * Skip possible byte order marks (I do not think we need more
  360. * charsets, but feel free to add more, you can use wikipedia for
  361. * reference: <https://en.wikipedia.org/wiki/Byte_Order_Mark>)
  362. *
  363. * @param string $contents The contents to strip BOM
  364. *
  365. * @todo BOM could be used for charset autodetection
  366. */
  367. public function skipByteOrderMarksFromContents(string $contents): string
  368. {
  369. // Do not use mb_ functions they are sensible to mb_internal_encoding()
  370. // UTF-8
  371. if (str_starts_with($contents, "\xEF\xBB\xBF")) {
  372. return substr($contents, 3);
  373. // UTF-16 BE, LE
  374. }
  375. if (str_starts_with($contents, "\xFE\xFF") || str_starts_with($contents, "\xFF\xFE")) {
  376. return substr($contents, 2);
  377. }
  378. return $contents;
  379. }
  380. /**
  381. * Returns the "Excel" column name (i.e. 1 = "A", 26 = "Z", 27 = "AA", etc.)
  382. *
  383. * This functions uses recursion to build the Excel column name.
  384. *
  385. * The column number (1-26) is converted to the responding
  386. * ASCII character (A-Z) and returned.
  387. *
  388. * If the column number is bigger than 26 (= num of letters in alphabet),
  389. * an extra character needs to be added. To find this extra character,
  390. * the number is divided by 26 and this value is passed to another instance
  391. * of the same function (hence recursion). In that new instance the number is
  392. * evaluated again, and if it is still bigger than 26, it is divided again
  393. * and passed to another instance of the same function. This continues until
  394. * the number is smaller than 26. Then the last called function returns
  395. * the corresponding ASCII character to the function that called it.
  396. * Each time a called function ends an extra character is added to the column name.
  397. * When the first function is reached, the last character is added and the complete
  398. * column name is returned.
  399. *
  400. * @param int $num the column number
  401. *
  402. * @return string The column's "Excel" name
  403. */
  404. public function getColumnAlphaName(int $num): string
  405. {
  406. $capitalA = 65; // ASCII value for capital "A"
  407. $colName = '';
  408. if ($num > 26) {
  409. $div = (int) ($num / 26);
  410. $remain = $num % 26;
  411. // subtract 1 of divided value in case the modulus is 0,
  412. // this is necessary because A-Z has no 'zero'
  413. if ($remain == 0) {
  414. $div--;
  415. }
  416. // recursive function call
  417. $colName = $this->getColumnAlphaName($div);
  418. // use modulus as new column number
  419. $num = $remain;
  420. }
  421. if ($num == 0) {
  422. // use 'Z' if column number is 0,
  423. // this is necessary because A-Z has no 'zero'
  424. $colName .= mb_chr($capitalA + 26 - 1);
  425. } else {
  426. // convert column number to ASCII character
  427. $colName .= mb_chr($capitalA + $num - 1);
  428. }
  429. return $colName;
  430. }
  431. /**
  432. * Returns the column number based on the Excel name.
  433. * So "A" = 1, "Z" = 26, "AA" = 27, etc.
  434. *
  435. * Basically this is a base26 (A-Z) to base10 (0-9) conversion.
  436. * It iterates through all characters in the column name and
  437. * calculates the corresponding value, based on character value
  438. * (A = 1, ..., Z = 26) and position in the string.
  439. *
  440. * @param string $name column name(i.e. "A", or "BC", etc.)
  441. *
  442. * @return int The column number
  443. */
  444. public function getColumnNumberFromName(string $name): int
  445. {
  446. if (empty($name)) {
  447. return 0;
  448. }
  449. $name = mb_strtoupper($name);
  450. $numChars = mb_strlen($name);
  451. $columnNumber = 0;
  452. for ($i = 0; $i < $numChars; ++$i) {
  453. // read string from back to front
  454. $charPos = $numChars - 1 - $i;
  455. // convert capital character to ASCII value
  456. // and subtract 64 to get corresponding decimal value
  457. // ASCII value of "A" is 65, "B" is 66, etc.
  458. // Decimal equivalent of "A" is 1, "B" is 2, etc.
  459. $number = (int) (mb_ord($name[$charPos]) - 64);
  460. // base26 to base10 conversion : multiply each number
  461. // with corresponding value of the position, in this case
  462. // $i=0 : 1; $i=1 : 26; $i=2 : 676; ...
  463. $columnNumber += $number * 26 ** $i;
  464. }
  465. return (int) $columnNumber;
  466. }
  467. /**
  468. * Obtains the precision (total # of digits) from a size of type decimal
  469. *
  470. * @param string $lastCumulativeSize Size of type decimal
  471. *
  472. * @return int Precision of the given decimal size notation
  473. */
  474. public function getDecimalPrecision(string $lastCumulativeSize): int
  475. {
  476. return (int) substr(
  477. $lastCumulativeSize,
  478. 0,
  479. (int) strpos($lastCumulativeSize, ',')
  480. );
  481. }
  482. /**
  483. * Obtains the scale (# of digits to the right of the decimal point)
  484. * from a size of type decimal
  485. *
  486. * @param string $lastCumulativeSize Size of type decimal
  487. *
  488. * @return int Scale of the given decimal size notation
  489. */
  490. public function getDecimalScale(string $lastCumulativeSize): int
  491. {
  492. return (int) substr(
  493. $lastCumulativeSize,
  494. strpos($lastCumulativeSize, ',') + 1,
  495. strlen($lastCumulativeSize) - strpos($lastCumulativeSize, ',')
  496. );
  497. }
  498. /**
  499. * Obtains the decimal size of a given cell
  500. *
  501. * @param string $cell cell content
  502. *
  503. * @return array Contains the precision, scale, and full size
  504. * representation of the given decimal cell
  505. */
  506. public function getDecimalSize(string $cell): array
  507. {
  508. $currSize = mb_strlen($cell);
  509. $decPos = mb_strpos($cell, '.');
  510. $decPrecision = $currSize - 1 - $decPos;
  511. $m = $currSize - 1;
  512. $d = $decPrecision;
  513. return [
  514. $m,
  515. $d,
  516. $m . ',' . $d,
  517. ];
  518. }
  519. /**
  520. * Obtains the size of the given cell
  521. *
  522. * @param string|int $lastCumulativeSize Last cumulative column size
  523. * @param int|null $lastCumulativeType Last cumulative column type (NONE or VARCHAR or DECIMAL or INT or BIGINT)
  524. * @param int $currentCellType Type of the current cell (NONE or VARCHAR or DECIMAL or INT or BIGINT)
  525. * @param string $cell The current cell
  526. *
  527. * @return string|int Size of the given cell in the type-appropriate format
  528. *
  529. * @todo Handle the error cases more elegantly
  530. */
  531. public function detectSize(
  532. $lastCumulativeSize,
  533. ?int $lastCumulativeType,
  534. int $currentCellType,
  535. string $cell
  536. ) {
  537. $currSize = mb_strlen($cell);
  538. /**
  539. * If the cell is NULL, don't treat it as a varchar
  540. */
  541. if (! strcmp('NULL', $cell)) {
  542. return $lastCumulativeSize;
  543. }
  544. if ($currentCellType == self::VARCHAR) {
  545. /**
  546. * What to do if the current cell is of type VARCHAR
  547. */
  548. /**
  549. * The last cumulative type was VARCHAR
  550. */
  551. if ($lastCumulativeType == self::VARCHAR) {
  552. if ($currSize >= $lastCumulativeSize) {
  553. return $currSize;
  554. }
  555. return $lastCumulativeSize;
  556. }
  557. if ($lastCumulativeType == self::DECIMAL) {
  558. /**
  559. * The last cumulative type was DECIMAL
  560. */
  561. $oldM = $this->getDecimalPrecision($lastCumulativeSize);
  562. if ($currSize >= $oldM) {
  563. return $currSize;
  564. }
  565. return $oldM;
  566. }
  567. if ($lastCumulativeType == self::BIGINT || $lastCumulativeType == self::INT) {
  568. /**
  569. * The last cumulative type was BIGINT or INT
  570. */
  571. if ($currSize >= $lastCumulativeSize) {
  572. return $currSize;
  573. }
  574. return $lastCumulativeSize;
  575. }
  576. if (! isset($lastCumulativeType) || $lastCumulativeType == self::NONE) {
  577. /**
  578. * This is the first row to be analyzed
  579. */
  580. return $currSize;
  581. }
  582. /**
  583. * An error has DEFINITELY occurred
  584. */
  585. /**
  586. * TODO: Handle this MUCH more elegantly
  587. */
  588. return -1;
  589. }
  590. if ($currentCellType == self::DECIMAL) {
  591. /**
  592. * What to do if the current cell is of type DECIMAL
  593. */
  594. /**
  595. * The last cumulative type was VARCHAR
  596. */
  597. if ($lastCumulativeType == self::VARCHAR) {
  598. /* Convert $last_cumulative_size from varchar to decimal format */
  599. $size = $this->getDecimalSize($cell);
  600. if ($size[self::M] >= $lastCumulativeSize) {
  601. return $size[self::M];
  602. }
  603. return $lastCumulativeSize;
  604. }
  605. if ($lastCumulativeType == self::DECIMAL) {
  606. /**
  607. * The last cumulative type was DECIMAL
  608. */
  609. $size = $this->getDecimalSize($cell);
  610. $oldM = $this->getDecimalPrecision($lastCumulativeSize);
  611. $oldD = $this->getDecimalScale($lastCumulativeSize);
  612. /* New val if M or D is greater than current largest */
  613. if ($size[self::M] > $oldM || $size[self::D] > $oldD) {
  614. /* Take the largest of both types */
  615. return (string) (($size[self::M] > $oldM ? $size[self::M] : $oldM)
  616. . ',' . ($size[self::D] > $oldD ? $size[self::D] : $oldD));
  617. }
  618. return $lastCumulativeSize;
  619. }
  620. if ($lastCumulativeType == self::BIGINT || $lastCumulativeType == self::INT) {
  621. /**
  622. * The last cumulative type was BIGINT or INT
  623. */
  624. /* Convert $last_cumulative_size from int to decimal format */
  625. $size = $this->getDecimalSize($cell);
  626. if ($size[self::M] >= $lastCumulativeSize) {
  627. return $size[self::FULL];
  628. }
  629. return $lastCumulativeSize . ',' . $size[self::D];
  630. }
  631. if (! isset($lastCumulativeType) || $lastCumulativeType == self::NONE) {
  632. /**
  633. * This is the first row to be analyzed
  634. */
  635. /* First row of the column */
  636. $size = $this->getDecimalSize($cell);
  637. return $size[self::FULL];
  638. }
  639. /**
  640. * An error has DEFINITELY occurred
  641. */
  642. /**
  643. * TODO: Handle this MUCH more elegantly
  644. */
  645. return -1;
  646. }
  647. if ($currentCellType == self::BIGINT || $currentCellType == self::INT) {
  648. /**
  649. * What to do if the current cell is of type BIGINT or INT
  650. */
  651. /**
  652. * The last cumulative type was VARCHAR
  653. */
  654. if ($lastCumulativeType == self::VARCHAR) {
  655. if ($currSize >= $lastCumulativeSize) {
  656. return $currSize;
  657. }
  658. return $lastCumulativeSize;
  659. }
  660. if ($lastCumulativeType == self::DECIMAL) {
  661. /**
  662. * The last cumulative type was DECIMAL
  663. */
  664. $oldM = $this->getDecimalPrecision($lastCumulativeSize);
  665. $oldD = $this->getDecimalScale($lastCumulativeSize);
  666. $oldInt = $oldM - $oldD;
  667. $newInt = mb_strlen((string) $cell);
  668. /* See which has the larger integer length */
  669. if ($oldInt >= $newInt) {
  670. /* Use old decimal size */
  671. return $lastCumulativeSize;
  672. }
  673. /* Use $newInt + $oldD as new M */
  674. return ($newInt + $oldD) . ',' . $oldD;
  675. }
  676. if ($lastCumulativeType == self::BIGINT || $lastCumulativeType == self::INT) {
  677. /**
  678. * The last cumulative type was BIGINT or INT
  679. */
  680. if ($currSize >= $lastCumulativeSize) {
  681. return $currSize;
  682. }
  683. return $lastCumulativeSize;
  684. }
  685. if (! isset($lastCumulativeType) || $lastCumulativeType == self::NONE) {
  686. /**
  687. * This is the first row to be analyzed
  688. */
  689. return $currSize;
  690. }
  691. /**
  692. * An error has DEFINITELY occurred
  693. */
  694. /**
  695. * TODO: Handle this MUCH more elegantly
  696. */
  697. return -1;
  698. }
  699. /**
  700. * An error has DEFINITELY occurred
  701. */
  702. /**
  703. * TODO: Handle this MUCH more elegantly
  704. */
  705. return -1;
  706. }
  707. /**
  708. * Determines what MySQL type a cell is
  709. *
  710. * @param int $lastCumulativeType Last cumulative column type
  711. * (VARCHAR or INT or BIGINT or DECIMAL or NONE)
  712. * @param string|null $cell String representation of the cell for which
  713. * a best-fit type is to be determined
  714. *
  715. * @return int The MySQL type representation
  716. * (VARCHAR or INT or BIGINT or DECIMAL or NONE)
  717. */
  718. public function detectType(?int $lastCumulativeType, ?string $cell): int
  719. {
  720. /**
  721. * If numeric, determine if decimal, int or bigint
  722. * Else, we call it varchar for simplicity
  723. */
  724. if (! strcmp('NULL', (string) $cell)) {
  725. if ($lastCumulativeType === null || $lastCumulativeType == self::NONE) {
  726. return self::NONE;
  727. }
  728. return $lastCumulativeType;
  729. }
  730. if (! is_numeric($cell)) {
  731. return self::VARCHAR;
  732. }
  733. if (
  734. $cell == (string) (float) $cell
  735. && str_contains((string) $cell, '.')
  736. && mb_substr_count((string) $cell, '.') === 1
  737. ) {
  738. return self::DECIMAL;
  739. }
  740. if (abs((int) $cell) > 2147483647) {
  741. return self::BIGINT;
  742. }
  743. if ($cell !== (string) (int) $cell) {
  744. return self::VARCHAR;
  745. }
  746. return self::INT;
  747. }
  748. /**
  749. * Determines if the column types are int, decimal, or string
  750. *
  751. * @link https://wiki.phpmyadmin.net/pma/Import
  752. *
  753. * @param array $table array(string $table_name, array $col_names, array $rows)
  754. *
  755. * @return array|bool array(array $types, array $sizes)
  756. *
  757. * @todo Handle the error case more elegantly
  758. */
  759. public function analyzeTable(array &$table)
  760. {
  761. /* Get number of rows in table */
  762. $numRows = count($table[self::ROWS]);
  763. /* Get number of columns */
  764. $numCols = count($table[self::COL_NAMES]);
  765. /* Current type for each column */
  766. $types = [];
  767. $sizes = [];
  768. /* Initialize $sizes to all 0's */
  769. for ($i = 0; $i < $numCols; ++$i) {
  770. $sizes[$i] = 0;
  771. }
  772. /* Initialize $types to NONE */
  773. for ($i = 0; $i < $numCols; ++$i) {
  774. $types[$i] = self::NONE;
  775. }
  776. /* If the passed array is not of the correct form, do not process it */
  777. if (
  778. is_array($table[self::TBL_NAME])
  779. || ! is_array($table[self::COL_NAMES])
  780. || ! is_array($table[self::ROWS])
  781. ) {
  782. /**
  783. * TODO: Handle this better
  784. */
  785. return false;
  786. }
  787. /* Analyze each column */
  788. for ($i = 0; $i < $numCols; ++$i) {
  789. /* Analyze the column in each row */
  790. for ($j = 0; $j < $numRows; ++$j) {
  791. $cellValue = $table[self::ROWS][$j][$i];
  792. /* Determine type of the current cell */
  793. $currType = $this->detectType($types[$i], $cellValue === null ? null : (string) $cellValue);
  794. /* Determine size of the current cell */
  795. $sizes[$i] = $this->detectSize($sizes[$i], $types[$i], $currType, (string) $cellValue);
  796. /**
  797. * If a type for this column has already been declared,
  798. * only alter it if it was a number and a varchar was found
  799. */
  800. if ($currType == self::NONE) {
  801. continue;
  802. }
  803. if ($currType == self::VARCHAR) {
  804. $types[$i] = self::VARCHAR;
  805. } elseif ($currType == self::DECIMAL) {
  806. if ($types[$i] != self::VARCHAR) {
  807. $types[$i] = self::DECIMAL;
  808. }
  809. } elseif ($currType == self::BIGINT) {
  810. if ($types[$i] != self::VARCHAR && $types[$i] != self::DECIMAL) {
  811. $types[$i] = self::BIGINT;
  812. }
  813. } elseif ($currType == self::INT) {
  814. if ($types[$i] != self::VARCHAR && $types[$i] != self::DECIMAL && $types[$i] != self::BIGINT) {
  815. $types[$i] = self::INT;
  816. }
  817. }
  818. }
  819. }
  820. /* Check to ensure that all types are valid */
  821. $len = count($types);
  822. for ($n = 0; $n < $len; ++$n) {
  823. if (strcmp((string) self::NONE, (string) $types[$n])) {
  824. continue;
  825. }
  826. $types[$n] = self::VARCHAR;
  827. $sizes[$n] = '10';
  828. }
  829. return [
  830. $types,
  831. $sizes,
  832. ];
  833. }
  834. /**
  835. * Builds and executes SQL statements to create the database and tables
  836. * as necessary, as well as insert all the data.
  837. *
  838. * @link https://wiki.phpmyadmin.net/pma/Import
  839. *
  840. * @param string $dbName Name of the database
  841. * @param array $tables Array of tables for the specified database
  842. * @param array|null $analyses Analyses of the tables
  843. * @param array|null $additionalSql Additional SQL statements to be executed
  844. * @param array|null $options Associative array of options
  845. * @param array $sqlData 2-element array with sql data
  846. */
  847. public function buildSql(
  848. string $dbName,
  849. array &$tables,
  850. ?array &$analyses = null,
  851. ?array &$additionalSql = null,
  852. ?array $options = null,
  853. array &$sqlData = []
  854. ): void {
  855. global $import_notice, $dbi;
  856. /* Needed to quell the beast that is Message */
  857. $import_notice = null;
  858. /* Take care of the options */
  859. $collation = 'utf8_general_ci';
  860. $charset = 'utf8';
  861. $createDb = $options['create_db'] ?? true;
  862. /**
  863. * Create SQL code to handle the database
  864. *
  865. * @var array<int,string> $sql
  866. */
  867. $sql = [];
  868. if ($createDb) {
  869. $sql[] = 'CREATE DATABASE IF NOT EXISTS ' . Util::backquote($dbName)
  870. . ' DEFAULT CHARACTER SET ' . $charset . ' COLLATE ' . $collation
  871. . ';';
  872. }
  873. /**
  874. * The calling plug-in should include this statement,
  875. * if necessary, in the $additional_sql parameter
  876. *
  877. * $sql[] = "USE " . backquote($db_name);
  878. */
  879. /* Execute the SQL statements create above */
  880. $sqlLength = count($sql);
  881. for ($i = 0; $i < $sqlLength; ++$i) {
  882. $this->runQuery($sql[$i], $sql[$i], $sqlData);
  883. }
  884. /* No longer needed */
  885. unset($sql);
  886. /* Run the $additional_sql statements supplied by the caller plug-in */
  887. if ($additionalSql != null) {
  888. /* Clean the SQL first */
  889. $additionalSqlLength = count($additionalSql);
  890. /**
  891. * Only match tables for now, because CREATE IF NOT EXISTS
  892. * syntax is lacking or nonexisting for views, triggers,
  893. * functions, and procedures.
  894. *
  895. * See: https://bugs.mysql.com/bug.php?id=15287
  896. *
  897. * To the best of my knowledge this is still an issue.
  898. *
  899. * $pattern = 'CREATE (TABLE|VIEW|TRIGGER|FUNCTION|PROCEDURE)';
  900. */
  901. $pattern = '/CREATE [^`]*(TABLE)/';
  902. $replacement = 'CREATE \\1 IF NOT EXISTS';
  903. /* Change CREATE statements to CREATE IF NOT EXISTS to support
  904. * inserting into existing structures
  905. */
  906. for ($i = 0; $i < $additionalSqlLength; ++$i) {
  907. $additionalSql[$i] = preg_replace($pattern, $replacement, $additionalSql[$i]);
  908. /* Execute the resulting statements */
  909. $this->runQuery($additionalSql[$i], $additionalSql[$i], $sqlData);
  910. }
  911. }
  912. if ($analyses != null) {
  913. $typeArray = [
  914. self::NONE => 'NULL',
  915. self::VARCHAR => 'varchar',
  916. self::INT => 'int',
  917. self::DECIMAL => 'decimal',
  918. self::BIGINT => 'bigint',
  919. self::GEOMETRY => 'geometry',
  920. ];
  921. /* TODO: Do more checking here to make sure they really are matched */
  922. if (count($tables) != count($analyses)) {
  923. exit;
  924. }
  925. /* Create SQL code to create the tables */
  926. $numTables = count($tables);
  927. for ($i = 0; $i < $numTables; ++$i) {
  928. $numCols = count($tables[$i][self::COL_NAMES]);
  929. $tempSQLStr = 'CREATE TABLE IF NOT EXISTS '
  930. . Util::backquote($dbName)
  931. . '.' . Util::backquote($tables[$i][self::TBL_NAME]) . ' (';
  932. for ($j = 0; $j < $numCols; ++$j) {
  933. $size = $analyses[$i][self::SIZES][$j];
  934. if ((int) $size == 0) {
  935. $size = 10;
  936. }
  937. $tempSQLStr .= Util::backquote($tables[$i][self::COL_NAMES][$j]) . ' '
  938. . $typeArray[$analyses[$i][self::TYPES][$j]];
  939. if ($analyses[$i][self::TYPES][$j] != self::GEOMETRY) {
  940. $tempSQLStr .= '(' . $size . ')';
  941. }
  942. if ($j == count($tables[$i][self::COL_NAMES]) - 1) {
  943. continue;
  944. }
  945. $tempSQLStr .= ', ';
  946. }
  947. $tempSQLStr .= ');';
  948. /**
  949. * Each SQL statement is executed immediately
  950. * after it is formed so that we don't have
  951. * to store them in a (possibly large) buffer
  952. */
  953. $this->runQuery($tempSQLStr, $tempSQLStr, $sqlData);
  954. }
  955. }
  956. /**
  957. * Create the SQL statements to insert all the data
  958. *
  959. * Only one insert query is formed for each table
  960. */
  961. $tempSQLStr = '';
  962. $colCount = 0;
  963. $numTables = count($tables);
  964. for ($i = 0; $i < $numTables; ++$i) {
  965. $numCols = count($tables[$i][self::COL_NAMES]);
  966. $numRows = count($tables[$i][self::ROWS]);
  967. if ($numRows === 0) {
  968. break;
  969. }
  970. $tempSQLStr = 'INSERT INTO ' . Util::backquote($dbName) . '.'
  971. . Util::backquote($tables[$i][self::TBL_NAME]) . ' (';
  972. for ($m = 0; $m < $numCols; ++$m) {
  973. $tempSQLStr .= Util::backquote($tables[$i][self::COL_NAMES][$m]);
  974. if ($m == $numCols - 1) {
  975. continue;
  976. }
  977. $tempSQLStr .= ', ';
  978. }
  979. $tempSQLStr .= ') VALUES ';
  980. for ($j = 0; $j < $numRows; ++$j) {
  981. $tempSQLStr .= '(';
  982. for ($k = 0; $k < $numCols; ++$k) {
  983. // If fully formatted SQL, no need to enclose
  984. // with apostrophes, add slashes etc.
  985. if (
  986. $analyses != null
  987. && isset($analyses[$i][self::FORMATTEDSQL][$colCount])
  988. && $analyses[$i][self::FORMATTEDSQL][$colCount] == true
  989. ) {
  990. $tempSQLStr .= (string) $tables[$i][self::ROWS][$j][$k];
  991. } else {
  992. if ($analyses != null) {
  993. $isVarchar = ($analyses[$i][self::TYPES][$colCount] === self::VARCHAR);
  994. } else {
  995. $isVarchar = ! is_numeric($tables[$i][self::ROWS][$j][$k]);
  996. }
  997. /* Don't put quotes around NULL fields */
  998. if (! strcmp((string) $tables[$i][self::ROWS][$j][$k], 'NULL')) {
  999. $isVarchar = false;
  1000. }
  1001. $tempSQLStr .= $isVarchar ? "'" : '';
  1002. $tempSQLStr .= $dbi->escapeString((string) $tables[$i][self::ROWS][$j][$k]);
  1003. $tempSQLStr .= $isVarchar ? "'" : '';
  1004. }
  1005. if ($k != $numCols - 1) {
  1006. $tempSQLStr .= ', ';
  1007. }
  1008. if ($colCount == $numCols - 1) {
  1009. $colCount = 0;
  1010. } else {
  1011. $colCount++;
  1012. }
  1013. /* Delete the cell after we are done with it */
  1014. unset($tables[$i][self::ROWS][$j][$k]);
  1015. }
  1016. $tempSQLStr .= ')';
  1017. if ($j != $numRows - 1) {
  1018. $tempSQLStr .= ",\n ";
  1019. }
  1020. $colCount = 0;
  1021. /* Delete the row after we are done with it */
  1022. unset($tables[$i][self::ROWS][$j]);
  1023. }
  1024. $tempSQLStr .= ';';
  1025. /**
  1026. * Each SQL statement is executed immediately
  1027. * after it is formed so that we don't have
  1028. * to store them in a (possibly large) buffer
  1029. */
  1030. $this->runQuery($tempSQLStr, $tempSQLStr, $sqlData);
  1031. }
  1032. /* No longer needed */
  1033. unset($tempSQLStr);
  1034. /**
  1035. * A work in progress
  1036. */
  1037. /**
  1038. * Add the viewable structures from $additional_sql
  1039. * to $tables so they are also displayed
  1040. */
  1041. $viewPattern = '@VIEW `[^`]+`\.`([^`]+)@';
  1042. $tablePattern = '@CREATE TABLE IF NOT EXISTS `([^`]+)`@';
  1043. /* Check a third pattern to make sure its not a "USE `db_name`;" statement */
  1044. $regs = [];
  1045. $inTables = false;
  1046. $additionalSqlLength = $additionalSql === null ? 0 : count($additionalSql);
  1047. for ($i = 0; $i < $additionalSqlLength; ++$i) {
  1048. preg_match($viewPattern, $additionalSql[$i], $regs);
  1049. if (count($regs) === 0) {
  1050. preg_match($tablePattern, $additionalSql[$i], $regs);
  1051. }
  1052. if (count($regs)) {
  1053. for ($n = 0; $n < $numTables; ++$n) {
  1054. if (! strcmp($regs[1], $tables[$n][self::TBL_NAME])) {
  1055. $inTables = true;
  1056. break;
  1057. }
  1058. }
  1059. if (! $inTables) {
  1060. $tables[] = [self::TBL_NAME => $regs[1]];
  1061. }
  1062. }
  1063. /* Reset the array */
  1064. $regs = [];
  1065. $inTables = false;
  1066. }
  1067. $params = ['db' => $dbName];
  1068. $dbUrl = Url::getFromRoute('/database/structure', $params);
  1069. $dbOperationsUrl = Url::getFromRoute('/database/operations', $params);
  1070. $message = '<br><br>';
  1071. $message .= '<strong>' . __(
  1072. 'The following structures have either been created or altered. Here you can:'
  1073. ) . '</strong><br>';
  1074. $message .= '<ul><li>' . __("View a structure's contents by clicking on its name.") . '</li>';
  1075. $message .= '<li>' . __('Change any of its settings by clicking the corresponding "Options" link.') . '</li>';
  1076. $message .= '<li>' . __('Edit structure by following the "Structure" link.')
  1077. . '</li>';
  1078. $message .= sprintf(
  1079. '<br><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">'
  1080. . __('Options') . '</a>)</li>',
  1081. $dbUrl,
  1082. sprintf(
  1083. __('Go to database: %s'),
  1084. htmlspecialchars(Util::backquote($dbName))
  1085. ),
  1086. htmlspecialchars($dbName),
  1087. $dbOperationsUrl,
  1088. sprintf(
  1089. __('Edit settings for %s'),
  1090. htmlspecialchars(Util::backquote($dbName))
  1091. )
  1092. );
  1093. $message .= '<ul>';
  1094. unset($params);
  1095. foreach ($tables as $table) {
  1096. $params = [
  1097. 'db' => $dbName,
  1098. 'table' => (string) $table[self::TBL_NAME],
  1099. ];
  1100. $tblUrl = Url::getFromRoute('/sql', $params);
  1101. $tblStructUrl = Url::getFromRoute('/table/structure', $params);
  1102. $tblOpsUrl = Url::getFromRoute('/table/operations', $params);
  1103. unset($params);
  1104. $tableObj = new Table($table[self::TBL_NAME], $dbName);
  1105. if (! $tableObj->isView()) {
  1106. $message .= sprintf(
  1107. '<li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __(
  1108. 'Structure'
  1109. ) . '</a>) (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
  1110. $tblUrl,
  1111. sprintf(
  1112. __('Go to table: %s'),
  1113. htmlspecialchars(
  1114. Util::backquote($table[self::TBL_NAME])
  1115. )
  1116. ),
  1117. htmlspecialchars($table[self::TBL_NAME]),
  1118. $tblStructUrl,
  1119. sprintf(
  1120. __('Structure of %s'),
  1121. htmlspecialchars(
  1122. Util::backquote($table[self::TBL_NAME])
  1123. )
  1124. ),
  1125. $tblOpsUrl,
  1126. sprintf(
  1127. __('Edit settings for %s'),
  1128. htmlspecialchars(
  1129. Util::backquote($table[self::TBL_NAME])
  1130. )
  1131. )
  1132. );
  1133. } else {
  1134. $message .= sprintf(
  1135. '<li><a href="%s" title="%s">%s</a></li>',
  1136. $tblUrl,
  1137. sprintf(
  1138. __('Go to view: %s'),
  1139. htmlspecialchars(
  1140. Util::backquote($table[self::TBL_NAME])
  1141. )
  1142. ),
  1143. htmlspecialchars($table[self::TBL_NAME])
  1144. );
  1145. }
  1146. }
  1147. $message .= '</ul></ul>';
  1148. $import_notice = $message;
  1149. }
  1150. /**
  1151. * Handles request for ROLLBACK.
  1152. *
  1153. * @param string $sqlQuery SQL query(s)
  1154. */
  1155. public function handleRollbackRequest(string $sqlQuery): void
  1156. {
  1157. global $dbi;
  1158. $sqlDelimiter = $_POST['sql_delimiter'];
  1159. $queries = explode($sqlDelimiter, $sqlQuery);
  1160. $error = false;
  1161. $errorMsg = __(
  1162. 'Only INSERT, UPDATE, DELETE and REPLACE '
  1163. . 'SQL queries containing transactional engine tables can be rolled back.'
  1164. );
  1165. foreach ($queries as $sqlQuery) {
  1166. if (empty($sqlQuery)) {
  1167. continue;
  1168. }
  1169. // Check each query for ROLLBACK support.
  1170. if ($this->checkIfRollbackPossible($sqlQuery)) {
  1171. continue;
  1172. }
  1173. $globalError = $dbi->getError();
  1174. if ($globalError) {
  1175. $error = $globalError;
  1176. } else {
  1177. $error = $errorMsg;
  1178. }
  1179. break;
  1180. }
  1181. if ($error) {
  1182. unset($_POST['rollback_query']);
  1183. $response = ResponseRenderer::getInstance();
  1184. $message = Message::rawError($error);
  1185. $response->addJSON('message', $message);
  1186. exit;
  1187. }
  1188. // If everything fine, START a transaction.
  1189. $dbi->query('START TRANSACTION');
  1190. }
  1191. /**
  1192. * Checks if ROLLBACK is possible for a SQL query or not.
  1193. *
  1194. * @param string $sqlQuery SQL query
  1195. */
  1196. public function checkIfRollbackPossible(string $sqlQuery): bool
  1197. {
  1198. $parser = new Parser($sqlQuery);
  1199. if (empty($parser->statements[0])) {
  1200. return true;
  1201. }
  1202. $statement = $parser->statements[0];
  1203. // Check if query is supported.
  1204. if (
  1205. ! (($statement instanceof InsertStatement)
  1206. || ($statement instanceof UpdateStatement)
  1207. || ($statement instanceof DeleteStatement)
  1208. || ($statement instanceof ReplaceStatement))
  1209. ) {
  1210. return false;
  1211. }
  1212. // Get table_references from the query.
  1213. $tables = Query::getTables($statement);
  1214. // Check if each table is 'InnoDB'.
  1215. foreach ($tables as $table) {
  1216. if (! $this->isTableTransactional($table)) {
  1217. return false;
  1218. }
  1219. }
  1220. return true;
  1221. }
  1222. /**
  1223. * Checks if a table is 'InnoDB' or not.
  1224. *
  1225. * @param string $table Table details
  1226. */
  1227. public function isTableTransactional(string $table): bool
  1228. {
  1229. global $dbi;
  1230. $table = explode('.', $table);
  1231. if (count($table) === 2) {
  1232. $db = Util::unQuote($table[0]);
  1233. $table = Util::unQuote($table[1]);
  1234. } else {
  1235. $db = $GLOBALS['db'];
  1236. $table = Util::unQuote($table[0]);
  1237. }
  1238. // Query to check if table exists.
  1239. $checkTableQuery = 'SELECT * FROM ' . Util::backquote($db)
  1240. . '.' . Util::backquote($table) . ' '
  1241. . 'LIMIT 1';
  1242. $result = $dbi->tryQuery($checkTableQuery);
  1243. if (! $result) {
  1244. return false;
  1245. }
  1246. // List of Transactional Engines.
  1247. $transactionalEngines = [
  1248. 'INNODB',
  1249. 'FALCON',
  1250. 'NDB',
  1251. 'INFINIDB',
  1252. 'TOKUDB',
  1253. 'XTRADB',
  1254. 'SEQUENCE',
  1255. 'BDB',
  1256. 'ROCKSDB',
  1257. ];
  1258. // Query to check if table is 'Transactional'.
  1259. $checkQuery = 'SELECT `ENGINE` FROM `information_schema`.`tables` '
  1260. . 'WHERE `table_name` = "' . $dbi->escapeString($table) . '" '
  1261. . 'AND `table_schema` = "' . $dbi->escapeString($db) . '" '
  1262. . 'AND UPPER(`engine`) IN ("'
  1263. . implode('", "', $transactionalEngines)
  1264. . '")';
  1265. $result = $dbi->tryQuery($checkQuery);
  1266. return $result && $result->numRows() == 1;
  1267. }
  1268. /** @return string[] */
  1269. public static function getCompressions(): array
  1270. {
  1271. global $cfg;
  1272. $compressions = [];
  1273. if ($cfg['GZipDump'] && function_exists('gzopen')) {
  1274. $compressions[] = 'gzip';
  1275. }
  1276. if ($cfg['BZipDump'] && function_exists('bzopen')) {
  1277. $compressions[] = 'bzip2';
  1278. }
  1279. if ($cfg['ZipDump'] && function_exists('zip_open')) {
  1280. $compressions[] = 'zip';
  1281. }
  1282. return $compressions;
  1283. }
  1284. /**
  1285. * @param array $importList List of plugin instances.
  1286. *
  1287. * @return false|string
  1288. */
  1289. public static function getLocalFiles(array $importList)
  1290. {
  1291. $fileListing = new FileListing();
  1292. $extensions = '';
  1293. foreach ($importList as $importPlugin) {
  1294. if (! empty($extensions)) {
  1295. $extensions .= '|';
  1296. }
  1297. $extensions .= $importPlugin->getProperties()->getExtension();
  1298. }
  1299. $matcher = '@\.(' . $extensions . ')(\.(' . $fileListing->supportedDecompressions() . '))?$@';
  1300. $active = isset($GLOBALS['timeout_passed'], $GLOBALS['local_import_file']) && $GLOBALS['timeout_passed']
  1301. ? $GLOBALS['local_import_file']
  1302. : '';
  1303. return $fileListing->getFileSelectOptions(
  1304. Util::userDir((string) ($GLOBALS['cfg']['UploadDir'] ?? '')),
  1305. $matcher,
  1306. $active
  1307. );
  1308. }
  1309. }