PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/libraries/classes/Controllers/ImportController.php

http://github.com/phpmyadmin/phpmyadmin
PHP | 840 lines | 625 code | 126 blank | 89 comment | 118 complexity | 33e29d8d0545fa00b1c3743ab4959460 MD5 | raw file
Possible License(s): GPL-2.0, MIT, LGPL-3.0
  1. <?php
  2. declare(strict_types=1);
  3. namespace PhpMyAdmin\Controllers;
  4. use PhpMyAdmin\Bookmark;
  5. use PhpMyAdmin\Console;
  6. use PhpMyAdmin\Core;
  7. use PhpMyAdmin\DatabaseInterface;
  8. use PhpMyAdmin\Encoding;
  9. use PhpMyAdmin\File;
  10. use PhpMyAdmin\Html\Generator;
  11. use PhpMyAdmin\Import;
  12. use PhpMyAdmin\Message;
  13. use PhpMyAdmin\ParseAnalyze;
  14. use PhpMyAdmin\Plugins;
  15. use PhpMyAdmin\Plugins\ImportPlugin;
  16. use PhpMyAdmin\ResponseRenderer;
  17. use PhpMyAdmin\Sql;
  18. use PhpMyAdmin\Template;
  19. use PhpMyAdmin\Url;
  20. use PhpMyAdmin\Util;
  21. use PhpMyAdmin\Utils\ForeignKey;
  22. use Throwable;
  23. use function __;
  24. use function _ngettext;
  25. use function htmlspecialchars;
  26. use function in_array;
  27. use function ini_get;
  28. use function ini_set;
  29. use function intval;
  30. use function is_array;
  31. use function is_link;
  32. use function is_numeric;
  33. use function is_uploaded_file;
  34. use function mb_strlen;
  35. use function mb_strtolower;
  36. use function preg_match;
  37. use function preg_quote;
  38. use function preg_replace;
  39. use function sprintf;
  40. use function strlen;
  41. use function substr;
  42. use function time;
  43. use function trim;
  44. final class ImportController extends AbstractController
  45. {
  46. /** @var Import */
  47. private $import;
  48. /** @var Sql */
  49. private $sql;
  50. /** @var DatabaseInterface */
  51. private $dbi;
  52. public function __construct(
  53. ResponseRenderer $response,
  54. Template $template,
  55. Import $import,
  56. Sql $sql,
  57. DatabaseInterface $dbi
  58. ) {
  59. parent::__construct($response, $template);
  60. $this->import = $import;
  61. $this->sql = $sql;
  62. $this->dbi = $dbi;
  63. }
  64. public function __invoke(): void
  65. {
  66. global $cfg, $collation_connection, $db, $import_type, $table, $goto, $display_query;
  67. global $format, $local_import_file, $ajax_reload, $import_text, $sql_query, $message, $errorUrl, $urlParams;
  68. global $memory_limit, $read_limit, $finished, $offset, $charset_conversion, $charset_of_file;
  69. global $timestamp, $maximum_time, $timeout_passed, $import_file, $go_sql, $sql_file, $error, $max_sql_len, $msg;
  70. global $sql_query_disabled, $executed_queries, $run_query, $reset_charset, $bookmark_created;
  71. global $result, $import_file_name, $sql_data, $import_notice, $read_multiply, $my_die, $active_page;
  72. global $show_as_php, $reload, $charset_connection, $is_js_confirmed, $MAX_FILE_SIZE, $message_to_show;
  73. global $noplugin, $skip_queries;
  74. $charset_of_file = $_POST['charset_of_file'] ?? null;
  75. $format = $_POST['format'] ?? '';
  76. $import_type = $_POST['import_type'] ?? null;
  77. $is_js_confirmed = $_POST['is_js_confirmed'] ?? null;
  78. $MAX_FILE_SIZE = $_POST['MAX_FILE_SIZE'] ?? null;
  79. $message_to_show = $_POST['message_to_show'] ?? null;
  80. $noplugin = $_POST['noplugin'] ?? null;
  81. $skip_queries = $_POST['skip_queries'] ?? null;
  82. $local_import_file = $_POST['local_import_file'] ?? null;
  83. $show_as_php = $_POST['show_as_php'] ?? null;
  84. // If there is a request to 'Simulate DML'.
  85. if (isset($_POST['simulate_dml'])) {
  86. $this->import->handleSimulateDmlRequest();
  87. return;
  88. }
  89. // If it's a refresh console bookmarks request
  90. if (isset($_GET['console_bookmark_refresh'])) {
  91. $this->response->addJSON(
  92. 'console_message_bookmark',
  93. Console::getBookmarkContent()
  94. );
  95. return;
  96. }
  97. // If it's a console bookmark add request
  98. if (isset($_POST['console_bookmark_add'])) {
  99. if (! isset($_POST['label'], $_POST['db'], $_POST['bookmark_query'], $_POST['shared'])) {
  100. $this->response->addJSON('message', __('Incomplete params'));
  101. return;
  102. }
  103. $cfgBookmark = Bookmark::getParams($cfg['Server']['user']);
  104. if (! is_array($cfgBookmark)) {
  105. $cfgBookmark = [];
  106. }
  107. $bookmarkFields = [
  108. 'bkm_database' => $_POST['db'],
  109. 'bkm_user' => $cfgBookmark['user'],
  110. 'bkm_sql_query' => $_POST['bookmark_query'],
  111. 'bkm_label' => $_POST['label'],
  112. ];
  113. $isShared = ($_POST['shared'] === 'true');
  114. $bookmark = Bookmark::createBookmark($this->dbi, $cfg['Server']['user'], $bookmarkFields, $isShared);
  115. if ($bookmark !== false && $bookmark->save()) {
  116. $this->response->addJSON('message', __('Succeeded'));
  117. $this->response->addJSON('data', $bookmarkFields);
  118. $this->response->addJSON('isShared', $isShared);
  119. } else {
  120. $this->response->addJSON('message', __('Failed'));
  121. }
  122. return;
  123. }
  124. // reset import messages for ajax request
  125. $_SESSION['Import_message']['message'] = null;
  126. $_SESSION['Import_message']['go_back_url'] = null;
  127. // default values
  128. $reload = false;
  129. // Use to identify current cycle is executing
  130. // a multiquery statement or stored routine
  131. if (! isset($_SESSION['is_multi_query'])) {
  132. $_SESSION['is_multi_query'] = false;
  133. }
  134. $ajax_reload = [];
  135. $import_text = '';
  136. // Are we just executing plain query or sql file?
  137. // (eg. non import, but query box/window run)
  138. if (! empty($sql_query)) {
  139. // apply values for parameters
  140. if (! empty($_POST['parameterized']) && ! empty($_POST['parameters']) && is_array($_POST['parameters'])) {
  141. $parameters = $_POST['parameters'];
  142. foreach ($parameters as $parameter => $replacement) {
  143. $replacementValue = $this->dbi->escapeString($replacement);
  144. if (! is_numeric($replacementValue)) {
  145. $replacementValue = '\'' . $replacementValue . '\'';
  146. }
  147. $quoted = preg_quote($parameter, '/');
  148. // making sure that :param does not apply values to :param1
  149. $sql_query = preg_replace(
  150. '/' . $quoted . '([^a-zA-Z0-9_])/',
  151. $replacementValue . '${1}',
  152. $sql_query
  153. );
  154. // for parameters the appear at the end of the string
  155. $sql_query = preg_replace('/' . $quoted . '$/', $replacementValue, $sql_query);
  156. }
  157. }
  158. // run SQL query
  159. $import_text = $sql_query;
  160. $import_type = 'query';
  161. $format = 'sql';
  162. $_SESSION['sql_from_query_box'] = true;
  163. // If there is a request to ROLLBACK when finished.
  164. if (isset($_POST['rollback_query'])) {
  165. $this->import->handleRollbackRequest($import_text);
  166. }
  167. // refresh navigation and main panels
  168. if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
  169. $reload = true;
  170. $ajax_reload['reload'] = true;
  171. }
  172. // refresh navigation panel only
  173. if (preg_match('/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
  174. $ajax_reload['reload'] = true;
  175. }
  176. // do a dynamic reload if table is RENAMED
  177. // (by sending the instruction to the AJAX response handler)
  178. if (preg_match('/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i', $sql_query, $rename_table_names)) {
  179. $ajax_reload['reload'] = true;
  180. $ajax_reload['table_name'] = Util::unQuote($rename_table_names[2]);
  181. }
  182. $sql_query = '';
  183. } elseif (! empty($sql_file)) {
  184. // run uploaded SQL file
  185. $import_file = $sql_file;
  186. $import_type = 'queryfile';
  187. $format = 'sql';
  188. unset($sql_file);
  189. } elseif (! empty($_POST['id_bookmark'])) {
  190. // run bookmark
  191. $import_type = 'query';
  192. $format = 'sql';
  193. }
  194. // If we didn't get any parameters, either user called this directly, or
  195. // upload limit has been reached, let's assume the second possibility.
  196. if ($_POST == [] && $_GET == []) {
  197. $message = Message::error(
  198. __(
  199. 'You probably tried to upload a file that is too large. Please refer ' .
  200. 'to %sdocumentation%s for a workaround for this limit.'
  201. )
  202. );
  203. $message->addParam('[doc@faq1-16]');
  204. $message->addParam('[/doc]');
  205. // so we can obtain the message
  206. $_SESSION['Import_message']['message'] = $message->getDisplay();
  207. $_SESSION['Import_message']['go_back_url'] = $goto;
  208. $this->response->setRequestStatus(false);
  209. $this->response->addJSON('message', $message);
  210. return; // the footer is displayed automatically
  211. }
  212. // Add console message id to response output
  213. if (isset($_POST['console_message_id'])) {
  214. $this->response->addJSON('console_message_id', $_POST['console_message_id']);
  215. }
  216. /**
  217. * Sets globals from $_POST patterns, for import plugins
  218. * We only need to load the selected plugin
  219. */
  220. if (! in_array($format, ['csv', 'ldi', 'mediawiki', 'ods', 'shp', 'sql', 'xml'])) {
  221. // this should not happen for a normal user
  222. // but only during an attack
  223. Core::fatalError('Incorrect format parameter');
  224. }
  225. $post_patterns = [
  226. '/^force_file_/',
  227. '/^' . $format . '_/',
  228. ];
  229. Core::setPostAsGlobal($post_patterns);
  230. // Check needed parameters
  231. Util::checkParameters(['import_type', 'format']);
  232. // We don't want anything special in format
  233. $format = Core::securePath($format);
  234. if (strlen($table) > 0 && strlen($db) > 0) {
  235. $urlParams = [
  236. 'db' => $db,
  237. 'table' => $table,
  238. ];
  239. } elseif (strlen($db) > 0) {
  240. $urlParams = ['db' => $db];
  241. } else {
  242. $urlParams = [];
  243. }
  244. // Create error and goto url
  245. if ($import_type === 'table') {
  246. $goto = Url::getFromRoute('/table/import');
  247. } elseif ($import_type === 'database') {
  248. $goto = Url::getFromRoute('/database/import');
  249. } elseif ($import_type === 'server') {
  250. $goto = Url::getFromRoute('/server/import');
  251. } elseif (empty($goto) || ! preg_match('@^index\.php$@i', $goto)) {
  252. if (strlen($table) > 0 && strlen($db) > 0) {
  253. $goto = Url::getFromRoute('/table/structure');
  254. } elseif (strlen($db) > 0) {
  255. $goto = Url::getFromRoute('/database/structure');
  256. } else {
  257. $goto = Url::getFromRoute('/server/sql');
  258. }
  259. }
  260. $errorUrl = $goto . Url::getCommon($urlParams, '&');
  261. $_SESSION['Import_message']['go_back_url'] = $errorUrl;
  262. if (strlen($db) > 0) {
  263. $this->dbi->selectDb($db);
  264. }
  265. Util::setTimeLimit();
  266. if (! empty($cfg['MemoryLimit'])) {
  267. ini_set('memory_limit', $cfg['MemoryLimit']);
  268. }
  269. $timestamp = time();
  270. if (isset($_POST['allow_interrupt'])) {
  271. $maximum_time = ini_get('max_execution_time');
  272. } else {
  273. $maximum_time = 0;
  274. }
  275. // set default values
  276. $timeout_passed = false;
  277. $error = false;
  278. $read_multiply = 1;
  279. $finished = false;
  280. $offset = 0;
  281. $max_sql_len = 0;
  282. $sql_query = '';
  283. $sql_query_disabled = false;
  284. $go_sql = false;
  285. $executed_queries = 0;
  286. $run_query = true;
  287. $charset_conversion = false;
  288. $reset_charset = false;
  289. $bookmark_created = false;
  290. $msg = 'Sorry an unexpected error happened!';
  291. /** @var mixed|bool $result */
  292. $result = false;
  293. // Bookmark Support: get a query back from bookmark if required
  294. if (! empty($_POST['id_bookmark'])) {
  295. $id_bookmark = (int) $_POST['id_bookmark'];
  296. switch ($_POST['action_bookmark']) {
  297. case 0: // bookmarked query that have to be run
  298. $bookmark = Bookmark::get(
  299. $this->dbi,
  300. $cfg['Server']['user'],
  301. $db,
  302. $id_bookmark,
  303. 'id',
  304. isset($_POST['action_bookmark_all'])
  305. );
  306. if (! $bookmark instanceof Bookmark) {
  307. break;
  308. }
  309. if (! empty($_POST['bookmark_variable'])) {
  310. $import_text = $bookmark->applyVariables($_POST['bookmark_variable']);
  311. } else {
  312. $import_text = $bookmark->getQuery();
  313. }
  314. // refresh navigation and main panels
  315. if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $import_text)) {
  316. $reload = true;
  317. $ajax_reload['reload'] = true;
  318. }
  319. // refresh navigation panel only
  320. if (preg_match('/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $import_text)) {
  321. $ajax_reload['reload'] = true;
  322. }
  323. break;
  324. case 1: // bookmarked query that have to be displayed
  325. $bookmark = Bookmark::get($this->dbi, $cfg['Server']['user'], $db, $id_bookmark);
  326. if (! $bookmark instanceof Bookmark) {
  327. break;
  328. }
  329. $import_text = $bookmark->getQuery();
  330. if ($this->response->isAjax()) {
  331. $message = Message::success(__('Showing bookmark'));
  332. $this->response->setRequestStatus($message->isSuccess());
  333. $this->response->addJSON('message', $message);
  334. $this->response->addJSON('sql_query', $import_text);
  335. $this->response->addJSON('action_bookmark', $_POST['action_bookmark']);
  336. return;
  337. } else {
  338. $run_query = false;
  339. }
  340. break;
  341. case 2: // bookmarked query that have to be deleted
  342. $bookmark = Bookmark::get($this->dbi, $cfg['Server']['user'], $db, $id_bookmark);
  343. if (! $bookmark instanceof Bookmark) {
  344. break;
  345. }
  346. $bookmark->delete();
  347. if ($this->response->isAjax()) {
  348. $message = Message::success(
  349. __('The bookmark has been deleted.')
  350. );
  351. $this->response->setRequestStatus($message->isSuccess());
  352. $this->response->addJSON('message', $message);
  353. $this->response->addJSON('action_bookmark', $_POST['action_bookmark']);
  354. $this->response->addJSON('id_bookmark', $id_bookmark);
  355. return;
  356. } else {
  357. $run_query = false;
  358. $error = true; // this is kind of hack to skip processing the query
  359. }
  360. break;
  361. }
  362. }
  363. // Do no run query if we show PHP code
  364. if (isset($show_as_php)) {
  365. $run_query = false;
  366. $go_sql = true;
  367. }
  368. // We can not read all at once, otherwise we can run out of memory
  369. $memory_limit = trim((string) ini_get('memory_limit'));
  370. // 2 MB as default
  371. if (empty($memory_limit)) {
  372. $memory_limit = 2 * 1024 * 1024;
  373. }
  374. // In case no memory limit we work on 10MB chunks
  375. if ($memory_limit === '-1') {
  376. $memory_limit = 10 * 1024 * 1024;
  377. }
  378. // Calculate value of the limit
  379. $memoryUnit = mb_strtolower(substr((string) $memory_limit, -1));
  380. if ($memoryUnit === 'm') {
  381. $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024;
  382. } elseif ($memoryUnit === 'k') {
  383. $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024;
  384. } elseif ($memoryUnit === 'g') {
  385. $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024 * 1024;
  386. } else {
  387. $memory_limit = (int) $memory_limit;
  388. }
  389. // Just to be sure, there might be lot of memory needed for uncompression
  390. $read_limit = $memory_limit / 8;
  391. // handle filenames
  392. if (isset($_FILES['import_file'])) {
  393. $import_file = $_FILES['import_file']['tmp_name'];
  394. $import_file_name = $_FILES['import_file']['name'];
  395. }
  396. if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
  397. // sanitize $local_import_file as it comes from a POST
  398. $local_import_file = Core::securePath($local_import_file);
  399. $import_file = Util::userDir((string) $cfg['UploadDir'])
  400. . $local_import_file;
  401. /*
  402. * Do not allow symlinks to avoid security issues
  403. * (user can create symlink to file they can not access,
  404. * but phpMyAdmin can).
  405. */
  406. if (@is_link($import_file)) {
  407. $import_file = 'none';
  408. }
  409. } elseif (empty($import_file) || ! is_uploaded_file($import_file)) {
  410. $import_file = 'none';
  411. }
  412. // Do we have file to import?
  413. if ($import_file !== 'none' && ! $error) {
  414. /**
  415. * Handle file compression
  416. */
  417. $importHandle = new File($import_file);
  418. $importHandle->checkUploadedFile();
  419. if ($importHandle->isError()) {
  420. /** @var Message $errorMessage */
  421. $errorMessage = $importHandle->getError();
  422. $importHandle->close();
  423. $_SESSION['Import_message']['message'] = $errorMessage->getDisplay();
  424. $this->response->setRequestStatus(false);
  425. $this->response->addJSON('message', $errorMessage->getDisplay());
  426. $this->response->addHTML($errorMessage->getDisplay());
  427. return;
  428. }
  429. $importHandle->setDecompressContent(true);
  430. $importHandle->open();
  431. if ($importHandle->isError()) {
  432. /** @var Message $errorMessage */
  433. $errorMessage = $importHandle->getError();
  434. $importHandle->close();
  435. $_SESSION['Import_message']['message'] = $errorMessage->getDisplay();
  436. $this->response->setRequestStatus(false);
  437. $this->response->addJSON('message', $errorMessage->getDisplay());
  438. $this->response->addHTML($errorMessage->getDisplay());
  439. return;
  440. }
  441. } elseif (! $error && (! isset($import_text) || empty($import_text))) {
  442. $message = Message::error(
  443. __(
  444. 'No data was received to import. Either no file name was ' .
  445. 'submitted, or the file size exceeded the maximum size permitted ' .
  446. 'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
  447. )
  448. );
  449. $_SESSION['Import_message']['message'] = $message->getDisplay();
  450. $this->response->setRequestStatus(false);
  451. $this->response->addJSON('message', $message->getDisplay());
  452. $this->response->addHTML($message->getDisplay());
  453. return;
  454. }
  455. // Convert the file's charset if necessary
  456. if (Encoding::isSupported() && isset($charset_of_file)) {
  457. if ($charset_of_file !== 'utf-8') {
  458. $charset_conversion = true;
  459. }
  460. } elseif (isset($charset_of_file) && $charset_of_file !== 'utf-8') {
  461. $this->dbi->query('SET NAMES \'' . $charset_of_file . '\'');
  462. // We can not show query in this case, it is in different charset
  463. $sql_query_disabled = true;
  464. $reset_charset = true;
  465. }
  466. // Something to skip? (because timeout has passed)
  467. if (! $error && isset($_POST['skip'])) {
  468. $original_skip = $skip = intval($_POST['skip']);
  469. while ($skip > 0 && ! $finished) {
  470. $this->import->getNextChunk($importHandle ?? null, $skip < $read_limit ? $skip : $read_limit);
  471. // Disable read progressivity, otherwise we eat all memory!
  472. $read_multiply = 1;
  473. $skip -= $read_limit;
  474. }
  475. unset($skip);
  476. }
  477. // This array contain the data like number of valid sql queries in the statement
  478. // and complete valid sql statement (which affected for rows)
  479. $sql_data = [
  480. 'valid_sql' => [],
  481. 'valid_queries' => 0,
  482. ];
  483. if (! $error) {
  484. /**
  485. * @var ImportPlugin $import_plugin
  486. */
  487. $import_plugin = Plugins::getPlugin('import', $format, $import_type);
  488. if ($import_plugin == null) {
  489. $message = Message::error(
  490. __('Could not load import plugins, please check your installation!')
  491. );
  492. $_SESSION['Import_message']['message'] = $message->getDisplay();
  493. $this->response->setRequestStatus(false);
  494. $this->response->addJSON('message', $message->getDisplay());
  495. $this->response->addHTML($message->getDisplay());
  496. return;
  497. }
  498. // Do the real import
  499. $default_fk_check = ForeignKey::handleDisableCheckInit();
  500. try {
  501. $import_plugin->doImport($importHandle ?? null, $sql_data);
  502. ForeignKey::handleDisableCheckCleanup($default_fk_check);
  503. } catch (Throwable $e) {
  504. ForeignKey::handleDisableCheckCleanup($default_fk_check);
  505. throw $e;
  506. }
  507. }
  508. if (isset($importHandle)) {
  509. $importHandle->close();
  510. }
  511. // Reset charset back, if we did some changes
  512. if ($reset_charset) {
  513. $this->dbi->query('SET CHARACTER SET ' . $charset_connection);
  514. $this->dbi->setCollation($collation_connection);
  515. }
  516. // Show correct message
  517. if (! empty($id_bookmark) && $_POST['action_bookmark'] == 2) {
  518. $message = Message::success(__('The bookmark has been deleted.'));
  519. $display_query = $import_text;
  520. $error = false; // unset error marker, it was used just to skip processing
  521. } elseif (! empty($id_bookmark) && $_POST['action_bookmark'] == 1) {
  522. $message = Message::notice(__('Showing bookmark'));
  523. } elseif ($bookmark_created) {
  524. $special_message = '[br]' . sprintf(
  525. __('Bookmark %s has been created.'),
  526. htmlspecialchars($_POST['bkm_label'])
  527. );
  528. } elseif ($finished && ! $error) {
  529. // Do not display the query with message, we do it separately
  530. $display_query = ';';
  531. if ($import_type !== 'query') {
  532. $message = Message::success(
  533. '<em>'
  534. . _ngettext(
  535. 'Import has been successfully finished, %d query executed.',
  536. 'Import has been successfully finished, %d queries executed.',
  537. $executed_queries
  538. )
  539. . '</em>'
  540. );
  541. $message->addParam($executed_queries);
  542. if (! empty($import_notice)) {
  543. $message->addHtml($import_notice);
  544. }
  545. if (! empty($local_import_file)) {
  546. $message->addText('(' . $local_import_file . ')');
  547. } else {
  548. $message->addText('(' . $_FILES['import_file']['name'] . ')');
  549. }
  550. }
  551. }
  552. // Did we hit timeout? Tell it user.
  553. if ($timeout_passed) {
  554. $urlParams['timeout_passed'] = '1';
  555. $urlParams['offset'] = $offset;
  556. if (isset($local_import_file)) {
  557. $urlParams['local_import_file'] = $local_import_file;
  558. }
  559. $importUrl = $errorUrl = $goto . Url::getCommon($urlParams, '&');
  560. $message = Message::error(
  561. __(
  562. 'Script timeout passed, if you want to finish import,'
  563. . ' please %sresubmit the same file%s and import will resume.'
  564. )
  565. );
  566. $message->addParamHtml('<a href="' . $importUrl . '">');
  567. $message->addParamHtml('</a>');
  568. if ($offset == 0 || (isset($original_skip) && $original_skip == $offset)) {
  569. $message->addText(
  570. __(
  571. 'However on last run no data has been parsed,'
  572. . ' this usually means phpMyAdmin won\'t be able to'
  573. . ' finish this import unless you increase php time limits.'
  574. )
  575. );
  576. }
  577. }
  578. // if there is any message, copy it into $_SESSION as well,
  579. // so we can obtain it by AJAX call
  580. if (isset($message)) {
  581. $_SESSION['Import_message']['message'] = $message->getDisplay();
  582. }
  583. // Parse and analyze the query, for correct db and table name
  584. // in case of a query typed in the query window
  585. // (but if the query is too large, in case of an imported file, the parser
  586. // can choke on it so avoid parsing)
  587. $sqlLength = mb_strlen($sql_query);
  588. if ($sqlLength <= $cfg['MaxCharactersInDisplayedSQL']) {
  589. [
  590. $analyzed_sql_results,
  591. $db,
  592. $table_from_sql,
  593. ] = ParseAnalyze::sqlQuery($sql_query, $db);
  594. $reload = $analyzed_sql_results['reload'];
  595. $offset = $analyzed_sql_results['offset'];
  596. if ($table != $table_from_sql && ! empty($table_from_sql)) {
  597. $table = $table_from_sql;
  598. }
  599. }
  600. // There was an error?
  601. if (isset($my_die)) {
  602. foreach ($my_die as $key => $die) {
  603. Generator::mysqlDie($die['error'], $die['sql'], false, $errorUrl, $error);
  604. }
  605. }
  606. if ($go_sql) {
  607. if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
  608. $_SESSION['is_multi_query'] = true;
  609. $sql_queries = $sql_data['valid_sql'];
  610. } else {
  611. $sql_queries = [$sql_query];
  612. }
  613. $html_output = '';
  614. foreach ($sql_queries as $sql_query) {
  615. // parse sql query
  616. [
  617. $analyzed_sql_results,
  618. $db,
  619. $table_from_sql,
  620. ] = ParseAnalyze::sqlQuery($sql_query, $db);
  621. $offset = $analyzed_sql_results['offset'];
  622. $reload = $analyzed_sql_results['reload'];
  623. // Check if User is allowed to issue a 'DROP DATABASE' Statement
  624. if (
  625. $this->sql->hasNoRightsToDropDatabase(
  626. $analyzed_sql_results,
  627. $cfg['AllowUserDropDatabase'],
  628. $this->dbi->isSuperUser()
  629. )
  630. ) {
  631. Generator::mysqlDie(
  632. __('"DROP DATABASE" statements are disabled.'),
  633. '',
  634. false,
  635. $_SESSION['Import_message']['go_back_url']
  636. );
  637. return;
  638. }
  639. if ($table != $table_from_sql && ! empty($table_from_sql)) {
  640. $table = $table_from_sql;
  641. }
  642. $html_output .= $this->sql->executeQueryAndGetQueryResponse(
  643. $analyzed_sql_results, // analyzed_sql_results
  644. false, // is_gotofile
  645. $db, // db
  646. $table, // table
  647. null, // find_real_end
  648. null, // sql_query_for_bookmark - see below
  649. null, // extra_data
  650. null, // message_to_show
  651. null, // sql_data
  652. $goto, // goto
  653. null, // disp_query
  654. null, // disp_message
  655. $sql_query, // sql_query
  656. null // complete_query
  657. );
  658. }
  659. // sql_query_for_bookmark is not included in Sql::executeQueryAndGetQueryResponse
  660. // since only one bookmark has to be added for all the queries submitted through
  661. // the SQL tab
  662. if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
  663. $cfgBookmark = Bookmark::getParams($cfg['Server']['user']);
  664. if (! is_array($cfgBookmark)) {
  665. $cfgBookmark = [];
  666. }
  667. $this->sql->storeTheQueryAsBookmark(
  668. $db,
  669. $cfgBookmark['user'],
  670. $_POST['sql_query'],
  671. $_POST['bkm_label'],
  672. isset($_POST['bkm_replace'])
  673. );
  674. }
  675. $this->response->addJSON('ajax_reload', $ajax_reload);
  676. $this->response->addHTML($html_output);
  677. return;
  678. }
  679. if ($result) {
  680. // Save a Bookmark with more than one queries (if Bookmark label given).
  681. if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
  682. $cfgBookmark = Bookmark::getParams($cfg['Server']['user']);
  683. if (! is_array($cfgBookmark)) {
  684. $cfgBookmark = [];
  685. }
  686. $this->sql->storeTheQueryAsBookmark(
  687. $db,
  688. $cfgBookmark['user'],
  689. $_POST['sql_query'],
  690. $_POST['bkm_label'],
  691. isset($_POST['bkm_replace'])
  692. );
  693. }
  694. $this->response->setRequestStatus(true);
  695. $this->response->addJSON('message', Message::success($msg));
  696. $this->response->addJSON(
  697. 'sql_query',
  698. Generator::getMessage($msg, $sql_query, 'success')
  699. );
  700. } elseif ($result === false) {
  701. $this->response->setRequestStatus(false);
  702. $this->response->addJSON('message', Message::error($msg));
  703. } else {
  704. $active_page = $goto;
  705. /** @psalm-suppress UnresolvableInclude */
  706. include ROOT_PATH . $goto;
  707. }
  708. // If there is request for ROLLBACK in the end.
  709. if (! isset($_POST['rollback_query'])) {
  710. return;
  711. }
  712. $this->dbi->query('ROLLBACK');
  713. }
  714. }