Translated using Weblate.
[phpmyadmin.git] / import.php
blobdfdfdc6dc134fcfa2c2d222808ca28f2ca35e7aa
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/display_import_functions.lib.php';
15 if (isset($_REQUEST['show_as_php'])) {
16 $GLOBALS['show_as_php'] = $_REQUEST['show_as_php'];
19 // reset import messages for ajax request
20 $_SESSION['Import_message']['message'] = null;
21 $_SESSION['Import_message']['go_back_url'] = null;
22 // default values
23 $GLOBALS['reload'] = false;
25 // Are we just executing plain query or sql file? (eg. non import, but query box/window run)
26 if (!empty($sql_query)) {
27 // run SQL query
28 $import_text = $sql_query;
29 $import_type = 'query';
30 $format = 'sql';
32 // refresh left frame on changes in table or db structure
33 if (preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
34 $GLOBALS['reload'] = true;
37 $sql_query = '';
38 } elseif (!empty($sql_localfile)) {
39 // run SQL file on server
40 $local_import_file = $sql_localfile;
41 $import_type = 'queryfile';
42 $format = 'sql';
43 unset($sql_localfile);
44 } elseif (!empty($sql_file)) {
45 // run uploaded SQL file
46 $import_file = $sql_file;
47 $import_type = 'queryfile';
48 $format = 'sql';
49 unset($sql_file);
50 } elseif (!empty($id_bookmark)) {
51 // run bookmark
52 $import_type = 'query';
53 $format = 'sql';
56 // If we didn't get any parameters, either user called this directly, or
57 // upload limit has been reached, let's assume the second possibility.
59 if ($_POST == array() && $_GET == array()) {
60 include_once './libraries/header.inc.php';
61 $message = PMA_Message::error(__('You probably tried to upload too large file. Please refer to %sdocumentation%s for ways to workaround this limit.'));
62 $message->addParam('[a@./Documentation.html#faq1_16@_blank]');
63 $message->addParam('[/a]');
65 // so we can obtain the message
66 $_SESSION['Import_message']['message'] = $message->getDisplay();
67 $_SESSION['Import_message']['go_back_url'] = $goto;
69 $message->display();
70 include './libraries/footer.inc.php';
73 // Check needed parameters
74 PMA_checkParameters(array('import_type', 'format'));
76 // We don't want anything special in format
77 $format = PMA_securePath($format);
79 // Import functions
80 require_once './libraries/import.lib.php';
82 // Create error and goto url
83 if ($import_type == 'table') {
84 $err_url = 'tbl_import.php?' . PMA_generate_common_url($db, $table);
85 $_SESSION['Import_message']['go_back_url'] = $err_url;
86 $goto = 'tbl_import.php';
87 } elseif ($import_type == 'database') {
88 $err_url = 'db_import.php?' . PMA_generate_common_url($db);
89 $_SESSION['Import_message']['go_back_url'] = $err_url;
90 $goto = 'db_import.php';
91 } elseif ($import_type == 'server') {
92 $err_url = 'server_import.php?' . PMA_generate_common_url();
93 $_SESSION['Import_message']['go_back_url'] = $err_url;
94 $goto = 'server_import.php';
95 } else {
96 if (empty($goto) || !preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
97 if (strlen($table) && strlen($db)) {
98 $goto = 'tbl_structure.php';
99 } elseif (strlen($db)) {
100 $goto = 'db_structure.php';
101 } else {
102 $goto = 'server_sql.php';
105 if (strlen($table) && strlen($db)) {
106 $common = PMA_generate_common_url($db, $table);
107 } elseif (strlen($db)) {
108 $common = PMA_generate_common_url($db);
109 } else {
110 $common = PMA_generate_common_url();
112 $err_url = $goto
113 . '?' . $common
114 . (preg_match('@^tbl_[a-z]*\.php$@', $goto) ? '&amp;table=' . htmlspecialchars($table) : '');
115 $_SESSION['Import_message']['go_back_url'] = $err_url;
119 if (strlen($db)) {
120 PMA_DBI_select_db($db);
123 @set_time_limit($cfg['ExecTimeLimit']);
124 if (!empty($cfg['MemoryLimit'])) {
125 @ini_set('memory_limit', $cfg['MemoryLimit']);
128 $timestamp = time();
129 if (isset($allow_interrupt)) {
130 $maximum_time = ini_get('max_execution_time');
131 } else {
132 $maximum_time = 0;
135 // set default values
136 $timeout_passed = false;
137 $error = false;
138 $read_multiply = 1;
139 $finished = false;
140 $offset = 0;
141 $max_sql_len = 0;
142 $file_to_unlink = '';
143 $sql_query = '';
144 $sql_query_disabled = false;
145 $go_sql = false;
146 $executed_queries = 0;
147 $run_query = true;
148 $charset_conversion = false;
149 $reset_charset = false;
150 $bookmark_created = false;
152 // Bookmark Support: get a query back from bookmark if required
153 if (!empty($id_bookmark)) {
154 $id_bookmark = (int)$id_bookmark;
155 include_once './libraries/bookmark.lib.php';
156 switch ($action_bookmark) {
157 case 0: // bookmarked query that have to be run
158 $import_text = PMA_Bookmark_get($db, $id_bookmark, 'id', isset($action_bookmark_all));
159 if (isset($bookmark_variable) && !empty($bookmark_variable)) {
160 $import_text = preg_replace('|/\*(.*)\[VARIABLE\](.*)\*/|imsU', '${1}' . PMA_sqlAddSlashes($bookmark_variable) . '${2}', $import_text);
163 // refresh left frame on changes in table or db structure
164 if (preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $import_text)) {
165 $GLOBALS['reload'] = true;
168 break;
169 case 1: // bookmarked query that have to be displayed
170 $import_text = PMA_Bookmark_get($db, $id_bookmark);
171 if ($GLOBALS['is_ajax_request'] == true) {
172 $extra_data['sql_query'] = $import_text;
173 $extra_data['action_bookmark'] = $action_bookmark;
174 $message = PMA_Message::success(__('Showing bookmark'));
175 PMA_ajaxResponse($message, $message->isSuccess(), $extra_data);
176 } else {
177 $run_query = false;
179 break;
180 case 2: // bookmarked query that have to be deleted
181 $import_text = PMA_Bookmark_get($db, $id_bookmark);
182 PMA_Bookmark_delete($db, $id_bookmark);
183 if ($GLOBALS['is_ajax_request'] == true) {
184 $message = PMA_Message::success(__('The bookmark has been deleted.'));
185 $extra_data['action_bookmark'] = $action_bookmark;
186 $extra_data['id_bookmark'] = $id_bookmark;
187 PMA_ajaxResponse($message, $message->isSuccess(), $extra_data);
188 } else {
189 $run_query = false;
190 $error = true; // this is kind of hack to skip processing the query
192 break;
194 } // end bookmarks reading
196 // Do no run query if we show PHP code
197 if (isset($GLOBALS['show_as_php'])) {
198 $run_query = false;
199 $go_sql = true;
202 // Store the query as a bookmark before executing it if bookmarklabel was given
203 if (!empty($bkm_label) && !empty($import_text)) {
204 include_once './libraries/bookmark.lib.php';
205 $bfields = array(
206 'dbase' => $db,
207 'user' => $cfg['Bookmark']['user'],
208 'query' => urlencode($import_text),
209 'label' => $bkm_label
212 // Should we replace bookmark?
213 if (isset($bkm_replace)) {
214 $bookmarks = PMA_Bookmark_getList($db);
215 foreach ($bookmarks as $key => $val) {
216 if ($val == $bkm_label) {
217 PMA_Bookmark_delete($db, $key);
222 PMA_Bookmark_save($bfields, isset($bkm_all_users));
224 $bookmark_created = true;
225 } // end store bookmarks
227 // We can not read all at once, otherwise we can run out of memory
228 $memory_limit = trim(@ini_get('memory_limit'));
229 // 2 MB as default
230 if (empty($memory_limit)) {
231 $memory_limit = 2 * 1024 * 1024;
233 // In case no memory limit we work on 10MB chunks
234 if ($memory_limit == -1) {
235 $memory_limit = 10 * 1024 * 1024;
238 // Calculate value of the limit
239 if (strtolower(substr($memory_limit, -1)) == 'm') {
240 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
241 } elseif (strtolower(substr($memory_limit, -1)) == 'k') {
242 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
243 } elseif (strtolower(substr($memory_limit, -1)) == 'g') {
244 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
245 } else {
246 $memory_limit = (int)$memory_limit;
249 $read_limit = $memory_limit / 8; // Just to be sure, there might be lot of memory needed for uncompression
251 // handle filenames
252 if (isset($_FILES['import_file'])) {
253 $import_file = $_FILES['import_file']['tmp_name'];
255 if (!empty($local_import_file) && !empty($cfg['UploadDir'])) {
257 // sanitize $local_import_file as it comes from a POST
258 $local_import_file = PMA_securePath($local_import_file);
260 $import_file = PMA_userDir($cfg['UploadDir']) . $local_import_file;
261 } elseif (empty($import_file) || !is_uploaded_file($import_file)) {
262 $import_file = 'none';
265 // Do we have file to import?
267 if ($import_file != 'none' && !$error) {
268 // work around open_basedir and other limitations
269 $open_basedir = @ini_get('open_basedir');
271 // If we are on a server with open_basedir, we must move the file
272 // before opening it. The doc explains how to create the "./tmp"
273 // directory
275 if (!empty($open_basedir)) {
277 $tmp_subdir = (PMA_IS_WINDOWS ? '.\\tmp\\' : './tmp/');
279 if (is_writable($tmp_subdir)) {
282 $import_file_new = $tmp_subdir . basename($import_file) . uniqid();
283 if (move_uploaded_file($import_file, $import_file_new)) {
284 $import_file = $import_file_new;
285 $file_to_unlink = $import_file_new;
288 $size = filesize($import_file);
293 * Handle file compression
294 * @todo duplicate code exists in File.class.php
296 $compression = PMA_detectCompression($import_file);
297 if ($compression === false) {
298 $message = PMA_Message::error(__('File could not be read'));
299 $error = true;
300 } else {
301 switch ($compression) {
302 case 'application/bzip2':
303 if ($cfg['BZipDump'] && @function_exists('bzopen')) {
304 $import_handle = @bzopen($import_file, 'r');
305 } else {
306 $message = PMA_Message::error(__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.'));
307 $message->addParam($compression);
308 $error = true;
310 break;
311 case 'application/gzip':
312 if ($cfg['GZipDump'] && @function_exists('gzopen')) {
313 $import_handle = @gzopen($import_file, 'r');
314 } else {
315 $message = PMA_Message::error(__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.'));
316 $message->addParam($compression);
317 $error = true;
319 break;
320 case 'application/zip':
321 if ($cfg['ZipDump'] && @function_exists('zip_open')) {
323 * Load interface for zip extension.
325 include_once './libraries/zip_extension.lib.php';
326 $result = PMA_getZipContents($import_file);
327 if (! empty($result['error'])) {
328 $message = PMA_Message::rawError($result['error']);
329 $error = true;
330 } else {
331 $import_text = $result['data'];
333 } else {
334 $message = PMA_Message::error(__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.'));
335 $message->addParam($compression);
336 $error = true;
338 break;
339 case 'none':
340 $import_handle = @fopen($import_file, 'r');
341 break;
342 default:
343 $message = PMA_Message::error(__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.'));
344 $message->addParam($compression);
345 $error = true;
346 break;
349 // use isset() because zip compression type does not use a handle
350 if (!$error && isset($import_handle) && $import_handle === false) {
351 $message = PMA_Message::error(__('File could not be read'));
352 $error = true;
354 } elseif (!$error) {
355 if (! isset($import_text) || empty($import_text)) {
356 $message = PMA_Message::error(__('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 [a@./Documentation.html#faq1_16@Documentation]FAQ 1.16[/a].'));
357 $error = true;
361 // so we can obtain the message
362 //$_SESSION['Import_message'] = $message->getDisplay();
364 // Convert the file's charset if necessary
365 if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE && isset($charset_of_file)) {
366 if ($charset_of_file != 'utf-8') {
367 $charset_conversion = true;
369 } elseif (isset($charset_of_file) && $charset_of_file != 'utf8') {
370 if (PMA_DRIZZLE) {
371 // Drizzle doesn't support other character sets, so we can't fallback to SET NAMES - throw an error
372 $error = true;
373 $message = PMA_Message::error(__('Cannot convert file\'s character set without character set conversion library'));
374 } else {
375 PMA_DBI_query('SET NAMES \'' . $charset_of_file . '\'');
376 // We can not show query in this case, it is in different charset
377 $sql_query_disabled = true;
378 $reset_charset = true;
382 // Something to skip?
383 if (!$error && isset($skip)) {
384 $original_skip = $skip;
385 while ($skip > 0) {
386 PMA_importGetNextChunk($skip < $read_limit ? $skip : $read_limit);
387 $read_multiply = 1; // Disable read progresivity, otherwise we eat all memory!
388 $skip -= $read_limit;
390 unset($skip);
393 if (!$error) {
394 // Check for file existance
395 if (!file_exists('./libraries/import/' . $format . '.php')) {
396 $error = true;
397 $message = PMA_Message::error(__('Could not load import plugins, please check your installation!'));
398 } else {
399 // Do the real import
400 $plugin_param = $import_type;
401 include './libraries/import/' . $format . '.php';
405 if (! $error && false !== $import_handle && null !== $import_handle) {
406 fclose($import_handle);
409 // Cleanup temporary file
410 if ($file_to_unlink != '') {
411 unlink($file_to_unlink);
414 // Reset charset back, if we did some changes
415 if ($reset_charset) {
416 PMA_DBI_query('SET CHARACTER SET utf8');
417 PMA_DBI_query('SET SESSION collation_connection =\'' . $collation_connection . '\'');
420 // Show correct message
421 if (!empty($id_bookmark) && $action_bookmark == 2) {
422 $message = PMA_Message::success(__('The bookmark has been deleted.'));
423 $display_query = $import_text;
424 $error = false; // unset error marker, it was used just to skip processing
425 } elseif (!empty($id_bookmark) && $action_bookmark == 1) {
426 $message = PMA_Message::notice(__('Showing bookmark'));
427 } elseif ($bookmark_created) {
428 $special_message = '[br]' . sprintf(__('Bookmark %s created'), htmlspecialchars($bkm_label));
429 } elseif ($finished && !$error) {
430 if ($import_type == 'query') {
431 $message = PMA_Message::success();
432 } else {
433 if ($import_notice) {
434 $message = PMA_Message::success('<em>'.__('Import has been successfully finished, %d queries executed.').'</em>');
435 $message->addParam($executed_queries);
437 $message->addString($import_notice);
438 $message->addString('(' . $_FILES['import_file']['name'] . ')');
439 } else {
440 $message = PMA_Message::success(__('Import has been successfully finished, %d queries executed.'));
441 $message->addParam($executed_queries);
442 $message->addString('(' . $_FILES['import_file']['name'] . ')');
447 // Did we hit timeout? Tell it user.
448 if ($timeout_passed) {
449 $message = PMA_Message::error(__('Script timeout passed, if you want to finish import, please resubmit same file and import will resume.'));
450 if ($offset == 0 || (isset($original_skip) && $original_skip == $offset)) {
451 $message->addString(__('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.'));
455 // if there is any message, copy it into $_SESSION as well, so we can obtain it by AJAX call
456 if (isset($message)) {
457 $_SESSION['Import_message']['message'] = $message->getDisplay();
458 // $_SESSION['Import_message']['go_back_url'] = $goto.'?'. PMA_generate_common_url();
460 // Parse and analyze the query, for correct db and table name
461 // in case of a query typed in the query window
462 // (but if the query is too large, in case of an imported file, the parser
463 // can choke on it so avoid parsing)
464 if (strlen($sql_query) <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
465 include_once './libraries/parse_analyze.lib.php';
468 // There was an error?
469 if (isset($my_die)) {
470 foreach ($my_die AS $key => $die) {
471 PMA_mysqlDie($die['error'], $die['sql'], '', $err_url, $error);
475 // we want to see the results of the last query that returned at least a row
476 if (! empty($last_query_with_results)) {
477 // but we want to show intermediate results too
478 $disp_query = $sql_query;
479 $disp_message = __('Your SQL query has been executed successfully');
480 $sql_query = $last_query_with_results;
481 $go_sql = true;
484 if ($go_sql) {
485 include './sql.php';
486 } else {
487 $active_page = $goto;
488 include './' . $goto;
490 exit();