<?php
function strhex($var)
	{
            $tab = unpack('H*',$var);
            return $tab[1];
	}

function hexstr($var)
	{
            return pack('H*',$var);
	}

/*function bitstr($var)
    {
        $r = NULL;
        for($i = 0; $i < strlen($var); $i += 8) $r .= chr(bindec(substr($var,$i,8)));
        return $r;
    }

function bithex($var)
    {
        $r = NULL;
        for($i = 0; $i < strlen($var); $i += 4) $r .= base_convert(substr($var,$i,4),2,16);
        return $r;
    }


function hex2bin($str)
    {
        $bin = "";
        $i = 0;
        do
    	    {
	        $bin .= chr(hexdec($str{$i}.$str{($i + 1)}));
		$i += 2;
            }
        while ($i < strlen($str));
        return $bin;
    }
*/
function cxor($msg,$cle)
	{	
            $xor = NULL;
            for($i = 0; $i < strlen($msg);$i++) $xor .= substr($msg,$i,1) ^ substr($cle,$i % strlen($cle),1);
            return $xor;
	}

function random($l=128)
	{
            $r = NULL;
            for($i = 1;$i <= $l/128 && $l/128 <= 32; $i++)
                    {
                            $var = time().microtime().mt_rand().md5(time()).md5(microtime()).md5(mt_rand()).sha1(time()).sha1(microtime()).sha1(mt_rand());
                            $r .= md5(cxor(md5($var,TRUE),sha1($var,TRUE)));
                    }
            return $r;
	}

function uniquehash($var,$length=128,$raw=FALSE)
    {
        $hashs = array('tiger192,4','haval256,5','md5','snefru','gost','ripemd160','whirlpool');
        $r = hash('sha512',$var,TRUE);
        
        foreach($hashs as $algo) $r = cxor(strrev($r),hash($algo,strrev($r),TRUE));
        
        if($length % 8 == 0 && $length >=128 && $length <= 512) $r = substr($r,0,$length/8);
        if(!$raw) $r = strhex($r);
        
        return $r;
    }

function temphash($var,$length=128,$raw=FALSE)
    {
        if(!$val = Cache::read('_temphash')) Cache::set('_temphash',$val = hexstr(random()));
        
        return uniquehash(cxor($var,$val),$length,$raw);
    }

function decode_ip($int_ip)
    {
	return inet_ntop(hex2bin($int_ip));
    }

function encode_ip($ip=FALSE)
    {
        if(!$ip)
            $ip = $_SERVER['REMOTE_ADDR'];

	return bin2hex(inet_pton($ip));            
    }

function url($string,$external=FALSE)
	{
            if($external) return htmlspecialchars($string);
            
            global $VAR;
        
            if(!empty($VAR['rewrite_url']))
                    {
                            $masque = $VAR['rewrite_url']['masque'];
                            $replace = $VAR['rewrite_url']['replace'];
                            $var = preg_replace($masque,$replace,$string);
                            return htmlspecialchars($var);
                    }
            else return htmlspecialchars($string);
	}
?>