Initial import.
[openemr.git] / interface / main / myadmin / export.php
blob3bd13a553264e226ce500f8b0ece5d9bda505304
1 <?php
2 /* $Id$ */
3 // vim: expandtab sw=4 ts=4 sts=4:
5 /**
6 * Get the variables sent or posted to this script and a core script
7 */
8 require_once('./libraries/grab_globals.lib.php');
9 require_once('./libraries/common.lib.php');
10 require_once('./libraries/zip.lib.php');
12 PMA_checkParameters(array('what'));
14 // What type of export are we doing?
15 if ($what == 'excel') {
16 $type = 'csv';
17 } else {
18 $type = $what;
21 /**
22 * Defines the url to return to in case of error in a sql statement
24 require('./libraries/export/' . $type . '.php');
26 // Generate error url
27 if ($export_type == 'server') {
28 $err_url = 'server_export.php?' . PMA_generate_common_url();
29 } elseif ($export_type == 'database') {
30 $err_url = 'db_details_export.php?' . PMA_generate_common_url($db);
31 } else {
32 $err_url = 'tbl_properties_export.php?' . PMA_generate_common_url($db, $table);
35 /**
36 * Increase time limit for script execution and initializes some variables
38 @set_time_limit($cfg['ExecTimeLimit']);
40 // Start with empty buffer
41 $dump_buffer = '';
42 $dump_buffer_len = 0;
44 // We send fake headers to avoid browser timeout when buffering
45 $time_start = time();
48 /**
49 * Output handler for all exports, if needed buffering, it stores data into
50 * $dump_buffer, otherwise it prints thems out.
52 * @param string the insert statement
54 * @return bool Whether output suceeded
56 function PMA_exportOutputHandler($line)
58 global $time_start, $dump_buffer, $dump_buffer_len;
60 // Kanji encoding convert feature
61 if (function_exists('PMA_kanji_str_conv')) {
62 $line = PMA_kanji_str_conv($line, $GLOBALS['knjenc'], isset($GLOBALS['xkana']) ? $GLOBALS['xkana'] : '');
64 // If we have to buffer data, we will perform everything at once at the end
65 if ($GLOBALS['buffer_needed']) {
67 $dump_buffer .= $line;
68 if ($GLOBALS['onfly_compression']) {
70 $dump_buffer_len += strlen($dump_buffer);
72 if ($dump_buffer_len > $GLOBALS['memory_limit']) {
73 // as bzipped
74 if ($GLOBALS['output_charset_conversion']) {
75 $dump_buffer = PMA_convert_string($GLOBALS['charset'], $GLOBALS['charset_of_file'], $dump_buffer);
77 if ($GLOBALS['compression'] == 'bzip' && @function_exists('bzcompress')) {
78 $dump_buffer = bzcompress($dump_buffer);
80 // as a gzipped file
81 else if ($GLOBALS['compression'] == 'gzip' && @function_exists('gzencode')) {
82 // without the optional parameter level because it bug
83 $dump_buffer = gzencode($dump_buffer);
85 if ($GLOBALS['save_on_server']) {
86 $write_result = @fwrite($GLOBALS['file_handle'], $dump_buffer);
87 if (!$write_result || ($write_result != strlen($line))) {
88 $GLOBALS['message'] = sprintf($GLOBALS['strNoSpace'], htmlspecialchars($save_filename));
89 return FALSE;
91 } else {
92 echo $dump_buffer;
94 $dump_buffer = '';
95 $dump_buffer_len = 0;
97 } else {
98 $time_now = time();
99 if ($time_start >= $time_now + 30) {
100 $time_start = $time_now;
101 header('X-pmaPing: Pong');
102 } // end if
104 } else {
105 if ($GLOBALS['asfile']) {
106 if ($GLOBALS['save_on_server']) {
107 $write_result = @fwrite($GLOBALS['file_handle'], $line);
108 if (!$write_result || ($write_result != strlen($line))) {
109 $GLOBALS['message'] = sprintf($GLOBALS['strNoSpace'], htmlspecialchars($save_filename));
110 return FALSE;
112 $time_now = time();
113 if ($time_start >= $time_now + 30) {
114 $time_start = $time_now;
115 header('X-pmaPing: Pong');
116 } // end if
117 } else {
118 // We export as file - output normally
119 if ($GLOBALS['output_charset_conversion']) {
120 $line = PMA_convert_string($GLOBALS['charset'], $GLOBALS['charset_of_file'], $line);
122 echo $line;
124 } else {
125 // We export as html - replace special chars
126 echo htmlspecialchars($line);
129 return TRUE;
130 } // end of the 'PMA_exportOutputHandler()' function
132 // Will we save dump on server?
133 $save_on_server = isset($cfg['SaveDir']) && !empty($cfg['SaveDir']) && !empty($onserver);
135 // Ensure compressed formats are associated with the download feature
136 if (empty($asfile)) {
137 if ($save_on_server) {
138 $asfile = TRUE;
139 } elseif (isset($compression) && ($compression == 'zip' | $compression == 'gzip' | $compression == 'bzip')) {
140 $asfile = TRUE;
141 } else {
142 $asfile = FALSE;
144 } else {
145 $asfile = TRUE;
148 // Defines the default <CR><LF> format
149 $crlf = PMA_whichCrlf();
151 // Do we need to convert charset?
152 $output_charset_conversion = $asfile &&
153 $cfg['AllowAnywhereRecoding'] && $allow_recoding
154 && isset($charset_of_file) && $charset_of_file != $charset;
156 // Set whether we will need buffering
157 $buffer_needed = isset($compression) && ($compression == 'zip' | $compression == 'gzip' | $compression == 'bzip');
159 // Use on fly compression?
160 $onfly_compression = $GLOBALS['cfg']['CompressOnFly'] && isset($compression) && ($compression == 'gzip' | $compression == 'bzip');
161 if ($onfly_compression) {
162 $memory_limit = trim(@ini_get('memory_limit'));
163 // 2 MB as default
164 if (empty($memory_limit)) $memory_limit = 2 * 1024 * 1024;
166 if (strtolower(substr($memory_limit, -1)) == 'm') $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
167 elseif (strtolower(substr($memory_limit, -1)) == 'k') $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
168 elseif (strtolower(substr($memory_limit, -1)) == 'g') $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
169 else $memory_limit = (int)$memory_limit;
171 // Some of memory is needed for other thins and as treshold.
172 // Nijel: During export I had allocated (see memory_get_usage function)
173 // approx 1.2MB so this comes from that.
174 if ($memory_limit > 1500000) $memory_limit -= 1500000;
176 // Some memory is needed for compression, assume 1/3
177 $memory_limit *= 2/3;
180 // Generate filename and mime type if needed
181 if ($asfile) {
182 $pma_uri_parts = parse_url($cfg['PmaAbsoluteUri']);
183 if ($export_type == 'server') {
184 if (isset($remember_template)) {
185 setcookie('pma_server_filename_template', $filename_template , 0,
186 substr($pma_uri_parts['path'], 0, strrpos($pma_uri_parts['path'], '/')),
187 '', ($pma_uri_parts['scheme'] == 'https'));
189 $filename = str_replace('__SERVER__', $GLOBALS['cfg']['Server']['host'], strftime($filename_template));
190 } elseif ($export_type == 'database') {
191 if (isset($remember_template)) {
192 setcookie('pma_db_filename_template', $filename_template , 0,
193 substr($pma_uri_parts['path'], 0, strrpos($pma_uri_parts['path'], '/')),
194 '', ($pma_uri_parts['scheme'] == 'https'));
196 $filename = str_replace('__DB__', $db, str_replace('__SERVER__', $GLOBALS['cfg']['Server']['host'], strftime($filename_template)));
197 } else {
198 if (isset($remember_template)) {
199 setcookie('pma_table_filename_template', $filename_template , 0,
200 substr($pma_uri_parts['path'], 0, strrpos($pma_uri_parts['path'], '/')),
201 '', ($pma_uri_parts['scheme'] == 'https'));
203 $filename = str_replace('__TABLE__', $table, str_replace('__DB__', $db, str_replace('__SERVER__', $GLOBALS['cfg']['Server']['host'], strftime($filename_template))));
206 // convert filename to iso-8859-1, it is safer
207 if (!(isset($cfg['AllowAnywhereRecoding']) && $cfg['AllowAnywhereRecoding'] && $allow_recoding)) {
208 $filename = PMA_convert_string($charset, 'iso-8859-1', $filename);
209 } else {
210 $filename = PMA_convert_string($convcharset, 'iso-8859-1', $filename);
213 // Generate basic dump extension
214 if ($type == 'csv') {
215 $filename .= '.csv';
216 $mime_type = 'text/x-csv';
217 } else if ($type == 'xml') {
218 $filename .= '.xml';
219 $mime_type = 'text/xml';
220 } else if ($type == 'latex') {
221 $filename .= '.tex';
222 $mime_type = 'application/x-tex';
223 } else {
224 $filename .= '.sql';
225 // loic1: 'application/octet-stream' is the registered IANA type but
226 // MSIE and Opera seems to prefer 'application/octetstream'
227 $mime_type = (PMA_USR_BROWSER_AGENT == 'IE' || PMA_USR_BROWSER_AGENT == 'OPERA')
228 ? 'application/octetstream'
229 : 'application/octet-stream';
232 // If dump is going to be compressed, set correct mime_type and add
233 // compression to extension
234 if (isset($compression) && $compression == 'bzip') {
235 $filename .= '.bz2';
236 $mime_type = 'application/x-bzip';
237 } else if (isset($compression) && $compression == 'gzip') {
238 $filename .= '.gz';
239 $mime_type = 'application/x-gzip';
240 } else if (isset($compression) && $compression == 'zip') {
241 $filename .= '.zip';
242 $mime_type = 'application/x-zip';
246 // Open file on server if needed
247 if ($save_on_server) {
248 if (substr($cfg['SaveDir'], -1) != '/') {
249 $cfg['SaveDir'] .= '/';
251 $save_filename = $cfg['SaveDir'] . preg_replace('@[/\\\\]@','_',$filename);
252 unset($message);
253 if (file_exists($save_filename) && empty($onserverover)) {
254 $message = sprintf($strFileAlreadyExists, htmlspecialchars($save_filename));
255 } else {
256 if (is_file($save_filename) && !is_writable($save_filename)) {
257 $message = sprintf($strNoPermission, htmlspecialchars($save_filename));
258 } else {
259 touch($save_filename); // php bug
260 if (!$file_handle = @fopen($save_filename, 'w')) {
261 $message = sprintf($strNoPermission, htmlspecialchars($save_filename));
265 if (isset($message)) {
266 $js_to_run = 'functions.js';
267 require_once('./header.inc.php');
268 if ($export_type == 'server') {
269 $active_page = 'server_export.php';
270 require('./server_export.php');
271 } elseif ($export_type == 'database') {
272 $active_page = 'db_details_export.php';
273 require('./db_details_export.php');
274 } else {
275 $active_page = 'tbl_properties_export.php';
276 require('./tbl_properties_export.php');
278 exit();
283 * Send headers depending on whether the user chose to download a dump file
284 * or not
286 if (!$save_on_server) {
287 if ($asfile ) {
288 // Download
289 header('Content-Type: ' . $mime_type);
290 header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
291 // lem9 & loic1: IE need specific headers
292 if (PMA_USR_BROWSER_AGENT == 'IE') {
293 header('Content-Disposition: inline; filename="' . $filename . '"');
294 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
295 header('Pragma: public');
296 } else {
297 header('Content-Disposition: attachment; filename="' . $filename . '"');
298 header('Pragma: no-cache');
300 } else {
301 // HTML
302 $backup_cfgServer = $cfg['Server'];
303 require_once('./header.inc.php');
304 $cfg['Server'] = $backup_cfgServer;
305 unset($backup_cfgServer);
306 echo '<div align="' . $cell_align_left . '">' . "\n";
307 echo ' <pre>' . "\n";
308 } // end download
311 // Check if we have something to export
312 if ($export_type == 'database') {
313 $tables = PMA_mysql_list_tables($db);
314 $num_tables = ($tables) ? @mysql_numrows($tables) : 0;
315 if ($num_tables == 0) {
316 $message = $strNoTablesFound;
317 $js_to_run = 'functions.js';
318 require_once('./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_details_export.php';
324 require('./db_details_export.php');
325 } else {
326 $active_page = 'tbl_properties_export.php';
327 require('./tbl_properties_export.php');
329 exit();
333 // Add possibly some comments to export
334 PMA_exportHeader();
336 // Will we need relation & co. setup?
337 $do_relation = isset($GLOBALS[$what . '_relation']);
338 $do_comments = isset($GLOBALS[$what . '_comments']);
339 $do_mime = isset($GLOBALS[$what . '_mime']);
340 if ($do_relation || $do_comments || $do_mime) {
341 require_once('./libraries/relation.lib.php');
342 $cfgRelation = PMA_getRelationsParam();
344 if ($do_mime) {
345 require_once('./libraries/transformations.lib.php');
348 // Include dates in export?
349 $do_dates = isset($GLOBALS[$what . '_dates']);
352 * Builds the dump
354 // Gets the number of tables if a dump of a database has been required
355 if ($export_type == 'server') {
357 * Gets the databases list - if it has not been built yet
359 if ($server > 0 && empty($dblist)) {
360 PMA_availableDatabases();
363 if (isset($db_select)) {
364 $tmp_select = implode($db_select, '|');
365 $tmp_select = '|' . $tmp_select . '|';
367 // Walk over databases
368 foreach($dblist AS $current_db) {
369 if ((isset($tmp_select) && strpos(' ' . $tmp_select, '|' . $current_db . '|'))
370 || !isset($tmp_select)) {
371 PMA_exportDBHeader($current_db);
372 PMA_exportDBCreate($current_db);
373 $tables = PMA_mysql_list_tables($current_db);
374 $num_tables = ($tables) ? @mysql_numrows($tables) : 0;
375 $i = 0;
376 while ($i < $num_tables) {
377 $table = PMA_mysql_tablename($tables, $i);
378 $local_query = 'SELECT * FROM ' . PMA_backquote($current_db) . '.' . PMA_backquote($table);
379 if (isset($GLOBALS[$what . '_structure'])) PMA_exportStructure($current_db, $table, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates);
380 if (isset($GLOBALS[$what . '_data'])) PMA_exportData($current_db, $table, $crlf, $err_url, $local_query);
381 $i++;
383 PMA_exportDBFooter($current_db);
386 } elseif ($export_type == 'database') {
387 PMA_exportDBHeader($db);
388 if (isset($table_select)) {
389 $tmp_select = implode($table_select, '|');
390 $tmp_select = '|' . $tmp_select . '|';
392 $i = 0;
393 while ($i < $num_tables) {
394 $table = PMA_mysql_tablename($tables, $i);
395 $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table);
396 if ((isset($tmp_select) && strpos(' ' . $tmp_select, '|' . $table . '|'))
397 || !isset($tmp_select)) {
399 if (isset($GLOBALS[$what . '_structure'])) PMA_exportStructure($db, $table, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates);
400 if (isset($GLOBALS[$what . '_data'])) PMA_exportData($db, $table, $crlf, $err_url, $local_query);
402 $i++;
404 PMA_exportDBFooter($db);
405 } else {
406 PMA_exportDBHeader($db);
407 // We export just one table
409 if ($limit_to > 0 && $limit_from >= 0) {
410 $add_query = ' LIMIT '
411 . (($limit_from > 0) ? $limit_from . ', ' : '')
412 . $limit_to;
413 } else {
414 $add_query = '';
417 if (!empty($sql_query)) {
418 $local_query = $sql_query . $add_query;
419 PMA_mysql_select_db($db);
420 } else {
421 $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table) . $add_query;
424 if (isset($GLOBALS[$what . '_structure'])) PMA_exportStructure($db, $table, $crlf, $err_url, $do_relation, $do_comments, $do_mime, $do_dates);
425 if (isset($GLOBALS[$what . '_data'])) PMA_exportData($db, $table, $crlf, $err_url, $local_query);
426 PMA_exportDBFooter($db);
430 * Send the dump as a file...
432 if (!empty($asfile)) {
433 // Convert the charset if required.
434 if ($output_charset_conversion) {
435 $dump_buffer = PMA_convert_string($GLOBALS['charset'], $GLOBALS['charset_of_file'], $dump_buffer);
438 // Do the compression
439 // 1. as a gzipped file
440 if (isset($compression) && $compression == 'zip') {
441 if (@function_exists('gzcompress')) {
442 if ($type == 'csv' ) {
443 $extbis = '.csv';
444 } else if ($type == 'xml') {
445 $extbis = '.xml';
446 } else {
447 $extbis = '.sql';
449 $zipfile = new zipfile();
450 $zipfile -> addFile($dump_buffer, $filename . $extbis);
451 $dump_buffer = $zipfile -> file();
454 // 2. as a bzipped file
455 else if (isset($compression) && $compression == 'bzip') {
456 if (@function_exists('bzcompress')) {
457 $dump_buffer = bzcompress($dump_buffer);
458 if ($dump_buffer === -8) {
459 require_once('./header.inc.php');
460 echo sprintf($strBzError, '<a href="http://bugs.php.net/bug.php?id=17300" target="_blank">17300</a>');
461 require_once('./footer.inc.php');
465 // 3. as a gzipped file
466 else if (isset($compression) && $compression == 'gzip') {
467 if (@function_exists('gzencode')) {
468 // without the optional parameter level because it bug
469 $dump_buffer = gzencode($dump_buffer);
473 /* If ve saved on server, we have to close file now */
474 if ($save_on_server) {
475 $write_result = @fwrite($file_handle, $dump_buffer);
476 fclose($file_handle);
477 if (strlen($dump_buffer) !=0 && (!$write_result || ($write_result != strlen($dump_buffer)))) {
478 $message = sprintf($strNoSpace, htmlspecialchars($save_filename));
479 } else {
480 $message = sprintf($strDumpSaved, htmlspecialchars($save_filename));
483 $js_to_run = 'functions.js';
484 require_once('./header.inc.php');
485 if ($export_type == 'server') {
486 $active_page = 'server_export.php';
487 require_once('./server_export.php');
488 } elseif ($export_type == 'database') {
489 $active_page = 'db_details_export.php';
490 require_once('./db_details_export.php');
491 } else {
492 $active_page = 'tbl_properties_export.php';
493 require_once('./tbl_properties_export.php');
495 exit();
496 } else {
497 echo $dump_buffer;
501 * Displays the dump...
503 else {
505 * Close the html tags and add the footers in dump is displayed on screen
507 echo ' </pre>' . "\n";
508 echo '</div>' . "\n";
509 echo "\n";
510 require_once('./footer.inc.php');
511 } // end if