ImportController.php 31 KB

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