2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Core script for import, this is just the glue around all other stuff
10 * Get the variables sent or posted to this script and a core script
12 require_once 'libraries/common.inc.php';
13 require_once 'libraries/sql.lib.php';
14 require_once 'libraries/bookmark.lib.php';
15 require_once 'libraries/Console.class.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_Response
::getInstance();
35 'console_message_bookmark', PMA_Console
::getBookmarkContent()
39 // If it's a console bookmark add request
40 if (isset($_REQUEST['console_bookmark_add'])) {
41 $response = PMA_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'));
68 * Sets globals from $_POST
82 // TODO: adapt full list of allowed parameters, as in export.php
83 foreach ($post_params as $one_post_param) {
84 if (isset($_POST[$one_post_param])) {
85 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
89 // reset import messages for ajax request
90 $_SESSION['Import_message']['message'] = null;
91 $_SESSION['Import_message']['go_back_url'] = null;
93 $GLOBALS['reload'] = false;
95 // Use to identify current cycle is executing
96 // a multiquery statement or stored routine
97 if (!isset($_SESSION['is_multi_query'])) {
98 $_SESSION['is_multi_query'] = false;
101 $ajax_reload = array();
102 // Are we just executing plain query or sql file?
103 // (eg. non import, but query box/window run)
104 if (! empty($sql_query)) {
106 // apply values for parameters
107 if (! empty($_REQUEST['parameterized'])
108 && ! empty($_REQUEST['parameters'])
109 && is_array($_REQUEST['parameters'])) {
110 $parameters = $_REQUEST['parameters'];
111 foreach ($parameters as $parameter => $replacement) {
112 $quoted = preg_quote($parameter);
113 // making sure that :param does not apply values to :param1
114 $sql_query = preg_replace(
115 '/' . $quoted . '([^a-zA-Z0-9_])/',
116 PMA_Util
::sqlAddSlashes($replacement) . '${1}',
119 // for parameters the appear at the end of the string
120 $sql_query = preg_replace(
121 '/' . $quoted . '$/',
122 PMA_Util
::sqlAddSlashes($replacement),
129 $import_text = $sql_query;
130 $import_type = 'query';
132 $_SESSION['sql_from_query_box'] = true;
134 // If there is a request to ROLLBACK when finished.
135 if (isset($_REQUEST['rollback_query'])) {
136 PMA_handleRollbackRequest($import_text);
139 // refresh navigation and main panels
140 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
141 $GLOBALS['reload'] = true;
142 $ajax_reload['reload'] = true;
145 // refresh navigation panel only
147 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
150 $ajax_reload['reload'] = true;
153 // do a dynamic reload if table is RENAMED
154 // (by sending the instruction to the AJAX response handler)
156 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
160 $ajax_reload['reload'] = true;
161 $ajax_reload['table_name'] = PMA_Util
::unQuote($rename_table_names[2]);
165 } elseif (! empty($sql_file)) {
166 // run uploaded SQL file
167 $import_file = $sql_file;
168 $import_type = 'queryfile';
171 } elseif (! empty($_REQUEST['id_bookmark'])) {
173 $import_type = 'query';
177 // If we didn't get any parameters, either user called this directly, or
178 // upload limit has been reached, let's assume the second possibility.
179 if ($_POST == array() && $_GET == array()) {
180 $message = PMA_Message
::error(
182 'You probably tried to upload a file that is too large. Please refer ' .
183 'to %sdocumentation%s for a workaround for this limit.'
186 $message->addParam('[doc@faq1-16]');
187 $message->addParam('[/doc]');
189 // so we can obtain the message
190 $_SESSION['Import_message']['message'] = $message->getDisplay();
191 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
194 exit; // the footer is displayed automatically
197 // Add console message id to response output
198 if (isset($_POST['console_message_id'])) {
199 $response = PMA_Response
::getInstance();
200 $response->addJSON('console_message_id', $_POST['console_message_id']);
204 * Sets globals from $_POST patterns, for import plugins
205 * We only need to load the selected plugin
221 // this should not happen for a normal user
222 // but only during an attack
223 PMA_fatalError('Incorrect format parameter');
226 $post_patterns = array(
228 '/^' . $format . '_/'
231 PMA_setPostAsGlobal($post_patterns);
233 // Check needed parameters
234 PMA_Util
::checkParameters(array('import_type', 'format'));
236 // We don't want anything special in format
237 $format = PMA_securePath($format);
238 /** @var PMA_String $pmaString */
239 $pmaString = $GLOBALS['PMA_String'];
241 // Create error and goto url
242 if ($import_type == 'table') {
243 $err_url = 'tbl_import.php' . PMA_URL_getCommon(
245 'db' => $db, 'table' => $table
248 $_SESSION['Import_message']['go_back_url'] = $err_url;
249 $goto = 'tbl_import.php';
250 } elseif ($import_type == 'database') {
251 $err_url = 'db_import.php' . PMA_URL_getCommon(array('db' => $db));
252 $_SESSION['Import_message']['go_back_url'] = $err_url;
253 $goto = 'db_import.php';
254 } elseif ($import_type == 'server') {
255 $err_url = 'server_import.php' . PMA_URL_getCommon();
256 $_SESSION['Import_message']['go_back_url'] = $err_url;
257 $goto = 'server_import.php';
259 if (empty($goto) ||
!preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
260 if (/*overload*/mb_strlen($table) && /*overload*/mb_strlen($db)) {
261 $goto = 'tbl_structure.php';
262 } elseif (/*overload*/mb_strlen($db)) {
263 $goto = 'db_structure.php';
265 $goto = 'server_sql.php';
268 if (/*overload*/mb_strlen($table) && /*overload*/mb_strlen($db)) {
269 $common = PMA_URL_getCommon(array('db' => $db, 'table' => $table));
270 } elseif (/*overload*/mb_strlen($db)) {
271 $common = PMA_URL_getCommon(array('db' => $db));
273 $common = PMA_URL_getCommon();
275 $err_url = $goto . $common
276 . (preg_match('@^tbl_[a-z]*\.php$@', $goto)
277 ?
'&table=' . htmlspecialchars($table)
279 $_SESSION['Import_message']['go_back_url'] = $err_url;
281 // Avoid setting selflink to 'import.php'
282 // problem similar to bug 4276
283 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
284 $_SERVER['SCRIPT_NAME'] = $goto;
288 if (/*overload*/mb_strlen($db)) {
289 $GLOBALS['dbi']->selectDb($db);
292 @set_time_limit
($cfg['ExecTimeLimit']);
293 if (! empty($cfg['MemoryLimit'])) {
294 @ini_set
('memory_limit', $cfg['MemoryLimit']);
298 if (isset($_REQUEST['allow_interrupt'])) {
299 $maximum_time = ini_get('max_execution_time');
304 // set default values
305 $timeout_passed = false;
311 $file_to_unlink = '';
313 $sql_query_disabled = false;
315 $executed_queries = 0;
317 $charset_conversion = false;
318 $reset_charset = false;
319 $bookmark_created = false;
321 // Bookmark Support: get a query back from bookmark if required
322 if (! empty($_REQUEST['id_bookmark'])) {
323 $id_bookmark = (int)$_REQUEST['id_bookmark'];
324 include_once 'libraries/bookmark.lib.php';
325 switch ($_REQUEST['action_bookmark']) {
326 case 0: // bookmarked query that have to be run
327 $import_text = PMA_Bookmark_get(
331 isset($_REQUEST['action_bookmark_all'])
333 if (! empty($_REQUEST['bookmark_variable'])) {
334 $import_text = PMA_Bookmark_applyVariables(
339 // refresh navigation and main panels
341 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
344 $GLOBALS['reload'] = true;
345 $ajax_reload['reload'] = true;
348 // refresh navigation panel only
350 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
354 $ajax_reload['reload'] = true;
357 case 1: // bookmarked query that have to be displayed
358 $import_text = PMA_Bookmark_get($db, $id_bookmark);
359 if ($GLOBALS['is_ajax_request'] == true) {
360 $message = PMA_Message
::success(__('Showing bookmark'));
361 $response = PMA_Response
::getInstance();
362 $response->isSuccess($message->isSuccess());
363 $response->addJSON('message', $message);
364 $response->addJSON('sql_query', $import_text);
365 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
371 case 2: // bookmarked query that have to be deleted
372 $import_text = PMA_Bookmark_get($db, $id_bookmark);
373 PMA_Bookmark_delete($id_bookmark);
374 if ($GLOBALS['is_ajax_request'] == true) {
375 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
376 $response = PMA_Response
::getInstance();
377 $response->isSuccess($message->isSuccess());
378 $response->addJSON('message', $message);
379 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
380 $response->addJSON('id_bookmark', $id_bookmark);
384 $error = true; // this is kind of hack to skip processing the query
388 } // end bookmarks reading
390 // Do no run query if we show PHP code
391 if (isset($GLOBALS['show_as_php'])) {
396 // We can not read all at once, otherwise we can run out of memory
397 $memory_limit = trim(@ini_get
('memory_limit'));
399 if (empty($memory_limit)) {
400 $memory_limit = 2 * 1024 * 1024;
402 // In case no memory limit we work on 10MB chunks
403 if ($memory_limit == -1) {
404 $memory_limit = 10 * 1024 * 1024;
407 // Calculate value of the limit
408 $memoryUnit = /*overload*/mb_strtolower(substr($memory_limit, -1));
409 if ('m' == $memoryUnit) {
410 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
411 } elseif ('k' == $memoryUnit) {
412 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
413 } elseif ('g' == $memoryUnit) {
414 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
416 $memory_limit = (int)$memory_limit;
419 // Just to be sure, there might be lot of memory needed for uncompression
420 $read_limit = $memory_limit / 8;
423 if (isset($_FILES['import_file'])) {
424 $import_file = $_FILES['import_file']['tmp_name'];
426 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
428 // sanitize $local_import_file as it comes from a POST
429 $local_import_file = PMA_securePath($local_import_file);
431 $import_file = PMA_Util
::userDir($cfg['UploadDir'])
432 . $local_import_file;
434 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
435 $import_file = 'none';
438 // Do we have file to import?
440 if ($import_file != 'none' && ! $error) {
441 // work around open_basedir and other limitations
442 $open_basedir = @ini_get
('open_basedir');
444 // If we are on a server with open_basedir, we must move the file
445 // before opening it.
447 if (! empty($open_basedir)) {
448 $tmp_subdir = ini_get('upload_tmp_dir');
449 if (empty($tmp_subdir)) {
450 $tmp_subdir = sys_get_temp_dir();
452 $tmp_subdir = rtrim($tmp_subdir, DIRECTORY_SEPARATOR
);
453 if (is_writable($tmp_subdir)) {
454 $import_file_new = $tmp_subdir . DIRECTORY_SEPARATOR
455 . basename($import_file) . uniqid();
456 if (move_uploaded_file($import_file, $import_file_new)) {
457 $import_file = $import_file_new;
458 $file_to_unlink = $import_file_new;
461 $size = filesize($import_file);
464 // If the php.ini is misconfigured (eg. there is no /tmp access defined
465 // with open_basedir), $tmp_subdir won't be writable and the user gets
466 // a 'File could not be read!' error (at PMA_detectCompression), which
467 // is not too meaningful. Show a meaningful error message to the user
470 $message = PMA_Message
::error(
472 'Uploaded file cannot be moved, because the server has ' .
473 'open_basedir enabled without access to the %s directory ' .
474 '(for temporary files).'
477 $message->addParam($tmp_subdir);
478 PMA_stopImport($message);
483 * Handle file compression
484 * @todo duplicate code exists in File.class.php
486 $compression = PMA_detectCompression($import_file);
487 if ($compression === false) {
488 $message = PMA_Message
::error(__('File could not be read!'));
489 PMA_stopImport($message); //Contains an 'exit'
492 switch ($compression) {
493 case 'application/bzip2':
494 if ($cfg['BZipDump'] && @function_exists
('bzopen')) {
495 $import_handle = @bzopen
($import_file, 'r');
497 $message = PMA_Message
::error(
499 'You attempted to load file with unsupported compression ' .
500 '(%s). Either support for it is not implemented or disabled ' .
501 'by your configuration.'
504 $message->addParam($compression);
505 PMA_stopImport($message);
508 case 'application/gzip':
509 if ($cfg['GZipDump'] && @function_exists
('gzopen')) {
510 $import_handle = @gzopen
($import_file, 'r');
512 $message = PMA_Message
::error(
514 'You attempted to load file with unsupported compression ' .
515 '(%s). Either support for it is not implemented or disabled ' .
516 'by your configuration.'
519 $message->addParam($compression);
520 PMA_stopImport($message);
523 case 'application/zip':
524 if ($cfg['ZipDump'] && @function_exists
('zip_open')) {
526 * Load interface for zip extension.
528 include_once 'libraries/zip_extension.lib.php';
529 $zipResult = PMA_getZipContents($import_file);
530 if (! empty($zipResult['error'])) {
531 $message = PMA_Message
::rawError($zipResult['error']);
532 PMA_stopImport($message);
534 $import_text = $zipResult['data'];
537 $message = PMA_Message
::error(
539 'You attempted to load file with unsupported compression ' .
540 '(%s). Either support for it is not implemented or disabled ' .
541 'by your configuration.'
544 $message->addParam($compression);
545 PMA_stopImport($message);
549 $import_handle = @fopen
($import_file, 'r');
552 $message = PMA_Message
::error(
554 'You attempted to load file with unsupported compression (%s). ' .
555 'Either support for it is not implemented or disabled by your ' .
559 $message->addParam($compression);
560 PMA_stopImport($message);
563 // use isset() because zip compression type does not use a handle
564 if (! $error && isset($import_handle) && $import_handle === false) {
565 $message = PMA_Message
::error(__('File could not be read!'));
566 PMA_stopImport($message);
568 } elseif (! $error) {
569 if (! isset($import_text) ||
empty($import_text)) {
570 $message = PMA_Message
::error(
572 'No data was received to import. Either no file name was ' .
573 'submitted, or the file size exceeded the maximum size permitted ' .
574 'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
577 PMA_stopImport($message);
581 // so we can obtain the message
582 //$_SESSION['Import_message'] = $message->getDisplay();
584 // Convert the file's charset if necessary
585 if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE
&& isset($charset_of_file)) {
586 if ($charset_of_file != 'utf-8') {
587 $charset_conversion = true;
589 } elseif (isset($charset_of_file) && $charset_of_file != 'utf-8') {
591 // Drizzle doesn't support other character sets,
592 // so we can't fallback to SET NAMES - throw an error
593 $message = PMA_Message
::error(
595 'Cannot convert file\'s character'
596 . ' set without character set conversion library!'
599 PMA_stopImport($message);
601 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
602 // We can not show query in this case, it is in different charset
603 $sql_query_disabled = true;
604 $reset_charset = true;
608 // Something to skip? (because timeout has passed)
609 if (! $error && isset($_POST['skip'])) {
610 $original_skip = $skip = $_POST['skip'];
612 PMA_importGetNextChunk($skip < $read_limit ?
$skip : $read_limit);
613 // Disable read progressivity, otherwise we eat all memory!
615 $skip -= $read_limit;
620 // This array contain the data like numberof valid sql queries in the statement
621 // and complete valid sql statement (which affected for rows)
622 $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
625 // Check for file existence
626 include_once "libraries/plugin_interface.lib.php";
627 /* @var $import_plugin ImportPlugin */
628 $import_plugin = PMA_getPlugin(
631 'libraries/plugins/import/',
634 if ($import_plugin == null) {
635 $message = PMA_Message
::error(
636 __('Could not load import plugins, please check your installation!')
638 PMA_stopImport($message);
640 // Do the real import
642 $default_fk_check = PMA_Util
::handleDisableFKCheckInit();
643 $import_plugin->doImport($sql_data);
644 PMA_Util
::handleDisableFKCheckCleanup($default_fk_check);
645 } catch (Exception
$e) {
646 PMA_Util
::handleDisableFKCheckCleanup($default_fk_check);
652 if (! empty($import_handle)) {
653 fclose($import_handle);
656 // Cleanup temporary file
657 if ($file_to_unlink != '') {
658 unlink($file_to_unlink);
661 // Reset charset back, if we did some changes
662 if ($reset_charset) {
663 $GLOBALS['dbi']->query('SET CHARACTER SET utf8');
664 $GLOBALS['dbi']->query(
665 'SET SESSION collation_connection =\'' . $collation_connection . '\''
669 // Show correct message
670 if (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 2) {
671 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
672 $display_query = $import_text;
673 $error = false; // unset error marker, it was used just to skip processing
674 } elseif (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 1) {
675 $message = PMA_Message
::notice(__('Showing bookmark'));
676 } elseif ($bookmark_created) {
677 $special_message = '[br]' . sprintf(
678 __('Bookmark %s has been created.'),
679 htmlspecialchars($_POST['bkm_label'])
681 } elseif ($finished && ! $error) {
682 if ($import_type == 'query') {
683 $message = PMA_Message
::success();
685 $message = PMA_Message
::success(
687 . __('Import has been successfully finished, %d queries executed.')
690 $message->addParam($executed_queries);
692 if ($import_notice) {
693 $message->addString($import_notice);
695 if (! empty($local_import_file)) {
696 $message->addString('(' . htmlspecialchars($local_import_file) . ')');
699 '(' . htmlspecialchars($_FILES['import_file']['name']) . ')'
705 // Did we hit timeout? Tell it user.
706 if ($timeout_passed) {
707 $importUrl = $err_url .= '&timeout_passed=1&offset=' . urlencode(
710 if (isset($local_import_file)) {
711 $importUrl .= '&local_import_file=' . urlencode($local_import_file);
713 $message = PMA_Message
::error(
715 'Script timeout passed, if you want to finish import,'
716 . ' please %sresubmit the same file%s and import will resume.'
719 $message->addParam('<a href="' . $importUrl . '">', false);
720 $message->addParam('</a>', false);
722 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
725 'However on last run no data has been parsed,'
726 . ' this usually means phpMyAdmin won\'t be able to'
727 . ' finish this import unless you increase php time limits.'
733 // if there is any message, copy it into $_SESSION as well,
734 // so we can obtain it by AJAX call
735 if (isset($message)) {
736 $_SESSION['Import_message']['message'] = $message->getDisplay();
738 // Parse and analyze the query, for correct db and table name
739 // in case of a query typed in the query window
740 // (but if the query is too large, in case of an imported file, the parser
741 // can choke on it so avoid parsing)
742 $sqlLength = /*overload*/mb_strlen($sql_query);
743 if ($sqlLength <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
744 include_once 'libraries/parse_analyze.inc.php';
747 // There was an error?
748 if (isset($my_die)) {
749 foreach ($my_die as $key => $die) {
751 $die['error'], $die['sql'], false, $err_url, $error
758 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
759 $_SESSION['is_multi_query'] = true;
760 $sql_queries = $sql_data['valid_sql'];
762 $sql_queries = array($sql_query);
766 foreach ($sql_queries as $sql_query) {
768 include 'libraries/parse_analyze.inc.php';
770 $html_output .= PMA_executeQueryAndGetQueryResponse(
771 $analyzed_sql_results, // analyzed_sql_results
772 false, // is_gotofile
775 null, // find_real_end
776 $_REQUEST['sql_query'], // sql_query_for_bookmark
778 null, // message_to_show
782 $pmaThemeImage, // pmaThemeImage
784 null, // disp_message
786 $sql_query, // sql_query
787 null, // selectedTables
788 null // complete_query
792 $response = PMA_Response
::getInstance();
793 $response->addJSON('ajax_reload', $ajax_reload);
794 $response->addHTML($html_output);
797 } else if ($result) {
798 // Save a Bookmark with more than one queries (if Bookmark label given).
799 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
800 $cfgBookmark = PMA_Bookmark_getParams();
801 PMA_storeTheQueryAsBookmark(
802 $db, $cfgBookmark['user'],
803 $_REQUEST['sql_query'], $_POST['bkm_label'],
804 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
808 $response = PMA_Response
::getInstance();
809 $response->isSuccess(true);
810 $response->addJSON('message', PMA_Message
::success($msg));
813 PMA_Util
::getMessage($msg, $sql_query, 'success')
815 } else if ($result == false) {
816 $response = PMA_Response
::getInstance();
817 $response->isSuccess(false);
818 $response->addJSON('message', PMA_Message
::error($msg));
820 $active_page = $goto;
824 // If there is request for ROLLBACK in the end.
825 if (isset($_REQUEST['rollback_query'])) {
826 $GLOBALS['dbi']->query('ROLLBACK');