<?php
	/**
	* Authentication based on SQL, with optional SSL authentication
	* @author Andreas 'Count' Kotes <count@flatline.de>
	* @copyright Copyright (C) 200x Andreas 'Count' Kotes <count@flatline.de>
	* @copyright Portions Copyright (C) 2004 Free Software Foundation, Inc. http://www.fsf.org/
	* @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
	* @package phpgwapi
	* @subpackage accounts
	* @version $Id: class.auth_sqlssl.inc.php,v 1.4.2.1.2.7 2004/06/28 07:08:09 powerstat Exp $
	*/

	/**
	* Authentication based on SQL, with optional SSL authentication
	*
	* @package phpgwapi
	* @subpackage accounts
	* @ignore
	*/
	class auth
	{
		var $previous_login = -1;

		function authenticate($username, $passwd)
		{
			$db = $GLOBALS['phpgw']->db;

			$local_debug = False;

			if($local_debug)
			{
				echo "<b>Debug SQL: uid - $username passwd - $passwd</b>";
			}

			// Apache + mod_ssl provide the data in the environment
			// Certificate (chain) verification occurs inside mod_ssl
			// see http://www.modssl.org/docs/2.8/ssl_howto.html#ToC6
			if(!isset($_SERVER['SSL_CLIENT_S_DN']))
			{
				// if we're not doing SSL authentication, behave like auth_sql
				$db->query("SELECT * FROM phpgw_accounts WHERE account_lid = '$username' AND "
					. "account_pwd='" . md5($passwd) . "' AND account_status ='A'",__LINE__,__FILE__);
				$db->next_record();
			}
			else
			{
				// use username only for authentication, ignore X.509 subject in $passwd for now
				$db->query('SELECT * FROM phpgw_accounts'
					. " WHERE account_lid = '" . $db->db_addslashes($username) . "'"
					. "AND account_status ='A'",__LINE__,__FILE__);
				$db->next_record();
			}

			if($db->f('account_lid'))
			{
				return True;
			}
			else
			{
				return False;
			}
		}

		function change_password($old_passwd, $new_passwd, $account_id = '')
		{
			if(!$account_id)
			{
				$account_id = $GLOBALS['phpgw_info']['user']['account_id'];
			}

			$encrypted_passwd = md5($new_passwd);

			$GLOBALS['phpgw']->db->query('UPDATE phpgw_accounts'
						. " SET account_pwd='" . md5($new_passwd) . "',"
						. ' account_lastpwd_change=' . time()
						. ' WHERE account_id=' . intval($account_id),__LINE__,__FILE__);

			$GLOBALS['phpgw']->session->appsession('password','phpgwapi',$new_passwd);

			return $encrypted_passwd;
		}

		function update_lastlogin($account_id, $ip)
		{
			$GLOBALS['phpgw']->db->query('SELECT account_lastlogin'
						. ' FROM phpgw_accounts'
						. ' WHERE account_id=' . intval($account_id),__LINE__,__FILE__);
			$GLOBALS['phpgw']->db->next_record();
			$this->previous_login = $GLOBALS['phpgw']->db->f('account_lastlogin');

			$GLOBALS['phpgw']->db->query('UPDATE phpgw_accounts'
					. " SET account_lastloginfrom='" . $GLOBALS['phpgw']->db->db_addslashes($ip) . "',"
					. ' account_lastlogin=' . time()
					. ' WHERE account_id=' . intval($account_id),__LINE__,__FILE__);
		}
	}
?>
