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(
187 __('You probably tried to upload a file that is too large. Please refer to %sdocumentation%s for a workaround for this limit.')
189 $message->addParam('[doc@faq1-16]');
190 $message->addParam('[/doc]');
192 // so we can obtain the message
193 $_SESSION['Import_message']['message'] = $message->getDisplay();
194 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
197 exit; // the footer is displayed automatically
200 // Add console message id to response output
201 if (isset($_POST['console_message_id'])) {
202 $response = PMA_Response
::getInstance();
203 $response->addJSON('console_message_id', $_POST['console_message_id']);
207 * Sets globals from $_POST patterns, for import plugins
208 * We only need to load the selected plugin
224 // this should not happen for a normal user
225 // but only during an attack
226 PMA_fatalError('Incorrect format parameter');
229 $post_patterns = array(
231 '/^' . $format . '_/'
234 PMA_setPostAsGlobal($post_patterns);
236 // Check needed parameters
237 PMA_Util
::checkParameters(array('import_type', 'format'));
239 // We don't want anything special in format
240 $format = PMA_securePath($format);
241 /** @var PMA_String $pmaString */
242 $pmaString = $GLOBALS['PMA_String'];
244 // Create error and goto url
245 if ($import_type == 'table') {
246 $err_url = 'tbl_import.php' . PMA_URL_getCommon(
248 'db' => $db, 'table' => $table
251 $_SESSION['Import_message']['go_back_url'] = $err_url;
252 $goto = 'tbl_import.php';
253 } elseif ($import_type == 'database') {
254 $err_url = 'db_import.php' . PMA_URL_getCommon(array('db' => $db));
255 $_SESSION['Import_message']['go_back_url'] = $err_url;
256 $goto = 'db_import.php';
257 } elseif ($import_type == 'server') {
258 $err_url = 'server_import.php' . PMA_URL_getCommon();
259 $_SESSION['Import_message']['go_back_url'] = $err_url;
260 $goto = 'server_import.php';
262 if (empty($goto) ||
!preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
263 if (/*overload*/mb_strlen($table) && /*overload*/mb_strlen($db)) {
264 $goto = 'tbl_structure.php';
265 } elseif (/*overload*/mb_strlen($db)) {
266 $goto = 'db_structure.php';
268 $goto = 'server_sql.php';
271 if (/*overload*/mb_strlen($table) && /*overload*/mb_strlen($db)) {
272 $common = PMA_URL_getCommon(array('db' => $db, 'table' => $table));
273 } elseif (/*overload*/mb_strlen($db)) {
274 $common = PMA_URL_getCommon(array('db' => $db));
276 $common = PMA_URL_getCommon();
278 $err_url = $goto . $common
279 . (preg_match('@^tbl_[a-z]*\.php$@', $goto)
280 ?
'&table=' . htmlspecialchars($table)
282 $_SESSION['Import_message']['go_back_url'] = $err_url;
284 // Avoid setting selflink to 'import.php'
285 // problem similar to bug 4276
286 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
287 $_SERVER['SCRIPT_NAME'] = $goto;
291 if (/*overload*/mb_strlen($db)) {
292 $GLOBALS['dbi']->selectDb($db);
295 @set_time_limit
($cfg['ExecTimeLimit']);
296 if (! empty($cfg['MemoryLimit'])) {
297 @ini_set
('memory_limit', $cfg['MemoryLimit']);
301 if (isset($_REQUEST['allow_interrupt'])) {
302 $maximum_time = ini_get('max_execution_time');
307 // set default values
308 $timeout_passed = false;
314 $file_to_unlink = '';
316 $sql_query_disabled = false;
318 $executed_queries = 0;
320 $charset_conversion = false;
321 $reset_charset = false;
322 $bookmark_created = false;
324 // Bookmark Support: get a query back from bookmark if required
325 if (! empty($_REQUEST['id_bookmark'])) {
326 $id_bookmark = (int)$_REQUEST['id_bookmark'];
327 include_once 'libraries/bookmark.lib.php';
328 switch ($_REQUEST['action_bookmark']) {
329 case 0: // bookmarked query that have to be run
330 $import_text = PMA_Bookmark_get(
334 isset($_REQUEST['action_bookmark_all'])
336 if (! empty($_REQUEST['bookmark_variable'])) {
337 $import_text = PMA_Bookmark_applyVariables(
342 // refresh navigation and main panels
344 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
347 $GLOBALS['reload'] = true;
348 $ajax_reload['reload'] = true;
351 // refresh navigation panel only
353 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
357 $ajax_reload['reload'] = true;
360 case 1: // bookmarked query that have to be displayed
361 $import_text = PMA_Bookmark_get($db, $id_bookmark);
362 if ($GLOBALS['is_ajax_request'] == true) {
363 $message = PMA_Message
::success(__('Showing bookmark'));
364 $response = PMA_Response
::getInstance();
365 $response->isSuccess($message->isSuccess());
366 $response->addJSON('message', $message);
367 $response->addJSON('sql_query', $import_text);
368 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
374 case 2: // bookmarked query that have to be deleted
375 $import_text = PMA_Bookmark_get($db, $id_bookmark);
376 PMA_Bookmark_delete($id_bookmark);
377 if ($GLOBALS['is_ajax_request'] == true) {
378 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
379 $response = PMA_Response
::getInstance();
380 $response->isSuccess($message->isSuccess());
381 $response->addJSON('message', $message);
382 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
383 $response->addJSON('id_bookmark', $id_bookmark);
387 $error = true; // this is kind of hack to skip processing the query
391 } // end bookmarks reading
393 // Do no run query if we show PHP code
394 if (isset($GLOBALS['show_as_php'])) {
399 // We can not read all at once, otherwise we can run out of memory
400 $memory_limit = trim(@ini_get
('memory_limit'));
402 if (empty($memory_limit)) {
403 $memory_limit = 2 * 1024 * 1024;
405 // In case no memory limit we work on 10MB chunks
406 if ($memory_limit == -1) {
407 $memory_limit = 10 * 1024 * 1024;
410 // Calculate value of the limit
411 $memoryUnit = /*overload*/mb_strtolower(substr($memory_limit, -1));
412 if ('m' == $memoryUnit) {
413 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
414 } elseif ('k' == $memoryUnit) {
415 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
416 } elseif ('g' == $memoryUnit) {
417 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
419 $memory_limit = (int)$memory_limit;
422 // Just to be sure, there might be lot of memory needed for uncompression
423 $read_limit = $memory_limit / 8;
426 if (isset($_FILES['import_file'])) {
427 $import_file = $_FILES['import_file']['tmp_name'];
429 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
431 // sanitize $local_import_file as it comes from a POST
432 $local_import_file = PMA_securePath($local_import_file);
434 $import_file = PMA_Util
::userDir($cfg['UploadDir'])
435 . $local_import_file;
437 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
438 $import_file = 'none';
441 // Do we have file to import?
443 if ($import_file != 'none' && ! $error) {
444 // work around open_basedir and other limitations
445 $open_basedir = @ini_get
('open_basedir');
447 // If we are on a server with open_basedir, we must move the file
448 // before opening it.
450 if (! empty($open_basedir)) {
451 $tmp_subdir = ini_get('upload_tmp_dir');
452 if (empty($tmp_subdir)) {
453 $tmp_subdir = sys_get_temp_dir();
455 $tmp_subdir = rtrim($tmp_subdir, DIRECTORY_SEPARATOR
);
456 if (is_writable($tmp_subdir)) {
457 $import_file_new = $tmp_subdir . DIRECTORY_SEPARATOR
458 . basename($import_file) . uniqid();
459 if (move_uploaded_file($import_file, $import_file_new)) {
460 $import_file = $import_file_new;
461 $file_to_unlink = $import_file_new;
464 $size = filesize($import_file);
467 // If the php.ini is misconfigured (eg. there is no /tmp access defined
468 // with open_basedir), $tmp_subdir won't be writable and the user gets
469 // a 'File could not be read!' error (at PMA_detectCompression), which
470 // is not too meaningful. Show a meaningful error message to the user
473 $message = PMA_Message
::error(
474 __('Uploaded file cannot be moved, because the server has open_basedir enabled without access to the %s directory (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(
497 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
499 $message->addParam($compression);
500 PMA_stopImport($message);
503 case 'application/gzip':
504 if ($cfg['GZipDump'] && @function_exists
('gzopen')) {
505 $import_handle = @gzopen
($import_file, 'r');
507 $message = PMA_Message
::error(
508 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
510 $message->addParam($compression);
511 PMA_stopImport($message);
514 case 'application/zip':
515 if ($cfg['ZipDump'] && @function_exists
('zip_open')) {
517 * Load interface for zip extension.
519 include_once 'libraries/zip_extension.lib.php';
520 $zipResult = PMA_getZipContents($import_file);
521 if (! empty($zipResult['error'])) {
522 $message = PMA_Message
::rawError($zipResult['error']);
523 PMA_stopImport($message);
525 $import_text = $zipResult['data'];
528 $message = PMA_Message
::error(
529 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
531 $message->addParam($compression);
532 PMA_stopImport($message);
536 $import_handle = @fopen
($import_file, 'r');
539 $message = PMA_Message
::error(
540 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
542 $message->addParam($compression);
543 PMA_stopImport($message);
546 // use isset() because zip compression type does not use a handle
547 if (! $error && isset($import_handle) && $import_handle === false) {
548 $message = PMA_Message
::error(__('File could not be read!'));
549 PMA_stopImport($message);
551 } elseif (! $error) {
552 if (! isset($import_text) ||
empty($import_text)) {
553 $message = PMA_Message
::error(
554 __('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].')
556 PMA_stopImport($message);
560 // so we can obtain the message
561 //$_SESSION['Import_message'] = $message->getDisplay();
563 // Convert the file's charset if necessary
564 if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE
&& isset($charset_of_file)) {
565 if ($charset_of_file != 'utf-8') {
566 $charset_conversion = true;
568 } elseif (isset($charset_of_file) && $charset_of_file != 'utf-8') {
570 // Drizzle doesn't support other character sets,
571 // so we can't fallback to SET NAMES - throw an error
572 $message = PMA_Message
::error(
574 'Cannot convert file\'s character'
575 . ' set without character set conversion library!'
578 PMA_stopImport($message);
580 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
581 // We can not show query in this case, it is in different charset
582 $sql_query_disabled = true;
583 $reset_charset = true;
587 // Something to skip?
588 if (! $error && isset($skip)) {
589 $original_skip = $skip;
591 PMA_importGetNextChunk($skip < $read_limit ?
$skip : $read_limit);
592 // Disable read progressivity, otherwise we eat all memory!
594 $skip -= $read_limit;
599 // This array contain the data like numberof valid sql queries in the statement
600 // and complete valid sql statement (which affected for rows)
601 $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
604 // Check for file existence
605 include_once "libraries/plugin_interface.lib.php";
606 /* @var $import_plugin ImportPlugin */
607 $import_plugin = PMA_getPlugin(
610 'libraries/plugins/import/',
613 if ($import_plugin == null) {
614 $message = PMA_Message
::error(
615 __('Could not load import plugins, please check your installation!')
617 PMA_stopImport($message);
619 // Do the real import
621 $default_fk_check = PMA_Util
::handleDisableFKCheckInit();
622 $import_plugin->doImport($sql_data);
623 PMA_Util
::handleDisableFKCheckCleanup($default_fk_check);
624 } catch (Exception
$e) {
625 PMA_Util
::handleDisableFKCheckCleanup($default_fk_check);
631 if (! empty($import_handle)) {
632 fclose($import_handle);
635 // Cleanup temporary file
636 if ($file_to_unlink != '') {
637 unlink($file_to_unlink);
640 // Reset charset back, if we did some changes
641 if ($reset_charset) {
642 $GLOBALS['dbi']->query('SET CHARACTER SET utf8');
643 $GLOBALS['dbi']->query(
644 'SET SESSION collation_connection =\'' . $collation_connection . '\''
648 // Show correct message
649 if (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 2) {
650 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
651 $display_query = $import_text;
652 $error = false; // unset error marker, it was used just to skip processing
653 } elseif (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 1) {
654 $message = PMA_Message
::notice(__('Showing bookmark'));
655 } elseif ($bookmark_created) {
656 $special_message = '[br]' . sprintf(
657 __('Bookmark %s has been created.'),
658 htmlspecialchars($bkm_label)
660 } elseif ($finished && ! $error) {
661 if ($import_type == 'query') {
662 $message = PMA_Message
::success();
664 $message = PMA_Message
::success(
666 . __('Import has been successfully finished, %d queries executed.')
669 $message->addParam($executed_queries);
671 if ($import_notice) {
672 $message->addString($import_notice);
674 if (isset($local_import_file)) {
675 $message->addString('(' . htmlspecialchars($local_import_file) . ')');
678 '(' . htmlspecialchars($_FILES['import_file']['name']) . ')'
684 // Did we hit timeout? Tell it user.
685 if ($timeout_passed) {
686 $importUrl = $err_url .= '&timeout_passed=1&offset=' . urlencode($GLOBALS['offset']);
687 if (isset($local_import_file)) {
688 $importUrl .= '&local_import_file=' . urlencode($local_import_file);
690 $message = PMA_Message
::error(
692 'Script timeout passed, if you want to finish import,'
693 . ' please %sresubmit the same file%s and import will resume.'
696 $message->addParam('<a href="' . $importUrl . '">', false);
697 $message->addParam('</a>', false);
699 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
702 'However on last run no data has been parsed,'
703 . ' this usually means phpMyAdmin won\'t be able to'
704 . ' finish this import unless you increase php time limits.'
710 // if there is any message, copy it into $_SESSION as well,
711 // so we can obtain it by AJAX call
712 if (isset($message)) {
713 $_SESSION['Import_message']['message'] = $message->getDisplay();
715 // Parse and analyze the query, for correct db and table name
716 // in case of a query typed in the query window
717 // (but if the query is too large, in case of an imported file, the parser
718 // can choke on it so avoid parsing)
719 $sqlLength = /*overload*/mb_strlen($sql_query);
720 if ($sqlLength <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
721 include_once 'libraries/parse_analyze.inc.php';
724 // There was an error?
725 if (isset($my_die)) {
726 foreach ($my_die as $key => $die) {
728 $die['error'], $die['sql'], false, $err_url, $error
735 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
736 $_SESSION['is_multi_query'] = true;
737 $sql_queries = $sql_data['valid_sql'];
739 $sql_queries = array($sql_query);
743 foreach ($sql_queries as $sql_query) {
745 include 'libraries/parse_analyze.inc.php';
747 $html_output .= PMA_executeQueryAndGetQueryResponse(
748 $analyzed_sql_results, false, $db, $table, null,
749 $sql_query, null, $analyzed_sql_results['is_affected'],
750 null, null, null, $goto, $pmaThemeImage,
751 null, null, null, $sql_query, null, null
755 $response = PMA_Response
::getInstance();
756 $response->addJSON('ajax_reload', $ajax_reload);
757 $response->addHTML($html_output);
760 } else if ($result) {
761 // Save a Bookmark with more than one queries (if Bookmark label given).
762 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
763 $cfgBookmark = PMA_Bookmark_getParams();
764 PMA_storeTheQueryAsBookmark(
765 $db, $cfgBookmark['user'],
766 $_REQUEST['sql_query'], $_POST['bkm_label'],
767 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
771 $response = PMA_Response
::getInstance();
772 $response->isSuccess(true);
773 $response->addJSON('message', PMA_Message
::success($msg));
776 PMA_Util
::getMessage($msg, $sql_query, 'success')
778 } else if ($result == false) {
779 $response = PMA_Response
::getInstance();
780 $response->isSuccess(false);
781 $response->addJSON('message', PMA_Message
::error($msg));
783 $active_page = $goto;
787 // If there is request for ROLLBACK in the end.
788 if (isset($_REQUEST['rollback_query'])) {
789 $GLOBALS['dbi']->query('ROLLBACK');