Import.php 56 KB

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