Czech translation update.
[phpmyadmin/crack.git] / export.php
blobbb1f479986adb11a2364ee8ca4a89a66bad0081a
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * @todo too much die here, or?
5 * @version $Id$
6 */
8 /**
9 * Get the variables sent or posted to this script and a core script
11 require_once './libraries/common.inc.php';
12 require_once './libraries/zip.lib.php';
13 require_once './libraries/plugin_interface.lib.php';
15 PMA_checkParameters(array('what', 'export_type'));
17 // Scan plugins
18 $export_list = PMA_getPlugins('./libraries/export/', array('export_type' => $export_type, 'single_table' => isset($single_table)));
20 // Backward compatbility
21 $type = $what;
23 // Check export type
24 if (!isset($export_list[$type])) {
25 die('Bad type!');
28 /**
29 * valid compression methods
31 $compression_methods = array(
32 'zip',
33 'gzip',
34 'bzip',
37 /**
38 * init and variable checking
40 $compression = false;
41 $onserver = false;
42 $save_on_server = false;
43 $buffer_needed = false;
44 if (empty($_REQUEST['asfile'])) {
45 $asfile = false;
46 } else {
47 $asfile = true;
48 if (in_array($_REQUEST['compression'], $compression_methods)) {
49 $compression = $_REQUEST['compression'];
50 $buffer_needed = true;
52 if (!empty($_REQUEST['onserver'])) {
53 $onserver = $_REQUEST['onserver'];
54 // Will we save dump on server?
55 $save_on_server = ! empty($cfg['SaveDir']) && $onserver;
59 // Does export require to be into file?
60 if (isset($export_list[$type]['force_file']) && ! $asfile) {
61 $message = PMA_Message::error('strExportMustBeFile');
62 $GLOBALS['js_include'][] = 'functions.js';
63 require_once './libraries/header.inc.php';
64 if ($export_type == 'server') {
65 $active_page = 'server_export.php';
66 require './server_export.php';
67 } elseif ($export_type == 'database') {
68 $active_page = 'db_export.php';
69 require './db_export.php';
70 } else {
71 $active_page = 'tbl_export.php';
72 require './tbl_export.php';
74 exit();
77 // Generate error url and check for needed variables
78 if ($export_type == 'server') {
79 $err_url = 'server_export.php?' . PMA_generate_common_url();
80 } elseif ($export_type == 'database' && strlen($db)) {
81 $err_url = 'db_export.php?' . PMA_generate_common_url($db);
82 // Check if we have something to export
83 if (isset($table_select)) {
84 $tables = $table_select;
85 } else {
86 $tables = array();
88 } elseif ($export_type == 'table' && strlen($db) && strlen($table)) {
89 $err_url = 'tbl_export.php?' . PMA_generate_common_url($db, $table);
90 } else {
91 die('Bad parameters!');
94 // Get the functions specific to the export type
95 require './libraries/export/' . PMA_securePath($type) . '.php';
97 /**
98 * Increase time limit for script execution and initializes some variables
100 @set_time_limit($cfg['ExecTimeLimit']);
101 if (!empty($cfg['MemoryLimit'])) {
102 @ini_set('memory_limit', $cfg['MemoryLimit']);
105 // Start with empty buffer
106 $dump_buffer = '';
107 $dump_buffer_len = 0;
109 // We send fake headers to avoid browser timeout when buffering
110 $time_start = time();
114 * Output handler for all exports, if needed buffering, it stores data into
115 * $dump_buffer, otherwise it prints thems out.
117 * @param string the insert statement
119 * @return bool Whether output suceeded
121 function PMA_exportOutputHandler($line)
123 global $time_start, $dump_buffer, $dump_buffer_len, $save_filename;
125 // Kanji encoding convert feature
126 if ($GLOBALS['output_kanji_conversion']) {
127 $line = PMA_kanji_str_conv($line, $GLOBALS['knjenc'], isset($GLOBALS['xkana']) ? $GLOBALS['xkana'] : '');
129 // If we have to buffer data, we will perform everything at once at the end
130 if ($GLOBALS['buffer_needed']) {
132 $dump_buffer .= $line;
133 if ($GLOBALS['onfly_compression']) {
135 $dump_buffer_len += strlen($line);
137 if ($dump_buffer_len > $GLOBALS['memory_limit']) {
138 if ($GLOBALS['output_charset_conversion']) {
139 $dump_buffer = PMA_convert_string($GLOBALS['charset'], $GLOBALS['charset_of_file'], $dump_buffer);
141 // as bzipped
142 if ($GLOBALS['compression'] == 'bzip' && @function_exists('bzcompress')) {
143 $dump_buffer = bzcompress($dump_buffer);
145 // as a gzipped file
146 elseif ($GLOBALS['compression'] == 'gzip' && @function_exists('gzencode')) {
147 // without the optional parameter level because it bug
148 $dump_buffer = gzencode($dump_buffer);
150 if ($GLOBALS['save_on_server']) {
151 $write_result = @fwrite($GLOBALS['file_handle'], $dump_buffer);
152 if (!$write_result || ($write_result != strlen($dump_buffer))) {
153 $GLOBALS['message'] = PMA_Message::error('strNoSpace');
154 $GLOBALS['message']->addParam($save_filename);
155 return false;
157 } else {
158 echo $dump_buffer;
160 $dump_buffer = '';
161 $dump_buffer_len = 0;
163 } else {
164 $time_now = time();
165 if ($time_start >= $time_now + 30) {
166 $time_start = $time_now;
167 header('X-pmaPing: Pong');
168 } // end if
170 } else {
171 if ($GLOBALS['asfile']) {
172 if ($GLOBALS['output_charset_conversion']) {
173 $line = PMA_convert_string($GLOBALS['charset'], $GLOBALS['charset_of_file'], $line);
175 if ($GLOBALS['save_on_server'] && strlen($line) > 0) {
176 $write_result = @fwrite($GLOBALS['file_handle'], $line);
177 if (!$write_result || ($write_result != strlen($line))) {
178 $GLOBALS['message'] = PMA_Message::error('strNoSpace');
179 $GLOBALS['message']->addParam($save_filename);
180 return false;
182 $time_now = time();
183 if ($time_start >= $time_now + 30) {
184 $time_start = $time_now;
185 header('X-pmaPing: Pong');
186 } // end if
187 } else {
188 // We export as file - output normally
189 echo $line;
191 } else {
192 // We export as html - replace special chars
193 echo htmlspecialchars($line);
196 return true;
197 } // end of the 'PMA_exportOutputHandler()' function
199 // Defines the default <CR><LF> format. For SQL always use \n as MySQL wants this on all platforms.
200 if ($what == 'sql') {
201 $crlf = "\n";
202 } else {
203 $crlf = PMA_whichCrlf();
206 $output_kanji_conversion = function_exists('PMA_kanji_str_conv') && $type != 'xls';
208 // Do we need to convert charset?
209 $output_charset_conversion = $asfile &&
210 $cfg['AllowAnywhereRecoding'] && $allow_recoding
211 && isset($charset_of_file) && $charset_of_file != $charset
212 && $type != 'xls';
214 // Use on fly compression?
215 $onfly_compression = $GLOBALS['cfg']['CompressOnFly'] && ($compression == 'gzip' | $compression == 'bzip');
216 if ($onfly_compression) {
217 $memory_limit = trim(@ini_get('memory_limit'));
218 // 2 MB as default
219 if (empty($memory_limit)) {
220 $memory_limit = 2 * 1024 * 1024;
223 if (strtolower(substr($memory_limit, -1)) == 'm') {
224 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
225 } elseif (strtolower(substr($memory_limit, -1)) == 'k') {
226 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
227 } elseif (strtolower(substr($memory_limit, -1)) == 'g') {
228 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
229 } else {
230 $memory_limit = (int)$memory_limit;
233 // Some of memory is needed for other thins and as treshold.
234 // Nijel: During export I had allocated (see memory_get_usage function)
235 // approx 1.2MB so this comes from that.
236 if ($memory_limit > 1500000) {
237 $memory_limit -= 1500000;
240 // Some memory is needed for compression, assume 1/3
241 $memory_limit /= 8;
244 // Generate filename and mime type if needed
245 if ($asfile) {
246 $pma_uri_parts = parse_url($cfg['PmaAbsoluteUri']);
247 if ($export_type == 'server') {
248 if (isset($remember_template)) {
249 PMA_setCookie('pma_server_filename_template', $filename_template);
251 $filename = str_replace('__SERVER__', $GLOBALS['cfg']['Server']['host'], strftime($filename_template));
252 } elseif ($export_type == 'database') {
253 if (isset($remember_template)) {
254 PMA_setCookie('pma_db_filename_template', $filename_template);
256 $filename = str_replace('__DB__', $db, str_replace('__SERVER__', $GLOBALS['cfg']['Server']['host'], strftime($filename_template)));
257 } else {
258 if (isset($remember_template)) {
259 PMA_setCookie('pma_table_filename_template', $filename_template);
261 $filename = str_replace('__TABLE__', $table, str_replace('__DB__', $db, str_replace('__SERVER__', $GLOBALS['cfg']['Server']['host'], strftime($filename_template))));
264 // convert filename to iso-8859-1, it is safer
265 if (!(isset($cfg['AllowAnywhereRecoding']) && $cfg['AllowAnywhereRecoding'] && $allow_recoding)) {
266 $filename = PMA_convert_string($charset, 'iso-8859-1', $filename);
267 } else {
268 $filename = PMA_convert_string($convcharset, 'iso-8859-1', $filename);
271 // Grab basic dump extension and mime type
272 $filename .= '.' . $export_list[$type]['extension'];
273 $mime_type = $export_list[$type]['mime_type'];
275 // If dump is going to be compressed, set correct encoding or mime_type and add
276 // compression to extension
277 $content_encoding = '';
278 if ($compression == 'bzip') {
279 $filename .= '.bz2';
280 // browsers don't like this:
281 //$content_encoding = 'x-bzip2';
282 $mime_type = 'application/x-bzip2';
283 } elseif ($compression == 'gzip') {
284 $filename .= '.gz';
285 // Needed to avoid recompression by server modules like mod_gzip.
286 // It seems necessary to check about zlib.output_compression
287 // to avoid compressing twice
288 if (!@ini_get('zlib.output_compression')) {
289 $content_encoding = 'x-gzip';
290 $mime_type = 'application/x-gzip';
292 } elseif ($compression == 'zip') {
293 $filename .= '.zip';
294 $mime_type = 'application/zip';
298 // Open file on server if needed
299 if ($save_on_server) {
300 $save_filename = PMA_userDir($cfg['SaveDir']) . preg_replace('@[/\\\\]@', '_', $filename);
301 unset($message);
302 if (file_exists($save_filename) && empty($onserverover)) {
303 $message = PMA_Message::error('strFileAlreadyExists');
304 $message->addParam($save_filename);
305 } else {
306 if (is_file($save_filename) && !is_writable($save_filename)) {
307 $message = PMA_Message::error('strNoPermission');
308 $message->addParam($save_filename);
309 } else {
310 if (!$file_handle = @fopen($save_filename, 'w')) {
311 $message = PMA_Message::error('strNoPermission');
312 $message->addParam($save_filename);
316 if (isset($message)) {
317 $GLOBALS['js_include'][] = 'functions.js';
318 require_once './libraries/header.inc.php';
319 if ($export_type == 'server') {
320 $active_page = 'server_export.php';
321 require './server_export.php';
322 } elseif ($export_type == 'database') {
323 $active_page = 'db_export.php';
324 require './db_export.php';
325 } else {
326 $active_page = 'tbl_export.php';
327 require './tbl_export.php';
329 exit();
334 * Send headers depending on whether the user chose to download a dump file
335 * or not
337 if (!$save_on_server) {
338 if ($asfile) {
339 // Download
340 if (!empty($content_encoding)) {
341 header('Content-Encoding: ' . $content_encoding);
343 header('Content-Type: ' . $mime_type);
344 header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
345 // lem9: Tested behavior of
346 // IE 5.50.4807.2300
347 // IE 6.0.2800.1106 (small glitch, asks twice when I click Open)
348 // IE 6.0.2900.2180
349 // Firefox 1.0.6
350 // in http and https
351 header('Content-Disposition: attachment; filename="' . $filename . '"');
352 if (PMA_USR_BROWSER_AGENT == 'IE') {
353 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
354 header('Pragma: public');
355 } else {
356 header('Pragma: no-cache');
358 } else {
359 // HTML
360 if ($export_type == 'database') {
361 $num_tables = count($tables);
362 if ($num_tables == 0) {
363 $message = PMA_Message::error('strNoTablesFound');
364 $GLOBALS['js_include'][] = 'functions.js';
365 require_once './libraries/header.inc.php';
366 $active_page = 'db_export.php';
367 require './db_export.php';
368 exit();
371 $backup_cfgServer = $cfg['Server'];
372 require_once './libraries/header.inc.php';
373 $cfg['Server'] = $backup_cfgServer;
374 unset($backup_cfgServer);
375 echo "\n" . '<div align="' . $cell_align_left . '">' . "\n";
376 //echo ' <pre>' . "\n";
377 echo ' <form name="nofunction">' . "\n"
378 // remove auto-select for now: there is no way to select
379 // only a part of the text; anyway, it should obey
380 // $cfg['TextareaAutoSelect']
381 //. ' <textarea name="sqldump" cols="50" rows="30" onclick="this.select();" id="textSQLDUMP" wrap="OFF">' . "\n";
382 . ' <textarea name="sqldump" cols="50" rows="30" id="textSQLDUMP" wrap="OFF">' . "\n";
383 } // end download
386 // Fake loop just to allow skip of remain of this code by break, I'd really
387 // need exceptions here :-)
388 do {
390 // Add possibly some comments to export
391 if (!PMA_exportHeader()) {
392 break;
395 // Will we need relation & co. setup?
396 $do_relation = isset($GLOBALS[$what . '_relation']);
397 $do_comments = isset($GLOBALS[$what . '_comments']);
398 $do_mime = isset($GLOBALS[$what . '_mime']);
399 if ($do_relation || $do_comments || $do_mime) {
400 require_once './libraries/relation.lib.php';
401 $cfgRelation = PMA_getRelationsParam();
403 if ($do_mime) {
404 require_once './libraries/transformations.lib.php';
407 // Include dates in export?
408 $do_dates = isset($GLOBALS[$what . '_dates']);
411 * Builds the dump
413 // Gets the number of tables if a dump of a database has been required
414 if ($export_type == 'server') {
415 if (isset($db_select)) {
416 $tmp_select = implode($db_select, '|');
417 $tmp_select = '|' . $tmp_select . '|';
419 // Walk over databases
420 foreach ($GLOBALS['PMA_List_Database']->items as $current_db) {
421 if ((isset($tmp_select) && strpos(' ' . $tmp_select, '|' . $current_db . '|'))
422 || !isset($tmp_select)) {
423 if (!PMA_exportDBHeader($current_db)) {
424 break 2;
426 if (!PMA_exportDBCreate($current_db)) {
427 break 2;
429 $tables = PMA_DBI_get_tables($current_db);
430 $views = array();
431 foreach ($tables as $table) {
432 // if this is a view, collect it for later; views must be exported
433 // after the tables
434 $is_view = PMA_Table::isView($current_db, $table);
435 if ($is_view) {
436 $views[] = $table;
438 if (isset($GLOBALS[$what . '_structure'])) {
439 // for a view, export a stand-in definition of the table
440 // to resolve view dependencies
441 if (!PMA_exportStructure($current_db, $table, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, $is_view ? 'stand_in' : 'create_table', $export_type)) {
442 break 3;
445 if (isset($GLOBALS[$what . '_data']) && ! $is_view) {
446 $local_query = 'SELECT * FROM ' . PMA_backquote($current_db) . '.' . PMA_backquote($table);
447 if (!PMA_exportData($current_db, $table, $crlf, $err_url, $local_query)) {
448 break 3;
452 foreach($views as $view) {
453 // no data export for a view
454 if (isset($GLOBALS[$what . '_structure'])) {
455 if (!PMA_exportStructure($current_db, $view, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, 'create_view', $export_type)) {
456 break 3;
460 if (!PMA_exportDBFooter($current_db)) {
461 break 2;
465 } elseif ($export_type == 'database') {
466 if (!PMA_exportDBHeader($db)) {
467 break;
469 $i = 0;
470 $views = array();
471 // $tables contains the choices from the user (via $table_select)
472 foreach ($tables as $table) {
473 // if this is a view, collect it for later; views must be exported after
474 // the tables
475 $is_view = PMA_Table::isView($db, $table);
476 if ($is_view) {
477 $views[] = $table;
479 if (isset($GLOBALS[$what . '_structure'])) {
480 // for a view, export a stand-in definition of the table
481 // to resolve view dependencies
482 if (!PMA_exportStructure($db, $table, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, $is_view ? 'stand_in' : 'create_table', $export_type)) {
483 break 2;
486 if (isset($GLOBALS[$what . '_data']) && ! $is_view) {
487 $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table);
488 if (!PMA_exportData($db, $table, $crlf, $err_url, $local_query)) {
489 break 2;
493 foreach ($views as $view) {
494 // no data export for a view
495 if (isset($GLOBALS[$what . '_structure'])) {
496 if (!PMA_exportStructure($db, $view, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, 'create_view', $export_type)) {
497 break 2;
502 if (!PMA_exportDBFooter($db)) {
503 break;
505 } else {
506 if (!PMA_exportDBHeader($db)) {
507 break;
509 // We export just one table
511 if ($limit_to > 0 && $limit_from >= 0) {
512 $add_query = ' LIMIT '
513 . (($limit_from > 0) ? $limit_from . ', ' : '')
514 . $limit_to;
515 } else {
516 $add_query = '';
519 $is_view = PMA_Table::isView($db, $table);
520 if (isset($GLOBALS[$what . '_structure'])) {
521 if (!PMA_exportStructure($db, $table, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, $is_view ? 'create_view' : 'create_table', $export_type)) {
522 break;
525 // If this is an export of a single view, we have to export data;
526 // for example, a PDF report
527 if (isset($GLOBALS[$what . '_data'])) {
528 if (!empty($sql_query)) {
529 // only preg_replace if needed
530 if (!empty($add_query)) {
531 // remove trailing semicolon before adding a LIMIT
532 $sql_query = preg_replace('%;\s*$%', '', $sql_query);
534 $local_query = $sql_query . $add_query;
535 PMA_DBI_select_db($db);
536 } else {
537 $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table) . $add_query;
539 if (!PMA_exportData($db, $table, $crlf, $err_url, $local_query)) {
540 break;
543 if (!PMA_exportDBFooter($db)) {
544 break;
547 if (!PMA_exportFooter()) {
548 break;
551 } while (false);
552 // End of fake loop
554 if ($save_on_server && isset($message)) {
555 $GLOBALS['js_include'][] = 'functions.js';
556 require_once './libraries/header.inc.php';
557 if ($export_type == 'server') {
558 $active_page = 'server_export.php';
559 require './server_export.php';
560 } elseif ($export_type == 'database') {
561 $active_page = 'db_export.php';
562 require './db_export.php';
563 } else {
564 $active_page = 'tbl_export.php';
565 require './tbl_export.php';
567 exit();
571 * Send the dump as a file...
573 if (!empty($asfile)) {
574 // Convert the charset if required.
575 if ($output_charset_conversion) {
576 $dump_buffer = PMA_convert_string($GLOBALS['charset'], $GLOBALS['charset_of_file'], $dump_buffer);
579 // Do the compression
580 // 1. as a gzipped file
581 if ($compression == 'zip') {
582 if (@function_exists('gzcompress')) {
583 $zipfile = new zipfile();
584 $zipfile -> addFile($dump_buffer, substr($filename, 0, -4));
585 $dump_buffer = $zipfile -> file();
588 // 2. as a bzipped file
589 elseif ($compression == 'bzip') {
590 if (@function_exists('bzcompress')) {
591 $dump_buffer = bzcompress($dump_buffer);
594 // 3. as a gzipped file
595 elseif ($compression == 'gzip') {
596 if (@function_exists('gzencode')) {
597 // without the optional parameter level because it bug
598 $dump_buffer = gzencode($dump_buffer);
602 /* If ve saved on server, we have to close file now */
603 if ($save_on_server) {
604 $write_result = @fwrite($file_handle, $dump_buffer);
605 fclose($file_handle);
606 if (strlen($dump_buffer) !=0 && (!$write_result || ($write_result != strlen($dump_buffer)))) {
607 $message = new PMA_Message('strNoSpace', PMA_Message::ERROR, $save_filename);
608 } else {
609 $message = new PMA_Message('strDumpSaved', PMA_Message::SUCCESS, $save_filename);
612 $GLOBALS['js_include'][] = 'functions.js';
613 require_once './libraries/header.inc.php';
614 if ($export_type == 'server') {
615 $active_page = 'server_export.php';
616 require_once './server_export.php';
617 } elseif ($export_type == 'database') {
618 $active_page = 'db_export.php';
619 require_once './db_export.php';
620 } else {
621 $active_page = 'tbl_export.php';
622 require_once './tbl_export.php';
624 exit();
625 } else {
626 echo $dump_buffer;
630 * Displays the dump...
632 else {
634 * Close the html tags and add the footers in dump is displayed on screen
636 //echo ' </pre>' . "\n";
637 echo '</textarea>' . "\n"
638 . ' </form>' . "\n";
639 echo '</div>' . "\n";
640 echo "\n";
642 <script type="text/javascript">
643 //<![CDATA[
644 var bodyWidth=null; var bodyHeight=null;
645 if (document.getElementById('textSQLDUMP')) {
646 bodyWidth = self.innerWidth;
647 bodyHeight = self.innerHeight;
648 if (!bodyWidth && !bodyHeight) {
649 if (document.compatMode && document.compatMode == "BackCompat") {
650 bodyWidth = document.body.clientWidth;
651 bodyHeight = document.body.clientHeight;
652 } else if (document.compatMode && document.compatMode == "CSS1Compat") {
653 bodyWidth = document.documentElement.clientWidth;
654 bodyHeight = document.documentElement.clientHeight;
657 document.getElementById('textSQLDUMP').style.width=(bodyWidth-50) + 'px';
658 document.getElementById('textSQLDUMP').style.height=(bodyHeight-100) + 'px';
660 //]]>
661 </script>
662 <?php
663 require_once './libraries/footer.inc.php';
664 } // end if