<?php
//standard $langA values are not available to this file

defined('WikyBlog') or die("Not an entry point...");

wbLang::getFile('register');

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//			Session log (in/out)
//

class sessLog{
	
	//
	//			logout
	//
	function out($warn=true){
		global $page,$wbTables,$serverName2,$wbNow;
		$page->session = true; //send a new userMenu
		
		if( empty($_COOKIE['wbsid2']) ){
			return;
		}
		
		$query = 'UPDATE '.$wbTables['users'].' SET ';
		$query .= ' `modified` = `modified`, ';
		$query .= ' `visited` = "'.$wbNow.'", ';
		$query .= ' `sid` = "" ';
		$query .= ' WHERE `sid` = "'.wbDB::escape($_COOKIE['wbsid2']).'" ';
		$query .= ' LIMIT 1';
		wbDB::runQuery($query);
		unset($_COOKIE['wbsid2']);
		
		wbSession::siteCookie('wbsid2',"",time()-2592000);
		
		if( $warn ){
			message('LOGGED_OUT');
		}
	}	
	
	
	
	//
	//	login
	//
	
	function in($registration=false){
		global $sessRemember,$page, $wbTables, $sessValues,$wbNow;
		
		
		if( !cookies() ){
			message('COOKIES_REQUIRED');
			return false;
		}
		
		session_start();
		//open edits
		if( !empty($_SESSION['editPage']) ){
			$sessValues['editPage'] = $_SESSION['editPage'];
		}
		session_write_close();
		
		//!! wondering about this helping the auto logout issue
		//foreach($_SESSION as $key => $value){
		//	unset($_SESSION[$key]);
		//}
		$_SESSION = array();
	
		
		
		/// Username, Password
			if( empty($_POST['username']) ){
				message('ENTER_USERNAME');
				return false;
			}
			if( empty($_POST['password']) ){
				message('ENTER_PASSWORD');
				return false;
			}
			
			$_POST['username'] = wbDB::escape( toStorage($_POST['username']) );
			
			
			$attempts = sessLog::checkAttempts($_POST['username']);
			if( $attempts === false){
				return false;
			}
		
			$logged_in = sessLog::set($_POST['username'], $_POST['password']);
			
		/// Failed
			if( !$logged_in ){
				//must set owner name because $pageOwner isn't available yet
				//$langA isnt available either..
				$url = '/Special/'.$GLOBALS['wbConfig']['pUser'].'/LostPassword';
				$linkA = '<a href="'.wbLinks::getUrl($url).'" rev="'.$page->revType.'">';
				$linkB = '</a>';
				message('LOGIN_FAILED',$linkA,$linkB);
				sessLog::addAttempt($_POST['username'],$attempts);
				return;
			}
			
		/// Success
			includeFile('tool/SpecialContent.php');
			$message = specialContent::get('Logged_In',array('name'=>$_POST['username']));
			if( $message === false ){
				message('LOGGED_IN',$_POST['username']);
			}else{
				message($message);
			}
			return true;
	}
	
	
	function set($username,$password){
		global $sessRemember, $page, $wbTables, $wbNow;
		
		//	similar to translateIP
			$temp = explode('.',$_SERVER['REMOTE_ADDR']);
			$checkIP = array_shift($temp);
			$checkIP .= str_pad(array_shift($temp),3,'0',STR_PAD_LEFT);
			$checkIP .= str_pad(array_shift($temp),3,'0',STR_PAD_LEFT);
					
		//	SID
			$length = mt_rand(60,100);
			$charString = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
			
			$sid = str_shuffle($charString);
			$sid = substr($sid,0,$length);//prefix can only be 114 characters long	
			$sid = uniqid($sid);		
			$sid = substr($sid,-$length);//strlen could be >100 so substr one more time
			
		/// Query
			$query = 'UPDATE '.$wbTables['users'].' SET ';
			$query .= ' `sid` = "'.$sid.'", ';
			$query .= ' `ip` = "'.$checkIP.'", ';
			$query .= ' `login_attempts` = 0, ';
			$query .= ' `visited` = "'.$wbNow.'", ';
			$query .= ' `modified`=`modified` ';
			$query .= ' WHERE `username` = "'. $username .'" ';
			if( $password !== false ){
				$query .= ' AND `password` = "'. wbDB::escape( md5($password) ).'" ';
			}
			$query .= ' LIMIT 1';
			$num = wbDB::runQuery($query,true);
			if($num !== 1){
				return false;
			}
			
			
		/// Success
			if( isset($_POST['remember']) && $_POST['remember'] === 'on'){
				$length = mt_rand(60,100);
				$sessRemember = str_shuffle($charString);
				$sessRemember = substr($sessRemember,0,$length);
			}else{
				$sessRemember = 'unset';
			}
			
			$_COOKIE['wbsid2'] = $sid;
			wbSession::cookie();
			
			$page->session = true; //send a new userMenu
			
		return true;
	}
	
	
	//
	//	Some things need to be done for login after the session has started
	//
	function afterIn(){
		global $sessRemember;
		if( !isset($_SESSION['username']) ){
			return;
		}
		
		//cannot be confirmed admin if they just logged in
		unset($_SESSION['adminConfirmed']);	
		
		//this will just force the checksum to be different
		$_SESSION['updateNow'] = true;
		
		
		/// Remember Me
		if( $sessRemember === 'unset' ){
			unset($_SESSION['remember']);
			
		}elseif( $sessRemember ){
			$_SESSION['remember'] = $sessRemember;
			
		}
	}	
	
	
	function addAttempt($username,$attempts){
		global $wbTables,$wbNow;
		$attempts['login_attempts']++;
		$query = 'UPDATE '.$wbTables['users'].' SET ';
		$query .= ' `login_attempts` = '.$attempts['login_attempts'].', ';
		$query .= ' `last_attempt` = "'.$wbNow.'", ';
		$query .= ' `modified` = `modified` ';
		$query .= ' WHERE username = "'.$username.'" ';
		$query .= ' LIMIT 1 ';
		wbDB::runQuery($query);
	}

	//
	//		Check the number of attempts
	//
	function checkAttempts($username){
		global $wbConfig,$wbTables;
		
			$query = 'SELECT `login_attempts`, `last_attempt` FROM '.$wbTables['users'].' WHERE `username`= "'.$username.'" LIMIT 1';
			$result = wbDB::runQuery($query);
			$num = mysql_num_rows($result);
			if( $num < 1){
				//usernames aren't hidden by the program in any way.. so why not help users that mistype their username
				
				$link = wbLinks::special('Register?username='.wbHtmlspecialchars($username),wbHtmlspecialchars($username),'',$GLOBALS['wbConfig']['pUser']);
				message('WRONG_USERNAME',$link);
				return false;
			}
			$attempts = mysql_fetch_assoc($result);
			$lastAttempt = dbFromDate($attempts['last_attempt'],'unix');

			$timeDiff = (time() - $lastAttempt)/60;
			
			$wbConfig['maxLoginAttempts'] = 5;
			$wbConfig['loginLockTime'] = 30;
			
			if( $attempts['login_attempts'] >= $wbConfig['maxLoginAttempts'] ){
				
				if( $timeDiff < $wbConfig['loginLockTime']){
					$remainingTime = $wbConfig['loginLockTime']-$timeDiff;
					message('LOGIN_BLOCK',$wbConfig['maxLoginAttempts'],ceil($remainingTime));
					return false;
					
				}else{
					$attempts['login_attempts'] = 0;
				}
			}
		return $attempts;
	}	
}

	//takes values from non-logged in user ($sessValues) 
	//and adds them to the logged in user
	function updateSessValues(){
		global $sessValues;
		if( empty($sessValues) ){
			return;
		}
		
		foreach($sessValues as $key => $value){
			if( empty($_SESSION[$key]) ){
				$_SESSION[$key] = $value;
				continue;
			}
			if( is_array($value) ){
				$_SESSION[$key] = array_merge( (array)$_SESSION[$key],$value);
				continue;
			}
			//message($key.' :: '.showArray($value));
		}
	}

