<?php defined("IN_DOCEBO") or die('Direct access is forbidden.');

/* ======================================================================== \
| 	DOCEBO - The E-Learning Suite											|
| 																			|
| 	Copyright (c) 2008 (Docebo)												|
| 	http://www.docebo.com													|
|   License 	http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt		|
\ ======================================================================== */

define('_AUTH_UCODE', 0); //use single user-code authentication
define('_AUTH_TOKEN', 1); //use generated token authentication

define('_AUTH_UCODE_DESC', 'SINGLE_CODE');
define('_AUTH_TOKEN_DESC', 'GENERATED_TOKEN');

class API {

	protected $db;
	protected $aclManager;

	protected $needAuthentication = true;
	protected $authenticated = false;
	protected $buffer = "";



	public function __construct() {
		$this->db = DbConn::getInstance();
		$this->aclManager = Docebo::user()->getAclManager();
	}



	/**
	 * Returns the buffer
	 * @return <return>
	 */
	public function get() { return $this->_buffer; }



	/**
	 * Writes in the buffer
	 * @param <string> $string
	 */
	protected function _write( $string ) { $this->_buffer .= $string; }



	/**
	 * Empty the buffer
	 */
	public function flush() { $this->_buffer = ""; }



	public function authenticateUser($username, $password) {
		$acl_man = Docebo::user()->getAclManager();
		$query="SELECT * FROM %adm_user "
			."WHERE userid='".$this->aclManager->absoluteId($username)."' AND pass='".$this->aclManager->encrypt($password)."'";
		$res = $this->db->query($query);
		return ($this->db->num_rows($res) > 0);
	}



	/*
	 * Check user authentication
	 */
	final public function checkAuthentication($code) {
		//eliminates old token
		$query = "DELETE FROM %adm_rest_authentication WHERE expiry_date < NOW()";
		$res = $this->db->query($query);

		if (!$this->needAuthentication) {
			//no authentication needed for this module
			return true;
		}

		//load auth setting
		$auth_method = Get::sett('rest_auth_method', 'none');

		$result = false;
		switch ($auth_method) {

			// use application's pre-set authentication code
			case _AUTH_UCODE: {
				$auth_code = Get::sett('rest_auth_code', false);
				$result = ($code == $auth_code);
			} break;

			// search the token in  authentications DB table
			case _AUTH_TOKEN: {
				$query = "SELECT * FROM %adm_rest_authentication WHERE token='$code'";
				$res = $this->db->query($query);
				if($this->db->num_rows($res) > 0) {

					$now = time();
					$result = true;
					$query = "UPDATE %adm_rest_authentication SET last_enter_date='".date("Y-m-d H:i:s", $now)."' ";
					if (Get::sett('rest_auth_update', false)) {
						$lifetime = Get::sett('rest_auth_lifetime', 1) * 60;
						$query .= " , expiry_date='".date("Y-m-d H:i:s", $now + $lifetime)."' ";
					}
					$query .= " WHERE token='$code'";
					$this->db->query($query);

				} else {
					$result = false;
				}
			} break;

			default: {}

		}
		return $result;
	}


	function call($name, $params) {
		return $this->$name($params);
	}


}


function API_Execute($auth_code, $module, $function, $params) {
	$class_path = _base_.'/api/lib/api.'.$module.'.php';
	$class_name = $module.'_API';

	require_once($class_path);
	$api_obj = new $class_name();
	
	$result = false;
	if ($api_obj->checkAuthentication($auth_code)) {
		$result = $api_obj->call($function, $params);
	}

	return $result;
}


?>