2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Core script for import, this is just the glue around all other stuff
8 declare(strict_types
=1);
10 use PhpMyAdmin\Bookmark
;
12 use PhpMyAdmin\DatabaseInterface
;
13 use PhpMyAdmin\Encoding
;
15 use PhpMyAdmin\Import
;
16 use PhpMyAdmin\ParseAnalyze
;
17 use PhpMyAdmin\Plugins
;
18 use PhpMyAdmin\Plugins\ImportPlugin
;
19 use PhpMyAdmin\Response
;
24 if (! defined('ROOT_PATH')) {
25 define('ROOT_PATH', __DIR__
. DIRECTORY_SEPARATOR
);
28 /* Enable LOAD DATA LOCAL INFILE for LDI plugin */
29 if (isset($_POST['format']) && $_POST['format'] == 'ldi') {
30 define('PMA_ENABLE_LDI', 1);
33 global $cfg, $collation_connection, $containerBuilder, $db, $import_type, $pmaThemeImage, $table;
35 require_once ROOT_PATH
. 'libraries/common.inc.php';
37 /** @var Response $response */
38 $response = $containerBuilder->get(Response
::class);
40 /** @var DatabaseInterface $dbi */
41 $dbi = $containerBuilder->get(DatabaseInterface
::class);
43 /** @var import $import */
44 $import = $containerBuilder->get('import');
46 if (isset($_POST['show_as_php'])) {
47 $GLOBALS['show_as_php'] = $_POST['show_as_php'];
50 // If there is a request to 'Simulate DML'.
51 if (isset($_POST['simulate_dml'])) {
52 $import->handleSimulateDmlRequest();
58 // If it's a refresh console bookmarks request
59 if (isset($_GET['console_bookmark_refresh'])) {
61 'console_message_bookmark',
62 PhpMyAdmin\Console
::getBookmarkContent()
66 // If it's a console bookmark add request
67 if (isset($_POST['console_bookmark_add'])) {
68 if (isset($_POST['label'], $_POST['db'], $_POST['bookmark_query'], $_POST['shared'])) {
69 $cfgBookmark = Bookmark
::getParams($GLOBALS['cfg']['Server']['user']);
71 'bkm_database' => $_POST['db'],
72 'bkm_user' => $cfgBookmark['user'],
73 'bkm_sql_query' => $_POST['bookmark_query'],
74 'bkm_label' => $_POST['label'],
76 $isShared = ($_POST['shared'] == 'true' ?
true : false);
77 $bookmark = Bookmark
::createBookmark(
79 $GLOBALS['cfg']['Server']['user'],
83 if ($bookmark !== false && $bookmark->save()) {
84 $response->addJSON('message', __('Succeeded'));
85 $response->addJSON('data', $bookmarkFields);
86 $response->addJSON('isShared', $isShared);
88 $response->addJSON('message', __('Failed'));
92 $response->addJSON('message', __('Incomplete params'));
100 * Sets globals from $_POST
114 foreach ($post_params as $one_post_param) {
115 if (isset($_POST[$one_post_param])) {
116 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
120 // reset import messages for ajax request
121 $_SESSION['Import_message']['message'] = null;
122 $_SESSION['Import_message']['go_back_url'] = null;
124 $GLOBALS['reload'] = false;
126 // Use to identify current cycle is executing
127 // a multiquery statement or stored routine
128 if (! isset($_SESSION['is_multi_query'])) {
129 $_SESSION['is_multi_query'] = false;
134 // Are we just executing plain query or sql file?
135 // (eg. non import, but query box/window run)
136 if (! empty($sql_query)) {
137 // apply values for parameters
138 if (! empty($_POST['parameterized'])
139 && ! empty($_POST['parameters'])
140 && is_array($_POST['parameters'])
142 $parameters = $_POST['parameters'];
143 foreach ($parameters as $parameter => $replacement) {
144 $quoted = preg_quote($parameter, '/');
145 // making sure that :param does not apply values to :param1
146 $sql_query = preg_replace(
147 '/' . $quoted . '([^a-zA-Z0-9_])/',
148 $dbi->escapeString($replacement) . '${1}',
151 // for parameters the appear at the end of the string
152 $sql_query = preg_replace(
153 '/' . $quoted . '$/',
154 $dbi->escapeString($replacement),
161 $import_text = $sql_query;
162 $import_type = 'query';
164 $_SESSION['sql_from_query_box'] = true;
166 // If there is a request to ROLLBACK when finished.
167 if (isset($_POST['rollback_query'])) {
168 $import->handleRollbackRequest($import_text);
171 // refresh navigation and main panels
172 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
173 $GLOBALS['reload'] = true;
174 $ajax_reload['reload'] = true;
177 // refresh navigation panel only
179 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
182 $ajax_reload['reload'] = true;
185 // do a dynamic reload if table is RENAMED
186 // (by sending the instruction to the AJAX response handler)
188 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
192 $ajax_reload['reload'] = true;
193 $ajax_reload['table_name'] = PhpMyAdmin\Util
::unQuote(
194 $rename_table_names[2]
199 } elseif (! empty($sql_file)) {
200 // run uploaded SQL file
201 $import_file = $sql_file;
202 $import_type = 'queryfile';
205 } elseif (! empty($_POST['id_bookmark'])) {
207 $import_type = 'query';
211 // If we didn't get any parameters, either user called this directly, or
212 // upload limit has been reached, let's assume the second possibility.
213 if ($_POST == [] && $_GET == []) {
214 $message = PhpMyAdmin\Message
::error(
216 'You probably tried to upload a file that is too large. Please refer ' .
217 'to %sdocumentation%s for a workaround for this limit.'
220 $message->addParam('[doc@faq1-16]');
221 $message->addParam('[/doc]');
223 // so we can obtain the message
224 $_SESSION['Import_message']['message'] = $message->getDisplay();
225 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
227 $response->setRequestStatus(false);
228 $response->addJSON('message', $message);
230 exit; // the footer is displayed automatically
233 // Add console message id to response output
234 if (isset($_POST['console_message_id'])) {
235 $response->addJSON('console_message_id', $_POST['console_message_id']);
239 * Sets globals from $_POST patterns, for import plugins
240 * We only need to load the selected plugin
256 // this should not happen for a normal user
257 // but only during an attack
258 Core
::fatalError('Incorrect format parameter');
263 '/^' . $format . '_/',
266 Core
::setPostAsGlobal($post_patterns);
268 // Check needed parameters
269 PhpMyAdmin\Util
::checkParameters(['import_type', 'format']);
271 // We don't want anything special in format
272 $format = Core
::securePath($format);
274 if (strlen($table) > 0 && strlen($db) > 0) {
279 } elseif (strlen($db) > 0) {
280 $urlparams = ['db' => $db];
285 // Create error and goto url
286 if ($import_type == 'table') {
287 $goto = 'tbl_import.php';
288 } elseif ($import_type == 'database') {
289 $goto = 'db_import.php';
290 } elseif ($import_type == 'server') {
291 $goto = 'server_import.php';
292 } elseif (empty($goto) ||
! preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
293 if (strlen($table) > 0 && strlen($db) > 0) {
294 $goto = Url
::getFromRoute('/table/structure');
295 } elseif (strlen($db) > 0) {
296 $goto = Url
::getFromRoute('/database/structure');
298 $goto = Url
::getFromRoute('/server/sql');
301 $err_url = $goto . Url
::getCommon($urlparams);
302 $_SESSION['Import_message']['go_back_url'] = $err_url;
303 // Avoid setting selflink to 'import.php'
304 // problem similar to bug 4276
305 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
306 $_SERVER['SCRIPT_NAME'] = $goto;
310 if (strlen($db) > 0) {
314 Util
::setTimeLimit();
315 if (! empty($cfg['MemoryLimit'])) {
316 ini_set('memory_limit', $cfg['MemoryLimit']);
320 if (isset($_POST['allow_interrupt'])) {
321 $maximum_time = ini_get('max_execution_time');
326 // set default values
327 $timeout_passed = false;
333 $file_to_unlink = '';
335 $sql_query_disabled = false;
337 $executed_queries = 0;
339 $charset_conversion = false;
340 $reset_charset = false;
341 $bookmark_created = false;
343 $msg = 'Sorry an unexpected error happened!';
345 // Bookmark Support: get a query back from bookmark if required
346 if (! empty($_POST['id_bookmark'])) {
347 $id_bookmark = (int) $_POST['id_bookmark'];
348 switch ($_POST['action_bookmark']) {
349 case 0: // bookmarked query that have to be run
350 $bookmark = Bookmark
::get(
352 $GLOBALS['cfg']['Server']['user'],
356 isset($_POST['action_bookmark_all'])
359 if (! empty($_POST['bookmark_variable'])) {
360 $import_text = $bookmark->applyVariables(
361 $_POST['bookmark_variable']
364 $import_text = $bookmark->getQuery();
367 // refresh navigation and main panels
369 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
372 $GLOBALS['reload'] = true;
373 $ajax_reload['reload'] = true;
376 // refresh navigation panel only
378 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
382 $ajax_reload['reload'] = true;
385 case 1: // bookmarked query that have to be displayed
386 $bookmark = Bookmark
::get(
388 $GLOBALS['cfg']['Server']['user'],
392 $import_text = $bookmark->getQuery();
393 if ($response->isAjax()) {
394 $message = PhpMyAdmin\Message
::success(__('Showing bookmark'));
395 $response->setRequestStatus($message->isSuccess());
396 $response->addJSON('message', $message);
397 $response->addJSON('sql_query', $import_text);
398 $response->addJSON('action_bookmark', $_POST['action_bookmark']);
404 case 2: // bookmarked query that have to be deleted
405 $bookmark = Bookmark
::get(
407 $GLOBALS['cfg']['Server']['user'],
411 if (! empty($bookmark)) {
413 if ($response->isAjax()) {
414 $message = PhpMyAdmin\Message
::success(
415 __('The bookmark has been deleted.')
417 $response->setRequestStatus($message->isSuccess());
418 $response->addJSON('message', $message);
419 $response->addJSON('action_bookmark', $_POST['action_bookmark']);
420 $response->addJSON('id_bookmark', $id_bookmark);
424 $error = true; // this is kind of hack to skip processing the query
430 } // end bookmarks reading
432 // Do no run query if we show PHP code
433 if (isset($GLOBALS['show_as_php'])) {
438 // We can not read all at once, otherwise we can run out of memory
439 $memory_limit = trim(ini_get('memory_limit'));
441 if (empty($memory_limit)) {
442 $memory_limit = 2 * 1024 * 1024;
444 // In case no memory limit we work on 10MB chunks
445 if ($memory_limit == -1) {
446 $memory_limit = 10 * 1024 * 1024;
449 // Calculate value of the limit
450 $memoryUnit = mb_strtolower(substr((string) $memory_limit, -1));
451 if ('m' == $memoryUnit) {
452 $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024;
453 } elseif ('k' == $memoryUnit) {
454 $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024;
455 } elseif ('g' == $memoryUnit) {
456 $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024 * 1024;
458 $memory_limit = (int) $memory_limit;
461 // Just to be sure, there might be lot of memory needed for uncompression
462 $read_limit = $memory_limit / 8;
465 if (isset($_FILES['import_file'])) {
466 $import_file = $_FILES['import_file']['tmp_name'];
467 $import_file_name = $_FILES['import_file']['name'];
469 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
470 // sanitize $local_import_file as it comes from a POST
471 $local_import_file = Core
::securePath($local_import_file);
473 $import_file = PhpMyAdmin\Util
::userDir($cfg['UploadDir'])
474 . $local_import_file;
477 * Do not allow symlinks to avoid security issues
478 * (user can create symlink to file he can not access,
479 * but phpMyAdmin can).
481 if (@is_link
($import_file)) {
482 $import_file = 'none';
484 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
485 $import_file = 'none';
488 // Do we have file to import?
490 if ($import_file != 'none' && ! $error) {
492 * Handle file compression
494 $import_handle = new File($import_file);
495 $import_handle->checkUploadedFile();
496 if ($import_handle->isError()) {
497 $import->stop($import_handle->getError());
499 $import_handle->setDecompressContent(true);
500 $import_handle->open();
501 if ($import_handle->isError()) {
502 $import->stop($import_handle->getError());
504 } elseif (! $error) {
505 if (! isset($import_text) ||
empty($import_text)) {
506 $message = PhpMyAdmin\Message
::error(
508 'No data was received to import. Either no file name was ' .
509 'submitted, or the file size exceeded the maximum size permitted ' .
510 'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
513 $import->stop($message);
517 // so we can obtain the message
518 //$_SESSION['Import_message'] = $message->getDisplay();
520 // Convert the file's charset if necessary
521 if (Encoding
::isSupported() && isset($charset_of_file)) {
522 if ($charset_of_file != 'utf-8') {
523 $charset_conversion = true;
525 } elseif (isset($charset_of_file) && $charset_of_file != 'utf-8') {
526 $dbi->query('SET NAMES \'' . $charset_of_file . '\'');
527 // We can not show query in this case, it is in different charset
528 $sql_query_disabled = true;
529 $reset_charset = true;
532 // Something to skip? (because timeout has passed)
533 if (! $error && isset($_POST['skip'])) {
534 $original_skip = $skip = intval($_POST['skip']);
535 while ($skip > 0 && ! $finished) {
536 $import->getNextChunk($skip < $read_limit ?
$skip : $read_limit);
537 // Disable read progressivity, otherwise we eat all memory!
539 $skip -= $read_limit;
544 // This array contain the data like numberof valid sql queries in the statement
545 // and complete valid sql statement (which affected for rows)
548 'valid_queries' => 0,
553 * @var ImportPlugin $import_plugin
555 $import_plugin = Plugins
::getPlugin(
558 'libraries/classes/Plugins/Import/',
561 if ($import_plugin == null) {
562 $message = PhpMyAdmin\Message
::error(
563 __('Could not load import plugins, please check your installation!')
565 $import->stop($message);
567 // Do the real import
568 $default_fk_check = PhpMyAdmin\Util
::handleDisableFKCheckInit();
570 $import_plugin->doImport($sql_data);
571 PhpMyAdmin\Util
::handleDisableFKCheckCleanup($default_fk_check);
572 } catch (Exception
$e) {
573 PhpMyAdmin\Util
::handleDisableFKCheckCleanup($default_fk_check);
579 if (isset($import_handle)) {
580 $import_handle->close();
583 // Cleanup temporary file
584 if ($file_to_unlink != '') {
585 unlink($file_to_unlink);
588 // Reset charset back, if we did some changes
589 if ($reset_charset) {
590 $dbi->query('SET CHARACTER SET ' . $GLOBALS['charset_connection']);
591 $dbi->setCollation($collation_connection);
594 // Show correct message
595 if (! empty($id_bookmark) && $_POST['action_bookmark'] == 2) {
596 $message = PhpMyAdmin\Message
::success(__('The bookmark has been deleted.'));
597 $display_query = $import_text;
598 $error = false; // unset error marker, it was used just to skip processing
599 } elseif (! empty($id_bookmark) && $_POST['action_bookmark'] == 1) {
600 $message = PhpMyAdmin\Message
::notice(__('Showing bookmark'));
601 } elseif ($bookmark_created) {
602 $special_message = '[br]' . sprintf(
603 __('Bookmark %s has been created.'),
604 htmlspecialchars($_POST['bkm_label'])
606 } elseif ($finished && ! $error) {
607 // Do not display the query with message, we do it separately
608 $display_query = ';';
609 if ($import_type != 'query') {
610 $message = PhpMyAdmin\Message
::success(
613 'Import has been successfully finished, %d query executed.',
614 'Import has been successfully finished, %d queries executed.',
619 $message->addParam($executed_queries);
621 if (! empty($import_notice)) {
622 $message->addHtml($import_notice);
624 if (! empty($local_import_file)) {
625 $message->addText('(' . $local_import_file . ')');
627 $message->addText('(' . $_FILES['import_file']['name'] . ')');
632 // Did we hit timeout? Tell it user.
633 if ($timeout_passed) {
634 $urlparams['timeout_passed'] = '1';
635 $urlparams['offset'] = $GLOBALS['offset'];
636 if (isset($local_import_file)) {
637 $urlparams['local_import_file'] = $local_import_file;
640 $importUrl = $err_url = $goto . Url
::getCommon($urlparams);
642 $message = PhpMyAdmin\Message
::error(
644 'Script timeout passed, if you want to finish import,'
645 . ' please %sresubmit the same file%s and import will resume.'
648 $message->addParamHtml('<a href="' . $importUrl . '">');
649 $message->addParamHtml('</a>');
651 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
654 'However on last run no data has been parsed,'
655 . ' this usually means phpMyAdmin won\'t be able to'
656 . ' finish this import unless you increase php time limits.'
662 // if there is any message, copy it into $_SESSION as well,
663 // so we can obtain it by AJAX call
664 if (isset($message)) {
665 $_SESSION['Import_message']['message'] = $message->getDisplay();
667 // Parse and analyze the query, for correct db and table name
668 // in case of a query typed in the query window
669 // (but if the query is too large, in case of an imported file, the parser
670 // can choke on it so avoid parsing)
671 $sqlLength = mb_strlen($sql_query);
672 if ($sqlLength <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
674 $analyzed_sql_results,
677 ) = ParseAnalyze
::sqlQuery($sql_query, $db);
678 // @todo: possibly refactor
679 extract($analyzed_sql_results);
681 if ($table != $table_from_sql && ! empty($table_from_sql)) {
682 $table = $table_from_sql;
686 // There was an error?
687 if (isset($my_die)) {
688 foreach ($my_die as $key => $die) {
689 PhpMyAdmin\Util
::mysqlDie(
700 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
701 $_SESSION['is_multi_query'] = true;
702 $sql_queries = $sql_data['valid_sql'];
704 $sql_queries = [$sql_query];
709 foreach ($sql_queries as $sql_query) {
712 $analyzed_sql_results,
715 ) = ParseAnalyze
::sqlQuery($sql_query, $db);
716 // @todo: possibly refactor
717 extract($analyzed_sql_results);
719 // Check if User is allowed to issue a 'DROP DATABASE' Statement
720 if ($sql->hasNoRightsToDropDatabase(
721 $analyzed_sql_results,
722 $cfg['AllowUserDropDatabase'],
725 PhpMyAdmin\Util
::mysqlDie(
726 __('"DROP DATABASE" statements are disabled.'),
729 $_SESSION['Import_message']['go_back_url']
734 if ($table != $table_from_sql && ! empty($table_from_sql)) {
735 $table = $table_from_sql;
738 $html_output .= $sql->executeQueryAndGetQueryResponse(
739 $analyzed_sql_results, // analyzed_sql_results
740 false, // is_gotofile
743 null, // find_real_end
744 null, // sql_query_for_bookmark - see below
746 null, // message_to_show
750 $pmaThemeImage, // pmaThemeImage
752 null, // disp_message
754 $sql_query, // sql_query
755 null, // selectedTables
756 null // complete_query
760 // sql_query_for_bookmark is not included in Sql::executeQueryAndGetQueryResponse
761 // since only one bookmark has to be added for all the queries submitted through
763 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
764 $cfgBookmark = Bookmark
::getParams($GLOBALS['cfg']['Server']['user']);
765 $sql->storeTheQueryAsBookmark(
767 $cfgBookmark['user'],
770 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
774 $response->addJSON('ajax_reload', $ajax_reload);
775 $response->addHTML($html_output);
778 // Save a Bookmark with more than one queries (if Bookmark label given).
779 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
780 $cfgBookmark = Bookmark
::getParams($GLOBALS['cfg']['Server']['user']);
781 $sql->storeTheQueryAsBookmark(
783 $cfgBookmark['user'],
786 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
790 $response->setRequestStatus(true);
791 $response->addJSON('message', PhpMyAdmin\Message
::success($msg));
794 PhpMyAdmin\Util
::getMessage($msg, $sql_query, 'success')
796 } elseif ($result === false) {
797 $response->setRequestStatus(false);
798 $response->addJSON('message', PhpMyAdmin\Message
::error($msg));
800 $active_page = $goto;
801 include ROOT_PATH
. $goto;
804 // If there is request for ROLLBACK in the end.
805 if (isset($_POST['rollback_query'])) {
806 $dbi->query('ROLLBACK');