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\Encoding
;
14 use PhpMyAdmin\Import
;
15 use PhpMyAdmin\ParseAnalyze
;
16 use PhpMyAdmin\Plugins
;
17 use PhpMyAdmin\Plugins\ImportPlugin
;
18 use PhpMyAdmin\Response
;
23 if (! defined('ROOT_PATH')) {
24 define('ROOT_PATH', __DIR__
. DIRECTORY_SEPARATOR
);
27 /* Enable LOAD DATA LOCAL INFILE for LDI plugin */
28 if (isset($_POST['format']) && $_POST['format'] == 'ldi') {
29 define('PMA_ENABLE_LDI', 1);
33 * Get the variables sent or posted to this script and a core script
35 require_once ROOT_PATH
. 'libraries/common.inc.php';
37 $import = new Import();
39 if (isset($_POST['show_as_php'])) {
40 $GLOBALS['show_as_php'] = $_POST['show_as_php'];
43 // If there is a request to 'Simulate DML'.
44 if (isset($_POST['simulate_dml'])) {
45 $import->handleSimulateDmlRequest();
49 $response = Response
::getInstance();
53 // If it's a refresh console bookmarks request
54 if (isset($_GET['console_bookmark_refresh'])) {
56 'console_message_bookmark',
57 PhpMyAdmin\Console
::getBookmarkContent()
61 // If it's a console bookmark add request
62 if (isset($_POST['console_bookmark_add'])) {
63 if (isset($_POST['label']) && isset($_POST['db'])
64 && isset($_POST['bookmark_query']) && isset($_POST['shared'])
66 $cfgBookmark = Bookmark
::getParams($GLOBALS['cfg']['Server']['user']);
68 'bkm_database' => $_POST['db'],
69 'bkm_user' => $cfgBookmark['user'],
70 'bkm_sql_query' => $_POST['bookmark_query'],
71 'bkm_label' => $_POST['label']
73 $isShared = ($_POST['shared'] == 'true' ?
true : false);
74 $bookmark = Bookmark
::createBookmark(
76 $GLOBALS['cfg']['Server']['user'],
80 if ($bookmark !== false && $bookmark->save()) {
81 $response->addJSON('message', __('Succeeded'));
82 $response->addJSON('data', $bookmarkFields);
83 $response->addJSON('isShared', $isShared);
85 $response->addJSON('message', __('Failed'));
89 $response->addJSON('message', __('Incomplete params'));
97 * Sets globals from $_POST
111 foreach ($post_params as $one_post_param) {
112 if (isset($_POST[$one_post_param])) {
113 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
117 // reset import messages for ajax request
118 $_SESSION['Import_message']['message'] = null;
119 $_SESSION['Import_message']['go_back_url'] = null;
121 $GLOBALS['reload'] = false;
123 // Use to identify current cycle is executing
124 // a multiquery statement or stored routine
125 if (! isset($_SESSION['is_multi_query'])) {
126 $_SESSION['is_multi_query'] = false;
131 // Are we just executing plain query or sql file?
132 // (eg. non import, but query box/window run)
133 if (! empty($sql_query)) {
134 // apply values for parameters
135 if (! empty($_POST['parameterized'])
136 && ! empty($_POST['parameters'])
137 && is_array($_POST['parameters'])
139 $parameters = $_POST['parameters'];
140 foreach ($parameters as $parameter => $replacement) {
141 $quoted = preg_quote($parameter, '/');
142 // making sure that :param does not apply values to :param1
143 $sql_query = preg_replace(
144 '/' . $quoted . '([^a-zA-Z0-9_])/',
145 $GLOBALS['dbi']->escapeString($replacement) . '${1}',
148 // for parameters the appear at the end of the string
149 $sql_query = preg_replace(
150 '/' . $quoted . '$/',
151 $GLOBALS['dbi']->escapeString($replacement),
158 $import_text = $sql_query;
159 $import_type = 'query';
161 $_SESSION['sql_from_query_box'] = true;
163 // If there is a request to ROLLBACK when finished.
164 if (isset($_POST['rollback_query'])) {
165 $import->handleRollbackRequest($import_text);
168 // refresh navigation and main panels
169 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
170 $GLOBALS['reload'] = true;
171 $ajax_reload['reload'] = true;
174 // refresh navigation panel only
176 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
179 $ajax_reload['reload'] = true;
182 // do a dynamic reload if table is RENAMED
183 // (by sending the instruction to the AJAX response handler)
185 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
189 $ajax_reload['reload'] = true;
190 $ajax_reload['table_name'] = PhpMyAdmin\Util
::unQuote(
191 $rename_table_names[2]
196 } elseif (! empty($sql_file)) {
197 // run uploaded SQL file
198 $import_file = $sql_file;
199 $import_type = 'queryfile';
202 } elseif (! empty($_POST['id_bookmark'])) {
204 $import_type = 'query';
208 // If we didn't get any parameters, either user called this directly, or
209 // upload limit has been reached, let's assume the second possibility.
210 if ($_POST == [] && $_GET == []) {
211 $message = PhpMyAdmin\Message
::error(
213 'You probably tried to upload a file that is too large. Please refer ' .
214 'to %sdocumentation%s for a workaround for this limit.'
217 $message->addParam('[doc@faq1-16]');
218 $message->addParam('[/doc]');
220 // so we can obtain the message
221 $_SESSION['Import_message']['message'] = $message->getDisplay();
222 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
224 $response->setRequestStatus(false);
225 $response->addJSON('message', $message);
227 exit; // the footer is displayed automatically
230 // Add console message id to response output
231 if (isset($_POST['console_message_id'])) {
232 $response->addJSON('console_message_id', $_POST['console_message_id']);
236 * Sets globals from $_POST patterns, for import plugins
237 * We only need to load the selected plugin
253 // this should not happen for a normal user
254 // but only during an attack
255 Core
::fatalError('Incorrect format parameter');
260 '/^' . $format . '_/',
263 Core
::setPostAsGlobal($post_patterns);
265 // Check needed parameters
266 PhpMyAdmin\Util
::checkParameters(['import_type', 'format']);
268 // We don't want anything special in format
269 $format = Core
::securePath($format);
271 if (strlen($table) > 0 && strlen($db) > 0) {
276 } elseif (strlen($db) > 0) {
277 $urlparams = ['db' => $db];
282 // Create error and goto url
283 if ($import_type == 'table') {
284 $goto = 'tbl_import.php';
285 } elseif ($import_type == 'database') {
286 $goto = 'db_import.php';
287 } elseif ($import_type == 'server') {
288 $goto = 'server_import.php';
289 } elseif (empty($goto) ||
! preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
290 if (strlen($table) > 0 && strlen($db) > 0) {
291 $goto = 'tbl_structure.php';
292 } elseif (strlen($db) > 0) {
293 $goto = 'db_structure.php';
295 $goto = 'server_sql.php';
298 $err_url = $goto . Url
::getCommon($urlparams);
299 $_SESSION['Import_message']['go_back_url'] = $err_url;
300 // Avoid setting selflink to 'import.php'
301 // problem similar to bug 4276
302 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
303 $_SERVER['SCRIPT_NAME'] = $goto;
307 if (strlen($db) > 0) {
308 $GLOBALS['dbi']->selectDb($db);
311 Util
::setTimeLimit();
312 if (! empty($cfg['MemoryLimit'])) {
313 ini_set('memory_limit', $cfg['MemoryLimit']);
317 if (isset($_POST['allow_interrupt'])) {
318 $maximum_time = ini_get('max_execution_time');
323 // set default values
324 $timeout_passed = false;
330 $file_to_unlink = '';
332 $sql_query_disabled = false;
334 $executed_queries = 0;
336 $charset_conversion = false;
337 $reset_charset = false;
338 $bookmark_created = false;
340 $msg = 'Sorry an unexpected error happened!';
342 // Bookmark Support: get a query back from bookmark if required
343 if (! empty($_POST['id_bookmark'])) {
344 $id_bookmark = (int) $_POST['id_bookmark'];
345 switch ($_POST['action_bookmark']) {
346 case 0: // bookmarked query that have to be run
347 $bookmark = Bookmark
::get(
349 $GLOBALS['cfg']['Server']['user'],
353 isset($_POST['action_bookmark_all'])
356 if (! empty($_POST['bookmark_variable'])) {
357 $import_text = $bookmark->applyVariables(
358 $_POST['bookmark_variable']
361 $import_text = $bookmark->getQuery();
364 // refresh navigation and main panels
366 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
369 $GLOBALS['reload'] = true;
370 $ajax_reload['reload'] = true;
373 // refresh navigation panel only
375 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
379 $ajax_reload['reload'] = true;
382 case 1: // bookmarked query that have to be displayed
383 $bookmark = Bookmark
::get(
385 $GLOBALS['cfg']['Server']['user'],
389 $import_text = $bookmark->getQuery();
390 if ($response->isAjax()) {
391 $message = PhpMyAdmin\Message
::success(__('Showing bookmark'));
392 $response->setRequestStatus($message->isSuccess());
393 $response->addJSON('message', $message);
394 $response->addJSON('sql_query', $import_text);
395 $response->addJSON('action_bookmark', $_POST['action_bookmark']);
401 case 2: // bookmarked query that have to be deleted
402 $bookmark = Bookmark
::get(
404 $GLOBALS['cfg']['Server']['user'],
408 if (! empty($bookmark)) {
410 if ($response->isAjax()) {
411 $message = PhpMyAdmin\Message
::success(
412 __('The bookmark has been deleted.')
414 $response->setRequestStatus($message->isSuccess());
415 $response->addJSON('message', $message);
416 $response->addJSON('action_bookmark', $_POST['action_bookmark']);
417 $response->addJSON('id_bookmark', $id_bookmark);
421 $error = true; // this is kind of hack to skip processing the query
427 } // end bookmarks reading
429 // Do no run query if we show PHP code
430 if (isset($GLOBALS['show_as_php'])) {
435 // We can not read all at once, otherwise we can run out of memory
436 $memory_limit = trim(ini_get('memory_limit'));
438 if (empty($memory_limit)) {
439 $memory_limit = 2 * 1024 * 1024;
441 // In case no memory limit we work on 10MB chunks
442 if ($memory_limit == -1) {
443 $memory_limit = 10 * 1024 * 1024;
446 // Calculate value of the limit
447 $memoryUnit = mb_strtolower(substr((string) $memory_limit, -1));
448 if ('m' == $memoryUnit) {
449 $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024;
450 } elseif ('k' == $memoryUnit) {
451 $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024;
452 } elseif ('g' == $memoryUnit) {
453 $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024 * 1024;
455 $memory_limit = (int) $memory_limit;
458 // Just to be sure, there might be lot of memory needed for uncompression
459 $read_limit = $memory_limit / 8;
462 if (isset($_FILES['import_file'])) {
463 $import_file = $_FILES['import_file']['tmp_name'];
465 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
466 // sanitize $local_import_file as it comes from a POST
467 $local_import_file = Core
::securePath($local_import_file);
469 $import_file = PhpMyAdmin\Util
::userDir($cfg['UploadDir'])
470 . $local_import_file;
473 * Do not allow symlinks to avoid security issues
474 * (user can create symlink to file he can not access,
475 * but phpMyAdmin can).
477 if (@is_link
($import_file)) {
478 $import_file = 'none';
480 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
481 $import_file = 'none';
484 // Do we have file to import?
486 if ($import_file != 'none' && ! $error) {
488 * Handle file compression
490 $import_handle = new File($import_file);
491 $import_handle->checkUploadedFile();
492 if ($import_handle->isError()) {
493 $import->stop($import_handle->getError());
495 $import_handle->setDecompressContent(true);
496 $import_handle->open();
497 if ($import_handle->isError()) {
498 $import->stop($import_handle->getError());
500 } elseif (! $error) {
501 if (! isset($import_text) ||
empty($import_text)) {
502 $message = PhpMyAdmin\Message
::error(
504 'No data was received to import. Either no file name was ' .
505 'submitted, or the file size exceeded the maximum size permitted ' .
506 'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
509 $import->stop($message);
513 // so we can obtain the message
514 //$_SESSION['Import_message'] = $message->getDisplay();
516 // Convert the file's charset if necessary
517 if (Encoding
::isSupported() && isset($charset_of_file)) {
518 if ($charset_of_file != 'utf-8') {
519 $charset_conversion = true;
521 } elseif (isset($charset_of_file) && $charset_of_file != 'utf-8') {
522 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
523 // We can not show query in this case, it is in different charset
524 $sql_query_disabled = true;
525 $reset_charset = true;
528 // Something to skip? (because timeout has passed)
529 if (! $error && isset($_POST['skip'])) {
530 $original_skip = $skip = intval($_POST['skip']);
531 while ($skip > 0 && ! $finished) {
532 $import->getNextChunk($skip < $read_limit ?
$skip : $read_limit);
533 // Disable read progressivity, otherwise we eat all memory!
535 $skip -= $read_limit;
540 // This array contain the data like numberof valid sql queries in the statement
541 // and complete valid sql statement (which affected for rows)
544 'valid_queries' => 0,
549 * @var ImportPlugin $import_plugin
551 $import_plugin = Plugins
::getPlugin(
554 'libraries/classes/Plugins/Import/',
557 if ($import_plugin == null) {
558 $message = PhpMyAdmin\Message
::error(
559 __('Could not load import plugins, please check your installation!')
561 $import->stop($message);
563 // Do the real import
564 $default_fk_check = PhpMyAdmin\Util
::handleDisableFKCheckInit();
566 $import_plugin->doImport($sql_data);
567 PhpMyAdmin\Util
::handleDisableFKCheckCleanup($default_fk_check);
568 } catch (Exception
$e) {
569 PhpMyAdmin\Util
::handleDisableFKCheckCleanup($default_fk_check);
575 if (isset($import_handle)) {
576 $import_handle->close();
579 // Cleanup temporary file
580 if ($file_to_unlink != '') {
581 unlink($file_to_unlink);
584 // Reset charset back, if we did some changes
585 if ($reset_charset) {
586 $GLOBALS['dbi']->query('SET CHARACTER SET ' . $GLOBALS['charset_connection']);
587 $GLOBALS['dbi']->setCollationConnection($collation_connection);
590 // Show correct message
591 if (! empty($id_bookmark) && $_POST['action_bookmark'] == 2) {
592 $message = PhpMyAdmin\Message
::success(__('The bookmark has been deleted.'));
593 $display_query = $import_text;
594 $error = false; // unset error marker, it was used just to skip processing
595 } elseif (! empty($id_bookmark) && $_POST['action_bookmark'] == 1) {
596 $message = PhpMyAdmin\Message
::notice(__('Showing bookmark'));
597 } elseif ($bookmark_created) {
598 $special_message = '[br]' . sprintf(
599 __('Bookmark %s has been created.'),
600 htmlspecialchars($_POST['bkm_label'])
602 } elseif ($finished && ! $error) {
603 // Do not display the query with message, we do it separately
604 $display_query = ';';
605 if ($import_type != 'query') {
606 $message = PhpMyAdmin\Message
::success(
609 'Import has been successfully finished, %d query executed.',
610 'Import has been successfully finished, %d queries executed.',
615 $message->addParam($executed_queries);
617 if (! empty($import_notice)) {
618 $message->addHtml($import_notice);
620 if (! empty($local_import_file)) {
621 $message->addText('(' . $local_import_file . ')');
623 $message->addText('(' . $_FILES['import_file']['name'] . ')');
628 // Did we hit timeout? Tell it user.
629 if ($timeout_passed) {
630 $urlparams['timeout_passed'] = '1';
631 $urlparams['offset'] = $GLOBALS['offset'];
632 if (isset($local_import_file)) {
633 $urlparams['local_import_file'] = $local_import_file;
636 $importUrl = $err_url = $goto . Url
::getCommon($urlparams);
638 $message = PhpMyAdmin\Message
::error(
640 'Script timeout passed, if you want to finish import,'
641 . ' please %sresubmit the same file%s and import will resume.'
644 $message->addParamHtml('<a href="' . $importUrl . '">');
645 $message->addParamHtml('</a>');
647 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
650 'However on last run no data has been parsed,'
651 . ' this usually means phpMyAdmin won\'t be able to'
652 . ' finish this import unless you increase php time limits.'
658 // if there is any message, copy it into $_SESSION as well,
659 // so we can obtain it by AJAX call
660 if (isset($message)) {
661 $_SESSION['Import_message']['message'] = $message->getDisplay();
663 // Parse and analyze the query, for correct db and table name
664 // in case of a query typed in the query window
665 // (but if the query is too large, in case of an imported file, the parser
666 // can choke on it so avoid parsing)
667 $sqlLength = mb_strlen($sql_query);
668 if ($sqlLength <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
670 $analyzed_sql_results,
673 ) = ParseAnalyze
::sqlQuery($sql_query, $db);
674 // @todo: possibly refactor
675 extract($analyzed_sql_results);
677 if ($table != $table_from_sql && ! empty($table_from_sql)) {
678 $table = $table_from_sql;
682 // There was an error?
683 if (isset($my_die)) {
684 foreach ($my_die as $key => $die) {
685 PhpMyAdmin\Util
::mysqlDie(
696 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
697 $_SESSION['is_multi_query'] = true;
698 $sql_queries = $sql_data['valid_sql'];
700 $sql_queries = [$sql_query];
705 foreach ($sql_queries as $sql_query) {
708 $analyzed_sql_results,
711 ) = ParseAnalyze
::sqlQuery($sql_query, $db);
712 // @todo: possibly refactor
713 extract($analyzed_sql_results);
715 // Check if User is allowed to issue a 'DROP DATABASE' Statement
716 if ($sql->hasNoRightsToDropDatabase(
717 $analyzed_sql_results,
718 $cfg['AllowUserDropDatabase'],
719 $GLOBALS['dbi']->isSuperuser()
721 PhpMyAdmin\Util
::mysqlDie(
722 __('"DROP DATABASE" statements are disabled.'),
725 $_SESSION['Import_message']['go_back_url']
730 if ($table != $table_from_sql && ! empty($table_from_sql)) {
731 $table = $table_from_sql;
734 $html_output .= $sql->executeQueryAndGetQueryResponse(
735 $analyzed_sql_results, // analyzed_sql_results
736 false, // is_gotofile
739 null, // find_real_end
740 null, // sql_query_for_bookmark - see below
742 null, // message_to_show
746 $pmaThemeImage, // pmaThemeImage
748 null, // disp_message
750 $sql_query, // sql_query
751 null, // selectedTables
752 null // complete_query
756 // sql_query_for_bookmark is not included in Sql::executeQueryAndGetQueryResponse
757 // since only one bookmark has to be added for all the queries submitted through
759 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
760 $cfgBookmark = Bookmark
::getParams($GLOBALS['cfg']['Server']['user']);
761 $sql->storeTheQueryAsBookmark(
763 $cfgBookmark['user'],
766 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
770 $response->addJSON('ajax_reload', $ajax_reload);
771 $response->addHTML($html_output);
774 // Save a Bookmark with more than one queries (if Bookmark label given).
775 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
776 $cfgBookmark = Bookmark
::getParams($GLOBALS['cfg']['Server']['user']);
777 $sql->storeTheQueryAsBookmark(
779 $cfgBookmark['user'],
782 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
786 $response->setRequestStatus(true);
787 $response->addJSON('message', PhpMyAdmin\Message
::success($msg));
790 PhpMyAdmin\Util
::getMessage($msg, $sql_query, 'success')
792 } elseif ($result == false) {
793 $response->setRequestStatus(false);
794 $response->addJSON('message', PhpMyAdmin\Message
::error($msg));
796 $active_page = $goto;
797 include ROOT_PATH
. $goto;
800 // If there is request for ROLLBACK in the end.
801 if (isset($_POST['rollback_query'])) {
802 $GLOBALS['dbi']->query('ROLLBACK');