<?php
/*
 * Script Fruit-Farm SM
 * Author: Smarty Scripts
 * Author Site: www.smartyscripts.com
 * Official Site: https://github.com/rubensrocha/fruit-farm
 */
class Base32Exception extends \Exception {}
class CashAddressException extends \Exception {}
class InvalidChecksumException extends Base32Exception {}

class CashAddress
{
    /**
     * @var array
     */
    protected static $hashBits = [
        160 => 0,
        192 => 1,
        224 => 2,
        256 => 3,
        320 => 4,
        384 => 5,
        448 => 6,
        512 => 7,
    ];

    /**
     * @var array
     */
    protected static $versionBits = [
        "pubkeyhash" => 0,
        "scripthash" => 1,
    ];

    /**
     * @param $string - cashaddr string
     * @return string[] - prefix, scriptType, hash
     * @throws Base32Exception
     * @throws CashAddressException
     */
    public static function decode($string)
    {
        try {
            /**
             * @var string $prefix
             * @var int[] $words
             */
            list ($prefix, $words) = Base32::decode($string);
        } catch (InvalidChecksumException $e) {
            throw new CashAddressException("Checksum failed to verify", 0, $e);
        } catch (Base32Exception $e) {
            throw new CashAddressException("Failed to decode address", 0, $e);
        }

        $numWords = count($words);
        $bytes = Base32::fromWords($numWords, $words);
        $numBytes = count($bytes);

        list ($scriptType, $hash) = self::extractPayload($numBytes, $bytes);

        return [$prefix, $scriptType, $hash];
    }



    /**
     * @param int $version
     * @return array
     * @throws CashAddressException
     */
    protected static function decodeVersion($version)
    {
        if (($version >> 7) & 1) {
            throw new CashAddressException("Invalid version - MSB is reserved");
        }

        $scriptMarkerBits = ($version >> 3) & 0x1f;
        $hashMarkerBits = ($version & 0x07);

        $hashBitsMap = array_flip(self::$hashBits);
        if (!array_key_exists($hashMarkerBits, $hashBitsMap)) {
            throw new CashAddressException("Invalid version or hash length");
        }
        $hashLength = $hashBitsMap[$hashMarkerBits];

        switch ($scriptMarkerBits) {
            case 0:
                $scriptType = "pubkeyhash";
                break;
            case 1:
                $scriptType = "scripthash";
                break;
            default:
                throw new CashAddressException('Invalid version or script type');
        }

        return [
            $scriptType, $hashLength
        ];
    }

    /**
     * @param int $numBytes
     * @param int[] $payloadBytes
     * @return string[] - script type and hash
     * @throws CashAddressException
     */
    protected static function extractPayload($numBytes, $payloadBytes)
    {
        if ($numBytes < 1) {
            throw new CashAddressException("Empty base32 string");
        }

        list ($scriptType, $hashLengthBits) = self::decodeVersion($payloadBytes[0]);

        if (($hashLengthBits / 8) !== $numBytes - 1) {
            throw new CashAddressException("Hash length does not match version");
        }

        $hash = "";

        foreach (array_slice($payloadBytes, 1) as $byte) {
            $hash .= pack("C*", $byte);
        }

        return [$scriptType, $hash];
    }
}

class Base32
{
    /**
     * @var string
     */
    const SEPARATOR = ':';

    /**
     * @var string
     */
    protected static $maskHex = '07ffffffff';

    /**
     * @var int
     */
    protected static $checksumLen = 8;

    /**
     * @var string
     */
    protected static $charset = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';

    /**
     * @var array
     */
    protected static $charsetKey = [
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        15, -1, 10, 17, 21, 20, 26, 30, 7, 5, -1, -1, -1, -1, -1, -1,
        -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1,
        1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1,
        -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1,
        1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1
    ];

    /**
     * @var array
     */
    protected static $generator = [0x98f2bc8e61, 0x79b76d99e2, 0xf33e5fb3c4, 0xae2eabe2a8, 0x1e4f43e470];

    /**
     * {@inheritDoc}
     * @see GmpMathInterface::bitwiseAnd()
     */
    protected static function bitwiseAnd($first, $other)
    {
        return gmp_and($first, $other);
    }

    /**
     * {@inheritDoc}
     * @see GmpMathInterface::rightShift()
     */
    protected static function rightShift($number, $positions)
    {
        // Shift 1 right = div / 2
        return gmp_div($number, gmp_pow(gmp_init(2, 10), $positions));
    }

    /**
     * {@inheritDoc}
     * @see GmpMathInterface::bitwiseXor()
     */
    protected static function bitwiseXor($first, $other)
    {
        return gmp_xor($first, $other);
    }

    /**
     * {@inheritDoc}
     * @see GmpMathInterface::leftShift()
     */
    protected static function leftShift($number, $positions)
    {
        // Shift 1 left = mul by 2
        return gmp_mul($number, gmp_pow(2, $positions));
    }

    /**
     * @param \GMP $prev
     * @return resource
     */
    protected static function polyModStep($prev)
    {
        $mask = gmp_init(self::$maskHex, 16);
        $one = gmp_init(1);

        $b = self::rightShift($prev, 35);
        $v = self::leftShift(self::bitwiseAnd($prev, $mask), 5);

        for ($j = 0; $j < 5; $j++) {
            $value = 0;
            if (gmp_cmp(self::bitwiseAnd(self::rightShift($b, $j), $one), 0) > 0) {
                $value = self::$generator[$j];
            }

            $v = self::bitwiseXor($v, gmp_init((string)$value, 10));
        }

        return $v;
    }

    /**
     * @param string $prefix
     * @return resource
     */
    protected static function prefixChk($prefix)
    {
        $chk = gmp_init(1);
        $length = strlen($prefix);
        for ($i = 0; $i < $length; $i++) {
            $char = ord($prefix[$i]) & 0x1f;
            $chk = self::bitwiseXor(self::polyModStep($chk), gmp_init($char, 10));
        }

        $chk = self::polyModStep($chk);

        return $chk;
    }

    /**
     * @param string $prefix - string prefix
     * @param array $words - 5bit words (array)
     * @return string
     * @throws Base32Exception
     */
    public static function encode($prefix, array $words)
    {
        if ((strlen($prefix) + 7 + count($words)) > 90) {
            throw new Base32Exception();
        }

        $prefix = strtolower($prefix);

        $chk = self::prefixChk($prefix);
        $result = $prefix . self::SEPARATOR;

        for ($i = 0, $wordLength = count($words); $i < $wordLength; ++$i) {
            $x = $words[$i];
            if ($x >> 5 !== 0) {
                throw new \RuntimeException("Non 5-bit word");
            }
            $chk = self::bitwiseXor(self::polyModStep($chk), gmp_init($x));
            $result .= self::$charset[$x];
        }

        for ($i = 0; $i < self::$checksumLen; ++$i) {
            $chk = self::polyModStep($chk);
        }
        $chk = self::bitwiseXor($chk, gmp_init(1));

        for ($i = 0; $i < self::$checksumLen; ++$i) {
            $pos = 5 * (self::$checksumLen - 1 - $i);
            $v2 = self::bitwiseAnd(self::rightShift($chk, $pos), gmp_init('1f', 16));
            $result .= self::$charset[(int) gmp_strval($v2, 10)];
        }

        return $result;
    }

    /**
     * @param string $string - base32 string
     * @return array<string, array<int>> - array<prefix, array<5 bit int>>
     * @throws Base32Exception
     * @throws InvalidChecksumException
     */
    public static function decode($string)
    {
        $stringLen = strlen($string);
        if ($stringLen < 8) {
            throw new Base32Exception("Address too short");
        }

        if ($stringLen > 90) {
            throw new Base32Exception("Address too long");
        }

        $chars = array_values(unpack("C*", $string));

        $haveUpper = $haveLower = false;
        $idxSeparator = -1;
        $separatorChar = ord(self::SEPARATOR);

        for ($i = 0; $i < $stringLen; $i++) {
            $x = $chars[$i];
            if ($x < 33 || $x > 126) {
                throw new Base32Exception("Out of range character in base32 string");
            }

            if ($x >= 0x61 && $x <= 0x7a) {
                $haveLower = true;
            }

            if ($x >= 0x41 && $x <= 0x5a) {
                $haveUpper = true;
                $x = $chars[$i] = $x + 0x20;
            }

            if ($x === $separatorChar) {
                $idxSeparator = $i;
            }
        }

        if ($haveUpper && $haveLower) {
            throw new Base32Exception("Data contains mixture of higher/lower case characters");
        }

        if ($idxSeparator === -1) {
            throw new Base32Exception("Missing separator character");
        } else if ($idxSeparator === 0) {
            throw new Base32Exception("Missing prefix");
        } else if (($idxSeparator + 7) > $stringLen) {
            throw new Base32Exception("Invalid location for separator character");
        }

        $prefix = "";

        foreach (array_slice($chars, 0, $idxSeparator) as $byte) {
            $prefix .= pack("C*", $byte);
        }


        $chk = self::prefixChk($prefix);

        $words = [];
        for ($i = $idxSeparator + 1; $i < $stringLen; $i++) {
            $char = $chars[$i];
            if (!array_key_exists($char, self::$charsetKey)) {
                throw new Base32Exception("Unknown character in address");
            }
            $word = self::$charsetKey[$char];
            $chk = self::bitwiseXor(self::polyModStep($chk), gmp_init($word));
            $words[] = $word;
        }

        if (gmp_cmp($chk, gmp_init(1)) !== 0) {
            throw new InvalidChecksumException();
        }

        return [
            $prefix,
            array_slice($words, 0, -self::$checksumLen)
        ];
    }

    /**
     * Convert $bytes, an array of 8 bit numbers, to
     * words, an array of 5 bit numbers.
     *
     * @param int $numBytes
     * @param int[] $bytes
     * @return int[]
     * @throws Base32Exception
     */
    public static function toWords($numBytes, array $bytes)
    {
        return self::convertBits($bytes, $numBytes, 8, 5, true);
    }

    /**
     * Convert $words, an array of 5 bit numbres, to
     * bytes, an arrayof 8 bit numbers.
     *
     * @param int $numWords
     * @param int[] $words
     * @return int[]
     * @throws Base32Exception
     */
    public static function fromWords($numWords, array $words)
    {
        return self::convertBits($words, $numWords, 5, 8, false);
    }

    /**
     * Converts words of $fromBits bits to $toBits bits in size.
     *
     * @param int[] $data - character array of data to convert
     * @param int $inLen - number of elements in array
     * @param int $fromBits - word (bit count) size of provided data
     * @param int $toBits - requested word size (bit count)
     * @param bool $pad - whether to pad (only when encoding)
     * @return int[]
     * @throws Base32Exception
     */
    protected static function convertBits(array $data, $inLen, $fromBits, $toBits, $pad = true)
    {
        $acc = 0;
        $bits = 0;
        $ret = [];
        $maxv = (1 << $toBits) - 1;
        $maxacc = (1 << ($fromBits + $toBits - 1)) - 1;

        for ($i = 0; $i < $inLen; $i++) {
            $value = $data[$i];
            if ($value < 0 || $value >> $fromBits) {
                throw new Base32Exception('Invalid value for convert bits');
            }

            $acc = (($acc << $fromBits) | $value) & $maxacc;
            $bits += $fromBits;

            while ($bits >= $toBits) {
                $bits -= $toBits;
                $ret[] = (($acc >> $bits) & $maxv);

            }
        }

        if ($pad) {
            if ($bits) {
                $ret[] = ($acc << $toBits - $bits) & $maxv;
            }
        } else if ($bits >= $fromBits || ((($acc << ($toBits - $bits))) & $maxv)) {
            throw new Base32Exception('Invalid data');
        }

        return $ret;
    }
}

function valid($addr) {
    if (strpos($addr, ":") === false) {
        $addr = "bitcoincash:" . $addr;
    }

    try {
        CashAddress::decode($addr);
    } catch (Base32Exception $e) {
        return false;
    } catch (CashAddressException $e) {
        return false;
    }

    return true;
}
class Func
{
    public $UserIP = "Undefined"; // IP пользователя
    public $UserCode = "Undefined"; // Код от IP
    public $TableID = -1; // ID таблицы
    public $UserAgent = "Undefined"; // Браузер пользователя

    /*======================================================================*\
    Function:    __construct
    Output:        Нет
    Descriiption: Выполняется при создании экземпляра класса
    \*======================================================================*/
    public function __construct()
    {
        $this->UserIP = $this->GetUserIp();
        $this->UserCode = $this->IpCode();
        $this->UserAgent = $this->UserAgent();
    }

    /*======================================================================*\
    Function:    __destruct
    Output:        Нет
    Descriiption: Уничтожение объекта
    \*======================================================================*/
    public function __destruct()
    {
    }


    /*======================================================================*\
    Function:    IsMail
    Output:        True / False
    Input:        Email
    Descriiption: Проверяет правильность ввода email адреса
    \*======================================================================*//*
    public function IsMail($mail){
    if(is_array($mail) && empty($mail) && strlen($mail) > 255 && strpos($mail,'@') > 64) return false;
    return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $mail)) ? false : strtolower($mail);
    }*/

    /*======================================================================*\
    Function:    IsPassword
    Output:        True / False
    Input:        Строка пароля, Маска, Длина ("10, 25") && ("10")
    Descriiption: Проверяет правильность ввода пароля
    \*======================================================================*//*
    public function IsPassword($password, $mask = "^[a-zA-Z0-9]", $len = "{4,20}"){
    return (is_array($password)) ? false : (ereg("{$mask}{$len}$", $password)) ? $password : false;

    }*/

    /*======================================================================*\
    Function:    IsLogin
    Output:        True / False
    Input:        Строка логина, Маска, Длина ("10, 25") && ("10")
    Descriiption: Проверяет правильность ввода логина
    \*======================================================================*//*
    public function IsLogin($login, $mask = "^[a-zA-Z0-9]", $len = "{4,10}"){
    return (is_array($login)) ? false : (ereg("{$mask}{$len}$", $login)) ? $login : false;
    }*/

    /*======================================================================*\
    Function:    GetUserIp
    Output:        UserIp
    Descriiption: Определяет IP пользователя
    \*======================================================================*/
    public function GetUserIp()
    {
        if ($this->UserIP == "Undefined") {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $client_ip = (!empty($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : ((!empty($_ENV['REMOTE_ADDR'])) ? $_ENV['REMOTE_ADDR'] : "unknown");
                $entries = preg_split('[, ]', $_SERVER['HTTP_X_FORWARDED_FOR']);
                reset($entries);
                while (list(, $entry) = each($entries)) {
                    $entry = trim($entry);
                    if (preg_match("/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/", $entry, $ip_list)) {
                        $private_ip = array(
                        '/^0\./',
                        '/^127\.0\.0\.1/',
                        '/^192\.168\..*/',
                        '/^172\.((1[6-9])|(2[0-9])|(3[0-1]))\..*/',
                        '/^10\..*/');
                        $found_ip = preg_replace($private_ip, $client_ip, $ip_list[1]);
                        if ($client_ip != $found_ip) {
                            $client_ip = $found_ip;
                            break;
                        }
                    }
                }
                $this->UserIP = $client_ip;
                return $client_ip;
            } else {
                return (!empty($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : ((!empty($_ENV['REMOTE_ADDR'])) ? $_ENV['REMOTE_ADDR'] : "unknown");
            }
        } else {
            return $this->UserIP;
        }
    }

    /*======================================================================*\
    Function:    SellItems
    Descriiption: Выводит сумму и остаток
    \*======================================================================*/
    public function SellItems($all_items, $for_one_coin)
    {
        if ($all_items <= 0 or $for_one_coin <= 0) {
            return 0;
        }
        return sprintf("%.2f", ($all_items / $for_one_coin));
    }

    /*======================================================================*\
    Function:    IpToLong
    Descriiption: Преобразует IP в целочисленное
    \*======================================================================*/
    public function IpToInt($ip)
    {
        $ip = ip2long($ip);
        ($ip < 0) ? $ip+=4294967296 : true;
        return $ip;
    }

    /*======================================================================*\
    Function:    IpToLong
    Descriiption: Преобразует целочисленное в IP
    \*======================================================================*/
    public function IntToIP($int)
    {
        return long2ip($int);
    }

    /*======================================================================*\
    Function:    IsWM
    Output:        True / False
    Input:        Реквизит, TYPE: 0 - WMID, 1 - WMR, 2 - WMZ, 3 - WME, 4 - WMU
    Descriiption: Проверяет правильность ввода пароля
    \*======================================================================*/
    public function IsWM($data, $type = 0)
    {
        $FirstChar = array( 1 => "R",
          2 => "Z",
          3 => "E",
          4 => "U");

        if (strlen($data) < 12 && strlen($data) > 12 && $type < 0 && $type > count($FirstChar)) {
            return false;
        }
        if ($type == 0) {
            return (is_array($data)) ? false : (ereg("^[0-9]{12}$", $data) ? $data : false);
        }
        if (substr(strtoupper($data), 0, 1) != $FirstChar[$type] or !ereg("^[0-9]{12}", substr($data, 1))) {
            return false;
        }
        return $data;
    }

    /*======================================================================*\
    Function:    IpCode
    Output:        String, Example 255025502550255
    Input:        -
    Descriiption: Возвращает IP с замененными знаками "." на "0"
    \*======================================================================*/
    public function IpCode()
    {
        $arr_mask = explode(".", $this->GetUserIp());
        return $arr_mask[0].".".$arr_mask[1].".".$arr_mask[2].".0";
    }

    /*======================================================================*\
    Function:    GetTime
    Descriiption: Возвращаер дату
    \*======================================================================*/
    public function GetTime($tis = 0, $unix = true, $template = "d.m.Y H:i:s")
    {
        if ($tis == 0) {
            return ($unix) ? time() : date($template, time());
        } else {
            return date($template, $unix);
        }
    }

    /*======================================================================*\
    Function:    UserAgent
    Descriiption: Возвращает браузер пользователя
    \*======================================================================*/
    public function UserAgent()
    {
        return $this->TextClean($_SERVER['HTTP_USER_AGENT']);
    }

    /*======================================================================*\
    Function:    TextClean
    Descriiption: Очистка текста
    \*======================================================================*/
    public function TextClean($text)
    {
        $array_find = array("`", "<", ">", "^", '"', "~", "\\");
        $array_replace = array("&#96;", "&lt;", "&gt;", "&circ;", "&quot;", "&tilde;", "");
        return str_replace($array_find, $array_replace, $text);
    }

    /*======================================================================*\
    Function:    ShowError
    Descriiption: Выводит список ошибок строкой
    \*======================================================================*/
    public function ShowError($errorArray = array(), $title = "Correct the following errors")
    {
        if (count($errorArray) > 0) {
            $string_a = "<div class='Error'><div class='ErrorTitle'>".$title."</div><ul>";
            foreach ($errorArray as $number => $value) {
                $string_a .= "<li>".($number+1)." - ".$value."</li>";
            }
            $string_a .= "</ul></div><BR />";
            return $string_a;
        } else {
            return "Unknown error :(";
        }
    }

    /*======================================================================*\
    Function:    ComissionWm
    Descriiption: Возвращает комиссию WM
    \*======================================================================*/
    public function ComissionWm($sum, $com_payee, $com_payysys)
    {
        $a = ceil(ceil($sum * $com_payee * 100) / 10000*100) / 100;
        $b = ceil(ceil($sum * str_replace("%", "", $com_payysys) * 100) / 10000*100) / 100;
        return $a+$b;
    }

    /*======================================================================*\
    Function:    md5Password
    Descriiption: Возвращает md5_пароля
    \*======================================================================*/
    public function md5Password($pass)
    {
        $pass = strtolower($pass);
        return md5("shark_md5"."-".$pass);
    }

    public function randomPassword()
    {
        $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
        $pass = array(); //remember to declare $pass as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 8; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        return implode($pass); //turn the array into a string
    }

    /*======================================================================*\
    Function:    ControlCode
    Descriiption: Возвращает контрольное число
    \*======================================================================*/
    public function ControlCode($time = 0)
    {
        return ($time > 0) ? date("Ymd", $time) : date("Ymd");
    }

    /*======================================================================*\
    Function:    SumCalc
    Descriiption: Возвращает сумму овощей
    \*======================================================================*/
    public function SumCalc($per_h, $sum_tree, $last_sbor)
    {
        if ($last_sbor > 0) {
            if ($sum_tree > 0 and $per_h > 0) {
                $last_sbor = ($last_sbor < time()) ? (time() - $last_sbor) : 0;
                $per_sec = $per_h / 3600;
                return round(($per_sec * $sum_tree) * $last_sbor);
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    /*
    * Generate CSRF input
    */
    public function csrf()
    {
        if (@!$_SESSION) {
            session_start();
        }
        $_SESSION['csrf'] = crc32(time()) . md5(time()) . strtoupper(sha1(time())) . strtoupper(md5(time())) . sha1(time());
        echo('<input type="hidden" name="@secury" value="'.$_SESSION['csrf'].'">');
    }

    /*
     * Verify CSRF input
     */
    public function csrfVerify()
    {
        if (@!$_SESSION) {
            session_start();
        }
        $value = filter_input(INPUT_POST, '@secury', FILTER_SANITIZE_STRING);
        if ($value == @$_SESSION['csrf']) {
            unset($_SESSION['csrf']);
            return 'true';
        } else {
            unset($_SESSION['csrf']);
            return 'false';
        }
    }

    public function activeMenu($page, $subpage=null, $class='active')
    {
        if ($page) {
            $url = $_GET['menu'];
            if ($_GET['sel']) {
                $sub = $_GET['sel'];
            } else {
                $sub = null;
            }
            if ($subpage) {
                if ($url == $page && $sub == $subpage) {
                    echo 'class="'.$class.'"';
                }
            } else {
                if ($url == $page && $sub == null) {
                    echo 'class="'.$class.'"';
                }
            }
        }
    }

    public function url($target=null)
    {
        if ($_SERVER['HTTPS'] == "on") {
            $protocol = 'https://';
        } else {
            $protocol = 'http://';
        }
        $base = $protocol.$_SERVER['HTTP_HOST'];
        if ($target) {
            echo $base.'/'.$target;
        } else {
            echo $base;
        }
    }

    public function urlAdmin($target=null)
    {
        if ($_SERVER['HTTPS'] == "on") {
            $protocol = 'https://';
        } else {
            $protocol = 'http://';
        }
        $base = $protocol.$_SERVER['HTTP_HOST'].'/admin';
        if ($target) {
            echo $base.'/'.$target;
        } else {
            echo $base;
        }
    }

    public function priceFormat($value)
    {
        $config = new Config;
        $code = $config->currency['symbol'];
        $place = $config->currency['symbol_position'];
        $decimals = $config->currency['decimals'];
        $dec_point = $config->currency['dec_point'];
        $thousand_point = $config->currency['thousand_point'];
        if ($place=='left') {
            return $code.' '.number_format($value, $decimals, $dec_point, $thousand_point);
        } else {
            return number_format($value, $decimals, $dec_point, $thousand_point).' '.$code;
        }
    }

    public function price($value)
    {
        $config = new Config;
        $decimals = $config->currency['decimals'];
        $dec_point = $config->currency['dec_point'];
        $thousand_point = $config->currency['thousand_point'];

        return number_format($value, $decimals, $dec_point, $thousand_point);
    }

    public function validatePurse($purse)
    {
        if (valid($purse)==false) {
            return false;
        }
        
        return $purse;
    }

    public function setTimer()
    {
        list($seconds, $microSeconds) = explode(' ', microtime());
        return $seconds + (float) $microSeconds;
    }

    public function setReferer()
    {
        if (isset($_GET["i"])) {
            $_rid = (intval($_GET["i"]) > 0) ? intval($_GET["i"]) : 1;
            setcookie("i", $_rid, time()+2592000);
            header("Location: /");
        }
    }
}
