<?php

class mfLoginController extends mfBaseController {
	
	protected function init($request) {
		$this->layout()->setTemplate("mfLogin/Index");
    if($request['mfLoginTemplate']) {
      $this->layout()->setTemplate($request['mfLoginTemplate']);
    }
		/*if($request['mfLoginGet']) {
			$_SESSION['mfLoginGet']=$request['mfLoginGet'];
		}*/
    if($request['mfLoginUrl']) {
			$_SESSION['mfLoginUrl']=$request['mfLoginUrl'];
		}
    
    
		$this->logout();
	}
	
  
	protected function indexAction() {
		if($_SESSION[MFAPPNAME."_loginfailed"]) {
			$this->layout()->set("LayoutError","Login fehlgeschlagen.");
		}
		unset($_SESSION[MFAPPNAME."_loginfailed"]);
		
	}
	
	protected function loginAction($request) {
		if(!$this->performLogin($request['Username'],$request['Password'])) {
			$_SESSION[MFAPPNAME."_loginfailed"]=true;
		}
		//$get=$_SESSION['mfLoginGet'];
    $url=$_SESSION['mfLoginUrl'];
		//unset($_SESSION['mfLoginGet']);
    unset($_SESSION['mfLoginUrl']);
    /*
    $mod=$get['action'];
    if(preg_match('/([^_]+)_(.+)/',$action,$m)) {
      $mod=$m[1];
      $action=$m[2];
    }
    unset($get['action']);
    
		self::redirect($mod,$action,$get);
    */
    
    header("Location: $url");
	}
	

	
	/*
	 * Internal functions
	 */
	public function logout() {
		if(!defined("MFAPPNAME")) define("MFAPPNAME","mvcfronk");
		if(!defined("MFUSERTABLE")) define("MFUSERTABLE","mfWorker");
    //session_name(MFAPPNAME."_session");
		//session_start();
		unset($_SESSION[MFAPPNAME.'_username']);
		unset($_SESSION[MFAPPNAME.'_ip']);
	}
	
	public static function isLoggedIn() {
		$db=new FronkDB();
		if(!defined("MFAPPNAME")) define("MFAPPNAME","mvcfronk");
		if(!defined("MFUSERTABLE")) define("MFUSERTABLE","mfWorker");
		
    //session_name(MFAPPNAME."_session");
		//session_start();
		if($_SESSION[MFAPPNAME.'_username'] && $_SESSION[MFAPPNAME.'_ip']) {
			$username=$_SESSION[MFAPPNAME.'_username'];
			$ip=$_SERVER['REMOTE_ADDR'];
			$sid=session_id();
			
			if($_SESSION[MFAPPNAME.'_ip']==$ip) {
				// session seems legit, check if user exists and additionally check IP saved in database
				$res=$db->select(MFUSERTABLE,"*","username='$username' AND ip='$ip' AND sessionid='$sid'");
				if($db->num_rows($res)) {
					$user=$db->fetch_object($res);
					self::initSession($user);
					return true;
				}
				return false;
			}
		} else {
      
			return false;
		}
	}
	
	protected static function initSession($user) {
		$_SESSION[MFAPPNAME.'_username']=$user->username;
		$_SESSION[MFAPPNAME.'_ip']=$_SERVER['REMOTE_ADDR'];
		unset($_SESSION[MFAPPNAME."_loginfailed"]);
		
		$user=mfUser::singleton($user);
		
		return true;
	}
	
	
	protected function performLogin($username,$password) {
		if(!defined("MFAPPNAME")) define("MFAPPNAME","mvcfronk");
		if(!defined("MFUSERTABLE")) define("MFUSERTABLE","mfWorker");
		
		//session_set_cookie_params(0);
    //session_name(MFAPPNAME."_session");
		//session_start();
		$username=$this->db()->escape($username);
		
		$res=$this->db()->select(MFUSERTABLE,"*","username='$username'");
		if(!$this->db()->num_rows($res)) {
			sleep(1);
			return false;
		}
		$user=$this->db()->fetch_object($res);
		$hash=$user->password;
		
		$salt=substr($hash,0,16);
		$passhash=$this->generatePasswordHash($password,$salt);
    
		if($passhash==$hash) {
      //session_name(MFAPPNAME."_session");
			//session_start();
			$this->db()->update(MFUSERTABLE,array('ip' => $_SERVER['REMOTE_ADDR'],'sessionid' => session_id()),"username='$username'");
      $this->log->debug("$username logged in");
      self::initSession($user);
			return true;
		}
		
    return false;
	}
	
	public static function generatePasswordHash($pass,$salt=NULL) {
		if(!$salt) {
			$salt = substr(md5(uniqid(rand(), true)), 0, 16);
		} else {
			$salt = substr($salt,0,16);
		}
		
		return $salt.sha1($salt.$pass);
	}
}
