<?php
/**
 * FormKey class
 * 
 * The class is documented in the file itself. If you find any bugs help me out and report them. Reporting can be done by sending an email to imerovic[at]gmail[dot]com.
 * If you report a bug, make sure you give me enough information (include your code). 
 * 
 * @author		Ivan Imerovic <imerovic@gmail.com>
 * @version		1.0.0
 *
 * @copyright	Copyright (c) 2009, Ivan Imerovic. All rights reserved.
 * @license		BSD License
 */
class FormKey{
	
	// Private declarations
	/**
	 * The form key
	 *
	 * @var	string
	 */
	private $formKey;
	
	/**
	 * The old form key
	 *
	 * @var	string
	 */
	private $old_formKey;
	
	// Constructor
	/**
	 * Default constructor
	 *
	 * @return	void
	 */
	function __construct(){
		if(isset($_SESSION['form_key'])){
			$this->old_formKey = $_SESSION['form_key'];
		}
	}

	// Public functions
	/**
	 * Outputs hidden input field with generated form key
	 *
	 * @return	string
	 * 
	 */
	public function outputKey(){
		$this->formKey = $this->generateKey();
		$_SESSION['form_key'] = $this->formKey;
		
		echo "<input type='hidden' name='form_key' id='form_key' value='".$this->formKey."' />";
	}
	
	/**
	 * Validate form key
	 *
	 * @return	boolean
	 * 
	 */
	public function validate(){
		if($_POST['form_key'] == $this->old_formKey){
			return true;
		}
		else{
			return false;
		}
	}
	
	// Private functions
	/**
	 * Generate unique form key
	 *
	 * @return	string
	 * 
	 */
	private function generateKey(){
		$ip = $_SERVER['REMOTE_ADDR'];
		$uniqid = uniqid(mt_rand(), true);
		
		return md5($ip . $uniqid);
	}
}
?>