<?php
$CFG_PATCHFILES = "E:\\www\\patcher_files\\";

//http://www.uo-mittelerde.ch/patcher.php?action=authenticate&user=benutzername&password=122423415131 
if(isset($_REQUEST['sessionId']) && strlen($_REQUEST['sessionId'])>0) {
    session_id($_REQUEST['sessionId']);
    require_once './core.php';
    
    $version = str_replace("patch_", "", $_REQUEST['request']);
    $version = str_replace(".me", "", $version);
    
    if(isset($_REQUEST['askformirror'])) {
    	list ($patch_verification) = $MySQL->query_first("SELECT patch_verification FROM patcher WHERE version = '$version' AND status = 'active' AND installID = '1'");
    		
    		list($url) = $MySQL->query_first("SELECT path FROM patchmirrors WHERE version >= '$version' AND installID = '1'");
    		
    		header( "patch_verification: ".$patch_verification);
    		header( "patch_url: $url");
    		die();	
    }
    
    if($_SESSION['patcher'] != "allowed") die(); // TODO: Logging
    
    if( true )
    {
    	//list ($patch_verification) = $MySQL->query_first("SELECT patch_verification FROM patcher WHERE version = '$version' AND status = 'active' AND auth <= '".intval($_SESSION['rank'])."' AND installID = '1'");
    	list ($patch_verification) = $MySQL->query_first("SELECT patch_verification FROM patcher WHERE version = '$version' AND status = 'active' AND installID = '1'");

    	if(strlen($patch_verification) != 32) die(); // TODO: Logging

    	header( 'Pragma: no-cache' );
    	header( 'Cache-Control: no-store, no-cache, must-revalidate' );
    	header( 'Cache-Control: post-check=0, pre-check=0', false );
    	header( 'Expires: 0' );
    	header( 'Content-Type: application/octet-stream' );
    	header( "Content-Disposition: attachment; filename=patch_".$version.".me".";" );
			header( "patch_verification: ".$patch_verification);    
    	header( "Content-Length: ".filesize( $CFG_PATCHFILES."patch_".$version.".me" ) );

    	//$MySQL->query("UPDATE patcher SET count_downloads = count_downloads +1 WHERE version = '$version' AND status = 'active' AND installID = '1'");
    	set_time_limit(0);
    	readfile( $CFG_PATCHFILES."patch_".$version.".me" );
		session_unset();
		die();
    };
}

require_once './core.php';

if(isset($_REQUEST['action']) && isset($_REQUEST['password']) && $_REQUEST['action']=="authenticate" AND strlen($_REQUEST['password'])==32) {
	// TODO: Logging
    $row = $MySQL->query_first("SELECT password, rank FROM server.accounts WHERE name= '".$_REQUEST['user']."' AND password = '".$_REQUEST['password']."'");
    if($_REQUEST['password']==$row['password']) {     
    	header("patcher-auth: ok");
        $_SESSION['patcher'] = "allowed";
        $_SESSION['rank'] = $row['rank'];
    }
    else { 
        header( "patcher-auth: failed" );
    }
}
?>