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;
209 // Avoid setting selflink to 'import.php'
210 // problem similar to bug 4276
211 if (basename($_SERVER['SCRIPT_NAME']) === 'import.php') {
212 $_SERVER['SCRIPT_NAME'] = $goto;
217 $GLOBALS['dbi']->selectDb($db);
220 @set_time_limit
($cfg['ExecTimeLimit']);
221 if (! empty($cfg['MemoryLimit'])) {
222 @ini_set
('memory_limit', $cfg['MemoryLimit']);
226 if (isset($allow_interrupt)) {
227 $maximum_time = ini_get('max_execution_time');
232 // set default values
233 $timeout_passed = false;
239 $file_to_unlink = '';
241 $sql_query_disabled = false;
243 $executed_queries = 0;
245 $charset_conversion = false;
246 $reset_charset = false;
247 $bookmark_created = false;
249 // Bookmark Support: get a query back from bookmark if required
250 if (! empty($id_bookmark)) {
251 $id_bookmark = (int)$id_bookmark;
252 include_once 'libraries/bookmark.lib.php';
253 switch ($action_bookmark) {
254 case 0: // bookmarked query that have to be run
255 $import_text = PMA_Bookmark_get(
259 isset($action_bookmark_all)
261 if (isset($bookmark_variable) && ! empty($bookmark_variable)) {
262 $import_text = preg_replace(
263 '|/\*(.*)\[VARIABLE\](.*)\*/|imsU',
264 '${1}' . PMA_Util
::sqlAddSlashes($bookmark_variable) . '${2}',
269 // refresh navigation and main panels
271 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
274 $GLOBALS['reload'] = true;
277 // refresh navigation panel only
279 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
283 $ajax_reload['reload'] = true;
286 case 1: // bookmarked query that have to be displayed
287 $import_text = PMA_Bookmark_get($db, $id_bookmark);
288 if ($GLOBALS['is_ajax_request'] == true) {
289 $message = PMA_Message
::success(__('Showing bookmark'));
290 $response = PMA_Response
::getInstance();
291 $response->isSuccess($message->isSuccess());
292 $response->addJSON('message', $message);
293 $response->addJSON('sql_query', $import_text);
294 $response->addJSON('action_bookmark', $action_bookmark);
300 case 2: // bookmarked query that have to be deleted
301 $import_text = PMA_Bookmark_get($db, $id_bookmark);
302 PMA_Bookmark_delete($id_bookmark);
303 if ($GLOBALS['is_ajax_request'] == true) {
304 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
305 $response = PMA_Response
::getInstance();
306 $response->isSuccess($message->isSuccess());
307 $response->addJSON('message', $message);
308 $response->addJSON('action_bookmark', $action_bookmark);
309 $response->addJSON('id_bookmark', $id_bookmark);
313 $error = true; // this is kind of hack to skip processing the query
317 } // end bookmarks reading
319 // Do no run query if we show PHP code
320 if (isset($GLOBALS['show_as_php'])) {
325 // We can not read all at once, otherwise we can run out of memory
326 $memory_limit = trim(@ini_get
('memory_limit'));
328 if (empty($memory_limit)) {
329 $memory_limit = 2 * 1024 * 1024;
331 // In case no memory limit we work on 10MB chunks
332 if ($memory_limit == -1) {
333 $memory_limit = 10 * 1024 * 1024;
336 // Calculate value of the limit
337 if (strtolower(substr($memory_limit, -1)) == 'm') {
338 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
339 } elseif (strtolower(substr($memory_limit, -1)) == 'k') {
340 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
341 } elseif (strtolower(substr($memory_limit, -1)) == 'g') {
342 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
344 $memory_limit = (int)$memory_limit;
347 // Just to be sure, there might be lot of memory needed for uncompression
348 $read_limit = $memory_limit / 8;
351 if (isset($_FILES['import_file'])) {
352 $import_file = $_FILES['import_file']['tmp_name'];
354 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
356 // sanitize $local_import_file as it comes from a POST
357 $local_import_file = PMA_securePath($local_import_file);
359 $import_file = PMA_Util
::userDir($cfg['UploadDir'])
360 . $local_import_file;
362 } elseif (empty($import_file) ||
! is_uploaded_file($import_file)) {
363 $import_file = 'none';
366 // Do we have file to import?
368 if ($import_file != 'none' && ! $error) {
369 // work around open_basedir and other limitations
370 $open_basedir = @ini_get
('open_basedir');
372 // If we are on a server with open_basedir, we must move the file
373 // before opening it.
375 if (! empty($open_basedir)) {
378 * @todo make use of the config's temp dir with fallback to the
381 $tmp_subdir = ini_get('upload_tmp_dir');
382 if (empty($tmp_subdir)) {
383 $tmp_subdir = sys_get_temp_dir();
386 if (is_writable($tmp_subdir)) {
388 $import_file_new = $tmp_subdir . basename($import_file) . uniqid();
389 if (move_uploaded_file($import_file, $import_file_new)) {
390 $import_file = $import_file_new;
391 $file_to_unlink = $import_file_new;
394 $size = filesize($import_file);
397 // If the php.ini is misconfigured (eg. there is no /tmp access defined
398 // with open_basedir), $tmp_subdir won't be writable and the user gets
399 // a 'File could not be read!' error (at PMA_detectCompression), which
400 // is not too meaningful. Show a meaningful error message to the user
403 $message = PMA_Message
::error(
404 __('Uploaded file cannot be moved, because the server has open_basedir enabled without access to the %s directory (for temporary files).')
406 $message->addParam($tmp_subdir);
407 PMA_stopImport($message);
412 * Handle file compression
413 * @todo duplicate code exists in File.class.php
415 $compression = PMA_detectCompression($import_file);
416 if ($compression === false) {
417 $message = PMA_Message
::error(__('File could not be read!'));
418 PMA_stopImport($message);
420 switch ($compression) {
421 case 'application/bzip2':
422 if ($cfg['BZipDump'] && @function_exists
('bzopen')) {
423 $import_handle = @bzopen
($import_file, 'r');
425 $message = PMA_Message
::error(
426 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
428 $message->addParam($compression);
429 PMA_stopImport($message);
432 case 'application/gzip':
433 if ($cfg['GZipDump'] && @function_exists
('gzopen')) {
434 $import_handle = @gzopen
($import_file, 'r');
436 $message = PMA_Message
::error(
437 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
439 $message->addParam($compression);
440 PMA_stopImport($message);
443 case 'application/zip':
444 if ($cfg['ZipDump'] && @function_exists
('zip_open')) {
446 * Load interface for zip extension.
448 include_once 'libraries/zip_extension.lib.php';
449 $zipResult = PMA_getZipContents($import_file);
450 if (! empty($zipResult['error'])) {
451 $message = PMA_Message
::rawError($zipResult['error']);
452 PMA_stopImport($message);
454 $import_text = $zipResult['data'];
457 $message = PMA_Message
::error(
458 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
460 $message->addParam($compression);
461 PMA_stopImport($message);
465 $import_handle = @fopen
($import_file, 'r');
468 $message = PMA_Message
::error(
469 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
471 $message->addParam($compression);
472 PMA_stopImport($message);
476 // use isset() because zip compression type does not use a handle
477 if (! $error && isset($import_handle) && $import_handle === false) {
478 $message = PMA_Message
::error(__('File could not be read!'));
479 PMA_stopImport($message);
481 } elseif (! $error) {
482 if (! isset($import_text) ||
empty($import_text)) {
483 $message = PMA_Message
::error(
484 __('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].')
486 PMA_stopImport($message);
490 // so we can obtain the message
491 //$_SESSION['Import_message'] = $message->getDisplay();
493 // Convert the file's charset if necessary
494 if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE
&& isset($charset_of_file)) {
495 if ($charset_of_file != 'utf-8') {
496 $charset_conversion = true;
498 } elseif (isset($charset_of_file) && $charset_of_file != 'utf8') {
500 // Drizzle doesn't support other character sets,
501 // so we can't fallback to SET NAMES - throw an error
502 $message = PMA_Message
::error(
503 __('Cannot convert file\'s character set without character set conversion library!')
505 PMA_stopImport($message);
507 $GLOBALS['dbi']->query('SET NAMES \'' . $charset_of_file . '\'');
508 // We can not show query in this case, it is in different charset
509 $sql_query_disabled = true;
510 $reset_charset = true;
514 // Something to skip?
515 if (! $error && isset($skip)) {
516 $original_skip = $skip;
518 PMA_importGetNextChunk($skip < $read_limit ?
$skip : $read_limit);
519 // Disable read progressivity, otherwise we eat all memory!
521 $skip -= $read_limit;
526 // This array contain the data like numberof valid sql queries in the statement
527 // and complete valid sql statement (which affected for rows)
528 $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
531 // Check for file existance
532 include_once "libraries/plugin_interface.lib.php";
533 $import_plugin = PMA_getPlugin(
536 'libraries/plugins/import/',
539 if ($import_plugin == null) {
540 $message = PMA_Message
::error(
541 __('Could not load import plugins, please check your installation!')
543 PMA_stopImport($message);
545 // Do the real import
546 $import_plugin->doImport($sql_data);
550 if (false !== $import_handle && null !== $import_handle) {
551 fclose($import_handle);
554 // Cleanup temporary file
555 if ($file_to_unlink != '') {
556 unlink($file_to_unlink);
559 // Reset charset back, if we did some changes
560 if ($reset_charset) {
561 $GLOBALS['dbi']->query('SET CHARACTER SET utf8');
562 $GLOBALS['dbi']->query(
563 'SET SESSION collation_connection =\'' . $collation_connection . '\''
567 // Show correct message
568 if (! empty($id_bookmark) && $action_bookmark == 2) {
569 $message = PMA_Message
::success(__('The bookmark has been deleted.'));
570 $display_query = $import_text;
571 $error = false; // unset error marker, it was used just to skip processing
572 } elseif (! empty($id_bookmark) && $action_bookmark == 1) {
573 $message = PMA_Message
::notice(__('Showing bookmark'));
574 } elseif ($bookmark_created) {
575 $special_message = '[br]' . sprintf(
576 __('Bookmark %s has been created.'),
577 htmlspecialchars($bkm_label)
579 } elseif ($finished && ! $error) {
580 if ($import_type == 'query') {
581 $message = PMA_Message
::success();
583 $message = PMA_Message
::success(
585 . __('Import has been successfully finished, %d queries executed.')
588 $message->addParam($executed_queries);
590 if ($import_notice) {
591 $message->addString($import_notice);
593 if (isset($local_import_file)) {
594 $message->addString('(' . htmlspecialchars($local_import_file) . ')');
597 '(' . htmlspecialchars($_FILES['import_file']['name']) . ')'
603 // Did we hit timeout? Tell it user.
604 if ($timeout_passed) {
605 $message = PMA_Message
::error(
606 __('Script timeout passed, if you want to finish import, please resubmit same file and import will resume.')
608 if ($offset == 0 ||
(isset($original_skip) && $original_skip == $offset)) {
610 __('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.')
615 // if there is any message, copy it into $_SESSION as well,
616 // so we can obtain it by AJAX call
617 if (isset($message)) {
618 $_SESSION['Import_message']['message'] = $message->getDisplay();
620 // Parse and analyze the query, for correct db and table name
621 // in case of a query typed in the query window
622 // (but if the query is too large, in case of an imported file, the parser
623 // can choke on it so avoid parsing)
624 if (strlen($sql_query) <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
625 include_once 'libraries/parse_analyze.inc.php';
628 // There was an error?
629 if (isset($my_die)) {
630 foreach ($my_die as $key => $die) {
632 $die['error'], $die['sql'], false, $err_url, $error
639 include_once 'libraries/parse_analyze.inc.php';
641 if (isset($ajax_reload) && $ajax_reload['reload'] === true) {
642 $response = PMA_Response
::getInstance();
643 $response->addJSON('ajax_reload', $ajax_reload);
645 PMA_executeQueryAndSendQueryResponse(
646 $analyzed_sql_results, false, $db, $table, null, $import_text, null,
647 $analyzed_sql_results['is_affected'], null,
648 null, null, null, $goto, $pmaThemeImage, null, null, null, $sql_query,
651 } else if ($result) {
652 // Save a Bookmark with more than one queries (if Bookmark label given).
653 if (! empty($_POST['bkm_label']) && ! empty($import_text)) {
654 PMA_storeTheQueryAsBookmark(
655 $db, $GLOBALS['cfg']['Bookmark']['user'],
656 $import_text, $_POST['bkm_label'],
657 isset($_POST['bkm_replace']) ?
$_POST['bkm_replace'] : null
661 $response = PMA_Response
::getInstance();
662 $response->isSuccess(true);
663 $response->addJSON('message', PMA_Message
::success($msg));
666 PMA_Util
::getMessage($msg, $sql_query, 'success')
668 } else if ($result == false) {
669 $response = PMA_Response
::getInstance();
670 $response->isSuccess(false);
671 $response->addJSON('message', PMA_Message
::error($msg));
673 $active_page = $goto;