Upgraded phpmyadmin to 4.0.4 (All Languages) - No modifications yet
[openemr.git] / phpmyadmin / import.php
blob9d193ae63d511d4f9fe09695ae8ef0389cb3cf3a
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 /**
20 * Sets globals from $_POST
22 $post_params = array(
23 'action_bookmark',
24 'allow_interrupt',
25 'bkm_label',
26 'bookmark_variable',
27 'charset_of_file',
28 'format',
29 'id_bookmark',
30 'import_type',
31 'is_js_confirmed',
32 'MAX_FILE_SIZE',
33 'message_to_show',
34 'noplugin',
35 'skip_queries',
36 'local_import_file'
39 // TODO: adapt full list of allowed parameters, as in export.php
40 foreach ($post_params as $one_post_param) {
41 if (isset($_POST[$one_post_param])) {
42 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
46 // reset import messages for ajax request
47 $_SESSION['Import_message']['message'] = null;
48 $_SESSION['Import_message']['go_back_url'] = null;
49 // default values
50 $GLOBALS['reload'] = false;
52 // Use to identify curren cycle is executing
53 // a multiquery statement or stored routine
54 if (!isset($_SESSION['is_multi_query'])) {
55 $_SESSION['is_multi_query'] = false;
58 // Are we just executing plain query or sql file?
59 // (eg. non import, but query box/window run)
60 if (! empty($sql_query)) {
61 // run SQL query
62 $import_text = $sql_query;
63 $import_type = 'query';
64 $format = 'sql';
66 // refresh navigation and main panels
67 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
68 $GLOBALS['reload'] = true;
71 // refresh navigation panel only
72 if (preg_match('/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
73 $ajax_reload['reload'] = true;
76 // do a dynamic reload if table is RENAMED
77 // (by sending the instruction to the AJAX response handler)
78 if (preg_match('/^RENAME\s+TABLE\s+(.*?)\s+TO\s+(.*?)($|;|\s)/i', $sql_query, $rename_table_names)) {
79 $ajax_reload['table_name'] = PMA_Util::unQuote($rename_table_names[2]);
80 $ajax_reload['reload'] = true;
83 $sql_query = '';
84 } elseif (! empty($sql_localfile)) {
85 // run SQL file on server
86 $local_import_file = $sql_localfile;
87 $import_type = 'queryfile';
88 $format = 'sql';
89 unset($sql_localfile);
90 } elseif (! empty($sql_file)) {
91 // run uploaded SQL file
92 $import_file = $sql_file;
93 $import_type = 'queryfile';
94 $format = 'sql';
95 unset($sql_file);
96 } elseif (! empty($id_bookmark)) {
97 // run bookmark
98 $import_type = 'query';
99 $format = 'sql';
102 // If we didn't get any parameters, either user called this directly, or
103 // upload limit has been reached, let's assume the second possibility.
105 if ($_POST == array() && $_GET == array()) {
106 $message = PMA_Message::error(
107 __('You probably tried to upload a file that is too large. Please refer to %sdocumentation%s for a workaround for this limit.')
109 $message->addParam('[doc@faq1-16]');
110 $message->addParam('[/doc]');
112 // so we can obtain the message
113 $_SESSION['Import_message']['message'] = $message->getDisplay();
114 $_SESSION['Import_message']['go_back_url'] = $goto;
116 $message->display();
117 exit; // the footer is displayed automatically
121 * Sets globals from $_POST patterns, for import plugins
122 * We only need to load the selected plugin
125 $post_patterns = array(
126 '/^force_file_/',
127 '/^'. $format . '_/'
129 foreach (array_keys($_POST) as $post_key) {
130 foreach ($post_patterns as $one_post_pattern) {
131 if (preg_match($one_post_pattern, $post_key)) {
132 $GLOBALS[$post_key] = $_POST[$post_key];
137 // Check needed parameters
138 PMA_Util::checkParameters(array('import_type', 'format'));
140 // We don't want anything special in format
141 $format = PMA_securePath($format);
143 // Import functions
144 require_once 'libraries/import.lib.php';
146 // Create error and goto url
147 if ($import_type == 'table') {
148 $err_url = 'tbl_import.php?' . PMA_generate_common_url($db, $table);
149 $_SESSION['Import_message']['go_back_url'] = $err_url;
150 $goto = 'tbl_import.php';
151 } elseif ($import_type == 'database') {
152 $err_url = 'db_import.php?' . PMA_generate_common_url($db);
153 $_SESSION['Import_message']['go_back_url'] = $err_url;
154 $goto = 'db_import.php';
155 } elseif ($import_type == 'server') {
156 $err_url = 'server_import.php?' . PMA_generate_common_url();
157 $_SESSION['Import_message']['go_back_url'] = $err_url;
158 $goto = 'server_import.php';
159 } else {
160 if (empty($goto) || !preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
161 if (strlen($table) && strlen($db)) {
162 $goto = 'tbl_structure.php';
163 } elseif (strlen($db)) {
164 $goto = 'db_structure.php';
165 } else {
166 $goto = 'server_sql.php';
169 if (strlen($table) && strlen($db)) {
170 $common = PMA_generate_common_url($db, $table);
171 } elseif (strlen($db)) {
172 $common = PMA_generate_common_url($db);
173 } else {
174 $common = PMA_generate_common_url();
176 $err_url = $goto . '?' . $common
177 . (preg_match('@^tbl_[a-z]*\.php$@', $goto)
178 ? '&amp;table=' . htmlspecialchars($table)
179 : '');
180 $_SESSION['Import_message']['go_back_url'] = $err_url;
184 if (strlen($db)) {
185 PMA_DBI_select_db($db);
188 @set_time_limit($cfg['ExecTimeLimit']);
189 if (! empty($cfg['MemoryLimit'])) {
190 @ini_set('memory_limit', $cfg['MemoryLimit']);
193 $timestamp = time();
194 if (isset($allow_interrupt)) {
195 $maximum_time = ini_get('max_execution_time');
196 } else {
197 $maximum_time = 0;
200 // set default values
201 $timeout_passed = false;
202 $error = false;
203 $read_multiply = 1;
204 $finished = false;
205 $offset = 0;
206 $max_sql_len = 0;
207 $file_to_unlink = '';
208 $sql_query = '';
209 $sql_query_disabled = false;
210 $go_sql = false;
211 $executed_queries = 0;
212 $run_query = true;
213 $charset_conversion = false;
214 $reset_charset = false;
215 $bookmark_created = false;
217 // Bookmark Support: get a query back from bookmark if required
218 if (! empty($id_bookmark)) {
219 $id_bookmark = (int)$id_bookmark;
220 include_once 'libraries/bookmark.lib.php';
221 switch ($action_bookmark) {
222 case 0: // bookmarked query that have to be run
223 $import_text = PMA_Bookmark_get(
224 $db,
225 $id_bookmark,
226 'id',
227 isset($action_bookmark_all)
229 if (isset($bookmark_variable) && ! empty($bookmark_variable)) {
230 $import_text = preg_replace(
231 '|/\*(.*)\[VARIABLE\](.*)\*/|imsU',
232 '${1}' . PMA_Util::sqlAddSlashes($bookmark_variable) . '${2}',
233 $import_text
237 // refresh navigation and main panels
238 if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $import_text)) {
239 $GLOBALS['reload'] = true;
242 // refresh navigation panel only
243 if (preg_match('/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $import_text)) {
244 $ajax_reload['reload'] = true;
246 break;
247 case 1: // bookmarked query that have to be displayed
248 $import_text = PMA_Bookmark_get($db, $id_bookmark);
249 if ($GLOBALS['is_ajax_request'] == true) {
250 $message = PMA_Message::success(__('Showing bookmark'));
251 $response = PMA_Response::getInstance();
252 $response->isSuccess($message->isSuccess());
253 $response->addJSON('message', $message);
254 $response->addJSON('sql_query', $import_text);
255 $response->addJSON('action_bookmark', $action_bookmark);
256 exit;
257 } else {
258 $run_query = false;
260 break;
261 case 2: // bookmarked query that have to be deleted
262 $import_text = PMA_Bookmark_get($db, $id_bookmark);
263 PMA_Bookmark_delete($db, $id_bookmark);
264 if ($GLOBALS['is_ajax_request'] == true) {
265 $message = PMA_Message::success(__('The bookmark has been deleted.'));
266 $response = PMA_Response::getInstance();
267 $response->isSuccess($message->isSuccess());
268 $response->addJSON('message', $message);
269 $response->addJSON('action_bookmark', $action_bookmark);
270 $response->addJSON('id_bookmark', $id_bookmark);
271 exit;
272 } else {
273 $run_query = false;
274 $error = true; // this is kind of hack to skip processing the query
276 break;
278 } // end bookmarks reading
280 // Do no run query if we show PHP code
281 if (isset($GLOBALS['show_as_php'])) {
282 $run_query = false;
283 $go_sql = true;
286 // We can not read all at once, otherwise we can run out of memory
287 $memory_limit = trim(@ini_get('memory_limit'));
288 // 2 MB as default
289 if (empty($memory_limit)) {
290 $memory_limit = 2 * 1024 * 1024;
292 // In case no memory limit we work on 10MB chunks
293 if ($memory_limit == -1) {
294 $memory_limit = 10 * 1024 * 1024;
297 // Calculate value of the limit
298 if (strtolower(substr($memory_limit, -1)) == 'm') {
299 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
300 } elseif (strtolower(substr($memory_limit, -1)) == 'k') {
301 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
302 } elseif (strtolower(substr($memory_limit, -1)) == 'g') {
303 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
304 } else {
305 $memory_limit = (int)$memory_limit;
308 // Just to be sure, there might be lot of memory needed for uncompression
309 $read_limit = $memory_limit / 8;
311 // handle filenames
312 if (isset($_FILES['import_file'])) {
313 $import_file = $_FILES['import_file']['tmp_name'];
315 if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
317 // sanitize $local_import_file as it comes from a POST
318 $local_import_file = PMA_securePath($local_import_file);
320 $import_file = PMA_Util::userDir($cfg['UploadDir'])
321 . $local_import_file;
323 } elseif (empty($import_file) || ! is_uploaded_file($import_file)) {
324 $import_file = 'none';
327 // Do we have file to import?
329 if ($import_file != 'none' && ! $error) {
330 // work around open_basedir and other limitations
331 $open_basedir = @ini_get('open_basedir');
333 // If we are on a server with open_basedir, we must move the file
334 // before opening it. The doc explains how to create the "./tmp"
335 // directory
337 if (! empty($open_basedir)) {
339 $tmp_subdir = (PMA_IS_WINDOWS ? '.\\tmp\\' : 'tmp/');
341 if (is_writable($tmp_subdir)) {
344 $import_file_new = $tmp_subdir . basename($import_file) . uniqid();
345 if (move_uploaded_file($import_file, $import_file_new)) {
346 $import_file = $import_file_new;
347 $file_to_unlink = $import_file_new;
350 $size = filesize($import_file);
355 * Handle file compression
356 * @todo duplicate code exists in File.class.php
358 $compression = PMA_detectCompression($import_file);
359 if ($compression === false) {
360 $message = PMA_Message::error(__('File could not be read'));
361 $error = true;
362 } else {
363 switch ($compression) {
364 case 'application/bzip2':
365 if ($cfg['BZipDump'] && @function_exists('bzopen')) {
366 $import_handle = @bzopen($import_file, 'r');
367 } else {
368 $message = PMA_Message::error(
369 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
371 $message->addParam($compression);
372 $error = true;
374 break;
375 case 'application/gzip':
376 if ($cfg['GZipDump'] && @function_exists('gzopen')) {
377 $import_handle = @gzopen($import_file, 'r');
378 } else {
379 $message = PMA_Message::error(
380 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
382 $message->addParam($compression);
383 $error = true;
385 break;
386 case 'application/zip':
387 if ($cfg['ZipDump'] && @function_exists('zip_open')) {
389 * Load interface for zip extension.
391 include_once 'libraries/zip_extension.lib.php';
392 $result = PMA_getZipContents($import_file);
393 if (! empty($result['error'])) {
394 $message = PMA_Message::rawError($result['error']);
395 $error = true;
396 } else {
397 $import_text = $result['data'];
399 } else {
400 $message = PMA_Message::error(
401 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
403 $message->addParam($compression);
404 $error = true;
406 break;
407 case 'none':
408 $import_handle = @fopen($import_file, 'r');
409 break;
410 default:
411 $message = PMA_Message::error(
412 __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
414 $message->addParam($compression);
415 $error = true;
416 break;
419 // use isset() because zip compression type does not use a handle
420 if (! $error && isset($import_handle) && $import_handle === false) {
421 $message = PMA_Message::error(__('File could not be read'));
422 $error = true;
424 } elseif (! $error) {
425 if (! isset($import_text) || empty($import_text)) {
426 $message = PMA_Message::error(
427 __('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].')
429 $error = true;
433 // so we can obtain the message
434 //$_SESSION['Import_message'] = $message->getDisplay();
436 // Convert the file's charset if necessary
437 if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE && isset($charset_of_file)) {
438 if ($charset_of_file != 'utf-8') {
439 $charset_conversion = true;
441 } elseif (isset($charset_of_file) && $charset_of_file != 'utf8') {
442 if (PMA_DRIZZLE) {
443 // Drizzle doesn't support other character sets,
444 // so we can't fallback to SET NAMES - throw an error
445 $error = true;
446 $message = PMA_Message::error(
447 __('Cannot convert file\'s character set without character set conversion library')
449 } else {
450 PMA_DBI_query('SET NAMES \'' . $charset_of_file . '\'');
451 // We can not show query in this case, it is in different charset
452 $sql_query_disabled = true;
453 $reset_charset = true;
457 // Something to skip?
458 if (! $error && isset($skip)) {
459 $original_skip = $skip;
460 while ($skip > 0) {
461 PMA_importGetNextChunk($skip < $read_limit ? $skip : $read_limit);
462 // Disable read progresivity, otherwise we eat all memory!
463 $read_multiply = 1;
464 $skip -= $read_limit;
466 unset($skip);
469 // This array contain the data like numberof valid sql queries in the statement
470 // and complete valid sql statement (which affected for rows)
471 $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
473 if (! $error) {
474 // Check for file existance
475 include_once "libraries/plugin_interface.lib.php";
476 $import_plugin = PMA_getPlugin(
477 "import",
478 $format,
479 'libraries/plugins/import/',
480 $import_type
482 if ($import_plugin == null) {
483 $error = true;
484 $message = PMA_Message::error(
485 __('Could not load import plugins, please check your installation!')
487 } else {
488 // Do the real import
489 $import_plugin->doImport($sql_data);
493 if (! $error && false !== $import_handle && null !== $import_handle) {
494 fclose($import_handle);
497 // Cleanup temporary file
498 if ($file_to_unlink != '') {
499 unlink($file_to_unlink);
502 // Reset charset back, if we did some changes
503 if ($reset_charset) {
504 PMA_DBI_query('SET CHARACTER SET utf8');
505 PMA_DBI_query(
506 'SET SESSION collation_connection =\'' . $collation_connection . '\''
510 // Show correct message
511 if (! empty($id_bookmark) && $action_bookmark == 2) {
512 $message = PMA_Message::success(__('The bookmark has been deleted.'));
513 $display_query = $import_text;
514 $error = false; // unset error marker, it was used just to skip processing
515 } elseif (! empty($id_bookmark) && $action_bookmark == 1) {
516 $message = PMA_Message::notice(__('Showing bookmark'));
517 } elseif ($bookmark_created) {
518 $special_message = '[br]' . sprintf(
519 __('Bookmark %s created'),
520 htmlspecialchars($bkm_label)
522 } elseif ($finished && ! $error) {
523 if ($import_type == 'query') {
524 $message = PMA_Message::success();
525 } else {
526 if ($import_notice) {
527 $message = PMA_Message::success(
528 '<em>' . __('Import has been successfully finished, %d queries executed.') . '</em>'
530 $message->addParam($executed_queries);
532 $message->addString($import_notice);
533 if (isset($local_import_file)) {
534 $message->addString('(' . $local_import_file . ')');
535 } else {
536 $message->addString('(' . $_FILES['import_file']['name'] . ')');
538 } else {
539 $message = PMA_Message::success(
540 __('Import has been successfully finished, %d queries executed.')
542 $message->addParam($executed_queries);
543 if (isset($local_import_file)) {
544 $message->addString('(' . $local_import_file . ')');
545 } else {
546 $message->addString('(' . $_FILES['import_file']['name'] . ')');
552 // Did we hit timeout? Tell it user.
553 if ($timeout_passed) {
554 $message = PMA_Message::error(
555 __('Script timeout passed, if you want to finish import, please resubmit same file and import will resume.')
557 if ($offset == 0 || (isset($original_skip) && $original_skip == $offset)) {
558 $message->addString(
559 __('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.')
564 // if there is any message, copy it into $_SESSION as well,
565 // so we can obtain it by AJAX call
566 if (isset($message)) {
567 $_SESSION['Import_message']['message'] = $message->getDisplay();
569 // Parse and analyze the query, for correct db and table name
570 // in case of a query typed in the query window
571 // (but if the query is too large, in case of an imported file, the parser
572 // can choke on it so avoid parsing)
573 if (strlen($sql_query) <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
574 include_once 'libraries/parse_analyze.lib.php';
577 // There was an error?
578 if (isset($my_die)) {
579 foreach ($my_die AS $key => $die) {
580 PMA_Util::mysqlDie(
581 $die['error'], $die['sql'], '', $err_url, $error
586 // we want to see the results of the last query that returned at least a row
587 if (! empty($last_query_with_results)) {
588 // but we want to show intermediate results too
589 $disp_query = $sql_query;
590 $disp_message = __('Your SQL query has been executed successfully');
591 $sql_query = $last_query_with_results;
592 $go_sql = true;
595 if ($go_sql) {
596 include 'sql.php';
597 } else {
598 $active_page = $goto;
599 include '' . $goto;