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 // Are we just executing plain query or sql file?
104 // (eg. non import, but query box/window run)
105 if (! empty($sql_query)) {
107 $import_text = $sql_query;
108 $import_type = 'query';
110 $_SESSION['sql_from_query_box'] = true;
112 // If there is a request to ROLLBACK when finished.
113 if (isset($_REQUEST['rollback_query'])) {
114 PMA_handleRollbackRequest($import_text);
117 // refresh navigation and main panels
118 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
119 $GLOBALS['reload'] = true;
122 // refresh navigation panel only
124 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
127 $ajax_reload = array('reload' => true);
130 // do a dynamic reload if table is RENAMED
131 // (by sending the instruction to the AJAX response handler)
133 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
137 $ajax_reload = array('reload' => true);
138 $ajax_reload['table_name'] = PMA_Util
::unQuote($rename_table_names[2]);
142 } elseif (! empty($sql_localfile)) {
143 // run SQL file on server
144 $local_import_file = $sql_localfile;
145 $import_type = 'queryfile';
147 unset($sql_localfile);
148 } elseif (! empty($sql_file)) {
149 // run uploaded SQL file
150 $import_file = $sql_file;
151 $import_type = 'queryfile';
154 } elseif (! empty($_REQUEST['id_bookmark'])) {
156 $import_type = 'query';
160 // If we didn't get any parameters, either user called this directly, or
161 // upload limit has been reached, let's assume the second possibility.
162 if ($_POST == array() && $_GET == array()) {
163 $message = PMA_Message
::error(
164 __('You probably tried to upload a file that is too large. Please refer to %sdocumentation%s for a workaround for this limit.')
166 $message->addParam('[doc@faq1-16]');
167 $message->addParam('[/doc]');
169 // so we can obtain the message
170 $_SESSION['Import_message']['message'] = $message->getDisplay();
171 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
174 exit; // the footer is displayed automatically
177 // Add console message id to response output
178 if (isset($_POST['console_message_id'])) {
179 $response = PMA_Response
::getInstance();
180 $response->addJSON('console_message_id', $_POST['console_message_id']);
184 * Sets globals from $_POST patterns, for import plugins
185 * We only need to load the selected plugin
201 // this should not happen for a normal user
202 // but only during an attack
203 PMA_fatalError('Incorrect format parameter');
206 $post_patterns = array(
208 '/^' . $format . '_/'
211 PMA_setPostAsGlobal($post_patterns);
213 // Check needed parameters
214 PMA_Util
::checkParameters(array('import_type', 'format'));
216 // We don't want anything special in format
217 $format = PMA_securePath($format);
218 /** @var PMA_String $pmaString */
219 $pmaString = $GLOBALS['PMA_String'];
221 // Create error and goto url
222 if ($import_type == 'table') {
223 $err_url = 'tbl_import.php' . PMA_URL_getCommon(
225 'db' => $db, 'table' => $table
228 $_SESSION['Import_message']['go_back_url'] = $err_url;
229 $goto = 'tbl_import.php';
230 } elseif ($import_type == 'database') {
231 $err_url = 'db_import.php' . PMA_URL_getCommon(array('db' => $db));
232 $_SESSION['Import_message']['go_back_url'] = $err_url;
233 $goto = 'db_import.php';
234 } elseif ($import_type == 'server') {
235 $err_url = 'server_import.php' . PMA_URL_getCommon();
236 $_SESSION['Import_message']['go_back_url'] = $err_url;
237 $goto = 'server_import.php';
239 if (empty($goto) ||
!preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
240 if (/*overload*/mb_strlen($table) && /*overload*/mb_strlen($db)) {
241 $goto = 'tbl_structure.php';
242 } elseif (/*overload*/mb_strlen($db)) {
243 $goto = 'db_structure.php';
245 $goto = 'server_sql.php';
248 if (/*overload*/mb_strlen($table) && /*overload*/mb_strlen($db)) {
249 $common = PMA_URL_getCommon(array('db' => $db, 'table' => $table));
250 } elseif (/*overload*/mb_strlen($db)) {
251 $common = PMA_URL_getCommon(array('db' => $db));
253 $common = PMA_URL_getCommon();
255 $err_url = $goto . $common
256 . (preg_match('@^tbl_[a-z]*\.php$@', $goto)
257 ?
'&table=' . htmlspecialchars($table)
259 $_SESSION['Import_message']['go_back_url'] = $err_url;
261 // Avoid setting selflink to 'import.php'
262 // problem similar to bug 4276
263 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
264 $_SERVER['SCRIPT_NAME'] = $goto;
268 if (/*overload*/mb_strlen($db)) {
269 $GLOBALS['dbi']->selectDb($db);
272 @set_time_limit
($cfg['ExecTimeLimit']);
273 if (! empty($cfg['MemoryLimit'])) {
274 @ini_set
('memory_limit', $cfg['MemoryLimit']);
278 if (isset($_REQUEST['allow_interrupt'])) {
279 $maximum_time = ini_get('max_execution_time');
284 // set default values
285 $timeout_passed = false;
291 $file_to_unlink = '';
293 $sql_query_disabled = false;
295 $executed_queries = 0;
297 $charset_conversion = false;
298 $reset_charset = false;
299 $bookmark_created = false;
301 // Bookmark Support: get a query back from bookmark if required
302 if (! empty($_REQUEST['id_bookmark'])) {
303 $id_bookmark = (int)$_REQUEST['id_bookmark'];
304 include_once 'libraries/bookmark.lib.php';
305 switch ($_REQUEST['action_bookmark']) {
306 case 0: // bookmarked query that have to be run
307 $import_text = PMA_Bookmark_get(
311 isset($_REQUEST['action_bookmark_all'])
313 if (! empty($_REQUEST['bookmark_variable'])) {
314 $import_text = preg_replace(
315 '|/\*(.*)\[VARIABLE\](.*)\*/|imsU',
316 '${1}' . PMA_Util
::sqlAddSlashes($_REQUEST['bookmark_variable']) . '${2}',
321 // refresh navigation and main panels
323 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
326 $GLOBALS['reload'] = true;
329 // refresh navigation panel only
331 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
335 if (! isset($ajax_reload)) {
336 $ajax_reload = array();
338 $ajax_reload['reload'] = true;
341 case 1: // bookmarked query that have to be displayed
342 $import_text = PMA_Bookmark_get($db, $id_bookmark);
343 if ($GLOBALS['is_ajax_request'] == true) {
344 $message = PMA_Message
::success(__('Showing bookmark'));
345 $response = PMA_Response
::getInstance();
346 $response->isSuccess($message->isSuccess());
347 $response->addJSON('message', $message);
348 $response->addJSON('sql_query', $import_text);
349 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
355 case 2: // bookmarked query that have to be deleted
356 $import_text = PMA_Bookmark_get($db, $id_bookmark);
357 PMA_Bookmark_delete($id_bookmark);
358 if ($GLOBALS['is_ajax_request'] == true) {
359 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
360 $response = PMA_Response
::getInstance();
361 $response->isSuccess($message->isSuccess());
362 $response->addJSON('message', $message);
363 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
364 $response->addJSON('id_bookmark', $id_bookmark);
368 $error = true; // this is kind of hack to skip processing the query
372 } // end bookmarks reading
374 // Do no run query if we show PHP code
375 if (isset($GLOBALS['show_as_php'])) {
380 // We can not read all at once, otherwise we can run out of memory
381 $memory_limit = trim(@ini_get
('memory_limit'));
383 if (empty($memory_limit)) {
384 $memory_limit = 2 * 1024 * 1024;
386 // In case no memory limit we work on 10MB chunks
387 if ($memory_limit == -1) {
388 $memory_limit = 10 * 1024 * 1024;
391 // Calculate value of the limit
392 $memoryUnit = /*overload*/mb_strtolower(substr($memory_limit, -1));
393 if ('m' == $memoryUnit) {
394 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
395 } elseif ('k' == $memoryUnit) {
396 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
397 } elseif ('g' == $memoryUnit) {
398 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
400 $memory_limit = (int)$memory_limit;
403 // Just to be sure, there might be lot of memory needed for uncompression
404 $read_limit = $memory_limit / 8;
407 if (isset($_FILES['import_file'])) {
408 $import_file = $_FILES['import_file']['tmp_name'];
410 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
412 // sanitize $local_import_file as it comes from a POST
413 $local_import_file = PMA_securePath($local_import_file);
415 $import_file = PMA_Util
::userDir($cfg['UploadDir'])
416 . $local_import_file;
418 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
419 $import_file = 'none';
422 // Do we have file to import?
424 if ($import_file != 'none' && ! $error) {
425 // work around open_basedir and other limitations
426 $open_basedir = @ini_get
('open_basedir');
428 // If we are on a server with open_basedir, we must move the file
429 // before opening it.
431 if (! empty($open_basedir)) {
432 $tmp_subdir = ini_get('upload_tmp_dir');
433 if (empty($tmp_subdir)) {
434 $tmp_subdir = sys_get_temp_dir();
436 $tmp_subdir = rtrim($tmp_subdir, DIRECTORY_SEPARATOR
);
437 if (is_writable($tmp_subdir)) {
438 $import_file_new = $tmp_subdir . DIRECTORY_SEPARATOR
439 . basename($import_file) . uniqid();
440 if (move_uploaded_file($import_file, $import_file_new)) {
441 $import_file = $import_file_new;
442 $file_to_unlink = $import_file_new;
445 $size = filesize($import_file);
448 // If the php.ini is misconfigured (eg. there is no /tmp access defined
449 // with open_basedir), $tmp_subdir won't be writable and the user gets
450 // a 'File could not be read!' error (at PMA_detectCompression), which
451 // is not too meaningful. Show a meaningful error message to the user
454 $message = PMA_Message
::error(
455 __('Uploaded file cannot be moved, because the server has open_basedir enabled without access to the %s directory (for temporary files).')
457 $message->addParam($tmp_subdir);
458 PMA_stopImport($message);
463 * Handle file compression
464 * @todo duplicate code exists in File.class.php
466 $compression = PMA_detectCompression($import_file);
467 if ($compression === false) {
468 $message = PMA_Message
::error(__('File could not be read!'));
469 PMA_stopImport($message); //Contains an 'exit'
472 switch ($compression) {
473 case 'application/bzip2':
474 if ($cfg['BZipDump'] && @function_exists
('bzopen')) {
475 $import_handle = @bzopen
($import_file, 'r');
477 $message = PMA_Message
::error(
478 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
480 $message->addParam($compression);
481 PMA_stopImport($message);
484 case 'application/gzip':
485 if ($cfg['GZipDump'] && @function_exists
('gzopen')) {
486 $import_handle = @gzopen
($import_file, 'r');
488 $message = PMA_Message
::error(
489 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
491 $message->addParam($compression);
492 PMA_stopImport($message);
495 case 'application/zip':
496 if ($cfg['ZipDump'] && @function_exists
('zip_open')) {
498 * Load interface for zip extension.
500 include_once 'libraries/zip_extension.lib.php';
501 $zipResult = PMA_getZipContents($import_file);
502 if (! empty($zipResult['error'])) {
503 $message = PMA_Message
::rawError($zipResult['error']);
504 PMA_stopImport($message);
506 $import_text = $zipResult['data'];
509 $message = PMA_Message
::error(
510 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
512 $message->addParam($compression);
513 PMA_stopImport($message);
517 $import_handle = @fopen
($import_file, 'r');
520 $message = PMA_Message
::error(
521 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
523 $message->addParam($compression);
524 PMA_stopImport($message);
527 // use isset() because zip compression type does not use a handle
528 if (! $error && isset($import_handle) && $import_handle === false) {
529 $message = PMA_Message
::error(__('File could not be read!'));
530 PMA_stopImport($message);
532 } elseif (! $error) {
533 if (! isset($import_text) ||
empty($import_text)) {
534 $message = PMA_Message
::error(
535 __('No data was received to import. Either no file name was submitted, or the file size exceeded the maximum size permitted by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].')
537 PMA_stopImport($message);
541 // so we can obtain the message
542 //$_SESSION['Import_message'] = $message->getDisplay();
544 // Convert the file's charset if necessary
545 if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE
&& isset($charset_of_file)) {
546 if ($charset_of_file != 'utf-8') {
547 $charset_conversion = true;
549 } elseif (isset($charset_of_file) && $charset_of_file != 'utf-8') {
551 // Drizzle doesn't support other character sets,
552 // so we can't fallback to SET NAMES - throw an error
553 $message = PMA_Message
::error(
555 'Cannot convert file\'s character'
556 . ' set without character set conversion library!'
559 PMA_stopImport($message);
561 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
562 // We can not show query in this case, it is in different charset
563 $sql_query_disabled = true;
564 $reset_charset = true;
568 // Something to skip?
569 if (! $error && isset($skip)) {
570 $original_skip = $skip;
572 PMA_importGetNextChunk($skip < $read_limit ?
$skip : $read_limit);
573 // Disable read progressivity, otherwise we eat all memory!
575 $skip -= $read_limit;
580 // This array contain the data like numberof valid sql queries in the statement
581 // and complete valid sql statement (which affected for rows)
582 $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
585 // Check for file existence
586 include_once "libraries/plugin_interface.lib.php";
587 $import_plugin = PMA_getPlugin(
590 'libraries/plugins/import/',
593 if ($import_plugin == null) {
594 $message = PMA_Message
::error(
595 __('Could not load import plugins, please check your installation!')
597 PMA_stopImport($message);
599 // Do the real import
600 $import_plugin->doImport($sql_data);
604 if (! empty($import_handle)) {
605 fclose($import_handle);
608 // Cleanup temporary file
609 if ($file_to_unlink != '') {
610 unlink($file_to_unlink);
613 // Reset charset back, if we did some changes
614 if ($reset_charset) {
615 $GLOBALS['dbi']->query('SET CHARACTER SET utf8');
616 $GLOBALS['dbi']->query(
617 'SET SESSION collation_connection =\'' . $collation_connection . '\''
621 // Show correct message
622 if (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 2) {
623 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
624 $display_query = $import_text;
625 $error = false; // unset error marker, it was used just to skip processing
626 } elseif (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 1) {
627 $message = PMA_Message
::notice(__('Showing bookmark'));
628 } elseif ($bookmark_created) {
629 $special_message = '[br]' . sprintf(
630 __('Bookmark %s has been created.'),
631 htmlspecialchars($bkm_label)
633 } elseif ($finished && ! $error) {
634 if ($import_type == 'query') {
635 $message = PMA_Message
::success();
637 $message = PMA_Message
::success(
639 . __('Import has been successfully finished, %d queries executed.')
642 $message->addParam($executed_queries);
644 if ($import_notice) {
645 $message->addString($import_notice);
647 if (isset($local_import_file)) {
648 $message->addString('(' . htmlspecialchars($local_import_file) . ')');
651 '(' . htmlspecialchars($_FILES['import_file']['name']) . ')'
657 // Did we hit timeout? Tell it user.
658 if ($timeout_passed) {
659 $importUrl = $err_url .= '&timeout_passed=1&offset=' . urlencode($GLOBALS['offset']);
660 if (isset($local_import_file)) {
661 $importUrl .= '&local_import_file=' . urlencode($local_import_file);
663 $message = PMA_Message
::error(
665 'Script timeout passed, if you want to finish import,'
666 . ' please %sresubmit the same file%s and import will resume.'
669 $message->addParam('<a href="' . $importUrl . '">', false);
670 $message->addParam('</a>', false);
672 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
675 'However on last run no data has been parsed,'
676 . ' this usually means phpMyAdmin won\'t be able to'
677 . ' finish this import unless you increase php time limits.'
683 // if there is any message, copy it into $_SESSION as well,
684 // so we can obtain it by AJAX call
685 if (isset($message)) {
686 $_SESSION['Import_message']['message'] = $message->getDisplay();
688 // Parse and analyze the query, for correct db and table name
689 // in case of a query typed in the query window
690 // (but if the query is too large, in case of an imported file, the parser
691 // can choke on it so avoid parsing)
692 $sqlLength = /*overload*/mb_strlen($sql_query);
693 if ($sqlLength <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
694 include_once 'libraries/parse_analyze.inc.php';
697 // There was an error?
698 if (isset($my_die)) {
699 foreach ($my_die as $key => $die) {
701 $die['error'], $die['sql'], false, $err_url, $error
708 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
709 $_SESSION['is_multi_query'] = true;
710 $sql_queries = $sql_data['valid_sql'];
712 $sql_queries = array($sql_query);
716 foreach ($sql_queries as $sql_query) {
718 include 'libraries/parse_analyze.inc.php';
720 $html_output .= PMA_executeQueryAndGetQueryResponse(
721 $analyzed_sql_results, false, $db, $table, null,
722 $sql_query, null, $analyzed_sql_results['is_affected'],
723 null, null, null, $goto, $pmaThemeImage,
724 null, null, null, $sql_query, null, null
728 if (!isset($ajax_reload)) {
729 $ajax_reload = array();
732 $ajax_reload['table_name'] = $table;
734 $response = PMA_Response
::getInstance();
735 $response->addJSON('ajax_reload', $ajax_reload);
736 $response->addHTML($html_output);
739 } else if ($result) {
740 // Save a Bookmark with more than one queries (if Bookmark label given).
741 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
742 $cfgBookmark = PMA_Bookmark_getParams();
743 PMA_storeTheQueryAsBookmark(
744 $db, $cfgBookmark['user'],
745 $_REQUEST['sql_query'], $_POST['bkm_label'],
746 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
750 $response = PMA_Response
::getInstance();
751 $response->isSuccess(true);
752 $response->addJSON('message', PMA_Message
::success($msg));
755 PMA_Util
::getMessage($msg, $sql_query, 'success')
757 } else if ($result == false) {
758 $response = PMA_Response
::getInstance();
759 $response->isSuccess(false);
760 $response->addJSON('message', PMA_Message
::error($msg));
762 $active_page = $goto;
766 // If there is request for ROLLBACK in the end.
767 if (isset($_REQUEST['rollback_query'])) {
768 $GLOBALS['dbi']->query('ROLLBACK');