<?php
include("config/config.inc.php");
include("class/Template.class.php");
include("class/dB.class.php");

function mysql_41_password($in)
{
    $p = sha1($in, true);
    $p = sha1($p);
    return '*'. strtoupper($p);
}

$loginInfo="";

session_start();

$mydbLogin = new DB_MySQL($db_name,$db_user,$db_pass,$db_server);

if(isset($_POST['login']))
{
	$login = $mydbLogin-> mysql_escape_string($_POST['login']);
	$password = $mydbLogin-> mysql_escape_string($_POST['password']);
    
    //Pürfe login auf SQL-Injection
    if (!preg_match("/^([a-zA-Z0-9öäüßÖÄÜß?!,.;:_()@ \n\r-]+)$/is", $login)) {
 		$login = "";
 	} 
    
	$mydbLogin->query("SELECT * FROM AdminUser WHERE BINARY UserLogin = '$login'");
	$row = $mydbLogin->fetchRow();
 	$dBPassword = $row['userPassword'];
 	$startId = $row['startId'];
	
	if ( (empty($dBPassword) != true) && ( mysql_41_password($password) == $dBPassword) )
	{
		$userid = $mydbLogin->mysql_escape_string($row['userId']);
		
		$_SESSION['auth'] = true;
		$_SESSION['userId'] = $userid;

		$mydbLogin->query("SELECT UserImage FROM AdminUserInformation WHERE userId = $userid");
	    $row = $mydbLogin->fetchRow();
 	    $image = $row['UserImage'];
 	    
 	    $file = fopen("img/". "UserPic". $userid .".png","w");
        fwrite($file, $image);
        fclose($file);
		
		
		header("Location: index.php?pageId=".$startId);
	} 
	else 
	{
		 $_SESSION['auth'] = false;
		 
		 $loginInfo .= "<div class=\"alert alert-danger alert-dismissable\">";
         $loginInfo .= "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button>";
         $loginInfo .= "Falsches Passwort oder falscher Login !</div>";
         
         
	}
	
}

// Das Template laden
$tpl = new Template();
$tpl->load("login.tpl");

// Platzhalter ersetzen
$tpl->assign( "Sitename", $pagename );
if(isset($_POST['login']))
{
 $tpl->assign( "LoginName", $login );
}
else
{
 $tpl->assign( "LoginName", "" );
}

$tpl->assign( "InfoMessageBox", $loginInfo);

// Seite anzeigen
$tpl->display();
?>
