<?php
/**
 * YANA library
 *
 * @package yana
 * @licence http://creativecommons.org/licenses/by-nc-sa/2.5/
 *
 * @ignore
 */

/**
 * FloodFile
 *
 * @access      public
 * @package     yana
 * @subpackage  io
 *
 * @ignore
 */
class FloodFile extends SecureFileStream
{

    /**
     * @ignore
     * @access private
     * @var    int */ 
    var $max = 0;

    /**
     * set
     * 
     * @access public
     * @return boolean
     */
    function set()
    {
        if (!$this->exists()) {
            $this->create();
        }
        if (!$this->isEmpty() && $this->attributes['REMOTE_ADDR'] != preg_replace("/\s/", "", $this->content[0]) || ($this->content[1] +20000) < time()) {
            $this->content[0] = $this->attributes['REMOTE_ADDR'] ."\n";
            $this->content[1] = time() ."\n";
            $this->content[2] = 1;
        } else {
            $this->content[1] = time() ."\n";
            $this->content[2] += 1;
        }
        $test = $this->write();
        assert('is_bool($test);');
        return $test;
    }

    /**
     * insert
     *
     * @access public
     */
    function insert()
    {
        $this->set();
    }

    /**
     * isBlocked
     *
     * @access public
     * @return boolean
     */
    function isBlocked() 
    {
        $this->read();
        if (!$this->isEmpty() && $this->length()>2) {
            return ($this->content[2] >= $this->max && $this->max > 0);
        } else {
            return false;
        }
    }

    /**
     * setMax
     *
     * @access public
     * @param int $max positive number
     * @return boolean
     */
    function setMax($max)
    {
        if (gettype($max) == "integer" && $max >= 0) {
            $this->max = $max;
            return true;
        } else {
            trigger_error("Expected maximum number to be a positive integer, found '".gettype($max)."(${max})"."' instead.", E_USER_NOTICE);
            return false;
        }
    }

    /**
     * isBlocked
     *
     * @access public
     * @return int
     */
    function getMax()
    {
        assert('is_int($this->max);');
        return $this->max;
    }

}

?>