All pastes #816681 Raw Edit

Anonymous

public text v1 · immutable
·published 2007-12-14 22:33 UTC
rendered paste body
<?php
/***********************\ 
--DO NOT EDIT THIS FILE--
\***********************/

if(!defined('IN_TRACKER'))
  die('Hacking attempt!');

require_once($rootpath . 'include/cleanup.php');
include_once($rootpath . 'include/globalfunctions.php');

//---- Max. Sysops v0.9 by xam
function maxsysop () {
	global $CURUSER,$rootpath, $lang;
	$lmaxclass  = UC_MODERATOR;
	$filename = $rootpath . 'config/STAFFNAMES';	
	$filename2 = $rootpath . 'config/STAFFIDS';	
	if ($CURUSER['class'] >= $lmaxclass) {
		$fp = fopen($filename, 'r');
		while (!feof($fp))
			{ 
				$staffnames= fgets($fp);
				$results = explode(' ', $staffnames); 
			}
		$msg = 'Fake Account Detected: Username: '.$CURUSER['username'].' - UserID: '.$CURUSER['id'].' - UserIP : '.getip();
		$subject = 'Warning: Fake Account Detected!';
		$added = sqlesc(get_date_time());
		if (!in_array($CURUSER['username'], $results, true)) { // true for strict comparison
			sql_query('INSERT INTO messages (sender, receiver, added, subject, msg, poster) VALUES(0, 1, '.$added.', '.sqlesc($subject).', '.sqlesc($msg).', 0)');
			write_log($msg);
			fclose($fp);
			stderr($lang->global['error'], $lang->global['fakeaccount']);
		}
		fclose($fp);
	}

	if ($CURUSER['class'] >= $lmaxclass) {
		$fp2 = fopen($filename2, 'r');
		while (!feof($fp2))
				{ 
					$staffids = fgets($fp2);
					$results2 = explode(' ', $staffids); 
				}
			if (!in_array($CURUSER['id'], $results2, true)) { // true for strict comparison				
				sql_query('INSERT INTO messages (sender, receiver, added, subject, msg, poster) VALUES(0, 1, '.$added.', '.sqlesc($subject).', '.sqlesc($msg).', 0)');
				write_log($msg);				
				fclose($fp2);
				stderr($lang->global['error'], $lang->global['fakeaccount']);		
			}
			fclose($fp2);
	}	
	return true;
}

function strip_magic_quotes($arr)
{
	foreach ($arr as $k => $v)
	{
	 if (is_array($v))
	  { $arr[$k] = strip_magic_quotes($v); }
	 else
	  { $arr[$k] = stripslashes($v); }
	}

	return $arr;
}

function fix_url($url) {
	$url = htmlspecialchars($url);
	$url = str_replace("&amp;", "&", $url);	
	return $url;
}

function htmlspecialchars_uni($text, $entities = true)
{
	return str_replace(
		// replace special html characters
		array('<', '>', '"'),
		array('&lt;', '&gt;', '&quot;'),
		preg_replace(
			// translates all non-unicode entities
			'/&(?!' . ($entities ? '#[0-9]+' : '(#[0-9]+|[a-z]+)') . ';)/si',
			'&',
			$text
		)
	);
}

function htmlspecialchars_uni2($message)
{
	$message = preg_replace("#&(?!\#[0-9]+;)#si", "&amp;", $message); // Fix & but allow unicode
	$message = str_replace("<","&lt;",$message);
	$message = str_replace(">","&gt;",$message);
	$message = str_replace("\"","&quot;",$message);
	$message = str_replace("  ", "&nbsp;&nbsp;", $message);
	return $message;
}

function xss_clean(&$var)
	{
		static
			$preg_find    = array('#javascript#i', '#vbscript#i'),
			$preg_replace = array('java script',   'vb script');

		$var = preg_replace($preg_find, $preg_replace, htmlspecialchars_uni($var));
		return $var;
	}

function local_user()
{
  return $_SERVER["SERVER_ADDR"] == $_SERVER["REMOTE_ADDR"];
}

function cur_user_check () {
	global $CURUSER, $lang;
	if ($CURUSER)
		stderr ($lang->global['error'], $lang->global['alreadylogged']);
}

function sql_query($query)
{	
	++$_SESSION['totalqueries'];
	return mysql_query($query);
}

function get_row_count($table = '', $suffix = '')
{
	if (isset($suffix))
		$suffix = " $suffix";
	($r = sql_query("SELECT COUNT(*) FROM $table$suffix")) or sqlerr(__FILE__, __LINE__);
	($a = mysql_fetch_row($r)) or sqlerr(__FILE__, __LINE__);
	return $a[0];
}

function write_log($text)
{
  $text = sqlesc($text);
  $added = sqlesc(get_date_time());
  sql_query("INSERT INTO sitelog (added, txt) VALUES($added, $text)") or sqlerr(__FILE__, __LINE__);
}

function KPS($type = '+', $point = '1.0', $id = '') {
	global $bonus;
	if ($bonus == 'enable' OR $bonus == 'disablesave')
		sql_query('UPDATE users SET seedbonus = seedbonus '.$type.' '.$point.' WHERE id = '.sqlesc($id)) or sqlerr(__FILE__, __LINE__);		
	else
		return;
}

//---- BANNED EMAILS v0.2 by xam
function EmailBanned($newEmail)
{
    $newEmail = trim(strtolower($newEmail));
    $sql = sql_query("SELECT * FROM bannedemails");
    $list = mysql_fetch_array($sql);
    $addresses = explode(' ', preg_replace("/[[:space:]]+/", " ", trim($list[value])) );

    if(count($addresses) > 0)
    {
        foreach ( $addresses as $email )
        {
            $email = trim(strtolower(ereg_replace('\.', '\\.', $email)));
            if(strstr($email, "@"))
            {
                if(ereg('^@', $email))
                {        // Any user @host?
                    // Expand the match expression to catch hosts and
                    // sub-domains
                    $email = ereg_replace('^@', '[@\\.]', $email);
                    if(ereg("$email$", $newEmail))
                    return true;
                }
            }
            elseif(ereg('@$', $email))
            {    // User at any host?
                if(ereg("^$email", $newEmail))
                return true;
            }
            else
            {                // User@host
                if(strtolower($email) == $newEmail)
                return true;
            }
        }
    }

    return false;
}

//---- Redirect MOD v0.5 by xam
function redirect($url, $message='', $title='', $wait=3, $usephp=false, $withbaseurl=true)
{
	global $SITENAME,$BASEURL,$defaulttemplate,$lang;

	if (empty($message))
		$message = $lang->global['redirect'];

	if(empty($title))
		$title = $SITENAME;
		
	$url = htmlspecialchars($url);
	$url = str_replace("&amp;", "&", $url);
	$url = ($withbaseurl ? $BASEURL.'/'.$url : $url);

	if ($usephp) {		
		header ("Location: $url");
		exit;
	}
	ob_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<head>
<title><?=$title;?></title>
<meta http-equiv="refresh" content="<?=$wait;?>;URL=<?=$url;?>" />
<link rel="stylesheet" href="<?=$BASEURL;?>/include/templates/<?=$defaulttemplate;?>/style/style.css" type="text/css" media="screen" />
</head>
<script type="text/javascript" src="overlib.js"></script>
<body>
<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>
<br />
<br />
<br />
<br />
<div style="margin: auto auto; width: 50%" align="center">
<table border="0" cellspacing="1" cellpadding="4" class="tborder">
<tr>
<td class="thead"><strong><a href=<?=$BASEURL;?>><?=$title;?></a></strong></td>
</tr>
<tr>
<td class="trow1" align="center"><p><font color=red><?=$message;?></font></p></td>
</tr>
<tr>
<td class="trow2" align="right"><a href="<?=$url;?>">
<span class="smalltext"><?=$lang->global['nowaitmessage'];?></span></a></td>
</tr>
</table>
</div>
</body>
</html>
<?php
	ob_end_flush();
	exit;
}

//---- CACHE MOD v0.4 by xam
function cache_check ($file = 'cachefile') {
	global $cache,$rootpath,$cachesystem,$lang;	
	if ($cachesystem == 'yes') {
		$cachefile = $rootpath.$cache . '/'.$file.'.html'; 
		$cachetime = 120 * 60; // 2 Hours     		
		if (file_exists($cachefile) && (TIMENOW - $cachetime < filemtime($cachefile))) 
		{
			include_once($cachefile);			
			print(sprintf($lang->global['cachedmessage'], date('Y-m-d H:i:s', filemtime($cachefile))));
			end_main_frame();
			stdfoot();	
			exit;
		}
		ob_start();
	}else
		return;
}
  
function cache_save  ($file = 'cachefile') {
	global $cache,$rootpath,$cachesystem;
	if ($cachesystem == 'yes') {
		$cachefile = $rootpath.$cache . '/'.$file.'.html'; 
		$fp = fopen($cachefile, 'w');
		fwrite($fp, ob_get_contents());      
		fclose($fp);        
		ob_end_flush();
	}else
		return;
}

//---- Secure Mail System v0.6 by xam
function safe_email($email) { 	
	$email = str_replace("<","",$email); 
	$email = str_replace(">","",$email); 
	$email = str_replace("\'","",$email); 
	$email = str_replace('\"',"",$email); 
	$email = str_replace("\\\\","",$email); 
	return $email; 
}

function check_email ($email) {
	# Check EMail Function v.03 by xam!
	if(ereg("^([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", $email)) 
		return true;
	else
		return false;
}

function sent_mail($to,$fromname,$fromemail,$subject,$body,$type = "confirmation",$showmsg=true,$multiple=false,$multiplemail='') {
	global $SITENAME,$SITEEMAIL,$smtptype,$smtp,$smtp_host,$smtp_port,$smtp_from,$smtpaddress,$smtpport,$accountname,$accountpassword,$rootpath,$charset, $lang;
	# Sent Mail Function v.06 by xam (This function to help avoid spam-filters.)
	if ($smtptype == 'default') {
		@mail($to, $subject, $body, "From: $SITEEMAIL", "-f$SITEEMAIL") or stderr("Error", "Unable to send mail. Please contact an administrator about this error.");    
	}elseif ($smtptype == 'advanced') {
	# Is the OS Windows or Mac or Linux?
	if (strtoupper(substr(PHP_OS,0,3)=='WIN')) {
		$eol="\r\n";
		$windows = true;
	}
	elseif (strtoupper(substr(PHP_OS,0,3)=='MAC'))
		$eol="\r";
	else
		$eol="\n"; 
	$mid = md5(getip() . $fromname);
	$name = $_SERVER["SERVER_NAME"];
	$headers .= "From: $fromname <$fromemail>".$eol;	
	$headers .= "Reply-To: $fromname <$fromemail>".$eol;
	$headers .= "Return-Path: $fromname <$fromemail>".$eol;
	$headers .= "Message-ID: <$mid thesystem@$name>".$eol;
	$headers .= "X-Mailer: PHP v".phpversion().$eol; 
    $headers .= "MIME-Version: 1.0".$eol; 
    $headers .= "X-Sender: PHP".$eol;        
    if ($multiple)
    	$headers .= "Bcc: $multiplemail.$eol";
	if ($smtp == "yes") {    	
		ini_set('SMTP', $smtp_host);
		ini_set('smtp_port', $smtp_port);
		if ($windows)
			ini_set('sendmail_from', $smtp_from);
		}
			
    	@mail($to,$subject,$body,$headers) or stderr($lang->global['error'], $lang->global['mailerror']);    
    	
    	ini_restore(SMTP); 
		ini_restore(smtp_port); 
		if ($windows)
			ini_restore(sendmail_from); 
	}elseif ($smtptype == 'external') {
		require_once($rootpath . 'include/smtp/smtp.lib.php');
		$mail = new smtp;		
		$mail->debug(false);
		$mail->open($smtpaddress, $smtpport);
		$mail->auth($accountname, $accountpassword);
		$mail->from($SITEEMAIL);
		$mail->to($to);
		$mail->subject($subject);
		$mail->body($body);
		$mail->send();
		$mail->close();		
	}		
    if ($showmsg) {
	    if ($type == "confirmation")
	    	stderr($lang->global['success'], sprintf($lang->global['mailsent'], htmlspecialchars(trim($to))) ,false);
	    else if ($type == "details")
	    	stderr($lang->global['success'], sprintf($lang->global['mailsent2'], htmlspecialchars(trim($to))) ,false);
	}else
		return true;    
}

//---- Login Attempts v0.6 by xam
function failedloginscheck ($type = 'Login') {
	global $maxloginattempts,$rootpath,$BASEURL,$ip,$lang;	
	$total = 0;
	if (!$ip)
		$ip = sqlesc(getip());
	$Query = sql_query("SELECT SUM(attempts) FROM loginattempts WHERE ip=$ip") or sqlerr(__FILE__, __LINE__);
	list($total) = mysql_fetch_array($Query);
	if ($total >= $maxloginattempts) {
			sql_query("UPDATE loginattempts SET banned = 'yes' WHERE ip=$ip") or sqlerr(__FILE__, __LINE__);			
			stderr(sprintf($lang->global['xlocked'], $type), sprintf($lang->global['xlocked2'], '<a href='.$BASEURL.'/unbaniprequest.php?ip='.htmlspecialchars($ip).'&action=showform>'),false);				
		}
}

function failedlogins ($type = 'login', $recover = false, $head = true, $msg=false, $uid = 0) {	
	global $BASEURL, $ip, $lang, $username, $password, $md5pw, $iphost, $ipaddress;
	if (!$ip)
		$ip = sqlesc(getip());
	$added = sqlesc(get_date_time());
	$a = (@mysql_fetch_row(@sql_query("select count(*) from loginattempts where ip=$ip"))) or sqlerr(__FILE__, __LINE__);
	if ($a[0] == 0)
		sql_query("INSERT INTO loginattempts (ip, added, attempts) VALUES ($ip, $added, 1)") or sqlerr(__FILE__, __LINE__);
	else
		sql_query("UPDATE loginattempts SET attempts = attempts + 1 where ip=$ip") or sqlerr(__FILE__, __LINE__);		
	if ($recover)
			sql_query("UPDATE loginattempts SET type = 'recover' WHERE ip = $ip") or sqlerr(__FILE__, __LINE__);
	if ($msg && $uid) {
		$subject = sqlesc($lang->global['warning']);
		$message = sqlesc(sprintf($lang->global['accountwarn'], $username, $password, $md5pw, $ipaddress, $iphost));
		sql_query("INSERT INTO messages (sender, receiver, added, msg, subject, poster) VALUES(0, $uid, $added, $message, $subject, 0)");
	}
	if ($type == 'silent')
		return;				
	elseif ($type == 'login')	
		
		stderr($lang->global['error'], sprintf($lang->global['incorrectlogin'], '<a href='.$BASEURL.'/recover.php>'),false);	
	else
		stderr($lang->global['error'],$type,false, $head);
	
}

function remaining ($type = 'login') {
	global $maxloginattempts,$ip;	
	$total = 0;
	if (!$ip)
		$ip = sqlesc(getip());
	$Query = sql_query("SELECT SUM(attempts) FROM loginattempts WHERE ip=$ip") or sqlerr(__FILE__, __LINE__);
	list($total) = mysql_fetch_array($Query);
	$remaining = $maxloginattempts - $total;
	if ($remaining <= 2 )
		$remaining = "<font color=red>[".$remaining."]</font>";
	else 
		$remaining = "<font color=green>[".$remaining."]</font>";
		
	return $remaining;
}

//---- Image Verification v0.3 by xam
function random_str($length="6")
{
	$str = '';
	$set = array("A","B","C","D","E","F","G","H","P","R","M","N","1","2","3","4","5","6","7","8","9");
	$str;
	for($i=1;$i<=$length;$i++)
	{
		$ch = rand(0, count($set)-1);
		$str .= $set[$ch];
	}
	return $str;
}

function image_code () {
			$randomstr = random_str();
			$imagehash = md5($randomstr);
			$dateline = TIMENOW;		
			$sql = 'INSERT INTO `regimages` (`imagehash`, `imagestring`, `dateline`) VALUES (\''.$imagehash.'\', \''.$randomstr.'\', \''.$dateline.'\');';
			sql_query($sql) or sqlerr(__FILE__, __LINE__);
			return $imagehash;
}

function check_code ($imagehash, $imagestring, $where = 'signup.php', $maxattemptlog=true) {
	global $BASEURL;
	$query = sprintf("SELECT * FROM regimages WHERE imagehash='%s' AND imagestring='%s'",
   mysql_real_escape_string($imagehash),
   mysql_real_escape_string($imagestring));
	$sql = sql_query($query);
	$imgcheck = mysql_fetch_array($sql);
	if(!$imgcheck['dateline']) {		
		$delete = sprintf("DELETE FROM regimages WHERE imagehash='%s'",
		mysql_real_escape_string($imagehash));	
		sql_query($delete);
		if ($where == 'login.php' && $maxattemptlog) {
			failedlogins('silent');
			Header("Location: $BASEURL/login.php?error=2");
			die;
		}elseif ($where == 'recover.php' && $maxattemptlog) {
			failedlogins('silent');
			Header("Location: $BASEURL/recover.php?error=2");
			die;
		}elseif ($where == 'recoverhint.php' && $maxattemptlog) {
			failedlogins('silent');
			Header("Location: $BASEURL/recoverhint.php?error=2");
			die;
		}elseif ($where == 'signup.php') {
			Header("Location: $BASEURL/signup.php?error=2");
			die;
		}elseif (substr($where, 0, 22) == 'signup.php?invitehash=') {
			Header("Location: ".$BASEURL."/".$where."&error=2");
			die;
		}else{
			failedlogins('silent');
			Header("Location: ".$BASEURL."/".$where);
			die;
		}
	}else{
		$delete = sprintf("DELETE FROM regimages WHERE imagehash='%s'",
		mysql_real_escape_string($imagehash));
		sql_query($delete);
		return true;
	}
}

function show_image_code ($submitbutton=false, $buttonname='go') {
	global $iv,$BASEURL,$lang;		
	if ($iv == "yes") {
		unset($imagehash);	
		$imagehash = image_code () ;
		Print("<input type=\"hidden\" name=\"imagehash\" value=\"$imagehash\" />");
		print ("<tr><td class=\"rowhead\">".$lang->global['secimage']."</td>");
		Print ("<td><img src=\"".$BASEURL."/image.php?action=regimage&imagehash=$imagehash\" border=\"0\"></a></td></tr>");
		Print ("<tr><td class=\"rowhead\">".$lang->global['seccode']."</td>");
		Print("<td><input type=\"text\" size=\"26\" name=\"imagestring\" style=\"width: 200px; border: 1px solid gray\" value=\"\" />
		".($submitbutton ? "<input type='submit' value='$buttonname' class='btn'>" : "")."
		</td></tr>");		
	}else
		return;
}

function validip($ip)
{
	if (!empty($ip) && $ip == long2ip(ip2long($ip)))
	{
		// reserved IANA IPv4 addresses
		// http://www.iana.org/assignments/ipv4-address-space
		$reserved_ips = array (
				array('0.0.0.0','2.255.255.255'),
				array('10.0.0.0','10.255.255.255'),
				array('127.0.0.0','127.255.255.255'),
				array('169.254.0.0','169.254.255.255'),
				array('172.16.0.0','172.31.255.255'),
				array('192.0.2.0','192.0.2.255'),
				array('192.168.0.0','192.168.255.255'),
				array('255.255.255.0','255.255.255.255')
		);

		foreach ($reserved_ips as $r)
		{
				$min = ip2long($r[0]);
				$max = ip2long($r[1]);
				if ((ip2long($ip) >= $min) && (ip2long($ip) <= $max)) return false;
		}
		return true;
	}
	else return false;
}

function maxslots () {
	global $CURUSER, $maxdlsystem, $lang;
	if ($maxdlsystem == "yes" && $CURUSER["class"] < UC_VIP) {
		$gigs = $CURUSER["uploaded"] / (1024*1024*1024);
		$ratio = (($CURUSER["downloaded"] > 0) ? ($CURUSER["uploaded"] / $CURUSER["downloaded"]) : 1);
		if ($ratio < 0.5 || $gigs < 5) $max = 1;
			elseif ($ratio < 0.65 || $gigs < 6.5) $max = 2;
				elseif ($ratio < 0.8 || $gigs < 8) $max = 3;
					elseif ($ratio < 0.95 || $gigs < 9.5) $max = 4;
						else $max = 0;
		if ($max > 0)
			print (sprintf($lang->global['slots'], $max));
	}
}

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 dbconn($automaticclean = false)
{
    global $mysql_host, $mysql_user, $mysql_pass, $mysql_db, $lang;

    if (!@mysql_pconnect($mysql_host, $mysql_user, $mysql_pass))
    {
	  switch (mysql_errno())
	  {
		case 1040:
		case 2002:
			if ($_SERVER['REQUEST_METHOD'] == 'GET')				
				die(sprintf($lang->global['serverload'], $_SERVER['REQUEST_URI']));
			else
				die($lang->global['toomanyusers']);
        default:
    	    die('[' . mysql_errno() . '] dbconn: mysql_pconnect: ' . mysql_error());
      }
    }
    mysql_select_db($mysql_db)
        or die('dbconn: mysql_select_db: ' + mysql_error());

    IsUserLogged();

    if ($automaticclean)
        register_shutdown_function('automaticclean');
}

//---- Login System v0.7 by xam
function IsUserLogged() {
    global $SITE_ONLINE, $SITENAME, $iplog1, $securelogin, $securehash, $lang, $rootpath;
    unset($GLOBALS["CURUSER"], $GLOBALS["usergroups"], $usergroup);

    $ip = getip();
		
    if(IsIpBanned($ip))
		{
		  header("HTTP/1.0 403 Forbidden");
		  die($lang->global['ipbanned']);
		}
		
	if (empty($_COOKIE["c_secure_pass"]) || empty($_COOKIE["c_secure_uid"]) || strlen($_COOKIE["c_secure_pass"]) != 32)
        return;
	
	if ($securelogin == "yes" || $_COOKIE["s_secure_access"])
		if (empty($_SESSION["s_secure_uid"]) || empty($_SESSION["s_secure_pass"]) || strlen($_SESSION["s_secure_pass"]) != 32)
			return;

    $b_id = base64($_COOKIE["c_secure_uid"],false);
    $id = (int)$b_id;

    if (!$id || !is_valid_id($id))
        return;
        
    $res = sql_query("SELECT users.*, NOW() as ctime FROM users WHERE id = ".sqlesc($id)." AND enabled='yes' AND status = 'confirmed' LIMIT 1");
    $row = mysql_fetch_array($res);

    if (!$row)
        return;

    if ($_COOKIE["c_secure_pass"] != md5(md5($row["passhash"]).$ip.md5($securehash.$SITENAME)))
        return;
	
	if ($securelogin == "yes" || $_COOKIE["s_secure_access"])
    	if ($_SESSION["s_secure_pass"] != md5(md5($row["passhash"]).$ip.md5($securehash.$SITENAME)))
    		return;
    		
    if (!$row["passkey"] || strlen($row["passkey"]) != 32){
	    $passkey = md5($row['username'].get_date_time().$row['passhash'].md5($securehash.$SITENAME));
    	sql_query("UPDATE users SET passkey = ".sqlesc($passkey)." WHERE id = " . sqlesc($row["id"]));
	}

	if ($iplog1 == "yes") {
		if (($ip != $row["ip"]) && $row["ip"]) {
			$getip = sql_query("SELECT * FROM iplog WHERE ip = ".sqlesc($ip)." AND userid = ".sqlesc($row["id"]));
			if (mysql_num_rows($getip) == 0)
				sql_query("INSERT INTO iplog (ip, userid, access) VALUES (".sqlesc($ip).", ".sqlesc($row["id"]).", ".sqlesc(get_date_time()).")");
		}
	}
	
    sql_query("UPDATE users SET last_access='" . get_date_time() . "', ip=".sqlesc($ip)." WHERE id = " . sqlesc($row["id"]));

    $row['ip'] = $ip;		
    $GLOBALS["CURUSER"] = $row;
	
	$classarrays = array(UC_USER, UC_POWER_USER, UC_VIP, UC_UPLOADER, UC_MODERATOR, UC_ADMINISTRATOR, UC_SYSOP, UC_STAFFLEADER);
	$usergroup = $row['class'];

	if (in_array($usergroup, $classarrays))
		$usergroup = $usergroup + 1;

	$get_group_data = sql_query('SELECT * FROM usergroups WHERE gid = '.sqlesc($usergroup));
	$group_data_results = mysql_fetch_array($get_group_data);
	$GLOBALS["usergroups"] = $group_data_results;
}

function automaticclean() {
    global $autoclean_interval,$lang,$usergroups;

    $now = TIMENOW;
    $docleanup = 0;

    $res = sql_query("SELECT value_u FROM avps WHERE arg = 'lastcleantime'");
    $row = mysql_fetch_array($res);
    if (!$row) {
        sql_query("INSERT INTO avps (arg, value_u) VALUES ('lastcleantime',$now)");
        return;
    }
    $ts = $row[0];
    if ($ts + $autoclean_interval > $now)
        return;
    sql_query("UPDATE avps SET value_u=$now WHERE arg='lastcleantime' AND value_u = $ts");
    if (!mysql_affected_rows())
        return;

    docleanup();
}

function unesc($x) {
    if (get_magic_quotes_gpc())
        return stripslashes($x);
    return $x;
}

function mksize($bytes = '')
{
	if ($bytes < 1000 * 1024)
		return number_format($bytes / 1024, 2) . " KB";
	elseif ($bytes < 1000 * 1048576)
		return number_format($bytes / 1048576, 2) . " MB";
	elseif ($bytes < 1000 * 1073741824)
		return number_format($bytes / 1073741824, 2) . " GB";
	else
		return number_format($bytes / 1099511627776, 2) . " TB";
}

function mksizeint($bytes)
{
	$bytes = max(0, $bytes);
	if ($bytes < 1000)
		return floor($bytes) . " B";
	elseif ($bytes < 1000 * 1024)
		return floor($bytes / 1024) . " KB";
	elseif ($bytes < 1000 * 1048576)
		return floor($bytes / 1048576) . " MB";
	elseif ($bytes < 1000 * 1073741824)
		return floor($bytes / 1073741824) . " GB";
	else
		return floor($bytes / 1099511627776) . " TB";
}

function deadtime() {
    global $announce_interval;
    return TIMENOW - floor($announce_interval * 1.3);
}

function mkprettytime($s) {
    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"] . "d " . sprintf("%02d:%02d:%02d", $t["hour"], $t["min"], $t["sec"]);
    if ($t["hour"])
        return sprintf("%d:%02d:%02d", $t["hour"], $t["min"], $t["sec"]);
        return sprintf("%d:%02d", $t["min"], $t["sec"]);

}

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 tr($x,$y,$noesc=0,$relation='') {
    if ($noesc)
        $a = $y;
    else {
        $a = htmlspecialchars($y);
        $a = str_replace("\n", "<br />\n", $a);
    }
    print("<tr".( $relation ? " relation = \"$relation\"" : "")."><td class=\"heading\" valign=\"top\" align=\"right\">$x</td><td valign=\"top\" align=\"left\">$a</td></tr>\n");
}

function validfilename($name) {
    return preg_match('/^[^\0-\x1f:\\\\\/?*\xff#<>|]+$/si', $name);
}

function validemail($email) {
    return preg_match('/^[\w.-]+@([\w.-]+\.)+[a-z]{2,6}$/is', $email);
}

function sqlesc($value) {
    // Stripslashes
   if (get_magic_quotes_gpc()) {
       $value = stripslashes($value);
   }
   // Quote if not a number or a numeric string
   if (!is_numeric($value)) {
       $value = "'" . mysql_real_escape_string($value) . "'";
   }
   return $value;
}

function sqlwildcardesc($x) {
    return str_replace(array("%","_"), array("\\%","\\_"), mysql_real_escape_string($x));
}

function urlparse($m) {
    $t = $m[0];
    if (preg_match(',^\w+://,', $t))
        return "<a href=\"$t\">$t</a>";
    return "<a href=\"http://$t\">$t</a>";
}

function parsedescr($d, $html) {
    if (!$html)
    {
      $d = htmlspecialchars($d);
      $d = str_replace("\n", "\n<br>", $d);
    }
    return $d;
}

//---- Where's User v0.3 by xam
function where ($scriptname = "index", $userid) {
	global $where;
	if ($where == "yes") {
		if (!is_valid_id($userid))
			die;
		if (preg_match("/details/i", $scriptname))
			$where = "Browsing Torrents Details...";
		elseif (preg_match("/browse/i", $scriptname))
			$where = "Browsing Torrent Lists...";
		elseif (preg_match("/userdetails/i", $scriptname))
			$where = "Browsing Userdetails...";
		elseif (preg_match("/upload/i", $scriptname))
			$where = "Uploading Torrent..";
		elseif (preg_match("/usercp/i", $scriptname))
			$where = "Browsing User Control Panel...";
		elseif (preg_match("/search/i", $scriptname))
			$where = "Searching...";
		elseif (preg_match("/forum/i", $scriptname))
			$where = "Browsing Forums...";
		elseif (preg_match("/index/i", $scriptname))
			$where = "Browsing Homepage...";
		elseif (preg_match("/viewrequests/i", $scriptname))
			$where = "Browsing Requests...";
		elseif (preg_match("/viewoffers/i", $scriptname))
			$where = "Browsing Offers...";
		elseif (preg_match("/irc/i", $scriptname))
			$where = "Chatting...";
		else
			$where = "Unknown Location...";
		$query = sprintf("UPDATE users SET page=".sqlesc($where)." WHERE id ='%s'",
		mysql_real_escape_string($userid));
		$result = sql_query($query);
		if (!$result)
			sqlerr(__FILE__,__LINE__);
		else
			return $where;
	}
	return;
}

function stdhead($title = '', $msgalert = true, $script = '') {
	global $CURUSER, $SITE_ONLINE, $SITENAME, $SITEEMAIL, $BASEURL, $offlinemsg, $disablerightclick, $showversion, $autorefreshtime, $autorefresh, $leftmenu, $gzipcompress, $delay, $url, $rootpath, $pic_base_url, $tn, $defaulttemplate, $charset, $metadesc, $metakeywords, $lang, $slogan;
	$lang->load('header');
	$script_name = htmlspecialchars($_SERVER['SCRIPT_NAME']);
	$offlinemsg = false;
	$new_announcement = false;	
	$includescripts = '';
	$includescripts2 = '';	

	if ($SITE_ONLINE == 'no') {
		$res = sql_query('SELECT ip FROM users WHERE class = '.UC_STAFFLEADER.' LIMIT 1');
		$arr = mysql_fetch_row($res);
		$getadminip = $arr[0];
		if (get_user_class() < UC_STAFFLEADER && getip() != $getadminip) {
			die($lang->global['trackerclosed']);
		}else
			$offlinemsg = true;
	}	

	if ($title == '')
		$title = $SITENAME.$showversion;
	else
		$title = $SITENAME . ' :: ' . htmlspecialchars($title) . $showversion;

	if ($msgalert && $CURUSER) {
		$res = sql_query('SELECT COUNT(*) FROM messages WHERE receiver=' . sqlesc($CURUSER['id']) . ' AND unread=\'yes\'');
		$arr = mysql_fetch_row($res);
		$unread = $arr[0];
		if ($unread)
			$inboxpic = '<img height="14px" style="border:none" alt="inbox" title="'.$lang->global['newmessage'].'" src="'.$rootpath.$pic_base_url.'pn_inboxnew.gif">';	
		else
			$inboxpic = '<img height="14px" style="border:none" alt="inbox" title="'.$lang->global['nonewmessage'].'" src="'.$rootpath.$pic_base_url.'pn_inbox.gif">';
	}

	if ($CURUSER && $CURUSER['announce_read'] == 'no') {
		$res = sql_query('SELECT * FROM announcements WHERE minclassread <= '.$CURUSER['class'].' ORDER by added DESC LIMIT 1');
		if (mysql_num_rows($res) == 0) {
			$an_subject = $lang->global['annoucementempty'];
			$an_message = $lang->global['nonewannoucement'];
			$an_added = get_date_time();
			$an_by = 'System';
			$new_announcement = false;
		}else{
			$arr = mysql_fetch_array($res);
			$an_subject = $arr['subject'];
			$an_message = $arr['message'];
			$an_added = $arr['added'];
			$an_by = $arr['by'];
			$new_announcement = true;
			$includescripts .= '<script type="text/javascript" src="'.$BASEURL.'/scripts/annoucement.js"></script>';
		}
	}
	
	$includescripts .= '<script type="text/javascript" src="'.$BASEURL.'/scripts/preview.js"></script>';
	if (preg_match('/usercp/i', $script_name))
		$includescripts .= '<script type="text/javascript" src="'.$BASEURL.'/scripts/rp.js"></script>';
	if (preg_match('/irc/i', $script_name)) {		
		$includescripts .= '<link rel="stylesheet" type="text/css" href="'.$BASEURL.'/pjirc/css.php">';
		$includescripts .= '<script language="JavaScript" type="text/javascript" src="'.$BASEURL.'/pjirc/chat.js"></script>';
	}
	if ($script == 'ps' OR preg_match('/signup/i', $script_name))
		$includescripts .= '<script type="text/javascript" src="'.$BASEURL.'/scripts/signup.js"></script>';
	if ($script == 'textarealimiter' OR preg_match('/usercp/i', $script_name)) 
		$includescripts .= '<script type="text/javascript" src="'.$BASEURL.'/scripts/textarealimiter.js"></script>';
	if (($leftmenu == 'yes') AND ($CURUSER['leftmenu'] == 'yes' OR !$CURUSER)) {
		$includescripts .= '<script src="'.$BASEURL.'/scripts/ssm.js" language="JavaScript1.2"></script>';
		if ($CURUSER)
			$includescripts .= '<script src="'.$BASEURL.'/scripts/ssm_registered.js" language="JavaScript1.2"></script>';
		else
			$includescripts .= '<script src="'.$BASEURL.'/scripts/ssm_guest.js" language="JavaScript1.2"></script>';
	}
	if ($autorefresh == 'yes' && !preg_match('/irc/i', $script_name) && !preg_match('/settings/i', $script_name) && !preg_match('/staffpanel/i', $script_name) && !preg_match('/statistics/i', $script_name) && !preg_match('/upload/i', $script_name) && !preg_match('/sendmessage/i', $script_name) && !preg_match('/signup/i', $script_name) && !preg_match('/takesignup/i', $script_name) && !preg_match('/donate/i', $script_name))
		$includescripts .= '<script type="text/javascript" src="'.$BASEURL.'/scripts/autorefresh.js"></script>';

	if (preg_match('/settings/i', $script_name))
		$includescripts2 .= '<script type="text/javascript" src="'.$BASEURL.'/scripts/tooltip.js"></script>';
	if ($disablerightclick == 'yes')
		$includescripts2 .= '<script type="text/javascript" src="'.$BASEURL.'/scripts/disablerightclick.js"></script>';

	if ($CURUSER){
		$datum = getdate();
		$datum['hours'] = sprintf('%02.0f', $datum['hours']);
		$datum['minutes'] = sprintf('%02.0f', $datum['minutes']);
		$uped = mksize($CURUSER['uploaded']);
		$downed = mksize($CURUSER['downloaded']);
		if ($CURUSER['downloaded'] > 0)
		{
			$ratio = $CURUSER['uploaded'] / $CURUSER['downloaded'];
			$ratio = number_format($ratio, 3);
			$color = get_ratio_color($ratio);
			
			if ($color && $ratio < 1)
				$ratio = '<font color='.$color.'>'.$ratio.'</font>';
			else
				$ratio = '<font color=#ffffff>'.$ratio.'</font>';
		}else

		if ($CURUSER['uploaded'] > 0)
			$ratio = '<font color=red>Inf.</font>';
		else
			$ratio = '<font color=red>-</font>';

		if ($CURUSER['donor'] == 'yes')
			$medaldon = '<img src="'.$rootpath.$pic_base_url.'star.gif" alt="donor" title="'.$lang->global['imgdonated'].'">';
		if ($CURUSER['warned'] == 'yes')
			$warn = '<img src="'.$rootpath.$pic_base_url.'warned.gif" alt="warned" title="'.$lang->global['imgwarned'].'">';
	}

	$total_funds1 = sql_query('SELECT sum(cash) as total_funds FROM funds');
	$arr_funds = mysql_fetch_array($total_funds1);    
	$funds_so_far = $arr_funds['total_funds'];    
	$funds_difference = $tn - $funds_so_far;
	$Progress_so_far = $funds_so_far / $tn * 100;
	if($Progress_so_far >= 100)
		$Progress_so_far = '100';

	if (get_user_class() > UC_MODERATOR){

		$resa = sql_query('select COUNT(id) AS numreports FROM reports WHERE dealtwith=0');
		$arra = mysql_fetch_array($resa);
		$numreports = $arra['numreports'];

		$rese = sql_query('SELECT COUNT(id) AS nummessages FROM staffmessages WHERE answered=\'no\'');
		$arre = mysql_fetch_array($rese);
		$nummessages = $arre['nummessages'];
	}
	
	ob_start();
	include($rootpath.'include/templates/'.$defaulttemplate.'/header.php');
	ob_end_flush();
}

function stdfoot() {	
	global $SITENAME,$BASEURL,$CURUSER,$rootpath,$defaulttemplate,$lang;
	$mtime = microtime();
	$mtime = explode (" ", $mtime);
	$mtime = $mtime[1] + $mtime[0];
	$tstart = $mtime;
	$mtime = microtime();
	$mtime = explode (" ", $mtime);
	$mtime = $mtime[1] + $mtime[0];
	$tend = $mtime;
	$totaltime = ($tend - $tstart);	
	ob_start();
	include($rootpath.'include/templates/'.$defaulttemplate.'/footer.php');
	unset($_SESSION['totalqueries']);
	ob_end_flush();	
}

function genbark($x,$y) {
    stdhead($y);
    print("<h2>" . htmlspecialchars($y) . "</h2>\n");
    print("<p>" . htmlspecialchars($x) . "</p>\n");
    stdfoot();
    exit();
}

function mksecret($length = 20) {
$set = array("a","A","b","B","c","C","d","D","e","E","f","F","g","G","h","H","i","I","j","J","k","K","l","L","m","M","n","N","o","O","p","P","q","Q","r","R","s","S","t","T","u","U","v","V","w","W","x","X","y","Y","z","Z","1","2","3","4","5","6","7","8","9");
        $str;
        for($i = 1; $i <= $length; $i++)
        {
            $ch = rand(0, count($set)-1);
            $str .= $set[$ch];
        }
        return $str;
} 

//---- httperr v0.2 by xam
function httperr($code = 404) {
	$sapi_name = php_sapi_name();
	if ($sapi_name == 'cgi' OR $sapi_name == 'cgi-fcgi')
	{
		header('Status: 404 Not Found');
	}
	else
	{
		header('HTTP/1.1 404 Not Found');
	}
	exit;
}

//---- Secure Login System v0.7 by xam
function securehash($var=NULL) {
	global $SITENAME,$securehash;
	return md5(md5($var).getip().md5($securehash.$SITENAME));	
}
function sessioncookie ($id, $passhash, $expires=false, $do=false) {
	global $securelogin;
	if ($securelogin == "yes" OR $do) {		
		$passhash = securehash($passhash);
		if ($expires)
			$GLOBALS[$sessioncacheexpire]  = true;
		ob_start();
		if ($do)
			setcookie("s_secure_access", securehash($_SERVER['REMOTE_ADDR']), 0x7fffffff, "/");
		$_SESSION['s_secure_uid'] = base64($id);
		$_SESSION['s_secure_pass'] = $passhash;
		ob_end_flush();
		if (isset($sessioncacheexpire))
			return $sessioncacheexpire;
		else
			return;
	}else
		return;
}

function logincookie($id, $passhash, $updatedb = 1, $expires = 0x7fffffff)
{
	$passhash = securehash($passhash);
	if ($expires != 0x7fffffff)
		$expires = TIMENOW+900;
	ob_start();
	setcookie("c_secure_uid", base64($id), $expires, "/");
	setcookie("c_secure_pass", $passhash, $expires, "/");
	ob_end_flush();

  if ($updatedb)
  	sql_query("UPDATE users SET last_login = NOW() WHERE id = ".sqlesc($id));
}

function logoutsession () {
	ob_start();
	session_unset();
	session_destroy();
	ob_end_flush();
}

function logoutcookie() {
	global $CURUSER;
	$uid = intval($CURUSER['id']);
	ob_start();
    setcookie("c_secure_uid", "", 0x7fffffff, "/");
    setcookie("c_secure_pass", "", 0x7fffffff, "/");
	setcookie("s_secure_access", "", 0x7fffffff, "/");
	ob_end_flush();
	if (my_getuid($uid)) {
		my_unsetcookiee("mybbuser");
		my_unsetcookiee("sid");
		$time = TIMENOW;
		$lastactive = $time-900;
		sql_query("UPDATE ".TABLE_PREFIX."users SET lastactive = ".sqlesc($lastactive).", lastvisit = ".sqlesc($time)." WHERE uid = ".sqlesc($uid));
	}	
}

function base64 ($string, $encode=true) {
	if ($encode)
		return base64_encode($string);
	else
		return base64_decode($string);
}

//---- Loggedinorreturn v.03 by xam
function loggedinorreturn($mainpage = false) {
    global $CURUSER,$BASEURL;
    if (!$CURUSER) {
	    if ($mainpage)
        	header('Location: '.$BASEURL.'/login.php');
        else {
	        $to = htmlspecialchars_uni($_SERVER['REQUEST_URI']);
	    	$to = basename($to);
        	header('Location: '.$BASEURL.'/login.php?returnto=' . urlencode($to));
    	}
        exit();
    }

}

function deletetorrent($id) {
    global $torrent_dir,$rootpath;
    sql_query("DELETE FROM torrents WHERE id = ".sqlesc($id));
    sql_query("DELETE FROM snatched WHERE torrentid = ".sqlesc($id));
    foreach(explode(".","peers.files.comments.ratings") as $x)
        sql_query("DELETE FROM $x WHERE torrent = ".sqlesc($id));
    @unlink($rootpath.$torrent_dir.'/'.$id.'.torrent');
}

function pager($rpp, $count, $href, $opts = array()) {
    $pages = ceil($count / $rpp);

    if (!$opts["lastpagedefault"])
        $pagedefault = 0;
    else {
        $pagedefault = floor(($count - 1) / $rpp);
        if ($pagedefault < 0)
            $pagedefault = 0;
    }

    if (isset($_GET["page"])) {
        $page = 0 + $_GET["page"];
        if ($page < 0)
            $page = $pagedefault;
    }
    else
        $page = $pagedefault;

    $pager_next = "";
	$pager_prev = "";

    $mp = $pages - 1;    
    if ($page >= 1) {
        $pager_prev .= "<li><a href=\"{$href}page=" . ($page - 1) . "\">&lt;&lt;</a></li>\n";
    }
    else
        $pager_prev .= "<li><a name=\"disabled\" class=\"disabled\">&lt;&lt;</a></li>\n";
    
    if ($page < $mp && $mp >= 0) {
        $pager_next .= "<li><a href=\"{$href}page=" . ($page + 1) . "\">&gt;&gt;</a></li>\n";
        
    }
    else
        $pager_next .= "<li><a name=\"disabled\" class=\"disabled\">&gt;&gt;</a></li>\n";

    if ($count) {
        $pagerarr = array();
        $dotted = 0;
        $dotspace = 2;
        $dotend = $pages - $dotspace;
        $curdotend = $page - $dotspace;
        $curdotstart = $page + $dotspace;
        for ($i = 0; $i < $pages; $i++) {
            if (($i >= $dotspace && $i <= $curdotend) || ($i >= $curdotstart && $i < $dotend)) {
                if (!$dotted)
                    $pagerarr[] = "<li><b><font color=red size=2>...</b></font></li>\n";
                $dotted = 1;
                continue;
            }
            $dotted = 0;
            $start = $i * $rpp + 1;
            $end = $start + $rpp - 1;
            if ($end > $count)
                $end = $count;
            $text = "$start&nbsp;-&nbsp;$end";
            if ($i != $page)
                $pagerarr[] = "<li><a href=\"{$href}page=$i\">$text</a></li>\n";
            else
                $pagerarr[] = "<li><a name=\"current\" class=\"current\">$text</a></li>\n";
        }
        $pagerstr = join("", $pagerarr);
        $pagertop = "<table width=100% class=none><tr class=none><td class=none><div id=navcontainer2><ul>$pager_prev $pagerstr $pager_next</ul></div></tr></td></table>\n";
        $pagerbottom = "<table width=100% class=none><tr class=none><td class=none><div id=navcontainer2><ul>$pager_prev $pagerstr $pager_next</ul></div></tr></td></table>\n";
    }
    else {
        $pagertop = $pager;
        $pagerbottom = $pagertop;
    }

    $start = $page * $rpp;

    return array($pagertop, $pagerbottom, "LIMIT $start,$rpp");
}

function downloaderdata($res) {
    $rows = array();
    $ids = array();
    $peerdata = array();
    while ($row = mysql_fetch_array($res)) {
        $rows[] = $row;
        $id = $row["id"];
        $ids[] = $id;
        $peerdata[$id] = array(downloaders => 0, seeders => 0, comments => 0);
    }

    if (count($ids)) {
        $allids = implode(",", $ids);
        $res = sql_query("SELECT COUNT(*) AS c, torrent, seeder FROM peers WHERE torrent IN ($allids) GROUP BY torrent, seeder");
        while ($row = mysql_fetch_array($res)) {
            if ($row["seeder"] == "yes")
                $key = "seeders";
            else
                $key = "downloaders";
            $peerdata[$row["torrent"]][$key] = $row["c"];
        }
        $res = sql_query("SELECT COUNT(*) AS c, torrent FROM comments WHERE torrent IN ($allids) GROUP BY torrent");
        while ($row = mysql_fetch_array($res)) {
            $peerdata[$row["torrent"]]["comments"] = $row["c"];
        }
    }

    return array($rows, $peerdata);
}

function commenttable($rows,$type='',$edit='')
{
	global $CURUSER,$BASEURL,$rootpath,$pic_base_url,$lang;
	begin_main_frame();
	begin_frame();
	$count = 0;
	foreach ($rows as $row)
	{
		
		print("<p class=sub>#" . $row["id"] . " by ");
    if (isset($row["username"]))
		{
			$title = $row["title"];
			if ($title == "")
				$title = get_user_class_name($row["class"]);
        print("<a name=comm". $row["id"] .
        	" href=".$BASEURL."/userdetails.php?id=" . $row["user"] . "><b>" .
        	htmlspecialchars($row["username"]) . "</b></a>" . ($row["donor"] == "yes" ? "<img src=".$rootpath.$pic_base_url."star.gif alt='".$lang->global['imgdonated']."'>" : "") . ($row["warned"] == "yes" ? "<img src=".$rootpath.$pic_base_url."warned.gif alt=\"".$lang->global['imgwarned']."\">" : "") . " ($title)\n");
		}
		else
   		print("<a name=\"comm" . $row["id"] . "\"><i>(orphaned)</i></a>\n");

		print(" at " . $row["added"] . " GMT" .
			($row["user"] == $CURUSER["id"] || get_user_class() >= UC_MODERATOR ? "- [<a href=".$BASEURL."/".$edit."comment.php?action=edit&cid=$row[id]>".$lang->global['edit']."</a>]" : "") .
			(get_user_class() >= UC_MODERATOR ? "- [<a href=".$BASEURL."/".$edit."comment.php?action=delete&cid=$row[id]>".$lang->global['deletecomment']."</a>]" : "") .
			($row["editedby"] && get_user_class() >= UC_MODERATOR ? "- [<a href=".$BASEURL."/".$edit."comment.php?action=vieworiginal&cid=$row[id]>".$lang->global['vieworj']."</a>]" : "") . "</p>\n");
		$text = format_comment($row["text"]);
    if ($row["editedby"])
    	$text .= "<p><font size=1 class=small>".$lang->global['lastedited']." <a href=".$BASEURL."/userdetails.php?id=$row[editedby]><b>$row[username]</b></a> $row[editedat] GMT</font></p>\n";
		begin_table(true);		
		$dt = gmtime() - 180;
		$dt = sqlesc(get_date_time($dt));
		print("<tr>\n");
		print("<td align=\"center\" width=\"100px\" height=\"100px\" style='padding: 0px'>".get_avatar($row["user"])."</td>\n");
		print("<td class=text valign=top>$text</td>\n");		
		print("</tr>\n");		
		
     	if ($row['invisible'] == "yes" AND get_user_class() < UC_MODERATOR AND $row['user'] != $CURUSER['id'])
     		$onoffpic = "<img src=".$rootpath.$pic_base_url."user_offline.gif border=0>";
     	elseif ("'".$row['last_access']."'" > $dt OR $row['user'] == $CURUSER['id'])
     		$onoffpic = "<img src=".$rootpath.$pic_base_url."user_online.gif border=0>";
     	else
     		$onoffpic = "<img src=".$rootpath.$pic_base_url."user_offline.gif border=0>";
		print("<tr><td colspan=2> $onoffpic <a href=\"".$BASEURL."/sendmessage.php?receiver=".htmlspecialchars(trim($row["user"]))."\"><img src=\"".$rootpath.$pic_base_url."pm.gif\" border=\"0\" title=\"".$lang->global['sendmessageto'].htmlspecialchars($row['username'])."\"></a> <a href=\"".$BASEURL."/report.php?action=report".$type."comment&reportid=".intval($row['id'])."\"><img src=\"".$rootpath.$pic_base_url."report.gif\" border=\"0\" title=\"".$lang->global['reportcomment']."\"></a></td>");		

     end_table();
  }
	end_frame();
	end_main_frame();
}

function searchfield($s) {
    return preg_replace(array('/[^a-z0-9]/si', '/^\s*/s', '/\s*$/s', '/\s+/s'), array(" ", "", "", " "), $s);
}

function genrelist() {
    $ret = array();
    $res = sql_query("SELECT id, name, minclassread FROM categories ORDER BY name");
    while ($row = mysql_fetch_array($res))
        $ret[] = $row;
    return $ret;
}

function linkcolor($num) {
    if (!$num)
        return "red";

    return "green";
}

function ratingpic($num) {
    global $pic_base_url,$rootpath;
    $r = round($num * 2) / 2;
    if ($r < 1 || $r > 5)
        return;
    return "<img src=\"".$rootpath.$pic_base_url.$r.".gif\" border=\"0\" alt=\"rating: $num / 5\" />";
}

function writecomment($userid, $comment) {
    $res = sql_query("SELECT modcomment FROM users WHERE id = ".sqlesc($userid));
	if (mysql_num_rows($res) >= 1) {
		$arr = mysql_fetch_array($res);    
		$modcomment = gmdate("Y-m-d") . " - " . $comment . "" . ($arr[modcomment] != "" ? "\n" : "") . "$arr[modcomment]";    
		$modcom = sqlesc($modcomment);		
		return mysql_query("UPDATE users SET modcomment = $modcom WHERE id = ".sqlesc($userid));
	}else
		return;
}
function overlib($input) {
$input = preg_replace("/(\r\n|\n|\r)/", "<br />", ($input));
$input = str_replace( "\"" , "",$input);
$input = str_replace( "'" , "",$input);
$input = preg_replace("/\[img\]([^\s'\"<>]+?)\[\/img\]/i", "", $input);
$input = preg_replace("/\[img=([^\s'\"<>]+?)\]/i", "", $input);
$input = preg_replace("/\[color=([a-zA-Z]+)\]/i", "", $input);
$input = preg_replace("/\[\/color\]/i", "", $input);
$input = preg_replace("/\[size=([1-7])\]/i", "", $input);
$input = preg_replace("/\[\/size\]/i", "", $input);
$input = preg_replace("#\[(.+?)\]#"  , "", ($input));
$input = str_replace( "[b]" , "",$input);
$input = str_replace( "[/b]" , "",$input);
$input = str_replace( "[u]" , "",$input);
$input = str_replace( "[/u]" , "",$input);
$input = str_replace( "[i]" , "",$input);
$input = str_replace( "[/i]" , "",$input);
$input = substr($input,0,200);
  return ($input);
  }

   function CutName ($vTxt, $Car) {
      while(strlen($vTxt) > $Car) {
      return substr($vTxt, 0, $Car) . "";
} return $vTxt;
}
function torrenttable($res, $variant = "index") {
	global $pic_base_url, $CURUSER,$waitsystem,$BASEURL,$rootpath, $lang;
	$oldlink = '';	
	unset($wait);
	$browse_res = sql_query("SELECT last_browse FROM users WHERE id=".sqlesc($CURUSER['id']));

	$browse_arr = mysql_fetch_row($browse_res);
	$last_browse = $browse_arr[0];
	$time_now = gmtime();
	if ($last_browse > $time_now) {
		$last_browse=$time_now;
	}
if (!empty($row["poster"])){
$poster= htmlspecialchars($row['poster']);
if (!empty($row["descr"])){
$descr= htmlspecialchars($row['descr']);
$descr= preg_replace("/(\r\n|\n|\r)/", "<br />", ($descr));
$descr= preg_replace("/(\r\n|\n|\r)/", "<br>", ($descr));
$descr= str_replace( "[*]" , "",$descr);
$descr= addslashes($descr);
$dispname2 = addslashes($dispname);
}
else
$descr= "click the torrent name for more info!";
$poster2 = "<img src=$poster width=180>";
}

if ($poster2){
$popup = "<table width=&quot;500&quot;><tr><td class=&quot;colhead&quot; colspan=2><h1>" . CutName($dispname2, mega_shok.gif) . "</h1></td></tr><tr><td  valign=&quot;top&quot; align=&quot;center&quot; width=&quot;180&quot;>$poster2</td><td align=&quot;left&quot; valign=&quot;top&quot;><p align=left>".CutName($descr, 600)."</p></td></tr></table>";
}
else
$popup = "";
if ($CURUSER["class"] < UC_VIP)
  {
	if ($waitsystem == "yes") {
		  $gigs = $CURUSER["uploaded"] / (1024*1024*1024);
		  $ratio = (($CURUSER["downloaded"] > 0) ? ($CURUSER["uploaded"] / $CURUSER["downloaded"]) : 0);
		  if ($ratio < 0.5 || $gigs < 5) $wait = 48;
		  	elseif ($ratio < 0.65 || $gigs < 6.5) $wait = 24;
		  		elseif ($ratio < 0.8 || $gigs < 8) $wait = 12;
		  			elseif ($ratio < 0.95 || $gigs < 9.5) $wait = 6;
		  				else $wait = 0;
  	}
  }

	echo '<table border="1" cellspacing="0" cellpadding="1" width="100%"><tr>';

	$count_get = 0;

	foreach ($_GET as $get_name => $get_value) {
		$get_name = mysql_escape_string(strip_tags(str_replace(array("\"","'"),array("",""),$get_name)));
		$get_value = mysql_escape_string(strip_tags(str_replace(array("\"","'"),array("",""),$get_value)));
		if ($get_name != "sort" && $get_name != "type") {
			if ($count_get > 0) {
				$oldlink = $oldlink . "&" . $get_name . "=" . $get_value;
			} else {
				$oldlink = $oldlink . $get_name . "=" . $get_value;
			}
			if (isset($count_get))
				$count_get++;
		}
	}

	if ($count_get > 0) {
		$oldlink = $oldlink . "&";
	}


	if (isset($_GET['sort']) == '1') {
		if (isset($_GET['type']) == "desc") {
			$link1 = "asc";
		} else {
			$link1 = "desc";
		}
	}

	if (isset($_GET['sort']) == "2") {
	if (isset($_GET['type']) == "desc") {
		$link2 = "asc";
	} else {
		$link2 = "desc";
		}
	}

	if (isset($_GET['sort']) == "3") {
		if (isset($_GET['type']) == "desc") {
			$link3 = "asc";
	} else {
		$link3 = "desc";
		}
	}

	if (isset($_GET['sort']) == "4") {
		if (isset($_GET['type']) == "desc") {
			$link4 = "asc";
	} else {
		$link4 = "desc";
		}
	}

	if (isset($_GET['sort']) == "5") {
		if (isset($_GET['type']) == "desc") {
			$link5 = "asc";
	} else {
		$link5 = "desc";
		}
	}

	if (isset($_GET['sort']) == "6") {
		if (isset($_GET['type']) == "desc") {
			$link6 = "asc";
	} else {
		$link6 = "desc";
		}
	}

	if (isset($_GET['sort']) == "7") {
		if (isset($_GET['type']) == "desc") {
			$link7 = "asc";
	} else {
		$link7 = "desc";
		}
	}

	if (isset($_GET['sort']) == "8") {
		if (isset($_GET['type']) == "desc") {
			$link8 = "asc";
	} else {
		$link8 = "desc";
		}
	}

	if (isset($_GET['sort']) == "9") {
		if (isset($_GET['type']) == "desc") {
			$link9 = "asc";
	} else {
		$link9 = "desc";
		}
	}

	if (isset($link1) == "") { $link1 = "asc"; }
	if (isset($link2) == "") { $link2 = "desc"; }
	if (isset($link3) == "") { $link3 = "desc"; }
	if (isset($link4) == "") { $link4 = "desc"; }
	if (isset($link5) == "") { $link5 = "desc"; }
	if (isset($link6) == "") { $link6 = "desc"; }
	if (isset($link7) == "") { $link7 = "desc"; }
	if (isset($link8) == "") { $link8 = "desc"; }
	if (isset($link9) == "") { $link9 = "desc"; }

	?>
	<td class="colhead" align="center"><font color=black><?=$lang->global['type'];?></font></td>
	<td class="colhead" align="left"><a href="<?=$BASEURL?>/browse.php?<?php print $oldlink; ?>sort=1&type=<?php print $link1; ?>"><?=$lang->global['name'];?></a> <font color=black>/</font> <a href="<?=$BASEURL?>/browse.php?<?php print $oldlink; ?>sort=4&type=<?php print $link4; ?>"><?=$lang->global['added'];?></a></td>
	<?php
	if ($CURUSER["downloadpos"] != "no")
		print("<td class=\"colhead\" align=\"center\"><font color=black>".$lang->global['dl']."</td>");

	if (isset($wait))
	{
		print("<td class=\"colhead\" align=\"center\"><font color=black>".$lang->global['wait']."</font></td>\n");
	}

	if ($variant == "mytorrents")
	{
		print("<td class=\"colhead\" align=\"center\">".$lang->global['edit']."</td>\n");
		print("<td class=\"colhead\" align=\"center\">".$lang->global['visible']."</td>\n");
	}

	?>
	<td class="colhead" align="center"><a href="<?=$BASEURL?>/browse.php?<?php print $oldlink; ?>sort=2&type=<?php print $link2; ?>"><img src=<?=$rootpath.$pic_base_url?>files.gif border=0 alt=files></a></td>
	<td class="colhead" align="center"><a href="<?=$BASEURL?>/browse.php?<?php print $oldlink; ?>sort=3&type=<?php print $link3; ?>"><img src=<?=$rootpath.$pic_base_url?>comments.gif border=0 alt=comments></a></td>
	<td class="colhead" align="center"><a href="<?=$BASEURL?>/browse.php?<?php print $oldlink; ?>sort=7&type=<?php print $link7; ?>"><img src=<?=$rootpath.$pic_base_url?>seeders.gif border=0 alt=seeders></a></td>
	<td class="colhead" align="center"><a href="<?=$BASEURL?>/browse.php?<?php print $oldlink; ?>sort=8&type=<?php print $link8; ?>"><img src=<?=$rootpath.$pic_base_url?>leechers.gif border=0 alt=seeders></a></td>
	<td class="colhead" align="center"><font color=black><?=$lang->global['speed'];?></font></td>
	<td class="colhead" align="center"><a href="<?=$BASEURL?>/browse.php?<?php print $oldlink; ?>sort=5&type=<?php print $link5; ?>"><?=$lang->global['size'];?></a> <font color=black>/</font> <a href="<?=$BASEURL?>/browse.php?<?php print $oldlink; ?>sort=6&type=<?php print $link6; ?>"><?=$lang->global['snatched'];?></a></td>
	<?php
	if ($variant == "index")
	print("<td class=\"colhead\" align=center><a href=\"$BASEURL/browse.php?".(isset($oldlink) ? $oldlink : '')."sort=9&type=".(isset($link9) ? $link9 : '')."\">".$lang->global['uploader']."</a></td>\n");
	if ($CURUSER['class']>=UC_MODERATOR) { ?>
	  <td class="colhead" align="center"><font color=black><?=$lang->global['action'];?></font></td>
	<?php 
	}
		print("</tr>\n");

		while ($row = mysql_fetch_array($res)) {
			
			if ($row['offensive'] == 'yes' && $CURUSER['showoffensivetorrents'] == 'no')
				continue;

			$id = $row["id"];
			 
			print("<tr".($row["sticky"] == "yes" ? " class=highlight" : "").">\n");

			print("<td align=center width=16 style='padding: 0px'>");
			if (isset($row["cat_name"])) {
				print("<a href=\"$BASEURL/browse.php?cat=" . $row["category"] . "\">");
				if (isset($row["cat_pic"]) && $row["cat_pic"] != "")
					print("<img border=\"0\" src=\"".$rootpath.$pic_base_url.$row["cat_pic"]."\" alt=\"" . $row["cat_name"] . "\" />");
				else
					print($row["cat_name"]);
				print("</a>");
			}
			else
print("-");
       print("</td>\n");

$dispname = htmlspecialchars($row["name"]);

if (!empty($row["poster"])){
$poster= htmlspecialchars($row['poster']);
if (!empty($row["descr"])){
$descr= htmlspecialchars($row['descr']);
$descr= preg_replace("/(\r\n|\n|\r)/", "<br />", ($descr));
$descr= preg_replace("/(\r\n|\n|\r)/", "<br>", ($descr));
$descr= str_replace( "[*]" , "",$descr);
$descr= addslashes($descr);
$dispname2 = addslashes($dispname);
}
else
$descr= "click the torrent name for more info!";
$poster2 = "<img src=$poster width=180>";
}

if ($poster2){
$popup = "<table width=&quot;500&quot;><tr><td class=&quot;colhead&quot; colspan=2><h1>" . CutName($dispname2, mega_shok.gif) . "</h1></td></tr><tr><td  valign=&quot;top&quot; align=&quot;center&quot; width=&quot;180&quot;>$poster2</td><td align=&quot;left&quot; valign=&quot;top&quot;><p align=left>".CutName($descr, 600)."</p></td></tr></table>";
}
else
$popup = "";

if (!empty($row["coverscan"]))
        print("<td align=left class=$class><a class=altlink  onmouseover=\"return overlib('$popup');\" onmouseout=\"return nd();\" href=\"details.php?");
        else
        print("<td align=left class=$class><a class=altlink href=\"details.php?");
			$count_dispname=strlen($dispname);
			$max_lenght_of_torrent_name="35"; // maximum lenght
			if($count_dispname > $max_lenght_of_torrent_name){
				$short_torrent_name_alt="title=\"$dispname \"";
				$dispname=substr($dispname, 0, $max_lenght_of_torrent_name) . "...";
			}else
				$short_torrent_name_alt="title=\"$dispname \"";
			print("<td align=left><a $short_torrent_name_alt href=\"$BASEURL/details.php?");
			if ($variant == "mytorrents")
				print("returnto=" . urlencode($_SERVER["REQUEST_URI"]) . "&");
			print("id=$id");
			if ($variant == "index")
				print("&hit=1");

			 $thisisfree = ($row[free]=="yes" ? "<img src='".$rootpath.$pic_base_url."freedownload.gif' />" : "");
			 $timezone = $row["added"];
			 unset($bookmark);
			 $gb = sql_query("SELECT * FROM bookmarks WHERE userid=$CURUSER[id] AND torrentid=$id");
			 $gbarr = mysql_fetch_array($gb);

print("\" onmouseover=\"return overlib('$descr', WIDTH, 250, DELAY, 400, CAPTION, '$dispname', CENTER);\" onmouseout=\"return nd();\"><b>$dispname</b></a><br /><i>" . $row["description"] . "</i>" . $new . "\n");

			 if ($variant == "index")
				if ($CURUSER["downloadpos"] != "no")
					print("<td align=\"center\"><a class=\"index\" href=\"$BASEURL/download.php?id=$id&name=" . rawurlencode($row["filename"]) . "\"><img src=".$rootpath.$pic_base_url."dl.gif border=0 alt=Download></a></td>\n");
					if (isset($wait))
					{
						$elapsed = floor((gmtime() - strtotime($row["added"])) / 3600);
						if ($elapsed < $wait)
						{
						  $color = dechex(floor(127*($wait - $elapsed)/48 + 128)*65536);
						  print("<td align=center><nobr><a href=\"$BASEURL/faq.php#46\"><font color=\"$color\">" . number_format($wait - $elapsed) . " h</font></a></nobr></td>\n");
						}
						else
						  print("<td align=center><nobr>".$lang->global['none']."</nobr></td>\n");
			}

		 if ($variant == "mytorrents")
				print("<td align=\"center\"><a href=\"$BASEURL/edit.php?returnto=" . urlencode($_SERVER["REQUEST_URI"]) . "&id=" . $row["id"] . "\">".$lang->global['edit']."</a>\n");
		print("</td>\n");
			if ($variant == "mytorrents") {
				print("<td align=\"right\">");
				if ($row["visible"] == "no")
					print($lang->global['no']);
				else
					print($lang->global['yes']);
				print("</td>\n");
			}

			if (isset($row['type']) && $row['type'] == 'single')
				print("<td align=\"center\">" . $row["numfiles"] . "</td>\n");
			else {
				if ($variant == "index")
					print("<td align=\"center\"><b><a href=\"$BASEURL/details.php?id=$id&hit=1&filelist=1\">" . $row["numfiles"] . "</a></b></td>\n");
				else
					print("<td align=\"center\"><b><a href=\"$BASEURL/details.php?id=$id&filelist=1#filelist\">" . $row["numfiles"] . "</a></b></td>\n");
			}

			if (!$row["comments"])
				print("<td align=\"center\">" . $row["comments"] . "</td>\n");
			else {
				if ($variant == "index")
					print("<td align=\"center\"><b><a href=\"$BASEURL/details.php?id=$id&hit=1&tocomm=1\">" . $row["comments"] . "</a></b></td>\n");
				else
					print("<td align=\"center\"><b><a href=\"$BASEURL/details.php?id=$id&page=0#startcomments\">" . $row["comments"] . "</a></b></td>\n");
			}
			
					if ($row["seeders"]) {
				if ($variant == "index")
				{
				   if ($row["leechers"]) $ratio = $row["seeders"] / $row["leechers"]; else $ratio = 1;
					print("<td align=center><b><a href=$BASEURL/details.php?id=$id&hit=1&toseeders=1><font color=" .
					  get_slr_color($ratio) . ">" . $row["seeders"] . "</font></a></b></td>\n");
				}
				else
					print("<td align=\"center\"><b><a class=\"" . linkcolor($row["seeders"]) . "\" href=\"$BASEURL/details.php?id=$id&dllist=1#seeders\">" .
					  $row["seeders"] . "</a></b></td>\n");
			}
			else
				print("<td align=\"center\"><span class=\"" . linkcolor($row["seeders"]) . "\">" . $row["seeders"] . "</span></td>\n");

			if ($row["leechers"]) {
				if ($variant == "index")
					print("<td align=center><b><a href=$BASEURL/details.php?id=$id&hit=1&todlers=1>" .
					   number_format($row["leechers"]) . (isset($peerlink) ? "</a>" : "") .
					   "</b></td>\n");
				else
					print("<td align=\"center\"><b><a class=\"" . linkcolor($row["leechers"]) . "\" href=\"$BASEURL/details.php?id=$id&dllist=1#leechers\">" .
					  $row["leechers"] . "</a></b></td>\n");
			}
			else
				print("<td align=\"center\">0</td>\n");

		$seedersProgressbar = array();
		$leechersProgressbar = array();
		$resProgressbar = sql_query("SELECT p.seeder, p.to_go, t.size FROM torrents AS t LEFT JOIN peers AS p ON t.id = p.torrent WHERE  p.torrent = ".sqlesc($id)) or sqlerr(__FILE__,__LINE__);
		$progressPerTorrent = 0;
		$iProgressbar = 0;
		while ($rowProgressbar = mysql_fetch_array($resProgressbar)) {
			$progressPerTorrent += sprintf("%.2f", 100 * (1 - ($rowProgressbar["to_go"] / $rowProgressbar["size"])));    
			$iProgressbar++;
		}
		if ($iProgressbar == 0)
			$iProgressbar = 1;
		$progressTotal = sprintf("%.2f", $progressPerTorrent / $iProgressbar);




			$_s = "";
			if ($row["times_completed"] != 1)
			  $_s = "s";
					print("<td align=center>" . str_replace(" ", "&nbsp;", mksize($row["size"])) . "<br><a href=$BASEURL/viewsnatches.php?id=$row[id]><b>" . number_format($row["times_completed"]) . " x </b>time$_s</a></td>\n");

			if ($variant == "index") {
	if ($row["anonymous"] == "yes") {
				print("<td align=center>".$lang->global['anonymous']."</td>\n");
		   }
	else {
			   print("<td align=center>" . (isset($row["username"]) ? ("<a href=$BASEURL/userdetails.php?id=" . $row["owner"] . "><b>" . htmlspecialchars($row["username"]) . "</b></a>") : $lang->global['unknown']) . "</td>\n");
		}
	}
	if ($CURUSER['class'] >= UC_MODERATOR) {
			print("<td align=center><a href=\"$BASEURL/admin/fastdelete.php?id=$row[id]\"><b>D</b></a>\n");
		   print(" / <a href=\"$BASEURL/edit.php?returnto=" . urlencode($_SERVER["REQUEST_URI"]) . "&id=" . $row["id"] . "\" alt=edit><b>E</b></a></td>\n");
			print("</tr>\n");
		}
		 
		}

		print("</table><p class=success><img src=".$rootpath.$pic_base_url."freedownload.gif border=0> ".$lang->global['freedownload']."&nbsp;&nbsp;&nbsp;&nbsp;<img src=".$rootpath.$pic_base_url."new.png border=0> ".$lang->global['newtorrent']);		
		if (isset($rows))
			return $rows;
		else
			return;
	}

function iplogger() {
	global $CURUSER, $iplog2;
	if ($iplog2 == "yes") {
		$ip = sqlesc(getip());
		$userid = sqlesc((int)$CURUSER['id']);
		$res = sql_query("SELECT * FROM ips WHERE ip = $ip AND userid = $userid");
		if (mysql_num_rows($res) == 0 ) {
			sql_query("INSERT INTO ips (userid, ip) VALUES ($userid, $ip)");
		}else
			return;
		}else
			return;
}

function hash_pad($hash) {
    return str_pad($hash, 20);
}

function hash_where($name, $hash) {
    $shhash = preg_replace('/ *$/s', "", $hash);
    return "($name = " . sqlesc($hash) . " OR $name = " . sqlesc($shhash) . ")";
}

function get_user_icons($arr, $big = false)
{
	global $rootpath,$pic_base_url, $lang;
    if ($big)
    {
        $donorpic = "starbig.gif";
        $leechwarnpic = "warnedbig.gif";
        $warnedpic = "warnedbig3.gif";
        $disabledpic = "disabledbig.gif";
        $style = "style='margin-left: 4pt'";
    }
    else
    {
        $donorpic = "star.gif";
        $leechwarnpic = "warned.gif";
        $warnedpic = "warned3.gif";
        $disabledpic = "disabled.gif";
        $style = "style=\"margin-left: 2pt\"";
    }
    $pics = $arr["donor"] == "yes" ? "<img src='".$rootpath.$pic_base_url.$donorpic."' alt='".$lang->global['imgdonated']."' title='".$lang->global['imgdonated']."' border=0 $style>" : "";
    if ($arr["enabled"] == "yes")
        $pics .= ($arr["leechwarn"] == "yes" ? "<img src='".$rootpath.$pic_base_url.$leechwarnpic."' title=\"".$lang->global['imgwarned']."\" alt=\"".$lang->global['imgwarned']."\" border=0 $style>" : "") . ($arr["warned"] == "yes" ? "<img src='".$rootpath.$pic_base_url.$warnedpic."' alt=\"".$lang->global['imgwarned']."\" title=\"".$lang->global['imgwarned']."\" border=0 $style>" : "");
    else
        $pics .= "<img src='".$rootpath.$pic_base_url.$disabledpic."' alt=\"".$lang->global['disabled']."\"  title=\"".$lang->global['disabled']."\" border=0 $style>\n";
    return $pics;
}

function get_percent_completed_image($p) {
	global $rootpath,$pic_base_url;
 $maxpx = "45";

 if ($p == 0) $progress = "<img src=\"".$rootpath.$pic_base_url."progbar-rest.gif\" height=9 width=" . ($maxpx) . " />";
 if ($p == 100) $progress = "<img src=\"".$rootpath.$pic_base_url."progbar-green.gif\" height=9 width=" . ($maxpx) . " />";
 if ($p >= 1 && $p <= 30) $progress = "<img src=\"".$rootpath.$pic_base_url."progbar-red.gif\" height=9 width=" . ($p*($maxpx/100)) . " /><img src=\"".$rootpath.$pic_base_url."progbar-rest.gif\" height=9 width=" . ((100-$p)*($maxpx/100)) . " />";
 if ($p >= 31 && $p <= 65) $progress = "<img src=\"".$rootpath.$pic_base_url."progbar-yellow.gif\" height=9 width=" . ($p*($maxpx/100)) . " /><img src=\"".$rootpath.$pic_base_url."progbar-rest.gif\" height=9 width=" . ((100-$p)*($maxpx/100)) . " />";
 if ($p >= 66 && $p <= 99) $progress = "<img src=\"".$rootpath.$pic_base_url."progbar-green.gif\" height=9 width=" . ($p*($maxpx/100)) . " /><img src=\"".$rootpath.$pic_base_url."progbar-rest.gif\" height=9 width=" . ((100-$p)*($maxpx/100)) . " />";
 return "<img src=\"".$rootpath.$pic_base_url."bar_left.gif\" />" . $progress ."<img src=\"".$rootpath.$pic_base_url."bar_right.gif\" />";
}

//---- Website Settings v0.4 by xam
function ReadConfig ($configname) {
	global $rootpath,$BASEURL;
    if (strstr($configname, ',')) {
        $configlist = explode(',', $configname);
        foreach ($configlist as $key=>$configname) {
            ReadConfig(trim($configname));
        }
    } else {
        $configname = basename($configname);
        $path = $rootpath . 'config/'.$configname;
        if (!file_exists($path)) {
            stderr("ERROR", "<font color=red>File [<b>".htmlspecialchars($configname)."</b>] doesn't exist!.</font><br><font color=blue>Before the setup starts, please ensure that you have properly configured file and directory access permissions. Please see below.</font><br><br>chmod 777 CONFIG (config directory).<br>chmod 777 CONFIG/main (the file which save the main settings).",false);
        }
        $fp = fopen($path, 'r');
        $content = '';
        while (!feof($fp)) {
            $content .= fread($fp, 102400);
        }
        fclose($fp);
        if (empty($content)) {
            if ($configname == 'XAM') {
                Header("Location: $BASEURL/index.php");  				
                die; 
            }
            return array();
        }
        $tmp        = @unserialize($content);
        if (empty($tmp)) {
            if ($configname == 'XAM') {
                Header("Location: $BASEURL/index.php");  				
                die;                
            }
            stderr("ERROR", "<font color=red>Cannot read file [<b>".htmlspecialchars($configname)."</b>]!.</font><br><font color=blue>Before the setup starts, please ensure that you have properly configured file and directory access permissions. Please see below.</font><br><br>chmod 777 CONFIG (config directory).<br>chmod 777 CONFIG/main (the file which save the main settings).",false);
        }
        $GLOBALS[$configname] = $tmp;
        return true;
    }
}

function WriteConfig ($configname, $config) {
	global $rootpath;
    $configname = basename($configname);
    $path = $rootpath . 'config/'.$configname;
    if (!file_exists($path) || !is_writable ($path)) {
        stdmsg("ERROR", "<font color=red>Cannot read file [<b>".htmlspecialchars($configname)."</b>]!.</font><br><font color=blue>Before the setup starts, please ensure that you have properly configured file and directory access permissions. Please see below.</font><br><br>chmod 777 CONFIG (config directory).<br>chmod 777 CONFIG/main (the file which save the main settings).",false);
    }
    $data = @serialize($config);
    if (empty($data)) {
        stdmsg("ERROR", "<font color=red>Cannot serialize file [<b>".htmlspecialchars($configname)."</b>]</font><br><font color=blue>Before the setup starts, please ensure that you have properly configured file and directory access permissions. Please see below.</font><br><br>chmod 777 CONFIG (config directory).<br>chmod 777 CONFIG/main (the file which save the main settings).",false);
    }
    $fp = @fopen ($path, 'w');
    if (!$fp) {
        stdmsg("ERROR", "<font color=red>Cannot open file [<b>".htmlspecialchars($configname)."</b>] to save info!.</font><br><font color=blue>Before the setup starts, please ensure that you have properly configured file and directory access permissions. Please see below.</font><br><br>chmod 777 CONFIG (config directory).<br>chmod 777 CONFIG/main (the file which save the main settings).",false);
    }
    $Res = @fwrite($fp, $data);
    if (empty($Res)) {
        stdmsg("ERROR", "<font color=red>Cannot save info in file (error in serialisation) [<b>".htmlspecialchars($configname)."</b>] to save info!.</font><br><font color=blue>Before the setup starts, please ensure that you have properly configured file and directory access permissions. Please see below.</font><br><br>chmod 777 CONFIG (config directory).<br>chmod 777 CONFIG/main (the file which save the main settings).",false);
    }
    fclose($fp);
    return true;
}

function GetVar ($name) {
    if ( is_array($name) ) {
        foreach ($name as $var) GetVar ($var);
    } else {
        if ( !isset($_REQUEST[$name]) )
            return false;
        if ( get_magic_quotes_gpc() ) {
            $_REQUEST[$name] = ssr($_REQUEST[$name]);
        }
        $GLOBALS[$name] = $_REQUEST[$name];
        return $GLOBALS[$name];
    }
}

function ssr ($arg) {
    if (is_array($arg)) {
        foreach ($arg as $key=>$arg_bit) {
            $arg[$key] = ssr($arg_bit);
        }
    } else {
        $arg = stripslashes($arg);
    }
    return $arg;
}

function parked()
{
       global $CURUSER, $lang;
       if ($CURUSER["parked"] == "yes")
			stderr($lang->global['error'], $lang->global['parked']);
}

//---- gZip Compression by xam v.0.1
function gzip () {
	global $gzipcompress;
	if ( $gzipcompress == 'yes' && @extension_loaded('zlib') && @ini_get('zlib.output_compression') != '1' && @ini_get('output_handler') != 'ob_gzhandler')
	{
		@ob_start('ob_gzhandler');
	}
}

//---- Ban System v0.3 by xam
function IsIPBanned($clientip)
{	
	$res = mysql_query('SELECT value FROM ipbans');
	if (mysql_num_rows($res) >= 1) {
		$getbanip = mysql_fetch_array($res);
		$addresses = explode(' ', preg_replace('/[[:space:]]+/', ' ', trim($getbanip['0'])) );
		if(count($addresses) > 0)
		{ 	
			foreach ( $addresses as $ip )
			{
				if(strpos($ip, '*') === false)
				{
					if($ip == $clientip)
						return true;
				}
				elseif(eregi($ip, $clientip))
					return true;
			}
		}
		return false;
	}else
		return true;
}

//---- MYBB Integration v.0.3 by xam
function get_avatar($userid,$show=false) {
	global $CURUSER,$rootpath,$pic_base_url;
	unset ($avatar);
	$avatar_width_height = '';
	$res = sql_query("SELECT avatar, avatardimensions, avatartype FROM ".TABLE_PREFIX."users WHERE uid = ".sqlesc($userid));
	if (mysql_num_rows($res) >= 1) {
		$post = mysql_fetch_array($res);

		if($post['avatar'])
			{
				$post['avatar'] = htmlspecialchars_uni2($post['avatar']);
				$avatar_dimensions = explode("|", $post['avatardimensions']);
				if($avatar_dimensions[0] && $avatar_dimensions[1])
				{
					$avatar_width_height = "width=\"{$avatar_dimensions[0]}\" height=\"{$avatar_dimensions[1]}\"";
				}
				if($post['avatartype'] == "remote" || strstr(strtolower($post["avatar"]), "http://") !== false)
					$avatar = "<img src=\"$post[avatar]\" alt=\"\" $avatar_width_height />";
				else
					$avatar = "<img src=\"community/".str_replace("./", "", $post["avatar"])."\" $avatar_width_height />";
			}else
				$avatar = "<img src=\"".$rootpath.$pic_base_url."default_avatar.gif\" border=\"0\">";
	}else
		$avatar = "<img src=\"".$rootpath.$pic_base_url."default_avatar.gif\" border=\"0\">";
	if ($CURUSER["avatars"] == "yes" OR $show)
		return $avatar;
	else
		return;
}

function my_setcookiee($name, $value="", $expires="", $httponly=false)
{
	global $mybbuser;
	if($expires == -1)
	{
		$expires = 0;
	}
	else if($expires == "" || $expires == null)
	{
		if(isset($mybbuser['remember']) && $mybbuser['remember'] == "no")
		{
			$expires = 0;
		}
		else
		{
			$expires = TIMENOW + (60*60*24*365); // Make the cookie expire in a years time
		}
	}
	else
	{
		$expires = TIMENOW + intval($expires);
	}
	
	// Versions of PHP prior to 5.2 do not support HttpOnly cookies and IE is buggy when specifying a blank domain so set the cookie manually
	$cookie = "Set-Cookie: {$name}=".urlencode($value);
	if($expires > 0)
	{
		$cookie .= "; expires=".gmdate('D, d-M-Y H:i:s \\G\\M\\T', $expires);
	}
	
	if($httponly == true)
	{
		$cookie .= "; HttpOnly";
	}
	header($cookie, false);
}

function my_unsetcookiee($name)
{
	$expires = -3600;
	my_setcookiee($name, "", $expires);
}

function my_getuid($id='') {

	if (empty($id))
		return false;
	else
		$res = sql_query("SELECT uid FROM ".TABLE_PREFIX."users WHERE uid = ".sqlesc($id));

	if (mysql_num_rows($res) >= 1)
		return true;
	else
		return false;
}

function my_get_userdata ($id='', $select='*') {

	if (empty($id))
		return;
	else
		$res = sql_query("SELECT $select FROM ".TABLE_PREFIX."users WHERE uid = ".sqlesc($id));

	if (mysql_num_rows($res) == 0)
		return;
	else
		$arr = mysql_fetch_array($res);

	if ($select != '*')
		return $arr["$select"];
	else
		return $arr;
	
}

//---- PM STORAGE Mod v.0.3 by xam
function pm_limit ($showlimit = true, $disablepm = false, $userid = '', $class = '') {
	global $lang, $CURUSER, $usergroups;

	if (!$CURUSER OR !$usergroups)
		return false;

	if (!$userid AND !$disablepm)
		$userid = (int)$CURUSER['id'];
	
	if ($disablepm){
		$gid = intval($class) + 1;
		$getamount = sql_query('SELECT pmquote FROM usergroups WHERE gid = '.sqlesc($gid));
		$amount = mysql_fetch_array($getamount);
		$maxpmstorage = (int)$amount['pmquote'];
	}else
		$maxpmstorage = (int)$usergroups['pmquote'];
	
	if ($maxpmstorage == 0)
		return;

	$query = sql_query('SELECT count(*) AS total FROM messages WHERE receiver = '.sqlesc($userid));
	$pmscount = mysql_fetch_array($query);

if ($pmscount['total'] >= $maxpmstorage AND $disablepm)	
	return false;
elseif ($showlimit) {
	if ($pmscount['total'] >= $maxpmstorage) {
		$spaceused = 100;
		$spaceused2 = 0;
		$belowhalf = '';
		$overhalf = '100%';
		$warnmsg = '<table border="0" cellspacing="0" cellpadding="0" class="tborder">
<tr>
<td class="trow1" align="center"><span class="smalltext"><strong><font color="red">'.$lang->global['reached_warning'].'</font></strong><br />'.$lang->global['reached_warning2'].'</span></td>
</tr></table><br>';
	}else{
		$spaceused = $pmscount['total'] / $maxpmstorage * 100;
		$spaceused2 = 100 - $spaceused;
		$warnmsg = '';
		if($spaceused <= "50")
		{
			$belowhalf = round($spaceused, 0)."%";
		}
		else
		{
			$overhalf = round($spaceused, 0)."%";
		}
	}
	$msg = '
<table border="0" cellspacing="0" cellpadding="5" class="tborder" width="100%">
<tr>
<td class="trow1" align="center"><p>'.sprintf($lang->global['pmlimitmsg'], $pmscount['total'], $maxpmstorage).'</p>
<table align=center cellspacing="0" cellpadding="0" width="230" style="border: solid 1px #000000;">
	<tr>
		<td width="'.$spaceused.'" bgcolor="red" align="center">
		<font color=black size=1><strong>'.$overhalf.'</font></span></td>
		<td width="'.$spaceused2.'" bgcolor="green" align="center">
		<font color=black size=1><strong>'.$belowhalf.'</font></span></td>
		<td width="130" align="center"><font color=black size=1><strong>'.$lang->global['pmspace'].'</strong></font></td>
	</tr>
</table></tr></td></table><br>';

	$msg = ($warnmsg ? $warnmsg.$msg : $msg);
	return $msg;
}else
	return true;
}

//---- Warn Donor's Mod v.0.1 by xam
function warn_donor($s,$warnday=3) {
    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"] < $warnday)
        return true;
    else
		return false;
}
function cutename($name,$max=35){	
	return (strlen($name) > $max ? substr(htmlspecialchars(trim($name)), 0, $max) . '...' : $name);
}
?>