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
87 // TODO: adapt full list of allowed parameters, as in export.php
88 foreach ($post_params as $one_post_param) {
89 if (isset($_POST[$one_post_param])) {
90 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
94 // reset import messages for ajax request
95 $_SESSION['Import_message']['message'] = null;
96 $_SESSION['Import_message']['go_back_url'] = null;
98 $GLOBALS['reload'] = false;
100 // Use to identify current cycle is executing
101 // a multiquery statement or stored routine
102 if (!isset($_SESSION['is_multi_query'])) {
103 $_SESSION['is_multi_query'] = false;
106 // Are we just executing plain query or sql file?
107 // (eg. non import, but query box/window run)
108 if (! empty($sql_query)) {
110 $import_text = $sql_query;
111 $import_type = 'query';
114 // If there is a request to ROLLBACK when finished.
115 if (isset($_REQUEST['rollback_query'])) {
116 PMA_handleRollbackRequest($import_text);
119 // refresh navigation and main panels
120 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
121 $GLOBALS['reload'] = true;
124 // refresh navigation panel only
126 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
129 $ajax_reload = array('reload' => true);
132 // do a dynamic reload if table is RENAMED
133 // (by sending the instruction to the AJAX response handler)
135 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
139 $ajax_reload = array('reload' => true);
140 $ajax_reload['table_name'] = PMA_Util
::unQuote($rename_table_names[2]);
144 } elseif (! empty($sql_localfile)) {
145 // run SQL file on server
146 $local_import_file = $sql_localfile;
147 $import_type = 'queryfile';
149 unset($sql_localfile);
150 } elseif (! empty($sql_file)) {
151 // run uploaded SQL file
152 $import_file = $sql_file;
153 $import_type = 'queryfile';
156 } elseif (! empty($id_bookmark)) {
158 $import_type = 'query';
162 // If we didn't get any parameters, either user called this directly, or
163 // upload limit has been reached, let's assume the second possibility.
164 if ($_POST == array() && $_GET == array()) {
165 $message = PMA_Message
::error(
166 __('You probably tried to upload a file that is too large. Please refer to %sdocumentation%s for a workaround for this limit.')
168 $message->addParam('[doc@faq1-16]');
169 $message->addParam('[/doc]');
171 // so we can obtain the message
172 $_SESSION['Import_message']['message'] = $message->getDisplay();
173 $_SESSION['Import_message']['go_back_url'] = $GLOBALS['goto'];
176 exit; // the footer is displayed automatically
179 // Add console message id to response output
180 if (isset($_POST['console_message_id'])) {
181 $response = PMA_Response
::getInstance();
182 $response->addJSON('console_message_id', $_POST['console_message_id']);
186 * Sets globals from $_POST patterns, for import plugins
187 * We only need to load the selected plugin
203 // this should not happen for a normal user
204 // but only during an attack
205 PMA_fatalError('Incorrect format parameter');
208 $post_patterns = array(
210 '/^' . $format . '_/'
212 foreach (array_keys($_POST) as $post_key) {
213 foreach ($post_patterns as $one_post_pattern) {
214 if (preg_match($one_post_pattern, $post_key)) {
215 $GLOBALS[$post_key] = $_POST[$post_key];
220 // Check needed parameters
221 PMA_Util
::checkParameters(array('import_type', 'format'));
223 // We don't want anything special in format
224 $format = PMA_securePath($format);
225 /** @var PMA_String $pmaString */
226 $pmaString = $GLOBALS['PMA_String'];
228 // Create error and goto url
229 if ($import_type == 'table') {
230 $err_url = 'tbl_import.php?' . PMA_URL_getCommon($db, $table);
231 $_SESSION['Import_message']['go_back_url'] = $err_url;
232 $goto = 'tbl_import.php';
233 } elseif ($import_type == 'database') {
234 $err_url = 'db_import.php?' . PMA_URL_getCommon($db);
235 $_SESSION['Import_message']['go_back_url'] = $err_url;
236 $goto = 'db_import.php';
237 } elseif ($import_type == 'server') {
238 $err_url = 'server_import.php?' . PMA_URL_getCommon();
239 $_SESSION['Import_message']['go_back_url'] = $err_url;
240 $goto = 'server_import.php';
242 if (empty($goto) ||
!preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
243 if ($pmaString->strlen($table) && $pmaString->strlen($db)) {
244 $goto = 'tbl_structure.php';
245 } elseif ($pmaString->strlen($db)) {
246 $goto = 'db_structure.php';
248 $goto = 'server_sql.php';
251 if ($pmaString->strlen($table) && $pmaString->strlen($db)) {
252 $common = PMA_URL_getCommon($db, $table);
253 } elseif ($pmaString->strlen($db)) {
254 $common = PMA_URL_getCommon($db);
256 $common = PMA_URL_getCommon();
258 $err_url = $goto . '?' . $common
259 . (preg_match('@^tbl_[a-z]*\.php$@', $goto)
260 ?
'&table=' . htmlspecialchars($table)
262 $_SESSION['Import_message']['go_back_url'] = $err_url;
264 // Avoid setting selflink to 'import.php'
265 // problem similar to bug 4276
266 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
267 $_SERVER['SCRIPT_NAME'] = $goto;
271 if ($pmaString->strlen($db)) {
272 $GLOBALS['dbi']->selectDb($db);
275 @set_time_limit
($cfg['ExecTimeLimit']);
276 if (! empty($cfg['MemoryLimit'])) {
277 @ini_set
('memory_limit', $cfg['MemoryLimit']);
281 if (isset($allow_interrupt)) {
282 $maximum_time = ini_get('max_execution_time');
287 // set default values
288 $timeout_passed = false;
294 $file_to_unlink = '';
296 $sql_query_disabled = false;
298 $executed_queries = 0;
300 $charset_conversion = false;
301 $reset_charset = false;
302 $bookmark_created = false;
304 // Bookmark Support: get a query back from bookmark if required
305 if (! empty($id_bookmark)) {
306 $id_bookmark = (int)$id_bookmark;
307 include_once 'libraries/bookmark.lib.php';
308 switch ($action_bookmark) {
309 case 0: // bookmarked query that have to be run
310 $import_text = PMA_Bookmark_get(
314 isset($action_bookmark_all)
316 if (isset($bookmark_variable) && ! empty($bookmark_variable)) {
317 $import_text = preg_replace(
318 '|/\*(.*)\[VARIABLE\](.*)\*/|imsU',
319 '${1}' . PMA_Util
::sqlAddSlashes($bookmark_variable) . '${2}',
324 // refresh navigation and main panels
326 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
329 $GLOBALS['reload'] = true;
332 // refresh navigation panel only
334 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
338 if (! isset($ajax_reload)) {
339 $ajax_reload = array();
341 $ajax_reload['reload'] = true;
344 case 1: // bookmarked query that have to be displayed
345 $import_text = PMA_Bookmark_get($db, $id_bookmark);
346 if ($GLOBALS['is_ajax_request'] == true) {
347 $message = PMA_Message
::success(__('Showing bookmark'));
348 $response = PMA_Response
::getInstance();
349 $response->isSuccess($message->isSuccess());
350 $response->addJSON('message', $message);
351 $response->addJSON('sql_query', $import_text);
352 $response->addJSON('action_bookmark', $action_bookmark);
358 case 2: // bookmarked query that have to be deleted
359 $import_text = PMA_Bookmark_get($db, $id_bookmark);
360 PMA_Bookmark_delete($id_bookmark);
361 if ($GLOBALS['is_ajax_request'] == true) {
362 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
363 $response = PMA_Response
::getInstance();
364 $response->isSuccess($message->isSuccess());
365 $response->addJSON('message', $message);
366 $response->addJSON('action_bookmark', $action_bookmark);
367 $response->addJSON('id_bookmark', $id_bookmark);
371 $error = true; // this is kind of hack to skip processing the query
375 } // end bookmarks reading
377 // Do no run query if we show PHP code
378 if (isset($GLOBALS['show_as_php'])) {
383 // We can not read all at once, otherwise we can run out of memory
384 $memory_limit = trim(@ini_get
('memory_limit'));
386 if (empty($memory_limit)) {
387 $memory_limit = 2 * 1024 * 1024;
389 // In case no memory limit we work on 10MB chunks
390 if ($memory_limit == -1) {
391 $memory_limit = 10 * 1024 * 1024;
394 // Calculate value of the limit
395 if ($pmaString->strtolower($pmaString->substr($memory_limit, -1)) == 'm') {
396 $memory_limit = (int)$pmaString->substr($memory_limit, 0, -1) * 1024 * 1024;
397 } elseif ($pmaString->strtolower($pmaString->substr($memory_limit, -1)) == 'k') {
398 $memory_limit = (int)$pmaString->substr($memory_limit, 0, -1) * 1024;
399 } elseif ($pmaString->strtolower($pmaString->substr($memory_limit, -1)) == 'g') {
401 = (int)$pmaString->substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
403 $memory_limit = (int)$memory_limit;
406 // Just to be sure, there might be lot of memory needed for uncompression
407 $read_limit = $memory_limit / 8;
410 if (isset($_FILES['import_file'])) {
411 $import_file = $_FILES['import_file']['tmp_name'];
413 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
415 // sanitize $local_import_file as it comes from a POST
416 $local_import_file = PMA_securePath($local_import_file);
418 $import_file = PMA_Util
::userDir($cfg['UploadDir'])
419 . $local_import_file;
421 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
422 $import_file = 'none';
425 // Do we have file to import?
427 if ($import_file != 'none' && ! $error) {
428 // work around open_basedir and other limitations
429 $open_basedir = @ini_get
('open_basedir');
431 // If we are on a server with open_basedir, we must move the file
432 // before opening it.
434 if (! empty($open_basedir)) {
437 * @todo make use of the config's temp dir with fallback to the
440 $tmp_subdir = ini_get('upload_tmp_dir');
441 if (empty($tmp_subdir)) {
442 $tmp_subdir = sys_get_temp_dir();
445 if (is_writable($tmp_subdir)) {
447 $import_file_new = $tmp_subdir . basename($import_file) . uniqid();
448 if (move_uploaded_file($import_file, $import_file_new)) {
449 $import_file = $import_file_new;
450 $file_to_unlink = $import_file_new;
453 $size = filesize($import_file);
456 // If the php.ini is misconfigured (eg. there is no /tmp access defined
457 // with open_basedir), $tmp_subdir won't be writable and the user gets
458 // a 'File could not be read!' error (at PMA_detectCompression), which
459 // is not too meaningful. Show a meaningful error message to the user
462 $message = PMA_Message
::error(
463 __('Uploaded file cannot be moved, because the server has open_basedir enabled without access to the %s directory (for temporary files).')
465 $message->addParam($tmp_subdir);
466 PMA_stopImport($message);
471 * Handle file compression
472 * @todo duplicate code exists in File.class.php
474 $compression = PMA_detectCompression($import_file);
475 if ($compression === false) {
476 $message = PMA_Message
::error(__('File could not be read!'));
477 PMA_stopImport($message); //Contains an 'exit'
480 switch ($compression) {
481 case 'application/bzip2':
482 if ($cfg['BZipDump'] && @function_exists
('bzopen')) {
483 $import_handle = @bzopen
($import_file, 'r');
485 $message = PMA_Message
::error(
486 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
488 $message->addParam($compression);
489 PMA_stopImport($message);
492 case 'application/gzip':
493 if ($cfg['GZipDump'] && @function_exists
('gzopen')) {
494 $import_handle = @gzopen
($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/zip':
504 if ($cfg['ZipDump'] && @function_exists
('zip_open')) {
506 * Load interface for zip extension.
508 include_once 'libraries/zip_extension.lib.php';
509 $zipResult = PMA_getZipContents($import_file);
510 if (! empty($zipResult['error'])) {
511 $message = PMA_Message
::rawError($zipResult['error']);
512 PMA_stopImport($message);
514 $import_text = $zipResult['data'];
517 $message = PMA_Message
::error(
518 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
520 $message->addParam($compression);
521 PMA_stopImport($message);
525 $import_handle = @fopen
($import_file, 'r');
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);
535 // use isset() because zip compression type does not use a handle
536 if (! $error && isset($import_handle) && $import_handle === false) {
537 $message = PMA_Message
::error(__('File could not be read!'));
538 PMA_stopImport($message);
540 } elseif (! $error) {
541 if (! isset($import_text) ||
empty($import_text)) {
542 $message = PMA_Message
::error(
543 __('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].')
545 PMA_stopImport($message);
549 // so we can obtain the message
550 //$_SESSION['Import_message'] = $message->getDisplay();
552 // Convert the file's charset if necessary
553 if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE
&& isset($charset_of_file)) {
554 if ($charset_of_file != 'utf-8') {
555 $charset_conversion = true;
557 } elseif (isset($charset_of_file) && $charset_of_file != 'utf8') {
559 // Drizzle doesn't support other character sets,
560 // so we can't fallback to SET NAMES - throw an error
561 $message = PMA_Message
::error(
562 __('Cannot convert file\'s character set without character set conversion library!')
564 PMA_stopImport($message);
566 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
567 // We can not show query in this case, it is in different charset
568 $sql_query_disabled = true;
569 $reset_charset = true;
573 // Something to skip?
574 if (! $error && isset($skip)) {
575 $original_skip = $skip;
577 PMA_importGetNextChunk($skip < $read_limit ?
$skip : $read_limit);
578 // Disable read progressivity, otherwise we eat all memory!
580 $skip -= $read_limit;
585 // This array contain the data like numberof valid sql queries in the statement
586 // and complete valid sql statement (which affected for rows)
587 $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
590 // Check for file existence
591 include_once "libraries/plugin_interface.lib.php";
592 $import_plugin = PMA_getPlugin(
595 'libraries/plugins/import/',
598 if ($import_plugin == null) {
599 $message = PMA_Message
::error(
600 __('Could not load import plugins, please check your installation!')
602 PMA_stopImport($message);
604 // Do the real import
605 $import_plugin->doImport($sql_data);
609 if (! empty($import_handle)) {
610 fclose($import_handle);
613 // Cleanup temporary file
614 if ($file_to_unlink != '') {
615 unlink($file_to_unlink);
618 // Reset charset back, if we did some changes
619 if ($reset_charset) {
620 $GLOBALS['dbi']->query('SET CHARACTER SET utf8');
621 $GLOBALS['dbi']->query(
622 'SET SESSION collation_connection =\'' . $collation_connection . '\''
626 // Show correct message
627 if (! empty($id_bookmark) && $action_bookmark == 2) {
628 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
629 $display_query = $import_text;
630 $error = false; // unset error marker, it was used just to skip processing
631 } elseif (! empty($id_bookmark) && $action_bookmark == 1) {
632 $message = PMA_Message
::notice(__('Showing bookmark'));
633 } elseif ($bookmark_created) {
634 $special_message = '[br]' . sprintf(
635 __('Bookmark %s has been created.'),
636 htmlspecialchars($bkm_label)
638 } elseif ($finished && ! $error) {
639 if ($import_type == 'query') {
640 $message = PMA_Message
::success();
642 $message = PMA_Message
::success(
644 . __('Import has been successfully finished, %d queries executed.')
647 $message->addParam($executed_queries);
649 if ($import_notice) {
650 $message->addString($import_notice);
652 if (isset($local_import_file)) {
653 $message->addString('(' . htmlspecialchars($local_import_file) . ')');
656 '(' . htmlspecialchars($_FILES['import_file']['name']) . ')'
662 // Did we hit timeout? Tell it user.
663 if ($timeout_passed) {
664 $message = PMA_Message
::error(
665 __('Script timeout passed, if you want to finish import, please resubmit same file and import will resume.')
667 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
669 __('However on last run no data has been parsed, this usually means phpMyAdmin won\'t be able to finish this import unless you increase php time limits.')
674 // if there is any message, copy it into $_SESSION as well,
675 // so we can obtain it by AJAX call
676 if (isset($message)) {
677 $_SESSION['Import_message']['message'] = $message->getDisplay();
679 // Parse and analyze the query, for correct db and table name
680 // in case of a query typed in the query window
681 // (but if the query is too large, in case of an imported file, the parser
682 // can choke on it so avoid parsing)
683 if ($pmaString->strlen($sql_query) <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
685 include_once 'libraries/parse_analyze.inc.php';
688 // There was an error?
689 if (isset($my_die)) {
690 foreach ($my_die as $key => $die) {
692 $die['error'], $die['sql'], false, $err_url, $error
699 include_once 'libraries/parse_analyze.inc.php';
701 if (isset($ajax_reload) && $ajax_reload['reload'] === true) {
702 $response = PMA_Response
::getInstance();
703 $response->addJSON('ajax_reload', $ajax_reload);
705 PMA_executeQueryAndSendQueryResponse(
706 $analyzed_sql_results, false, $db, $table, null, $import_text, null,
707 $analyzed_sql_results['is_affected'], null,
708 null, null, null, $goto, $pmaThemeImage, null, null, null, $sql_query,
711 } else if ($result) {
712 // Save a Bookmark with more than one queries (if Bookmark label given).
713 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
714 $cfgBookmark = PMA_Bookmark_getParams();
715 PMA_storeTheQueryAsBookmark(
716 $db, $cfgBookmark['user'],
717 $import_text, $_POST['bkm_label'],
718 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
722 $response = PMA_Response
::getInstance();
723 $response->isSuccess(true);
724 $response->addJSON('message', PMA_Message
::success($msg));
727 PMA_Util
::getMessage($msg, $sql_query, 'success')
729 } else if ($result == false) {
730 $response = PMA_Response
::getInstance();
731 $response->isSuccess(false);
732 $response->addJSON('message', PMA_Message
::error($msg));
734 $active_page = $goto;
738 // If there is request for ROLLBACK in the end.
739 if (isset($_REQUEST['rollback_query'])) {
740 $GLOBALS['dbi']->query('ROLLBACK');