<?php

/*
 * phpMyEdit - instant MySQL table editor and code generator
 *
 * phpMyEditSetup.php - interactive table configuration utility (setup)
 * ____________________________________________________________
 *
 * Copyright (c) 1999-2002 John McCreesh <jpmcc@users.sourceforge.net>
 * Copyright (c) 2001-2002 Jim Kraai <jkraai@users.sourceforge.net>
 * Versions 5.0 and higher developed by Ondrej Jombik <nepto@php.net>
 * Copyright (c) 2002-2004 Platon SDG, http://platon.sk/
 * All rights reserved.
 *
 * See README file for more information about this software.
 * See COPYING file for license information.
 *
 * Download the latest version from
 * http://platon.sk/projects/phpMyEdit/
 */

/* $Platon: phpMyEdit/phpMyEditSetup.php,v 1.34 2004/01/16 19:46:32 nepto Exp $ */

ini_set('max_execution_time', 0);
require_once 'auth.php';

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
            "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<title>phpMyEdit Setup</title>
	<style type="text/css">
	<!--
		body  { font-family: "Verdana", "Arial", "Sans-Serif"; text-align: left }
		h1    { color: #004d9c; font-size: 13pt; font-weight: bold }
		h2    { color: #004d9c; font-size: 11pt; font-weight: bold }
		h3    { color: #004d9c; font-size: 11pt; }
		p     { color: #004d9c; font-size: 9pt; }
		table { border: 1px solid #004d9c; border-collapse: collapse; border-spacing: 0px; }
		td    { border: 1px solid; padding: 3px; color: #004d9c; font-size: 9pt; }
		hr
		{
		height: 1px;
		background-color: #000000;
		color: #000000;
		border: solid #000000 0;
		padding: 0;
		margin: 0;
		border-top-width: 1px;
		}
	-->
	</style>
</head>
<body bgcolor="white">

<?php

$hn = @$HTTP_POST_VARS['hn'];
$un = @$HTTP_POST_VARS['un'];
$pw = @$HTTP_POST_VARS['pw'];
$db = @$HTTP_POST_VARS['db'];
$tb = @$HTTP_POST_VARS['tb'];
$id = @$HTTP_POST_VARS['id'];
$submit        = @$HTTP_POST_VARS['submit'];
$options       = @$HTTP_POST_VARS['options'];
$baseFilename  = @$HTTP_POST_VARS['baseFilename'];
$pageTitle     = @$HTTP_POST_VARS['pageTitle'];
$pageHeader    = @$HTTP_POST_VARS['pageHeader'];
$HTMLissues    = @$HTTP_POST_VARS['HTMLissues'];
$CSSstylesheet = @$HTTP_POST_VARS['CSSstylesheet'];

/* QBUILDER TRAP */
$adodb->debug = 0;
$rs = $adodb->Execute("SELECT * FROM qb_report WHERE id = ?", $_GET['id']);
if (!$rs || $rs->EOF) die("Error: Report '".$_GET['id']."' does not exist.");
$tableid = "qb_report_".abs(crc32($_SESSION['userid']."_".$rs->fields['id']));
$tableid2 = "qb_report_".$rs->fields['id'];
$adodb->Execute("DROP TABLE ".$tableid);
$sql = $rs->fields['sql'];
$sql = str_replace('[userid]', "'".$_SESSION['userid']."'", $sql);
$adodb->Execute("CREATE TABLE ".$tableid." AS ".$sql) or die($adodb->ErrorMsg());
$adodb->Execute("ALTER TABLE ".$tableid." ADD qb_id INTEGER");
$adodb->Execute("ALTER TABLE ".$tableid." ADD KEY (qb_id) ");
$adodb->Execute("ALTER TABLE ".$tableid." CHANGE qb_id qb_id INTEGER NOT NULL auto_increment");

$_SESSION['reptb'] = $tableid;
$_SESSION['repid'] = $_GET['id'];

// template
$crcTable = abs(crc32($tableid));

$pkey = $rs->fields['pkey'];

$adodb->Execute("ALTER TABLE ".$tableid." ADD UNIQUE KEY (".$pkey.")");

$hidden = $rs->fields['hidden'];
$piece = explode(",", $hidden);
$arrHidden = array();
foreach ($piece as $k => $v) {
	$v = trim($v);
	if ($v) $arrHidden[$v] = 1;
}

$arrSortField = array();

$reportName = $rs->fields['name'];
$groupText = $rs->fields['groupby'];
$parameterText = $rs->fields['paramtxt'];
$paramsql = $rs->fields['paramsql'];
$rs2 = $adodb->SelectLimit("SELECT * FROM ".$tableid, 1);
$rows = $rs2->GetRows();
$smartyFilename = 'report_'.htmlspecialchars($reportName);
$assignTxt = '';
$fileTpl = "templates".DIRECTORY_SEPARATOR.$smartyFilename."_default.tpl";
$Tplhandle = @fopen($fileTpl, 'w+');
if ($Tplhandle) {
	$columnHeader = $fieldText = $detailText = $formText = '';
	$columnCount = 0;
	$rows0 = $rows[0];
	if (!is_array($rows0)) $rows0 = array();
	$fieldText = implode(", ", array_keys($rows0));
	foreach ($rows0 as $k => $v) {
		if ($k == 'qb_id') continue;
		$assignTxt .= '$smarty->assign("'.$k.'Txt", __("'.$k.'", "'.$k.'", '.
		' $tableid2));'."\n";
		if (! array_key_exists($k, $arrHidden)) {
			$columnHeader .= "\t\t<td>{\$".$k."Txt2}</td>\n";
			$detailText .= "\t\t<td>&nbsp;{\$rows.".$k."}</td>\n";
		}
		$formText .= "
		<tr>
			<td>{\$".$k."Txt}</td>
			<td>{\$".$k."Val}</td>
		</tr>";
		$columnCount++;
	}

	$parameterForm = '';
	$p = explode(",", $parameterText);
	foreach ($p as $k => $v) {
		$v = trim($v);
		if (!$v) continue;
        $arr = explode(":", $v);
        $fld = $arr[0];
        $svar = $arr[1];
        $vType = $arr[2];
        if($arr[2] == 'date')
        {
        	if(!isset($dateFormat))
            	$dateFormat = array();
        	array_push($dateFormat, $svar);
        }

		$parameterForm .= '<td>{$filter_'.$svar.'Txt}</td><td>{$filter_'.$svar.'Val}</td>';
	}

	if ($parameterForm) {
		$parameterForm = '
		<form method="POST" action="{$smarty.server.PHP_SELF}" onSubmit="return dateFormat(\''.@join(":", $dateFormat).'\');">
		<table id="report_filter_table" class="report_filter_table">
        <tr id="report_filter_table_submit"><td><input type=submit class="pme-filter" value="{$Query}"></td></tr>
        <tr id="report_filter_table_input">
		'.$parameterForm.'
		</tr>
		</table>
		</form>
		';
	}

	$groupHeader = '';
	if ($groupText) {
		$p1 = explode(";", $groupText);
		foreach ($p1 as $k1 => $v1) {
			$v1 = trim($v1);
			if (!$v1) continue;
			$p2 = explode(":", $v1);
			$group = trim($p2[0]);

			$arrSortField[] = $group;

			$first = $calc = $reset = $reset2 = $print = '';
			$p3 = explode(",", trim($p2[1]));
			foreach ($p3 as $k3 => $v3) {
				$v3 = trim($v3);
				if (!$v3) continue;
				$p4 = explode(".", $v3);
				$func = strtoupper(trim($p4[0]));
				$fld = trim($p4[1]);
				if (!$fld) $fld = $group;
				if ($func == 'SUM') {
					$print .= "
		{\$".$fld."Txt}={\$".$group."Group_".$func."}
					";
				} else if ($func == 'COUNT') {
					$print .= "
		{\$".strtolower($func)."}={\$".$group."Group_".$func."}
					";

 				}
		}
			if ($group != "ALL") {
				$groupFooter = "
	{if \$".$group."Group_counter == 0}
		<tr><td colspan={\$columnCount}>
		{\$subTotal} ".$print."
		</td></tr>
	{/if}
				".$groupFooter;
			} else {
				$columnFooter = "
		".$reset2."
		<tr><td colspan={\$columnCount}>
		{\$grandTotal} ".$print."
		</td></tr>
				".$columnFooter;
			}
            }
	}


	$Tplbuffer = "
{* title *}
{include file=\"reportHeader.tpl\"}

{*Edited*}
<div class=\"report_filter\">

{if \$columnCount > 0}
	{* parameter *}
	{* ".$parameterText." *}
	".$parameterForm."
{/if}

{*Edited*}
</div>

{* variable *}
{* {\$REPORT_COUNT} *}

{* field *}
{* ".$fieldText." *}

{* group *}
{* ".$groupText." *}

{* pageHeader *}
{* <p>{\$Total}: {\$REPORT_COUNT}</p> *}
{\$form_begin}

{*Edited*}
	<!--<hr>-->

{*Edited*}
	<div id=\"report_content\" class=\"report_content\">

{if \$columnCount > 0}

{php}
	global \$phpme;
	while (\$phpme->assign_rows()) {
{/php}

		{* columnHeader *}
		{if \$rows_count == 1}
			<div id=\"report_content_header\" class=\"report_content_header\">
			<table id=\"report_content_header_table\" class=\"report_content_header_table\">
			<tr><td>&nbsp;</td>
	".$columnHeader."
			</tr>
			</table>
			{if strlen(\$sortInfo) > 0}
				{\$sortInfo}
			{/if}
			</div>
			<div id=\"report_content_table\" class=\"report_content_table\">
			<table id=\"report_content_table_table\" class=\"report_content_table_table\">

		{/if}

		{* detail *}
		{if \$rows_count % 2 == 0}
			<tr bgcolor=#E8EEFF>
		{else}
			<tr>
		{/if}

			<td nowrap>
			{\$rows.link_change}
			{\$rows.link_copy}
			{\$rows.link_delete}
			</td>
	".$detailText."
			</tr>

		{* groupFooter *}
	".$groupFooter."

		{* columnFooter *}
		{if ! \$rows_next}

			</table>
            </div>
			</div>
			<div id=\"report_gesamt_berechnung\" class=\"report_gesamt_berechung\">
	".$columnFooter."
			</div>
		{/if}

{php}
	}
{/php}

	{if \$rows_count == 0}
		<h5 align='center'>{'NoData'|__}</h5>
        </div>
	{/if}
	</div>
{else}
	{section name=html loop=\$form_hidden}
		{\$form_hidden[html]}
	{/section}
	<table class='report_content_formular_table' cellspacing='0px'>
	".$formText."
	</table>
	</div>

	{* using translate : {'add'|__} *}
	{* for value : \$rows.keyname *}
{/if}

{if \$columnCount > 0}
	{include file=\"listButtons.tpl\"}
{else}
	{include file=\"recordButtons.tpl\"}
{/if}

{* summary *}

{* pageFooter *}
{\$form_end}
{include file=\"reportFooter.tpl\"}
";

	fwrite($Tplhandle, $Tplbuffer);
	flush($Tplhandle);
	fclose($Tplhandle);
} else {
	echo 'Trying write <b>'.$fileTpl.'</b> <b><font color=red>Failed</font></b><br>';
	exit;
}
/* ----------------------------------------------------------------------------------------------------------------------------------
		BEGIN OF phpME_report_...
        (is placed in root directory of qbuilder)
   ----------------------------------------------------------------------------------------------------------------------------------
*/

//***********************************************************************************************************************************
// Edited by Dennis Ritz 07.04.2006
// New Filter Functions
// Only SUM over cols is supported
//***********************************************************************************************************************************
	$parameterForm = '';
	$p = explode(",", $parameterText);

	foreach ($p as $k => $v) {
		$v = trim($v);
		if (!$v) continue;
        $arr = explode(":", $v);
        $fld = $arr[0];
        $svar = $arr[1];
        $vType = $arr[2];

		$_SESSION[$v.'_'.$crcTable] = '';

        if($vType == 'select')
        {
        	$filters .= "
        		\$rsFilters = \$adodb->Execute('SELECT ".$fld." FROM ".$tableid." GROUP BY ".$fld."');
                \$".$svar." = \$rsFilters -> GetMenu('".$svar."', \$_SESSION['".$svar."_".$crcTable."']);
            		";
            $assignTxt .= '$smarty->assign("filter_'.$svar.'Txt", __("'.$fld.'", "'.$fld.'", "$tableid2"));'."\n";
			$assignTxt .= '$smarty->assign("filter_'.$svar.'Val", $'.$svar.');'."\n";
			$assignTxt .= '$smarty->assign("filter_'.$svar.'Val", $'.$svar.');'."\n";
        }
        if($vType == 'text')
        {
        	$filters .= "
                \$".$svar." = '<input type=\'text\' class=\'report_filter_table_input_small\' name=\'".$svar."\' value=\''.\$_SESSION['".$svar."_".$crcTable."'].'\'>';
            		";
            $assignTxt .= '$smarty->assign("filter_'.$svar.'Txt", __("'.$fld.'", "'.$fld.'", "$tableid2"));'."\n";
			$assignTxt .= '$smarty->assign("filter_'.$svar.'Val", $'.$svar.');'."\n";
        }
        if($vType == 'hidtext')
        {
        	$filters .= "
                \$".$svar." = '<input type=\'hidden\' class=\'report_filter_table_input_small\' name=\'".$svar."\' value=\''.\$_SESSION['".$svar."_".$crcTable."'].'\'>';
            		";
			$assignTxt .= '$smarty->assign("filter_'.$svar.'Val", $'.$svar.');'."\n";
        }
        if($vType == 'date')
        {
        	$filters .= "
                \$".$svar." = '<input type=\'text\' class=\'report_filter_table_input_small\' name=\'".$svar."\' value=\''.\$_SESSION['".$svar."_".$crcTable."'].'\'><image src=\'images/dynCalendar.gif\' name=\'calendar\' date=date onclick=\'startCalendar(this,\"".$svar."\", \"down\");\'>';
            		";
            $assignTxt .= '$smarty->assign("filter_'.$svar.'Txt", __("'.$fld.'", "'.$fld.'", "$tableid2"));'."\n";
			$assignTxt .= '$smarty->assign("filter_'.$svar.'Val", $'.$svar.');'."\n";
        }
	}
//***********************************************************************************************************************************
// END OF EDIT
//***********************************************************************************************************************************


$_SESSION['filters_'.$crcTable] = '';
$smartyHeader = "
\$tableid = '".$tableid."';
\$tableid2 = '".$tableid2."';
\$reportName = '".$reportName."';
\$paramsql = '".$paramsql."';

\$isparam = false;
foreach (\$_POST as \$k => \$v) {
        \$v = trim(\$v);
        // old style
        if (strstr(\$paramsql, '['.\$k.']')) {
                \$_SESSION[\$k.'_".$crcTable."'] = \$v;
                \$isparam = true;
                \$key = '['.\$k.']';
                \$value = \"'\".\$v.\"'\";
        // new style
        } else if (ereg('\['.\$k.':([^]]+)\]', \$paramsql, \$r)) {
                \$isparam = true;
                \$key = \$r[0];
                if (\$v) {
                	if(ereg('([0-9]{1,2}).([0-9]{1,2}).([0-9]{4})', \$v, \$regs))
                    {
                    	\$z = \$regs[3].'-'.\$regs[2].'-'.\$regs[1];
                    	\$value = \"'\".\$z.\"'\";
                    }else
                        \$value = \"'\".\$v.\"'\";
                    \$_SESSION[\$k.'_".$crcTable."'] = \$v;
                } else {
                  	\$value = \$r[1];
                    \$_SESSION[\$k.'_".$crcTable."'] = '';
                }
        }
        \$paramsql = str_replace(\$key, \$value, \$paramsql);
}
if (\$isparam) {
        \$opts['filters'] = \$paramsql;
        \$_SESSION['filters_".$crcTable."'] = \$opts['filters'];
} else {
        \$opts['filters'] = \$_SESSION['filters_".$crcTable."'];
}

//SQL for content of Filters
".$filters."

function translate(\$str) {
	return __(\$str, null, \$tableid2);
}

require 'smarty/libs/Smarty.class.php';
\$smarty = new Smarty;
\$smarty->compile_check = true;
\$smarty->debugging = false;
\$smarty->register_modifier(\"translate\",\"translate\");
\$smarty->register_modifier(\"number_format\",\"number_format\");
\$smarty->assign('curdate', time());
\$smarty->assign('count', __('COUNT'));
\$smarty->assign('grandTotal', __('grandTotal'));
\$smarty->assign('subTotal', __('subTotal'));
\$smarty->assign('title', __(\"TITLE\", \$reportName, \$tableid2));
\$smarty->assign('Total', __('Total'));
\$smarty->assign('Query', __('Query'));
\$smarty->assign('Reset', __('Reset'));
".$assignTxt."
";

$smartyFooter = "

\$columnCount = \$smarty->get_template_vars('columnCount');
#if (\$columnCount < 1) return;

if (isset(\$_GET['dopdf'])) {
	ob_start();
}

if (\$smarty->template_exists('".$smartyFilename.".tpl')) {
	\$smarty->display('".$smartyFilename.".tpl');
} else {
	\$smarty->display('".$smartyFilename."_default.tpl');
}

if (isset(\$_GET['dopdf'])) {
	\$tmpfname = tempnam(\"/tmp\", \"output.html\");
	\$fp = fopen(\$tmpfname, 'w');
	fwrite(\$fp, ob_get_contents());
	ob_end_clean();
	fclose(\$fp);

	header('Content-Type: application/pdf');
	passthru('htmldoc -t pdf --webpage '.\$tmpfname);
}

";

//***********************************************************************************************************************************
// Edited by Dennis Ritz 07.04.2006
// Calculate over fields
// Only SUM over cols is supported
//***********************************************************************************************************************************
	$calculate = '';
	if ($groupText) {
		$p1 = explode(";", $groupText);
		foreach ($p1 as $k1 => $v1) {
			$v1 = trim($v1);
			if (!$v1) continue;
			$p2 = explode(":", $v1);
			$group = trim($p2[0]);

			$arrSortField[] = $group;

			$first = $calc = $reset = $reset2 = $print = '';
			$p3 = explode(",", trim($p2[1]));
			foreach ($p3 as $k3 => $v3) {
				$v3 = trim($v3);
				if (!$v3) continue;
				$p4 = explode(".", $v3);
				$func = strtoupper(trim($p4[0]));
				$fld = trim($p4[1]);
				if (!$fld) $fld = $group;
				if ($func == 'SUM') {
                	if($group == 'ALL')
                    {
                    	$calculate .= "
                        	\$where='';
                        	if(\$whereParam = \$phpme -> make_where_from_query_opts())
                            	\$where = 'WHERE '.\$whereParam;
	                        \$rsGroup = \$adodb->Execute('SELECT @A:=SUM(".$fld.") as ".$group."Group_".$fld." FROM ".$tableid." '.\$where);
                            //die(\$phpme -> make_where_from_query_opts());
	                		\$smarty->assign('".$group."Group_".$func."', __(\$rsGroup->fields['".$group."Group_".$fld."']));
	                        ";
					}
 				}
            }
		}
	}
//***********************************************************************************************************************************
// END OF EDIT
//***********************************************************************************************************************************



$hn = $adodb_host;
$un = $adodb_user;
$pw = $adodb_pass;
$db = $adodb_db;
$tb = $tableid;
$tb2 = $tableid2;
$id = 'qb_id';
$submit = true;
$options = 1;
$baseFilename = 'phpME_report_'.htmlspecialchars(abs(crc32($tb)));
$pageTitle = __("TITLE", $rs->fields['name'], $tableid2);
$pageHeader = true;
$HTMLissues = true;
$CSSstylesheet = true;
/* QBUILDER TRAP */


$phpExtension = '.php';
if (isset($baseFilename) && $baseFilename != '') {
	$phpFile = $baseFilename.$phpExtension;
	//$contentFile = $baseFilename.'Content.inc';
	$contentFile = $baseFilename.'.php';
} elseif (isset($tb)) {
	$phpFile = $tb.$phpExtension;
	//$contentFile = $tb.'Content.inc';
	$contentFile = $tb.'.php';
} else {
	$phpFile = 'index'.$phpExtension;
	//$contentFile = 'Content.inc';
	$contentFile = 'phpMyEdit-content.php';
}

$buffer = '';

function echo_html($x)
{
	echo htmlspecialchars($x),"\n";
}

function echo_buffer($x)
{
	global $buffer;
	$buffer .= $x."\n";
}

$self = basename($HTTP_SERVER_VARS['PHP_SELF']);
$dbl  = @mysql_pconnect($hn, $un, $pw);

if ((!$dbl) or empty($submit)) {
	echo '<h1>Please log in to your MySQL database</h1>';
	if (!empty($submit)) {
		echo '<h2>Sorry - login failed - please try again</h2>'."\n";
	}
	if (! isset($hn)) {
		$hn = 'localhost';
	}
	echo '
		<form action="'.htmlspecialchars($self).'" method="POST">
		<table border="1" cellpadding="1" cellspacing="0" summary="Login form">
		<tr>
		<td>Hostname:</td>
		<td><input type="text" name="hn" value="'.htmlspecialchars($hn).'"></td>
		</tr><tr>
		<td>Username:</td>
		<td><input type="text" name="un" value="'.htmlspecialchars($un).'"></td>
		</tr><tr>
		<td>Password:</td>
		<td><input type="password" name="pw" value="'.htmlspecialchars($pw).'"></td>
		</tr>
		</table><br>
		<input type="submit" name="submit" value="Submit">
		</form>'."\n";
} else if (! isset($db)) {
	$dbs     = @mysql_list_dbs($dbl);
	$num_dbs = @mysql_num_rows($dbs);
	echo '<h1>Please select a database</h1>
		<form action="'.htmlspecialchars($self).'" method="POST">
		<input type="hidden" name="hn" value="'.htmlspecialchars($hn).'">
		<input type="hidden" name="un" value="'.htmlspecialchars($un).'">
		<input type="hidden" name="pw" value="'.htmlspecialchars($pw).'">
		<table border="1" cellpadding="1" cellspacing="1" summary="Database selection">'."\n";
	for ($i = 0; $i < $num_dbs; $i++) {
		$db = @mysql_db_name($dbs, $i);
		$checked = ! strcasecmp($un, $db) ? ' checked' : '';
		$db = htmlspecialchars($db);
		echo '<tr><td><input'.$checked.' type="radio" name="db" value="'.$db.'"></td><td>'.$db.'</td></tr>'."\n";
	}
	echo '</table><br>
		<input type="submit" name="submit" value="Submit">
		<input type="submit" name="cancel" value="Cancel">
		</form>'."\n";
} else if (!isset($tb)) {
	echo '<h1>Please select a table from database: '.htmlspecialchars($db).'</h1>
		<form action="'.htmlspecialchars($self).'" method="POST">
		<input type="hidden" name="hn" value="'.htmlspecialchars($hn).'">
		<input type="hidden" name="un" value="'.htmlspecialchars($un).'">
		<input type="hidden" name="pw" value="'.htmlspecialchars($pw).'">
		<input type="hidden" name="db" value="'.htmlspecialchars($db).'">
		<table border="1" cellpadding="1" cellspacing="1" summary="Table selection">'."\n";
	$tbs     = @mysql_list_tables($db, $dbl);
	$num_tbs = @mysql_num_rows($tbs);
	for ($j = 0; $j < $num_tbs; $j++) {
		$tb = @mysql_tablename($tbs, $j);
		$tb = htmlspecialchars($tb);
		$checked = $j == 0 ? ' checked' : '';
		echo '<tr><td><input'.$checked.' type="radio" name="tb" value="'.$tb.'"></td><td>'.$tb.'</td></tr>'."\n";
	}
	echo '</table><br>
		<input type="submit" name="submit" value="Submit">
		<input type="submit" name="cancel" value="Cancel">
		</form>'."\n";
} else if (!isset($id)) {
	echo '  <h1>Please select an identifier from table: '.htmlspecialchars($tb).'</h1>
		<p>
		This field will be used in change, view, copy and delete operations.<br>
		The field should be numeric and must uniquely identify a record.
		</p>
		<p>
		Please note, that there were problems reported by phpMyEdit users
		regarding using MySQL reserved word as unique key name (the example for
				this is "key" name). Thus we recommend you to use another name
		of unique key. Usage of "id" or "ID" should be safe and good idea.
		</p>
		<form action="'.htmlspecialchars($self).'" method="POST">
		<input type="hidden" name="hn" value="'.htmlspecialchars($hn).'">
		<input type="hidden" name="un" value="'.htmlspecialchars($un).'">
		<input type="hidden" name="pw" value="'.htmlspecialchars($pw).'">
		<input type="hidden" name="db" value="'.htmlspecialchars($db).'">
		<input type="hidden" name="tb" value="'.htmlspecialchars($tb).'">
		<table border="1" cellpadding="1" cellspacing="1" summary="Key selection">'."\n";
//		<tr><td><input type="radio" name="id" value="">
//		<td><i>None</i></td><td><i>No id field required</i></td></tr>
	@mysql_select_db($db);
	$tb_desc = @mysql_query("DESCRIBE $tb");
	$fds     = @mysql_list_fields($db,$tb,$dbl);
	for ($j = 0; ($fd = @mysql_field_name($fds, $j)) != false; $j++) {
		$ff = @mysql_field_flags($fds, $j);
		strlen($ff) <= 0 && $ff = '---';
		$checked = stristr($ff, 'primary_key') ? ' checked' : '';
		echo '<tr><td><input',$checked,' type="radio" name="id" value="',htmlspecialchars($fd),'"></td>';
		echo '<td>',htmlspecialchars($fd),'</td>';
		echo '<td>',htmlspecialchars($ff),'</td>';
		$r = @mysql_fetch_array($tb_desc, $j);
	}
	echo '</table><br>
		<input type="submit" name="submit" value="Submit">
		<input type="submit" name="cancel" value="Cancel">
		</form>'."\n";

} else if (!isset($options)) {
	echo '<h1>Please select additional options</h1>
		<form action="'.htmlspecialchars($self).'" method="POST">
		<input type="hidden" name="hn" value="'.htmlspecialchars($hn).'">
		<input type="hidden" name="un" value="'.htmlspecialchars($un).'">
		<input type="hidden" name="pw" value="'.htmlspecialchars($pw).'">
		<input type="hidden" name="db" value="'.htmlspecialchars($db).'">
		<input type="hidden" name="tb" value="'.htmlspecialchars($tb).'">
		<input type="hidden" name="id" value="'.htmlspecialchars($id).'">
		<table border="1" cellpadding="1" cellspacing="1" summary="Additional options">
		<tr><td>Base filename</td><td><input type="text" name=baseFilename value ="'.htmlspecialchars($tb).'"></td></tr>
		<tr><td>Page title</td><td><input type="text" name=pageTitle value ="'.htmlspecialchars($tb).'"></td></tr>
		<tr><td>Page header</td><td><input type="checkbox" name=pageHeader></td></tr>
		<tr><td>HTML header &amp; footer</td><td><input type="checkbox" name=HTMLissues></td></tr>
		<tr><td>CSS basic stylesheet</td><td><input checked type="checkbox" name=CSSstylesheet></td></tr>
		</table><br>
		<input type="submit" name="submit" value="Submit">
		<input type="submit" name="cancel" value="Cancel">
		<input type="hidden" name="options" value="1">
		</form>'."\n";
} else {
//	echo '<h1>Here is your phpMyEdit calling program</h1>'."\n";
//	echo '<h2>You may now copy and paste it into your PHP editor</h2>'."\n";
	if ($pageHeader) {
		#echo_buffer('<h3>'.$pageTitle.'</h3>');
	}

echo_buffer("<?php

/*
 * IMPORTANT NOTE: This generated file contains only a subset of huge amount
 * of options that can be used with phpMyEdit. To get information about all
 * features offered by phpMyEdit, check official documentation. It is available
 * online and also for download on phpMyEdit project management page:
 *
 * http://www.platon.sk/projects/main_page.php?project_id=5
 */

// MySQL host name, user name, password, database, and table
\$opts['tb'] = '$tb';
\$opts['tb2'] = '$tb2';

// Name of field which is the unique key
\$opts['key'] = '$id';

// Type of key field (int/real/string/date etc.)");

	if ($id == '') {
		echo_buffer("\$opts['key_type'] = '';");
	} else {
		$fds = @mysql_list_fields($db,$tb,$dbl);
		for ($j = 0; ($fd = @mysql_field_name($fds, $j)) != ''; $j++) {
			if ($fd == $id) {
				echo_buffer("\$opts['key_type'] = '".@mysql_field_type($fds, $j)."';");
				break;
			}
		}
	}

	#$extraOpt = '';
	#if ($rs->fields['cols']) $extraOpt = 'C';

	echo_buffer("
// Sorting field(s)
\$opts['sort_field'] = array('".implode("','", array_reverse($arrSortField))/*$id*/."');
if (\$opts['sort_field'][0] === '') \$opts['sort_field'] = array();

// Number of records to display on the screen
// Value of -1 lists all records in a table
\$opts['inc'] = 250;  //ORIGINAL

// Options you wish to give the users
// A - add,  C - change, P - copy, V - view, D - delete,
// F - filter, I - initial sort suppressed
\$opts['options'] = ''; // FACDPV

// Number of lines to display on multiple selection filters
\$opts['multiple'] = '4';

// Navigation style: B - buttons (default), T - text links, G - graphic links
// Buttons position: U - up, D - down (default)
\$opts['navigation'] = 'UG'; //'DB';

// Display special page elements
\$opts['display'] = array(
	'form'  => true,
	'query' => true,
	'sort'  => true,
	'time'  => true,
	'tabs'  => true
);

\$opts['logtable'] =  'qb_changelog';

/* Get the user's default language and use it if possible or you can
   specify particular one you want to use. Refer to official documentation
   for list of available languages. */
\$opts['language'] = \$HTTP_SERVER_VARS['HTTP_ACCEPT_LANGUAGE'];

/* Table-level filter capability. If set, it is included in the WHERE clause
   of any generated SELECT statement in SQL query. This gives you ability to
   work only with subset of data from table.

\$opts['filters'] = \"column1 like '%11%' AND column2<17\";
\$opts['filters'] = \"section_id = 9\";
\$opts['filters'] = \"PMEtable0.sessions_count > 200\";
*/

/* Field definitions

Fields will be displayed left to right on the screen in the order in which they
appear in generated list. Here are some most used field options documented.

['name'] is the title used for column headings, etc.;
['maxlen'] maximum length to display add/edit/search input boxes
['trimlen'] maximum length of string content to display in row listing
['width'] is an optional display width specification for the column
          e.g.  ['width'] = '100px';
['mask'] a string that is used by sprintf() to format field output
['sort'] true or false; means the users may sort the display on this column
['strip_tags'] true or false; whether to strip tags from content
['nowrap'] true or false; whether this field should get a NOWRAP
['required'] true or false; if generate javascript to prevent null entries
['select'] T - text, N - numeric, D - drop-down, M - multiple selection
['options'] optional parameter to control whether a field is displayed
  L - list, F - filter, A - add, C - change, P - copy, D - delete, V - view
            Another flags are:
            R - indicates that a field is read only
            W - indicates that a field is a password field
            H - indicates that a field is to be hidden and marked as hidden
['URL'] is used to make a field 'clickable' in the display
        e.g.: 'mailto:\$value', 'http://\$value' or '\$page?stuff';
['URLtarget']  HTML target link specification (for example: _blank)
['textarea']['rows'] and/or ['textarea']['cols']
  specifies a textarea is to be used to give multi-line input
  e.g. ['textarea']['rows'] = 5; ['textarea']['cols'] = 10
['values'] restricts user input to the specified constants,
           e.g. ['values'] = array('A','B','C') or ['values'] = range(1,99)
['values']['table'] and ['values']['column'] restricts user input
  to the values found in the specified column of another table
['values']['description'] = 'desc_column'
  The optional ['values']['description'] field allows the value(s) displayed
  to the user to be different to those in the ['values']['column'] field.
  This is useful for giving more meaning to column values. Multiple
  descriptions fields are also possible. Check documentation for this.
*/
");

	@mysql_select_db($db);
	$tb_desc = @mysql_query("DESCRIBE $tb");
	$fds     = @mysql_list_fields($db, $tb, $dbl);
	$num_fds = @mysql_num_fields($fds);
	$ts_cnt  = 0;
	for ($k = 0; $k < $num_fds; $k++) {
		$fd = mysql_field_name($fds,$k);
		$fm = mysql_fetch_field($fds,$k);
		$fn = strtr($fd, '_-.', '   ');
		$fn = preg_replace('/(^| +)id( +|$)/', '\\1ID\\2', $fn); // uppercase IDs
		$fn = ucfirst($fn);
		$row = @mysql_fetch_array($tb_desc);
		$label = str_replace('\'','\\\'',$fn);
		if ($arrLabel[$fd]) $label = $arrLabel[$fd];
		if (eregi(' ', $fd)) echo_buffer('$opts[\'fdd\'][\'`'.$fd.'`\'] = array('); // )
		else echo_buffer('$opts[\'fdd\'][\''.$fd.'\'] = array('); // )
		echo_buffer("  'name'     => '".$label."',");
		$auto_increment = strstr($row[5], 'auto_increment') ? 1 : 0;
		if (substr($row[1],0,3) == 'set') {
			echo_buffer("  'select'   => 'M',");
		} else {
			echo_buffer("  'select'   => 'T',");
		}
		if ($auto_increment) {
			echo_buffer("  'options'  => 'AVCPDR', // auto increment");
		}
		// timestamps are read-only
		else if (@mysql_field_type($fds, $k) == 'timestamp') {
			if ($ts_cnt > 0) {
				echo_buffer("  'options'  => 'AVCPD',");
			} else { // first timestamp
				echo_buffer("  'options'  => 'AVCPDR', // updated automatically (MySQL feature)");
			}
			$ts_cnt++;
		}
		echo_buffer("  'maxlen'   => ".@mysql_field_len($fds,$k).',');
		// blobs -> textarea
		if (@mysql_field_type($fds,$k) == 'blob') {
			echo_buffer("  'textarea' => array(");
			echo_buffer("    'rows' => 5,");
			echo_buffer("    'cols' => 50),");
		}
		// SETs and ENUMs get special treatment
		if ((substr($row[1],0,3) == 'set' || substr($row[1],0,4) == 'enum')
				&& ! (($pos = strpos($row[1], '(')) === false)) {
			$indent = str_repeat(' ', 18);
			$outstr = substr($row[1], $pos + 2, -2);
			$outstr = explode("','", $outstr);
			$outstr = str_replace("''", "'",  $outstr);
			$outstr = str_replace('"', '\\"', $outstr);
			$outstr = implode("\",\n$indent\"", $outstr);
			echo_buffer("  'values'   => array(\n$indent\"".$outstr.'"),');
		}
		// automatic support for Default values
		if ($row[4] != '' && $row[4] != 'NULL') {
			echo_buffer("  'default'  => '".$row[4]."',");
		} else if ($auto_increment) {
			echo_buffer("  'default'  => '0',");
		}
		if (stristr(@mysql_field_flags($fds, $k), 'not_null') && ! $auto_increment) {
			echo_buffer("  'required' => true,");
		}
		echo_buffer("  'sort'     => true");
		//echo_buffer("  'nowrap'   => false,");
		echo_buffer(');');
	}

	#$enableCols = '';
	#if ($rs->fields['cols']) {
	#	$p = split(',', $rs->fields['cols']);
	#	foreach ($p as $v) {
	#		$v = trim($v);
	#		$enableCols .= "unset(\$opts['fdd']['`".$v."`']['input']);\n";
	#	}

	$onInsert = $rs->fields['oninsert'];
	$onUpdate = $rs->fields['onupdate'];
	$onDelete = $rs->fields['ondelete'];
	$isDelete = $rs->fields['isdelete'];
	$readOnly = $rs->fields['readonly'];

	if ($onInsert) {
		$fileTIA = $baseFilename.".TIA.inc.php";
		$optsTIA = "\$opts['triggers']['insert']['after'] = '".$fileTIA."';";
		// write the content include file
//		echo 'Trying write <b>'.$fileTIA.'</b> ';
		$TIAhandle = @fopen('./'.$fileTIA, 'w+');
		if ($TIAhandle) {
			$TIAbuffer = "<"."? require_once 'auth.php';
			global \$adodb;
			//\$adodb->debug = 1;
			\$sql = \"".addslashes($onInsert)."\";
			\$p = explode(';', \$sql);
			foreach (\$p as \$key => \$sql) {
				\$sql = trim(\$sql);
				if (!\$sql) continue;
				foreach (\$newvals as \$k => \$v) {
					\$v = addslashes(\$v);
					\$sql = str_replace('['.\$k.']', \"'\$v'\", \$sql);
				}
				\$rs = \$adodb->Execute(\$sql);
				if (!\$rs) echo \$adodb->ErrorMsg();
			}
			\$adodb->debug = 0;
			?".">";
			fwrite($TIAhandle, $TIAbuffer);
			flush($TIAhandle);
			fclose($TIAhandle);
//			echo '<b><font color=green>Success</font></b><br>';
		} else {
//			echo '<b><font color=red>Failed</font></b><br>';
			exit;
		}
	}

	if ($onUpdate) {
		$fileTUA = $baseFilename.".TUA.inc.php";
		$optsTUA = "\$opts['triggers']['update']['after'] = '".$fileTUA."';";
		// write the content include file
//		echo 'Trying write <b>'.$fileTUA.'</b> ';
		$TUAhandle = @fopen('./'.$fileTUA, 'w+');
		if ($TUAhandle) {
			$TUAbuffer = "<"."? require_once 'auth.php';
			global \$adodb;
			\$rs2 = \$adodb->Execute(\"SELECT * FROM \".\$this->tb.\" \".
			\" WHERE \".\$this->key.\" = ?\", \$this->rec);
			//\$adodb->debug = 1;
			\$sql = \"".addslashes($onUpdate)."\";
			\$p = explode(';', \$sql);
			foreach (\$p as \$key => \$sql) {
				\$sql = trim(\$sql);
				if (!\$sql) continue;
				if (\$rs2->EOF) continue;
				foreach (\$rs2->fields as \$k => \$v) {
					\$v = addslashes(\$v);
					\$sql = str_replace('['.\$k.']', \"'\$v'\", \$sql);
				}
				\$rs = \$adodb->Execute(\$sql);
				if (!\$rs) echo \$adodb->ErrorMsg();
			}
			\$adodb->debug = 0;
			?".">";
			fwrite($TUAhandle, $TUAbuffer);
			flush($TUAhandle);
			fclose($TUAhandle);
//			echo '<b><font color=green>Success</font></b><br>';
		} else {
//			echo '<b><font color=red>Failed</font></b><br>';
			exit;
		}
	}

	if ($onDelete) {
		$fileTDA = $baseFilename.".TDA.inc.php";
		$optsTDA = "\$opts['triggers']['delete']['after'] = '".$fileTDA."';";
		// write the content include file
//		echo 'Trying write <b>'.$fileTDA.'</b> ';
		$TDAhandle = @fopen('./'.$fileTDA, 'w+');
		if ($TDAhandle) {
			$TDAbuffer = "<"."? require_once 'auth.php';
			global \$adodb;
			//\$adodb->debug = 1;
			\$sql = \"".addslashes($onDelete)."\";
			\$p = explode(';', \$sql);
			foreach (\$p as \$key => \$sql) {
				\$sql = trim(\$sql);
				if (!\$sql) continue;
				foreach (\$oldvals as \$k => \$v) {
					\$v = addslashes(\$v);
					\$sql = str_replace('['.\$k.']', \"'\$v'\", \$sql);
				}
				\$rs = \$adodb->Execute(\$sql);
				if (!\$rs) echo \$adodb->ErrorMsg();
			}
			\$adodb->debug = 0;
			?".">";
			fwrite($TDAhandle, $TDAbuffer);
			flush($TDAhandle);
			fclose($TDAhandle);
//			echo '<b><font color=green>Success</font></b><br>';
		} else {
//			echo '<b><font color=red>Failed</font></b><br>';
			exit;
		}
	}

	$disableCols = '';
	$piece = explode(",", $readOnly);
	foreach ($piece as $k => $v) {
		$v = addslashes(trim($v));
		$disableCols .= "if (\$opts['fdd']['".$v."']) {
			\$opts['fdd']['".$v."']['input'] = 'R';
		}";
	}

	$hiddenCols = '';
	foreach ($arrHidden as $k => $v) {
		$hiddenCols .= "if (\$opts['fdd']['".$k."']) {
			\$opts['fdd']['".$k."']['options'] = 'ACD';
		}";
	}

	if ($isDelete) {
		$disableCols = "
function flag_enabled(\$rec) {
	global \$adodb, \$opts;
	\$rs2 = \$adodb->Execute('SELECT * FROM '.\$opts['tb'].' '.
	' WHERE '.\$opts['key'].' = ? ', array(\$rec));
	if (\$rs2->EOF) return 1;
	\$sql = \"".addslashes($isDelete)."\";
	\$sql = trim(\$sql);
	if (!\$sql) return 1;
	foreach (\$rs2->fields as \$k => \$v) {
		\$v = addslashes(\$v);
		\$sql = str_replace('['.\$k.']', \"'\$v'\", \$sql);
	}
	\$rs = \$adodb->Execute(\$sql);
	if (\$rs->EOF) return 1;
	return 0;
}

if (flag_enabled(\$_REQUEST['rec']) === 0) {
".$disableCols."
}
";
	}


	#}

#foreach (\$opts['fdd'] as \$k => \$v) {
#	\$opts['fdd'][\$k]['input'] = 'R';
#}
#".$enableCols."
#if (\$userAction['editData']) \$opts['options'] .= '".$extraOpt."';
	$canInsert = $onInsert ? 'A' : '';
	$canUpdate = $onUpdate ? 'C' : '';
	$canDelete = $onDelete ? 'D' : '';

	echo_buffer("
".$disableCols."
".$hiddenCols."
".$optsTIA."
".$optsTUA."
".$optsTDA."
\$opts['fdd']['qb_id']['input'] = 'H';
if (\$isSupervisor) {
	\$userAction['add'] = 1;
        \$userAction['change'] = 1;
	\$userAction['delete'] = 1;
	\$userAction['list'] = 1;
	\$userAction['filter'] = 1;
	\$userAction['copy'] = 1;
} else {
        \$userAction = getReportActions(\$_SESSION['userid'], '".$rs->fields['name']."');
}
if (\$userAction['add']) \$opts['options'] .= '".$canInsert."';
if (\$userAction['change']) \$opts['options'] .= '".$canUpdate."';
if (\$userAction['delete']) \$opts['options'] .= '".$canDelete."';
if (!\$userAction['list']) \$opts['filters'] = '1=0';
if (\$userAction['filter']) \$opts['options'] .= 'F';
#if (\$userAction['copy']) \$opts['options'] .= 'P';

".$smartyHeader."


// Now important call to phpMyEdit
global \$phpme;
require_once 'phpMyEdit3.class.php';
\$phpme = new phpMyEdit(\$opts);
".$calculate."
".$smartyFooter."

?>
");

	$css_directive = <<<END
<style type="text/css">
	table { border: #004d9c 1px solid; border-collapse: collapse; border-spacing: 0px; width: 100%; }
	th    { border: #004d9c 1px solid; padding: 4px; background: #add8e6; }
	td    { border: #004d9c 1px solid; padding: 3px; }
	hr    { border: 0px solid; padding: 0px; margin: 0px; border-top-width: 1px; height: 1px; }
</style>
END;

	$css_directive = <<<END
<link rel="stylesheet" href="phpME.css" type="text/css"></link>
END;
	if (! $CSSstylesheet) {
		$css_directive = '';
	}

	if ($HTMLissues) {
		$htmlbuffer = <<<END
<?php require_once 'auth.php'; ?>
<?php
ini_set('max_execution_time', 0);
/*
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
		"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<title>$pageTitle</title>
$css_directive
</head>
<body>
*/
?>
END;

		/*
		$htmlbuffer .= "
<script language=javascript>
	function windowOpen(u,W,H) {
		TopPosition = (screen.height) ? (screen.height-H)/2 : 0;
		LeftPosition = (screen.width) ? (screen.width-W)/2 : 0;
		settings = 'height='+H+',width='+W+',top='+TopPosition+',left='+LeftPosition+
		',scrollbars=1,resizable=0,toolbar=0,location=0,directories=0,status=0,menubar=0';
		win  = window.open(u,'_blank',settings);
		return win;
	}

	function exporttable(tb) {
		//windowOpen('exporttable.php?tableid='+tb, 600, 200);
		location.href = ('exporttable.php?tableid='+tb);
	}
</script>
<h3>$pageTitle
<input type=button value='".__('Export CSV')."' onClick='exporttable(\"$tb\")'>
</h3>
";
		*/


		$buffer = $htmlbuffer."\n" . $buffer;
	} else if ($CSSstylesheet) {
		$buffer = $css_directive . $buffer;
	}
	if ($HTMLissues) {
		$buffer .= "
		<script language=javascript>
		top.window.moveTo(0,0);
		if (document.all) {
		top.window.resizeTo(screen.availWidth,screen.availHeight);
		}
		else if (document.layers||document.getElementById) {
		if (top.window.outerHeight<screen.availHeight||top.window.outerWidth<screen.availWidth){
		top.window.outerHeight = screen.availHeight;
		top.window.outerWidth = screen.availWidth;
		}
		}
		</script>
		";
		$buffer .= "</body>\n";
		$buffer .= "</html>\n";
	}
	// write the content include file
//	echo 'Trying to write content file to: <b>'.'./'.$contentFile.'</b><br>'."\n";
	$filehandle = @fopen('./'.$contentFile, 'w+');
	if ($filehandle) {
		fwrite($filehandle, $buffer);
		flush($filehandle);
		fclose($filehandle);
//		echo 'phpMyEdit content file written successfully<br>';

		/* QBUILDER TRAP */
		echo "
		<script language=javascript>
		location.href = '$contentFile';
		</script>
		";
		/* QBUILDER TRAP */
	} else {
//		echo 'phpMyEdit content file was NOT written due to inssufficient privileges.<br>';
//		echo 'Please copy and paste content listed below to <i>'.'./'.$contentFile.'</i> file.';
	}
//	echo '<br><hr>';
//	echo '<pre>';
	echo_html($buffer);
	echo '</pre><hr>'."\n";
}

?>

</body>
</html>
