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 /* Enable LOAD DATA LOCAL INFILE for LDI plugin */
24 if (isset($_POST['format']) && $_POST['format'] == 'ldi') {
25 define('PMA_ENABLE_LDI', 1);
29 * Get the variables sent or posted to this script and a core script
31 require_once 'libraries/common.inc.php';
33 $import = new Import();
35 if (isset($_REQUEST['show_as_php'])) {
36 $GLOBALS['show_as_php'] = $_REQUEST['show_as_php'];
39 // If there is a request to 'Simulate DML'.
40 if (isset($_REQUEST['simulate_dml'])) {
41 $import->handleSimulateDmlRequest();
45 $response = Response
::getInstance();
49 // If it's a refresh console bookmarks request
50 if (isset($_REQUEST['console_bookmark_refresh'])) {
52 'console_message_bookmark',
53 PhpMyAdmin\Console
::getBookmarkContent()
57 // If it's a console bookmark add request
58 if (isset($_REQUEST['console_bookmark_add'])) {
59 if (isset($_REQUEST['label']) && isset($_REQUEST['db'])
60 && isset($_REQUEST['bookmark_query']) && isset($_REQUEST['shared'])
62 $cfgBookmark = Bookmark
::getParams($GLOBALS['cfg']['Server']['user']);
64 'bkm_database' => $_REQUEST['db'],
65 'bkm_user' => $cfgBookmark['user'],
66 'bkm_sql_query' => $_REQUEST['bookmark_query'],
67 'bkm_label' => $_REQUEST['label']
69 $isShared = ($_REQUEST['shared'] == 'true' ?
true : false);
70 $bookmark = Bookmark
::createBookmark(
72 $GLOBALS['cfg']['Server']['user'],
76 if ($bookmark !== false && $bookmark->save()) {
77 $response->addJSON('message', __('Succeeded'));
78 $response->addJSON('data', $bookmarkFields);
79 $response->addJSON('isShared', $isShared);
81 $response->addJSON('message', __('Failed'));
85 $response->addJSON('message', __('Incomplete params'));
93 * Sets globals from $_POST
107 foreach ($post_params as $one_post_param) {
108 if (isset($_POST[$one_post_param])) {
109 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
113 // reset import messages for ajax request
114 $_SESSION['Import_message']['message'] = null;
115 $_SESSION['Import_message']['go_back_url'] = null;
117 $GLOBALS['reload'] = false;
119 // Use to identify current cycle is executing
120 // a multiquery statement or stored routine
121 if (!isset($_SESSION['is_multi_query'])) {
122 $_SESSION['is_multi_query'] = false;
126 // Are we just executing plain query or sql file?
127 // (eg. non import, but query box/window run)
128 if (! empty($sql_query)) {
129 // apply values for parameters
130 if (! empty($_REQUEST['parameterized'])
131 && ! empty($_REQUEST['parameters'])
132 && is_array($_REQUEST['parameters'])
134 $parameters = $_REQUEST['parameters'];
135 foreach ($parameters as $parameter => $replacement) {
136 $quoted = preg_quote($parameter, '/');
137 // making sure that :param does not apply values to :param1
138 $sql_query = preg_replace(
139 '/' . $quoted . '([^a-zA-Z0-9_])/',
140 $GLOBALS['dbi']->escapeString($replacement) . '${1}',
143 // for parameters the appear at the end of the string
144 $sql_query = preg_replace(
145 '/' . $quoted . '$/',
146 $GLOBALS['dbi']->escapeString($replacement),
153 $import_text = $sql_query;
154 $import_type = 'query';
156 $_SESSION['sql_from_query_box'] = true;
158 // If there is a request to ROLLBACK when finished.
159 if (isset($_REQUEST['rollback_query'])) {
160 $import->handleRollbackRequest($import_text);
163 // refresh navigation and main panels
164 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
165 $GLOBALS['reload'] = true;
166 $ajax_reload['reload'] = true;
169 // refresh navigation panel only
171 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
174 $ajax_reload['reload'] = true;
177 // do a dynamic reload if table is RENAMED
178 // (by sending the instruction to the AJAX response handler)
180 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
184 $ajax_reload['reload'] = true;
185 $ajax_reload['table_name'] = PhpMyAdmin\Util
::unQuote(
186 $rename_table_names[2]
191 } elseif (! empty($sql_file)) {
192 // run uploaded SQL file
193 $import_file = $sql_file;
194 $import_type = 'queryfile';
197 } elseif (! empty($_REQUEST['id_bookmark'])) {
199 $import_type = 'query';
203 // If we didn't get any parameters, either user called this directly, or
204 // upload limit has been reached, let's assume the second possibility.
205 if ($_POST == [] && $_GET == []) {
206 $message = PhpMyAdmin\Message
::error(
208 'You probably tried to upload a file that is too large. Please refer ' .
209 'to %sdocumentation%s for a workaround for this limit.'
212 $message->addParam('[doc@faq1-16]');
213 $message->addParam('[/doc]');
215 // so we can obtain the message
216 $_SESSION['Import_message']['message'] = $message->getDisplay();
217 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
219 $response->setRequestStatus(false);
220 $response->addJSON('message', $message);
222 exit; // the footer is displayed automatically
225 // Add console message id to response output
226 if (isset($_POST['console_message_id'])) {
227 $response->addJSON('console_message_id', $_POST['console_message_id']);
231 * Sets globals from $_POST patterns, for import plugins
232 * We only need to load the selected plugin
248 // this should not happen for a normal user
249 // but only during an attack
250 Core
::fatalError('Incorrect format parameter');
255 '/^' . $format . '_/'
258 Core
::setPostAsGlobal($post_patterns);
260 // Check needed parameters
261 PhpMyAdmin\Util
::checkParameters(['import_type', 'format']);
263 // We don't want anything special in format
264 $format = Core
::securePath($format);
266 if (strlen($table) > 0 && strlen($db) > 0) {
267 $urlparams = ['db' => $db, 'table' => $table];
268 } elseif (strlen($db) > 0) {
269 $urlparams = ['db' => $db];
274 // Create error and goto url
275 if ($import_type == 'table') {
276 $goto = 'tbl_import.php';
277 } elseif ($import_type == 'database') {
278 $goto = 'db_import.php';
279 } elseif ($import_type == 'server') {
280 $goto = 'server_import.php';
282 if (empty($goto) ||
!preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
283 if (strlen($table) > 0 && strlen($db) > 0) {
284 $goto = 'tbl_structure.php';
285 } elseif (strlen($db) > 0) {
286 $goto = 'db_structure.php';
288 $goto = 'server_sql.php';
292 $err_url = $goto . Url
::getCommon($urlparams);
293 $_SESSION['Import_message']['go_back_url'] = $err_url;
294 // Avoid setting selflink to 'import.php'
295 // problem similar to bug 4276
296 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
297 $_SERVER['SCRIPT_NAME'] = $goto;
301 if (strlen($db) > 0) {
302 $GLOBALS['dbi']->selectDb($db);
305 Util
::setTimeLimit();
306 if (! empty($cfg['MemoryLimit'])) {
307 ini_set('memory_limit', $cfg['MemoryLimit']);
311 if (isset($_REQUEST['allow_interrupt'])) {
312 $maximum_time = ini_get('max_execution_time');
317 // set default values
318 $timeout_passed = false;
324 $file_to_unlink = '';
326 $sql_query_disabled = false;
328 $executed_queries = 0;
330 $charset_conversion = false;
331 $reset_charset = false;
332 $bookmark_created = false;
334 $msg = 'Sorry an unexpected error happened!';
336 // Bookmark Support: get a query back from bookmark if required
337 if (! empty($_REQUEST['id_bookmark'])) {
338 $id_bookmark = (int)$_REQUEST['id_bookmark'];
339 switch ($_REQUEST['action_bookmark']) {
340 case 0: // bookmarked query that have to be run
341 $bookmark = Bookmark
::get(
343 $GLOBALS['cfg']['Server']['user'],
347 isset($_REQUEST['action_bookmark_all'])
350 if (! empty($_REQUEST['bookmark_variable'])) {
351 $import_text = $bookmark->applyVariables(
352 $_REQUEST['bookmark_variable']
355 $import_text = $bookmark->getQuery();
358 // refresh navigation and main panels
360 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
363 $GLOBALS['reload'] = true;
364 $ajax_reload['reload'] = true;
367 // refresh navigation panel only
369 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
373 $ajax_reload['reload'] = true;
376 case 1: // bookmarked query that have to be displayed
377 $bookmark = Bookmark
::get(
379 $GLOBALS['cfg']['Server']['user'],
383 $import_text = $bookmark->getQuery();
384 if ($response->isAjax()) {
385 $message = PhpMyAdmin\Message
::success(__('Showing bookmark'));
386 $response->setRequestStatus($message->isSuccess());
387 $response->addJSON('message', $message);
388 $response->addJSON('sql_query', $import_text);
389 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
395 case 2: // bookmarked query that have to be deleted
396 $bookmark = Bookmark
::get(
398 $GLOBALS['cfg']['Server']['user'],
402 if (! empty($bookmark)) {
404 if ($response->isAjax()) {
405 $message = PhpMyAdmin\Message
::success(
406 __('The bookmark has been deleted.')
408 $response->setRequestStatus($message->isSuccess());
409 $response->addJSON('message', $message);
410 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
411 $response->addJSON('id_bookmark', $id_bookmark);
415 $error = true; // this is kind of hack to skip processing the query
421 } // end bookmarks reading
423 // Do no run query if we show PHP code
424 if (isset($GLOBALS['show_as_php'])) {
429 // We can not read all at once, otherwise we can run out of memory
430 $memory_limit = trim(ini_get('memory_limit'));
432 if (empty($memory_limit)) {
433 $memory_limit = 2 * 1024 * 1024;
435 // In case no memory limit we work on 10MB chunks
436 if ($memory_limit == -1) {
437 $memory_limit = 10 * 1024 * 1024;
440 // Calculate value of the limit
441 $memoryUnit = mb_strtolower(substr((string) $memory_limit, -1));
442 if ('m' == $memoryUnit) {
443 $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024;
444 } elseif ('k' == $memoryUnit) {
445 $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024;
446 } elseif ('g' == $memoryUnit) {
447 $memory_limit = (int) substr((string) $memory_limit, 0, -1) * 1024 * 1024 * 1024;
449 $memory_limit = (int) $memory_limit;
452 // Just to be sure, there might be lot of memory needed for uncompression
453 $read_limit = $memory_limit / 8;
456 if (isset($_FILES['import_file'])) {
457 $import_file = $_FILES['import_file']['tmp_name'];
459 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
460 // sanitize $local_import_file as it comes from a POST
461 $local_import_file = Core
::securePath($local_import_file);
463 $import_file = PhpMyAdmin\Util
::userDir($cfg['UploadDir'])
464 . $local_import_file;
467 * Do not allow symlinks to avoid security issues
468 * (user can create symlink to file he can not access,
469 * but phpMyAdmin can).
471 if (@is_link
($import_file)) {
472 $import_file = 'none';
474 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
475 $import_file = 'none';
478 // Do we have file to import?
480 if ($import_file != 'none' && ! $error) {
482 * Handle file compression
484 $import_handle = new File($import_file);
485 $import_handle->checkUploadedFile();
486 if ($import_handle->isError()) {
487 $import->stop($import_handle->getError());
489 $import_handle->setDecompressContent(true);
490 $import_handle->open();
491 if ($import_handle->isError()) {
492 $import->stop($import_handle->getError());
494 } elseif (! $error) {
495 if (! isset($import_text) ||
empty($import_text)) {
496 $message = PhpMyAdmin\Message
::error(
498 'No data was received to import. Either no file name was ' .
499 'submitted, or the file size exceeded the maximum size permitted ' .
500 'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
503 $import->stop($message);
507 // so we can obtain the message
508 //$_SESSION['Import_message'] = $message->getDisplay();
510 // Convert the file's charset if necessary
511 if (Encoding
::isSupported() && isset($charset_of_file)) {
512 if ($charset_of_file != 'utf-8') {
513 $charset_conversion = true;
515 } elseif (isset($charset_of_file) && $charset_of_file != 'utf-8') {
516 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
517 // We can not show query in this case, it is in different charset
518 $sql_query_disabled = true;
519 $reset_charset = true;
522 // Something to skip? (because timeout has passed)
523 if (! $error && isset($_POST['skip'])) {
524 $original_skip = $skip = intval($_POST['skip']);
525 while ($skip > 0 && ! $finished) {
526 $import->getNextChunk($skip < $read_limit ?
$skip : $read_limit);
527 // Disable read progressivity, otherwise we eat all memory!
529 $skip -= $read_limit;
534 // This array contain the data like numberof valid sql queries in the statement
535 // and complete valid sql statement (which affected for rows)
536 $sql_data = ['valid_sql' => [], 'valid_queries' => 0];
539 /* @var $import_plugin ImportPlugin */
540 $import_plugin = Plugins
::getPlugin(
543 'libraries/classes/Plugins/Import/',
546 if ($import_plugin == null) {
547 $message = PhpMyAdmin\Message
::error(
548 __('Could not load import plugins, please check your installation!')
550 $import->stop($message);
552 // Do the real import
554 $default_fk_check = PhpMyAdmin\Util
::handleDisableFKCheckInit();
555 $import_plugin->doImport($sql_data);
556 PhpMyAdmin\Util
::handleDisableFKCheckCleanup($default_fk_check);
557 } catch (Exception
$e) {
558 PhpMyAdmin\Util
::handleDisableFKCheckCleanup($default_fk_check);
564 if (isset($import_handle)) {
565 $import_handle->close();
568 // Cleanup temporary file
569 if ($file_to_unlink != '') {
570 unlink($file_to_unlink);
573 // Reset charset back, if we did some changes
574 if ($reset_charset) {
575 $GLOBALS['dbi']->query('SET CHARACTER SET ' . $GLOBALS['charset_connection']);
576 $GLOBALS['dbi']->setCollationConnection($collation_connection);
579 // Show correct message
580 if (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 2) {
581 $message = PhpMyAdmin\Message
::success(__('The bookmark has been deleted.'));
582 $display_query = $import_text;
583 $error = false; // unset error marker, it was used just to skip processing
584 } elseif (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 1) {
585 $message = PhpMyAdmin\Message
::notice(__('Showing bookmark'));
586 } elseif ($bookmark_created) {
587 $special_message = '[br]' . sprintf(
588 __('Bookmark %s has been created.'),
589 htmlspecialchars($_POST['bkm_label'])
591 } elseif ($finished && ! $error) {
592 // Do not display the query with message, we do it separately
593 $display_query = ';';
594 if ($import_type != 'query') {
595 $message = PhpMyAdmin\Message
::success(
598 'Import has been successfully finished, %d query executed.',
599 'Import has been successfully finished, %d queries executed.',
604 $message->addParam($executed_queries);
606 if (! empty($import_notice)) {
607 $message->addHtml($import_notice);
609 if (! empty($local_import_file)) {
610 $message->addText('(' . $local_import_file . ')');
612 $message->addText('(' . $_FILES['import_file']['name'] . ')');
617 // Did we hit timeout? Tell it user.
618 if ($timeout_passed) {
619 $urlparams['timeout_passed'] = '1';
620 $urlparams['offset'] = $GLOBALS['offset'];
621 if (isset($local_import_file)) {
622 $urlparams['local_import_file'] = $local_import_file;
625 $importUrl = $err_url = $goto . Url
::getCommon($urlparams);
627 $message = PhpMyAdmin\Message
::error(
629 'Script timeout passed, if you want to finish import,'
630 . ' please %sresubmit the same file%s and import will resume.'
633 $message->addParamHtml('<a href="' . $importUrl . '">');
634 $message->addParamHtml('</a>');
636 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
639 'However on last run no data has been parsed,'
640 . ' this usually means phpMyAdmin won\'t be able to'
641 . ' finish this import unless you increase php time limits.'
647 // if there is any message, copy it into $_SESSION as well,
648 // so we can obtain it by AJAX call
649 if (isset($message)) {
650 $_SESSION['Import_message']['message'] = $message->getDisplay();
652 // Parse and analyze the query, for correct db and table name
653 // in case of a query typed in the query window
654 // (but if the query is too large, in case of an imported file, the parser
655 // can choke on it so avoid parsing)
656 $sqlLength = mb_strlen($sql_query);
657 if ($sqlLength <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
659 $analyzed_sql_results,
662 ) = ParseAnalyze
::sqlQuery($sql_query, $db);
663 // @todo: possibly refactor
664 extract($analyzed_sql_results);
666 if ($table != $table_from_sql && !empty($table_from_sql)) {
667 $table = $table_from_sql;
671 // There was an error?
672 if (isset($my_die)) {
673 foreach ($my_die as $key => $die) {
674 PhpMyAdmin\Util
::mysqlDie(
685 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
686 $_SESSION['is_multi_query'] = true;
687 $sql_queries = $sql_data['valid_sql'];
689 $sql_queries = [$sql_query];
694 foreach ($sql_queries as $sql_query) {
697 $analyzed_sql_results,
700 ) = ParseAnalyze
::sqlQuery($sql_query, $db);
701 // @todo: possibly refactor
702 extract($analyzed_sql_results);
704 // Check if User is allowed to issue a 'DROP DATABASE' Statement
705 if ($sql->hasNoRightsToDropDatabase(
706 $analyzed_sql_results,
707 $cfg['AllowUserDropDatabase'],
708 $GLOBALS['dbi']->isSuperuser()
710 PhpMyAdmin\Util
::mysqlDie(
711 __('"DROP DATABASE" statements are disabled.'),
714 $_SESSION['Import_message']['go_back_url']
719 if ($table != $table_from_sql && !empty($table_from_sql)) {
720 $table = $table_from_sql;
723 $html_output .= $sql->executeQueryAndGetQueryResponse(
724 $analyzed_sql_results, // analyzed_sql_results
725 false, // is_gotofile
728 null, // find_real_end
729 null, // sql_query_for_bookmark - see below
731 null, // message_to_show
735 $pmaThemeImage, // pmaThemeImage
737 null, // disp_message
739 $sql_query, // sql_query
740 null, // selectedTables
741 null // complete_query
745 // sql_query_for_bookmark is not included in Sql::executeQueryAndGetQueryResponse
746 // since only one bookmark has to be added for all the queries submitted through
748 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
749 $cfgBookmark = Bookmark
::getParams($GLOBALS['cfg']['Server']['user']);
750 $sql->storeTheQueryAsBookmark(
752 $cfgBookmark['user'],
755 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
759 $response->addJSON('ajax_reload', $ajax_reload);
760 $response->addHTML($html_output);
763 // Save a Bookmark with more than one queries (if Bookmark label given).
764 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
765 $cfgBookmark = Bookmark
::getParams($GLOBALS['cfg']['Server']['user']);
766 $sql->storeTheQueryAsBookmark(
768 $cfgBookmark['user'],
771 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
775 $response->setRequestStatus(true);
776 $response->addJSON('message', PhpMyAdmin\Message
::success($msg));
779 PhpMyAdmin\Util
::getMessage($msg, $sql_query, 'success')
781 } elseif ($result == false) {
782 $response->setRequestStatus(false);
783 $response->addJSON('message', PhpMyAdmin\Message
::error($msg));
785 $active_page = $goto;
789 // If there is request for ROLLBACK in the end.
790 if (isset($_REQUEST['rollback_query'])) {
791 $GLOBALS['dbi']->query('ROLLBACK');