<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ApiSecurity
 *
 * @author NE
 */
class RCMS_Object_ApiSecurity_ApiSecurity {

	private $_model = null;

	public function  __construct() {
		$this->_model = new RCMS_Object_ApiSecurity_ApiSecurityModel();
	}

	/**
	 * Super owesome cription algorythm =)
	 *
	 * @param string $valueOne
	 * @param string $valueTwo
	 * @return string
	 */
	public function generateAuthHashCode($valueOne, $valueTwo) {
		$partOne = sha1($valueTwo);
		$partTwo = sha1($valueOne);
		return $authHashCode = substr(md5($partOne.$partTwo.$partTwo.$partOne), 2, 7);
	}

	/**
	 * Check for authorization descriptor in request header
	 *
	 * @param string $requestHeaders
	 * @return string
	 */
	private function _getAuthDescriptorFromRequestHeaders($requestHeaders) {
		$authHeader = $requestHeaders['Http-Rcms-Auth'];
		preg_match('/RCMSLogin "Auth=([a-z0-9]{7})"/', $authHeader, $found);
		if(isset($found[1])) {
			return $found[1];
		}
		return false;
	}

	/**
	 * Save authorization descriptor
	 *
	 * @param integer $userId
	 * @param string $descriptor
	 */
	public function saveAuthDescriptor($userId, $descriptor) {
		$this->_model->saveAuthDescriptor($userId, $descriptor);
	}

	/**
	 * Check for descriptor
	 *
	 * @return string or false on failure
	 */
	public function checkAuthdescriptor() {
		$headers = $this->_getAllHeaders();
		return $this->_getAuthDescriptorFromRequestHeaders($headers);
	}

	/**
	 * Gets user id according to auth descriptor
	 *
	 * @param string $descriptor
	 * @return integer
	 */
	public function getUserIdByDescriptor($descriptor) {
		return $this->_model->getUserIdByDescriptor($descriptor);
	}

	/**
	 * Check that user with login and password exists
	 *
	 * @param string $login
	 * @param string $password
	 * @return boolean
	 */
	public function checkUserByLoginAndPass($login, $password) {
		return $this->_model->checkUserByLoginAndPass($login, $password);
	}

	protected function _getAllHeaders() {
		foreach ($_SERVER as $name => $value) {
			if (substr($name, 0, 5) == 'HTTP_') {
				$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
			}
		}
       return $headers;
//		$request = new Zend_Controller_Request_Http();
//		$headers['Authorization'] = $request->getHeader('Authorization');
//		return $headers;
	}

}

