<?php 
/**
* 
*/
class Security
{
    public function csrf_verify()    
    {
        if(count($_POST) == 0)
        {
            return '';
        }
        if(!isset($_POST[$tokenname])
            OR !isset($_COOKIE[$tokenname]))
        {
            return '';
        }
        unset($_POST[$tokenname]);
        unset($_COOKIE[$tokenname]);
    }

    public function csrf_set_cookie()
    {
        $expire = time()+$this->expire;
        $secure_cookie = 1;
        if($secure_cookie)
        {
            $req = isset($_SERVER['HTTPS'])?$_SERVER['HTTPS']:FALSE;
        }
        setcookie($cookiename, $hash, $expire, $cookiepath, $cookedomain, $secure_cookie);
        return $this;
    }

    public function xss_clean($str, $is_image = FALSE)
    {
        if(is_array($str))
        {
            while (list($key) = each($str))
            {
                $str[$key] = '';
            }
            return $str;
        }

        $str = rawurldecode($str);
        $str = preg_replace_callback('/[a-z]+=([\'\"]).*?\\1/si', array($this, '_conver_attribute', $str);
        $str = preg_replace('/<\w+.*?(?=>|<|$)/si', array($this, '_decode_entity', $str);    

        if(strpos($str, "\t") !== FALSE)
        {
            $str = str_replace("\t", ' ', $str);
        }

        if($is_image === TRUE)
        {
            $str = preg_replace('/<\?(php)/i', '&lt;?\\1', $str);
        }

        do
        {
            $original = $str;
            if(preg_match("/<a/i", $str))
            {
                $str = preg_replace_callback("##si", array($this, '_js_link_removal'), $str);
            }
        }
        while ($original != $str);
        unset($original);
    }

    public function xss_hash()
    {
        mt_srand();
        $xss_hash = md5(time() + mt_rand(0, 199999999999999));
        return $xss_hash;
    }

    public function entity_decode($str, $charset='UTF-8')
    {
        if (stristr($str, '&') === FALSE) {
            return $str;
        }

        $str = html_entity_decode($str, ENT_COMPAT, $charset);
        $str = preg_replace('~&#X(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
        return stripslashes(preg_replace('~&#([0-9]{2-4})~e', 'chr(\\1)', $str));
    }
}