home *** CD-ROM | disk | FTP | other *** search
/ Enter 2004 June / ENTER.ISO / files / xampp-win32-1.4.5-installer.exe / xampp / export.php < prev    next >
Encoding:
PHP Script  |  2004-06-06  |  19.9 KB  |  553 lines

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