<?

/*/
	© 2001-2004 by Locke Enterprises (iLocke.com) - All rights reserved.
	License:  Authorized for use on the AutoGlassHosting.com website.
	File:  inc/Reporting.phi
	Purpose:  Extensible reporting module.
	Created:  7/3/2001 - Nathan
	Modification History:
		· 7/10/2001 - Nathan - developed the initial routines and schema for this module
		· 6/18/2004 - Nathan - introduced a basic/core report(s) for the AutoGlassHosting.com website
		· 7/3/2004 - Nathan - redeployed to use the new GLOBAL / NDB constructs
		· 8/24/2004 - Nathan - extracted these core elements out into a separate module
		· 10/27/2004 - Nathan - added the maxRows and rActions parameters to ShowResults
		· 11/27/2004 - Nathan - new permissions scheme for !/subsystem elements; implemented REPORTING_SUBSYSTEM
		· mm/dd/yyyy - [name] - [comment]
/*/


	/// when logged in, certain actions should NOT be done by users; only the programmer
	$A = $_REQUEST['A'];
	if( !isset($REPORTING_SUBSYSTEM) ) {
		$REPORTING_SUBSYSTEM = false;
		if( isset($_SESSION["ADMIN_LEVEL"]) && intval($_SESSION["ADMIN_LEVEL"])>0 && eregi("^!",$A) ) {
			if( intval($_SESSION["ADMIN_LEVEL"]) >= 9 ) $REPORTING_SUBSYSTEM = true;  // must be superadmin to automatically run ! actions
		}
	}

	/// initz...
	UseAlternateDB();
	if( $bMagicQuotes ) {
		$SQL = stripSlashes($SQL);
		$SQL2 = stripSlashes($SQL);
		$CMD = stripSlashes($CMD);
	}

	/// stock flags...
	$bHandled = true;
	$bFocus = true;

/*/ -- Stock dbadmin actions. -- /*/
	if( $REPORTING_SUBSYSTEM !== true ) {
		$bHandled = false; // then do *nothing*
/// advanced user selection entry...
	} elseif( $A=="FORM" || $A=="S!" ) {
		if( $SQL!="" ) ShowSelectResults( "Custom Query", $SQL );
		else CustomSelectForm( $SQL=="" );
/// admin custom querying...
	} elseif( $A=="!" ) {
		if( $SQL != "" ) ShowResults( "Custom Query", $SQL );
		CustomForm( $SQL=="" );
	} elseif( $A=="!SQL2" || $A=="!SQL2-RUN" ) {
		if( $SQL!="" )
			if( $SQL2!="" ) Execute2D( $SQL, $SQL2, ($SaveSQLs2=="Y") );
			else $bFocus = ShowResults( "Custom Query", $SQL );
		CustomSelectForm2D( $SQL2=="" && $bFocus );
/// db management...
	} elseif ( $A=="!ST" ) {
		ShowTables();
		CustomForm(false);
	} elseif ( $A=="!DELF" ) {
		DeleteFrom( $table );
	} elseif ( $A=="!DROPF" ) {
		DropFrom( $table );
	} elseif( $A=="!DB" ) {
		if( isset($db) && $db!="" ) UseAlternateDB( $db );
		ShowChangeLinks();
		CustomForm(false);
/// all tables commands...
	} elseif( $A=="!A-RT" ) {
		AllTablesCommandRun( "REPAIR TABLE", true );
	} elseif( $A=="!A-OT" ) {
		AllTablesCommandRun( "OPTIMIZE TABLE", true );
	} elseif( $A=="!A-SC" ) {
		AllTablesCommandRun( "SHOW CREATE TABLE", true );
	} elseif( $A=="!A-E" ) {
		AllTablesCommandRun( "EXPLAIN", true );
/// auto-execute SQLs...
	} elseif ( $A=="!AUTOX" ) {  // include some special handling
		$transID = intval(getField("SELECT max(transID) FROM sql")) + 1;
		mysql_query("UPDATE sql SET transID=$transID WHERE executed='N'");  // AND transID=0
		echo "Executing <b>".getField("SELECT Count(*) FROM sql WHERE transID=$transID")."</b> commands...";
		SQL_AutoExecutor($transID);
		$hData = mysql_query("SELECT * FROM sql WHERE transID=$transID AND successful='N'");
		echo " &nbsp; (".mysql_num_rows($hData)." unsuccessful)<br>\n";
		if( mysql_num_rows($hData) ) showData($hData);
		CustomForm(false);
/// special utils...
	} elseif( $A=="!MYD" ) {
		MysqlDumper();
/// system...
	} elseif( $A=="!_SYSFORM" ) {
		SystemForm();
	} elseif( $A=="!_SYSRUN" ) {
		SystemRun();
	} elseif ( $A=="!_VARS" ) {
		ShowVarsInfo();
	} else {
		$bHandled = false;
	}
	if( $bHandled ) exit;
	

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/// high level admin functions...
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


///-------------------------------------------------------------------------
function CustomForm( $bFocus ) {

	global $PHP_SELF, $g_oNDB, $SQL;
	
	?>
	<form name=CustomForm action=<? echo $PHP_SELF; ?> method=POST>
		<input type=hidden name="A" value="!">
		<b><u>Custom Query</u></b><font style='font-size: 4px;'><br><br></font>
		<textarea name="SQL" class=normal style='font-family: Courier New, Courier;' cols=60 rows=10 wrap=soft><? echo $SQL; ?></textarea>
		<br><br>
		<input type=submit class=button value="Run the Query"> &nbsp;
		<? echo "<b>".$g_oNDB->getField("SELECT Database()")."</b>"; ?>
	</form><br>
	<?
	AdminLinks();
	if( $bFocus ) echo "<script language=JavaScript>document.CustomForm.SQL.focus();</script>";

} // CustomForm()


//-------------------------------------------------------------------------
// ShowChangeLinks:  Display links to change the CurrentDB.
//-------------------------------------------------------------------------
function ShowChangeLinks() {

	global $g_oNDB;

	$curdb = $g_oNDB->getField("SELECT Database()");
	echo "Current Database:&nbsp; <b>".$curdb."</b><br><br><br>\n";
	echo "<u><b>Change DB Links</b></u><br><br>\n";
	$AllData = $g_oNDB->getArrayFromQuery("SHOW DATABASES");
	foreach( $AllData as $rData ) {
		echo ereg_replace("^0","&nbsp;",sprintf("%02d",++$i)) . "&nbsp; <a href='$PHP_SELF?A=!DB&db=".$rData[0]."'>".($rData[0]==$curdb?"<b style='color: #C80000;'>":"").$rData[0]."</b></a><br>\n";
	}
	echo "<br>\n";

} // ShowChangeLinks()


//-------------------------------------------------------------------------
// UseAlternateDB:  Connect to an alternate database.
//-------------------------------------------------------------------------
function UseAlternateDB( $db="" ) {

	global $g_oNDB, $g_Config;

	if( $db!="" ) {
		echo "<p class=action>&gt;&gt; Changed to:&nbsp; <font color=#0000C0>".($_SESSION['CurrentDB'] = $db)."</font></p>\n";
	}

	if( isset($_SESSION['CurrentDB']) && $_SESSION['CurrentDB']!="" ) {
		$g_oNDB->open( $_SESSION['CurrentDB'], $g_Config->dbInfo['user'], $g_Config->dbInfo['password'] );  // allow alternate db
	}

} // UseAlternateDB()


//-------------------------------------------------------------------------
// ShowTables:  Display a list of the tables and some useful links.
//-------------------------------------------------------------------------
function ShowTables() {

	global $PHP_SELF, $g_oNDB;
	
	?>
	<table border=0 bordercolor=red cellspacing=0 cellpadding=0><tr valign=top><td colspan=1 align=left valign=top bgcolor=#808080>
	<table border=0 bordercolor=red cellspacing=1 cellpadding=2>
		<tr bgcolor=#C0E8F8>
			<td><b>Table</b></td>
			<td><b>Count</b></td>
			<td colspan=5 align=center style='text-align: center;'><b>Actions</b></td>
		</tr>
	<?
	
	$i = 0;
	$oNRS = new nRS("SHOW TABLES");
	while( $rTable = $oNRS->read() ) {
		echo "<tr bgcolor=".($i++%2==0?"#F0F0F0":"#E0E0E8").">";
		echo "<td>&nbsp; <a class=thin href=\"".$PHP_SELF."?A=!&SQL=SELECT+*+FROM+$rTable[0]+LIMIT+25\">$rTable[0]</a> &nbsp;</td>";
		echo "<td align=right>" . $g_oNDB->getField(0,"SELECT Count(*) FROM $rTable[0]") . "</td>";
		echo "<td align=center>&nbsp; <a class=thin href=\"".$PHP_SELF."?A=!&SQL=EXPLAIN+$rTable[0]\">Explain</a> &nbsp;</td>";
		echo "<td align=center>&nbsp; <a class=thin href=\"".$PHP_SELF."?A=!&SQL=SHOW+CREATE+TABLE+".$rTable[0]."\">Show Create</a> &nbsp;</td>";
		echo "<td align=center>&nbsp; <a class=thin onClick=\"return confirm('Really DELETE all data from [".$rTable[0]."] ?? &nbsp; &nbsp;');\" style='color: #C00000' href=\"".$PHP_SELF."?A=!DELF&table=$rTable[0]\">Delete ALL</a> &nbsp;</td>";
		echo "<td align=center>&nbsp; <a class=thin onClick=\"return confirm('Really DROP the [".$rTable[0]."] table ?? &nbsp; &nbsp;');\" style='color: #C00000' href=\"".$PHP_SELF."?A=!DROPF&table=".$rTable[0]."\">DROP</a> &nbsp;</td>";
		echo "</tr>";
	}
	echo "</table>";
	echo "</td></tr></table>";
	
} // ShowTables()


//-------------------------------------------------------------------------
// DeleteFrom:  A confirmation form to delete out the contents of a table.
//-------------------------------------------------------------------------
function DeleteFrom( $table ) {
	
	global $PHP_SELF;
	
	echo "Really delete ALL of the contents of the <b>`$table`</b> table?!<br><br>";
	echo "<a style='color: #C00000' href=\"".$PHP_SELF."?A=!ST\">&nbsp; NO &nbsp</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ";
	echo "<a style='color: #00A000' href=\"".$PHP_SELF."?A=!&SQL=DELETE+FROM+$table\">&nbsp; YES &nbsp</a><br><br>";

} // DeleteFrom


//-------------------------------------------------------------------------
// DropFrom:  A confirmation form to delete out the contents of a table.
//-------------------------------------------------------------------------
function DropFrom( $table ) {
	
	global $PHP_SELF;
	
	echo "Really DROP the <b>`$table`</b> table?!<br><br>";
	echo "<a style='color: #C00000' href=\"".$PHP_SELF."?A=!ST\">&nbsp; NO &nbsp</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ";
	echo "<a style='color: #00A000' href=\"".$PHP_SELF."?A=!&SQL=DROP+TABLE+$table\">&nbsp; YES &nbsp</a><br><br>";

} // DropFrom


/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/// main utility functions...
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


///-------------------------------------------------------------------------
function ShowResults( $Title, $SQL, $maxRows=300, $rActions=null ) {

	global $PHP_SELF, $g_oNDB;
	
	/// special handling for a 'show tables' command...
	if( strtoupper(trim($SQL))=="SHOW TABLES" ) {
		ShowTables();
		return true;
	}
	
	/// a regular query...
	echo "<nobr><b><u>".$Title."</u></b><!-- &nbsp; <font face='Courier New'>SQL: &nbsp; \"\n\n".$SQL."\n\n\"</font>--></nobr><font style='font-size: 4px;'><br><br></font>\n";
	$oNRS = new nRS();
	if( !$oNRS->open($SQL) ) {
		echo "<br><font color=#C00000><b>ERROR:</b>&nbsp; " . $oNRS->message . "</font><br><br><br>";
		return false;
	}
	if( $oNRS->success ) {
		echo "<br><font color=#00A000><b>Query successful.</b></font><br><br><br>";
	} else {
		if( eregi("SHOW CREATE TABLE",trim($SQL)) ) {
			$rData = $oNRS->read();
			printArray( array($rData[0] => "<pre>".$rData[1]), false );
			echo "</pre>";
		} else {
			$oNRS->showData( (true && $rActions==null), "", $maxRows, $rActions );  // pass the display off when we can, but nRS->printArray() won't support the actions
		}
	}
	echo "<br>\n";
	return true;
	
} // ShowResults()


///-------------------------------------------------------------------------
function ShowSelectResults( $Title, $SQL ) {

	global $PHP_SELF, $g_oNDB;
	
	/// be sure this type of query is allowed...
	if( !eregi("^[[:space:]]*SELECT ",$SQL) ) {
		if( !eregi("^[[:space:]]*SHOW ",$SQL) ) {
			if( !eregi("^[[:space:]]*EXPLAIN ",$SQL) ) {
				echo "Unallowed Query";
				exit;
			}
		}
	}

	/// perform the query and display the results...
	echo "<font size=4><u>".$Title."</u></font>\n<blockquote>\n";
	echo "<nowrap><pre>SQL: &nbsp; \"".$SQL."\"</pre></nowrap><br>\n";
	$
	$hData = mysql_query( $SQL, $hDB );
	echo mysql_num_rows($hData)." matching items<br>";
	$oNRS = new nRS();
	if( !$oNRS->open($SQL) ) {
		echo "<br><font color=#C00000><b>ERROR:</b> " . $oNRS->message . "</font><br><br><br>";
		return;
	}
	$oNRS->showData();
	echo "</blockquote>\n<a href='".$PHP_SELF."'>Action List</a><br>\n";
	
} // ShowSelectResults()


//-------------------------------------------------------------------------
// ShowResultRow:  Show the row and return the value in the last column.
//-------------------------------------------------------------------------
function ShowResultRow( $RowName, $SQL, $align="right" ) {

	global $hDB;
	
	$oNRS = new nRS($SQL);
	if( $oNRS->reading ) {
		if( $rData = $oNRS->read() ) {
			$fields = mysql_num_fields($hData);
			echo "\t<tr bgcolor=#F8F8F8><td>$RowName</td>\n";
			for( $k=0; $k<$fields; $k++) {
				echo "\t\t<td nowrap align=$align>".$rData[$k]."</td>\n";
				$returnvalue = $rData[$k];
			}
			echo "\t</tr>\n";
		}
		mysql_free_result($hData);
	} else {
		echo "<tr bgcolor=#E8E8E8><td align=center><font color=#808080>(no results)</td></tr>";
	}
	return $returnvalue;

} // ShowResultRow()


///-------------------------------------------------------------------------
/// ExportResults:  Print results of each column of the query in CSV format.
///-------------------------------------------------------------------------
function ExportResults( $ExportFilename, $SQL, $fields=NULL, $maxRows=1000 ) {

	global $PHP_SELF, $g_oNDB;
	
	// sort this out
	header( "Content-type: text/csv\r\n" );
	header( "Content-disposition: attachment; filename=\"".$ExportFilename."\"\r\n" );

	// init
	$i = 0;
	$num = 0;
	$oNRS = new nRS($SQL);
	
	// export fields
	if( $fields !== NULL && is_array($fields) ) {
		for( $i=0; $i<count($fields); $i++ ) {
			if( $i > 0 ) {
				echo ",";
			}
			echo str_replace(",", ";", $fields[$i]);
		}
		echo "\n";
	}

	// export data
	while( $rTable = $oNRS->read() ) {
		for( $i=0; $i<count($rTable); $i++ ) {
			if( $i > 0 ) {
				echo ",";
			}
			echo str_replace(",", ";", $rTable[$i]);
		}
		echo "\n";
		if( ++$num >= $maxRows ) {
			break;
		}
	}
	exit;
	
} // ShowResults()


///-------------------------------------------------------------------------
function CustomSelectForm () {

	global $PHP_SELF, $SQL;
	?>
	<form action=<? echo $PHP_SELF; ?> method=POST>
		<input type=hidden name="A" value="S!">
		<textarea name="SQL" class=normal cols=60 rows=10 wrap=soft><? echo $SQL; ?></textarea>
		<br><br>
		<input type=submit class=button value="Run the Query">
	</form>
	<?

} // CustomSelectForm()


//-------------------------------------------------------------------------
// AllTablesCommandRun:  Run a command on all tables in the database. (ie: "REPAIR TABLE")
//-------------------------------------------------------------------------
function AllTablesCommandRun( $command="REPAIR TABLE", $bAdmin=false ) {

	echo "Running '$command' on all tables...<br><br>\n";
	$hTables = mysql_query("SHOW TABLES");
	while( $rTable = mysql_fetch_array($hTables) ) {
		$SQL = $command." ".$rTable[0];
		if( !($hData = mysql_query($SQL)) ) {
			echo $rTable[0].": ERROR = ".mysql_error()."<br>$SQL<br><br>\n";
			continue;
		}
		$numRows = intval(@mysql_num_rows($hData));
		if( $numRows <= 1 ) {
			$rData = mysql_fetch_array($hData);
			if( $rData['Op']=="repair" && $rData['Msg_type']=="status" && $rData['Msg_text']=="OK" ) {
				echo $rTable[0] . ": REPAIRED<br>\n";
			} else {
				if( eregi("^CREATE TABLE", $rData['Create Table']) ) {
					ereg_replace("PRIMARY KEY","\nPRIMARY KEY",$rData['Create Table']);
					$rData['Create Table'] = nl2br($rData[1]);
				}
				PrintArray($rData);
			}
		} else {
			showData($hData);
		}
		echo "<br>";
	}
	echo "<br>...done<br><br>\n";
	if( $bAdmin ) AdminLinks();

} // AllTablesCommandRun()


//-------------------------------------------------------------------------
// MysqlDumper:  Generate output similar to a `mysqldump` command. Defaults to deleting all intermediary files.
//-------------------------------------------------------------------------
function MysqlDumper() {

	echo "<br>\n<br>\n- DISABLED -";

	exit;
	/// initz...
	set_time_limit(180);
	global $g_oNDB, $limit, $cleanup;
	if( $limit>0 ) $limit = " LIMIT $limit";
	$bCleanup = (!isset($cleanup) || $cleanup!="N") ? true : false;
	
	/// create an output destination folder...
	//$mainfolder = "/usr/shared/web/boom16/admin/backup/";
	$mainfolder = "/usr/local/www/vhosts/eagleenergyinc.com/htdocs/admin/backup/";
	$timestamp = date("Y-m-d_H-i-s");
	$subfolder = $mainfolder."sql_".$timestamp;
	system( "mkdir $subfolder" );
	$subfolder .= "/";
	
	/// test the destination folder...
	$testfile = $subfolder.".test";
	if( !($FH = fopen($testfile,"w")) ) {
		echo "Error opening output file.";
		return false;
	}
	fclose( $FH );
	system( "rm ".$testfile );

	/// get all tables and print out all rows then column data...
	$hTables = mysql_query("SHOW TABLES");
	while( $rTable = mysql_fetch_row($hTables) ) {
		$table = $rTable[0];
		if( $hData = mysql_query("SELECT * FROM ".$table.$limit) ) {
			echo "Writing output for <b>$table</b>... ";
			flush();
			/// create the table's file...
			$filename = $subfolder.$table.".sql";
			if( !($FH = fopen($filename,"w")) ) {
				echo "Error creating output file for $table.";
				return false;
			}
			/// dump in the create table command...
			$line = "\n\n\n### ".$rTable[0]." - ".mysql_num_rows($hData)." rows\n\n";
			$line .= $g_oNDB->getField(1,"SHOW CREATE TABLE ".$rTable[0],"(could not retrieve CREATE TABLE)").";\n\n";
			fputs( $FH, $line );
			/// compile an insert command for each row...
			while( $rData = mysql_fetch_row($hData) ) {
				/// column values - just quote everything...
				$values = "";
				for( $i=0; $i<count($rData); $i++ ) {
					$values .= "'".addslashes($rData[$i])."',";
				}
				/// print the insert line...
				if( $values!="" ) {
					$values = substr($values,0,strlen($values)-1);
					fputs( $FH, "INSERT INTO ".$table." VALUES(".$values.");\n" );
				}
			}
			echo "done!<br>\n";
			fputs( $FH, "\n\n\n" );
			fclose( $FH );
			exec( "chmod 0777 ".$filename );
			flush();
		}
	}

	/// archive the sql files...
	$filename = $mainfolder."sql_".$timestamp.".tar";
	$msg = exec( "tar -cvf ".$filename." ".$subfolder."*.sql");
	$msg = exec( "CHMOD 0777 ".$filename );
	echo "COMPLETED WRITING CREATING TARBALL: ".$filename." &nbsp; &nbsp; ".$msg."<br>\n";
	//$text = system("/usr/bin/gzip -c9 $filename > $filename".".gz");
	$msg = exec( "/usr/bin/gzip -9 ".$filename );
	echo "<font color=#00A000><b>DONE!</b></font> - gZipped as: ".$filename.".gz &nbsp; &nbsp; ".$msg."</b></font><br>\n";
	flush();
	
	/// when  cleanup was requested...
	if( $bCleanup ) {
		$msg = system( "rm ".$subfolder."*.sql" );
		$msg = system( "rmdir ".$subfolder );
	}
	
	/// all done...
	AdminLinks();
	return true;

} // MysqlDumper()


///-------------------------------------------------------------------------
function SystemForm() {

	global $PHP_SELF, $CMD;
	
	?>
	<form action=<? echo $PHP_SELF; ?> method=POST>
		<input type=hidden name="A" value="!_SYSRUN">
		<textarea name="CMD" style='color: white; background: black; font-family: Courier New, Courier, Monospace; font-size: 12px;' cols=60 rows=3 wrap=soft><? echo $CMD; ?></textarea>
		<br><br>
		<input type=submit class=button style='color: #E0E0C0; background: #800000; border: #B0B0C8 2px outset; ' value="Run the Command">
	</form>
	<br>
	<?
	AdminLinks();

} // SystemForm()


///-------------------------------------------------------------------------
function SystemRun() {

	global $CMD;
	
	echo "<pre style='color: #000000; background: #F0F0F0; border: #808080 1px solid;padding: 10px; font-family: Courier New, Courier, Monospace; font-size: 12px; font-weight: bold;'>";
	system($CMD);
	echo "</pre>";
	
	SystemForm();

} // SystemRun()


///-------------------------------------------------------------------------
function ShowVarsInfo() {

	global $g_oNDB, $tick;
	
	/// all done...
	AdminLinks();
	
	/// PHP info...
	if( $tick!="" ) echo "magic quotes are <b>".($tick=="'" ? "OFF" : "ON")."</b><br>\n";
	echo "PHP Version: ".phpversion()."<br>\n";
	echo "_SESSION (not HTTP_SESSION_VARS)<br>\n";
	printArray( $_SESSION );  // _SESSION
	echo "<br>\n";

	/// server info...
	echo "_SERVER (not HTTP_SERVER_VARS)<br>\n";
	printArray( $_SERVER );  // $_SERVER
	echo "<br>\n";
	
	/// show all of the ini/gpc settings if possible...
	echo "<br><br><br>INI settings...<br>";
	$a = ini_get_all();
	$i = 0;
	$output="<table border=0 cellspacing=1 cellpadding=1 bgcolor=#C0C0C0>";
	while( list($key, $value) = each($a) ) {
		list($k, $v)= each( $a[$key] );
		$output .= "<tr bgcolor=".(++$i%2==0?"#FFFFFF":"#F4F4F4")."><td>$key</td><td>$v</td><td>$k</td></tr>";
	}
	$output.="</table>"; //Finish up
	echo $output; //Spit it all out

	/// session # testing...
	$sessionID = session_id();
	$sessionNum = hexdec($sessionID);
	//$sessionNum = hexdec(substr($sessionID,0,16));
	//$sessionNum = sprintf( "%.32d", $sessionNum );
	$sessionNum = number_format( $sessionNum, 32, "", "" );
	echo "<br>$sessionID == $sessionNum<br><br>\n";

	/// [NL:2018] (disabled) MySQL Informations...
	//echo "<hr><br>MySQL Version: " . $g_oNDB->getField("SELECT Version()") . "<br>\n";
	//ShowTables();
	//echo "<br><hr><br>";

	/// variables...
	echo "GLOBALS<pre>\n";
	print_r( $GLOBALS );
	//var_dump( $GLOBALS );
	echo "</pre>\n";

	/// random testing...
	echo "TESTING...<pre>\n";
	$temp = "memberID=1234:productID=4321";
	eregi("memberID=(.*):productID=(.*)$",$temp,$regs);
	$memberID = intval($regs[1]);
	$productID = intval($regs[2]);
	echo "<br>MEMBER / Product: '$memberID' : '$productID'<br>";
	list( $a, $b, $c ) = array( "'AA", "B'B", "CC'" );
	echo "ABC1 = $a:$b:$c<br>\n";
	

} // ShowVarsInfo()


///-------------------------------------------------------------------------
function CustomSelectForm2D( $bFocus=true ) {

	global $PHP_SELF, $SQL, $SQL2, $SaveSQLs2;
	?>
	<form name=CustomSelectForm action="<? echo $PHP_SELF; ?>" method=POST>
		<input type=hidden name="A" value="!SQL2-RUN">
		SQL data source:<br>
		<textarea name="SQL" class=normal style='font-family: Courier New;' cols=80 rows=8 wrap=soft><? echo htmlspecialchars($SQL); ?></textarea><br><br>
		2D SQL:<br><textarea class=normal style='font-family: Courier New; color: #0000C0; background: #FCFCEC;' name=SQL2 cols=80 rows=4 wrap=soft><? echo htmlspecialchars($SQL2); ?></textarea><br>
		<input type=checkbox name=SaveSQLs2 value='Y'<? if($SaveSQLs2=="Y") echo " CHECKED"; ?>> Save as CMDs the `SQL` table (otherwise just displays first 25)<br>
		<br><input type=submit class=button value="Run the Query">
	</form>
	<?
	AdminLinks();
	if( $bFocus ) echo "<script language=JavaScript>document.CustomSelectForm.SQL.focus();</script>";
	
} // CustomSelectForm2D()


//-------------------------------------------------------------------------
// Execute2D:  Execute a 2-Dimensional SQL querying.
// SQL:   SELECT signup.ID as signupID, studentID, schoolName, school, username FROM customer LEFT JOIN signup ON customer.id=signup.studentID WHERE teacher='elmprep' AND school<>schoolName ORDER BY customer.ID desc
// SQL2:  UPDATE signup SET school='$school' WHERE ID=$signupID
//-------------------------------------------------------------------------
function Execute2D( $SQL, $SQL2, $bRun ) {

	/// initz; get the field names...
	echo "<u><b>Execute2D</b></u><pre>\n";
	$hData = mysql_query($SQL);
	$fields = array();
	for( $i=0; $i<mysql_num_fields($hData); $i++ ) {
		$fields[] = mysql_field_name($hData, $i);
	}
	if( mysql_num_rows($hData) < 1 ) echo "(no results returned from the SQL1)<br><br>\n";
	
	/// print out or save as a CMD each output row...
	$counter = 0;
	$inserted = 0;
	while( $rData = mysql_fetch_array($hData) ) {
		if( !$bRun && ++$counter > 25 ) {
			echo "</pre>";
			return;
		}
		$CMD = $SQL2;
		for( $i=0; $i<count($fields); $i++ ) {
			$CMD = str_replace('$'.$fields[$i], mysql_escape_string($rData[$i]), $CMD);
		}
		if( $bRun ) {
			$inserted++;
			mysql_query("INSERT INTO sql SET cmd='".mysql_escape_string($CMD)."'");
		} else {
			echo $CMD."\n";
			printArray($rData,true,false,true);
			echo "<br>\n";
		}
	}
	echo "</pre>";
	if( $inserted>0 ) {
		echo "<b>".$inserted."</b> sql cmds inserted<br><br>\n";
		printArray(getRow("SELECT * FROM sql ORDER BY ID DESC LIMIT 1"));
	}

} // Execute2D


///-------------------------------------------------------------------------
function RegularLinks() {

	/* NYI */

} // RegularLinks()


//-------------------------------------------------------------------------
// AdminLinks:  Links for the the superadmin N user.
//-------------------------------------------------------------------------
function AdminLinks() {

	?>
	<a href="<?=$PHP_SELF?>?A=!ST" style="font-weight: bold;">Show Tables</a> &nbsp;&middot;&nbsp; 
	<a href="<?=$PHP_SELF?>?A=!" style="color: #207010;">Custom Query</a> &nbsp;&nbsp;|&nbsp;&nbsp; 
	<b>All:</b>&nbsp;&nbsp;
	<a href="<?=$PHP_SELF?>?A=!A-OT">Optimize</a> &nbsp;&middot;&nbsp; 
	<a href="<?=$PHP_SELF?>?A=!A-RT">Repair</a> &nbsp;&middot;&nbsp; 
	<a href="<?=$PHP_SELF?>?A=!A-E">Explain</a> &nbsp;&middot;&nbsp; 
	<a href="<?=$PHP_SELF?>?A=!A-SC">Show Create</a><br>
	<a href="<?=$PHP_SELF?>?A=!DB">Change DB</a> &nbsp;&middot;&nbsp; 
	<a href="<?=$PHP_SELF?>?A=!MYD">MySQL Dumper</a> &nbsp;&middot;&nbsp;
	<a href='<?=$PHP_SELF?>?A=!SQL2'>2D-CMD</a> &nbsp;&middot;&nbsp; 
	<a href='<?=$PHP_SELF?>?A=!AUTOX'>SqlExecutor</a> &nbsp;&nbsp;|&nbsp;&nbsp; 
	<a href="<?=$PHP_SELF?>?A=!_VARS&tick='" style="color: #207010;">Show Vars</a> &nbsp;&middot;&nbsp; 
	<a href="<?=$PHP_SELF?>?A=!_SYSFORM" style="color: #C00000;">System Command</a>
	<br><br>&nbsp;
	<?

 } // AdminLinks()


?>