bug #2568722 [designer] Compound key not shown
[phpmyadmin/crack.git] / export.php
blob666cbd06878c797f8df28623b3fb147893defe80
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 && $cfg['AllowAnywhereRecoding']
210 && isset($charset_of_file) && $charset_of_file != $charset
211 && $type != 'xls';
213 // Use on the fly compression?
214 $onfly_compression = $GLOBALS['cfg']['CompressOnFly'] && ($compression == 'gzip' || $compression == 'bzip');
215 if ($onfly_compression) {
216 $memory_limit = trim(@ini_get('memory_limit'));
217 // 2 MB as default
218 if (empty($memory_limit)) {
219 $memory_limit = 2 * 1024 * 1024;
222 if (strtolower(substr($memory_limit, -1)) == 'm') {
223 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
224 } elseif (strtolower(substr($memory_limit, -1)) == 'k') {
225 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
226 } elseif (strtolower(substr($memory_limit, -1)) == 'g') {
227 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
228 } else {
229 $memory_limit = (int)$memory_limit;
232 // Some of memory is needed for other thins and as treshold.
233 // Nijel: During export I had allocated (see memory_get_usage function)
234 // approx 1.2MB so this comes from that.
235 if ($memory_limit > 1500000) {
236 $memory_limit -= 1500000;
239 // Some memory is needed for compression, assume 1/3
240 $memory_limit /= 8;
243 // Generate filename and mime type if needed
244 if ($asfile) {
245 $pma_uri_parts = parse_url($cfg['PmaAbsoluteUri']);
246 if ($export_type == 'server') {
247 if (isset($remember_template)) {
248 PMA_setCookie('pma_server_filename_template', $filename_template);
250 $filename = str_replace('__SERVER__', $GLOBALS['cfg']['Server']['host'], strftime($filename_template));
251 } elseif ($export_type == 'database') {
252 if (isset($remember_template)) {
253 PMA_setCookie('pma_db_filename_template', $filename_template);
255 $filename = str_replace('__DB__', $db, str_replace('__SERVER__', $GLOBALS['cfg']['Server']['host'], strftime($filename_template)));
256 } else {
257 if (isset($remember_template)) {
258 PMA_setCookie('pma_table_filename_template', $filename_template);
260 $filename = str_replace('__TABLE__', $table, str_replace('__DB__', $db, str_replace('__SERVER__', $GLOBALS['cfg']['Server']['host'], strftime($filename_template))));
263 // convert filename to iso-8859-1, it is safer
264 if (!(isset($cfg['AllowAnywhereRecoding']) && $cfg['AllowAnywhereRecoding'] )) {
265 $filename = PMA_convert_string($charset, 'iso-8859-1', $filename);
266 } else {
267 $filename = PMA_convert_string($convcharset, 'iso-8859-1', $filename);
270 // Grab basic dump extension and mime type
271 $filename .= '.' . $export_list[$type]['extension'];
272 $mime_type = $export_list[$type]['mime_type'];
274 // If dump is going to be compressed, set correct encoding or mime_type and add
275 // compression to extension
276 $content_encoding = '';
277 if ($compression == 'bzip') {
278 $filename .= '.bz2';
279 // browsers don't like this:
280 //$content_encoding = 'x-bzip2';
281 $mime_type = 'application/x-bzip2';
282 } elseif ($compression == 'gzip') {
283 $filename .= '.gz';
284 // Needed to avoid recompression by server modules like mod_gzip.
285 // It seems necessary to check about zlib.output_compression
286 // to avoid compressing twice
287 if (!@ini_get('zlib.output_compression')) {
288 // On Firefox 3, sending this content encoding corrupts the .gz
289 // (as tested on Windows and Linux) but detect GECKO 1.9
290 if (! (PMA_USR_BROWSER_AGENT == 'GECKO' && PMA_USR_BROWSER_VER == '1.9')) {
291 $content_encoding = 'x-gzip';
293 $mime_type = 'application/x-gzip';
295 } elseif ($compression == 'zip') {
296 $filename .= '.zip';
297 $mime_type = 'application/zip';
301 // Open file on server if needed
302 if ($save_on_server) {
303 $save_filename = PMA_userDir($cfg['SaveDir']) . preg_replace('@[/\\\\]@', '_', $filename);
304 unset($message);
305 if (file_exists($save_filename) && empty($onserverover)) {
306 $message = PMA_Message::error('strFileAlreadyExists');
307 $message->addParam($save_filename);
308 } else {
309 if (is_file($save_filename) && !is_writable($save_filename)) {
310 $message = PMA_Message::error('strNoPermission');
311 $message->addParam($save_filename);
312 } else {
313 if (!$file_handle = @fopen($save_filename, 'w')) {
314 $message = PMA_Message::error('strNoPermission');
315 $message->addParam($save_filename);
319 if (isset($message)) {
320 $GLOBALS['js_include'][] = 'functions.js';
321 require_once './libraries/header.inc.php';
322 if ($export_type == 'server') {
323 $active_page = 'server_export.php';
324 require './server_export.php';
325 } elseif ($export_type == 'database') {
326 $active_page = 'db_export.php';
327 require './db_export.php';
328 } else {
329 $active_page = 'tbl_export.php';
330 require './tbl_export.php';
332 exit();
337 * Send headers depending on whether the user chose to download a dump file
338 * or not
340 if (!$save_on_server) {
341 if ($asfile) {
342 // Download
343 // (avoid rewriting data containing HTML with anchors and forms;
344 // this was reported to happen under Plesk)
345 @ini_set('url_rewriter.tags','');
347 if (!empty($content_encoding)) {
348 header('Content-Encoding: ' . $content_encoding);
350 header('Content-Type: ' . $mime_type);
351 header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
352 // lem9: Tested behavior of
353 // IE 5.50.4807.2300
354 // IE 6.0.2800.1106 (small glitch, asks twice when I click Open)
355 // IE 6.0.2900.2180
356 // Firefox 1.0.6
357 // in http and https
358 header('Content-Disposition: attachment; filename="' . $filename . '"');
359 if (PMA_USR_BROWSER_AGENT == 'IE') {
360 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
361 header('Pragma: public');
362 } else {
363 header('Pragma: no-cache');
364 // test case: exporting a database into a .gz file with Safari
365 // would produce files not having the current time
366 // (added this header for Safari but should not harm other browsers)
367 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
369 } else {
370 // HTML
371 if ($export_type == 'database') {
372 $num_tables = count($tables);
373 if ($num_tables == 0) {
374 $message = PMA_Message::error('strNoTablesFound');
375 $GLOBALS['js_include'][] = 'functions.js';
376 require_once './libraries/header.inc.php';
377 $active_page = 'db_export.php';
378 require './db_export.php';
379 exit();
382 $backup_cfgServer = $cfg['Server'];
383 require_once './libraries/header.inc.php';
384 $cfg['Server'] = $backup_cfgServer;
385 unset($backup_cfgServer);
386 echo "\n" . '<div align="' . $cell_align_left . '">' . "\n";
387 //echo ' <pre>' . "\n";
388 echo ' <form name="nofunction">' . "\n"
389 // remove auto-select for now: there is no way to select
390 // only a part of the text; anyway, it should obey
391 // $cfg['TextareaAutoSelect']
392 //. ' <textarea name="sqldump" cols="50" rows="30" onclick="this.select();" id="textSQLDUMP" wrap="OFF">' . "\n";
393 . ' <textarea name="sqldump" cols="50" rows="30" id="textSQLDUMP" wrap="OFF">' . "\n";
394 } // end download
397 // Fake loop just to allow skip of remain of this code by break, I'd really
398 // need exceptions here :-)
399 do {
401 // Add possibly some comments to export
402 if (!PMA_exportHeader()) {
403 break;
406 // Will we need relation & co. setup?
407 $do_relation = isset($GLOBALS[$what . '_relation']);
408 $do_comments = isset($GLOBALS[$what . '_comments']);
409 $do_mime = isset($GLOBALS[$what . '_mime']);
410 if ($do_relation || $do_comments || $do_mime) {
411 require_once './libraries/relation.lib.php';
412 $cfgRelation = PMA_getRelationsParam();
414 if ($do_mime) {
415 require_once './libraries/transformations.lib.php';
418 // Include dates in export?
419 $do_dates = isset($GLOBALS[$what . '_dates']);
422 * Builds the dump
424 // Gets the number of tables if a dump of a database has been required
425 if ($export_type == 'server') {
426 if (isset($db_select)) {
427 $tmp_select = implode($db_select, '|');
428 $tmp_select = '|' . $tmp_select . '|';
430 // Walk over databases
431 foreach ($GLOBALS['pma']->databases as $current_db) {
432 if ((isset($tmp_select) && strpos(' ' . $tmp_select, '|' . $current_db . '|'))
433 || !isset($tmp_select)) {
434 if (!PMA_exportDBHeader($current_db)) {
435 break 2;
437 if (!PMA_exportDBCreate($current_db)) {
438 break 2;
440 $tables = PMA_DBI_get_tables($current_db);
441 $views = array();
442 foreach ($tables as $table) {
443 // if this is a view, collect it for later; views must be exported
444 // after the tables
445 $is_view = PMA_Table::isView($current_db, $table);
446 if ($is_view) {
447 $views[] = $table;
449 if (isset($GLOBALS[$what . '_structure'])) {
450 // for a view, export a stand-in definition of the table
451 // to resolve view dependencies
452 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)) {
453 break 3;
456 if (isset($GLOBALS[$what . '_data']) && ! $is_view) {
457 $local_query = 'SELECT * FROM ' . PMA_backquote($current_db) . '.' . PMA_backquote($table);
458 if (!PMA_exportData($current_db, $table, $crlf, $err_url, $local_query)) {
459 break 3;
463 foreach($views as $view) {
464 // no data export for a view
465 if (isset($GLOBALS[$what . '_structure'])) {
466 if (!PMA_exportStructure($current_db, $view, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, 'create_view', $export_type)) {
467 break 3;
471 if (!PMA_exportDBFooter($current_db)) {
472 break 2;
476 } elseif ($export_type == 'database') {
477 if (!PMA_exportDBHeader($db)) {
478 break;
480 $i = 0;
481 $views = array();
482 // $tables contains the choices from the user (via $table_select)
483 foreach ($tables as $table) {
484 // if this is a view, collect it for later; views must be exported after
485 // the tables
486 $is_view = PMA_Table::isView($db, $table);
487 if ($is_view) {
488 $views[] = $table;
490 if (isset($GLOBALS[$what . '_structure'])) {
491 // for a view, export a stand-in definition of the table
492 // to resolve view dependencies
493 if (!PMA_exportStructure($db, $table, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, $is_view ? 'stand_in' : 'create_table', $export_type)) {
494 break 2;
497 if (isset($GLOBALS[$what . '_data']) && ! $is_view) {
498 $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table);
499 if (!PMA_exportData($db, $table, $crlf, $err_url, $local_query)) {
500 break 2;
504 foreach ($views as $view) {
505 // no data export for a view
506 if (isset($GLOBALS[$what . '_structure'])) {
507 if (!PMA_exportStructure($db, $view, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, 'create_view', $export_type)) {
508 break 2;
513 if (!PMA_exportDBFooter($db)) {
514 break;
516 } else {
517 if (!PMA_exportDBHeader($db)) {
518 break;
520 // We export just one table
522 if ($limit_to > 0 && $limit_from >= 0) {
523 $add_query = ' LIMIT '
524 . (($limit_from > 0) ? $limit_from . ', ' : '')
525 . $limit_to;
526 } else {
527 $add_query = '';
530 $is_view = PMA_Table::isView($db, $table);
531 if (isset($GLOBALS[$what . '_structure'])) {
532 if (!PMA_exportStructure($db, $table, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, $is_view ? 'create_view' : 'create_table', $export_type)) {
533 break;
536 // If this is an export of a single view, we have to export data;
537 // for example, a PDF report
538 if (isset($GLOBALS[$what . '_data'])) {
539 if (!empty($sql_query)) {
540 // only preg_replace if needed
541 if (!empty($add_query)) {
542 // remove trailing semicolon before adding a LIMIT
543 $sql_query = preg_replace('%;\s*$%', '', $sql_query);
545 $local_query = $sql_query . $add_query;
546 PMA_DBI_select_db($db);
547 } else {
548 $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table) . $add_query;
550 if (!PMA_exportData($db, $table, $crlf, $err_url, $local_query)) {
551 break;
554 if (!PMA_exportDBFooter($db)) {
555 break;
558 if (!PMA_exportFooter()) {
559 break;
562 } while (false);
563 // End of fake loop
565 if ($save_on_server && isset($message)) {
566 $GLOBALS['js_include'][] = 'functions.js';
567 require_once './libraries/header.inc.php';
568 if ($export_type == 'server') {
569 $active_page = 'server_export.php';
570 require './server_export.php';
571 } elseif ($export_type == 'database') {
572 $active_page = 'db_export.php';
573 require './db_export.php';
574 } else {
575 $active_page = 'tbl_export.php';
576 require './tbl_export.php';
578 exit();
582 * Send the dump as a file...
584 if (!empty($asfile)) {
585 // Convert the charset if required.
586 if ($output_charset_conversion) {
587 $dump_buffer = PMA_convert_string($GLOBALS['charset'], $GLOBALS['charset_of_file'], $dump_buffer);
590 // Do the compression
591 // 1. as a zipped file
592 if ($compression == 'zip') {
593 if (@function_exists('gzcompress')) {
594 $zipfile = new zipfile();
595 $zipfile -> addFile($dump_buffer, substr($filename, 0, -4));
596 $dump_buffer = $zipfile -> file();
599 // 2. as a bzipped file
600 elseif ($compression == 'bzip') {
601 if (@function_exists('bzcompress')) {
602 $dump_buffer = bzcompress($dump_buffer);
605 // 3. as a gzipped file
606 elseif ($compression == 'gzip') {
607 if (@function_exists('gzencode')) {
608 // without the optional parameter level because it bug
609 $dump_buffer = gzencode($dump_buffer);
613 /* If ve saved on server, we have to close file now */
614 if ($save_on_server) {
615 $write_result = @fwrite($file_handle, $dump_buffer);
616 fclose($file_handle);
617 if (strlen($dump_buffer) !=0 && (!$write_result || ($write_result != strlen($dump_buffer)))) {
618 $message = new PMA_Message('strNoSpace', PMA_Message::ERROR, $save_filename);
619 } else {
620 $message = new PMA_Message('strDumpSaved', PMA_Message::SUCCESS, $save_filename);
623 $GLOBALS['js_include'][] = 'functions.js';
624 require_once './libraries/header.inc.php';
625 if ($export_type == 'server') {
626 $active_page = 'server_export.php';
627 require_once './server_export.php';
628 } elseif ($export_type == 'database') {
629 $active_page = 'db_export.php';
630 require_once './db_export.php';
631 } else {
632 $active_page = 'tbl_export.php';
633 require_once './tbl_export.php';
635 exit();
636 } else {
637 echo $dump_buffer;
641 * Displays the dump...
643 else {
645 * Close the html tags and add the footers in dump is displayed on screen
647 //echo ' </pre>' . "\n";
648 echo '</textarea>' . "\n"
649 . ' </form>' . "\n";
650 echo '</div>' . "\n";
651 echo "\n";
653 <script type="text/javascript">
654 //<![CDATA[
655 var bodyWidth=null; var bodyHeight=null;
656 if (document.getElementById('textSQLDUMP')) {
657 bodyWidth = self.innerWidth;
658 bodyHeight = self.innerHeight;
659 if (!bodyWidth && !bodyHeight) {
660 if (document.compatMode && document.compatMode == "BackCompat") {
661 bodyWidth = document.body.clientWidth;
662 bodyHeight = document.body.clientHeight;
663 } else if (document.compatMode && document.compatMode == "CSS1Compat") {
664 bodyWidth = document.documentElement.clientWidth;
665 bodyHeight = document.documentElement.clientHeight;
668 document.getElementById('textSQLDUMP').style.width=(bodyWidth-50) + 'px';
669 document.getElementById('textSQLDUMP').style.height=(bodyHeight-100) + 'px';
671 //]]>
672 </script>
673 <?php
674 require_once './libraries/footer.inc.php';
675 } // end if