<?php
if(file_exists("E:/www/hp/service.php")) { 
	require_once("E:/www/hp/service.php");
}
// include required files
include './lib/config.inc.php';
include './lib/functions.inc.php';
include './lib/MySQL.class.php';
include './lib/Account.class.php';
include './smarty_/Smarty.class.php';

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

// new smarty instance
$Smarty = new Smarty;

// get settings from db
$settings = array();
$result = $MySQL->query( "SELECT * FROM settings" );
while( $row = $MySQL->fetch_array( $result ) )
{
	$settings[$row['key']] = $row['value'];
}
$Smarty->assign( 'settings', $settings );
if( isset( $settings['smtp'] ) )
	@ini_set( "SMTP", $settings['smtp'] );

ini_set( "sendmail_from", $settings['sendmail_from'] );

// set some information
if(defined('CORE_URL')===false) {
	// Über Config kann der Datenbankeintrag überschrieben werden
	define( 'CORE_URL', combine_path( "http://", $settings['host'], $settings['core_path'] ) );
}
$Smarty->assign( 'CORE_URL', CORE_URL );
if( !defined( 'REQUIRE_USER' ) )
	define( 'REQUIRE_USER', true );

$n = intval( intval( $settings['bb_num'] ) );
$page = array();

if( REQUIRE_USER )
{
	// initiate session
	session_start();
	session_name( "sid" );
	if( !is_empty( SID ) )
    {
        define( 'SID', "sid=".session_id() );
        $Smarty->assign( 'SID', SID );
        $Smarty->assign( 'SID_SHORT', session_id() );
    }

    // user already logged in or cookie data found?
    if ( isset( $_SESSION['accountid'] ) && isset( $_SESSION['password'] ) )
    {
        $user = new Account( intval( $_SESSION['accountid'] ) );

        if( $user->ID > 0 && $user->check_access( $_SESSION['password'] ) )
        {
            $Smarty->assign( 'user', $user );

            $user->last_activity = time();
            //$user->save( 'last_activity' ); 
        }
        else {
        	unset( $user, $_SESSION['accountid'], $_SESSION['password'] );
        }
    }
    else if( isset( $_COOKIE['accountid'] ) && isset( $_COOKIE['password'] ) )
    {
        $user = new Account( intval( $_COOKIE['accountid'] ) );

        if( $user->ID > 0 && $user->check_access( $_COOKIE['password'] ) )
        {
            $Smarty->assign( 'user', $user );

            $user->last_activity = time();
            $user->last_ip = $_SERVER['REMOTE_ADDR'];
            //$user->save( 'last_ip', 'last_activity' );

            $_SESSION['accountid'] = $user->ID;
            $_SESSION['password'] = $user->password;

            setcookie( "accountid", $user->ID, ( time() + intval( $settings['cookie_lifetime'] ) ) );
            setcookie( "password", $user->password, ( time() + intval( $settings['cookie_lifetime'] ) ) );
        }
        else
        {
        	unset( $user );
            setcookie( "accountid", NULL );
            setcookie( "password", NULL );
        }
    }

    
    // session table
    if(rand(0,500)==500) {
    	$MySQL->query( "DELETE FROM sessions WHERE expire <= ".time() );
    }

    $exp_time = ( time() + ( intval( $settings['session_expire'] ) * 60 ) );

    if( isset( $user ) )
    {
        $MySQL->query( "DELETE FROM sessions WHERE accountid = ".$user->ID." || sessionID = '".session_id()."'" );
        $MySQL->query( "INSERT INTO sessions (sessionID,accountid,expire) VALUES ('".session_id()."',".$user->ID.",".$exp_time.")" );
        
    	// Account abuse detector
			/*
    	if(isset($_SESSION['session_nr']) AND $_SESSION['session_nr'] > 0) {
	    	$MySQL->query("UPDATE account_abuse_detector SET accountid = '".$user->ID."', pot = NOW() WHERE session_nr = ".$_SESSION['session_nr']." AND what = 'lastaction' AND service = 'hp' LIMIT 1");	
	    }
	    else {

    		$MySQL->query("START TRANSACTION");
	    	list($_SESSION['session_nr']) = $MySQL->query_first("SELECT max(session_nr)+1 FROM account_abuse_detector");
    		$MySQL->query("INSERT INTO account_abuse_detector SET session_nr = '".$_SESSION['session_nr']."', service = 'hp', what = 'login', accountid = '".$user->ID."', ip_addr = '".strrev($_SERVER['REMOTE_ADDR'])."'");
    		$MySQL->query("INSERT INTO account_abuse_detector SET session_nr = '".$_SESSION['session_nr']."', service = 'hp', what = 'lastaction', accountid = '".$user->ID."', ip_addr = '".strrev($_SERVER['REMOTE_ADDR'])."'");
    		$MySQL->query("COMMIT");

    	}		*/
    }
    else
    {
        $MySQL->query( "UPDATE sessions SET expire = ".$exp_time." WHERE sessionID='".session_id()."'" );
        if( !$MySQL->affected_rows() )
            $MySQL->query( "INSERT INTO sessions (sessionID,accountid,expire) VALUES ('".session_id()."',null,".$exp_time.")");
    }
}

// select & get style
$style = array();
if ( isset( $_REQUEST['style_id'] ) )
    $page['style_id'] = $_REQUEST['style_id'];
else if ( isset( $_SESSION['style_id'] ) )
    $page['style_id'] = $_SESSION['style_id'];

if( !isset( $page['style_id'] ) )
{
    if( isset( $user ) )
        $page['style_id'] = $user->style_id;
    else
    {
        $default_style = $MySQL->query_first( "SELECT styleID FROM styles WHERE default_style=1" );
        $page['style_id'] = $default_style['styleID'];
    }
}

if( !defined( 'REQUIRED_STYLE' ) )
    $style = $MySQL->query_first( "SELECT * FROM styles WHERE styleID=".$page['style_id'] );
else
    $style = $MySQL->query_first( "SELECT * FROM styles WHERE styleID='".REQUIRED_STYLE );

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

if ( isset( $_REQUEST['style_id'] ) || isset( $_SESSION['style_id'] ) )
    $_SESSION['style_id'] = $page['style_id'];

$styles = $MySQL->fetch_complete( "SELECT styleID, name FROM styles ORDER BY default_style DESC", MYSQL_ASSOC );
$Smarty->assign( 'styles', $styles );

// random screenshot
$screenshots = $MySQL->query( "SELECT screenshotID FROM screenshots" );
$screen_num = $MySQL->num_rows( $screenshots );
srand( intval( substr( microtime(), 2, 8 ) ) );

$screen_row = rand( 0, $screen_num-1 );
$rand_screen = $MySQL->query_first( "SELECT screenshotID,title FROM screenshots LIMIT ".$screen_row.",1" );
$Smarty->assign( 'rand_screen', $rand_screen );

$rand_screen_img_url = combine_path( $settings['screenshots_dir'], 'image'.$rand_screen['screenshotID'].'.jpg' );
$rand_screen_thumb_url = combine_path( $settings['screenshots_dir'], 'thumb'.$rand_screen['screenshotID'].'.gif' );

$Smarty->assign( 'rand_screen_thumb_size', @getimagesize( $rand_screen_thumb_url ) );
$Smarty->assign( 'rand_screen_img_size', @getimagesize( $rand_screen_img_url ) );

// counter
$file = "counter.txt";
$ftp = @fopen( $file, "r+" );
$homepage_clicks = (int)fgets( $ftp, 10 );
$homepage_clicks++;
$Smarty->Assign( 'homepage_clicks', $homepage_clicks );
rewind( $ftp );
fwrite( $ftp, $homepage_clicks );
fclose( $ftp );

// Chars to be activated
if(isset($user) && $user->can_access('activation')) {
	$Smarty->assign('cactivation', $MySQL->query_first("SELECT COUNT(*) FROM server.chars WHERE aktiviert = 0"));
	$Smarty->assign('myactivation', $MySQL->query_first("SELECT COUNT(*) FROM server.chars WHERE aktiviert_von = '".$user->ID."' AND aktiviert = 0"));
}

function smarty_block_dynamic($param, $content, &$smarty) {
    return $content;
}
$Smarty->register_block('dynamic', 'smarty_block_dynamic', false);

// Serverstatus
$serverstatus = "<b>Server: </b>";
list($countlive, $changedl) = $MySQL->query_first("SELECT value, changed FROM server.serverstatus WHERE changed >= NOW()-INTERVAL 15 SECOND AND server = 0 AND statusvariable = 0 ORDER BY changed DESC LIMIT 0,1");
if(strlen($changedl)==0) {
	$serverstatus.="<font color=\"red\"><b>offline</b></font>";
	/*if($user->ID = 767) {
	print_R($MySQL->query_first("SELECT NOW()--INTERVAL 30 SECOND"));
	print_R($MySQL->fetch_complete("SELECT * FROM server.serverstatus ORDER BY changed DESC LIMIT 0,10"));
	
	$z = $MySQL->query_first("SELECT value, changed FROM server.serverstatus WHERE changed >= NOW()-INTERVAL 30 SECOND AND server = 0 AND statusvariable = 0 ORDER BY changed DESC LIMIT 0,1");
	
	var_dump($z);
	die();
	Print_R($z);
	//Print_R($GLOBALS);
	}*/
} else {
	if($countlive < 3) $countlive = "&lt;3";
	$serverstatus.="<font color=\"green\"><b>$countlive online</b></font>";
}



if(isset($user) && $user->rank >= 5) {
	// Testserver
	list($counttest, $changedt) = $MySQL->query_first("SELECT value, changed FROM server.serverstatus WHERE changed >= NOW()-INTERVAL 30 SECOND AND server = 1 AND statusvariable = 0 ORDER BY changed DESC LIMIT 0,1");
	$serverstatus.= " <b>Test: </b>";
	if(strlen($changedt)==0) {
		$serverstatus.="<font color=\"red\"><b>offline</b></font>";
	} else {
		$serverstatus.="<font color=\"green\"><b>$counttest</b></font>";
	}
	
	// Bauserver
	list($countbau, $changedb) = $MySQL->query_first("SELECT value, changed FROM server.serverstatus WHERE changed >= NOW()-INTERVAL 30 SECOND AND server = 2 AND statusvariable = 0 ORDER BY changed DESC LIMIT 0,1");
	$serverstatus.= " <b>Bau: </b>";
	if(strlen($changedb)==0) {
		$serverstatus.="<font color=\"red\"><b>offline</b></font>";
	} else {
		$serverstatus.="<font color=\"green\"><b>$countbau</b></font>";
	}
}

$Smarty->assign('serverstatus', $serverstatus);
?>
