<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class form_hash{
    
    private $CI;
    public $time_point = 10; // default - count of seconds
    
    function __construct() {
        if(!isset($this->CI)){
            $this->CI = &get_instance();
        }
    }
    
    /**
     * Set in form hidden field with hash. Also set hash in session.
     * @return string 
     */
    public function set_form_hash(){

        $value = substr(md5(md5(microtime()) . $this->CI->config->item('encryption_key')), 0, 15);
        $html = '<input type="hidden" name="hash" value="'.$value.'" />';
        
        $hash = $this->CI->session->userdata('form_hash');
        
        if (!is_array($hash)) {
            $hash = array();
        }
        
        $hash[] = $value;
        
        $this->CI->session->set_userdata('form_hash', $hash);
        $this->set_time_point();
        
        return $html;
    }
    
    /**
     * Check hash from form
     * @return bolean 
     */
    public function check_form_hash(){
        
        if(!empty($_POST['hash'])){

            $hash = $this->CI->session->userdata('form_hash');
            
            $key_hash = array_search($_POST['hash'], $hash);
            
            if($key_hash !== FALSE && $this->check_time_point()){
                
                //unset hash
                unset($hash[$key_hash]);
                $this->CI->session->set_userdata('form_hash', $hash);
                
                return TRUE;
            }
        }
        
        return FALSE;
    }
    
    /**
     * Set time in session. Then form was build 
     * @return void
     */
    private function set_time_point(){
        
        $time = date('H:i:s');
        $this->CI->session->set_userdata('form_time', $time);
    }
    
    /**
     * Check time to filing form
     * @return bolean
     */
    private function check_time_point(){
        
        $point = $this->CI->session->userdata('form_time');
        
        if(!empty($point)){
            
            if(date('H:i:s', strtotime('-'.$this->time_point.' seconds', strtotime(date('H:i:s'))))>=$point){
                return TRUE;
            }
            else{
                $this->set_time_point();
                return FALSE;
            }
        }
        
        return TRUE;
    }
    
}
