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 $parameters = $_REQUEST['parameters'];
109 foreach ($parameters as $parameter => $replacement) {
110 $quoted = preg_quote($parameter);
111 // making sure that :param does not apply values to :param1
112 $sql_query = preg_replace(
113 '/' . $quoted . '([^a-zA-Z0-9_])/',
114 PMA_Util
::sqlAddSlashes($replacement) . '${1}',
117 // for parameters the appear at the end of the string
118 $sql_query = preg_replace(
119 '/' . $quoted . '$/',
120 PMA_Util
::sqlAddSlashes($replacement),
127 $import_text = $sql_query;
128 $import_type = 'query';
130 $_SESSION['sql_from_query_box'] = true;
132 // If there is a request to ROLLBACK when finished.
133 if (isset($_REQUEST['rollback_query'])) {
134 PMA_handleRollbackRequest($import_text);
137 // refresh navigation and main panels
138 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
139 $GLOBALS['reload'] = true;
140 $ajax_reload['reload'] = true;
143 // refresh navigation panel only
145 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
148 $ajax_reload['reload'] = true;
151 // do a dynamic reload if table is RENAMED
152 // (by sending the instruction to the AJAX response handler)
154 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
158 $ajax_reload['reload'] = true;
159 $ajax_reload['table_name'] = PMA_Util
::unQuote($rename_table_names[2]);
163 } elseif (! empty($sql_file)) {
164 // run uploaded SQL file
165 $import_file = $sql_file;
166 $import_type = 'queryfile';
169 } elseif (! empty($_REQUEST['id_bookmark'])) {
171 $import_type = 'query';
175 // If we didn't get any parameters, either user called this directly, or
176 // upload limit has been reached, let's assume the second possibility.
177 if ($_POST == array() && $_GET == array()) {
178 $message = PMA_Message
::error(
180 'You probably tried to upload a file that is too large. Please refer ' .
181 'to %sdocumentation%s for a workaround for this limit.'
184 $message->addParam('[doc@faq1-16]');
185 $message->addParam('[/doc]');
187 // so we can obtain the message
188 $_SESSION['Import_message']['message'] = $message->getDisplay();
189 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
192 exit; // the footer is displayed automatically
195 // Add console message id to response output
196 if (isset($_POST['console_message_id'])) {
197 $response = PMA_Response
::getInstance();
198 $response->addJSON('console_message_id', $_POST['console_message_id']);
202 * Sets globals from $_POST patterns, for import plugins
203 * We only need to load the selected plugin
219 // this should not happen for a normal user
220 // but only during an attack
221 PMA_fatalError('Incorrect format parameter');
224 $post_patterns = array(
226 '/^' . $format . '_/'
229 PMA_setPostAsGlobal($post_patterns);
231 // Check needed parameters
232 PMA_Util
::checkParameters(array('import_type', 'format'));
234 // We don't want anything special in format
235 $format = PMA_securePath($format);
236 /** @var PMA_String $pmaString */
237 $pmaString = $GLOBALS['PMA_String'];
239 // Create error and goto url
240 if ($import_type == 'table') {
241 $err_url = 'tbl_import.php' . PMA_URL_getCommon(
243 'db' => $db, 'table' => $table
246 $_SESSION['Import_message']['go_back_url'] = $err_url;
247 $goto = 'tbl_import.php';
248 } elseif ($import_type == 'database') {
249 $err_url = 'db_import.php' . PMA_URL_getCommon(array('db' => $db));
250 $_SESSION['Import_message']['go_back_url'] = $err_url;
251 $goto = 'db_import.php';
252 } elseif ($import_type == 'server') {
253 $err_url = 'server_import.php' . PMA_URL_getCommon();
254 $_SESSION['Import_message']['go_back_url'] = $err_url;
255 $goto = 'server_import.php';
257 if (empty($goto) ||
!preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
258 if (/*overload*/mb_strlen($table) && /*overload*/mb_strlen($db)) {
259 $goto = 'tbl_structure.php';
260 } elseif (/*overload*/mb_strlen($db)) {
261 $goto = 'db_structure.php';
263 $goto = 'server_sql.php';
266 if (/*overload*/mb_strlen($table) && /*overload*/mb_strlen($db)) {
267 $common = PMA_URL_getCommon(array('db' => $db, 'table' => $table));
268 } elseif (/*overload*/mb_strlen($db)) {
269 $common = PMA_URL_getCommon(array('db' => $db));
271 $common = PMA_URL_getCommon();
273 $err_url = $goto . $common
274 . (preg_match('@^tbl_[a-z]*\.php$@', $goto)
275 ?
'&table=' . htmlspecialchars($table)
277 $_SESSION['Import_message']['go_back_url'] = $err_url;
279 // Avoid setting selflink to 'import.php'
280 // problem similar to bug 4276
281 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
282 $_SERVER['SCRIPT_NAME'] = $goto;
286 if (/*overload*/mb_strlen($db)) {
287 $GLOBALS['dbi']->selectDb($db);
290 @set_time_limit
($cfg['ExecTimeLimit']);
291 if (! empty($cfg['MemoryLimit'])) {
292 @ini_set
('memory_limit', $cfg['MemoryLimit']);
296 if (isset($_REQUEST['allow_interrupt'])) {
297 $maximum_time = ini_get('max_execution_time');
302 // set default values
303 $timeout_passed = false;
309 $file_to_unlink = '';
311 $sql_query_disabled = false;
313 $executed_queries = 0;
315 $charset_conversion = false;
316 $reset_charset = false;
317 $bookmark_created = false;
319 // Bookmark Support: get a query back from bookmark if required
320 if (! empty($_REQUEST['id_bookmark'])) {
321 $id_bookmark = (int)$_REQUEST['id_bookmark'];
322 include_once 'libraries/bookmark.lib.php';
323 switch ($_REQUEST['action_bookmark']) {
324 case 0: // bookmarked query that have to be run
325 $import_text = PMA_Bookmark_get(
329 isset($_REQUEST['action_bookmark_all'])
331 if (! empty($_REQUEST['bookmark_variable'])) {
332 $import_text = PMA_Bookmark_applyVariables(
337 // refresh navigation and main panels
339 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
342 $GLOBALS['reload'] = true;
343 $ajax_reload['reload'] = true;
346 // refresh navigation panel only
348 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
352 $ajax_reload['reload'] = true;
355 case 1: // bookmarked query that have to be displayed
356 $import_text = PMA_Bookmark_get($db, $id_bookmark);
357 if ($GLOBALS['is_ajax_request'] == true) {
358 $message = PMA_Message
::success(__('Showing bookmark'));
359 $response = PMA_Response
::getInstance();
360 $response->isSuccess($message->isSuccess());
361 $response->addJSON('message', $message);
362 $response->addJSON('sql_query', $import_text);
363 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
369 case 2: // bookmarked query that have to be deleted
370 $import_text = PMA_Bookmark_get($db, $id_bookmark);
371 PMA_Bookmark_delete($id_bookmark);
372 if ($GLOBALS['is_ajax_request'] == true) {
373 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
374 $response = PMA_Response
::getInstance();
375 $response->isSuccess($message->isSuccess());
376 $response->addJSON('message', $message);
377 $response->addJSON('action_bookmark', $_REQUEST['action_bookmark']);
378 $response->addJSON('id_bookmark', $id_bookmark);
382 $error = true; // this is kind of hack to skip processing the query
386 } // end bookmarks reading
388 // Do no run query if we show PHP code
389 if (isset($GLOBALS['show_as_php'])) {
394 // We can not read all at once, otherwise we can run out of memory
395 $memory_limit = trim(@ini_get
('memory_limit'));
397 if (empty($memory_limit)) {
398 $memory_limit = 2 * 1024 * 1024;
400 // In case no memory limit we work on 10MB chunks
401 if ($memory_limit == -1) {
402 $memory_limit = 10 * 1024 * 1024;
405 // Calculate value of the limit
406 $memoryUnit = /*overload*/mb_strtolower(substr($memory_limit, -1));
407 if ('m' == $memoryUnit) {
408 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
409 } elseif ('k' == $memoryUnit) {
410 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
411 } elseif ('g' == $memoryUnit) {
412 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
414 $memory_limit = (int)$memory_limit;
417 // Just to be sure, there might be lot of memory needed for uncompression
418 $read_limit = $memory_limit / 8;
421 if (isset($_FILES['import_file'])) {
422 $import_file = $_FILES['import_file']['tmp_name'];
424 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
426 // sanitize $local_import_file as it comes from a POST
427 $local_import_file = PMA_securePath($local_import_file);
429 $import_file = PMA_Util
::userDir($cfg['UploadDir'])
430 . $local_import_file;
432 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
433 $import_file = 'none';
436 // Do we have file to import?
438 if ($import_file != 'none' && ! $error) {
439 // work around open_basedir and other limitations
440 $open_basedir = @ini_get
('open_basedir');
442 // If we are on a server with open_basedir, we must move the file
443 // before opening it.
445 if (! empty($open_basedir)) {
446 $tmp_subdir = ini_get('upload_tmp_dir');
447 if (empty($tmp_subdir)) {
448 $tmp_subdir = sys_get_temp_dir();
450 $tmp_subdir = rtrim($tmp_subdir, DIRECTORY_SEPARATOR
);
451 if (is_writable($tmp_subdir)) {
452 $import_file_new = $tmp_subdir . DIRECTORY_SEPARATOR
453 . basename($import_file) . uniqid();
454 if (move_uploaded_file($import_file, $import_file_new)) {
455 $import_file = $import_file_new;
456 $file_to_unlink = $import_file_new;
459 $size = filesize($import_file);
462 // If the php.ini is misconfigured (eg. there is no /tmp access defined
463 // with open_basedir), $tmp_subdir won't be writable and the user gets
464 // a 'File could not be read!' error (at PMA_detectCompression), which
465 // is not too meaningful. Show a meaningful error message to the user
468 $message = PMA_Message
::error(
470 'Uploaded file cannot be moved, because the server has ' .
471 'open_basedir enabled without access to the %s directory ' .
472 '(for temporary files).'
475 $message->addParam($tmp_subdir);
476 PMA_stopImport($message);
481 * Handle file compression
482 * @todo duplicate code exists in File.class.php
484 $compression = PMA_detectCompression($import_file);
485 if ($compression === false) {
486 $message = PMA_Message
::error(__('File could not be read!'));
487 PMA_stopImport($message); //Contains an 'exit'
490 switch ($compression) {
491 case 'application/bzip2':
492 if ($cfg['BZipDump'] && @function_exists
('bzopen')) {
493 $import_handle = @bzopen
($import_file, 'r');
495 $message = PMA_Message
::error(
497 'You attempted to load file with unsupported compression ' .
498 '(%s). Either support for it is not implemented or disabled ' .
499 'by your configuration.'
502 $message->addParam($compression);
503 PMA_stopImport($message);
506 case 'application/gzip':
507 if ($cfg['GZipDump'] && @function_exists
('gzopen')) {
508 $import_handle = @gzopen
($import_file, 'r');
510 $message = PMA_Message
::error(
512 'You attempted to load file with unsupported compression ' .
513 '(%s). Either support for it is not implemented or disabled ' .
514 'by your configuration.'
517 $message->addParam($compression);
518 PMA_stopImport($message);
521 case 'application/zip':
522 if ($cfg['ZipDump'] && @function_exists
('zip_open')) {
524 * Load interface for zip extension.
526 include_once 'libraries/zip_extension.lib.php';
527 $zipResult = PMA_getZipContents($import_file);
528 if (! empty($zipResult['error'])) {
529 $message = PMA_Message
::rawError($zipResult['error']);
530 PMA_stopImport($message);
532 $import_text = $zipResult['data'];
535 $message = PMA_Message
::error(
537 'You attempted to load file with unsupported compression ' .
538 '(%s). Either support for it is not implemented or disabled ' .
539 'by your configuration.'
542 $message->addParam($compression);
543 PMA_stopImport($message);
547 $import_handle = @fopen
($import_file, 'r');
550 $message = PMA_Message
::error(
552 'You attempted to load file with unsupported compression (%s). ' .
553 'Either support for it is not implemented or disabled by your ' .
557 $message->addParam($compression);
558 PMA_stopImport($message);
561 // use isset() because zip compression type does not use a handle
562 if (! $error && isset($import_handle) && $import_handle === false) {
563 $message = PMA_Message
::error(__('File could not be read!'));
564 PMA_stopImport($message);
566 } elseif (! $error) {
567 if (! isset($import_text) ||
empty($import_text)) {
568 $message = PMA_Message
::error(
570 'No data was received to import. Either no file name was ' .
571 'submitted, or the file size exceeded the maximum size permitted ' .
572 'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
575 PMA_stopImport($message);
579 // so we can obtain the message
580 //$_SESSION['Import_message'] = $message->getDisplay();
582 // Convert the file's charset if necessary
583 if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE
&& isset($charset_of_file)) {
584 if ($charset_of_file != 'utf-8') {
585 $charset_conversion = true;
587 } elseif (isset($charset_of_file) && $charset_of_file != 'utf-8') {
589 // Drizzle doesn't support other character sets,
590 // so we can't fallback to SET NAMES - throw an error
591 $message = PMA_Message
::error(
593 'Cannot convert file\'s character'
594 . ' set without character set conversion library!'
597 PMA_stopImport($message);
599 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
600 // We can not show query in this case, it is in different charset
601 $sql_query_disabled = true;
602 $reset_charset = true;
606 // Something to skip? (because timeout has passed)
607 if (! $error && isset($_POST['skip'])) {
608 $original_skip = $skip = $_POST['skip'];
610 PMA_importGetNextChunk($skip < $read_limit ?
$skip : $read_limit);
611 // Disable read progressivity, otherwise we eat all memory!
613 $skip -= $read_limit;
618 // This array contain the data like numberof valid sql queries in the statement
619 // and complete valid sql statement (which affected for rows)
620 $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
623 // Check for file existence
624 include_once "libraries/plugin_interface.lib.php";
625 /* @var $import_plugin ImportPlugin */
626 $import_plugin = PMA_getPlugin(
629 'libraries/plugins/import/',
632 if ($import_plugin == null) {
633 $message = PMA_Message
::error(
634 __('Could not load import plugins, please check your installation!')
636 PMA_stopImport($message);
638 // Do the real import
640 $default_fk_check = PMA_Util
::handleDisableFKCheckInit();
641 $import_plugin->doImport($sql_data);
642 PMA_Util
::handleDisableFKCheckCleanup($default_fk_check);
643 } catch (Exception
$e) {
644 PMA_Util
::handleDisableFKCheckCleanup($default_fk_check);
650 if (! empty($import_handle)) {
651 fclose($import_handle);
654 // Cleanup temporary file
655 if ($file_to_unlink != '') {
656 unlink($file_to_unlink);
659 // Reset charset back, if we did some changes
660 if ($reset_charset) {
661 $GLOBALS['dbi']->query('SET CHARACTER SET utf8');
662 $GLOBALS['dbi']->query(
663 'SET SESSION collation_connection =\'' . $collation_connection . '\''
667 // Show correct message
668 if (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 2) {
669 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
670 $display_query = $import_text;
671 $error = false; // unset error marker, it was used just to skip processing
672 } elseif (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 1) {
673 $message = PMA_Message
::notice(__('Showing bookmark'));
674 } elseif ($bookmark_created) {
675 $special_message = '[br]' . sprintf(
676 __('Bookmark %s has been created.'),
677 htmlspecialchars($_POST['bkm_label'])
679 } elseif ($finished && ! $error) {
680 if ($import_type == 'query') {
681 $message = PMA_Message
::success();
683 $message = PMA_Message
::success(
685 . __('Import has been successfully finished, %d queries executed.')
688 $message->addParam($executed_queries);
690 if ($import_notice) {
691 $message->addString($import_notice);
693 if (isset($local_import_file)) {
694 $message->addString('(' . htmlspecialchars($local_import_file) . ')');
697 '(' . htmlspecialchars($_FILES['import_file']['name']) . ')'
703 // Did we hit timeout? Tell it user.
704 if ($timeout_passed) {
705 $importUrl = $err_url .= '&timeout_passed=1&offset=' . urlencode(
708 if (isset($local_import_file)) {
709 $importUrl .= '&local_import_file=' . urlencode($local_import_file);
711 $message = PMA_Message
::error(
713 'Script timeout passed, if you want to finish import,'
714 . ' please %sresubmit the same file%s and import will resume.'
717 $message->addParam('<a href="' . $importUrl . '">', false);
718 $message->addParam('</a>', false);
720 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
723 'However on last run no data has been parsed,'
724 . ' this usually means phpMyAdmin won\'t be able to'
725 . ' finish this import unless you increase php time limits.'
731 // if there is any message, copy it into $_SESSION as well,
732 // so we can obtain it by AJAX call
733 if (isset($message)) {
734 $_SESSION['Import_message']['message'] = $message->getDisplay();
736 // Parse and analyze the query, for correct db and table name
737 // in case of a query typed in the query window
738 // (but if the query is too large, in case of an imported file, the parser
739 // can choke on it so avoid parsing)
740 $sqlLength = /*overload*/mb_strlen($sql_query);
741 if ($sqlLength <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
742 include_once 'libraries/parse_analyze.inc.php';
745 // There was an error?
746 if (isset($my_die)) {
747 foreach ($my_die as $key => $die) {
749 $die['error'], $die['sql'], false, $err_url, $error
756 if (! empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
757 $_SESSION['is_multi_query'] = true;
758 $sql_queries = $sql_data['valid_sql'];
760 $sql_queries = array($sql_query);
764 foreach ($sql_queries as $sql_query) {
766 include 'libraries/parse_analyze.inc.php';
768 $html_output .= PMA_executeQueryAndGetQueryResponse(
769 $analyzed_sql_results, // analyzed_sql_results
770 false, // is_gotofile
773 null, // find_real_end
774 $sql_query, // sql_query_for_bookmark
776 null, // message_to_show
780 $pmaThemeImage, // pmaThemeImage
782 null, // disp_message
784 $sql_query, // sql_query
785 null, // selectedTables
786 null // complete_query
790 $response = PMA_Response
::getInstance();
791 $response->addJSON('ajax_reload', $ajax_reload);
792 $response->addHTML($html_output);
795 } else if ($result) {
796 // Save a Bookmark with more than one queries (if Bookmark label given).
797 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
798 $cfgBookmark = PMA_Bookmark_getParams();
799 PMA_storeTheQueryAsBookmark(
800 $db, $cfgBookmark['user'],
801 $_REQUEST['sql_query'], $_POST['bkm_label'],
802 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
806 $response = PMA_Response
::getInstance();
807 $response->isSuccess(true);
808 $response->addJSON('message', PMA_Message
::success($msg));
811 PMA_Util
::getMessage($msg, $sql_query, 'success')
813 } else if ($result == false) {
814 $response = PMA_Response
::getInstance();
815 $response->isSuccess(false);
816 $response->addJSON('message', PMA_Message
::error($msg));
818 $active_page = $goto;
822 // If there is request for ROLLBACK in the end.
823 if (isset($_REQUEST['rollback_query'])) {
824 $GLOBALS['dbi']->query('ROLLBACK');