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

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

    /**
     * get
     *
     * @access public
     * @return string
     */
    function get()
    {
        if ($this->isEmpty()) {
            return "";
        } else {
            return implode("\n", $this->content);
        }
    }
    
    /**
     * set
     *
     * @access public
     * @param string $input
     * @return boolean
     */
    function set($input)
    {
        assert('is_string($input);');
        settype($input, "string");
        $this->content = explode("\n", preg_replace("/[;,\s]+/s", "\n", $input));
        assert('is_array($this->content);');
        for ($i=0;$i<count($this->content);$i++)
        {
            $this->content[$i] .= "\n";
        }
        return true;
    }
    
    /**
     * read
     *
     * @access public
     * @return boolean
     */
    function read()
    {
        if (!$this->exists()) {
            return false;
        } else {
            $this->source  = file($this->getFilename());
            $this->content = explode("\n", preg_replace("/[;,\s]+/", "\n", implode("",$this->source)));
            $this->options = $this->attributes;
            return true;
        }
    }
    
    /**
     * isBlocked
     *
     * @access public
     * @return boolean
     */
    function isBlocked()
    {
        assert('is_array($this->content);');
        settype($this->content,"array");
        $this->read();
        if (empty($this->attributes['REMOTE_ADDR'])) {
            return false;
        } else {
            settype($this->content, "array");
        }
        
        foreach ($this->content as $key => $value)
        {
            settype($value, "String");
            if (preg_match("/(\*|\d{1,3})\.(\*|\d{1,3})\.(\*|\d{1,3})\.(\*|\d{1,3})/",$value)) {
                $a = str_replace('.', '\.', $value);
                $a = str_replace('*', '\d{1,3}', $a);
                if (preg_match("/".$a."/", $this->attributes['REMOTE_ADDR'])) {
                    return true;
                }
            }
        }
        
        return false;
    }
    
    /**
     * toString
     *
     * @access public
     * @return string
     */
    function toString()
    {
        if (!$this->exists()) {
            return "Blocklist-file ".$this->getFilename()." does not exist";
        } elseif ($this->isEmpty()) {
            return "Blocklist-file ".$this->getFilename()." is wether empty or not loaded";
        } else {
            return $this->get();
        }
    }

}

?>