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/display_import_functions.lib.php';
17 if (isset($_REQUEST['show_as_php'])) {
18 $GLOBALS['show_as_php'] = $_REQUEST['show_as_php'];
22 * Sets globals from $_POST
41 // TODO: adapt full list of allowed parameters, as in export.php
42 foreach ($post_params as $one_post_param) {
43 if (isset($_POST[$one_post_param])) {
44 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
48 // reset import messages for ajax request
49 $_SESSION['Import_message']['message'] = null;
50 $_SESSION['Import_message']['go_back_url'] = null;
52 $GLOBALS['reload'] = false;
54 // Use to identify curren cycle is executing
55 // a multiquery statement or stored routine
56 if (!isset($_SESSION['is_multi_query'])) {
57 $_SESSION['is_multi_query'] = false;
60 // Are we just executing plain query or sql file?
61 // (eg. non import, but query box/window run)
62 if (! empty($sql_query)) {
64 $import_text = $sql_query;
65 $import_type = 'query';
68 // refresh navigation and main panels
69 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
70 $GLOBALS['reload'] = true;
73 // refresh navigation panel only
75 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
78 $ajax_reload['reload'] = true;
81 // do a dynamic reload if table is RENAMED
82 // (by sending the instruction to the AJAX response handler)
84 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
88 $ajax_reload['table_name'] = PMA_Util
::unQuote($rename_table_names[2]);
89 $ajax_reload['reload'] = true;
93 } elseif (! empty($sql_localfile)) {
94 // run SQL file on server
95 $local_import_file = $sql_localfile;
96 $import_type = 'queryfile';
98 unset($sql_localfile);
99 } elseif (! empty($sql_file)) {
100 // run uploaded SQL file
101 $import_file = $sql_file;
102 $import_type = 'queryfile';
105 } elseif (! empty($id_bookmark)) {
107 $import_type = 'query';
111 // If we didn't get any parameters, either user called this directly, or
112 // upload limit has been reached, let's assume the second possibility.
114 if ($_POST == array() && $_GET == array()) {
115 $message = PMA_Message
::error(
116 __('You probably tried to upload a file that is too large. Please refer to %sdocumentation%s for a workaround for this limit.')
118 $message->addParam('[doc@faq1-16]');
119 $message->addParam('[/doc]');
121 // so we can obtain the message
122 $_SESSION['Import_message']['message'] = $message->getDisplay();
123 $_SESSION['Import_message']['go_back_url'] = $goto;
126 exit; // the footer is displayed automatically
130 * Sets globals from $_POST patterns, for import plugins
131 * We only need to load the selected plugin
147 // this should not happen for a normal user
148 // but only during an attack
149 PMA_fatalError('Incorrect format parameter');
152 $post_patterns = array(
154 '/^' . $format . '_/'
156 foreach (array_keys($_POST) as $post_key) {
157 foreach ($post_patterns as $one_post_pattern) {
158 if (preg_match($one_post_pattern, $post_key)) {
159 $GLOBALS[$post_key] = $_POST[$post_key];
164 // Check needed parameters
165 PMA_Util
::checkParameters(array('import_type', 'format'));
167 // We don't want anything special in format
168 $format = PMA_securePath($format);
171 require_once 'libraries/import.lib.php';
173 // Create error and goto url
174 if ($import_type == 'table') {
175 $err_url = 'tbl_import.php?' . PMA_URL_getCommon($db, $table);
176 $_SESSION['Import_message']['go_back_url'] = $err_url;
177 $goto = 'tbl_import.php';
178 } elseif ($import_type == 'database') {
179 $err_url = 'db_import.php?' . PMA_URL_getCommon($db);
180 $_SESSION['Import_message']['go_back_url'] = $err_url;
181 $goto = 'db_import.php';
182 } elseif ($import_type == 'server') {
183 $err_url = 'server_import.php?' . PMA_URL_getCommon();
184 $_SESSION['Import_message']['go_back_url'] = $err_url;
185 $goto = 'server_import.php';
187 if (empty($goto) ||
!preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
188 if (strlen($table) && strlen($db)) {
189 $goto = 'tbl_structure.php';
190 } elseif (strlen($db)) {
191 $goto = 'db_structure.php';
193 $goto = 'server_sql.php';
196 if (strlen($table) && strlen($db)) {
197 $common = PMA_URL_getCommon($db, $table);
198 } elseif (strlen($db)) {
199 $common = PMA_URL_getCommon($db);
201 $common = PMA_URL_getCommon();
203 $err_url = $goto . '?' . $common
204 . (preg_match('@^tbl_[a-z]*\.php$@', $goto)
205 ?
'&table=' . htmlspecialchars($table)
207 $_SESSION['Import_message']['go_back_url'] = $err_url;
212 $GLOBALS['dbi']->selectDb($db);
215 @set_time_limit
($cfg['ExecTimeLimit']);
216 if (! empty($cfg['MemoryLimit'])) {
217 @ini_set
('memory_limit', $cfg['MemoryLimit']);
221 if (isset($allow_interrupt)) {
222 $maximum_time = ini_get('max_execution_time');
227 // set default values
228 $timeout_passed = false;
234 $file_to_unlink = '';
236 $sql_query_disabled = false;
238 $executed_queries = 0;
240 $charset_conversion = false;
241 $reset_charset = false;
242 $bookmark_created = false;
244 // Bookmark Support: get a query back from bookmark if required
245 if (! empty($id_bookmark)) {
246 $id_bookmark = (int)$id_bookmark;
247 include_once 'libraries/bookmark.lib.php';
248 switch ($action_bookmark) {
249 case 0: // bookmarked query that have to be run
250 $import_text = PMA_Bookmark_get(
254 isset($action_bookmark_all)
256 if (isset($bookmark_variable) && ! empty($bookmark_variable)) {
257 $import_text = preg_replace(
258 '|/\*(.*)\[VARIABLE\](.*)\*/|imsU',
259 '${1}' . PMA_Util
::sqlAddSlashes($bookmark_variable) . '${2}',
264 // refresh navigation and main panels
266 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
269 $GLOBALS['reload'] = true;
272 // refresh navigation panel only
274 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
278 $ajax_reload['reload'] = true;
281 case 1: // bookmarked query that have to be displayed
282 $import_text = PMA_Bookmark_get($db, $id_bookmark);
283 if ($GLOBALS['is_ajax_request'] == true) {
284 $message = PMA_Message
::success(__('Showing bookmark'));
285 $response = PMA_Response
::getInstance();
286 $response->isSuccess($message->isSuccess());
287 $response->addJSON('message', $message);
288 $response->addJSON('sql_query', $import_text);
289 $response->addJSON('action_bookmark', $action_bookmark);
295 case 2: // bookmarked query that have to be deleted
296 $import_text = PMA_Bookmark_get($db, $id_bookmark);
297 PMA_Bookmark_delete($id_bookmark);
298 if ($GLOBALS['is_ajax_request'] == true) {
299 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
300 $response = PMA_Response
::getInstance();
301 $response->isSuccess($message->isSuccess());
302 $response->addJSON('message', $message);
303 $response->addJSON('action_bookmark', $action_bookmark);
304 $response->addJSON('id_bookmark', $id_bookmark);
308 $error = true; // this is kind of hack to skip processing the query
312 } // end bookmarks reading
314 // Do no run query if we show PHP code
315 if (isset($GLOBALS['show_as_php'])) {
320 // We can not read all at once, otherwise we can run out of memory
321 $memory_limit = trim(@ini_get
('memory_limit'));
323 if (empty($memory_limit)) {
324 $memory_limit = 2 * 1024 * 1024;
326 // In case no memory limit we work on 10MB chunks
327 if ($memory_limit == -1) {
328 $memory_limit = 10 * 1024 * 1024;
331 // Calculate value of the limit
332 if (strtolower(substr($memory_limit, -1)) == 'm') {
333 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
334 } elseif (strtolower(substr($memory_limit, -1)) == 'k') {
335 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
336 } elseif (strtolower(substr($memory_limit, -1)) == 'g') {
337 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
339 $memory_limit = (int)$memory_limit;
342 // Just to be sure, there might be lot of memory needed for uncompression
343 $read_limit = $memory_limit / 8;
346 if (isset($_FILES['import_file'])) {
347 $import_file = $_FILES['import_file']['tmp_name'];
349 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
351 // sanitize $local_import_file as it comes from a POST
352 $local_import_file = PMA_securePath($local_import_file);
354 $import_file = PMA_Util
::userDir($cfg['UploadDir'])
355 . $local_import_file;
357 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
358 $import_file = 'none';
361 // Do we have file to import?
363 if ($import_file != 'none' && ! $error) {
364 // work around open_basedir and other limitations
365 $open_basedir = @ini_get
('open_basedir');
367 // If we are on a server with open_basedir, we must move the file
368 // before opening it.
370 if (! empty($open_basedir)) {
373 * @todo make use of the config's temp dir with fallback to the
376 $tmp_subdir = ini_get('upload_tmp_dir');
378 if (is_writable($tmp_subdir)) {
380 $import_file_new = $tmp_subdir . basename($import_file) . uniqid();
381 if (move_uploaded_file($import_file, $import_file_new)) {
382 $import_file = $import_file_new;
383 $file_to_unlink = $import_file_new;
386 $size = filesize($import_file);
389 // If the php.ini is misconfigured (eg. there is no /tmp access defined
390 // with open_basedir), $tmp_subdir won't be writable and the user gets
391 // a 'File could not be read!' error (at PMA_detectCompression), which
392 // is not too meaningful. Show a meaningful error message to the user
395 $message = PMA_Message
::error(
396 __('Uploaded file cannot be moved, because the server has open_basedir enabled without access to the %s directory (for temporary files).')
398 $message->addParam($tmp_subdir);
399 PMA_stopImport($message);
404 * Handle file compression
405 * @todo duplicate code exists in File.class.php
407 $compression = PMA_detectCompression($import_file);
408 if ($compression === false) {
409 $message = PMA_Message
::error(__('File could not be read!'));
410 PMA_stopImport($message);
412 switch ($compression) {
413 case 'application/bzip2':
414 if ($cfg['BZipDump'] && @function_exists
('bzopen')) {
415 $import_handle = @bzopen
($import_file, 'r');
417 $message = PMA_Message
::error(
418 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
420 $message->addParam($compression);
421 PMA_stopImport($message);
424 case 'application/gzip':
425 if ($cfg['GZipDump'] && @function_exists
('gzopen')) {
426 $import_handle = @gzopen
($import_file, 'r');
428 $message = PMA_Message
::error(
429 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
431 $message->addParam($compression);
432 PMA_stopImport($message);
435 case 'application/zip':
436 if ($cfg['ZipDump'] && @function_exists
('zip_open')) {
438 * Load interface for zip extension.
440 include_once 'libraries/zip_extension.lib.php';
441 $zipResult = PMA_getZipContents($import_file);
442 if (! empty($zipResult['error'])) {
443 $message = PMA_Message
::rawError($zipResult['error']);
444 PMA_stopImport($message);
446 $import_text = $zipResult['data'];
449 $message = PMA_Message
::error(
450 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
452 $message->addParam($compression);
453 PMA_stopImport($message);
457 $import_handle = @fopen
($import_file, 'r');
460 $message = PMA_Message
::error(
461 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
463 $message->addParam($compression);
464 PMA_stopImport($message);
468 // use isset() because zip compression type does not use a handle
469 if (! $error && isset($import_handle) && $import_handle === false) {
470 $message = PMA_Message
::error(__('File could not be read!'));
471 PMA_stopImport($message);
473 } elseif (! $error) {
474 if (! isset($import_text) ||
empty($import_text)) {
475 $message = PMA_Message
::error(
476 __('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].')
478 PMA_stopImport($message);
482 // so we can obtain the message
483 //$_SESSION['Import_message'] = $message->getDisplay();
485 // Convert the file's charset if necessary
486 if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE
&& isset($charset_of_file)) {
487 if ($charset_of_file != 'utf-8') {
488 $charset_conversion = true;
490 } elseif (isset($charset_of_file) && $charset_of_file != 'utf8') {
492 // Drizzle doesn't support other character sets,
493 // so we can't fallback to SET NAMES - throw an error
494 $message = PMA_Message
::error(
495 __('Cannot convert file\'s character set without character set conversion library!')
497 PMA_stopImport($message);
499 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
500 // We can not show query in this case, it is in different charset
501 $sql_query_disabled = true;
502 $reset_charset = true;
506 // Something to skip?
507 if (! $error && isset($skip)) {
508 $original_skip = $skip;
510 PMA_importGetNextChunk($skip < $read_limit ?
$skip : $read_limit);
511 // Disable read progressivity, otherwise we eat all memory!
513 $skip -= $read_limit;
518 // This array contain the data like numberof valid sql queries in the statement
519 // and complete valid sql statement (which affected for rows)
520 $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
523 // Check for file existance
524 include_once "libraries/plugin_interface.lib.php";
525 $import_plugin = PMA_getPlugin(
528 'libraries/plugins/import/',
531 if ($import_plugin == null) {
532 $message = PMA_Message
::error(
533 __('Could not load import plugins, please check your installation!')
535 PMA_stopImport($message);
537 // Do the real import
538 $import_plugin->doImport($sql_data);
542 if (false !== $import_handle && null !== $import_handle) {
543 fclose($import_handle);
546 // Cleanup temporary file
547 if ($file_to_unlink != '') {
548 unlink($file_to_unlink);
551 // Reset charset back, if we did some changes
552 if ($reset_charset) {
553 $GLOBALS['dbi']->query('SET CHARACTER SET utf8');
554 $GLOBALS['dbi']->query(
555 'SET SESSION collation_connection =\'' . $collation_connection . '\''
559 // Show correct message
560 if (! empty($id_bookmark) && $action_bookmark == 2) {
561 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
562 $display_query = $import_text;
563 $error = false; // unset error marker, it was used just to skip processing
564 } elseif (! empty($id_bookmark) && $action_bookmark == 1) {
565 $message = PMA_Message
::notice(__('Showing bookmark'));
566 } elseif ($bookmark_created) {
567 $special_message = '[br]' . sprintf(
568 __('Bookmark %s has been created.'),
569 htmlspecialchars($bkm_label)
571 } elseif ($finished && ! $error) {
572 if ($import_type == 'query') {
573 $message = PMA_Message
::success();
575 $message = PMA_Message
::success(
577 . __('Import has been successfully finished, %d queries executed.')
580 $message->addParam($executed_queries);
582 if ($import_notice) {
583 $message->addString($import_notice);
585 if (isset($local_import_file)) {
586 $message->addString('(' . htmlspecialchars($local_import_file) . ')');
589 '(' . htmlspecialchars($_FILES['import_file']['name']) . ')'
595 // Did we hit timeout? Tell it user.
596 if ($timeout_passed) {
597 $message = PMA_Message
::error(
598 __('Script timeout passed, if you want to finish import, please resubmit same file and import will resume.')
600 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
602 __('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.')
607 // if there is any message, copy it into $_SESSION as well,
608 // so we can obtain it by AJAX call
609 if (isset($message)) {
610 $_SESSION['Import_message']['message'] = $message->getDisplay();
612 // Parse and analyze the query, for correct db and table name
613 // in case of a query typed in the query window
614 // (but if the query is too large, in case of an imported file, the parser
615 // can choke on it so avoid parsing)
616 if (strlen($sql_query) <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
617 include_once 'libraries/parse_analyze.inc.php';
620 // There was an error?
621 if (isset($my_die)) {
622 foreach ($my_die as $key => $die) {
624 $die['error'], $die['sql'], false, $err_url, $error
631 include_once 'libraries/parse_analyze.inc.php';
633 if (isset($ajax_reload) && $ajax_reload['reload'] === true) {
634 $response = PMA_Response
::getInstance();
635 $response->addJSON('ajax_reload', $ajax_reload);
637 PMA_executeQueryAndSendQueryResponse(
638 $analyzed_sql_results, false, $db, $table, null, $import_text, null,
639 $analyzed_sql_results['is_affected'], null,
640 null, null, null, $goto, $pmaThemeImage, null, null, null, $sql_query,
643 } else if ($result) {
644 // Save a Bookmark with more than one queries (if Bookmark label given).
645 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
646 PMA_storeTheQueryAsBookmark(
647 $db, $GLOBALS['cfg']['Bookmark']['user'],
648 $import_text, $_POST['bkm_label'],
649 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
653 $response = PMA_Response
::getInstance();
654 $response->isSuccess(true);
655 $response->addJSON('message', PMA_Message
::success($msg));
658 PMA_Util
::getMessage($msg, $sql_query, 'success')
660 } else if ($result == false) {
661 $response = PMA_Response
::getInstance();
662 $response->isSuccess(false);
663 $response->addJSON('message', PMA_Message
::error($msg));
665 $active_page = $goto;