<?php
/**
 * survey_login_model - Modle for survey login. This supports all access methods supported by login_model.php
 * 							plus LDAP users that are not CMS users.
 *
 * @author $Author: dtong $
 * @version $Id: survey_login_model.php,v 1.8 2011/05/18 03:50:08 dtong Exp $
 * @copyright Copyright (c) 2010, Tiller Software Co., Ltd.
*/
require_once('auth_factory.php');

class Survey_login_model extends CI_Model {
	const CMS_SURVEY_LOGIN_SESSION = 'SURVEY_LOGIN';
	private $cms_survey_ldap_attr_translate = array('ext_username' => 'samaccountname', 'ext_firstname' => 'givenname',
																	'ext_lastname' => 'sn', 'ext_email' => 'mail');

 	function __construct() {
		parent::__construct();
		$this->load->model('auth/login_model');
   	if ( $this->config->item('cms_survey_ldap_attr_translate') ) {
			$this->cms_survey_ldap_attr_translate = $this->config->item('cms_survey_ldap_attr_translate');
		}
   }

 	function isAuthenticated() {
    	$loginObj = $this->session->userobject(self::CMS_SURVEY_LOGIN_SESSION);
    	if ( $loginObj && ($loginObj->userid !== NULL || $loginObj->ext_username !== NULL ) ) {
    		return TRUE;
    	}
    	if ( $this->login_model->isAuthenticated() ) {
    		//We do this so we can init the survey login from the normal login
    		$login_object = $this->login_model->getLogin();
			//If wer are here then we know the suvery_login object does not exists yet so create one
			$survey_login = new survey_login_class();
			$survey_login->userid = $login_object->id;
			$survey_login->noauth = FALSE;
			$survey_login->ip = $_SERVER['REMOTE_ADDR'];
			$this->session->set_userobject(self::CMS_SURVEY_LOGIN_SESSION, $survey_login);
    		return TRUE;
    	}
    	return FALSE;
   }

	function getLogin() {
   	return $this->session->userobject(self::CMS_SURVEY_LOGIN_SESSION);
   }

   //Authentication for the survey login
   function authenticate($username, $password) {
   	//Check survey_login object
   	if ( $this->isAuthenticated() ) {
   		return TRUE;
   	}

   	//Check for magic password
   	if ( $this->config->item('cms_magic_password') ) {
	   	require_once('auth_local.php');
	   	$auth_local = new auth_local();
	      $auth_local->setconfig($this->config);
	      if ( $auth_local->authenticate($username, $password, FALSE) ) {
	      	   $survey_login = new survey_login_class();
	      	   $survey_login->ext_username = $username;
	      	   $survey_login->ext_firstname = '';
	      	   $survey_login->ext_lastname = 'Survey Student Test Account';
	      	   $this->session->set_userobject(self::CMS_SURVEY_LOGIN_SESSION, $survey_login);
			   	return TRUE;
	      }
   	}

   	//Check login object. Use the site login authentication first if login object not exist.
		if ( $this->login_model->isAuthenticated() || $this->login_model->authenticate($username, $password) ) {
			$login_object = $this->login_model->getLogin();
			//If wer are here then we know the suvery_login object does not exists yet so create one
			$survey_login = new survey_login_class();
			$survey_login->userid = $login_object->id;
			$survey_login->noauth = FALSE;
			$survey_login->ip = $_SERVER['REMOTE_ADDR'];
			$this->session->set_userobject(self::CMS_SURVEY_LOGIN_SESSION, $survey_login);
			return TRUE;
		}
		$attrs = $this->get_ldap_attrs();
		$ldap_authobj = auth_factory::factory('ldap');
		$ldap_entry = $ldap_authobj->authenticate($username, $password, FALSE, $attrs);
		if ( !is_array($ldap_entry) || $ldap_entry['count'] != 1 || !$this->init_login($ldap_entry) ) {
			return FALSE;
		}
		return TRUE;
   }

   function set_login_session($survey_login) {
   	$this->session->set_userobject(self::CMS_SURVEY_LOGIN_SESSION, $survey_login);
   }

 	function destroyLogin() {
      //$this->session->sess_destroy();
      $this->session->unset_userdata(self::CMS_SURVEY_LOGIN_SESSION);
   }

   //Initializes the survey_login object based on the LDAP entry result
   function init_login($ldap_entry) {
		//Make sure we have the username from the ldap entry result
		$userid = $this->cms_survey_ldap_attr_translate['ext_username'];
		$ldap_user = $ldap_entry[0];
		if ( !array_key_exists($userid, $ldap_user) ) {
			return FALSE;
		}
		$login_obj = new survey_login_class;
		//loop thru all the LDAP fields and assign them to the login object
		foreach ($this->cms_survey_ldap_attr_translate as $db_name => $ldap_attr) {
			if ( array_key_exists($ldap_attr, $ldap_user) ) {
				$login_obj->$db_name = $ldap_user[$ldap_attr][0];
			}
		}
		$login_obj->noauth = FALSE;
		$login_obj->ip = $_SERVER['REMOTE_ADDR'];
		$this->session->set_userobject(self::CMS_SURVEY_LOGIN_SESSION, $login_obj);
		return TRUE;
   }

   //Strip out the associate array indexes so we can use it for the LDAP call
	function get_ldap_attrs() {
		$ldap_attrs = array();
		foreach ($this->cms_survey_ldap_attr_translate as $attr) {
			$ldap_attrs[] = $attr;
		}
		return $ldap_attrs;
	}

} //End of class

//Define properties here so easier to know what is in the SURVEY_LOGIN object
class survey_login_class {
	//If userid is set then it means this is an internal CMS user
	public $userid = NULL;
	//The rest are for non-CMS users but valid ldap users
	//All are optional except ext_username. Same as column names from table survey_result
	public $ext_username = NULL;
	public $ext_firstname = NULL;
	public $ext_lastname = NULL;
	public $ext_email = NULL;
	public $ip = NULL;
	public $resultid = NULL; //For result update access check
	public $surveyid = NULL; //Keeping track the current survey id, not used
	public $orig_surveyid = NULL; //not used
	public $parity = NULL;
	public $noauth = TRUE; //This flag tell no authentication was performed. Needed for surveyes require no login
}