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 use PMA\libraries\plugins\ImportPlugin
;
11 * Get the variables sent or posted to this script and a core script
13 require_once 'libraries/common.inc.php';
14 require_once 'libraries/sql.lib.php';
15 require_once 'libraries/bookmark.lib.php';
16 //require_once 'libraries/display_import_functions.lib.php';
18 if (isset($_REQUEST['show_as_php'])) {
19 $GLOBALS['show_as_php'] = $_REQUEST['show_as_php'];
23 require_once 'libraries/import.lib.php';
25 // If there is a request to 'Simulate DML'.
26 if (isset($_REQUEST['simulate_dml'])) {
27 PMA_handleSimulateDMLRequest();
31 // If it's a refresh console bookmarks request
32 if (isset($_REQUEST['console_bookmark_refresh'])) {
33 $response = PMA\libraries\Response
::getInstance();
35 'console_message_bookmark', PMA\libraries\Console
::getBookmarkContent()
39 // If it's a console bookmark add request
40 if (isset($_REQUEST['console_bookmark_add'])) {
41 $response = PMA\libraries\Response
::getInstance();
42 if (isset($_REQUEST['label']) && isset($_REQUEST['db'])
43 && isset($_REQUEST['bookmark_query']) && isset($_REQUEST['shared'])
45 $cfgBookmark = PMA_Bookmark_getParams();
46 $bookmarkFields = array(
47 'bkm_database' => $_REQUEST['db'],
48 'bkm_user' => $cfgBookmark['user'],
49 'bkm_sql_query' => urlencode($_REQUEST['bookmark_query']),
50 'bkm_label' => $_REQUEST['label']
52 $isShared = ($_REQUEST['shared'] == 'true' ?
true : false);
53 if (PMA_Bookmark_save($bookmarkFields, $isShared)) {
54 $response->addJSON('message', __('Succeeded'));
55 $response->addJSON('data', $bookmarkFields);
56 $response->addJSON('isShared', $isShared);
58 $response->addJSON('message', __('Failed'));
62 $response->addJSON('message', __('Incomplete params'));
70 * Sets globals from $_POST
84 // TODO: adapt full list of allowed parameters, as in export.php
85 foreach ($post_params as $one_post_param) {
86 if (isset($_POST[$one_post_param])) {
87 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
91 // reset import messages for ajax request
92 $_SESSION['Import_message']['message'] = null;
93 $_SESSION['Import_message']['go_back_url'] = null;
95 $GLOBALS['reload'] = false;
97 // Use to identify current cycle is executing
98 // a multiquery statement or stored routine
99 if (!isset($_SESSION['is_multi_query'])) {
100 $_SESSION['is_multi_query'] = false;
103 $ajax_reload = array();
104 // Are we just executing plain query or sql file?
105 // (eg. non import, but query box/window run)
106 if (! empty($sql_query)) {
108 // apply values for parameters
109 if (! empty($_REQUEST['parameterized'])
110 && ! empty($_REQUEST['parameters'])
111 && is_array($_REQUEST['parameters'])) {
112 $parameters = $_REQUEST['parameters'];
113 foreach ($parameters as $parameter => $replacement) {
114 $quoted = preg_quote($parameter);
115 // making sure that :param does not apply values to :param1
116 $sql_query = preg_replace(
117 '/' . $quoted . '([^a-zA-Z0-9_])/',
118 PMA\libraries\Util
::sqlAddSlashes($replacement) . '${1}',
121 // for parameters the appear at the end of the string
122 $sql_query = preg_replace(
123 '/' . $quoted . '$/',
124 PMA\libraries\Util
::sqlAddSlashes($replacement),
131 $import_text = $sql_query;
132 $import_type = 'query';
134 $_SESSION['sql_from_query_box'] = true;
136 // If there is a request to ROLLBACK when finished.
137 if (isset($_REQUEST['rollback_query'])) {
138 PMA_handleRollbackRequest($import_text);
141 // refresh navigation and main panels
142 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
143 $GLOBALS['reload'] = true;
144 $ajax_reload['reload'] = true;
147 // refresh navigation panel only
149 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
152 $ajax_reload['reload'] = true;
155 // do a dynamic reload if table is RENAMED
156 // (by sending the instruction to the AJAX response handler)
158 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
162 $ajax_reload['reload'] = true;
163 $ajax_reload['table_name'] = PMA\libraries\Util
::unQuote(
164 $rename_table_names[2]
169 } elseif (! empty($sql_file)) {
170 // run uploaded SQL file
171 $import_file = $sql_file;
172 $import_type = 'queryfile';
175 } elseif (! empty($_REQUEST['id_bookmark'])) {
177 $import_type = 'query';
181 // If we didn't get any parameters, either user called this directly, or
182 // upload limit has been reached, let's assume the second possibility.
183 if ($_POST == array() && $_GET == array()) {
184 $message = PMA\libraries\Message
::error(
186 'You probably tried to upload a file that is too large. Please refer ' .
187 'to %sdocumentation%s for a workaround for this limit.'
190 $message->addParam('[doc@faq1-16]');
191 $message->addParam('[/doc]');
193 // so we can obtain the message
194 $_SESSION['Import_message']['message'] = $message->getDisplay();
195 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
198 exit; // the footer is displayed automatically
201 // Add console message id to response output
202 if (isset($_POST['console_message_id'])) {
203 $response = PMA\libraries\Response
::getInstance();
204 $response->addJSON('console_message_id', $_POST['console_message_id']);
208 * Sets globals from $_POST patterns, for import plugins
209 * We only need to load the selected plugin
225 // this should not happen for a normal user
226 // but only during an attack
227 PMA_fatalError('Incorrect format parameter');
230 $post_patterns = array(
232 '/^' . $format . '_/'
235 PMA_setPostAsGlobal($post_patterns);
237 // Check needed parameters
238 PMA\libraries\Util
::checkParameters(array('import_type', 'format'));
240 // We don't want anything special in format
241 $format = PMA_securePath($format);
243 // Create error and goto url
244 if ($import_type == 'table') {
245 $err_url = 'tbl_import.php' . PMA_URL_getCommon(
247 'db' => $db, 'table' => $table
250 $_SESSION['Import_message']['go_back_url'] = $err_url;
251 $goto = 'tbl_import.php';
252 } elseif ($import_type == 'database') {
253 $err_url = 'db_import.php' . PMA_URL_getCommon(array('db' => $db));
254 $_SESSION['Import_message']['go_back_url'] = $err_url;
255 $goto = 'db_import.php';
256 } elseif ($import_type == 'server') {
257 $err_url = 'server_import.php' . PMA_URL_getCommon();
258 $_SESSION['Import_message']['go_back_url'] = $err_url;
259 $goto = 'server_import.php';
261 if (empty($goto) ||
!preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
262 if (mb_strlen($table) && mb_strlen($db)) {
263 $goto = 'tbl_structure.php';
264 } elseif (mb_strlen($db)) {
265 $goto = 'db_structure.php';
267 $goto = 'server_sql.php';
270 if (mb_strlen($table) && mb_strlen($db)) {
271 $common = PMA_URL_getCommon(array('db' => $db, 'table' => $table));
272 } elseif (mb_strlen($db)) {
273 $common = PMA_URL_getCommon(array('db' => $db));
275 $common = PMA_URL_getCommon();
277 $err_url = $goto . $common
278 . (preg_match('@^tbl_[a-z]*\.php$@', $goto)
279 ?
'&table=' . htmlspecialchars($table)
281 $_SESSION['Import_message']['go_back_url'] = $err_url;
283 // Avoid setting selflink to 'import.php'
284 // problem similar to bug 4276
285 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
286 $_SERVER['SCRIPT_NAME'] = $goto;
290 if (mb_strlen($db)) {
291 $GLOBALS['dbi']->selectDb($db);
294 @set_time_limit
($cfg['ExecTimeLimit']);
295 if (! empty($cfg['MemoryLimit'])) {
296 @ini_set
('memory_limit', $cfg['MemoryLimit']);
300 if (isset($_REQUEST['allow_interrupt'])) {
301 $maximum_time = ini_get('max_execution_time');
306 // set default values
307 $timeout_passed = false;
313 $file_to_unlink = '';
315 $sql_query_disabled = false;
317 $executed_queries = 0;
319 $charset_conversion = false;
320 $reset_charset = false;
321 $bookmark_created = false;
323 // Bookmark Support: get a query back from bookmark if required
324 if (! empty($_REQUEST['id_bookmark'])) {
325 $id_bookmark = (int)$_REQUEST['id_bookmark'];
326 include_once 'libraries/bookmark.lib.php';
327 switch ($_REQUEST['action_bookmark']) {
328 case 0: // bookmarked query that have to be run
329 $import_text = PMA_Bookmark_get(
333 isset($_REQUEST['action_bookmark_all'])
335 if (! empty($_REQUEST['bookmark_variable'])) {
336 $import_text = PMA_Bookmark_applyVariables(
341 // refresh navigation and main panels
343 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
346 $GLOBALS['reload'] = true;
347 $ajax_reload['reload'] = true;
350 // refresh navigation panel only
352 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
356 $ajax_reload['reload'] = true;
359 case 1: // bookmarked query that have to be displayed
360 $import_text = PMA_Bookmark_get($db, $id_bookmark);
361 if ($GLOBALS['is_ajax_request'] == true) {
362 $message = PMA\libraries\Message
::success(__('Showing bookmark'));
363 $response = PMA\libraries\Response
::getInstance();
364 $response->setRequestStatus($message->isSuccess());
365 $response->addJSON('message', $message);
366 $response->addJSON('sql_query', $import_text);
367 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
373 case 2: // bookmarked query that have to be deleted
374 $import_text = PMA_Bookmark_get($db, $id_bookmark);
375 PMA_Bookmark_delete($id_bookmark);
376 if ($GLOBALS['is_ajax_request'] == true) {
377 $message = PMA\libraries\Message
::success(
378 __('The bookmark has been deleted.')
380 $response = PMA\libraries\Response
::getInstance();
381 $response->setRequestStatus($message->isSuccess());
382 $response->addJSON('message', $message);
383 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
384 $response->addJSON('id_bookmark', $id_bookmark);
388 $error = true; // this is kind of hack to skip processing the query
392 } // end bookmarks reading
394 // Do no run query if we show PHP code
395 if (isset($GLOBALS['show_as_php'])) {
400 // We can not read all at once, otherwise we can run out of memory
401 $memory_limit = trim(@ini_get
('memory_limit'));
403 if (empty($memory_limit)) {
404 $memory_limit = 2 * 1024 * 1024;
406 // In case no memory limit we work on 10MB chunks
407 if ($memory_limit == -1) {
408 $memory_limit = 10 * 1024 * 1024;
411 // Calculate value of the limit
412 $memoryUnit = mb_strtolower(substr($memory_limit, -1));
413 if ('m' == $memoryUnit) {
414 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
415 } elseif ('k' == $memoryUnit) {
416 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
417 } elseif ('g' == $memoryUnit) {
418 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
420 $memory_limit = (int)$memory_limit;
423 // Just to be sure, there might be lot of memory needed for uncompression
424 $read_limit = $memory_limit / 8;
427 if (isset($_FILES['import_file'])) {
428 $import_file = $_FILES['import_file']['tmp_name'];
430 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
432 // sanitize $local_import_file as it comes from a POST
433 $local_import_file = PMA_securePath($local_import_file);
435 $import_file = PMA\libraries\Util
::userDir($cfg['UploadDir'])
436 . $local_import_file;
438 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
439 $import_file = 'none';
442 // Do we have file to import?
444 if ($import_file != 'none' && ! $error) {
445 // work around open_basedir and other limitations
446 $open_basedir = @ini_get
('open_basedir');
448 // If we are on a server with open_basedir, we must move the file
449 // before opening it.
451 if (! empty($open_basedir)) {
452 $tmp_subdir = ini_get('upload_tmp_dir');
453 if (empty($tmp_subdir)) {
454 $tmp_subdir = sys_get_temp_dir();
456 $tmp_subdir = rtrim($tmp_subdir, DIRECTORY_SEPARATOR
);
457 if (@is_writable
($tmp_subdir)) {
458 $import_file_new = $tmp_subdir . DIRECTORY_SEPARATOR
459 . basename($import_file) . uniqid();
460 if (move_uploaded_file($import_file, $import_file_new)) {
461 $import_file = $import_file_new;
462 $file_to_unlink = $import_file_new;
465 $size = filesize($import_file);
468 // If the php.ini is misconfigured (eg. there is no /tmp access defined
469 // with open_basedir), $tmp_subdir won't be writable and the user gets
470 // a 'File could not be read!' error (at PMA_detectCompression), which
471 // is not too meaningful. Show a meaningful error message to the user
474 $message = PMA\libraries\Message
::error(
476 'Uploaded file cannot be moved, because the server has ' .
477 'open_basedir enabled without access to the %s directory ' .
478 '(for temporary files).'
481 $message->addParam($tmp_subdir);
482 PMA_stopImport($message);
487 * Handle file compression
488 * @todo duplicate code exists in File.php
490 $compression = PMA_detectCompression($import_file);
491 if ($compression === false) {
492 $message = PMA\libraries\Message
::error(__('File could not be read!'));
493 PMA_stopImport($message); //Contains an 'exit'
496 switch ($compression) {
497 case 'application/bzip2':
498 if ($cfg['BZipDump'] && @function_exists
('bzopen')) {
499 $import_handle = @bzopen
($import_file, 'r');
501 $message = PMA\libraries\Message
::error(
503 'You attempted to load file with unsupported compression ' .
504 '(%s). Either support for it is not implemented or disabled ' .
505 'by your configuration.'
508 $message->addParam($compression);
509 PMA_stopImport($message);
512 case 'application/gzip':
513 if ($cfg['GZipDump'] && @function_exists
('gzopen')) {
514 $import_handle = @gzopen
($import_file, 'r');
516 $message = PMA\libraries\Message
::error(
518 'You attempted to load file with unsupported compression ' .
519 '(%s). Either support for it is not implemented or disabled ' .
520 'by your configuration.'
523 $message->addParam($compression);
524 PMA_stopImport($message);
527 case 'application/zip':
528 if ($cfg['ZipDump'] && @function_exists
('zip_open')) {
530 * Load interface for zip extension.
532 include_once 'libraries/zip_extension.lib.php';
533 $zipResult = PMA_getZipContents($import_file);
534 if (! empty($zipResult['error'])) {
535 $message = PMA\libraries\Message
::rawError($zipResult['error']);
536 PMA_stopImport($message);
538 $import_text = $zipResult['data'];
541 $message = PMA\libraries\Message
::error(
543 'You attempted to load file with unsupported compression ' .
544 '(%s). Either support for it is not implemented or disabled ' .
545 'by your configuration.'
548 $message->addParam($compression);
549 PMA_stopImport($message);
553 $import_handle = @fopen
($import_file, 'r');
556 $message = PMA\libraries\Message
::error(
558 'You attempted to load file with unsupported compression (%s). ' .
559 'Either support for it is not implemented or disabled by your ' .
563 $message->addParam($compression);
564 PMA_stopImport($message);
565 // the previous function exits
567 // use isset() because zip compression type does not use a handle
568 if (! $error && isset($import_handle) && $import_handle === false) {
569 $message = PMA\libraries\Message
::error(__('File could not be read!'));
570 PMA_stopImport($message);
572 } elseif (! $error) {
573 if (! isset($import_text) ||
empty($import_text)) {
574 $message = PMA\libraries\Message
::error(
576 'No data was received to import. Either no file name was ' .
577 'submitted, or the file size exceeded the maximum size permitted ' .
578 'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
581 PMA_stopImport($message);
585 // so we can obtain the message
586 //$_SESSION['Import_message'] = $message->getDisplay();
588 // Convert the file's charset if necessary
589 if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE
&& isset($charset_of_file)) {
590 if ($charset_of_file != 'utf-8') {
591 $charset_conversion = true;
593 } elseif (isset($charset_of_file) && $charset_of_file != 'utf-8') {
594 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
595 // We can not show query in this case, it is in different charset
596 $sql_query_disabled = true;
597 $reset_charset = true;
600 // Something to skip? (because timeout has passed)
601 if (! $error && isset($_POST['skip'])) {
602 $original_skip = $skip = $_POST['skip'];
604 PMA_importGetNextChunk($skip < $read_limit ?
$skip : $read_limit);
605 // Disable read progressivity, otherwise we eat all memory!
607 $skip -= $read_limit;
612 // This array contain the data like numberof valid sql queries in the statement
613 // and complete valid sql statement (which affected for rows)
614 $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
617 // Check for file existence
618 include_once "libraries/plugin_interface.lib.php";
619 /* @var $import_plugin ImportPlugin */
620 $import_plugin = PMA_getPlugin(
623 'libraries/plugins/import/',
626 if ($import_plugin == null) {
627 $message = PMA\libraries\Message
::error(
628 __('Could not load import plugins, please check your installation!')
630 PMA_stopImport($message);
632 // Do the real import
634 $default_fk_check = PMA\libraries\Util
::handleDisableFKCheckInit();
635 $import_plugin->doImport($sql_data);
636 PMA\libraries\Util
::handleDisableFKCheckCleanup($default_fk_check);
637 } catch (Exception
$e) {
638 PMA\libraries\Util
::handleDisableFKCheckCleanup($default_fk_check);
644 if (! empty($import_handle)) {
645 fclose($import_handle);
648 // Cleanup temporary file
649 if ($file_to_unlink != '') {
650 unlink($file_to_unlink);
653 // Reset charset back, if we did some changes
654 if ($reset_charset) {
655 $GLOBALS['dbi']->query('SET CHARACTER SET utf8');
656 $GLOBALS['dbi']->query(
657 'SET SESSION collation_connection =\'' . $collation_connection . '\''
661 // Show correct message
662 if (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 2) {
663 $message = PMA\libraries\Message
::success(__('The bookmark has been deleted.'));
664 $display_query = $import_text;
665 $error = false; // unset error marker, it was used just to skip processing
666 } elseif (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 1) {
667 $message = PMA\libraries\Message
::notice(__('Showing bookmark'));
668 } elseif ($bookmark_created) {
669 $special_message = '[br]' . sprintf(
670 __('Bookmark %s has been created.'),
671 htmlspecialchars($_POST['bkm_label'])
673 } elseif ($finished && ! $error) {
674 // Do not display the query with message, we do it separately
675 $display_query = ';';
676 if ($import_type != 'query') {
677 $message = PMA\libraries\Message
::success(
680 'Import has been successfully finished, %d query executed.',
681 'Import has been successfully finished, %d queries executed.',
686 $message->addParam($executed_queries);
688 if ($import_notice) {
689 $message->addString($import_notice);
691 if (! empty($local_import_file)) {
692 $message->addString('(' . htmlspecialchars($local_import_file) . ')');
695 '(' . htmlspecialchars($_FILES['import_file']['name']) . ')'
701 // Did we hit timeout? Tell it user.
702 if ($timeout_passed) {
703 $importUrl = $err_url .= '&timeout_passed=1&offset=' . urlencode(
706 if (isset($local_import_file)) {
707 $importUrl .= '&local_import_file=' . urlencode($local_import_file);
709 $message = PMA\libraries\Message
::error(
711 'Script timeout passed, if you want to finish import,'
712 . ' please %sresubmit the same file%s and import will resume.'
715 $message->addParam('<a href="' . $importUrl . '">', false);
716 $message->addParam('</a>', false);
718 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
721 'However on last run no data has been parsed,'
722 . ' this usually means phpMyAdmin won\'t be able to'
723 . ' finish this import unless you increase php time limits.'
729 // if there is any message, copy it into $_SESSION as well,
730 // so we can obtain it by AJAX call
731 if (isset($message)) {
732 $_SESSION['Import_message']['message'] = $message->getDisplay();
734 // Parse and analyze the query, for correct db and table name
735 // in case of a query typed in the query window
736 // (but if the query is too large, in case of an imported file, the parser
737 // can choke on it so avoid parsing)
738 $sqlLength = mb_strlen($sql_query);
739 if ($sqlLength <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
740 include_once 'libraries/parse_analyze.lib.php';
743 $analyzed_sql_results,
746 ) = PMA_parseAnalyze($sql_query, $db);
747 // @todo: possibly refactor
748 extract($analyzed_sql_results);
751 // There was an error?
752 if (isset($my_die)) {
753 foreach ($my_die as $key => $die) {
754 PMA\libraries\Util
::mysqlDie(
755 $die['error'], $die['sql'], false, $err_url, $error
762 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
763 $_SESSION['is_multi_query'] = true;
764 $sql_queries = $sql_data['valid_sql'];
766 $sql_queries = array($sql_query);
770 foreach ($sql_queries as $sql_query) {
773 include_once 'libraries/parse_analyze.lib.php';
775 $analyzed_sql_results,
778 ) = PMA_parseAnalyze($sql_query, $db);
779 // @todo: possibly refactor
780 extract($analyzed_sql_results);
782 $html_output .= PMA_executeQueryAndGetQueryResponse(
783 $analyzed_sql_results, // analyzed_sql_results
784 false, // is_gotofile
787 null, // find_real_end
788 $_REQUEST['sql_query'], // sql_query_for_bookmark
790 null, // message_to_show
794 $pmaThemeImage, // pmaThemeImage
796 null, // disp_message
798 $sql_query, // sql_query
799 null, // selectedTables
800 null // complete_query
804 $response = PMA\libraries\Response
::getInstance();
805 $response->addJSON('ajax_reload', $ajax_reload);
806 $response->addHTML($html_output);
809 } else if ($result) {
810 // Save a Bookmark with more than one queries (if Bookmark label given).
811 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
812 $cfgBookmark = PMA_Bookmark_getParams();
813 PMA_storeTheQueryAsBookmark(
814 $db, $cfgBookmark['user'],
815 $_REQUEST['sql_query'], $_POST['bkm_label'],
816 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
820 $response = PMA\libraries\Response
::getInstance();
821 $response->setRequestStatus(true);
822 $response->addJSON('message', PMA\libraries\Message
::success($msg));
825 PMA\libraries\Util
::getMessage($msg, $sql_query, 'success')
827 } else if ($result == false) {
828 $response = PMA\libraries\Response
::getInstance();
829 $response->setRequestStatus(false);
830 $response->addJSON('message', PMA\libraries\Message
::error($msg));
832 $active_page = $goto;
836 // If there is request for ROLLBACK in the end.
837 if (isset($_REQUEST['rollback_query'])) {
838 $GLOBALS['dbi']->query('ROLLBACK');