Leveraged Andy's Installer class to automate installation of
[openemr.git] / phpmyadmin / export.php
blob1d22a302881d96433b7ae1bef0dbb5a18c6f5033
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 = $strExportMustBeFile;
62 $GLOBALS['show_error_header'] = true;
63 $js_to_run = 'functions.js';
64 require_once './libraries/header.inc.php';
65 if ($export_type == 'server') {
66 $active_page = 'server_export.php';
67 require './server_export.php';
68 } elseif ($export_type == 'database') {
69 $active_page = 'db_export.php';
70 require './db_export.php';
71 } else {
72 $active_page = 'tbl_export.php';
73 require './tbl_export.php';
75 exit();
78 // Generate error url and check for needed variables
79 if ($export_type == 'server') {
80 $err_url = 'server_export.php?' . PMA_generate_common_url();
81 } elseif ($export_type == 'database' && strlen($db)) {
82 $err_url = 'db_export.php?' . PMA_generate_common_url($db);
83 // Check if we have something to export
84 if (isset($table_select)) {
85 $tables = $table_select;
86 } else {
87 $tables = array();
89 } elseif ($export_type == 'table' && strlen($db) && strlen($table)) {
90 $err_url = 'tbl_export.php?' . PMA_generate_common_url($db, $table);
91 } else {
92 die('Bad parameters!');
95 // Get the functions specific to the export type
96 require './libraries/export/' . PMA_securePath($type) . '.php';
98 /**
99 * Increase time limit for script execution and initializes some variables
101 @set_time_limit($cfg['ExecTimeLimit']);
102 if (!empty($cfg['MemoryLimit'])) {
103 @ini_set('memory_limit', $cfg['MemoryLimit']);
106 // Start with empty buffer
107 $dump_buffer = '';
108 $dump_buffer_len = 0;
110 // We send fake headers to avoid browser timeout when buffering
111 $time_start = time();
115 * Output handler for all exports, if needed buffering, it stores data into
116 * $dump_buffer, otherwise it prints thems out.
118 * @param string the insert statement
120 * @return bool Whether output suceeded
122 function PMA_exportOutputHandler($line)
124 global $time_start, $dump_buffer, $dump_buffer_len, $save_filename;
126 // Kanji encoding convert feature
127 if ($GLOBALS['output_kanji_conversion']) {
128 $line = PMA_kanji_str_conv($line, $GLOBALS['knjenc'], isset($GLOBALS['xkana']) ? $GLOBALS['xkana'] : '');
130 // If we have to buffer data, we will perform everything at once at the end
131 if ($GLOBALS['buffer_needed']) {
133 $dump_buffer .= $line;
134 if ($GLOBALS['onfly_compression']) {
136 $dump_buffer_len += strlen($line);
138 if ($dump_buffer_len > $GLOBALS['memory_limit']) {
139 if ($GLOBALS['output_charset_conversion']) {
140 $dump_buffer = PMA_convert_string($GLOBALS['charset'], $GLOBALS['charset_of_file'], $dump_buffer);
142 // as bzipped
143 if ($GLOBALS['compression'] == 'bzip' && @function_exists('bzcompress')) {
144 $dump_buffer = bzcompress($dump_buffer);
146 // as a gzipped file
147 elseif ($GLOBALS['compression'] == 'gzip' && @function_exists('gzencode')) {
148 // without the optional parameter level because it bug
149 $dump_buffer = gzencode($dump_buffer);
151 if ($GLOBALS['save_on_server']) {
152 $write_result = @fwrite($GLOBALS['file_handle'], $dump_buffer);
153 if (!$write_result || ($write_result != strlen($dump_buffer))) {
154 $GLOBALS['message'] = sprintf($GLOBALS['strNoSpace'], htmlspecialchars($save_filename));
155 $GLOBALS['show_error_header'] = true;
156 return false;
158 } else {
159 echo $dump_buffer;
161 $dump_buffer = '';
162 $dump_buffer_len = 0;
164 } else {
165 $time_now = time();
166 if ($time_start >= $time_now + 30) {
167 $time_start = $time_now;
168 header('X-pmaPing: Pong');
169 } // end if
171 } else {
172 if ($GLOBALS['asfile']) {
173 if ($GLOBALS['output_charset_conversion']) {
174 $line = PMA_convert_string($GLOBALS['charset'], $GLOBALS['charset_of_file'], $line);
176 if ($GLOBALS['save_on_server'] && strlen($line) > 0) {
177 $write_result = @fwrite($GLOBALS['file_handle'], $line);
178 if (!$write_result || ($write_result != strlen($line))) {
179 $GLOBALS['message'] = sprintf($GLOBALS['strNoSpace'], htmlspecialchars($save_filename));
180 $GLOBALS['show_error_header'] = true;
181 return false;
183 $time_now = time();
184 if ($time_start >= $time_now + 30) {
185 $time_start = $time_now;
186 header('X-pmaPing: Pong');
187 } // end if
188 } else {
189 // We export as file - output normally
190 echo $line;
192 } else {
193 // We export as html - replace special chars
194 echo htmlspecialchars($line);
197 return true;
198 } // end of the 'PMA_exportOutputHandler()' function
200 // Defines the default <CR><LF> format. For SQL always use \n as MySQL wants this on all platforms.
201 if ($what == 'sql') {
202 $crlf = "\n";
203 } else {
204 $crlf = PMA_whichCrlf();
207 $output_kanji_conversion = function_exists('PMA_kanji_str_conv') && $type != 'xls';
209 // Do we need to convert charset?
210 $output_charset_conversion = $asfile &&
211 $cfg['AllowAnywhereRecoding'] && $allow_recoding
212 && isset($charset_of_file) && $charset_of_file != $charset
213 && $type != 'xls';
215 // Use on fly compression?
216 $onfly_compression = $GLOBALS['cfg']['CompressOnFly'] && ($compression == 'gzip' | $compression == 'bzip');
217 if ($onfly_compression) {
218 $memory_limit = trim(@ini_get('memory_limit'));
219 // 2 MB as default
220 if (empty($memory_limit)) {
221 $memory_limit = 2 * 1024 * 1024;
224 if (strtolower(substr($memory_limit, -1)) == 'm') {
225 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
226 } elseif (strtolower(substr($memory_limit, -1)) == 'k') {
227 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
228 } elseif (strtolower(substr($memory_limit, -1)) == 'g') {
229 $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
230 } else {
231 $memory_limit = (int)$memory_limit;
234 // Some of memory is needed for other thins and as treshold.
235 // Nijel: During export I had allocated (see memory_get_usage function)
236 // approx 1.2MB so this comes from that.
237 if ($memory_limit > 1500000) {
238 $memory_limit -= 1500000;
241 // Some memory is needed for compression, assume 1/3
242 $memory_limit /= 8;
245 // Generate filename and mime type if needed
246 if ($asfile) {
247 $pma_uri_parts = parse_url($cfg['PmaAbsoluteUri']);
248 if ($export_type == 'server') {
249 if (isset($remember_template)) {
250 PMA_setCookie('pma_server_filename_template', $filename_template);
252 $filename = str_replace('__SERVER__', $GLOBALS['cfg']['Server']['host'], strftime($filename_template));
253 } elseif ($export_type == 'database') {
254 if (isset($remember_template)) {
255 PMA_setCookie('pma_db_filename_template', $filename_template);
257 $filename = str_replace('__DB__', $db, str_replace('__SERVER__', $GLOBALS['cfg']['Server']['host'], strftime($filename_template)));
258 } else {
259 if (isset($remember_template)) {
260 PMA_setCookie('pma_table_filename_template', $filename_template);
262 $filename = str_replace('__TABLE__', $table, str_replace('__DB__', $db, str_replace('__SERVER__', $GLOBALS['cfg']['Server']['host'], strftime($filename_template))));
265 // convert filename to iso-8859-1, it is safer
266 if (!(isset($cfg['AllowAnywhereRecoding']) && $cfg['AllowAnywhereRecoding'] && $allow_recoding)) {
267 $filename = PMA_convert_string($charset, 'iso-8859-1', $filename);
268 } else {
269 $filename = PMA_convert_string($convcharset, 'iso-8859-1', $filename);
272 // Grab basic dump extension and mime type
273 $filename .= '.' . $export_list[$type]['extension'];
274 $mime_type = $export_list[$type]['mime_type'];
276 // If dump is going to be compressed, set correct encoding or mime_type and add
277 // compression to extension
278 $content_encoding = '';
279 if ($compression == 'bzip') {
280 $filename .= '.bz2';
281 // browsers don't like this:
282 //$content_encoding = 'x-bzip2';
283 $mime_type = 'application/x-bzip2';
284 } elseif ($compression == 'gzip') {
285 $filename .= '.gz';
286 // Needed to avoid recompression by server modules like mod_gzip.
287 // It seems necessary to check about zlib.output_compression
288 // to avoid compressing twice
289 if (!@ini_get('zlib.output_compression')) {
290 // On Firefox 3, sending this content encoding corrupts the .gz
291 // (as tested on Windows and Linux) but detect GECKO 1.9
292 if (! (PMA_USR_BROWSER_AGENT == 'GECKO' && PMA_USR_BROWSER_VER == '1.9')) {
293 $content_encoding = 'x-gzip';
295 $mime_type = 'application/x-gzip';
297 } elseif ($compression == 'zip') {
298 $filename .= '.zip';
299 $mime_type = 'application/zip';
303 // Open file on server if needed
304 if ($save_on_server) {
305 $save_filename = PMA_userDir($cfg['SaveDir']) . preg_replace('@[/\\\\]@', '_', $filename);
306 unset($message);
307 if (file_exists($save_filename) && empty($onserverover)) {
308 $message = sprintf($strFileAlreadyExists, htmlspecialchars($save_filename));
309 $GLOBALS['show_error_header'] = true;
310 } else {
311 if (is_file($save_filename) && !is_writable($save_filename)) {
312 $message = sprintf($strNoPermission, htmlspecialchars($save_filename));
313 $GLOBALS['show_error_header'] = true;
314 } else {
315 if (!$file_handle = @fopen($save_filename, 'w')) {
316 $message = sprintf($strNoPermission, htmlspecialchars($save_filename));
317 $GLOBALS['show_error_header'] = true;
321 if (isset($message)) {
322 $js_to_run = 'functions.js';
323 require_once './libraries/header.inc.php';
324 if ($export_type == 'server') {
325 $active_page = 'server_export.php';
326 require './server_export.php';
327 } elseif ($export_type == 'database') {
328 $active_page = 'db_export.php';
329 require './db_export.php';
330 } else {
331 $active_page = 'tbl_export.php';
332 require './tbl_export.php';
334 exit();
339 * Send headers depending on whether the user chose to download a dump file
340 * or not
342 if (!$save_on_server) {
343 if ($asfile) {
344 // Download
345 // (avoid rewriting data containing HTML with anchors and forms;
346 // this was reported to happen under Plesk)
347 @ini_set('url_rewriter.tags','');
349 if (!empty($content_encoding)) {
350 header('Content-Encoding: ' . $content_encoding);
352 header('Content-Type: ' . $mime_type);
353 header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
354 // lem9: Tested behavior of
355 // IE 5.50.4807.2300
356 // IE 6.0.2800.1106 (small glitch, asks twice when I click Open)
357 // IE 6.0.2900.2180
358 // Firefox 1.0.6
359 // in http and https
360 header('Content-Disposition: attachment; filename="' . $filename . '"');
361 if (PMA_USR_BROWSER_AGENT == 'IE') {
362 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
363 header('Pragma: public');
364 } else {
365 header('Pragma: no-cache');
366 // test case: exporting a database into a .gz file with Safari
367 // would produce files not having the current time
368 if ('SAFARI' == PMA_USR_BROWSER_AGENT) {
369 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
372 } else {
373 // HTML
374 if ($export_type == 'database') {
375 $num_tables = count($tables);
376 if ($num_tables == 0) {
377 $message = $strNoTablesFound;
378 $js_to_run = 'functions.js';
379 require_once './libraries/header.inc.php';
380 $active_page = 'db_export.php';
381 require './db_export.php';
382 exit();
385 $backup_cfgServer = $cfg['Server'];
386 require_once './libraries/header.inc.php';
387 $cfg['Server'] = $backup_cfgServer;
388 unset($backup_cfgServer);
389 echo "\n" . '<div align="' . $cell_align_left . '">' . "\n";
390 //echo ' <pre>' . "\n";
391 echo ' <form name="nofunction">' . "\n"
392 // remove auto-select for now: there is no way to select
393 // only a part of the text; anyway, it should obey
394 // $cfg['TextareaAutoSelect']
395 //. ' <textarea name="sqldump" cols="50" rows="30" onclick="this.select();" id="textSQLDUMP" wrap="OFF">' . "\n";
396 . ' <textarea name="sqldump" cols="50" rows="30" id="textSQLDUMP" wrap="OFF">' . "\n";
397 } // end download
400 // Fake loop just to allow skip of remain of this code by break, I'd really
401 // need exceptions here :-)
402 do {
404 // Add possibly some comments to export
405 if (!PMA_exportHeader()) {
406 break;
409 // Will we need relation & co. setup?
410 $do_relation = isset($GLOBALS[$what . '_relation']);
411 $do_comments = isset($GLOBALS[$what . '_comments']);
412 $do_mime = isset($GLOBALS[$what . '_mime']);
413 if ($do_relation || $do_comments || $do_mime) {
414 require_once './libraries/relation.lib.php';
415 $cfgRelation = PMA_getRelationsParam();
417 if ($do_mime) {
418 require_once './libraries/transformations.lib.php';
421 // Include dates in export?
422 $do_dates = isset($GLOBALS[$what . '_dates']);
425 * Builds the dump
427 // Gets the number of tables if a dump of a database has been required
428 if ($export_type == 'server') {
429 if (isset($db_select)) {
430 $tmp_select = implode($db_select, '|');
431 $tmp_select = '|' . $tmp_select . '|';
433 // Walk over databases
434 foreach ($GLOBALS['PMA_List_Database']->items as $current_db) {
435 if ((isset($tmp_select) && strpos(' ' . $tmp_select, '|' . $current_db . '|'))
436 || !isset($tmp_select)) {
437 if (!PMA_exportDBHeader($current_db)) {
438 break 2;
440 if (!PMA_exportDBCreate($current_db)) {
441 break 2;
443 $tables = PMA_DBI_get_tables($current_db);
444 $views = array();
445 foreach ($tables as $table) {
446 // if this is a view, collect it for later; views must be exported
447 // after the tables
448 $is_view = PMA_Table::isView($current_db, $table);
449 if ($is_view) {
450 $views[] = $table;
452 if (isset($GLOBALS[$what . '_structure'])) {
453 // for a view, export a stand-in definition of the table
454 // to resolve view dependencies
455 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)) {
456 break 3;
459 if (isset($GLOBALS[$what . '_data']) && ! $is_view) {
460 $local_query = 'SELECT * FROM ' . PMA_backquote($current_db) . '.' . PMA_backquote($table);
461 if (!PMA_exportData($current_db, $table, $crlf, $err_url, $local_query)) {
462 break 3;
466 foreach($views as $view) {
467 // no data export for a view
468 if (isset($GLOBALS[$what . '_structure'])) {
469 if (!PMA_exportStructure($current_db, $view, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, 'create_view', $export_type)) {
470 break 3;
474 if (!PMA_exportDBFooter($current_db)) {
475 break 2;
479 } elseif ($export_type == 'database') {
480 if (!PMA_exportDBHeader($db)) {
481 break;
483 $i = 0;
484 $views = array();
485 // $tables contains the choices from the user (via $table_select)
486 foreach ($tables as $table) {
487 // if this is a view, collect it for later; views must be exported after
488 // the tables
489 $is_view = PMA_Table::isView($db, $table);
490 if ($is_view) {
491 $views[] = $table;
493 if (isset($GLOBALS[$what . '_structure'])) {
494 // for a view, export a stand-in definition of the table
495 // to resolve view dependencies
496 if (!PMA_exportStructure($db, $table, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, $is_view ? 'stand_in' : 'create_table', $export_type)) {
497 break 2;
500 if (isset($GLOBALS[$what . '_data']) && ! $is_view) {
501 $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table);
502 if (!PMA_exportData($db, $table, $crlf, $err_url, $local_query)) {
503 break 2;
507 foreach ($views as $view) {
508 // no data export for a view
509 if (isset($GLOBALS[$what . '_structure'])) {
510 if (!PMA_exportStructure($db, $view, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, 'create_view', $export_type)) {
511 break 2;
516 if (!PMA_exportDBFooter($db)) {
517 break;
519 } else {
520 if (!PMA_exportDBHeader($db)) {
521 break;
523 // We export just one table
525 if ($limit_to > 0 && $limit_from >= 0) {
526 $add_query = ' LIMIT '
527 . (($limit_from > 0) ? $limit_from . ', ' : '')
528 . $limit_to;
529 } else {
530 $add_query = '';
533 $is_view = PMA_Table::isView($db, $table);
534 if (isset($GLOBALS[$what . '_structure'])) {
535 if (!PMA_exportStructure($db, $table, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates, $is_view ? 'create_view' : 'create_table', $export_type)) {
536 break;
539 // If this is an export of a single view, we have to export data;
540 // for example, a PDF report
541 if (isset($GLOBALS[$what . '_data'])) {
542 if (!empty($sql_query)) {
543 // only preg_replace if needed
544 if (!empty($add_query)) {
545 // remove trailing semicolon before adding a LIMIT
546 $sql_query = preg_replace('%;\s*$%', '', $sql_query);
548 $local_query = $sql_query . $add_query;
549 PMA_DBI_select_db($db);
550 } else {
551 $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table) . $add_query;
553 if (!PMA_exportData($db, $table, $crlf, $err_url, $local_query)) {
554 break;
557 if (!PMA_exportDBFooter($db)) {
558 break;
561 if (!PMA_exportFooter()) {
562 break;
565 } while (false);
566 // End of fake loop
568 if ($save_on_server && isset($message)) {
569 $js_to_run = 'functions.js';
570 require_once './libraries/header.inc.php';
571 if ($export_type == 'server') {
572 $active_page = 'server_export.php';
573 require './server_export.php';
574 } elseif ($export_type == 'database') {
575 $active_page = 'db_export.php';
576 require './db_export.php';
577 } else {
578 $active_page = 'tbl_export.php';
579 require './tbl_export.php';
581 exit();
585 * Send the dump as a file...
587 if (!empty($asfile)) {
588 // Convert the charset if required.
589 if ($output_charset_conversion) {
590 $dump_buffer = PMA_convert_string($GLOBALS['charset'], $GLOBALS['charset_of_file'], $dump_buffer);
593 // Do the compression
594 // 1. as a zipped file
595 if ($compression == 'zip') {
596 if (@function_exists('gzcompress')) {
597 $zipfile = new zipfile();
598 $zipfile -> addFile($dump_buffer, substr($filename, 0, -4));
599 $dump_buffer = $zipfile -> file();
602 // 2. as a bzipped file
603 elseif ($compression == 'bzip') {
604 if (@function_exists('bzcompress')) {
605 $dump_buffer = bzcompress($dump_buffer);
606 if ($dump_buffer === -8) {
607 require_once './libraries/header.inc.php';
608 echo sprintf($strBzError, '<a href="http://bugs.php.net/bug.php?id=17300" target="_blank">17300</a>');
609 require_once './libraries/footer.inc.php';
613 // 3. as a gzipped file
614 elseif ($compression == 'gzip') {
615 if (@function_exists('gzencode')) {
616 // without the optional parameter level because it bug
617 $dump_buffer = gzencode($dump_buffer);
621 /* If ve saved on server, we have to close file now */
622 if ($save_on_server) {
623 $write_result = @fwrite($file_handle, $dump_buffer);
624 fclose($file_handle);
625 if (strlen($dump_buffer) !=0 && (!$write_result || ($write_result != strlen($dump_buffer)))) {
626 $message = sprintf($strNoSpace, htmlspecialchars($save_filename));
627 } else {
628 $message = sprintf($strDumpSaved, htmlspecialchars($save_filename));
631 $js_to_run = 'functions.js';
632 require_once './libraries/header.inc.php';
633 if ($export_type == 'server') {
634 $active_page = 'server_export.php';
635 require_once './server_export.php';
636 } elseif ($export_type == 'database') {
637 $active_page = 'db_export.php';
638 require_once './db_export.php';
639 } else {
640 $active_page = 'tbl_export.php';
641 require_once './tbl_export.php';
643 exit();
644 } else {
645 echo $dump_buffer;
649 * Displays the dump...
651 else {
653 * Close the html tags and add the footers in dump is displayed on screen
655 //echo ' </pre>' . "\n";
656 echo '</textarea>' . "\n"
657 . ' </form>' . "\n";
658 echo '</div>' . "\n";
659 echo "\n";
661 <script type="text/javascript">
662 //<![CDATA[
663 var bodyWidth=null; var bodyHeight=null;
664 if (document.getElementById('textSQLDUMP')) {
665 bodyWidth = self.innerWidth;
666 bodyHeight = self.innerHeight;
667 if (!bodyWidth && !bodyHeight) {
668 if (document.compatMode && document.compatMode == "BackCompat") {
669 bodyWidth = document.body.clientWidth;
670 bodyHeight = document.body.clientHeight;
671 } else if (document.compatMode && document.compatMode == "CSS1Compat") {
672 bodyWidth = document.documentElement.clientWidth;
673 bodyHeight = document.documentElement.clientHeight;
676 document.getElementById('textSQLDUMP').style.width=(bodyWidth-50) + 'px';
677 document.getElementById('textSQLDUMP').style.height=(bodyHeight-100) + 'px';
679 //]]>
680 </script>
681 <?php
682 require_once './libraries/footer.inc.php';
683 } // end if