Translated using Weblate (Turkish)
[phpmyadmin.git] / import.php
blob56a584aa11985c81239501e1e1a626ca8c7683a8
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Core script for import, this is just the glue around all other stuff
6 * @package PhpMyAdmin
7 */
9 /**
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'];
21 /**
22 * Sets globals from $_POST
24 $post_params = array(
25 'action_bookmark',
26 'allow_interrupt',
27 'bkm_label',
28 'bookmark_variable',
29 'charset_of_file',
30 'format',
31 'id_bookmark',
32 'import_type',
33 'is_js_confirmed',
34 'MAX_FILE_SIZE',
35 'message_to_show',
36 'noplugin',
37 'skip_queries',
38 'local_import_file'
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;
51 // default values
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)) {
63 // run SQL query
64 $import_text = $sql_query;
65 $import_type = 'query';
66 $format = 'sql';
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
74 if (preg_match(
75 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
76 $sql_query
77 )) {
78 $ajax_reload['reload'] = true;
81 // do a dynamic reload if table is RENAMED
82 // (by sending the instruction to the AJAX response handler)
83 if (preg_match(
84 '/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i',
85 $sql_query,
86 $rename_table_names
87 )) {
88 $ajax_reload['table_name'] = PMA_Util::unQuote($rename_table_names[2]);
89 $ajax_reload['reload'] = true;
92 $sql_query = '';
93 } elseif (! empty($sql_localfile)) {
94 // run SQL file on server
95 $local_import_file = $sql_localfile;
96 $import_type = 'queryfile';
97 $format = 'sql';
98 unset($sql_localfile);
99 } elseif (! empty($sql_file)) {
100 // run uploaded SQL file
101 $import_file = $sql_file;
102 $import_type = 'queryfile';
103 $format = 'sql';
104 unset($sql_file);
105 } elseif (! empty($id_bookmark)) {
106 // run bookmark
107 $import_type = 'query';
108 $format = 'sql';
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;
125 $message->display();
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
134 if (! in_array(
135 $format,
136 array(
137 'csv',
138 'ldi',
139 'mediawiki',
140 'ods',
141 'shp',
142 'sql',
143 'xml'
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(
153 '/^force_file_/',
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);
170 // Import functions
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';
186 } else {
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';
192 } else {
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);
200 } else {
201 $common = PMA_URL_getCommon();
203 $err_url = $goto . '?' . $common
204 . (preg_match('@^tbl_[a-z]*\.php$@', $goto)
205 ? '&amp;table=' . htmlspecialchars($table)
206 : '');
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;
216 if (strlen($db)) {
217 $GLOBALS['dbi']->selectDb($db);
220 @set_time_limit($cfg['ExecTimeLimit']);
221 if (! empty($cfg['MemoryLimit'])) {
222 @ini_set('memory_limit', $cfg['MemoryLimit']);
225 $timestamp = time();
226 if (isset($allow_interrupt)) {
227 $maximum_time = ini_get('max_execution_time');
228 } else {
229 $maximum_time = 0;
232 // set default values
233 $timeout_passed = false;
234 $error = false;
235 $read_multiply = 1;
236 $finished = false;
237 $offset = 0;
238 $max_sql_len = 0;
239 $file_to_unlink = '';
240 $sql_query = '';
241 $sql_query_disabled = false;
242 $go_sql = false;
243 $executed_queries = 0;
244 $run_query = true;
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(
256 $db,
257 $id_bookmark,
258 'id',
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}',
265 $import_text
269 // refresh navigation and main panels
270 if (preg_match(
271 '/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
272 $import_text
273 )) {
274 $GLOBALS['reload'] = true;
277 // refresh navigation panel only
278 if (preg_match(
279 '/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
280 $import_text
283 $ajax_reload['reload'] = true;
285 break;
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);
295 exit;
296 } else {
297 $run_query = false;
299 break;
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);
310 exit;
311 } else {
312 $run_query = false;
313 $error = true; // this is kind of hack to skip processing the query
315 break;
317 } // end bookmarks reading
319 // Do no run query if we show PHP code
320 if (isset($GLOBALS['show_as_php'])) {
321 $run_query = false;
322 $go_sql = true;
325 // We can not read all at once, otherwise we can run out of memory
326 $memory_limit = trim(@ini_get('memory_limit'));
327 // 2 MB as default
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;
343 } else {
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;
350 // handle filenames
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
379 * system's tmp dir
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);
395 } else {
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
401 // instead.
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);
419 } else {
420 switch ($compression) {
421 case 'application/bzip2':
422 if ($cfg['BZipDump'] && @function_exists('bzopen')) {
423 $import_handle = @bzopen($import_file, 'r');
424 } else {
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);
431 break;
432 case 'application/gzip':
433 if ($cfg['GZipDump'] && @function_exists('gzopen')) {
434 $import_handle = @gzopen($import_file, 'r');
435 } else {
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);
442 break;
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);
453 } else {
454 $import_text = $zipResult['data'];
456 } else {
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);
463 break;
464 case 'none':
465 $import_handle = @fopen($import_file, 'r');
466 break;
467 default:
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);
473 break;
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') {
499 if (PMA_DRIZZLE) {
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);
506 } else {
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;
517 while ($skip > 0) {
518 PMA_importGetNextChunk($skip < $read_limit ? $skip : $read_limit);
519 // Disable read progressivity, otherwise we eat all memory!
520 $read_multiply = 1;
521 $skip -= $read_limit;
523 unset($skip);
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);
530 if (! $error) {
531 // Check for file existance
532 include_once "libraries/plugin_interface.lib.php";
533 $import_plugin = PMA_getPlugin(
534 "import",
535 $format,
536 'libraries/plugins/import/',
537 $import_type
539 if ($import_plugin == null) {
540 $message = PMA_Message::error(
541 __('Could not load import plugins, please check your installation!')
543 PMA_stopImport($message);
544 } else {
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();
582 } else {
583 $message = PMA_Message::success(
584 '<em>'
585 . __('Import has been successfully finished, %d queries executed.')
586 . '</em>'
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) . ')');
595 } else {
596 $message->addString(
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)) {
609 $message->addString(
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) {
631 PMA_Util::mysqlDie(
632 $die['error'], $die['sql'], false, $err_url, $error
637 if ($go_sql) {
638 // parse sql query
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,
649 null, null
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));
664 $response->addJSON(
665 'sql_query',
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));
672 } else {
673 $active_page = $goto;
674 include '' . $goto;