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 $db, $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']) && isset($_POST['db'])
69 && isset($_POST['bookmark_query']) && isset($_POST['shared'])
71 $cfgBookmark = Bookmark
::getParams($GLOBALS['cfg']['Server']['user']);
73 'bkm_database' => $_POST['db'],
74 'bkm_user' => $cfgBookmark['user'],
75 'bkm_sql_query' => $_POST['bookmark_query'],
76 'bkm_label' => $_POST['label'],
78 $isShared = ($_POST['shared'] == 'true' ?
true : false);
79 $bookmark = Bookmark
::createBookmark(
81 $GLOBALS['cfg']['Server']['user'],
85 if ($bookmark !== false && $bookmark->save()) {
86 $response->addJSON('message', __('Succeeded'));
87 $response->addJSON('data', $bookmarkFields);
88 $response->addJSON('isShared', $isShared);
90 $response->addJSON('message', __('Failed'));
94 $response->addJSON('message', __('Incomplete params'));
102 * Sets globals from $_POST
116 foreach ($post_params as $one_post_param) {
117 if (isset($_POST[$one_post_param])) {
118 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
122 // reset import messages for ajax request
123 $_SESSION['Import_message']['message'] = null;
124 $_SESSION['Import_message']['go_back_url'] = null;
126 $GLOBALS['reload'] = false;
128 // Use to identify current cycle is executing
129 // a multiquery statement or stored routine
130 if (! isset($_SESSION['is_multi_query'])) {
131 $_SESSION['is_multi_query'] = false;
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'])
141 && ! empty($_POST['parameters'])
142 && is_array($_POST['parameters'])
144 $parameters = $_POST['parameters'];
145 foreach ($parameters as $parameter => $replacement) {
146 $quoted = preg_quote($parameter, '/');
147 // making sure that :param does not apply values to :param1
148 $sql_query = preg_replace(
149 '/' . $quoted . '([^a-zA-Z0-9_])/',
150 $dbi->escapeString($replacement) . '${1}',
153 // for parameters the appear at the end of the string
154 $sql_query = preg_replace(
155 '/' . $quoted . '$/',
156 $dbi->escapeString($replacement),
163 $import_text = $sql_query;
164 $import_type = 'query';
166 $_SESSION['sql_from_query_box'] = true;
168 // If there is a request to ROLLBACK when finished.
169 if (isset($_POST['rollback_query'])) {
170 $import->handleRollbackRequest($import_text);
173 // refresh navigation and main panels
174 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
175 $GLOBALS['reload'] = true;
176 $ajax_reload['reload'] = true;
179 // refresh navigation panel only
181 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
184 $ajax_reload['reload'] = true;
187 // do a dynamic reload if table is RENAMED
188 // (by sending the instruction to the AJAX response handler)
190 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
194 $ajax_reload['reload'] = true;
195 $ajax_reload['table_name'] = PhpMyAdmin\Util
::unQuote(
196 $rename_table_names[2]
201 } elseif (! empty($sql_file)) {
202 // run uploaded SQL file
203 $import_file = $sql_file;
204 $import_type = 'queryfile';
207 } elseif (! empty($_POST['id_bookmark'])) {
209 $import_type = 'query';
213 // If we didn't get any parameters, either user called this directly, or
214 // upload limit has been reached, let's assume the second possibility.
215 if ($_POST == [] && $_GET == []) {
216 $message = PhpMyAdmin\Message
::error(
218 'You probably tried to upload a file that is too large. Please refer ' .
219 'to %sdocumentation%s for a workaround for this limit.'
222 $message->addParam('[doc@faq1-16]');
223 $message->addParam('[/doc]');
225 // so we can obtain the message
226 $_SESSION['Import_message']['message'] = $message->getDisplay();
227 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
229 $response->setRequestStatus(false);
230 $response->addJSON('message', $message);
232 exit; // the footer is displayed automatically
235 // Add console message id to response output
236 if (isset($_POST['console_message_id'])) {
237 $response->addJSON('console_message_id', $_POST['console_message_id']);
241 * Sets globals from $_POST patterns, for import plugins
242 * We only need to load the selected plugin
258 // this should not happen for a normal user
259 // but only during an attack
260 Core
::fatalError('Incorrect format parameter');
265 '/^' . $format . '_/',
268 Core
::setPostAsGlobal($post_patterns);
270 // Check needed parameters
271 PhpMyAdmin\Util
::checkParameters(['import_type', 'format']);
273 // We don't want anything special in format
274 $format = Core
::securePath($format);
276 if (strlen($table) > 0 && strlen($db) > 0) {
281 } elseif (strlen($db) > 0) {
282 $urlparams = ['db' => $db];
287 // Create error and goto url
288 if ($import_type == 'table') {
289 $goto = 'tbl_import.php';
290 } elseif ($import_type == 'database') {
291 $goto = 'db_import.php';
292 } elseif ($import_type == 'server') {
293 $goto = 'server_import.php';
294 } elseif (empty($goto) ||
! preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
295 if (strlen($table) > 0 && strlen($db) > 0) {
296 $goto = 'tbl_structure.php';
297 } elseif (strlen($db) > 0) {
298 $goto = 'db_structure.php';
300 $goto = 'server_sql.php';
303 $err_url = $goto . Url
::getCommon($urlparams);
304 $_SESSION['Import_message']['go_back_url'] = $err_url;
305 // Avoid setting selflink to 'import.php'
306 // problem similar to bug 4276
307 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
308 $_SERVER['SCRIPT_NAME'] = $goto;
312 if (strlen($db) > 0) {
316 Util
::setTimeLimit();
317 if (! empty($cfg['MemoryLimit'])) {
318 ini_set('memory_limit', $cfg['MemoryLimit']);
322 if (isset($_POST['allow_interrupt'])) {
323 $maximum_time = ini_get('max_execution_time');
328 // set default values
329 $timeout_passed = false;
335 $file_to_unlink = '';
337 $sql_query_disabled = false;
339 $executed_queries = 0;
341 $charset_conversion = false;
342 $reset_charset = false;
343 $bookmark_created = false;
345 $msg = 'Sorry an unexpected error happened!';
347 // Bookmark Support: get a query back from bookmark if required
348 if (! empty($_POST['id_bookmark'])) {
349 $id_bookmark = (int) $_POST['id_bookmark'];
350 switch ($_POST['action_bookmark']) {
351 case 0: // bookmarked query that have to be run
352 $bookmark = Bookmark
::get(
354 $GLOBALS['cfg']['Server']['user'],
358 isset($_POST['action_bookmark_all'])
361 if (! empty($_POST['bookmark_variable'])) {
362 $import_text = $bookmark->applyVariables(
363 $_POST['bookmark_variable']
366 $import_text = $bookmark->getQuery();
369 // refresh navigation and main panels
371 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
374 $GLOBALS['reload'] = true;
375 $ajax_reload['reload'] = true;
378 // refresh navigation panel only
380 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
384 $ajax_reload['reload'] = true;
387 case 1: // bookmarked query that have to be displayed
388 $bookmark = Bookmark
::get(
390 $GLOBALS['cfg']['Server']['user'],
394 $import_text = $bookmark->getQuery();
395 if ($response->isAjax()) {
396 $message = PhpMyAdmin\Message
::success(__('Showing bookmark'));
397 $response->setRequestStatus($message->isSuccess());
398 $response->addJSON('message', $message);
399 $response->addJSON('sql_query', $import_text);
400 $response->addJSON('action_bookmark', $_POST['action_bookmark']);
406 case 2: // bookmarked query that have to be deleted
407 $bookmark = Bookmark
::get(
409 $GLOBALS['cfg']['Server']['user'],
413 if (! empty($bookmark)) {
415 if ($response->isAjax()) {
416 $message = PhpMyAdmin\Message
::success(
417 __('The bookmark has been deleted.')
419 $response->setRequestStatus($message->isSuccess());
420 $response->addJSON('message', $message);
421 $response->addJSON('action_bookmark', $_POST['action_bookmark']);
422 $response->addJSON('id_bookmark', $id_bookmark);
426 $error = true; // this is kind of hack to skip processing the query
432 } // end bookmarks reading
434 // Do no run query if we show PHP code
435 if (isset($GLOBALS['show_as_php'])) {
440 // We can not read all at once, otherwise we can run out of memory
441 $memory_limit = trim(ini_get('memory_limit'));
443 if (empty($memory_limit)) {
444 $memory_limit = 2 * 1024 * 1024;
446 // In case no memory limit we work on 10MB chunks
447 if ($memory_limit == -1) {
448 $memory_limit = 10 * 1024 * 1024;
451 // Calculate value of the limit
452 $memoryUnit = mb_strtolower(substr((string) $memory_limit, -1));
453 if ('m' == $memoryUnit) {
454 $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024;
455 } elseif ('k' == $memoryUnit) {
456 $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024;
457 } elseif ('g' == $memoryUnit) {
458 $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024 * 1024;
460 $memory_limit = (int) $memory_limit;
463 // Just to be sure, there might be lot of memory needed for uncompression
464 $read_limit = $memory_limit / 8;
467 if (isset($_FILES['import_file'])) {
468 $import_file = $_FILES['import_file']['tmp_name'];
469 $import_file_name = $_FILES['import_file']['name'];
471 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
472 // sanitize $local_import_file as it comes from a POST
473 $local_import_file = Core
::securePath($local_import_file);
475 $import_file = PhpMyAdmin\Util
::userDir($cfg['UploadDir'])
476 . $local_import_file;
479 * Do not allow symlinks to avoid security issues
480 * (user can create symlink to file he can not access,
481 * but phpMyAdmin can).
483 if (@is_link
($import_file)) {
484 $import_file = 'none';
486 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
487 $import_file = 'none';
490 // Do we have file to import?
492 if ($import_file != 'none' && ! $error) {
494 * Handle file compression
496 $import_handle = new File($import_file);
497 $import_handle->checkUploadedFile();
498 if ($import_handle->isError()) {
499 $import->stop($import_handle->getError());
501 $import_handle->setDecompressContent(true);
502 $import_handle->open();
503 if ($import_handle->isError()) {
504 $import->stop($import_handle->getError());
506 } elseif (! $error) {
507 if (! isset($import_text) ||
empty($import_text)) {
508 $message = PhpMyAdmin\Message
::error(
510 'No data was received to import. Either no file name was ' .
511 'submitted, or the file size exceeded the maximum size permitted ' .
512 'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
515 $import->stop($message);
519 // so we can obtain the message
520 //$_SESSION['Import_message'] = $message->getDisplay();
522 // Convert the file's charset if necessary
523 if (Encoding
::isSupported() && isset($charset_of_file)) {
524 if ($charset_of_file != 'utf-8') {
525 $charset_conversion = true;
527 } elseif (isset($charset_of_file) && $charset_of_file != 'utf-8') {
528 $dbi->query('SET NAMES \'' . $charset_of_file . '\'');
529 // We can not show query in this case, it is in different charset
530 $sql_query_disabled = true;
531 $reset_charset = true;
534 // Something to skip? (because timeout has passed)
535 if (! $error && isset($_POST['skip'])) {
536 $original_skip = $skip = intval($_POST['skip']);
537 while ($skip > 0 && ! $finished) {
538 $import->getNextChunk($skip < $read_limit ?
$skip : $read_limit);
539 // Disable read progressivity, otherwise we eat all memory!
541 $skip -= $read_limit;
546 // This array contain the data like numberof valid sql queries in the statement
547 // and complete valid sql statement (which affected for rows)
550 'valid_queries' => 0,
555 * @var ImportPlugin $import_plugin
557 $import_plugin = Plugins
::getPlugin(
560 'libraries/classes/Plugins/Import/',
563 if ($import_plugin == null) {
564 $message = PhpMyAdmin\Message
::error(
565 __('Could not load import plugins, please check your installation!')
567 $import->stop($message);
569 // Do the real import
570 $default_fk_check = PhpMyAdmin\Util
::handleDisableFKCheckInit();
572 $import_plugin->doImport($sql_data);
573 PhpMyAdmin\Util
::handleDisableFKCheckCleanup($default_fk_check);
574 } catch (Exception
$e) {
575 PhpMyAdmin\Util
::handleDisableFKCheckCleanup($default_fk_check);
581 if (isset($import_handle)) {
582 $import_handle->close();
585 // Cleanup temporary file
586 if ($file_to_unlink != '') {
587 unlink($file_to_unlink);
590 // Reset charset back, if we did some changes
591 if ($reset_charset) {
592 $dbi->query('SET CHARACTER SET ' . $GLOBALS['charset_connection']);
593 $dbi->setCollation($collation_connection);
596 // Show correct message
597 if (! empty($id_bookmark) && $_POST['action_bookmark'] == 2) {
598 $message = PhpMyAdmin\Message
::success(__('The bookmark has been deleted.'));
599 $display_query = $import_text;
600 $error = false; // unset error marker, it was used just to skip processing
601 } elseif (! empty($id_bookmark) && $_POST['action_bookmark'] == 1) {
602 $message = PhpMyAdmin\Message
::notice(__('Showing bookmark'));
603 } elseif ($bookmark_created) {
604 $special_message = '[br]' . sprintf(
605 __('Bookmark %s has been created.'),
606 htmlspecialchars($_POST['bkm_label'])
608 } elseif ($finished && ! $error) {
609 // Do not display the query with message, we do it separately
610 $display_query = ';';
611 if ($import_type != 'query') {
612 $message = PhpMyAdmin\Message
::success(
615 'Import has been successfully finished, %d query executed.',
616 'Import has been successfully finished, %d queries executed.',
621 $message->addParam($executed_queries);
623 if (! empty($import_notice)) {
624 $message->addHtml($import_notice);
626 if (! empty($local_import_file)) {
627 $message->addText('(' . $local_import_file . ')');
629 $message->addText('(' . $_FILES['import_file']['name'] . ')');
634 // Did we hit timeout? Tell it user.
635 if ($timeout_passed) {
636 $urlparams['timeout_passed'] = '1';
637 $urlparams['offset'] = $GLOBALS['offset'];
638 if (isset($local_import_file)) {
639 $urlparams['local_import_file'] = $local_import_file;
642 $importUrl = $err_url = $goto . Url
::getCommon($urlparams);
644 $message = PhpMyAdmin\Message
::error(
646 'Script timeout passed, if you want to finish import,'
647 . ' please %sresubmit the same file%s and import will resume.'
650 $message->addParamHtml('<a href="' . $importUrl . '">');
651 $message->addParamHtml('</a>');
653 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
656 'However on last run no data has been parsed,'
657 . ' this usually means phpMyAdmin won\'t be able to'
658 . ' finish this import unless you increase php time limits.'
664 // if there is any message, copy it into $_SESSION as well,
665 // so we can obtain it by AJAX call
666 if (isset($message)) {
667 $_SESSION['Import_message']['message'] = $message->getDisplay();
669 // Parse and analyze the query, for correct db and table name
670 // in case of a query typed in the query window
671 // (but if the query is too large, in case of an imported file, the parser
672 // can choke on it so avoid parsing)
673 $sqlLength = mb_strlen($sql_query);
674 if ($sqlLength <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
676 $analyzed_sql_results,
679 ) = ParseAnalyze
::sqlQuery($sql_query, $db);
680 // @todo: possibly refactor
681 extract($analyzed_sql_results);
683 if ($table != $table_from_sql && ! empty($table_from_sql)) {
684 $table = $table_from_sql;
688 // There was an error?
689 if (isset($my_die)) {
690 foreach ($my_die as $key => $die) {
691 PhpMyAdmin\Util
::mysqlDie(
702 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
703 $_SESSION['is_multi_query'] = true;
704 $sql_queries = $sql_data['valid_sql'];
706 $sql_queries = [$sql_query];
711 foreach ($sql_queries as $sql_query) {
714 $analyzed_sql_results,
717 ) = ParseAnalyze
::sqlQuery($sql_query, $db);
718 // @todo: possibly refactor
719 extract($analyzed_sql_results);
721 // Check if User is allowed to issue a 'DROP DATABASE' Statement
722 if ($sql->hasNoRightsToDropDatabase(
723 $analyzed_sql_results,
724 $cfg['AllowUserDropDatabase'],
727 PhpMyAdmin\Util
::mysqlDie(
728 __('"DROP DATABASE" statements are disabled.'),
731 $_SESSION['Import_message']['go_back_url']
736 if ($table != $table_from_sql && ! empty($table_from_sql)) {
737 $table = $table_from_sql;
740 $html_output .= $sql->executeQueryAndGetQueryResponse(
741 $analyzed_sql_results, // analyzed_sql_results
742 false, // is_gotofile
745 null, // find_real_end
746 null, // sql_query_for_bookmark - see below
748 null, // message_to_show
752 $pmaThemeImage, // pmaThemeImage
754 null, // disp_message
756 $sql_query, // sql_query
757 null, // selectedTables
758 null // complete_query
762 // sql_query_for_bookmark is not included in Sql::executeQueryAndGetQueryResponse
763 // since only one bookmark has to be added for all the queries submitted through
765 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
766 $cfgBookmark = Bookmark
::getParams($GLOBALS['cfg']['Server']['user']);
767 $sql->storeTheQueryAsBookmark(
769 $cfgBookmark['user'],
772 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
776 $response->addJSON('ajax_reload', $ajax_reload);
777 $response->addHTML($html_output);
780 // Save a Bookmark with more than one queries (if Bookmark label given).
781 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
782 $cfgBookmark = Bookmark
::getParams($GLOBALS['cfg']['Server']['user']);
783 $sql->storeTheQueryAsBookmark(
785 $cfgBookmark['user'],
788 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
792 $response->setRequestStatus(true);
793 $response->addJSON('message', PhpMyAdmin\Message
::success($msg));
796 PhpMyAdmin\Util
::getMessage($msg, $sql_query, 'success')
798 } elseif ($result === false) {
799 $response->setRequestStatus(false);
800 $response->addJSON('message', PhpMyAdmin\Message
::error($msg));
802 $active_page = $goto;
803 include ROOT_PATH
. $goto;
806 // If there is request for ROLLBACK in the end.
807 if (isset($_POST['rollback_query'])) {
808 $dbi->query('ROLLBACK');