Import.php 56 KB

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