<?php
require_once 'framework/fwk.php';
require_once 'framework/common/mysql.php';

class Scores_AuthAdapter implements Zend_Auth_Adapter_Interface
{
	protected $_username;
	protected $_password;
	protected $_hash;
	protected $_timeout = 1800;
	protected $checkWs = true;

	public function __construct($username, $password, $checkWs = true)
	{
		$this->_username = $username;
		$this->_password = $password;
		$this->_hash = md5($username.'|'.$password);
		$this->checkWs = $checkWs;
	}

	public function authenticate()
	{
		$iDbCrm = new WDB('sdv1');

		if ($this->checkWs) {
			$where = "u.login='$this->_username' AND u.idClient=c.id AND u.actif=1 AND u.deleted=0 AND u.accesWS=1 AND c.actif='Oui'";
		} else {
			$where = "u.login='$this->_username' AND u.idClient=c.id AND u.actif=1 AND u.deleted=0 AND c.actif='Oui'";
		}
		$rep = $iDbCrm->select(
			'utilisateurs u, clients c',
			'u.login, u.id, u.email, u.password, u.idClient, u.typeCompte, u.actif, u.filtre_ip, u.civilite, u.nom, u.prenom, u.tel, u.fax, u.mobile, u.profil, u.raisonSociale, u.siret, u.adrNum, u.adrIndRep, u.adrTypeVoie, u.adrLibVoie, u.adrCp, u.adrVille, u.adrComp, u.tel, u.fax, u.mobile, u.pref, u.profil, u.dateInscription, u.dateValidation, u.nombreConnexions, u.dateDerniereConnexion, u.droits, u.referenceParDefaut, u.nbReponses, u.formatMail, u.dateDebutCompte, u.dateFinCompte, u.maxFicheId, c.droits AS droitsClients, c.timeout',
			$where,
			false, MYSQL_ASSOC);

		$tabRep = $rep[0];

		$identity = new stdClass();
		$identity->username = $this->_username;
		$identity->hash = $this->_hash;
		$identity->idClient = $tabRep['idClient'];

		$timeout = (!empty($InfosLogin->result->timeout)) ? $InfosLogin->result->timeout : $this->_timeout;
		$identity->timeout = $timeout;
		
		$identity->time = time() + $timeout;
		
		if (count($rep)==0) {
			//debugLog('W',"CheckAuth $login/$password inexistant ou inactif (IP=$ipConnexion)", __LINE__,__FILE__, __FUNCTION__, __CLASS__);
			return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, $identity);
		} else {
			if ( $this->_password==$tabRep['password'] || $this->_password==md5($tabRep['login'].'|'.$tabRep['password']) ) {
				//debugLog('W',"CheckAuth $login/$password OK", __LINE__,__FILE__, __FUNCTION__, __CLASS__);
				return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity);
			} else {
				//debugLog('W',"CheckAuth $login/$password incorrect (IP=$ipConnexion)", __LINE__,__FILE__, __FUNCTION__, __CLASS__);
				return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, $identity);
			}
		}
	}

}