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
83 // TODO: adapt full list of allowed parameters, as in export.php
84 foreach ($post_params as $one_post_param) {
85 if (isset($_POST[$one_post_param])) {
86 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
90 // reset import messages for ajax request
91 $_SESSION['Import_message']['message'] = null;
92 $_SESSION['Import_message']['go_back_url'] = null;
94 $GLOBALS['reload'] = false;
96 // Use to identify current cycle is executing
97 // a multiquery statement or stored routine
98 if (!isset($_SESSION['is_multi_query'])) {
99 $_SESSION['is_multi_query'] = false;
102 $ajax_reload = array();
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 // apply values for parameters
108 if (! empty($_REQUEST['parameterized'])) {
109 $parameters = $_REQUEST['parameters'];
110 foreach ($parameters as $parameter => $replacement) {
111 $quoted = preg_quote($parameter);
112 // making sure that :param does not apply values to :param1
113 $sql_query = preg_replace(
114 '/' . $quoted . '([^a-zA-Z0-9_])/',
115 PMA_Util
::sqlAddSlashes($replacement) . '${1}',
118 // for parameters the appear at the end of the string
119 $sql_query = preg_replace(
120 '/' . $quoted . '$/',
121 PMA_Util
::sqlAddSlashes($replacement),
128 $import_text = $sql_query;
129 $import_type = 'query';
131 $_SESSION['sql_from_query_box'] = true;
133 // If there is a request to ROLLBACK when finished.
134 if (isset($_REQUEST['rollback_query'])) {
135 PMA_handleRollbackRequest($import_text);
138 // refresh navigation and main panels
139 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
140 $GLOBALS['reload'] = true;
141 $ajax_reload['reload'] = true;
144 // refresh navigation panel only
146 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
149 $ajax_reload['reload'] = true;
152 // do a dynamic reload if table is RENAMED
153 // (by sending the instruction to the AJAX response handler)
155 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
159 $ajax_reload['reload'] = true;
160 $ajax_reload['table_name'] = PMA_Util
::unQuote($rename_table_names[2]);
164 } elseif (! empty($sql_file)) {
165 // run uploaded SQL file
166 $import_file = $sql_file;
167 $import_type = 'queryfile';
170 } elseif (! empty($_REQUEST['id_bookmark'])) {
172 $import_type = 'query';
176 // If we didn't get any parameters, either user called this directly, or
177 // upload limit has been reached, let's assume the second possibility.
178 if ($_POST == array() && $_GET == array()) {
179 $message = PMA_Message
::error(
181 'You probably tried to upload a file that is too large. Please refer ' .
182 'to %sdocumentation%s for a workaround for this limit.'
185 $message->addParam('[doc@faq1-16]');
186 $message->addParam('[/doc]');
188 // so we can obtain the message
189 $_SESSION['Import_message']['message'] = $message->getDisplay();
190 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
193 exit; // the footer is displayed automatically
196 // Add console message id to response output
197 if (isset($_POST['console_message_id'])) {
198 $response = PMA_Response
::getInstance();
199 $response->addJSON('console_message_id', $_POST['console_message_id']);
203 * Sets globals from $_POST patterns, for import plugins
204 * We only need to load the selected plugin
220 // this should not happen for a normal user
221 // but only during an attack
222 PMA_fatalError('Incorrect format parameter');
225 $post_patterns = array(
227 '/^' . $format . '_/'
230 PMA_setPostAsGlobal($post_patterns);
232 // Check needed parameters
233 PMA_Util
::checkParameters(array('import_type', 'format'));
235 // We don't want anything special in format
236 $format = PMA_securePath($format);
237 /** @var PMA_String $pmaString */
238 $pmaString = $GLOBALS['PMA_String'];
240 // Create error and goto url
241 if ($import_type == 'table') {
242 $err_url = 'tbl_import.php' . PMA_URL_getCommon(
244 'db' => $db, 'table' => $table
247 $_SESSION['Import_message']['go_back_url'] = $err_url;
248 $goto = 'tbl_import.php';
249 } elseif ($import_type == 'database') {
250 $err_url = 'db_import.php' . PMA_URL_getCommon(array('db' => $db));
251 $_SESSION['Import_message']['go_back_url'] = $err_url;
252 $goto = 'db_import.php';
253 } elseif ($import_type == 'server') {
254 $err_url = 'server_import.php' . PMA_URL_getCommon();
255 $_SESSION['Import_message']['go_back_url'] = $err_url;
256 $goto = 'server_import.php';
258 if (empty($goto) ||
!preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
259 if (/*overload*/mb_strlen($table) && /*overload*/mb_strlen($db)) {
260 $goto = 'tbl_structure.php';
261 } elseif (/*overload*/mb_strlen($db)) {
262 $goto = 'db_structure.php';
264 $goto = 'server_sql.php';
267 if (/*overload*/mb_strlen($table) && /*overload*/mb_strlen($db)) {
268 $common = PMA_URL_getCommon(array('db' => $db, 'table' => $table));
269 } elseif (/*overload*/mb_strlen($db)) {
270 $common = PMA_URL_getCommon(array('db' => $db));
272 $common = PMA_URL_getCommon();
274 $err_url = $goto . $common
275 . (preg_match('@^tbl_[a-z]*\.php$@', $goto)
276 ?
'&table=' . htmlspecialchars($table)
278 $_SESSION['Import_message']['go_back_url'] = $err_url;
280 // Avoid setting selflink to 'import.php'
281 // problem similar to bug 4276
282 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
283 $_SERVER['SCRIPT_NAME'] = $goto;
287 if (/*overload*/mb_strlen($db)) {
288 $GLOBALS['dbi']->selectDb($db);
291 @set_time_limit
($cfg['ExecTimeLimit']);
292 if (! empty($cfg['MemoryLimit'])) {
293 @ini_set
('memory_limit', $cfg['MemoryLimit']);
297 if (isset($_REQUEST['allow_interrupt'])) {
298 $maximum_time = ini_get('max_execution_time');
303 // set default values
304 $timeout_passed = false;
310 $file_to_unlink = '';
312 $sql_query_disabled = false;
314 $executed_queries = 0;
316 $charset_conversion = false;
317 $reset_charset = false;
318 $bookmark_created = false;
320 // Bookmark Support: get a query back from bookmark if required
321 if (! empty($_REQUEST['id_bookmark'])) {
322 $id_bookmark = (int)$_REQUEST['id_bookmark'];
323 include_once 'libraries/bookmark.lib.php';
324 switch ($_REQUEST['action_bookmark']) {
325 case 0: // bookmarked query that have to be run
326 $import_text = PMA_Bookmark_get(
330 isset($_REQUEST['action_bookmark_all'])
332 if (! empty($_REQUEST['bookmark_variable'])) {
333 $import_text = PMA_Bookmark_applyVariables(
338 // refresh navigation and main panels
340 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
343 $GLOBALS['reload'] = true;
344 $ajax_reload['reload'] = true;
347 // refresh navigation panel only
349 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
353 $ajax_reload['reload'] = true;
356 case 1: // bookmarked query that have to be displayed
357 $import_text = PMA_Bookmark_get($db, $id_bookmark);
358 if ($GLOBALS['is_ajax_request'] == true) {
359 $message = PMA_Message
::success(__('Showing bookmark'));
360 $response = PMA_Response
::getInstance();
361 $response->isSuccess($message->isSuccess());
362 $response->addJSON('message', $message);
363 $response->addJSON('sql_query', $import_text);
364 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
370 case 2: // bookmarked query that have to be deleted
371 $import_text = PMA_Bookmark_get($db, $id_bookmark);
372 PMA_Bookmark_delete($id_bookmark);
373 if ($GLOBALS['is_ajax_request'] == true) {
374 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
375 $response = PMA_Response
::getInstance();
376 $response->isSuccess($message->isSuccess());
377 $response->addJSON('message', $message);
378 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
379 $response->addJSON('id_bookmark', $id_bookmark);
383 $error = true; // this is kind of hack to skip processing the query
387 } // end bookmarks reading
389 // Do no run query if we show PHP code
390 if (isset($GLOBALS['show_as_php'])) {
395 // We can not read all at once, otherwise we can run out of memory
396 $memory_limit = trim(@ini_get
('memory_limit'));
398 if (empty($memory_limit)) {
399 $memory_limit = 2 * 1024 * 1024;
401 // In case no memory limit we work on 10MB chunks
402 if ($memory_limit == -1) {
403 $memory_limit = 10 * 1024 * 1024;
406 // Calculate value of the limit
407 $memoryUnit = /*overload*/mb_strtolower(substr($memory_limit, -1));
408 if ('m' == $memoryUnit) {
409 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
410 } elseif ('k' == $memoryUnit) {
411 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
412 } elseif ('g' == $memoryUnit) {
413 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
415 $memory_limit = (int)$memory_limit;
418 // Just to be sure, there might be lot of memory needed for uncompression
419 $read_limit = $memory_limit / 8;
422 if (isset($_FILES['import_file'])) {
423 $import_file = $_FILES['import_file']['tmp_name'];
425 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
427 // sanitize $local_import_file as it comes from a POST
428 $local_import_file = PMA_securePath($local_import_file);
430 $import_file = PMA_Util
::userDir($cfg['UploadDir'])
431 . $local_import_file;
433 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
434 $import_file = 'none';
437 // Do we have file to import?
439 if ($import_file != 'none' && ! $error) {
440 // work around open_basedir and other limitations
441 $open_basedir = @ini_get
('open_basedir');
443 // If we are on a server with open_basedir, we must move the file
444 // before opening it.
446 if (! empty($open_basedir)) {
447 $tmp_subdir = ini_get('upload_tmp_dir');
448 if (empty($tmp_subdir)) {
449 $tmp_subdir = sys_get_temp_dir();
451 $tmp_subdir = rtrim($tmp_subdir, DIRECTORY_SEPARATOR
);
452 if (is_writable($tmp_subdir)) {
453 $import_file_new = $tmp_subdir . DIRECTORY_SEPARATOR
454 . basename($import_file) . uniqid();
455 if (move_uploaded_file($import_file, $import_file_new)) {
456 $import_file = $import_file_new;
457 $file_to_unlink = $import_file_new;
460 $size = filesize($import_file);
463 // If the php.ini is misconfigured (eg. there is no /tmp access defined
464 // with open_basedir), $tmp_subdir won't be writable and the user gets
465 // a 'File could not be read!' error (at PMA_detectCompression), which
466 // is not too meaningful. Show a meaningful error message to the user
469 $message = PMA_Message
::error(
471 'Uploaded file cannot be moved, because the server has ' .
472 'open_basedir enabled without access to the %s directory ' .
473 '(for temporary files).'
476 $message->addParam($tmp_subdir);
477 PMA_stopImport($message);
482 * Handle file compression
483 * @todo duplicate code exists in File.class.php
485 $compression = PMA_detectCompression($import_file);
486 if ($compression === false) {
487 $message = PMA_Message
::error(__('File could not be read!'));
488 PMA_stopImport($message); //Contains an 'exit'
491 switch ($compression) {
492 case 'application/bzip2':
493 if ($cfg['BZipDump'] && @function_exists
('bzopen')) {
494 $import_handle = @bzopen
($import_file, 'r');
496 $message = PMA_Message
::error(
498 'You attempted to load file with unsupported compression ' .
499 '(%s). Either support for it is not implemented or disabled ' .
500 'by your configuration.'
503 $message->addParam($compression);
504 PMA_stopImport($message);
507 case 'application/gzip':
508 if ($cfg['GZipDump'] && @function_exists
('gzopen')) {
509 $import_handle = @gzopen
($import_file, 'r');
511 $message = PMA_Message
::error(
513 'You attempted to load file with unsupported compression ' .
514 '(%s). Either support for it is not implemented or disabled ' .
515 'by your configuration.'
518 $message->addParam($compression);
519 PMA_stopImport($message);
522 case 'application/zip':
523 if ($cfg['ZipDump'] && @function_exists
('zip_open')) {
525 * Load interface for zip extension.
527 include_once 'libraries/zip_extension.lib.php';
528 $zipResult = PMA_getZipContents($import_file);
529 if (! empty($zipResult['error'])) {
530 $message = PMA_Message
::rawError($zipResult['error']);
531 PMA_stopImport($message);
533 $import_text = $zipResult['data'];
536 $message = PMA_Message
::error(
538 'You attempted to load file with unsupported compression ' .
539 '(%s). Either support for it is not implemented or disabled ' .
540 'by your configuration.'
543 $message->addParam($compression);
544 PMA_stopImport($message);
548 $import_handle = @fopen
($import_file, 'r');
551 $message = PMA_Message
::error(
553 'You attempted to load file with unsupported compression (%s). ' .
554 'Either support for it is not implemented or disabled by your ' .
558 $message->addParam($compression);
559 PMA_stopImport($message);
562 // use isset() because zip compression type does not use a handle
563 if (! $error && isset($import_handle) && $import_handle === false) {
564 $message = PMA_Message
::error(__('File could not be read!'));
565 PMA_stopImport($message);
567 } elseif (! $error) {
568 if (! isset($import_text) ||
empty($import_text)) {
569 $message = PMA_Message
::error(
571 'No data was received to import. Either no file name was ' .
572 'submitted, or the file size exceeded the maximum size permitted ' .
573 'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
576 PMA_stopImport($message);
580 // so we can obtain the message
581 //$_SESSION['Import_message'] = $message->getDisplay();
583 // Convert the file's charset if necessary
584 if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE
&& isset($charset_of_file)) {
585 if ($charset_of_file != 'utf-8') {
586 $charset_conversion = true;
588 } elseif (isset($charset_of_file) && $charset_of_file != 'utf-8') {
590 // Drizzle doesn't support other character sets,
591 // so we can't fallback to SET NAMES - throw an error
592 $message = PMA_Message
::error(
594 'Cannot convert file\'s character'
595 . ' set without character set conversion library!'
598 PMA_stopImport($message);
600 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
601 // We can not show query in this case, it is in different charset
602 $sql_query_disabled = true;
603 $reset_charset = true;
607 // Something to skip? (because timeout has passed)
608 if (! $error && isset($_POST['skip'])) {
609 $original_skip = $skip = $_POST['skip'];
611 PMA_importGetNextChunk($skip < $read_limit ?
$skip : $read_limit);
612 // Disable read progressivity, otherwise we eat all memory!
614 $skip -= $read_limit;
619 // This array contain the data like numberof valid sql queries in the statement
620 // and complete valid sql statement (which affected for rows)
621 $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
624 // Check for file existence
625 include_once "libraries/plugin_interface.lib.php";
626 /* @var $import_plugin ImportPlugin */
627 $import_plugin = PMA_getPlugin(
630 'libraries/plugins/import/',
633 if ($import_plugin == null) {
634 $message = PMA_Message
::error(
635 __('Could not load import plugins, please check your installation!')
637 PMA_stopImport($message);
639 // Do the real import
641 $default_fk_check = PMA_Util
::handleDisableFKCheckInit();
642 $import_plugin->doImport();
643 PMA_Util
::handleDisableFKCheckCleanup($default_fk_check);
644 } catch (Exception
$e) {
645 PMA_Util
::handleDisableFKCheckCleanup($default_fk_check);
651 if (! empty($import_handle)) {
652 fclose($import_handle);
655 // Cleanup temporary file
656 if ($file_to_unlink != '') {
657 unlink($file_to_unlink);
660 // Reset charset back, if we did some changes
661 if ($reset_charset) {
662 $GLOBALS['dbi']->query('SET CHARACTER SET utf8');
663 $GLOBALS['dbi']->query(
664 'SET SESSION collation_connection =\'' . $collation_connection . '\''
668 // Show correct message
669 if (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 2) {
670 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
671 $display_query = $import_text;
672 $error = false; // unset error marker, it was used just to skip processing
673 } elseif (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 1) {
674 $message = PMA_Message
::notice(__('Showing bookmark'));
675 } elseif ($bookmark_created) {
676 $special_message = '[br]' . sprintf(
677 __('Bookmark %s has been created.'),
678 htmlspecialchars($bkm_label)
680 } elseif ($finished && ! $error) {
681 if ($import_type == 'query') {
682 $message = PMA_Message
::success();
684 $message = PMA_Message
::success(
686 . __('Import has been successfully finished, %d queries executed.')
689 $message->addParam($executed_queries);
691 if ($import_notice) {
692 $message->addString($import_notice);
694 if (isset($local_import_file)) {
695 $message->addString('(' . htmlspecialchars($local_import_file) . ')');
698 '(' . htmlspecialchars($_FILES['import_file']['name']) . ')'
704 // Did we hit timeout? Tell it user.
705 if ($timeout_passed) {
706 $importUrl = $err_url .= '&timeout_passed=1&offset=' . urlencode(
709 if (isset($local_import_file)) {
710 $importUrl .= '&local_import_file=' . urlencode($local_import_file);
712 $message = PMA_Message
::error(
714 'Script timeout passed, if you want to finish import,'
715 . ' please %sresubmit the same file%s and import will resume.'
718 $message->addParam('<a href="' . $importUrl . '">', false);
719 $message->addParam('</a>', false);
721 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
724 'However on last run no data has been parsed,'
725 . ' this usually means phpMyAdmin won\'t be able to'
726 . ' finish this import unless you increase php time limits.'
732 // if there is any message, copy it into $_SESSION as well,
733 // so we can obtain it by AJAX call
734 if (isset($message)) {
735 $_SESSION['Import_message']['message'] = $message->getDisplay();
737 // Parse and analyze the query, for correct db and table name
738 // in case of a query typed in the query window
739 // (but if the query is too large, in case of an imported file, the parser
740 // can choke on it so avoid parsing)
741 $sqlLength = /*overload*/mb_strlen($sql_query);
742 if ($sqlLength <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
743 include_once 'libraries/parse_analyze.inc.php';
746 // There was an error?
747 if (isset($my_die)) {
748 foreach ($my_die as $key => $die) {
750 $die['error'], $die['sql'], false, $err_url, $error
757 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
758 $_SESSION['is_multi_query'] = true;
759 $sql_queries = $sql_data['valid_sql'];
761 $sql_queries = array($sql_query);
765 foreach ($sql_queries as $sql_query) {
767 include 'libraries/parse_analyze.inc.php';
769 $html_output .= PMA_executeQueryAndGetQueryResponse(
770 $analyzed_sql_results, // analyzed_sql_results
771 false, // is_gotofile
774 null, // find_real_end
775 $sql_query, // sql_query_for_bookmark
777 null, // message_to_show
781 $pmaThemeImage, // pmaThemeImage
783 null, // disp_message
785 $sql_query, // sql_query
786 null, // selectedTables
787 null // complete_query
791 $response = PMA_Response
::getInstance();
792 $response->addJSON('ajax_reload', $ajax_reload);
793 $response->addHTML($html_output);
796 } else if ($result) {
797 // Save a Bookmark with more than one queries (if Bookmark label given).
798 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
799 $cfgBookmark = PMA_Bookmark_getParams();
800 PMA_storeTheQueryAsBookmark(
801 $db, $cfgBookmark['user'],
802 $_REQUEST['sql_query'], $_POST['bkm_label'],
803 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
807 $response = PMA_Response
::getInstance();
808 $response->isSuccess(true);
809 $response->addJSON('message', PMA_Message
::success($msg));
812 PMA_Util
::getMessage($msg, $sql_query, 'success')
814 } else if ($result == false) {
815 $response = PMA_Response
::getInstance();
816 $response->isSuccess(false);
817 $response->addJSON('message', PMA_Message
::error($msg));
819 $active_page = $goto;
823 // If there is request for ROLLBACK in the end.
824 if (isset($_REQUEST['rollback_query'])) {
825 $GLOBALS['dbi']->query('ROLLBACK');