cache table information
[phpmyadmin.git] / import.php
blob61e92018090565a053ee534875012dbd360157b0
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 * @uses PMA_Bookmark_getList()
7 * @version $Id$
8 */
10 /**
11 * Get the variables sent or posted to this script and a core script
13 require_once './libraries/common.inc.php';
14 $GLOBALS['js_include'][] = 'functions.js';
16 // default values
17 $GLOBALS['reload'] = false;
19 // Are we just executing plain query or sql file? (eg. non import, but query box/window run)
20 if (!empty($sql_query)) {
21 // run SQL query
22 $import_text = $sql_query;
23 $import_type = 'query';
24 $format = 'sql';
26 // refresh left frame on changes in table or db structure
27 if (preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
28 $GLOBALS['reload'] = true;
31 $sql_query = '';
32 } elseif (!empty($sql_localfile)) {
33 // run SQL file on server
34 $local_import_file = $sql_localfile;
35 $import_type = 'queryfile';
36 $format = 'sql';
37 unset($sql_localfile);
38 } elseif (!empty($sql_file)) {
39 // run uploaded SQL file
40 $import_file = $sql_file;
41 $import_type = 'queryfile';
42 $format = 'sql';
43 unset($sql_file);
44 } elseif (!empty($id_bookmark)) {
45 // run bookmark
46 $import_type = 'query';
47 $format = 'sql';
50 // If we didn't get any parameters, either user called this directly, or
51 // upload limit has been reached, let's assume the second possibility.
52 if ($_POST == array() && $_GET == array()) {
53 require_once './libraries/header.inc.php';
54 $message = PMA_Message::error('strUploadLimit');
55 $message->addParam('[a@./Documentation.html#faq1_16@_blank]');
56 $message->addParam('[/a]');
57 $message->display();
58 require './libraries/footer.inc.php';
61 // Check needed parameters
62 PMA_checkParameters(array('import_type', 'format'));
64 // We don't want anything special in format
65 $format = PMA_securePath($format);
67 // Import functions
68 require_once './libraries/import.lib.php';
70 // Create error and goto url
71 if ($import_type == 'table') {
72 $err_url = 'tbl_import.php?' . PMA_generate_common_url($db, $table);
73 $goto = 'tbl_import.php';
74 } elseif ($import_type == 'database') {
75 $err_url = 'db_import.php?' . PMA_generate_common_url($db);
76 $goto = 'db_import.php';
77 } elseif ($import_type == 'server') {
78 $err_url = 'server_import.php?' . PMA_generate_common_url();
79 $goto = 'server_import.php';
80 } else {
81 if (empty($goto) || !preg_match('@^(server|db|tbl)(_[a-z]*)*\.php$@i', $goto)) {
82 if (strlen($table) && strlen($db)) {
83 $goto = 'tbl_structure.php';
84 } elseif (strlen($db)) {
85 $goto = 'db_structure.php';
86 } else {
87 $goto = 'server_sql.php';
90 if (strlen($table) && strlen($db)) {
91 $common = PMA_generate_common_url($db, $table);
92 } elseif (strlen($db)) {
93 $common = PMA_generate_common_url($db);
94 } else {
95 $common = PMA_generate_common_url();
97 $err_url = $goto
98 . '?' . $common
99 . (preg_match('@^tbl_[a-z]*\.php$@', $goto) ? '&amp;table=' . urlencode($table) : '');
103 if (strlen($db)) {
104 PMA_DBI_select_db($db);
107 @set_time_limit($cfg['ExecTimeLimit']);
108 if (!empty($cfg['MemoryLimit'])) {
109 @ini_set('memory_limit', $cfg['MemoryLimit']);
112 $timestamp = time();
113 if (isset($allow_interrupt)) {
114 $maximum_time = ini_get('max_execution_time');
115 } else {
116 $maximum_time = 0;
119 // set default values
120 $timeout_passed = FALSE;
121 $error = FALSE;
122 $read_multiply = 1;
123 $finished = FALSE;
124 $offset = 0;
125 $max_sql_len = 0;
126 $file_to_unlink = '';
127 $sql_query = '';
128 $sql_query_disabled = FALSE;
129 $go_sql = FALSE;
130 $executed_queries = 0;
131 $run_query = TRUE;
132 $charset_conversion = FALSE;
133 $reset_charset = FALSE;
134 $bookmark_created = FALSE;
136 // Bookmark Support: get a query back from bookmark if required
137 if (!empty($id_bookmark)) {
138 require_once './libraries/bookmark.lib.php';
139 switch ($action_bookmark) {
140 case 0: // bookmarked query that have to be run
141 $import_text = PMA_Bookmark_get($db, $id_bookmark, 'id', isset($action_bookmark_all));
142 if (isset($bookmark_variable) && !empty($bookmark_variable)) {
143 $import_text = preg_replace('|/\*(.*)\[VARIABLE\](.*)\*/|imsU', '${1}' . PMA_sqlAddslashes($bookmark_variable) . '${2}', $import_text);
146 // refresh left frame on changes in table or db structure
147 if (preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $import_text)) {
148 $GLOBALS['reload'] = true;
151 break;
152 case 1: // bookmarked query that have to be displayed
153 $import_text = PMA_Bookmark_get($db, $id_bookmark);
154 $run_query = FALSE;
155 break;
156 case 2: // bookmarked query that have to be deleted
157 $import_text = PMA_Bookmark_get($db, $id_bookmark);
158 PMA_Bookmark_delete($db, $id_bookmark);
159 $run_query = FALSE;
160 $error = TRUE; // this is kind of hack to skip processing the query
161 break;
163 } // end bookmarks reading
165 // Do no run query if we show PHP code
166 if (isset($GLOBALS['show_as_php'])) {
167 $run_query = FALSE;
168 $go_sql = TRUE;
171 // Store the query as a bookmark before executing it if bookmarklabel was given
172 if (!empty($bkm_label) && !empty($import_text)) {
173 require_once './libraries/bookmark.lib.php';
174 $bfields = array(
175 'dbase' => $db,
176 'user' => $cfg['Bookmark']['user'],
177 'query' => urlencode($import_text),
178 'label' => $bkm_label
181 // Should we replace bookmark?
182 if (isset($bkm_replace)) {
183 $bookmarks = PMA_Bookmark_getList($db);
184 foreach ($bookmarks as $key => $val) {
185 if ($val == $bkm_label) {
186 PMA_Bookmark_delete($db, $key);
191 PMA_Bookmark_save($bfields, isset($bkm_all_users));
193 $bookmark_created = TRUE;
194 } // end store bookmarks
196 // We can not read all at once, otherwise we can run out of memory
197 $memory_limit = trim(@ini_get('memory_limit'));
198 // 2 MB as default
199 if (empty($memory_limit)) {
200 $memory_limit = 2 * 1024 * 1024;
202 // In case no memory limit we work on 10MB chunks
203 if ($memory_limit = -1) {
204 $memory_limit = 10 * 1024 * 1024;
207 // Calculate value of the limit
208 if (strtolower(substr($memory_limit, -1)) == 'm') {
209 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
210 } elseif (strtolower(substr($memory_limit, -1)) == 'k') {
211 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
212 } elseif (strtolower(substr($memory_limit, -1)) == 'g') {
213 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
214 } else {
215 $memory_limit = (int)$memory_limit;
218 $read_limit = $memory_limit / 8; // Just to be sure, there might be lot of memory needed for uncompression
220 // handle filenames
221 if (!empty($local_import_file) && !empty($cfg['UploadDir'])) {
223 // sanitize $local_import_file as it comes from a POST
224 $local_import_file = PMA_securePath($local_import_file);
226 $import_file = PMA_userDir($cfg['UploadDir']) . $local_import_file;
227 } elseif (empty($import_file) || !is_uploaded_file($import_file)) {
228 $import_file = 'none';
231 // Do we have file to import?
232 if ($import_file != 'none' && !$error) {
233 // work around open_basedir and other limitations
234 $open_basedir = @ini_get('open_basedir');
236 // If we are on a server with open_basedir, we must move the file
237 // before opening it. The doc explains how to create the "./tmp"
238 // directory
240 if (!empty($open_basedir)) {
242 $tmp_subdir = (PMA_IS_WINDOWS ? '.\\tmp\\' : './tmp/');
244 if (is_writable($tmp_subdir)) {
245 $import_file_new = $tmp_subdir . basename($import_file);
246 if (move_uploaded_file($import_file, $import_file_new)) {
247 $import_file = $import_file_new;
248 $file_to_unlink = $import_file_new;
253 // Handle file compression
254 $compression = PMA_detectCompression($import_file);
255 if ($compression === FALSE) {
256 $message = PMA_Message::error('strFileCouldNotBeRead');
257 $error = TRUE;
258 } else {
259 switch ($compression) {
260 case 'application/bzip2':
261 if ($cfg['BZipDump'] && @function_exists('bzopen')) {
262 $import_handle = @bzopen($import_file, 'r');
263 } else {
264 $message = PMA_Message::error('strUnsupportedCompressionDetected');
265 $message->addParam($compression);
266 $error = TRUE;
268 break;
269 case 'application/gzip':
270 if ($cfg['GZipDump'] && @function_exists('gzopen')) {
271 $import_handle = @gzopen($import_file, 'r');
272 } else {
273 $message = PMA_Message::error('strUnsupportedCompressionDetected');
274 $message->addParam($compression);
275 $error = TRUE;
277 break;
278 case 'application/zip':
279 if ($cfg['GZipDump'] && @function_exists('gzinflate')) {
280 include_once './libraries/unzip.lib.php';
281 $import_handle = new SimpleUnzip();
282 $import_handle->ReadFile($import_file);
283 if ($import_handle->Count() == 0) {
284 $message = PMA_Message::error('strNoFilesFoundInZip');
285 $error = TRUE;
286 } elseif ($import_handle->GetError(0) != 0) {
287 $message = PMA_Message::rawError($strErrorInZipFile . ' ' . $import_handle->GetErrorMsg(0));
288 $error = TRUE;
289 } else {
290 $import_text = $import_handle->GetData(0);
292 // We don't need to store it further
293 $import_handle = '';
294 } else {
295 $message = PMA_Message::error('strUnsupportedCompressionDetected');
296 $message->addParam($compression);
297 $error = TRUE;
299 break;
300 case 'none':
301 $import_handle = @fopen($import_file, 'r');
302 break;
303 default:
304 $message = PMA_Message::error('strUnsupportedCompressionDetected');
305 $message->addParam($compression);
306 $error = TRUE;
307 break;
310 if (!$error && $import_handle === FALSE) {
311 $message = PMA_Message::error('strFileCouldNotBeRead');
312 $error = TRUE;
314 } elseif (!$error) {
315 if (!isset($import_text) || empty($import_text)) {
316 $message = PMA_Message::error('strNoDataReceived');
317 $error = TRUE;
321 // Convert the file's charset if necessary
322 if ($cfg['AllowAnywhereRecoding'] && $allow_recoding
323 && isset($charset_of_file)) {
324 if ($charset_of_file != $charset) {
325 $charset_conversion = TRUE;
327 } elseif (isset($charset_of_file) && $charset_of_file != 'utf8') {
328 PMA_DBI_query('SET NAMES \'' . $charset_of_file . '\'');
329 // We can not show query in this case, it is in different charset
330 $sql_query_disabled = TRUE;
331 $reset_charset = TRUE;
334 // Something to skip?
335 if (!$error && isset($skip)) {
336 $original_skip = $skip;
337 while ($skip > 0) {
338 PMA_importGetNextChunk($skip < $read_limit ? $skip : $read_limit);
339 $read_multiply = 1; // Disable read progresivity, otherwise we eat all memory!
340 $skip -= $read_limit;
342 unset($skip);
345 if (!$error) {
346 // Check for file existance
347 if (!file_exists('./libraries/import/' . $format . '.php')) {
348 $error = TRUE;
349 $message = PMA_Message::error('strCanNotLoadImportPlugins');
350 } else {
351 // Do the real import
352 $plugin_param = $import_type;
353 require './libraries/import/' . $format . '.php';
357 // Cleanup temporary file
358 if ($file_to_unlink != '') {
359 unlink($file_to_unlink);
362 // Reset charset back, if we did some changes
363 if ($reset_charset) {
364 PMA_DBI_query('SET CHARACTER SET utf8');
365 PMA_DBI_query('SET SESSION collation_connection =\'' . $collation_connection . '\'');
368 // Show correct message
369 if (!empty($id_bookmark) && $action_bookmark == 2) {
370 $message = PMA_Message::success('strBookmarkDeleted');
371 $display_query = $import_text;
372 $error = FALSE; // unset error marker, it was used just to skip processing
373 } elseif (!empty($id_bookmark) && $action_bookmark == 1) {
374 $message = PMA_Message::notice('strShowingBookmark');
375 } elseif ($bookmark_created) {
376 $special_message = '[br]' . sprintf($strBookmarkCreated, htmlspecialchars($bkm_label));
377 } elseif ($finished && !$error) {
378 if ($import_type == 'query') {
379 $message = PMA_Message::success();
380 } else {
381 $message = PMA_Message::success('strImportSuccessfullyFinished');
382 $message->addParam($executed_queries);
386 // Did we hit timeout? Tell it user.
387 if ($timeout_passed) {
388 $message = PMA_Message::error('strTimeoutPassed');
389 if ($offset == 0 || (isset($original_skip) && $original_skip == $offset)) {
390 $message->addString('strTimeoutNothingParsed');
394 // Parse and analyze the query, for correct db and table name
395 // in case of a query typed in the query window
396 require_once './libraries/parse_analyze.lib.php';
398 // There was an error?
399 if (isset($my_die)) {
400 foreach ($my_die AS $key => $die) {
401 PMA_mysqlDie($die['error'], $die['sql'], '', $err_url, $error);
405 if ($go_sql) {
406 require './sql.php';
407 } else {
408 $active_page = $goto;
409 require './' . $goto;
411 exit();