<?PHP

$CFG_INSTALLATION = array(0 => "Bitte ausw&auml;hlen...", 1 => "GMs");
$CFG_ACTIVE = array(0 => "disabled", 1 => "active" );
$CFG_PATCHFILES = "E:\\www\\patcher_files\\";
$CFG_VERSIONPATH = "E:\\www\\patcher\\";

include './core.php';

if( !isset( $user ) || !$user->can_access( 'patcher' ) ) access_error();

if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'activate') {
	// Patch freigeben
	$MySQL->query("START TRANSACTION");
	$row = $MySQL->query_first("SELECT * FROM patcher WHERE installID = '".intval($_REQUEST['installation'])."' AND version = '".intval($_REQUEST['version'])."'");
	
	if(strtolower($row['patch_verification']) != @md5_file($CFG_PATCHFILES."patch_".$_REQUEST['version'].".me")) {
		error("Datei nicht korrekt hochgeladen oder falscher MD5-Hash.", true);
	}
	if($_REQUEST['version'] > 1) {
		$z = intval($_REQUEST['version'])-1;
		if( $MySQL->num_rows($MySQL->query("SELECT status FROM patcher WHERE version = '$z' AND installID = '".intval($_REQUEST['installation'])."' AND status = 'active'")) != 1) {
			error("Der letzte Patch wurde noch nicht aktiviert");
		}	
	}
	
	$MySQL->query("UPDATE patcher SET filesize = '".filesize($CFG_PATCHFILES."patch_".$_REQUEST['version'].".me")."', status = 'active' WHERE installID = '".intval($_REQUEST['installation'])."' AND version = '".intval($_REQUEST['version'])."'");
	// WRITE version.tdv
	$filename = $CFG_VERSIONPATH."version.tdv";
	$content =  "[TDV]\r\n";					
	$content .= "Version=".$row['version']."\r\n";
	$content .= "Versionname=".$row['versionname']."\r\n";
	$content .= "Shardinfo=Willkommen auf Mittelerde\r\n";
	$content .= "Banner=MEBanner.jpg\r\n";
	$content .= "Auth=1\r\n";
	$content .= "MCrypt=197\r\n";
	$content .= "FileSuffix=me\r\n";
	$content .= "EnableDownloadResume=1\r\n";
	$content .= "ShowPatcherOnlyForPatches=1\r\n";
	$content .= "PatchMessages=1\r\n";
	$content .= "Hashes=1\r\n";
		
	// Let's make sure the file exists and is writable first.
	if (is_writable($filename))
	{
	   	if (!$handle = fopen($filename, 'w+'))
   		{
        	error( "Cannot open file ($filename)", true);
         	exit;
    	}	
    
    	if (fwrite($handle, $content) === FALSE)
    	{
       		error("Cannot write to file ($filename)", true);
       		exit;
    	}
		
   		fclose($handle);
	}
	else
	{
   		error("The file $filename is not writable",true);
	}
	
	//Write messages.ini
	$filename = $CFG_VERSIONPATH."messages.ini";
	$content = "[Patch]\r\n";
	$patcher_res = $MySQL->query( "SELECT * FROM patcher ORDER BY installID, version" );
	$patches = array();
	while( $row = $MySQL->fetch_array( $patcher_res ) )
	{
		$content .= $row['version']."=".$row[ 'shardinfo' ]." (".filesize($CFG_PATCHFILES."patch_".$row['version'].".me")." bytes)\r\n";		
	}
	
	// Let's make sure the file exists and is writable first.
	if (is_writable($filename))
	{
	   	if (!$handle = fopen($filename, 'w+'))
   		{
        	error( "Cannot open file ($filename)", true);
         	exit;
    	}	
    
    	if (fwrite($handle, $content) === FALSE)
    	{
       		error("Cannot write to file ($filename)", true);
       		exit;
    	}
   	
   		fclose($handle);
	}
	else
	{
   		error("The file $filename is not writable",true);
	}   	
	
	//Write hashes.ini
	$filename = $CFG_VERSIONPATH."hashes.ini";
	$content = "[Patch]\r\n";
	$patcher_res = $MySQL->query( "SELECT * FROM patcher ORDER BY installID, version" );
	$patches = array();
	while( $row = $MySQL->fetch_array( $patcher_res ) )
	{
		$content .= $row['version']."=".$row[ 'patch_verification' ]."\r\n";
	}
	
	// Let's make sure the file exists and is writable first.
	if (is_writable($filename))
	{
	   	if (!$handle = fopen($filename, 'w+'))
   		{
        	error( "Cannot open file ($filename)", true);
         	exit;
    	}	
    
    	if (fwrite($handle, $content) === FALSE)
    	{
       		error("Cannot write to file ($filename)", true);
       		exit;
    	}
    	else
    	{
   			$MySQL->query("COMMIT");
   		}	
   	
   		fclose($handle);
	}
	else
	{
   		error("The file $filename is not writable",true);
	} 
}

if( isset( $_POST['send_add'] ) ) 
{
	$installID = intval($_REQUEST['installID']);
	if($installID==0 OR strlen($CFG_INSTALLATION[$installID])==0)
	{
		$form_errors[] = "Installation auswählen";
		
		$Smarty->assign( 'form_errors', $form_errors );
			assign_formvalues( 'versionname', 'shardinfo', 'auth', 'patch_verification');  // TODO
	}
	else
	{	
		if(strlen($_REQUEST['versionname'])==0)
		{
			$form_errors[] = 'Bitte Version angeben';
			$Smarty->assign( 'form_errors', $form_errors );
		}
		else 
		{
			$MySQL->query("START TRANSACTION;");
			$version = $MySQL->query_first("SELECT max(version) FROM patcher WHERE installID = '".$_REQUEST['installID']."'");
			$version = 1+$version[0];

			$MySQL->query("INSERT INTO patcher SET installID = '".intval($_REQUEST['installID'])."', version = '".intval($version)."', versionname = '".$_REQUEST['versionname']."', shardinfo = '".$_REQUEST['shardinfo']."', patch_creation = NOW(), patch_verification = '".$_REQUEST['patch_verification']."', auth = '".intval($_REQUEST['auth'])."', status = 'disabled', accountid = $user->ID");
			$MySQL->query("COMMIT;");	
		}
	}
}

if( isset( $_REQUEST['delete'] ) )
{
	$MySQL->query( "DELETE FROM patcher WHERE status = 'disabled' AND installID = '".$_REQUEST['installID']."' AND version = '".$_REQUEST['installID']."' LIMIT 1" );
}

if( isset( $_POST['send_edit'] ) )
{
	$go_back = 0;
	$write_version = 0;
	$write_messages = 0;
	
	$MySQL->query("START TRANSACTION");
	$row = $MySQL->query_first("SELECT * FROM patcher WHERE installID = '".intval($_REQUEST['installation'])."' AND version = '".intval($_REQUEST['version'])."'");	
	
	if(strlen($_REQUEST['versionname'])==0)
	{
		$form_errors[] = 'Bitte Version angeben';
		$Smarty->assign( 'form_errors', $form_errors );
	}
	else if(strtolower($_REQUEST['patch_verification']) != @md5_file($CFG_PATCHFILES."patch_".$_REQUEST['version'].".me"))
	{
		error("Datei nicht korrekt hochgeladen oder falscher MD5-Hash.", true);
		exit;
	}
	else
	{					
		if( $row[ 'status' ] == 'active' )
		{
			$oldstatus = 1;
		}
		else
		{
			$oldstatus = 0;
		}
			
		$go_on = 1;
		
		if( $oldstatus != intval($_REQUEST['status'] ) )
		{
			if( $oldstatus == 0 )
			{
				$form_errors[] = 'Aktivieren nur über dafür vorgesehenen link';
				$Smarty->assign( 'form_errors', $form_errors );
				$go_on = 0;
			}
			elseif( $oldstatus == 1 )
			{
				$version = $MySQL->query_first("SELECT max(version) FROM patcher WHERE installID = '".$_REQUEST['installation']."' AND status = 'active'");
				if( $version[0] != intval($_REQUEST['version']) )
				{
					$form_errors[] = 'Es ist nur möglich, den letzten aktivierten Patch zu deaktivieren.';
					$Smarty->assign( 'form_errors', $form_errors );
					$go_on = 0;
				}
				else 
				{
					$write_version = 1;
				}
			}				
		}
		
		if( $row[ 'shardinfo' ] != $_REQUEST[ 'shardinfo' ] )
		{
			$write_messages = 1;
		}		
		
		if( $go_on == 1 )
		{
			$MySQL->query("UPDATE patcher SET status = '".$CFG_ACTIVE[intval($_REQUEST['status'] )]."', versionname = '".$_REQUEST['versionname']."', shardinfo = '".$_REQUEST['shardinfo']."', patch_verification = '".$_REQUEST['patch_verification']."' WHERE installID = '".intval($_REQUEST['installation'])."' AND version = '".intval($_REQUEST['version'])."'");
			$MySQL->query("COMMIT");							
			$go_back = 1;
		}	
	
		if( $write_version == 1 )
		{
			$patchversion = intval($_REQUEST['version'])-1;
			$latestpatch = $MySQL->query_first("SELECT * FROM patcher WHERE installID = '".intval($_REQUEST['installation'])."' AND version = '".$patchversion."'");
			
			// WRITE version.tdv
			$filename = $CFG_VERSIONPATH."version.tdv";
			$content =  "[TDV]\r\n";					
			$content .= "Version=".$latestpatch['version']."\r\n";
			$content .= "Versionname=".$latestpatch['versionname']."\r\n";
			$content .= "Shardinfo=Willkommen auf Mittelerde\r\n";
			$content .= "Banner=MEBanner.jpg\r\n";
			$content .= "Auth=1\r\n";
			$content .= "MCrypt=197\r\n";
			$content .= "FileSuffix=me\r\n";
			$content .= "EnableDownloadResume=1\r\n";
			$content .= "ShowPatcherOnlyForPatches=1\r\n";
			$content .= "PatchMessages=1\r\n";
			$content .= "Hashes=1\r\n";
		
			// Let's make sure the file exists and is writable first.
			if (is_writable($filename))
			{
	   			if (!$handle = fopen($filename, 'w+'))
   				{
        			error( "Cannot open file ($filename)", true);
         			exit;
    			}	
    
    			if (fwrite($handle, $content) === FALSE)
    			{
       				error("Cannot write to file ($filename)", true);
       				exit;
    			}
   	
   				fclose($handle);
			}
			else
			{
   				error("The file $filename is not writable",true);
   				exit;
			}
		}
		if( $write_messages == 1 )
		{
			//Write messages.ini
			$filename = $CFG_VERSIONPATH."messages.ini";
			$content = "[Patch]\r\n";
			$patcher_res = $MySQL->query( "SELECT * FROM patcher ORDER BY installID, version" );
			$patches = array();
			while( $row = $MySQL->fetch_array( $patcher_res ) )
			{
				$content .= $row['version']."=".$row[ 'shardinfo' ]." (".filesize($CFG_PATCHFILES."patch_".$row['version'].".me")." bytes)\r\n";
			}
	
			// Let's make sure the file exists and is writable first.
			if (is_writable($filename))
			{
	   			if (!$handle = fopen($filename, 'w+'))
   				{
        			error( "Cannot open file ($filename)", true);
         			exit;
    			}	
    
    			if (fwrite($handle, $content) === FALSE)
    			{
       				error("Cannot write to file ($filename)", true);
       				exit;
    			}
   	
   				fclose($handle);
			}
			else
			{
   				error("The file $filename is not writable",true);
   				exit;
			}
		}
		
		//Write hashes.ini
		$filename = $CFG_VERSIONPATH."hashes.ini";
		$content = "[Patch]\r\n";
		$patcher_res = $MySQL->query( "SELECT * FROM patcher ORDER BY installID, version" );
		$patches = array();
		while( $row = $MySQL->fetch_array( $patcher_res ) )
		{
			$content .= $row['version']."=".$row[ 'patch_verification' ]."\r\n";
		}
	
		// Let's make sure the file exists and is writable first.
		if (is_writable($filename))
		{
	   		if (!$handle = fopen($filename, 'w+'))
   			{
        		error( "Cannot open file ($filename)", true);
         		exit;
    		}	
    
    		if (fwrite($handle, $content) === FALSE)
    		{
       			error("Cannot write to file ($filename)", true);
       			exit;
    		}
   	   		fclose($handle);
		}
		else
		{
   			error("The file $filename is not writable",true);
		} 
	}	
	
	if( $go_back == 0 )
	{
		$Smarty->assign( 'CFG_INSTALLATION', $CFG_INSTALLATION );
		$Smarty->assign( 'CFG_ACTIVE', $CFG_ACTIVE );
	
		$formvalues = array();
		$formvalues[ 'installation' ] = intval($_REQUEST['installation']);
		$formvalues[ 'installationname' ] = $CFG_INSTALLATION[intval($_REQUEST['installation'])];
		$formvalues[ 'versionname' ] = $row[ 'versionname'];
		$formvalues[ 'shardinfo' ] = $row['shardinfo'];
		$formvalues[ 'version' ] = $row[ 'version' ];
		$formvalues[ 'auth' ] = $row[ 'auth' ];
		$formvalues[ 'patch_verification' ] = $row[ 'patch_verification' ];
		if ( $row[ 'status' ] == 'active' )
		{
			$formvalues[ 'status' ] = 1;
		}
		else
		{
			$formvalues[ 'status' ] = 0;
		}
		
		$Smarty->assign( 'formvalues', $formvalues );
		
		$page['content'] = $Smarty->fetch( 'patch_admin_edit.tpl' );

		$Smarty->assign( 'page', $page );
		$Smarty->display( 'main.tpl' );
		exit;
	}
}

if( isset( $_REQUEST['edit'] ) )
{
	$MySQL->query("START TRANSACTION");
	$row = $MySQL->query_first("SELECT * FROM patcher WHERE installID = '".intval($_REQUEST['installation'])."' AND version = '".intval($_REQUEST['version'])."'");
		
	$Smarty->assign( 'CFG_INSTALLATION', $CFG_INSTALLATION );
	$Smarty->assign( 'CFG_ACTIVE', $CFG_ACTIVE );
	
	$formvalues = array();
	$formvalues[ 'installation' ] = intval($_REQUEST['installation']);
	$formvalues[ 'installationname' ] = $CFG_INSTALLATION[intval($_REQUEST['installation'])];
	$formvalues[ 'versionname' ] = $row[ 'versionname'];
	$formvalues[ 'shardinfo' ] = $row['shardinfo'];
	$formvalues[ 'version' ] = $row[ 'version' ];
	$formvalues[ 'auth' ] = $row[ 'auth' ];
	$formvalues[ 'patch_verification' ] = $row[ 'patch_verification' ];
	if ( $row[ 'status' ] == 'active' )
	{
		$formvalues[ 'status' ] = 1;
	}
	else
	{
		$formvalues[ 'status' ] = 0;
	}
		
	$Smarty->assign( 'formvalues', $formvalues );
		
	$page['content'] = $Smarty->fetch( 'patch_admin_edit.tpl' );

	$Smarty->assign( 'page', $page );
	$Smarty->display( 'main.tpl' );
	exit;
}

if( isset( $_POST['send_createstaticpatch'] ) ) 
{
	$serverpath = "E:\\RunUO-Bau\\mefiles\\";	
	$backuppath = "D:\\Static-Patch-Arena\\files_von_mefiles\\";
		
	$serveridx = fopen($serverpath."staidx0.mul", "rb");
	if( $serveridx == FALSE )
	{
		exit;
	}
	$servermul = fopen($serverpath."statics0.mul", "rb");
	if( $servermul == FALSE )
	{
		fclose( $serveridx );
		exit;
	}
	
	$saveidx = fopen($backuppath."staidx0.mul", "rb" );
	if( $saveidx == FALSE )
	{
		fclose( $serveridx );
		fclose( $servermul );
		exit;
	}
	
	$savemul = fopen($backuppath."statics0.mul", "rb" );
	if( $savemul == FALSE )
	{
		fclose( $serveridx );
		fclose( $servermul );
		fclose( $saveidx );
		exit;
	}
	
	//for( $i=0; i < 	
	
	fclose( $serveridx );
	fclose( $servermul );
	fclose( $saveidx );
	fclose( $savemul );
}

$patcher_res = $MySQL->query( "SELECT * FROM patcher ORDER BY installID, version" );

$Smarty->assign( 'CFG_INSTALLATION', $CFG_INSTALLATION);

$patches = array();
while( $row = $MySQL->fetch_array( $patcher_res ) )
{
	$z = $row['installID'];
	$y = $row['auth'];
	$row['installation'] = $CFG_INSTALLATION[$z];
	$row['auth'] = $user->ranknames[$y];
	if($row['status'] == "active") {
		$row['status'] = "aktiviert";
	}
	else {
		$row['status'] = "<a href=\"patch_admin.php?action=activate&installation=$z&version=".$row['version']."\">aktivieren</a>";
	}
	$row['edit'] = "<a href=\"patch_admin.php?edit&installation=$z&version=".$row['version']."\">bearbeiten</a>";
	if(strlen($row['shardinfo'])>60) $row['shardinfo'] = substr($row['shardinfo'], 0, 60)."...";
	$patches[] = $row;
}

$Smarty->assign( 'patches', $patches );

$page['content'] = $Smarty->fetch( 'patch_admin.tpl' );

$Smarty->assign( 'page', $page );
$Smarty->display( 'main.tpl' );

	

?>