Complete docs for controuser/controlpass.
[phpmyadmin/crack.git] / export.php
blob841926d046e7765a3a95e1f355a1f3ff6c9ea350
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 // (avoid rewriting data containing HTML with anchors and forms;
341 // this was reported to happen under Plesk)
342 ini_set('url_rewriter.tags','');
344 if (!empty($content_encoding)) {
345 header('Content-Encoding: ' . $content_encoding);
347 header('Content-Type: ' . $mime_type);
348 header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
349 // lem9: Tested behavior of
350 // IE 5.50.4807.2300
351 // IE 6.0.2800.1106 (small glitch, asks twice when I click Open)
352 // IE 6.0.2900.2180
353 // Firefox 1.0.6
354 // in http and https
355 header('Content-Disposition: attachment; filename="' . $filename . '"');
356 if (PMA_USR_BROWSER_AGENT == 'IE') {
357 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
358 header('Pragma: public');
359 } else {
360 header('Pragma: no-cache');
362 } else {
363 // HTML
364 if ($export_type == 'database') {
365 $num_tables = count($tables);
366 if ($num_tables == 0) {
367 $message = PMA_Message::error('strNoTablesFound');
368 $GLOBALS['js_include'][] = 'functions.js';
369 require_once './libraries/header.inc.php';
370 $active_page = 'db_export.php';
371 require './db_export.php';
372 exit();
375 $backup_cfgServer = $cfg['Server'];
376 require_once './libraries/header.inc.php';
377 $cfg['Server'] = $backup_cfgServer;
378 unset($backup_cfgServer);
379 echo "\n" . '<div align="' . $cell_align_left . '">' . "\n";
380 //echo ' <pre>' . "\n";
381 echo ' <form name="nofunction">' . "\n"
382 // remove auto-select for now: there is no way to select
383 // only a part of the text; anyway, it should obey
384 // $cfg['TextareaAutoSelect']
385 //. ' <textarea name="sqldump" cols="50" rows="30" onclick="this.select();" id="textSQLDUMP" wrap="OFF">' . "\n";
386 . ' <textarea name="sqldump" cols="50" rows="30" id="textSQLDUMP" wrap="OFF">' . "\n";
387 } // end download
390 // Fake loop just to allow skip of remain of this code by break, I'd really
391 // need exceptions here :-)
392 do {
394 // Add possibly some comments to export
395 if (!PMA_exportHeader()) {
396 break;
399 // Will we need relation & co. setup?
400 $do_relation = isset($GLOBALS[$what . '_relation']);
401 $do_comments = isset($GLOBALS[$what . '_comments']);
402 $do_mime = isset($GLOBALS[$what . '_mime']);
403 if ($do_relation || $do_comments || $do_mime) {
404 require_once './libraries/relation.lib.php';
405 $cfgRelation = PMA_getRelationsParam();
407 if ($do_mime) {
408 require_once './libraries/transformations.lib.php';
411 // Include dates in export?
412 $do_dates = isset($GLOBALS[$what . '_dates']);
415 * Builds the dump
417 // Gets the number of tables if a dump of a database has been required
418 if ($export_type == 'server') {
419 if (isset($db_select)) {
420 $tmp_select = implode($db_select, '|');
421 $tmp_select = '|' . $tmp_select . '|';
423 // Walk over databases
424 foreach ($GLOBALS['pma']->databases as $current_db) {
425 if ((isset($tmp_select) && strpos(' ' . $tmp_select, '|' . $current_db . '|'))
426 || !isset($tmp_select)) {
427 if (!PMA_exportDBHeader($current_db)) {
428 break 2;
430 if (!PMA_exportDBCreate($current_db)) {
431 break 2;
433 $tables = PMA_DBI_get_tables($current_db);
434 $views = array();
435 foreach ($tables as $table) {
436 // if this is a view, collect it for later; views must be exported
437 // after the tables
438 $is_view = PMA_Table::isView($current_db, $table);
439 if ($is_view) {
440 $views[] = $table;
442 if (isset($GLOBALS[$what . '_structure'])) {
443 // for a view, export a stand-in definition of the table
444 // to resolve view dependencies
445 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)) {
446 break 3;
449 if (isset($GLOBALS[$what . '_data']) && ! $is_view) {
450 $local_query = 'SELECT * FROM ' . PMA_backquote($current_db) . '.' . PMA_backquote($table);
451 if (!PMA_exportData($current_db, $table, $crlf, $err_url, $local_query)) {
452 break 3;
456 foreach($views as $view) {
457 // no data export for a view
458 if (isset($GLOBALS[$what . '_structure'])) {
459 if (!PMA_exportStructure($current_db, $view, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, 'create_view', $export_type)) {
460 break 3;
464 if (!PMA_exportDBFooter($current_db)) {
465 break 2;
469 } elseif ($export_type == 'database') {
470 if (!PMA_exportDBHeader($db)) {
471 break;
473 $i = 0;
474 $views = array();
475 // $tables contains the choices from the user (via $table_select)
476 foreach ($tables as $table) {
477 // if this is a view, collect it for later; views must be exported after
478 // the tables
479 $is_view = PMA_Table::isView($db, $table);
480 if ($is_view) {
481 $views[] = $table;
483 if (isset($GLOBALS[$what . '_structure'])) {
484 // for a view, export a stand-in definition of the table
485 // to resolve view dependencies
486 if (!PMA_exportStructure($db, $table, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, $is_view ? 'stand_in' : 'create_table', $export_type)) {
487 break 2;
490 if (isset($GLOBALS[$what . '_data']) && ! $is_view) {
491 $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table);
492 if (!PMA_exportData($db, $table, $crlf, $err_url, $local_query)) {
493 break 2;
497 foreach ($views as $view) {
498 // no data export for a view
499 if (isset($GLOBALS[$what . '_structure'])) {
500 if (!PMA_exportStructure($db, $view, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, 'create_view', $export_type)) {
501 break 2;
506 if (!PMA_exportDBFooter($db)) {
507 break;
509 } else {
510 if (!PMA_exportDBHeader($db)) {
511 break;
513 // We export just one table
515 if ($limit_to > 0 && $limit_from >= 0) {
516 $add_query = ' LIMIT '
517 . (($limit_from > 0) ? $limit_from . ', ' : '')
518 . $limit_to;
519 } else {
520 $add_query = '';
523 $is_view = PMA_Table::isView($db, $table);
524 if (isset($GLOBALS[$what . '_structure'])) {
525 if (!PMA_exportStructure($db, $table, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, $is_view ? 'create_view' : 'create_table', $export_type)) {
526 break;
529 // If this is an export of a single view, we have to export data;
530 // for example, a PDF report
531 if (isset($GLOBALS[$what . '_data'])) {
532 if (!empty($sql_query)) {
533 // only preg_replace if needed
534 if (!empty($add_query)) {
535 // remove trailing semicolon before adding a LIMIT
536 $sql_query = preg_replace('%;\s*$%', '', $sql_query);
538 $local_query = $sql_query . $add_query;
539 PMA_DBI_select_db($db);
540 } else {
541 $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table) . $add_query;
543 if (!PMA_exportData($db, $table, $crlf, $err_url, $local_query)) {
544 break;
547 if (!PMA_exportDBFooter($db)) {
548 break;
551 if (!PMA_exportFooter()) {
552 break;
555 } while (false);
556 // End of fake loop
558 if ($save_on_server && isset($message)) {
559 $GLOBALS['js_include'][] = 'functions.js';
560 require_once './libraries/header.inc.php';
561 if ($export_type == 'server') {
562 $active_page = 'server_export.php';
563 require './server_export.php';
564 } elseif ($export_type == 'database') {
565 $active_page = 'db_export.php';
566 require './db_export.php';
567 } else {
568 $active_page = 'tbl_export.php';
569 require './tbl_export.php';
571 exit();
575 * Send the dump as a file...
577 if (!empty($asfile)) {
578 // Convert the charset if required.
579 if ($output_charset_conversion) {
580 $dump_buffer = PMA_convert_string($GLOBALS['charset'], $GLOBALS['charset_of_file'], $dump_buffer);
583 // Do the compression
584 // 1. as a gzipped file
585 if ($compression == 'zip') {
586 if (@function_exists('gzcompress')) {
587 $zipfile = new zipfile();
588 $zipfile -> addFile($dump_buffer, substr($filename, 0, -4));
589 $dump_buffer = $zipfile -> file();
592 // 2. as a bzipped file
593 elseif ($compression == 'bzip') {
594 if (@function_exists('bzcompress')) {
595 $dump_buffer = bzcompress($dump_buffer);
598 // 3. as a gzipped file
599 elseif ($compression == 'gzip') {
600 if (@function_exists('gzencode')) {
601 // without the optional parameter level because it bug
602 $dump_buffer = gzencode($dump_buffer);
606 /* If ve saved on server, we have to close file now */
607 if ($save_on_server) {
608 $write_result = @fwrite($file_handle, $dump_buffer);
609 fclose($file_handle);
610 if (strlen($dump_buffer) !=0 && (!$write_result || ($write_result != strlen($dump_buffer)))) {
611 $message = new PMA_Message('strNoSpace', PMA_Message::ERROR, $save_filename);
612 } else {
613 $message = new PMA_Message('strDumpSaved', PMA_Message::SUCCESS, $save_filename);
616 $GLOBALS['js_include'][] = 'functions.js';
617 require_once './libraries/header.inc.php';
618 if ($export_type == 'server') {
619 $active_page = 'server_export.php';
620 require_once './server_export.php';
621 } elseif ($export_type == 'database') {
622 $active_page = 'db_export.php';
623 require_once './db_export.php';
624 } else {
625 $active_page = 'tbl_export.php';
626 require_once './tbl_export.php';
628 exit();
629 } else {
630 echo $dump_buffer;
634 * Displays the dump...
636 else {
638 * Close the html tags and add the footers in dump is displayed on screen
640 //echo ' </pre>' . "\n";
641 echo '</textarea>' . "\n"
642 . ' </form>' . "\n";
643 echo '</div>' . "\n";
644 echo "\n";
646 <script type="text/javascript">
647 //<![CDATA[
648 var bodyWidth=null; var bodyHeight=null;
649 if (document.getElementById('textSQLDUMP')) {
650 bodyWidth = self.innerWidth;
651 bodyHeight = self.innerHeight;
652 if (!bodyWidth && !bodyHeight) {
653 if (document.compatMode && document.compatMode == "BackCompat") {
654 bodyWidth = document.body.clientWidth;
655 bodyHeight = document.body.clientHeight;
656 } else if (document.compatMode && document.compatMode == "CSS1Compat") {
657 bodyWidth = document.documentElement.clientWidth;
658 bodyHeight = document.documentElement.clientHeight;
661 document.getElementById('textSQLDUMP').style.width=(bodyWidth-50) + 'px';
662 document.getElementById('textSQLDUMP').style.height=(bodyHeight-100) + 'px';
664 //]]>
665 </script>
666 <?php
667 require_once './libraries/footer.inc.php';
668 } // end if