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
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 $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_localfile)) {
166 // run SQL file on server
167 $local_import_file = $sql_localfile;
168 $import_type = 'queryfile';
170 unset($sql_localfile);
171 } elseif (! empty($sql_file)) {
172 // run uploaded SQL file
173 $import_file = $sql_file;
174 $import_type = 'queryfile';
177 } elseif (! empty($_REQUEST['id_bookmark'])) {
179 $import_type = 'query';
183 // If we didn't get any parameters, either user called this directly, or
184 // upload limit has been reached, let's assume the second possibility.
185 if ($_POST == array() && $_GET == array()) {
186 $message = PMA_Message
::error(
188 'You probably tried to upload a file that is too large. Please refer ' .
189 'to %sdocumentation%s for a workaround for this limit.'
192 $message->addParam('[doc@faq1-16]');
193 $message->addParam('[/doc]');
195 // so we can obtain the message
196 $_SESSION['Import_message']['message'] = $message->getDisplay();
197 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
200 exit; // the footer is displayed automatically
203 // Add console message id to response output
204 if (isset($_POST['console_message_id'])) {
205 $response = PMA_Response
::getInstance();
206 $response->addJSON('console_message_id', $_POST['console_message_id']);
210 * Sets globals from $_POST patterns, for import plugins
211 * We only need to load the selected plugin
227 // this should not happen for a normal user
228 // but only during an attack
229 PMA_fatalError('Incorrect format parameter');
232 $post_patterns = array(
234 '/^' . $format . '_/'
237 PMA_setPostAsGlobal($post_patterns);
239 // Check needed parameters
240 PMA_Util
::checkParameters(array('import_type', 'format'));
242 // We don't want anything special in format
243 $format = PMA_securePath($format);
244 /** @var PMA_String $pmaString */
245 $pmaString = $GLOBALS['PMA_String'];
247 // Create error and goto url
248 if ($import_type == 'table') {
249 $err_url = 'tbl_import.php' . PMA_URL_getCommon(
251 'db' => $db, 'table' => $table
254 $_SESSION['Import_message']['go_back_url'] = $err_url;
255 $goto = 'tbl_import.php';
256 } elseif ($import_type == 'database') {
257 $err_url = 'db_import.php' . PMA_URL_getCommon(array('db' => $db));
258 $_SESSION['Import_message']['go_back_url'] = $err_url;
259 $goto = 'db_import.php';
260 } elseif ($import_type == 'server') {
261 $err_url = 'server_import.php' . PMA_URL_getCommon();
262 $_SESSION['Import_message']['go_back_url'] = $err_url;
263 $goto = 'server_import.php';
265 if (empty($goto) ||
!preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
266 if (/*overload*/mb_strlen($table) && /*overload*/mb_strlen($db)) {
267 $goto = 'tbl_structure.php';
268 } elseif (/*overload*/mb_strlen($db)) {
269 $goto = 'db_structure.php';
271 $goto = 'server_sql.php';
274 if (/*overload*/mb_strlen($table) && /*overload*/mb_strlen($db)) {
275 $common = PMA_URL_getCommon(array('db' => $db, 'table' => $table));
276 } elseif (/*overload*/mb_strlen($db)) {
277 $common = PMA_URL_getCommon(array('db' => $db));
279 $common = PMA_URL_getCommon();
281 $err_url = $goto . $common
282 . (preg_match('@^tbl_[a-z]*\.php$@', $goto)
283 ?
'&table=' . htmlspecialchars($table)
285 $_SESSION['Import_message']['go_back_url'] = $err_url;
287 // Avoid setting selflink to 'import.php'
288 // problem similar to bug 4276
289 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
290 $_SERVER['SCRIPT_NAME'] = $goto;
294 if (/*overload*/mb_strlen($db)) {
295 $GLOBALS['dbi']->selectDb($db);
298 @set_time_limit
($cfg['ExecTimeLimit']);
299 if (! empty($cfg['MemoryLimit'])) {
300 @ini_set
('memory_limit', $cfg['MemoryLimit']);
304 if (isset($_REQUEST['allow_interrupt'])) {
305 $maximum_time = ini_get('max_execution_time');
310 // set default values
311 $timeout_passed = false;
317 $file_to_unlink = '';
319 $sql_query_disabled = false;
321 $executed_queries = 0;
323 $charset_conversion = false;
324 $reset_charset = false;
325 $bookmark_created = false;
327 // Bookmark Support: get a query back from bookmark if required
328 if (! empty($_REQUEST['id_bookmark'])) {
329 $id_bookmark = (int)$_REQUEST['id_bookmark'];
330 include_once 'libraries/bookmark.lib.php';
331 switch ($_REQUEST['action_bookmark']) {
332 case 0: // bookmarked query that have to be run
333 $import_text = PMA_Bookmark_get(
337 isset($_REQUEST['action_bookmark_all'])
339 if (! empty($_REQUEST['bookmark_variable'])) {
340 $import_text = PMA_Bookmark_applyVariables(
345 // refresh navigation and main panels
347 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
350 $GLOBALS['reload'] = true;
351 $ajax_reload['reload'] = true;
354 // refresh navigation panel only
356 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
360 $ajax_reload['reload'] = true;
363 case 1: // bookmarked query that have to be displayed
364 $import_text = PMA_Bookmark_get($db, $id_bookmark);
365 if ($GLOBALS['is_ajax_request'] == true) {
366 $message = PMA_Message
::success(__('Showing bookmark'));
367 $response = PMA_Response
::getInstance();
368 $response->isSuccess($message->isSuccess());
369 $response->addJSON('message', $message);
370 $response->addJSON('sql_query', $import_text);
371 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
377 case 2: // bookmarked query that have to be deleted
378 $import_text = PMA_Bookmark_get($db, $id_bookmark);
379 PMA_Bookmark_delete($id_bookmark);
380 if ($GLOBALS['is_ajax_request'] == true) {
381 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
382 $response = PMA_Response
::getInstance();
383 $response->isSuccess($message->isSuccess());
384 $response->addJSON('message', $message);
385 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
386 $response->addJSON('id_bookmark', $id_bookmark);
390 $error = true; // this is kind of hack to skip processing the query
394 } // end bookmarks reading
396 // Do no run query if we show PHP code
397 if (isset($GLOBALS['show_as_php'])) {
402 // We can not read all at once, otherwise we can run out of memory
403 $memory_limit = trim(@ini_get
('memory_limit'));
405 if (empty($memory_limit)) {
406 $memory_limit = 2 * 1024 * 1024;
408 // In case no memory limit we work on 10MB chunks
409 if ($memory_limit == -1) {
410 $memory_limit = 10 * 1024 * 1024;
413 // Calculate value of the limit
414 $memoryUnit = /*overload*/mb_strtolower(substr($memory_limit, -1));
415 if ('m' == $memoryUnit) {
416 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
417 } elseif ('k' == $memoryUnit) {
418 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
419 } elseif ('g' == $memoryUnit) {
420 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
422 $memory_limit = (int)$memory_limit;
425 // Just to be sure, there might be lot of memory needed for uncompression
426 $read_limit = $memory_limit / 8;
429 if (isset($_FILES['import_file'])) {
430 $import_file = $_FILES['import_file']['tmp_name'];
432 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
434 // sanitize $local_import_file as it comes from a POST
435 $local_import_file = PMA_securePath($local_import_file);
437 $import_file = PMA_Util
::userDir($cfg['UploadDir'])
438 . $local_import_file;
440 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
441 $import_file = 'none';
444 // Do we have file to import?
446 if ($import_file != 'none' && ! $error) {
447 // work around open_basedir and other limitations
448 $open_basedir = @ini_get
('open_basedir');
450 // If we are on a server with open_basedir, we must move the file
451 // before opening it.
453 if (! empty($open_basedir)) {
454 $tmp_subdir = ini_get('upload_tmp_dir');
455 if (empty($tmp_subdir)) {
456 $tmp_subdir = sys_get_temp_dir();
458 $tmp_subdir = rtrim($tmp_subdir, DIRECTORY_SEPARATOR
);
459 if (is_writable($tmp_subdir)) {
460 $import_file_new = $tmp_subdir . DIRECTORY_SEPARATOR
461 . basename($import_file) . uniqid();
462 if (move_uploaded_file($import_file, $import_file_new)) {
463 $import_file = $import_file_new;
464 $file_to_unlink = $import_file_new;
467 $size = filesize($import_file);
470 // If the php.ini is misconfigured (eg. there is no /tmp access defined
471 // with open_basedir), $tmp_subdir won't be writable and the user gets
472 // a 'File could not be read!' error (at PMA_detectCompression), which
473 // is not too meaningful. Show a meaningful error message to the user
476 $message = PMA_Message
::error(
478 'Uploaded file cannot be moved, because the server has ' .
479 'open_basedir enabled without access to the %s directory ' .
480 '(for temporary files).'
483 $message->addParam($tmp_subdir);
484 PMA_stopImport($message);
489 * Handle file compression
490 * @todo duplicate code exists in File.class.php
492 $compression = PMA_detectCompression($import_file);
493 if ($compression === false) {
494 $message = PMA_Message
::error(__('File could not be read!'));
495 PMA_stopImport($message); //Contains an 'exit'
498 switch ($compression) {
499 case 'application/bzip2':
500 if ($cfg['BZipDump'] && @function_exists
('bzopen')) {
501 $import_handle = @bzopen
($import_file, 'r');
503 $message = PMA_Message
::error(
505 'You attempted to load file with unsupported compression ' .
506 '(%s). Either support for it is not implemented or disabled ' .
507 'by your configuration.'
510 $message->addParam($compression);
511 PMA_stopImport($message);
514 case 'application/gzip':
515 if ($cfg['GZipDump'] && @function_exists
('gzopen')) {
516 $import_handle = @gzopen
($import_file, 'r');
518 $message = PMA_Message
::error(
520 'You attempted to load file with unsupported compression ' .
521 '(%s). Either support for it is not implemented or disabled ' .
522 'by your configuration.'
525 $message->addParam($compression);
526 PMA_stopImport($message);
529 case 'application/zip':
530 if ($cfg['ZipDump'] && @function_exists
('zip_open')) {
532 * Load interface for zip extension.
534 include_once 'libraries/zip_extension.lib.php';
535 $zipResult = PMA_getZipContents($import_file);
536 if (! empty($zipResult['error'])) {
537 $message = PMA_Message
::rawError($zipResult['error']);
538 PMA_stopImport($message);
540 $import_text = $zipResult['data'];
543 $message = PMA_Message
::error(
545 'You attempted to load file with unsupported compression ' .
546 '(%s). Either support for it is not implemented or disabled ' .
547 'by your configuration.'
550 $message->addParam($compression);
551 PMA_stopImport($message);
555 $import_handle = @fopen
($import_file, 'r');
558 $message = PMA_Message
::error(
560 'You attempted to load file with unsupported compression (%s). ' .
561 'Either support for it is not implemented or disabled by your ' .
565 $message->addParam($compression);
566 PMA_stopImport($message);
569 // use isset() because zip compression type does not use a handle
570 if (! $error && isset($import_handle) && $import_handle === false) {
571 $message = PMA_Message
::error(__('File could not be read!'));
572 PMA_stopImport($message);
574 } elseif (! $error) {
575 if (! isset($import_text) ||
empty($import_text)) {
576 $message = PMA_Message
::error(
578 'No data was received to import. Either no file name was ' .
579 'submitted, or the file size exceeded the maximum size permitted ' .
580 'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
583 PMA_stopImport($message);
587 // so we can obtain the message
588 //$_SESSION['Import_message'] = $message->getDisplay();
590 // Convert the file's charset if necessary
591 if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE
&& isset($charset_of_file)) {
592 if ($charset_of_file != 'utf-8') {
593 $charset_conversion = true;
595 } elseif (isset($charset_of_file) && $charset_of_file != 'utf-8') {
597 // Drizzle doesn't support other character sets,
598 // so we can't fallback to SET NAMES - throw an error
599 $message = PMA_Message
::error(
601 'Cannot convert file\'s character'
602 . ' set without character set conversion library!'
605 PMA_stopImport($message);
607 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
608 // We can not show query in this case, it is in different charset
609 $sql_query_disabled = true;
610 $reset_charset = true;
614 // Something to skip?
615 if (! $error && isset($skip)) {
616 $original_skip = $skip;
618 PMA_importGetNextChunk($skip < $read_limit ?
$skip : $read_limit);
619 // Disable read progressivity, otherwise we eat all memory!
621 $skip -= $read_limit;
626 // This array contain the data like numberof valid sql queries in the statement
627 // and complete valid sql statement (which affected for rows)
628 $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
631 // Check for file existence
632 include_once "libraries/plugin_interface.lib.php";
633 /* @var $import_plugin ImportPlugin */
634 $import_plugin = PMA_getPlugin(
637 'libraries/plugins/import/',
640 if ($import_plugin == null) {
641 $message = PMA_Message
::error(
642 __('Could not load import plugins, please check your installation!')
644 PMA_stopImport($message);
646 // Do the real import
648 $default_fk_check = PMA_Util
::handleDisableFKCheckInit();
649 $import_plugin->doImport();
650 PMA_Util
::handleDisableFKCheckCleanup($default_fk_check);
651 } catch (Exception
$e) {
652 PMA_Util
::handleDisableFKCheckCleanup($default_fk_check);
658 if (! empty($import_handle)) {
659 fclose($import_handle);
662 // Cleanup temporary file
663 if ($file_to_unlink != '') {
664 unlink($file_to_unlink);
667 // Reset charset back, if we did some changes
668 if ($reset_charset) {
669 $GLOBALS['dbi']->query('SET CHARACTER SET utf8');
670 $GLOBALS['dbi']->query(
671 'SET SESSION collation_connection =\'' . $collation_connection . '\''
675 // Show correct message
676 if (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 2) {
677 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
678 $display_query = $import_text;
679 $error = false; // unset error marker, it was used just to skip processing
680 } elseif (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 1) {
681 $message = PMA_Message
::notice(__('Showing bookmark'));
682 } elseif ($bookmark_created) {
683 $special_message = '[br]' . sprintf(
684 __('Bookmark %s has been created.'),
685 htmlspecialchars($bkm_label)
687 } elseif ($finished && ! $error) {
688 if ($import_type == 'query') {
689 $message = PMA_Message
::success();
691 $message = PMA_Message
::success(
693 . __('Import has been successfully finished, %d queries executed.')
696 $message->addParam($executed_queries);
698 if ($import_notice) {
699 $message->addString($import_notice);
701 if (isset($local_import_file)) {
702 $message->addString('(' . htmlspecialchars($local_import_file) . ')');
705 '(' . htmlspecialchars($_FILES['import_file']['name']) . ')'
711 // Did we hit timeout? Tell it user.
712 if ($timeout_passed) {
713 $importUrl = $err_url .= '&timeout_passed=1&offset=' . urlencode(
716 if (isset($local_import_file)) {
717 $importUrl .= '&local_import_file=' . urlencode($local_import_file);
719 $message = PMA_Message
::error(
721 'Script timeout passed, if you want to finish import,'
722 . ' please %sresubmit the same file%s and import will resume.'
725 $message->addParam('<a href="' . $importUrl . '">', false);
726 $message->addParam('</a>', false);
728 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
731 'However on last run no data has been parsed,'
732 . ' this usually means phpMyAdmin won\'t be able to'
733 . ' finish this import unless you increase php time limits.'
739 // if there is any message, copy it into $_SESSION as well,
740 // so we can obtain it by AJAX call
741 if (isset($message)) {
742 $_SESSION['Import_message']['message'] = $message->getDisplay();
744 // Parse and analyze the query, for correct db and table name
745 // in case of a query typed in the query window
746 // (but if the query is too large, in case of an imported file, the parser
747 // can choke on it so avoid parsing)
748 $sqlLength = /*overload*/mb_strlen($sql_query);
749 if ($sqlLength <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
750 include_once 'libraries/parse_analyze.inc.php';
753 // There was an error?
754 if (isset($my_die)) {
755 foreach ($my_die as $key => $die) {
757 $die['error'], $die['sql'], false, $err_url, $error
764 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
765 $_SESSION['is_multi_query'] = true;
766 $sql_queries = $sql_data['valid_sql'];
768 $sql_queries = array($sql_query);
772 foreach ($sql_queries as $sql_query) {
774 include 'libraries/parse_analyze.inc.php';
776 $html_output .= PMA_executeQueryAndGetQueryResponse(
777 $analyzed_sql_results, // analyzed_sql_results
778 false, // is_gotofile
781 null, // find_real_end
782 $sql_query, // sql_query_for_bookmark
784 null, // message_to_show
788 $pmaThemeImage, // pmaThemeImage
790 null, // disp_message
792 $sql_query, // sql_query
793 null, // selectedTables
794 null // complete_query
798 $response = PMA_Response
::getInstance();
799 $response->addJSON('ajax_reload', $ajax_reload);
800 $response->addHTML($html_output);
803 } else if ($result) {
804 // Save a Bookmark with more than one queries (if Bookmark label given).
805 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
806 $cfgBookmark = PMA_Bookmark_getParams();
807 PMA_storeTheQueryAsBookmark(
808 $db, $cfgBookmark['user'],
809 $_REQUEST['sql_query'], $_POST['bkm_label'],
810 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
814 $response = PMA_Response
::getInstance();
815 $response->isSuccess(true);
816 $response->addJSON('message', PMA_Message
::success($msg));
819 PMA_Util
::getMessage($msg, $sql_query, 'success')
821 } else if ($result == false) {
822 $response = PMA_Response
::getInstance();
823 $response->isSuccess(false);
824 $response->addJSON('message', PMA_Message
::error($msg));
826 $active_page = $goto;
830 // If there is request for ROLLBACK in the end.
831 if (isset($_REQUEST['rollback_query'])) {
832 $GLOBALS['dbi']->query('ROLLBACK');