<?php

require_once('./lib/config.inc.php');
require_once('./lib/MySQL.class.php');


function LogError($message = false) {
	global $MySQL;
	
	if($message === false) $message = "Ein Fehler ist aufgetreten";
		
	$backtrace = debug_backtrace();
	
 	$dump= sprintf("Ausnahme: %s. Trace: %s", $message, Print_R($backtrace, true));
	$dump.= sprintf(": %s", Print_R($GLOBALS, true));
 	$sql = sprintf("INSERT INTO logdb.me_errors SET typ = 69, accountID = NULL, zeit = NOW(), meldung = '%s', service = 'homepage'", me_escape($dump));
 	$MySQL->query($sql);

	die();
}

function me_escape($value)
{
   // Stripslashes
   if (get_magic_quotes_gpc()) {
       $value = stripslashes($value);
   }
   // Quote if not integer
   if (!is_numeric($value)) {
       $value = mysql_real_escape_string($value);
   }
   return $value;
}

// new mysql instance
$MySQL = new MySQL( MYSQL_HOST, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DATABASE );

if(isset($_GET['sessionId']) && strlen($_GET['sessionId']) > 0 && isset($_GET['request'])) {
		// Dateianfrage
		session_id($_REQUEST['sessionId']);
		session_start();
		
		if(isset($_SESSION['patcher']) === false || $_SESSION['patcher'] != 'allowed') {
			// Authentifizierung nicht erfolgt
			LogError("Authentifizierung seltsam fehlgeschlagen");
			die();
		}
		
		$version = str_replace("patch_", "", $_REQUEST['request']);
    $version = intval(str_replace(".me", "", $version));
		
		$row = $MySQL->query_first(sprintf("SELECT patch_verification FROM patcher WHERE version = '%d' AND status = 'active' AND installID = '1'", $version));
		if(count($row) != 1 || strlen($row['patch_verification']) != 32 ) {
			LogError("Patch existiert nicht oder ungültige patch_verification".Print_R($row, true));
			die();
		}	
		$patch_verification = $row['patch_verification'];
  
	  if(isset($_GET['askformirror'])) {
  		$row = $MySQL->query_first(sprintf("SELECT path FROM patchmirrors WHERE version >= '%d' AND installID = '1'", $version));
			if(count($row) == 0) {
				LogError("Kein Mirror-Pfad gefunden");
				// wenn url leer ist, könnten wir auch einfach die Datei ausliefern. Fraglich, ob der Patcher das unterstützt
				die();
			}
			$url = $row['path'];
  		header( "patch_verification: ".$patch_verification);
  		header( "patch_url: $url");
  		die();	
    }

		if(file_exists( CFG_PATCHFILES."patch_".$version.".me" )===false) {
			LogError("Datei ".CFG_PATCHFILES."patch_".$version.".me"." exisitiert nicht");
			header("HTTP/1.0 404 Not Found");
			die();
		}
		
   	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" );
		die();
} elseif(isset($_GET['action']) && $_GET['action'] == 'authenticate') {
		// Authentifizierung
		if(isset($_GET['user']) && isset($_GET['password']) && strlen($_GET['password']) == 32) {
		    $row = $MySQL->query_first(sprintf("SELECT password, rank FROM server.accounts WHERE name= '%s' AND password = '%s'", me_escape($_REQUEST['user']), me_escape($_REQUEST['password'])));
			if(count($row) > 0) {
				session_start();
    		header("patcher-auth: ok");
        	$_SESSION['patcher'] = 'allowed';
        	$_SESSION['rank'] = $row['rank'];
				die();
    	}
			else { 
        	header( "patcher-auth: failed" );
				die();
    	}
		} else {
			LogError("Ungültige Anfrage");
			die();
		}
} else {
		LogError("Ungültige Anfrage");
}
?>