<?php
/*
*----------------------------phpMyBitTorrent V 2.0-----------------------------*
*--- The Ultimate BitTorrent Tracker and BMS (Bittorrent Management System) ---*
*--------------   Created By Antonio Anzivino (aka DJ Echelon)   --------------*
*-------------               http://www.p2pmania.it               -------------*
*------------ Based on the Bit Torrent Protocol made by Bram Cohen ------------*
*-------------              http://www.bittorrent.com             -------------*
*------------------------------------------------------------------------------*
*------------------------------------------------------------------------------*
*--   This program is free software; you can redistribute it and/or modify   --*
*--   it under the terms of the GNU General Public License as published by   --*
*--   the Free Software Foundation; either version 2 of the License, or      --*
*--   (at your option) any later version.                                    --*
*--                                                                          --*
*--   This program is distributed in the hope that it will be useful,        --*
*--   but WITHOUT ANY WARRANTY; without even the implied warranty of         --*
*--   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          --*
*--   GNU General Public License for more details.                           --*
*--                                                                          --*
*--   You should have received a copy of the GNU General Public License      --*
*--   along with this program; if not, write to the Free Software            --*
*-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA --*
*--                                                                          --*
*------------------------------------------------------------------------------*
*------              ©2005 phpMyBitTorrent Development Team              ------*
*-----------               http://phpmybittorrent.com               -----------*
*------------------------------------------------------------------------------*
*-----------------   Sunday, September 14, 2008 9:05 PM   ---------------------*
*/

// This file contains Bit Torrent main functions. MUST be included before every
// other file at the beginning of any script
if (eregi("functions.php",$_SERVER['PHP_SELF'])) die("You can't access this file directly");
if (!function_exists("sha1")) require_once("include/sha1lib.php");
if (!eregi("download.php",$_SERVER['PHP_SELF']))include ("./include/forum_settings.php");
if (!eregi("download.php",$_SERVER['PHP_SELF']))include ("./include/functions_phpBB3.php"); 

/*---------------------------------
ERROR HANDLING FUNCTIONS
----------------------------------*/
function sqlerr(){
return  btsqlerror();
}
function get_user_timezone($id) {
        global $db, $db_prefix, $user;
  if ($user->user){
	   $sql = "SELECT * FROM ".$db_prefix."_users WHERE id=$id LIMIT 1";
       $query = mysql_query($sql);
       if (mysql_num_rows($query) != "0") {
			$kasutaja = mysql_fetch_array($query);
			$timezone = $kasutaja["tzoffset"]+77;
			return "$timezone";
		} else {
         return "377";
		} //Default timezone
	}
}


function mkglobal($vars) {
    if (!is_array($vars))
        $vars = explode(":", $vars);
    foreach ($vars as $v) {
        if (isset($_GET[$v]))
            $GLOBALS[$v] = unesc($_GET[$v]);
        elseif (isset($_POST[$v]))
            $GLOBALS[$v] = unesc($_POST[$v]);
        else
            return 0;
    }
    return 1;
}

function btsqlerror($sql) { //Returns SQL Error
        global $db, $db_prefix;
        $err = Array();
        $err = $db->sql_error();
        OpenErrTable("SQL Error");
        $msg = "<p>\n";
        $msg .= _btsqlerror1.htmlspecialchars($sql) ;
        $msg .=("<br />");
        $msg .= _btsqlerror2.$err["code"];
        $msg .=("<br />");
        $msg .= _btsqlerror3.htmlspecialchars($err["message"]);
        $msg .= "</p>";
		echo $msg;
        logerror($msg, "Data base sql error");
        CloseErrTable();
        CloseTable2();
        CloseTable();
        //logerror($err["message"],$sql);
        $db->sql_query("",END_TRANSACTION);
        @include("footer.php");
        die();
}
function get_elapsed_time($ts)
{
  $mins = floor((strtotime(gmdate("Y-m-d H:i:s", time())) - $ts) / 60);
  $hours = floor($mins / 60);
  $mins -= $hours * 60;
  $days = floor($hours / 24);
  $hours -= $days * 24;
  $weeks = floor($days / 7);
  $days -= $weeks * 7;
  $t = "";
  if ($weeks)
    return "$weeks week" . ($weeks > 1 ? "s" : "");
  if ($days)
    return "$days day" . ($days > 1 ? "s" : "");
  if ($hours)
    return "$hours hour" . ($hours > 1 ? "s" : "");
  if ($mins)
    return "$mins min" . ($mins > 1 ? "s" : "");
  return "< 1 min";
}
function bterror($error, $title = _btgenerror, $fatal = true) {
        global $db, $db_prefix;
        OpenErrTable($title);
        if (is_array($error)) {
                echo "<p>"._btalertmsg."</p>\n";
                echo "<ul>\n";
                foreach ($error as $msg) {
                        echo "<li><p>".$msg."</p></li>\n";
                }
                echo "</ul>\n";
        }else {
                 echo "<p class=\"errortext\">".$error."</p>";
        }
        CloseErrTable();
        if (is_array($error)) $error = implode("<br />",$error);
        //if (!eregi("admin.php",$_SERVER["PHP_SELF"])) logerror($error);
        if (!$fatal) return;
        CloseTable2();
        CloseTable();
        @include("footer.php");
        die();
}
function loginrequired($level, $guickclose = false) {
        global $user, $gfx_check;
	    $returnto = $_SERVER["REQUEST_URI"];
		$returnto = str_replace('sid', 'oldsd', $returnto);
		$returnto = str_replace('&', '@', $returnto);
        $loginbox = "<br><br><form method=\"POST\" action=\"user.php?returnto=".$returnto."\"><input type=\"hidden\" name=\"op\" value=\"login\" />\n
        <p align=\"center\">"._btusername."<br><input type=\"text\" name=\"username\" size=\"20\" />\n<br>"._btpassword."<br><input type=\"password\" name=\"password\" size=\"20\" />\n<br>Remember Me<br><input type=\"checkbox\" name=\"remember\" value=\"yes\" /></p>\n";
        if ($gfx_check) {
                $rnd_code = strtoupper(RandomAlpha(5));
                $loginbox .= "<p align=\"center\">"._btsecuritycode."<br><img src=\"gfxgen.php?code=".base64_encode($rnd_code)."\" alt=\"Security Code\"><br>\n<input type=\"text\" name=\"gfxcode\" size=\"10\" maxlength=\"6\">";
                $loginbox .= "<input type=\"hidden\" name=\"gfxcheck\" value=\"".md5($rnd_code)."\">\n\n";
        }
        $loginbox .= "<p><input type=\"submit\" value=\""._btlogin."\" /></p></form>";
        OpenErrTable('login');
        switch ($level) {
                case "user": {
                        echo "<p>"._btdenuser."</p>";
                        echo $loginbox;
                        break;
                }
                case "premium": {
                        echo "<p>"._btdenpremium."</p>";
                        if (!$user->user){
				echo "<p>"._btdenpremium."</p>";
				echo $loginbox;
                        }else echo "<p>"._btdenpremium2."</p>";
                        break;
                }
                case "admin": {
                        echo _btdenadmin;
                        if (!$user->user){ 
				echo "<p>"._btdenadmin."</p>";
				echo $loginbox;
                        }else echo _btdenadmin2;
                        break;
                }
                default: {
                        echo("Fatal Error!");
                        break;
                }
        }
        CloseErrTable();
        CloseTable2();
		if (defined('BT_SHARE')){
		echo "</div></td></tr></table>";
        }
        CloseTable();
		if ($guickclose)die();
		include("footer.php");
}
function autoclean() {
    global $db, $db_prefix, $autoclean_interval;

    $now = time();
    $docleanup = 0;

    $cln = "SELECT value_u FROM ".$db_prefix."_avps WHERE arg = 'lastcleantime'";
	$res = $db->sql_query($cln);
    $row = $db->sql_fetchrow($res);
    if (!$row) {
        $db->sql_query("INSERT INTO ".$db_prefix."_avps (arg, value_u) VALUES ('lastcleantime',$now)");
        return;
    }
    $ts = $row[0];
    if ($ts + $autoclean_interval > $now)
        return;
    $db->sql_query("UPDATE ".$db_prefix."_avps SET value_u=$now WHERE arg='lastcleantime' AND value_u = $ts");

    bonouse();
     


}

function bonouse(){
    global $db, $db_prefix;
                        $bon = "SELECT active, seeding, by_torrent FROM ".$db_prefix."_bonus_points ;";
                        $bonset = $db->sql_query($bon);
                        list ($active, $seeding_point, $by_torrent) = $db->sql_fetchrow($bonset);
                        $db->sql_freeresult($bonset);
						if($by_torrent == 1)$point_per = true;
						else
						$point_per = false;
if($active=='true')
{

//=== Update seeding bonus  
    /******************************************************
    Use ONLY one of the two options below... 
    the first is per torrents seeded, the second will only give the bonus for ONE torrent no matter how many are seeded.
    
    also you will have to play with how much bonus you want to give...
    ie: seedbonus+0.0225 = 0.25 bonus points per hour
        seedbonus+0.125 = 0.5 bonus points per hour
        seedbonus+0.225 = 1 bonus point per hour
    *****************************************************/
    //======use this part to give seeding bonus per torrent    
if($point_per)
{
   $res = $db->sql_query("SELECT DISTINCT uid FROM ".$db_prefix."_peers WHERE seeder = 'yes'");
   if ($db->sql_numrows($res) > 0)
   {
       while ($arr = $db->sql_fetchrow($res))
       {
       $work = $db->sql_query("select count(*) from torrent_peers WHERE seeder ='yes' AND uid = $arr[userid]");
       $row_count = mysql_result($work,0,"count(*)");
	   $seedbonus = $seeding_point*$row_count;
       $db->sql_query("UPDATE ".$db_prefix."_users SET seedbonus = seedbonus + '".$seedbonus."' WHERE id = $arr[userid] AND active = '1' AND warned = 'no'") or sqlerr(__FILE__, __LINE__);
       }
   }
}else{   //==use this part to only give seeding bonus for 1 torrent no matter how many are being seeded
   $res = $db->sql_query("SELECT DISTINCT uid FROM ".$db_prefix."_peers WHERE seeder = 'yes'");
   if ($db->sql_numrows($res) > 0)
   {
       while ($arr = $db->sql_fetchrow($res))
       {

	   //$bonus2 = 0.250;
	   //$useridb = $arr['userid'];
       $db->sql_query("UPDATE ".$db_prefix."_users SET seedbonus = seedbonus + '".$seeding_point."' WHERE id = $arr[uid] AND active = '1' AND warned = 'no'");
       }
   }
   }
}
}
function getip() {
   if (isset($_SERVER)) {
     if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && validip($_SERVER['HTTP_X_FORWARDED_FOR'])) {
       $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
     } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && validip($_SERVER['HTTP_CLIENT_IP'])) {
       $ip = $_SERVER['HTTP_CLIENT_IP'];
     } else {
       $ip = $_SERVER['REMOTE_ADDR'];
     }
   } else {
     if (getenv('HTTP_X_FORWARDED_FOR') && validip(getenv('HTTP_X_FORWARDED_FOR'))) {
       $ip = getenv('HTTP_X_FORWARDED_FOR');
     } elseif (getenv('HTTP_CLIENT_IP') && validip(getenv('HTTP_CLIENT_IP'))) {
       $ip = getenv('HTTP_CLIENT_IP');
     } else {
       $ip = getenv('REMOTE_ADDR');
     }
   }

   return $ip;
}
function logerror($message, $error = _btgenerror) {
        global $db, $db_prefix, $user;
                $ip = getip();
       $sql = "INSERT INTO ".$db_prefix."_log (action, results, ip, host, userid) VALUES ('".addslashes($error)."', '".addslashes($message)."', '".sprintf("%u",ip2long($ip))."',  '".gethostbyaddr($ip)."', '".$user->id."');";
        $db->sql_query($sql);
        return;
}
/*---------------------------------
SECURITY FUNCTIONS
---------------------------------*/
function cookie_decode($cookie) {
        global $use_rsa, $rsa;
        if ($use_rsa) $cookie = $rsa->decrypt($cookie);
        else $cookie = base64_decode($cookie);
        $cookie = stripslashes($cookie);
        $cookie = addslashes($cookie);
        $cookie = explode("::", $cookie);
        if (count($cookie) != 4) return Array("","","","");
        return $cookie;
}

function cookie_encode(&$cookie) {
        global $use_rsa, $rsa;
        $cookie = implode("::",$cookie);
        if ($use_rsa) $cookie = $rsa->encrypt($cookie);
        else $cookie = base64_encode($cookie);
        return $cookie;
}

function is_banned($user, &$reason) {
        //Both checking against username and IP
        global $db, $db_prefix, $_SERVER;
        if (!array_key_exists("HTTP_X_FORWARDED_FOR",$_SERVER)) {
                $ip = $_SERVER["REMOTE_ADDR"];
        } else {
                $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        }
        $ip = sprintf("%u",ip2long($_SERVER["REMOTE_ADDR"]));

        $sql = "SELECT banreason as reason FROM ".$db_prefix."_users WHERE id = '".$user->id."' AND ban = 1 UNION SELECT reason FROM ".$db_prefix."_bans WHERE ipstart <= '".$ip."' AND ipend >= '".$ip."'  LIMIT 1;";
        $res = $db->sql_query($sql) or btsqlerror($sql);
        if ($db->sql_numrows($res) < 1) {
                $reason = "";
                return false;
        } else {
                list ($reason) = $db->sql_fetchrow($res);
                return true;
        }
}

function is_user($user) {//Deprecated
        //trigger_error("Function is_user() is deprecated",E_USER_WARNING);
        global $user;
        return $user->user;
}

function is_btadmin($user) {//Deprecated
        //trigger_error("Function is_btadmin() is deprecated",E_USER_WARNING);
        global $user;
        return $user->admin;
}

function is_premium($user) {//Deprecated
        //trigger_error("Function is_premium() is deprecated",E_USER_WARNING);
        global $user;
        return $user->premium;
}

function is_moderator($user) {//Deprecated
        //trigger_error("Function is_moderator() is deprecated",E_USER_WARNING);
        global $user;
        return $user->moderator;
}

function can_download($user, &$torrent) {
        if ($user->premium) return true;
        global $user, $db, $db_prefix, $download_level, $torrent_global_privacy;
        if ($download_level == "all" OR $torrent["tracker"] != "") return true;
        if ($download_level == "premium" AND !$user->premium) return false;
        if ($download_level == "user" AND !$user->user) return false;
        if ($download_level == "user" AND !$torrent_global_privacy) return true;
        if ($download_level == "user" AND $torrent_global_privacy) {
                if ($torrent["ownertype"] == 2 OR $torrent["private"] != "true") return true;
                $ratioqry = "SELECT uploaded, downloaded FROM ".$db_prefix."_users WHERE id = '".$user->id."';";
                $ratiores = $db->sql_query($ratioqry);
                list ($uploaded, $downloaded) = $db->sql_fetchrow($ratiores);
                $db->sql_freeresult($ratiores);
                //if ($downloaded == 0) return true;
                if ($torrent["min_ratio"] > "0.00" AND ($downloaded > 0) AND $uploaded/$downloaded >= $torrent["min_ratio"]) return true;

                $sql = "SELECT status FROM ".$db_prefix."_privacy_global WHERE master = '".$torrent["owner"]."' AND slave = '".$user->id."';";
                $privacylist = $db->sql_query($sql) or btsqlerror($sql);
                if ($db->sql_numrows($privacylist) == 1) {
                        $privacy = $db->sql_fetchrow($privacylist);
                        if ($privacy["status"] == "whitelist") return true;
                        else return false;
                }
                $sql = "SELECT status FROM ".$db_prefix."_privacy_file WHERE slave = '".$user->id."' AND torrent = '".$torrent["id"]."';";
                $authqry = $db->sql_query($sql) or btsqlerror($sql);
                if ($db->sql_numrows($authqry) == 0) return false;
                $authrow = $db->sql_fetchrow($authqry);
                if ($authrow["status"] == "granted") return true;
                else return false;
        }
        return false;
}
function userlogin($username, &$cookiedata) {
include_once('include/forum_settings.php');
global $db, $db_prefix, $cookiedomain, $cookiepath, $logintime;
$res = $db->sql_query("SELECT * FROM ".$db_prefix."_users WHERE username ='".escape($username)."';");
if (!$res) return;
$row = $db->sql_fetchrow($res);
if (!$row) return;
$remember = $row['remember'];
$session_time = time() + (($logintime) ? 3200 * (int) $logintime : 31536000);
$cookiedata = Array($row["id"],addslashes($row["username"]),$row["password"],$row["act_key"]);
cookie_encode($cookiedata);
//$sql="UPDATE ".$db_prefix."_users SET lastlogin2 = NOW()-1400 WHERE username ='".escape($username)."';";
//$db->sql_query($sql);
if ($remember=="no"){
setcookie("btuser",$cookiedata,$session_time,$cookiepath,$cookiedomain,0);
if ($row["theme"] != "" AND is_dir("themes/".$row["theme"]) AND $row["theme"] != "CVS") setcookie("bttheme",$row["theme"],$session_time,$cookiepath,$cookiedomain,0);
else setcookie("bttheme","",$session_time,$cookiepath,$cookiedomain,0);
if ($row["language"] != "" AND is_readable("language/".$row["language"].".php")) setcookie("btlanguage",$row["language"],$session_time,$cookiepath,$cookiedomain,0);
else setcookie("btlanguage","",$session_time,$cookiepath,$cookiedomain,0);
return;
}else{
        setcookie("btuser",$cookiedata,time()+8640000,$cookiepath,$cookiedomain,0);
        if ($row["theme"] != "" AND is_dir("themes/".$row["theme"]) AND $row["theme"] != "CVS") setcookie("bttheme",$row["theme"],time()+8640000,$cookiepath,$cookiedomain,0);
        else setcookie("bttheme","",time()+8640000,$cookiepath,$cookiedomain,0);
        if ($row["language"] != "" AND is_readable("language/".$row["language"].".php")) setcookie("btlanguage",$row["language"],time()+8640000,$cookiepath,$cookiedomain,0);
        else setcookie("btlanguage","",time()+8640000,$cookiepath,$cookiedomain,0);
        return;
}
} 
function getuserid($user) { //Deprecated
        //trigger_error("Function getuserid() is deprecated",E_USER_WARNING);
        global $user;
        return $user->id;
}

function getusername($user) { //Gets the user name from cookie
        //trigger_error("Function getusername() is deprecated",E_USER_WARNING);
        global $user;
        return $user->name;
}
function is_url($url) {
        return preg_match('/^http[s]{0,1}:\/\/[\\w\\.]*\\.[\\w]{2,6}(\/[\\w]*){0,}/', $url);
}
function is_email($email) {
        return preg_match("/^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\\-+)|([A-Za-z0-9]+\\.+)|([A-Za-z0-9]+\\++))*[A-Za-z0-9_]+@((\\w+\\-+)|(\\w+\\.))*\\w{1,63}\\.[a-zA-Z]{2,6}$/",$email);
}
function is_filename($name) { //Is the file name valid?
        return preg_match('/^[^\\\\:\/<>|*"?]*$/si', $name);
}
function escape($x) { //Like mysql_escape_string()
        return addslashes($x);
}
function unescape($x) {
        return stripslashes($x);
}
function sqlwildcardesc($x) { //Replaces wildcards
        return str_replace(array("%","_"), array("\\%","\\_"), str_replace("'", "\'", $x));
}

function RandomNum($num) {
        $set = "0123456789";
        $resp = "";
        for ($i=1; $i<=$num; $i++) {
                $char = rand(0,strlen($set));
                $resp.=$set[$char];
        }
        return $resp;
}
function RandomAlpha($num) {
        $set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789";
        $resp = "";
        for ($i=1; $i<=$num; $i++) {
                $char = rand(0,strlen($set)-1);
                $resp.=$set[$char];
        }
        return $resp;
}
function spellmail($email) {
        $search = Array("@",".");
        $replace = Array(_at,_dot);
        return "<i>".str_replace($search,$replace,$email)."</i>";
}

function sql_timestamp_to_unix_timestamp($s)
{
  return mktime(substr($s, 11, 2), substr($s, 14, 2), substr($s, 17, 2), substr($s, 5, 2), substr($s, 8, 2), substr($s, 0, 4));
}
define('INT_SECOND', 1);
define('INT_MINUTE', 60);
define('INT_HOUR', 3600);
define('INT_DAY', 86400);
define('INT_WEEK', 604800);

function get_formatted_timediff($then, $now = false)
{
    $now      = (!$now) ? time() : $now;
    $timediff = ($now - $then);
    $weeks    = (int) intval($timediff / INT_WEEK);
    $timediff = (int) intval($timediff - (INT_WEEK * $weeks));
    $days     = (int) intval($timediff / INT_DAY);
    $timediff = (int) intval($timediff - (INT_DAY * $days));
    $hours    = (int) intval($timediff / INT_HOUR);
    $timediff = (int) intval($timediff - (INT_HOUR * $hours));
    $mins     = (int) intval($timediff / INT_MINUTE);
    $timediff = (int) intval($timediff - (INT_MINUTE * $mins));
    $sec      = (int) intval($timediff / INT_SECOND);
    $timediff = (int) intval($timediff - ($sec * INT_SECOND));

    $str = '';
    if ( $weeks )
    {
        $str .= intval($weeks);
        $str .= ($weeks > 1) ? 'weeks' : 'week';
    }

    if ( $days )
    {
        $str .= ($str) ? ',' : '';
        $str .= intval($days);
        $str .= ($days > 1) ? 'days' : 'day';
    }

    if ( $hours )
    {
        $str .= ($str) ? ',' : '';
        $str .= intval($hours);
        $str .= ($hours > 1) ? 'hours' : 'hour';
    }

    if ( $mins )
    {
        $str .= ($str) ? ',' : '';
        $str .= intval($mins);
        $str .= ($mins > 1) ? 'minutes' : 'minute';
    }

    if ( $sec )
    {
        $str .= ($str) ? ',' : '';
        $str .= intval($sec);
        $str .= ($sec > 1) ? 'seconds' : 'second';
    }
   
    if ( !$weeks && !$days && !$hours && !$mins && !$sec )
    {
        $str .= '0seconds ';
    }
    else
    {
        $str .= '';
    }
   
    return $str;
}

/*---------------------------------
TEXT & GRAPHICS FUNCTIONS
----------------------------------*/

/*
GETURL FUNCTION
RETURNS URL IN NORMAL STYLE

PARAMETERS:
 FILE = THE FILE TO LOAD IN MAIN DIRECTORY
 ARGS = [KEY]=>[VAL] ARRAY OF ADDITIONAL GET PARAMETERS

EXAMPLE:
GETURL("INDEX",ARRAY("OP"=>"LOAD","ACTION"=>"DOIT"));

RETURNS
INDEX.PHP?OP=LOAD&ACTION=DOIT
*/
function geturl($file, $args = Array()) {
        $s = $file.".php";
        if (count($args) > 0) $s .="?";
        $i = 0;
        foreach ($args as $key=>$val) {
                if ($i != 0) $s .= "&";
                $s .= $key."=".$val;
                $i++;
        }
        return htmlspecialchars($s); //Required by W3C specifications
}
function unesc($x) { //Useful for escaping strings
        if (get_magic_quotes_gpc())
                return stripslashes($x);
        return $x;
}
function mksize($s) { //Byte, Kilobyte, Megabyte, Gigabyte size
        $x = 4;
        $a = array("","K","M","G","T");
        for (;;) {
                $v = pow(1024, $x);
                if (!$x OR $s >= $v) {
                        $ss = sprintf("%.2f", ($s / $v));
                        $xx = $ss . " " . $a[$x] . "B";
                        break;
                }
                $x--;
        }
        return $xx;
}
function formatTimestamp($time) {//Formats date & time
    setlocale(LC_TIME, _LOCALE);
    ereg("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
    $datetime = strftime(_DATESTRING, mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
    $datetime = ucfirst($datetime);
    return($datetime);
}
function mkprettytime($s) {//Formats date&time?
        if ($s < 0)
                $s = 0;
        $t = array();
        foreach (array("60:sec","60:min","24:hour","0:day") as $x) {
                $y = explode(":", $x);
                if ($y[0] > 1) {
                        $v = $s % $y[0];
                        $s = floor($s / $y[0]);
                }
                else
                        $v = $s;
                $t[$y[1]] = $v;
        }

        if ($t["day"])
                return $t["day"]._btdays.", ".$t["hour"]._bthours. $t["min"]._btmins.$t["sec"]._btsecs;
        if ($t["hour"])
                return $t["hour"]._bthours. $t["min"]._btmins. $t["sec"]._btsecs;
        if ($t["min"])
                return $t["min"]._btmins. $t["sec"]._btsecs;
        return $t["sec"]. _btsecs;
}

function urlparse($m) { //Makes URLs clickable
        $t = $m[0];
        if (preg_match(',^\w+://,', $t))
                return "<a href=\"".$t."\">".$t."</a>";
        return "<a href=\"http://".$t."\">".$t."</a>";
}
function parsedescr($d) { //Parses Torrent description
        $pd = str_replace(array("\n", "\r"), array("<br />\n", ""), htmlspecialchars($d));
        $pd = preg_replace_callback('i?1(\w+://([^\s/:@]+(:[^\s/:@]++)?@)?|\bwww\.)[\w.-]+(:\d+)?(/[-\w=./?&%+#;|@]*)?[0-9a-z/]i?1is', "urlparse", $pd);
        return $pd;
}
function searchfield($s) {
        return preg_replace(array('/[^a-z0-9]/si', '/^\s*/s', '/\s*$/s', '/\s+/s'), array(" ", "", "", " "), $s);
}
function parse_html(&$text) {
        $allowed_tags = Array(
		"<br />",
        "<p>",
        "<i>",
        "<u>",
        "<br>",
        "<img>",
        "<a>",
        "<ul>",
        "<ol>",
        "<tr>",
        "<td>",
        "<thead>",
        "<tbody>",
        "<hr>",
        "<div>",
        "<span>",
        "<strong>",
        "<strike>",
        "<pre>",
        "<address>",
        "<font>",
        "<h1>",
        "<h2>",
        "<h3>",
        "<h4>",
        "<h5>",
        "<h6>",
        "<h7>"
        );
       // $text = strip_tags($text,implode(",",$allowed_tags));
}
function parse_smiles(&$text) { //Parses text against smiles
        global $db, $db_prefix, $siteurl;
        $sql = "SELECT * FROM ".$db_prefix."_smiles;";
        $smile_res = $db->sql_query($sql);
        $search = Array();
        $replace = Array();
        while ($smile = $db->sql_fetchrow($smile_res)) {
                $search[] = $smile["code"];
                $replace[] = "<img src=\"".$siteurl."/smiles/".$smile["file"]."\" border=\"0\" alt=\"".$smile["alt"]."\">";
        }
        $text = str_replace($search,$replace,$text);
        $db->sql_freeresult($smile_res);
}
function hex_esc($matches) {
        return sprintf("%02x", ord($matches[0]));
}
function catlist() { //Category List
        global $db, $db_prefix;
        $ret = array();
        if(! $res = $db->sql_query("SELECT id, name, image FROM ".$db_prefix."_categories ORDER BY sort_index, id ASC") )
                bterror("SELECT id, name FROM ".$db_prefix."_categories ORDER BY sort_index, id ASC");
        while ($row = $db->sql_fetchrow($res))
                $ret[] = $row;
        return $ret;
}
function pic($name, $url = "", $alt = "") {//Gets a picture from theme directory
        global $theme;
        if ($alt == "" AND $alt != null AND defined("_btalt_".$name)) $alt = constant("_btalt_".$name);

        $ret = "<img src=\"themes/".$theme."/pics/".$name."\" border=\"0\" alt=\"".$alt."\" title=\"".$alt."\" />";
        if ($url != "") {
                return "<a href=\"".$url."\">".$ret."</a>";
        }
        return $ret;
}
function ratingpic($num) {//Gets the correct star rating picture
        $r = round($num * 2) / 2;
        if ($r < 1 OR $r > 5) return;
        return pic($r."-rating.png");
}
function format_comment($text, $strip_html = false, $strip_slash = false)
{
	global $smilies, $privatesmilies;

	$s = $text;

	if ($strip_html)
		$s = htmlspecialchars($s);

	if ($strip_slash)
		$s = stripslashes($s);

$s = str_replace("]\n", "]", $s);
$match = array(
"/\[list\]\s*((\s|.)+?)\s*\[\/list\]/i",
"/\[list=(.*?)\]\s*((\s|.)+?)\s*\[\/list=(.*?)\]/i",
"/\[\*\]/i",
"/\[br\]/",
"/\[b\]((\s|.)+?)\[\/b\]/",
"/\[i\]((\s|.)+?)\[\/i\]/",
"/\[u\]((\s|.)+?)\[\/u\]/",
"/\[img\](http:\/\/[^\s'\"<>]+(\.gif|\.jpg|\.png))\[\/img\]/i",
"/\[img=(http:\/\/[^\s'\"<>]+(\.gif|\.jpg|\.png))\]/i",
"/\[color=([a-zA-Z]+)\]((\s|.)+?)\[\/color\]/i",
"/\[color=(#[a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9])\]((\s|.)+?)\[\/color\]/i",
"/\[url=((http|ftp|https|ftps|irc):\/\/[^<>\s]+?)\]((\s|.)+?)\[\/url\]/i",
"/\[url\]((http|ftp|https|ftps|irc):\/\/[^<>\s]+?)\[\/url\]/i",
"/\[size=([1-7])\]((\s|.)+?)\[\/size\]/i",
"/\[center\]((\s|.)+?)\[\/center\]/i",
"/\[font=([a-zA-Z ,]+)\]((\s|.)+?)\[\/font\]/i",
"/\[video=[^\s'\"<>]*youtube.com.*v=([^\s'\"<>]+)\]/ims",
"/\[video=[^\s'\"<>]*video.google.com.*docid=(-?[0-9]+).*\]/ims",
'#\[code=php\](.*?)\[\/code\]#se',
'#\[php\](.*?)\[\/php\]#se',
"/\[skype\]((\s|.)+?)\[\/skype\]\s*/i",
"/\[website\](.*?)\[\/website\]\s*/i",
"/\[spoiler\]\s*((\s|.)+?)\s*\[\/spoiler\]\s*/i",
"/\[msn=(.*?)\]\s*/i",
"/\[yahoo\](.*?)\[\/yahoo\]\s*/i",
"/\[aim=(.*?)\](.*?)\[\/aim\]\s*/i",
);
$replace = array(
"<span><ul>\\1</ul></span>",
"<span><ol TYPE=\\1>\\2</ol></span>",
"<li>",
"<br>",
"<b>\\1</b>",
"<i>\\1</i>",
"<u>\\1</u>",
"<a href=\"\\1\" target=\"_blank\"><img border=0 src=\"\\1\" onLoad='SetSize(this, 300)'></a>",
"<a href=\"\\1\" target=\"_blank\"><img border=0 src=\"\\1\" onLoad='SetSize(this, 300)'></a>",
"<font color=\\1>\\2</font>",
"<font color=\\1>\\2</font>",
"<a href=redirect.php?url=\\1 target=\"_blank\">\\3</a>",
"<a href=redirect.php?url=\\1 target=\"_blank\">\\1</a>",
"<font size=\\1>\\2</font>",
"<center>\\1</center>",
"<font face=\"\\1\">\\2</font>",
"<object width=\"500\" height=\"410\"><param name=\"movie\" value=\"http://www.youtube.com/v/\\1\"></param><embed src=\"http://www.youtube.com/v/\\1\" type=\"application/x-shockwave-flash\" width=\"500\" height=\"410\"></embed></object>",
"<embed style=\"width:500px; height:410px;\" id=\"VideoPlayback\" align=\"middle\" type=\"application/x-shockwave-flash\" src=\"http://video.google.com/googleplayer.swf?docId=\\1\" allowScriptAccess=\"sameDomain\" quality=\"best\" bgcolor=\"#ffffff\" scale=\"noScale\" wmode=\"window\" salign=\"TL\"  FlashVars=\"playerMode=embedded\"> </embed>",
"'<dl class=\"codebox\"><dt>Code: <a href=\"#\" onclick=\"selectCode(this); return false;\">Select all</a></dt><table class=main2 border=0 cellspacing=0 cellpadding=10><tr><td>'.highlight_string(stripslashes('$1'), true).'<td></tr></table><br /></dl>'",
"'<dl class=\"codebox\"><dt>Code: <a href=\"#\" onclick=\"selectCode(this); return false;\">Select all</a></dt><table class=main2 border=0 cellspacing=0 cellpadding=10><tr><td>'.highlight_string(stripslashes('$1'), true).'<td></tr></table><br /></dl>'",
"<script type=\"text/javascript\" src=\"http://download.skype.com/share/skypebuttons/js/skypeCheck.js\"></script><a href=\"skype:spockst?call\"><img src=\"http://mystatus.skype.com/smallclassic/\\1\" style=\"border: none;\" width=\"114\" height=\"20\" alt=\"My status\" /></a>",
"<iframe src=\"\\1\" name=\"frame1\" scrolling=\"auto\" frameborder=\"0\" align=\"middle\" height = \"500px\" width = \"600px\"></iframe>",
"<div style=\"padding: 3px; background-color: #FFFFFF; border: 1px solid #d8d8d8; font-size: 1em;\"><div style=\"text-transform: uppercase; border-bottom: 1px solid #CCCCCC; margin-bottom: 3px; font-size: 0.8em; font-weight: bold; display: block;\"><span onClick=\"if (this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display != '') {  this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = ''; this.innerHTML = '<b>Spoiler: </b><a href=\'#\' onClick=\'return false;\'>hide</a>'; } else { this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = 'none'; this.innerHTML = '<b>Spoiler: </b><a href=\'#\' onClick=\'return false;\'>show</a>'; }\" /><b>Spoiler: </b><a href=\"#\" onClick=\"return false;\">show</a></span></div><div class=\"quotecontent\"><div style=\"display: none;\">\\1</div></div></div>",
"<img title=\"msn online indicator\" alt=\"msn status\" src=\"http://www.bencastricum.nl/msn/status.php/\\1.png\"/>",
"<a href=http://edit.yahoo.com/config/send_webmesg?.target=\\1&.src=pg><img border=0 src=http://opi.yahoo.com/online?u=\\1",
"<img src=http://www.funnyweb.dk:8080/aim/\\1 alt=\\2>",
);
$s = preg_replace($match, $replace, $s);
	// URLs
	$s = format_urls($s);


	// Maintain spacing
	$s = str_replace("  ", " &nbsp;", $s);
	//Quotes
$s = format_quotes($s);
	// Linebreaks
	$s = nl2br($s);

	return $s;
}
function format_urls($s)
{
return preg_replace(
    "/(\A|[^=\]'\"a-zA-Z0-9])((http|ftp|https|ftps|irc):\/\/[^<>\s]+)/i",
    "\\1<a href=redirect.php?url=\\2>\\2</a>", $s);
}
function format_quotes($s)
{
   preg_match_all('/\\[quote.*?\\]/', $s, $result, PREG_PATTERN_ORDER);
    $openquotecount = count($openquote = $result[0]);
   preg_match_all('/\\[\/quote\\]/', $s, $result, PREG_PATTERN_ORDER);
    $closequotecount = count($closequote = $result[0]);

   if ($openquotecount != $closequotecount) return $s; // quote mismatch. Return raw string...

   // Get position of opening quotes
    $openval = array();
   $pos = -1;

   foreach($openquote as $val)
 $openval[] = $pos = strpos($s,$val,$pos+1);

   // Get position of closing quotes
   $closeval = array();
   $pos = -1;

   foreach($closequote as $val)
       $closeval[] = $pos = strpos($s,$val,$pos+1);


   for ($i=0; $i < count($openval); $i++)
 if ($openval[$i] > $closeval[$i]) return $s; // Cannot close before opening. Return raw string...


    $s = str_replace("[quote]","<p class=sub><b>Quote:</b></p><table class=main border=1 cellspacing=0 cellpadding=10><tr><td style='border: 1px black dotted'>",$s);
   $s = preg_replace("/\\[quote=(.+?)\\]/", "<p class=sub><b>\\1 wrote:</b></p><table class=main border=1 cellspacing=0 cellpadding=10><tr><td style='border: 1px black dotted'>", $s);
   $s = str_replace("[/quote]","</td></tr></table><br>",$s);
   return $s;
}
?>
