<?php
/*
* vi: set ts=4 :
*
* WebCompiler Main Page
*
* Copyright (C) 2004-2005 David "BAILOPAN" Anderson and the AMX Mod X Development Team
* Copyright (C) 2005-2010 NiLuJe <niluje@ak-team.com>
*
* $Id: webcompiler.php 6335 2010-06-01 23:48:50Z NiLuJe $
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*
*/

//note: this will not be difficult to port to metacms.
/**********************************************/

/* SVN Id */
$MY_SVN_ID = '$Id: webcompiler.php 6335 2010-06-01 23:48:50Z NiLuJe $';

/* GenTime */
$pg_start = microtime( true );

/* Gen URL */
$me = $_SERVER['PHP_SELF'];
$Apathweb = explode('/', $me);
$MY_NAME = array_pop($Apathweb);
$pathweb = implode("/", $Apathweb);
$MY_URI = 'http://'.$_SERVER['HTTP_HOST'].$pathweb.'/'.$MY_NAME;
$MY_CSS = str_replace( $MY_NAME, "webcomp_style.css", $MY_URI );

/* Config selon version */
/* Cookies */
$cookie_ltime = time()+60*60*24*30*12;

/* Essaye d'utiliser la langue par défaut du browser. On fait ça un peu à la bourrin, en n'utilisant que la toute première langue préferée... (On ne boucle donc _pas_ sur tout l'array en jouant avec les poids de préférence et tout). */
$browser_lang_arr = explode( ',', $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
$browser_lang = strtolower( substr( chop( $browser_lang_arr[0] ), 0, 2 ) );

$vars_arr = array( 'amxver' => 'amxx181', 'dbglvl' => '1', 'lang' => $browser_lang, 'adv' => 'off' );

foreach( $vars_arr as $key => $value )
{
	/* Setcookie seulement sur le POST */
	$var_is_post = is_post( $key );

	if ( $key == "adv" && $var_is_post === false && $_POST ) // Workaround pour la checkbox, si elle n'est pas cochée, $_POST['adv'] n'existe pas, donc is_post retourne false. (Peut pas faire un simple !, vu que si $var_is_post = 0, ça passerait dedans, or ça peut être le cas pour dbglvl)
		setcookie( $key, 'off', $cookie_ltime );

	if ( $var_is_post !== false )
		setcookie( $key, $var_is_post, $cookie_ltime );

	/* Si on a un cookie, on l'utilise */
	$var_is_cookie = is_cookie( $key );
	if ( $var_is_cookie !== false )
		$vars_arr[$key] = $var_is_cookie;

	/* Si POST ou GET, use it, POST master */
	$var_cvar = cvar( $key );

	if ( ( $key == "adv" && $var_cvar === false && $_POST ) || ( $key == "adv" && $var_cvar === false && $_GET ) ) // Workaround pour la checkbox, si elle n'est pas cochée, $_(POST|GET)['adv'] n'existe pas, donc cvar retourne false
		$vars_arr[$key] = 'off';

	if ( $var_cvar !== false )
		$vars_arr[$key] = $var_cvar;
}

$amxver = $vars_arr['amxver'];
$dbglvl = $vars_arr['dbglvl'];
$lang = $vars_arr['lang'];
$adv = $vars_arr['adv'];

/* Config */
set_compiler_conf( $amxver, $dbglvl, $lang, $adv );

/* Charge la langue */
$localized = TRUE;
switch ( $LANG )
{
	case 'fr' :
		setlocale( LC_ALL, 'fr_FR' );
		break;
	case 'ru' :
		setlocale( LC_ALL, 'ru_RU' );
		break;
	default :
		setlocale( LC_ALL, 'en_US' );
		$localized = FALSE;
}

bindtextdomain( "messages", "./locale" );
bind_textdomain_codeset( "messages", "UTF-8" );
textdomain( "messages" );

require_once( 'Compiler.class.php' );

$go = cvar('go');
switch ( $go )
{
	case '' :
	case 'disp' :
		include('header.inc.php');
		disp_compiler();
		break;
	case 'upload' :
		include('header.inc.php');
		compile_upload();
		break;
	case 'send' :
		include('header.inc.php');
		compile_text();
		break;
	case 'dl' :
		download(ivar("id"));
		break;
	default :
		include('header.inc.php');
		disp_compiler();
}

/**********************************************/
echo '<p>'."\n";
$query = "SELECT * FROM amxx_comp3_stats ORDER BY `id` ASC";
$pStats = mysql_query($query) or die ('<p>Line: '.__LINE__.'<br />'.mysql_error().'</p>');

echo '<span class="stats">'."\n";

/**
 * Ugly hack to manage the stats translation via gettext, while still using a single mysql_fetch_array in a while loop...
 * Here are all the strings in the 'text' row of the stats table to be translated. Specified here so poedit/xgettext can detect them,
 * because I'm too lazy to modify each catalog by hand.
 */
function webcomp_foobar_gettext()
{
	_(' successful compiles to date.<br/>(');
	_(' with AMXx 1.8.1,');
	_(' with AMXx 1.8.0,');
	_(' with AMXx 1.76d,');
	_(' with AMXx 1.75,');
	_(' with AMXx 1.71,');
	_(' with AMXx 1.70,');
	_(' with AMXx 1.60,<br/>');
	_(' with AMX 2006.3,');
	_(' with AMX 2006.2,');
	_(' with AMX 2005.1,');
	_(' with AMX 0.9.9,');
	_(' with AMXx 1.55 and');
	_(' with AMXx 1.01 ).<br/><br/>');
	_(' failed compiles to date.<br/>(');
	_(' with AMXx 1.01 ).<br/><br/><br/>');
}

while ( $pStats_data = mysql_fetch_array( $pStats ) )
{
	echo ( intval( $pStats_data['val'] ) )._( $pStats_data['text'] )."\n";
}
echo '</span>'."\n";

mysql_free_result($pStats);
//echo _('Old compiler: 101980 compiles before decommission.').'<br/>'."\n";
echo '<span class="credits">';
echo _('Tool developped by: <a href="http://www.amxmodx.org" style="color: #365d95" onmouseover="fadeElement(this, \'#1f2126\')" onmouseout="fadeElement(this, \'#365d95\')" onclick="window.open(this.href);return(false);">David "BAILOPAN" Anderson</a>. Mods for MultiLang &amp; MultiVers by <a href="http://trac.ak-team.com" style="color: #365d95" onmouseover="fadeElement(this, \'#1f2126\')" onmouseout="fadeElement(this, \'#365d95\')" onclick="window.open(this.href);return(false);">NiLuJe</a>, helped by the <a href="http://www.cs-amx.com" style="color: #365d95" onmouseover="fadeElement(this, \'#1f2126\')" onmouseout="fadeElement(this, \'#365d95\')" onclick="window.open(this.href);return(false);">Cs-AmX</a> team.');
if ( $localized )
{
	echo _(' YOURLANGUAGE translation by YOURNAME.');
}
echo '</span></p>'."\n";
remove_old();
include('footer.inc.php');

////////////////////////////////////
//////// HELPER FUNCTIONS //////////
////////////////////////////////////

/* Config */

/* Cookies à set only sur les POST */
function is_post( $var )
{
	if ( isset( $_POST[$var] ) )
		return $_POST[$var];
	return false;
}

/* Petit gateau sec */
function is_cookie( $var )
{
	if ( isset( $_COOKIE[$var] ) )
		return $_COOKIE[$var];
	return false;
}

/* Création des Path à partir du bordel ci-dessus ^^*/
function set_compiler_conf( $amxver, $dbglvl, $lang, $adv )
{
	/* Traitements GPC */
	global $AMX_VER, $BIN_NAME, $BIN_DIR, $BIN_EXT, $AMX_VERSION, $DBG_LVL, $LANG, $ALWAYS_SHOW_OUT;

	/* BIN_DIR */
	$arr_bin_dir = array(
				"amxx181" => "amxx-1.8.1",
				"amxx180" => "amxx-1.8.0",
				"amxx176" => "amxx-1.76",
				"amxx175" => "amxx-1.75",
				"amxx171" => "amxx-1.71",
				"amxx170" => "amxx-1.70",
				"amxx160" => "amxx-1.60",
				"amxx155" => "amxx-1.55",
				"amxx101" => "amxx-1.01",
				"amx099" => "amx-0.9.9",
				"amx20051rc1" => "amx-2005.1-rc1",
				"amx20062" => "amx-2006.2",
				"amx20063" => "amx-2006.3"
			);
	/* AMX_VERSION */
	$arr_amx_ver = array(
				"amxx181" => "AMX Mod X 1.8.1",
				"amxx180" => "AMX Mod X 1.8.0",
				"amxx176" => "AMX Mod X 1.76d",
				"amxx175" => "AMX Mod X 1.75a",
				"amxx171" => "AMX Mod X 1.71",
				"amxx170" => "AMX Mod X 1.70",
				"amxx160" => "AMX Mod X 1.60",
				"amxx155" => "AMX Mod X 1.55",
				"amxx101" => "AMX Mod X 1.01",
				"amx099" => "AMX Mod 0.9.9",
				"amx20051rc1" => "AMX Mod 2005.1",
				"amx20062" => "AMX Mod 2006.2",
				"amx20063" => "AMX Mod 2006.3"
			);

	/**
	 * Switch Version AMX(x). Défaut sur AMXx 1.8.1
	 * Vérifie qu'on a pas passé un truc farfelu comme amxver ...
	 */
	if ( ! array_key_exists( $amxver, $arr_bin_dir ) && ! array_key_exists( $amxver, $arr_amx_ver ) )
		$AMX_VER = "amxx181";
	else
		$AMX_VER = $amxver;

	/* Path vers le compilo */
	$BIN_DIR = $arr_bin_dir[$AMX_VER];

	/* Extension des plugins & binaire du compilo. (.amxx via amxxpc (sauf en 1.01, amxxsc) sous AMXX, .amx via sc sous AMX) */
	if ( strpos( $AMX_VER, "amxx" ) === false )
	{
		$BIN_NAME = "sc";
		$BIN_EXT = ".amx";
	}
	else
	{
		/* Exception 1.01 */
		if ( $AMX_VER == "amxx101" )
			$BIN_NAME = "amxxsc";
		else
			$BIN_NAME = "amxxpc";
		$BIN_EXT = ".amxx";
	}

	/* Nom complet de la version */
	$AMX_VERSION = $arr_amx_ver[$AMX_VER];

	/** Switch -d Defaut: -d1
	 * Vérifie qu'on a pas passé un truc farfelu comme dbglvl ...
	 */
	if ( !is_numeric( $dbglvl ) || $dbglvl < 0 || $dbglvl > 3 )
		$DBG_LVL = 1;
	else
		$DBG_LVL = $dbglvl;

	/* Switch Langue. Defaut: set by browser. Fallback: en */
	switch ( $lang )
	{
		case 'fr' :
			$LANG = "fr";
			break;
		case 'ru' :
			$LANG = "ru";
			break;
		default :
			$LANG = "en";
	}

	/* Switch output Compilo. Defaut: off */
	if ( $adv != "on" )
		$ALWAYS_SHOW_OUT = "off";
	else
		$ALWAYS_SHOW_OUT = $adv;
}

/* Test préselection des sliders */
function test_selected( $var, $value )
{
	$is_selected = '';

	/* On check si notre option correspond avec la config */
	global $AMX_VER, $DBG_LVL, $LANG;
	$var_arr = array( "amxver" => $AMX_VER, "dbglvl" => $DBG_LVL, "lang" => $LANG );

	if ( $var_arr[$var] == $value )
		$is_selected=' selected="selected"';

	return $is_selected;
}

/* Test préselection des checkbox */
function test_checked( $value_name, $option_name )
{
	global $ALWAYS_SHOW_OUT;

	$is_checked = '';

	if ( $ALWAYS_SHOW_OUT == 'on' )
		$is_checked=' checked="checked"';

	return $is_checked;
}


/* Affiche les sliders de config */
function show_config()
{
	global $MY_NAME, $AMX_VER;

	echo <<<EOF
<form method="post" enctype="multipart/form-data" action="$MY_NAME">
<p><br/></p>
<p>
EOF;
		/**
		 * Trick JS sur le onchange pour être XHTL 1.1 valid (pas de name pour les form...), on utilise l'array des forms,
		 * via getElementsByTagName('form') (document.forms n'existe pas forcément dans du XHTML servi en XML,
		 * cf. http://www.xml.com/pub/a/2003/03/19/dive-into-xml.html & https://bugzilla.mozilla.org/show_bug.cgi?id=111514),
		 * par exemple, getElementsByTagName('form')[1] est la 2e form (textarea).
		 * Le this & cie chope la value en cour sur ce form + un refresh onchange, pour le switch d'affichage du debug (avec
		 * set du go à disp, pour pas se bouffer le message d'erreur 'vous devez spécifier un fichier à uploader', vu que la form le set à
		 * upload en temps normal)
		 * NOTE: Le go.value=disp + submit systématique est un poil overkill, idéalement on n'aurait besoin de le faire que du switch d'amx vers amxx
		 * et inversement, vu que ce n'est qu'entre ces deux la qu'on choisit d'afficher ou pas la combobox de niveau de debug,
		 * mais c'est un poil lourd à implémenter, surtout en inline comme ça, pour pas grand chose...
		 */
		echo _('AMX(x) version: ').'<select name="amxver" onchange="document.getElementsByTagName(\'form\')[1].amxver.value=this.options[this.selectedIndex].value;this.form.go.value=\'disp\';this.form.submit();">'."\n";
			echo "\t".'<option value="amxx181"'.(test_selected('amxver', 'amxx181')).'>AMX Mod X 1.8.1</option>'."\n";
			echo "\t".'<option value="amxx180"'.(test_selected('amxver', 'amxx180')).'>AMX Mod X 1.8.0</option>'."\n";
			echo "\t".'<option value="amxx176"'.(test_selected('amxver', 'amxx176')).'>AMX Mod X 1.76d</option>'."\n";
			echo "\t".'<option value="amxx175"'.(test_selected('amxver', 'amxx175')).'>AMX Mod X 1.75a</option>'."\n";
			echo "\t".'<option value="amxx171"'.(test_selected('amxver', 'amxx171')).'>AMX Mod X 1.71</option>'."\n";
			echo "\t".'<option value="amxx170"'.(test_selected('amxver', 'amxx170')).'>AMX Mod X 1.70</option>'."\n";
			echo "\t".'<option value="amxx160"'.(test_selected('amxver', 'amxx160')).'>AMX Mod X 1.60</option>'."\n";
			echo "\t".'<option value="amx20063"'.(test_selected('amxver', 'amx20063')).'>AMX Mod 2006.3</option>'."\n";
			echo "\t".'<option value="amx20062"'.(test_selected('amxver', 'amx20062')).'>AMX Mod 2006.2</option>'."\n";
			echo "\t".'<option value="amx20051rc1"'.(test_selected('amxver', 'amx20051rc1')).'>AMX Mod 2005.1</option>'."\n";
			echo "\t".'<option value="amx099"'.(test_selected('amxver', 'amx099')).'>AMX Mod 0.9.9</option>'."\n";
			echo "\t".'<option value="amxx155"'.(test_selected('amxver', 'amxx155')).'>AMX Mod X 1.55</option>'."\n";
			echo "\t".'<option value="amxx101"'.(test_selected('amxver', 'amxx101')).'>AMX Mod X 1.01</option>'."\n";
		echo '</select>'."\n";

		/* On n'affiche pas le choix debug sous AMXx */
		if ( strpos( $AMX_VER, "amxx" ) === false )
		{
			echo _('  Debug level: ').'<select name="dbglvl" onchange="document.getElementsByTagName(\'form\')[1].dbglvl.value=this.options[this.selectedIndex].value;">'."\n";
				echo "\t".'<option value="0"'.(test_selected('dbglvl', '0')).'>0</option>'."\n";
				echo "\t".'<option value="1"'.(test_selected('dbglvl', '1')).'>1 (*)</option>'."\n";
				echo "\t".'<option value="2"'.(test_selected('dbglvl', '2')).'>2</option>'."\n";
				echo "\t".'<option value="3"'.(test_selected('dbglvl', '3')).'>3</option>'."\n";
			echo '</select>'."\n";
		}

		/* Refresh onchange lang */
		echo _('  Language: ').'<select name="lang" onchange="document.getElementsByTagName(\'form\')[1].lang.value=this.options[this.selectedIndex].value;this.form.submit();">'."\n";
			echo "\t".'<option value="en"'.(test_selected('lang', 'en')).'>English</option>'."\n";
			echo "\t".'<option value="fr"'.(test_selected('lang', 'fr')).'>Fran&#231;ais &nbsp;</option>'."\n";
			echo "\t".'<option value="ru"'.(test_selected('lang', 'ru')).'>Russian</option>'."\n";
		echo '</select>'."\n";
	echo '</p>'."\n";
		echo '<p><input type="checkbox" name="adv" '.(test_checked('adv', 'on')).' onclick="if (this.checked) { document.getElementsByTagName(\'form\')[1].adv.value = \'on\'; this.form.adv.value = \'on\' } else { document.getElementsByTagName(\'form\')[1].adv.value = \'off\'; this.form.adv.value = \'off\' }"/>'._(' Always show compiler output').'</p>'."\n";
	echo '<p><br/></p>'."\n";
}

function download($id)
{
	global $BIN_EXT;

	$pFile = GetFileData($id);

	if (!$pFile || intval($pFile['done']))
	{
		include('header.inc.php');
		echo '<p><span class="error">'._('This file does not exist or has expired past its time limit.').'</span><br/><br/></p>'."\n";
		return false;
	} else {
		OutputAmxx($pFile['phys_name'], str_replace('.sma', $BIN_EXT, $pFile['real_name']));
		exit();
	}
}

function compile_upload()
{
	global $BIN_EXT;

	if ( ! $_FILES )
	{
		echo '<p><span class="error">'._('You must upload a valid file!').'</span><br/><br/></p>'."\n";
		disp_compiler();
		return false;
	}

	$temp_name = strip_filename($_FILES['sma']['tmp_name']).'.sma';
	$path = TEMP_SRCPATH.'/'.$temp_name;
	$real_name = $_FILES['sma']['name'];

	if ( $_FILES['sma']['size'] == 0 && $_FILES['sma']['error'] == 4 )  // 4 = UPLOAD_ERR_NO_FILE ( submit sans fichier selectionné )
	{
		if ( is_cookie( 'lang' ) != is_post( 'lang' ) ) // issu du submit @ lang onchange (Changement/set de cookie)
		{
			disp_compiler();
			return false;
		}
		else
		{
			echo '<p><span class="error">'._('You must upload a valid file!').'</span><br/><br/></p>'."\n";
			disp_compiler();
			return false;
		}
	}

	if (!stristr($real_name, '.sma'))
	{
		echo '<p><span class="error">'._('You must upload a valid file!').'</span><br/><br/></p>'."\n";
		disp_compiler();
		return false;
	}
	move_uploaded_file($_FILES['sma']['tmp_name'], $path);
	if (!file_exists($path))
	{
		echo '<p><span class="error">'._('You must upload a valid file!').'</span><br/><br/></p>'."\n";
		disp_compiler();
		return false;
	}

	$bin = TEMP_OUTPATH.'/'.strip_filename(str_replace('.sma', $BIN_EXT, $path));
	TryCompile($path, $bin, $real_name);
	unlink($path);
}

function compile_text()
{
	global $BIN_EXT, $MY_NAME, $AMX_VER, $DBG_LVL, $LANG, $ALWAYS_SHOW_OUT;

	$path = tempnam(TEMP_SRCPATH, 'text');

	/* Test Blank Code Box & Stop */
	$plug_code = cvar('scode');
	if ( ! $plug_code )
	{
		echo '<p><span class="error">'._('ERROR: You didn\'t type anything in the box!').'</span><br/><br/></p>'."\n";
		unlink($path);
		disp_compiler();
		return false;
	}

	/* Test Blank Plugin Name & Warn */
	$plug_name = cvar('fname');
	if ( ! $plug_name )
	{
		echo '<p><span class="warn">'._('Warning: You didn\'t give a name to your plugin!').'</span><br/><br/></p>'."\n";
	}

	/* Test Plugin Name Length & Abort */
	if ( ! is_string( $plug_name ) || strlen( $plug_name ) > 24 )
	{
		echo '<p><span class="error">'._('ERROR: The plugin name you specified is too long!').'</span><br/><br/></p>'."\n";
		unlink($path);
		disp_compiler();
		return false;
	}

	$code = stripslashes( $plug_code );

	rename($path, $path.'.sma');
	$path .= '.sma';

	$real_name = '';
	if ( $plug_name )
		$real_name = str_replace(' ', '', strip_filename($plug_name)).$BIN_EXT;
	else
		$real_name = str_replace('.sma', $BIN_EXT, strip_filename($path));

	$fp = fopen($path, 'w');
	fwrite($fp, $code);
	fclose($fp);

	$bin = TEMP_OUTPATH.'/'.str_replace('.sma', $BIN_EXT, strip_filename($path));
	$s = TryCompile($path, $bin, $real_name);

	/* Make XHTML 1.1 + XML happy */
	$code = htmlspecialchars( $code, ENT_QUOTES );

	echo <<<EOF
<p>
<br/>
</p>
<form method="post" action="$MY_NAME">
<p>
EOF;
	echo _('Plugin short name: ').'<input type="text" name="fname" size="15" maxlength="24" value="'.$plug_name.'"/><br/><br/>'."\n";
	echo <<<EOF
<textarea name="scode" rows="25" cols="70">
$code
</textarea><br/>
<input type="hidden" name="go" value="send"/>
<input type="hidden" name="amxver" value="$AMX_VER"/>
<input type="hidden" name="dbglvl" value="$DBG_LVL"/>
<input type="hidden" name="lang" value="$LANG"/><br/>
<input type="hidden" name="adv" value="$ALWAYS_SHOW_OUT"/><br/>
EOF;
	echo '<input type="submit" value="'._('Compile').'"/>'."\n";
	echo <<<EOF
</p></form>
<p><br/></p>
EOF;

	unlink($path);
}

function TryCompile($input, $output, $real_name)
{
	global $AMX_VERSION, $AMX_VER, $MY_NAME, $MY_URI, $BIN_EXT, $ALWAYS_SHOW_OUT;

	$comp = new Compiler($input, $output, $real_name);

	if (!$comp->Compile(true))
	{
		echo '<p><a href="'.$MY_NAME.'" style="color: #365d95" onmouseover="fadeElement(this, \'#1f2126\')" onmouseout="fadeElement(this, \'#365d95\')">.: '._('Return to main page').' :.</a><br/><br/></p>'."\n";
		echo '<p><span class="error">';
		printf( _('Your plugin failed to compile! (Via the "%s" compiler)'), $AMX_VERSION );
		echo '</span><br/><br/>'._('Check errors below:').'<br/><br/></p>'."\n";
		echo '<div class="box"><pre>'."\n";
		echo htmlspecialchars( $comp->output, ENT_QUOTES )."\n";

		echo '</pre></div>'."\n";
		IncStatKey('compile_failures');
		IncStatKey('compile_failures_'.$AMX_VER);
	}
	else
	{
		echo '<p><a href="'.$MY_NAME.'" style="color: #365d95" onmouseover="fadeElement(this, \'#1f2126\')" onmouseout="fadeElement(this, \'#365d95\')">.: '._('Return to main page').' :.</a><br/><br/></p>'."\n";
		echo '<p><span class="success">';
		printf( _('Your plugin successfully compiled! (Via the "%s" compiler )'), $AMX_VERSION );
		echo '</span><br/><br/></p>'."\n";
		echo '<p>'._('Use the link below to download your plugin.  It will be valid for ten minutes.').'<br/><br/></p>'."\n";

		$id = AddTempPlugin($output, $real_name);
		echo '<p>'."\n";
		echo '<a href="'.$MY_NAME.'?go=dl&amp;id='.$id.'" style="color: #699966" onmouseover="fadeElement(this, \'#669900\')" onmouseout="fadeElement(this, \'#699966\')">'.$MY_URI.'?go=dl&amp;id='.$id.'</a>'."\n";
		echo '<br/><br/>'."\n";

		if ( $ALWAYS_SHOW_OUT == 'on' )
		{
			echo '<div class="box"><pre>'."\n";
			echo htmlspecialchars( $comp->output, ENT_QUOTES )."\n";
			echo '</pre></div>'."\n";
		}

		echo '</p>'."\n";
		IncStatKey('compile_successes');
		IncStatKey('compile_successes_'.$AMX_VER);
	}
}

function IncStatKey($key)
{
	$query = "SELECT val FROM amxx_comp3_stats WHERE `key` = '".$key."'";
	$pStats = mysql_query($query) or die ('<p>Line: '.__LINE__.'<br />'.mysql_error().'</p>');
	if (!$pStats || !mysql_num_rows($pStats))
		return false;

	$pStat = mysql_fetch_array($pStats);
	$query = "UPDATE amxx_comp3_stats SET val = '".(intval($pStat['val'])+1)."' WHERE `key` = '".$key."'";
	mysql_query($query) or die ('<p>Line: '.__LINE__.'<br />'.mysql_error().'</p>');
	mysql_free_result($pStats);
}

function AddTempPlugin($output, $real_name)
{
	$query = "INSERT INTO amxx_comp3_files VALUES(NULL, '".mysql_real_escape_string($output)."', '".mysql_real_escape_string($real_name)."', UNIX_TIMESTAMP(), '".getenv("REMOTE_ADDR")."', 0)";
	mysql_query($query) or die ('<p>Line: '.__LINE__.'<br />'.mysql_error().'</p>');
	return mysql_insert_id();
}

function disp_compiler()
{
	global $MY_NAME, $AMX_VER, $DBG_LVL, $LANG, $ALWAYS_SHOW_OUT;

	//there are two modes, upload file or a large text box....
	echo '<h3>'._('Welcome to the Multi AMX Mod (X) Web Compiler.').'</h3><p>'._('You can use this to compile plugins online.').'</p>'."\n";
	echo '<p>'._('Once you upload a file, you will receive the compiler output and a link to the compiled plugin.').'</p>'."\n";

	//Config
	echo show_config();

	echo '<p>'."\n";
	echo _('Upload .sma file: ').'<input type="file" name="sma"/>'."\n";
	echo <<<EOF
<input type="hidden" name="MAX_FILE_SIZE" value="512000"/>
<input type="hidden" name="go" value="upload"/>&nbsp;&nbsp;
EOF;
	echo '<input type="submit" value="'._('Compile').'"/>'."\n";
	echo '</p></form>'."\n";
	echo '<p><br/>'._('If you prefer, you can also paste your plugin source code into the box below:').'<br/><br/></p>'."\n";
	echo <<<EOF
<form method="post" action="$MY_NAME">
<p>
EOF;
	echo _('Plugin short name: ').'<input type="text" name="fname" size="15" maxlength="24"/><br/><br/>'."\n";
	echo <<<EOF
<textarea name="scode" rows="25" cols="70">
</textarea><br/>
<input type="hidden" name="go" value="send"/>
<input type="hidden" name="amxver" value="$AMX_VER"/>
<input type="hidden" name="dbglvl" value="$DBG_LVL"/>
<input type="hidden" name="lang" value="$LANG"/>
<input type="hidden" name="adv" value="$ALWAYS_SHOW_OUT"/>
EOF;
	echo '<br/><input type="submit" value="'._('Compile').'"/>'."\n";
	echo '<br/><br/></p></form>'."\n";

}

function cvar($var)
{
	if ( isset( $_POST[$var] ) )
		return $_POST[$var];
	if ( isset( $_GET[$var] ) )
		return $_GET[$var];
	return false;
}

function ivar($var)
{
	return intval(cvar($var));
}

function remove_old()
{
	$query = "SELECT * FROM amxx_comp3_files WHERE compiled + 600 < UNIX_TIMESTAMP() AND done = 0";
	$Plugins = mysql_query($query) or die ('<p>Line: '.__LINE__.'<br />'.mysql_error().'</p>');
	if (!$Plugins)
		return false;

	$c = mysql_num_rows($Plugins);
	for ($i=1; $i<=$c; $i++)
	{
		$Plugin = mysql_fetch_array($Plugins);
		if (file_exists($Plugin['phys_name']))
			unlink($Plugin['phys_name']);
	}
	mysql_query("UPDATE amxx_comp3_files SET done = 1 WHERE compiled + 600 < UNIX_TIMESTAMP() AND done = 0") or die ('<p>Line: '.__LINE__.'<br />'.mysql_error().'</p>');
	mysql_free_result($Plugins);
}

function GetFileData($file_id)
{
	$query = "SELECT * FROM amxx_comp3_files WHERE id = ".$file_id;
	$pFiles = mysql_query($query) or die ('<p>Line: '.__LINE__.'<br />'.mysql_error().'</p>');

	if (!$pFiles)
		return false;

	if (!mysql_num_rows($pFiles))
		return false;

	$pFile = mysql_fetch_array($pFiles);
	mysql_free_result($pFiles);
	return $pFile;
}
?>
