<?php
/*
EasyGUI XP is free software released under the terms of the following BSD license.

Copyright (c) 2005,2006 Gaetan Lauff (glauff@plansoft.de)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, 
this list of conditions and the following disclaimer. 

- Redistributions in binary form must reproduce the above copyright notice, 
this list of conditions and the following disclaimer in the documentation 
and/or other materials provided with the distribution.

- Neither the name of the developer nor the names of its contributors may 
be used to endorse or promote products derived from this software without 
specific prior written permission. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**
 * Authentication Handler for Applications
 *
 * @author Gaetan Lauff <glauff@plansoft.de>
 * @version	XP $Id: class.ek_auth.php 8 2006-02-15 13:45:24Z glauff $
 * @package auth
 */
class EK_Auth
{
	/**
	 * @var string
	 */
	var $feedback = "";
	
	/**
	 * Instance of Database connection Class
	 * @var object
	 */
	var $dbHandler;
	
	/**
	 * Instance of Session Class
	 * @var object
	 */
	var $session;
	
	/**
	 * Hash Var
	 * @var	string
	 */
	var $hashKey = 'SBLA572LG';
	
	/**
	* Constructor
	* Checks for valid Users
	*
	* @param	object	database connection
	* @param	array	authentication settings
	* @param	boolean	if passwords are md5 encrypted
	*
	* @return 	void
	*
	* @access 	public
	*/
	function EK_Auth(&$dbHandler, &$session, &$settings )
	{		
		@define ( 'USER_LOGIN_VAR', 	EK_SimpleXML::getAttribute( $settings, 'user_login_var', 'USERNAME' ));
		@define ( 'USER_PASSW_VAR', 	EK_SimpleXML::getAttribute( $settings, 'user_passw_var', 'PASSWORD' ));
		/**
		 * User Table Details
		 */
		@define ( 'USER_TABLE', 		EK_SimpleXML::getAttribute( $settings, 'user_table', 'users' ));
		@define ( 'USER_TABLE_ID', 		EK_SimpleXML::getAttribute( $settings, 'user_table_id', 'user_id'));
		@define ( 'USER_TABLE_LOGIN', 	EK_SimpleXML::getAttribute( $settings, 'user_table_login', 'username' ));
		@define ( 'USER_TABLE_PASSW',  	EK_SimpleXML::getAttribute( $settings, 'user_table_passw', 'password' ));
		
		$this->md5 		 = EK_SimpleXML::getAttribute( $settings, 'md5', TRUE );
		$this->dbHandler = &$dbHandler;
		$this->session 	 = &$session;
	}
	
	/**
    * Checks username and password against database
    *
    * @return void
    *
    * @access private
    */
    function login() {
        if ( $this->session->get('login_hash') ) {
            return $this->confirmAuth();
        }

        $login = EK_Common::getSubmitValue( USER_LOGIN_VAR );
        $password = EK_Common::getSubmitValue( USER_PASSW_VAR );
        
        if ( !$login || !$password ) {
        	return false;
        }
        
        if ( $this->md5 ) {
            $password = md5( $password );
        }
        
        $login 		= mysql_escape_string($login);
        $password 	= mysql_escape_string($password);

        $sql="SELECT * FROM ".USER_TABLE."
                	WHERE ".USER_TABLE_LOGIN."='".$login."'
                	AND ".USER_TABLE_PASSW."='".$password."'";

        $result = $this->dbHandler->Execute( $sql );
        
        if ($result->RecordCount() != 1) {
        	return false;
        }
        	
        $row 	= $result->FetchRow();
        $this->storeAuth($login,$password, $row[USER_TABLE_ID]);
        
        return true;
    }
    /**
    * Sets the session variables after a successful login
    *
    * @return void
    *
    * @access private
    */
    function storeAuth( $login, $password, $user_id )
    {
    	$this->session->set( 'IDC_USER_ID', $user_id);
        $this->session->set( USER_LOGIN_VAR, $login );
        $this->session->set( USER_PASSW_VAR, $password );
        $hashKey = md5( $this->hashKey . $login . $password );
        $this->session->set( 'login_hash' , $hashKey );
    }
    
    /**
    * Confirms that an existing login is still valid
    *
    * @return void
    *
    * @access private
    */
    function confirmAuth() 
    {
        $login 		= $this->session->get( USER_LOGIN_VAR );
        $password 	= $this->session->get( USER_PASSW_VAR );
        $hashKey 	= $this->session->get( 'login_hash' );
        
        if ( md5( $this->hashKey.$login.$password) != $hashKey ) {
            return false;
        }
        
        return true;
    }
    
    /**
    * Logs the user out
    *
    * @return void
    *
    * @access public
    */
    function logout ()
    {
    	@session_regenerate_id( true );
        @session_destroy();   
    }
    
    /**
     * Returns an attribute from the User Table
     *
     * @param 	string	$attribute	Attribute to search for
     * @param 	string	$userName	Username
     *
     * @return 	The user Attribute if it's found, FALSE otherwise 
     * @access 	public
     */
    function getUserAttribute($attribute, $userName)
	{
		$sql = "SELECT ".$attribute." FROM " . USER_TABLE ." WHERE " . USER_TABLE_LOGIN ."='".$userName."';";
		$result =& $this->dbHandler->Execute( $sql );
		
		if ( $result->RecordCount() == 0 ) {
			$this->feedback = "COULD_NOT_RETRIEVE_ATTRIBUTE";
			return false;
		} else {
			$row = $result->FetchRow();
			return $row[$attribute];
		}
	}
}
?>