Import.php 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  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($cell) > 2147483647) {
  728. return self::BIGINT;
  729. }
  730. return self::INT;
  731. }
  732. /**
  733. * Determines if the column types are int, decimal, or string
  734. *
  735. * @param array &$table array(string $table_name, array $col_names, array $rows)
  736. *
  737. * @return array array(array $types, array $sizes)
  738. * @access public
  739. *
  740. * @link https://wiki.phpmyadmin.net/pma/Import
  741. *
  742. * @todo Handle the error case more elegantly
  743. */
  744. public static function analyzeTable(array &$table)
  745. {
  746. /* Get number of rows in table */
  747. $numRows = count($table[self::ROWS]);
  748. /* Get number of columns */
  749. $numCols = count($table[self::COL_NAMES]);
  750. /* Current type for each column */
  751. $types = array();
  752. $sizes = array();
  753. /* Initialize $sizes to all 0's */
  754. for ($i = 0; $i < $numCols; ++$i) {
  755. $sizes[$i] = 0;
  756. }
  757. /* Initialize $types to NONE */
  758. for ($i = 0; $i < $numCols; ++$i) {
  759. $types[$i] = self::NONE;
  760. }
  761. /* If the passed array is not of the correct form, do not process it */
  762. if (!is_array($table)
  763. || is_array($table[self::TBL_NAME])
  764. || !is_array($table[self::COL_NAMES])
  765. || !is_array($table[self::ROWS])
  766. ) {
  767. /**
  768. * TODO: Handle this better
  769. */
  770. return false;
  771. }
  772. /* Analyze each column */
  773. for ($i = 0; $i < $numCols; ++$i) {
  774. /* Analyze the column in each row */
  775. for ($j = 0; $j < $numRows; ++$j) {
  776. /* Determine type of the current cell */
  777. $curr_type = self::detectType($types[$i], $table[self::ROWS][$j][$i]);
  778. /* Determine size of the current cell */
  779. $sizes[$i] = self::detectSize(
  780. $sizes[$i],
  781. $types[$i],
  782. $curr_type,
  783. $table[self::ROWS][$j][$i]
  784. );
  785. /**
  786. * If a type for this column has already been declared,
  787. * only alter it if it was a number and a varchar was found
  788. */
  789. if ($curr_type != self::NONE) {
  790. if ($curr_type == self::VARCHAR) {
  791. $types[$i] = self::VARCHAR;
  792. } elseif ($curr_type == self::DECIMAL) {
  793. if ($types[$i] != self::VARCHAR) {
  794. $types[$i] = self::DECIMAL;
  795. }
  796. } elseif ($curr_type == self::BIGINT) {
  797. if ($types[$i] != self::VARCHAR && $types[$i] != self::DECIMAL) {
  798. $types[$i] = self::BIGINT;
  799. }
  800. } elseif ($curr_type == self::INT) {
  801. if ($types[$i] != self::VARCHAR
  802. && $types[$i] != self::DECIMAL
  803. && $types[$i] != self::BIGINT
  804. ) {
  805. $types[$i] = self::INT;
  806. }
  807. }
  808. }
  809. }
  810. }
  811. /* Check to ensure that all types are valid */
  812. $len = count($types);
  813. for ($n = 0; $n < $len; ++$n) {
  814. if (! strcmp(self::NONE, $types[$n])) {
  815. $types[$n] = self::VARCHAR;
  816. $sizes[$n] = '10';
  817. }
  818. }
  819. return array($types, $sizes);
  820. }
  821. /**
  822. * Builds and executes SQL statements to create the database and tables
  823. * as necessary, as well as insert all the data.
  824. *
  825. * @param string $db_name Name of the database
  826. * @param array &$tables Array of tables for the specified database
  827. * @param array|null &$analyses Analyses of the tables
  828. * @param array|null &$additional_sql Additional SQL statements to be executed
  829. * @param array|null $options Associative array of options
  830. * @param array &$sql_data 2-element array with sql data
  831. *
  832. * @return void
  833. * @access public
  834. *
  835. * @link https://wiki.phpmyadmin.net/pma/Import
  836. */
  837. public static function buildSql($db_name, array &$tables, &$analyses = null,
  838. &$additional_sql = null, $options = null, array &$sql_data
  839. ) {
  840. /* Needed to quell the beast that is Message */
  841. $import_notice = null;
  842. /* Take care of the options */
  843. if (isset($options['db_collation'])&& ! is_null($options['db_collation'])) {
  844. $collation = $options['db_collation'];
  845. } else {
  846. $collation = "utf8_general_ci";
  847. }
  848. if (isset($options['db_charset']) && ! is_null($options['db_charset'])) {
  849. $charset = $options['db_charset'];
  850. } else {
  851. $charset = "utf8";
  852. }
  853. if (isset($options['create_db'])) {
  854. $create_db = $options['create_db'];
  855. } else {
  856. $create_db = true;
  857. }
  858. /* Create SQL code to handle the database */
  859. $sql = array();
  860. if ($create_db) {
  861. $sql[] = "CREATE DATABASE IF NOT EXISTS " . Util::backquote($db_name)
  862. . " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation
  863. . ";";
  864. }
  865. /**
  866. * The calling plug-in should include this statement,
  867. * if necessary, in the $additional_sql parameter
  868. *
  869. * $sql[] = "USE " . backquote($db_name);
  870. */
  871. /* Execute the SQL statements create above */
  872. $sql_len = count($sql);
  873. for ($i = 0; $i < $sql_len; ++$i) {
  874. self::runQuery($sql[$i], $sql[$i], $sql_data);
  875. }
  876. /* No longer needed */
  877. unset($sql);
  878. /* Run the $additional_sql statements supplied by the caller plug-in */
  879. if ($additional_sql != null) {
  880. /* Clean the SQL first */
  881. $additional_sql_len = count($additional_sql);
  882. /**
  883. * Only match tables for now, because CREATE IF NOT EXISTS
  884. * syntax is lacking or nonexisting for views, triggers,
  885. * functions, and procedures.
  886. *
  887. * See: https://bugs.mysql.com/bug.php?id=15287
  888. *
  889. * To the best of my knowledge this is still an issue.
  890. *
  891. * $pattern = 'CREATE (TABLE|VIEW|TRIGGER|FUNCTION|PROCEDURE)';
  892. */
  893. $pattern = '/CREATE [^`]*(TABLE)/';
  894. $replacement = 'CREATE \\1 IF NOT EXISTS';
  895. /* Change CREATE statements to CREATE IF NOT EXISTS to support
  896. * inserting into existing structures
  897. */
  898. for ($i = 0; $i < $additional_sql_len; ++$i) {
  899. $additional_sql[$i] = preg_replace(
  900. $pattern,
  901. $replacement,
  902. $additional_sql[$i]
  903. );
  904. /* Execute the resulting statements */
  905. self::runQuery($additional_sql[$i], $additional_sql[$i], $sql_data);
  906. }
  907. }
  908. if ($analyses != null) {
  909. $type_array = array(
  910. self::NONE => "NULL",
  911. self::VARCHAR => "varchar",
  912. self::INT => "int",
  913. self::DECIMAL => "decimal",
  914. self::BIGINT => "bigint",
  915. self::GEOMETRY => 'geometry'
  916. );
  917. /* TODO: Do more checking here to make sure they really are matched */
  918. if (count($tables) != count($analyses)) {
  919. exit();
  920. }
  921. /* Create SQL code to create the tables */
  922. $num_tables = count($tables);
  923. for ($i = 0; $i < $num_tables; ++$i) {
  924. $num_cols = count($tables[$i][self::COL_NAMES]);
  925. $tempSQLStr = "CREATE TABLE IF NOT EXISTS "
  926. . Util::backquote($db_name)
  927. . '.' . Util::backquote($tables[$i][self::TBL_NAME]) . " (";
  928. for ($j = 0; $j < $num_cols; ++$j) {
  929. $size = $analyses[$i][self::SIZES][$j];
  930. if ((int)$size == 0) {
  931. $size = 10;
  932. }
  933. $tempSQLStr .= Util::backquote(
  934. $tables[$i][self::COL_NAMES][$j]
  935. ) . " "
  936. . $type_array[$analyses[$i][self::TYPES][$j]];
  937. if ($analyses[$i][self::TYPES][$j] != self::GEOMETRY) {
  938. $tempSQLStr .= "(" . $size . ")";
  939. }
  940. if ($j != (count($tables[$i][self::COL_NAMES]) - 1)) {
  941. $tempSQLStr .= ", ";
  942. }
  943. }
  944. $tempSQLStr .= ") DEFAULT CHARACTER SET " . $charset
  945. . " COLLATE " . $collation . ";";
  946. /**
  947. * Each SQL statement is executed immediately
  948. * after it is formed so that we don't have
  949. * to store them in a (possibly large) buffer
  950. */
  951. self::runQuery($tempSQLStr, $tempSQLStr, $sql_data);
  952. }
  953. }
  954. /**
  955. * Create the SQL statements to insert all the data
  956. *
  957. * Only one insert query is formed for each table
  958. */
  959. $tempSQLStr = "";
  960. $col_count = 0;
  961. $num_tables = count($tables);
  962. for ($i = 0; $i < $num_tables; ++$i) {
  963. $num_cols = count($tables[$i][self::COL_NAMES]);
  964. $num_rows = count($tables[$i][self::ROWS]);
  965. $tempSQLStr = "INSERT INTO " . Util::backquote($db_name) . '.'
  966. . Util::backquote($tables[$i][self::TBL_NAME]) . " (";
  967. for ($m = 0; $m < $num_cols; ++$m) {
  968. $tempSQLStr .= Util::backquote($tables[$i][self::COL_NAMES][$m]);
  969. if ($m != ($num_cols - 1)) {
  970. $tempSQLStr .= ", ";
  971. }
  972. }
  973. $tempSQLStr .= ") VALUES ";
  974. for ($j = 0; $j < $num_rows; ++$j) {
  975. $tempSQLStr .= "(";
  976. for ($k = 0; $k < $num_cols; ++$k) {
  977. // If fully formatted SQL, no need to enclose
  978. // with apostrophes, add slashes etc.
  979. if ($analyses != null
  980. && isset($analyses[$i][self::FORMATTEDSQL][$col_count])
  981. && $analyses[$i][self::FORMATTEDSQL][$col_count] == true
  982. ) {
  983. $tempSQLStr .= (string) $tables[$i][self::ROWS][$j][$k];
  984. } else {
  985. if ($analyses != null) {
  986. $is_varchar = ($analyses[$i][self::TYPES][$col_count] === self::VARCHAR);
  987. } else {
  988. $is_varchar = ! is_numeric($tables[$i][self::ROWS][$j][$k]);
  989. }
  990. /* Don't put quotes around NULL fields */
  991. if (! strcmp($tables[$i][self::ROWS][$j][$k], 'NULL')) {
  992. $is_varchar = false;
  993. }
  994. $tempSQLStr .= (($is_varchar) ? "'" : "");
  995. $tempSQLStr .= $GLOBALS['dbi']->escapeString(
  996. (string) $tables[$i][self::ROWS][$j][$k]
  997. );
  998. $tempSQLStr .= (($is_varchar) ? "'" : "");
  999. }
  1000. if ($k != ($num_cols - 1)) {
  1001. $tempSQLStr .= ", ";
  1002. }
  1003. if ($col_count == ($num_cols - 1)) {
  1004. $col_count = 0;
  1005. } else {
  1006. $col_count++;
  1007. }
  1008. /* Delete the cell after we are done with it */
  1009. unset($tables[$i][self::ROWS][$j][$k]);
  1010. }
  1011. $tempSQLStr .= ")";
  1012. if ($j != ($num_rows - 1)) {
  1013. $tempSQLStr .= ",\n ";
  1014. }
  1015. $col_count = 0;
  1016. /* Delete the row after we are done with it */
  1017. unset($tables[$i][self::ROWS][$j]);
  1018. }
  1019. $tempSQLStr .= ";";
  1020. /**
  1021. * Each SQL statement is executed immediately
  1022. * after it is formed so that we don't have
  1023. * to store them in a (possibly large) buffer
  1024. */
  1025. self::runQuery($tempSQLStr, $tempSQLStr, $sql_data);
  1026. }
  1027. /* No longer needed */
  1028. unset($tempSQLStr);
  1029. /**
  1030. * A work in progress
  1031. */
  1032. /* Add the viewable structures from $additional_sql
  1033. * to $tables so they are also displayed
  1034. */
  1035. $view_pattern = '@VIEW `[^`]+`\.`([^`]+)@';
  1036. $table_pattern = '@CREATE TABLE IF NOT EXISTS `([^`]+)`@';
  1037. /* Check a third pattern to make sure its not a "USE `db_name`;" statement */
  1038. $regs = array();
  1039. $inTables = false;
  1040. $additional_sql_len = is_null($additional_sql) ? 0 : count($additional_sql);
  1041. for ($i = 0; $i < $additional_sql_len; ++$i) {
  1042. preg_match($view_pattern, $additional_sql[$i], $regs);
  1043. if (count($regs) == 0) {
  1044. preg_match($table_pattern, $additional_sql[$i], $regs);
  1045. }
  1046. if (count($regs)) {
  1047. for ($n = 0; $n < $num_tables; ++$n) {
  1048. if (! strcmp($regs[1], $tables[$n][self::TBL_NAME])) {
  1049. $inTables = true;
  1050. break;
  1051. }
  1052. }
  1053. if (! $inTables) {
  1054. $tables[] = array(self::TBL_NAME => $regs[1]);
  1055. }
  1056. }
  1057. /* Reset the array */
  1058. $regs = array();
  1059. $inTables = false;
  1060. }
  1061. $params = array('db' => (string)$db_name);
  1062. $db_url = 'db_structure.php' . Url::getCommon($params);
  1063. $db_ops_url = 'db_operations.php' . Url::getCommon($params);
  1064. $message = '<br /><br />';
  1065. $message .= '<strong>' . __(
  1066. 'The following structures have either been created or altered. Here you can:'
  1067. ) . '</strong><br />';
  1068. $message .= '<ul><li>' . __(
  1069. "View a structure's contents by clicking on its name."
  1070. ) . '</li>';
  1071. $message .= '<li>' . __(
  1072. 'Change any of its settings by clicking the corresponding "Options" link.'
  1073. ) . '</li>';
  1074. $message .= '<li>' . __('Edit structure by following the "Structure" link.')
  1075. . '</li>';
  1076. $message .= sprintf(
  1077. '<br /><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">'
  1078. . __('Options') . '</a>)</li>',
  1079. $db_url,
  1080. sprintf(
  1081. __('Go to database: %s'),
  1082. htmlspecialchars(Util::backquote($db_name))
  1083. ),
  1084. htmlspecialchars($db_name),
  1085. $db_ops_url,
  1086. sprintf(
  1087. __('Edit settings for %s'),
  1088. htmlspecialchars(Util::backquote($db_name))
  1089. )
  1090. );
  1091. $message .= '<ul>';
  1092. unset($params);
  1093. $num_tables = count($tables);
  1094. for ($i = 0; $i < $num_tables; ++$i) {
  1095. $params = array(
  1096. 'db' => (string) $db_name,
  1097. 'table' => (string) $tables[$i][self::TBL_NAME]
  1098. );
  1099. $tbl_url = 'sql.php' . Url::getCommon($params);
  1100. $tbl_struct_url = 'tbl_structure.php' . Url::getCommon($params);
  1101. $tbl_ops_url = 'tbl_operations.php' . Url::getCommon($params);
  1102. unset($params);
  1103. $_table = new Table($tables[$i][self::TBL_NAME], $db_name);
  1104. if (! $_table->isView()) {
  1105. $message .= sprintf(
  1106. '<li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __(
  1107. 'Structure'
  1108. ) . '</a>) (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
  1109. $tbl_url,
  1110. sprintf(
  1111. __('Go to table: %s'),
  1112. htmlspecialchars(
  1113. Util::backquote($tables[$i][self::TBL_NAME])
  1114. )
  1115. ),
  1116. htmlspecialchars($tables[$i][self::TBL_NAME]),
  1117. $tbl_struct_url,
  1118. sprintf(
  1119. __('Structure of %s'),
  1120. htmlspecialchars(
  1121. Util::backquote($tables[$i][self::TBL_NAME])
  1122. )
  1123. ),
  1124. $tbl_ops_url,
  1125. sprintf(
  1126. __('Edit settings for %s'),
  1127. htmlspecialchars(
  1128. Util::backquote($tables[$i][self::TBL_NAME])
  1129. )
  1130. )
  1131. );
  1132. } else {
  1133. $message .= sprintf(
  1134. '<li><a href="%s" title="%s">%s</a></li>',
  1135. $tbl_url,
  1136. sprintf(
  1137. __('Go to view: %s'),
  1138. htmlspecialchars(
  1139. Util::backquote($tables[$i][self::TBL_NAME])
  1140. )
  1141. ),
  1142. htmlspecialchars($tables[$i][self::TBL_NAME])
  1143. );
  1144. }
  1145. }
  1146. $message .= '</ul></ul>';
  1147. global $import_notice;
  1148. $import_notice = $message;
  1149. unset($tables);
  1150. }
  1151. /**
  1152. * Stops the import on (mostly upload/file related) error
  1153. *
  1154. * @param Message $error_message The error message
  1155. *
  1156. * @return void
  1157. * @access public
  1158. *
  1159. */
  1160. public static function stop(Message $error_message)
  1161. {
  1162. global $import_handle, $file_to_unlink;
  1163. // Close open handles
  1164. if ($import_handle !== false && $import_handle !== null) {
  1165. $import_handle->close();
  1166. }
  1167. // Delete temporary file
  1168. if ($file_to_unlink != '') {
  1169. unlink($file_to_unlink);
  1170. }
  1171. $msg = $error_message->getDisplay();
  1172. $_SESSION['Import_message']['message'] = $msg;
  1173. $response = Response::getInstance();
  1174. $response->setRequestStatus(false);
  1175. $response->addJSON('message', Message::error($msg));
  1176. exit;
  1177. }
  1178. /**
  1179. * Handles request for Simulation of UPDATE/DELETE queries.
  1180. *
  1181. * @return void
  1182. */
  1183. public static function handleSimulateDmlRequest()
  1184. {
  1185. $response = Response::getInstance();
  1186. $error = false;
  1187. $error_msg = __('Only single-table UPDATE and DELETE queries can be simulated.');
  1188. $sql_delimiter = $_POST['sql_delimiter'];
  1189. $sql_data = array();
  1190. $queries = explode($sql_delimiter, $GLOBALS['sql_query']);
  1191. foreach ($queries as $sql_query) {
  1192. if (empty($sql_query)) {
  1193. continue;
  1194. }
  1195. // Parsing the query.
  1196. $parser = new Parser($sql_query);
  1197. if (empty($parser->statements[0])) {
  1198. continue;
  1199. }
  1200. $statement = $parser->statements[0];
  1201. $analyzed_sql_results = array(
  1202. 'query' => $sql_query,
  1203. 'parser' => $parser,
  1204. 'statement' => $statement,
  1205. );
  1206. if ((!(($statement instanceof UpdateStatement)
  1207. || ($statement instanceof DeleteStatement)))
  1208. || (!empty($statement->join))
  1209. ) {
  1210. $error = $error_msg;
  1211. break;
  1212. }
  1213. $tables = Query::getTables($statement);
  1214. if (count($tables) > 1) {
  1215. $error = $error_msg;
  1216. break;
  1217. }
  1218. // Get the matched rows for the query.
  1219. $result = self::getMatchedRows($analyzed_sql_results);
  1220. if (! $error = $GLOBALS['dbi']->getError()) {
  1221. $sql_data[] = $result;
  1222. } else {
  1223. break;
  1224. }
  1225. }
  1226. if ($error) {
  1227. $message = Message::rawError($error);
  1228. $response->addJSON('message', $message);
  1229. $response->addJSON('sql_data', false);
  1230. } else {
  1231. $response->addJSON('sql_data', $sql_data);
  1232. }
  1233. }
  1234. /**
  1235. * Find the matching rows for UPDATE/DELETE query.
  1236. *
  1237. * @param array $analyzed_sql_results Analyzed SQL results from parser.
  1238. *
  1239. * @return mixed
  1240. */
  1241. public static function getMatchedRows(array $analyzed_sql_results = array())
  1242. {
  1243. $statement = $analyzed_sql_results['statement'];
  1244. $matched_row_query = '';
  1245. if ($statement instanceof DeleteStatement) {
  1246. $matched_row_query = self::getSimulatedDeleteQuery($analyzed_sql_results);
  1247. } elseif ($statement instanceof UpdateStatement) {
  1248. $matched_row_query = self::getSimulatedUpdateQuery($analyzed_sql_results);
  1249. }
  1250. // Execute the query and get the number of matched rows.
  1251. $matched_rows = self::executeMatchedRowQuery($matched_row_query);
  1252. // URL to matched rows.
  1253. $_url_params = array(
  1254. 'db' => $GLOBALS['db'],
  1255. 'sql_query' => $matched_row_query
  1256. );
  1257. $matched_rows_url = 'sql.php' . Url::getCommon($_url_params);
  1258. return array(
  1259. 'sql_query' => Util::formatSql($analyzed_sql_results['query']),
  1260. 'matched_rows' => $matched_rows,
  1261. 'matched_rows_url' => $matched_rows_url
  1262. );
  1263. }
  1264. /**
  1265. * Transforms a UPDATE query into SELECT statement.
  1266. *
  1267. * @param array $analyzed_sql_results Analyzed SQL results from parser.
  1268. *
  1269. * @return string SQL query
  1270. */
  1271. public static function getSimulatedUpdateQuery(array $analyzed_sql_results)
  1272. {
  1273. $table_references = Query::getTables(
  1274. $analyzed_sql_results['statement']
  1275. );
  1276. $where = Query::getClause(
  1277. $analyzed_sql_results['statement'],
  1278. $analyzed_sql_results['parser']->list,
  1279. 'WHERE'
  1280. );
  1281. if (empty($where)) {
  1282. $where = '1';
  1283. }
  1284. $columns = array();
  1285. $diff = array();
  1286. foreach ($analyzed_sql_results['statement']->set as $set) {
  1287. $columns[] = $set->column;
  1288. $not_equal_operator = ' <> ';
  1289. if(strtoupper($set->value) == 'NULL'){
  1290. $not_equal_operator = ' IS NOT ';
  1291. }
  1292. $diff[] = $set->column . $not_equal_operator . $set->value;
  1293. }
  1294. if (!empty($diff)) {
  1295. $where .= ' AND (' . implode(' OR ', $diff) . ')';
  1296. }
  1297. $order_and_limit = '';
  1298. if (!empty($analyzed_sql_results['statement']->order)) {
  1299. $order_and_limit .= ' ORDER BY ' . Query::getClause(
  1300. $analyzed_sql_results['statement'],
  1301. $analyzed_sql_results['parser']->list,
  1302. 'ORDER BY'
  1303. );
  1304. }
  1305. if (!empty($analyzed_sql_results['statement']->limit)) {
  1306. $order_and_limit .= ' LIMIT ' . Query::getClause(
  1307. $analyzed_sql_results['statement'],
  1308. $analyzed_sql_results['parser']->list,
  1309. 'LIMIT'
  1310. );
  1311. }
  1312. return 'SELECT ' . implode(', ', $columns) .
  1313. ' FROM ' . implode(', ', $table_references) .
  1314. ' WHERE ' . $where . $order_and_limit;
  1315. }
  1316. /**
  1317. * Transforms a DELETE query into SELECT statement.
  1318. *
  1319. * @param array $analyzed_sql_results Analyzed SQL results from parser.
  1320. *
  1321. * @return string SQL query
  1322. */
  1323. public static function getSimulatedDeleteQuery(array $analyzed_sql_results)
  1324. {
  1325. $table_references = Query::getTables(
  1326. $analyzed_sql_results['statement']
  1327. );
  1328. $where = Query::getClause(
  1329. $analyzed_sql_results['statement'],
  1330. $analyzed_sql_results['parser']->list,
  1331. 'WHERE'
  1332. );
  1333. if (empty($where)) {
  1334. $where = '1';
  1335. }
  1336. $order_and_limit = '';
  1337. if (!empty($analyzed_sql_results['statement']->order)) {
  1338. $order_and_limit .= ' ORDER BY ' . Query::getClause(
  1339. $analyzed_sql_results['statement'],
  1340. $analyzed_sql_results['parser']->list,
  1341. 'ORDER BY'
  1342. );
  1343. }
  1344. if (!empty($analyzed_sql_results['statement']->limit)) {
  1345. $order_and_limit .= ' LIMIT ' . Query::getClause(
  1346. $analyzed_sql_results['statement'],
  1347. $analyzed_sql_results['parser']->list,
  1348. 'LIMIT'
  1349. );
  1350. }
  1351. return 'SELECT * FROM ' . implode(', ', $table_references) .
  1352. ' WHERE ' . $where . $order_and_limit;
  1353. }
  1354. /**
  1355. * Executes the matched_row_query and returns the resultant row count.
  1356. *
  1357. * @param string $matched_row_query SQL query
  1358. *
  1359. * @return integer Number of rows returned
  1360. */
  1361. public static function executeMatchedRowQuery($matched_row_query)
  1362. {
  1363. $GLOBALS['dbi']->selectDb($GLOBALS['db']);
  1364. // Execute the query.
  1365. $result = $GLOBALS['dbi']->tryQuery($matched_row_query);
  1366. // Count the number of rows in the result set.
  1367. $result = $GLOBALS['dbi']->numRows($result);
  1368. return $result;
  1369. }
  1370. /**
  1371. * Handles request for ROLLBACK.
  1372. *
  1373. * @param string $sql_query SQL query(s)
  1374. *
  1375. * @return void
  1376. */
  1377. public static function handleRollbackRequest($sql_query)
  1378. {
  1379. $sql_delimiter = $_POST['sql_delimiter'];
  1380. $queries = explode($sql_delimiter, $sql_query);
  1381. $error = false;
  1382. $error_msg = __(
  1383. 'Only INSERT, UPDATE, DELETE and REPLACE '
  1384. . 'SQL queries containing transactional engine tables can be rolled back.'
  1385. );
  1386. foreach ($queries as $sql_query) {
  1387. if (empty($sql_query)) {
  1388. continue;
  1389. }
  1390. // Check each query for ROLLBACK support.
  1391. if (! self::checkIfRollbackPossible($sql_query)) {
  1392. $global_error = $GLOBALS['dbi']->getError();
  1393. if ($global_error) {
  1394. $error = $global_error;
  1395. } else {
  1396. $error = $error_msg;
  1397. }
  1398. break;
  1399. }
  1400. }
  1401. if ($error) {
  1402. unset($_POST['rollback_query']);
  1403. $response = Response::getInstance();
  1404. $message = Message::rawError($error);
  1405. $response->addJSON('message', $message);
  1406. exit;
  1407. } else {
  1408. // If everything fine, START a transaction.
  1409. $GLOBALS['dbi']->query('START TRANSACTION');
  1410. }
  1411. }
  1412. /**
  1413. * Checks if ROLLBACK is possible for a SQL query or not.
  1414. *
  1415. * @param string $sql_query SQL query
  1416. *
  1417. * @return bool
  1418. */
  1419. public static function checkIfRollbackPossible($sql_query)
  1420. {
  1421. $parser = new Parser($sql_query);
  1422. if (empty($parser->statements[0])) {
  1423. return false;
  1424. }
  1425. $statement = $parser->statements[0];
  1426. // Check if query is supported.
  1427. if (!(($statement instanceof InsertStatement)
  1428. || ($statement instanceof UpdateStatement)
  1429. || ($statement instanceof DeleteStatement)
  1430. || ($statement instanceof ReplaceStatement))
  1431. ) {
  1432. return false;
  1433. }
  1434. // Get table_references from the query.
  1435. $tables = Query::getTables($statement);
  1436. // Check if each table is 'InnoDB'.
  1437. foreach ($tables as $table) {
  1438. if (! self::isTableTransactional($table)) {
  1439. return false;
  1440. }
  1441. }
  1442. return true;
  1443. }
  1444. /**
  1445. * Checks if a table is 'InnoDB' or not.
  1446. *
  1447. * @param string $table Table details
  1448. *
  1449. * @return bool
  1450. */
  1451. public static function isTableTransactional($table)
  1452. {
  1453. $table = explode('.', $table);
  1454. if (count($table) == 2) {
  1455. $db = Util::unQuote($table[0]);
  1456. $table = Util::unQuote($table[1]);
  1457. } else {
  1458. $db = $GLOBALS['db'];
  1459. $table = Util::unQuote($table[0]);
  1460. }
  1461. // Query to check if table exists.
  1462. $check_table_query = 'SELECT * FROM ' . Util::backquote($db)
  1463. . '.' . Util::backquote($table) . ' '
  1464. . 'LIMIT 1';
  1465. $result = $GLOBALS['dbi']->tryQuery($check_table_query);
  1466. if (! $result) {
  1467. return false;
  1468. }
  1469. // List of Transactional Engines.
  1470. $transactional_engines = array(
  1471. 'INNODB',
  1472. 'FALCON',
  1473. 'NDB',
  1474. 'INFINIDB',
  1475. 'TOKUDB',
  1476. 'XTRADB',
  1477. 'SEQUENCE',
  1478. 'BDB'
  1479. );
  1480. // Query to check if table is 'Transactional'.
  1481. $check_query = 'SELECT `ENGINE` FROM `information_schema`.`tables` '
  1482. . 'WHERE `table_name` = "' . $table . '" '
  1483. . 'AND `table_schema` = "' . $db . '" '
  1484. . 'AND UPPER(`engine`) IN ("'
  1485. . implode('", "', $transactional_engines)
  1486. . '")';
  1487. $result = $GLOBALS['dbi']->tryQuery($check_query);
  1488. return $GLOBALS['dbi']->numRows($result) == 1;
  1489. }
  1490. }