<?php

/* Silence is golden, except everything is correct. */
error_reporting(0);

if (is_numeric($_GET['i']) AND isset($_GET['l']) AND ($_GET['t'] == 'excel' OR $_GET['t'] == 'csv'))
{
	$num = (integer)$_GET['i'];
	include($_SERVER[DOCUMENT_ROOT]."/wp-config.php");

	$db = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die();
	mysql_select_db(DB_NAME,$db) or die();

    $secretchk = mysql_query("SELECT `id` FROM `".$wpdb->prefix."wct_list` WHERE `id`='".mysql_real_escape_string($num)."' AND `secret`='".mysql_real_escape_string($_GET['l'])."' LIMIT 1;", $db);
    if (@mysql_num_rows($secretchk) == '1') { 
		$table = mysql_query("SHOW CREATE TABLE `".$wpdb->prefix."wct".mysql_real_escape_string($num)."`;", $db);
		if (@mysql_num_rows($table) == '1') { 
			if ($_GET['t'] == 'csv') {
				header("Content-type: application/CSV");
				header("Content-Disposition: attachment; filename=".date("Ymd",time())."_wct_table".$num.".csv");  
			}
			else {
				header("Content-type: application/vnd-ms-excel");
				header("Content-Disposition: attachment; filename=".date("Ymd",time())."_wct_table".$num.".xls");
				echo "<table border=\"1\"><tr>";  
			}
			$felder = explode("\n",mysql_result($table,0,"Create Table"));
			for ($i=3;$felder[$i] != '';$i++) {
				if ($_GET['t'] == 'csv') {
					echo preg_replace("/.*`(.*)`.*/","\"$1\";",$felder[$i-2]);
				}
				elseif ($_GET['t'] == 'excel') {
					echo preg_replace("/.*`(.*)`.*/","<td><strong>$1</strong></td>",$felder[$i-2]);
				}
			}
			if ($_GET['t'] == 'csv') { echo "\r\n"; } else { echo "</tr>"; }
			$i = $i - 4;

			$abfrage = mysql_query("SELECT * FROM `".$wpdb->prefix."wct".mysql_real_escape_string($num)."`;", $db);
			if (mysql_num_rows($abfrage) >= '1') {
				while ($row = mysql_fetch_array($abfrage))
				{
					if ($_GET['t'] == 'excel') { echo "<tr>"; }
					for ($x=0;$x <= $i;$x++) {
						if ($_GET['t'] == 'csv') {
							echo "\"".htmlentities($row[$x], ENT_QUOTES, "UTF-8")."\";";
						}
						else {
							echo "<td>".htmlentities($row[$x], ENT_QUOTES, "UTF-8")."</td>";
						}
					}
					if ($_GET['t'] == 'csv') { echo "\r\n"; } else { echo "</tr>"; }
				}	
			} 
			if ($_GET['t'] == 'excel') { echo "</table>"; }
		}
	}
}
?>
