<?php
#================================#
#	   TorrentTrader 2.08	     #
#  http://www.torrenttrader.org  #
#--------------------------------#
#	   Modified by BigMax	     #
#================================#

/*/===| Invite update function
function autoinvites($interval, $minlimit, $maxlimit, $minratio, $invites, $maxinvites)
{
	$time	 = gmtime() - ($interval * 86400);
	$minlimit = $minlimit * 1024 * 1024 * 1024;
	$maxlimit = $maxlimit * 1024 * 1024 * 1024;
	$res	  = SQL_Query_exec("SELECT id, username, class, invites FROM users WHERE enabled = 'yes' AND status = 'confirmed' AND downloaded >= $minlimit AND downloaded < $maxlimit AND uploaded / downloaded >= $minratio AND warned = 'no' AND UNIX_TIMESTAMP(invitedate) <= $time");
	if (mysqli_num_rows($res) > 0) {
		while ($arr = mysqli_fetch_assoc($res)) {
			$maxninvites = $maxinvites[$arr['class']];
			if ($arr['invites'] >= $maxninvites)
				continue;
			if (($maxninvites - $arr['invites']) < $invites)
				$invites = $maxninvites - $arr['invites'];
			SQL_Query_exec("UPDATE users SET invites = invites+$invites, invitedate = NOW() WHERE id=$arr[id]");
			write_log("Gave $invites invites to '$arr[username]' - Class: " . get_user_class_name($arr['class']) . "");
		}
	}
}//*/
function do_cleanup()
{
	global $site_config;
	//===| LOCAL TORRENTS - GET PEERS DATA AND UPDATE BROWSE STATS
	//===| DELETE OLD NON-ACTIVE PEERS
	$deadtime = get_date_time(gmtime() - $site_config['announce_interval']);
	SQL_Query_exec("DELETE FROM peers WHERE last_action < '$deadtime'");
	$torrents = array();
	$res	  = SQL_Query_exec("SELECT torrent, seeder, COUNT(*) AS c FROM peers GROUP BY torrent, seeder");
	while ($row = mysqli_fetch_assoc($res)) {
		if ($row["seeder"] == "yes")
			$key = "seeders";
		else
			$key = "leechers";
		$torrents[$row["torrent"]][$key] = $row["c"];
	}
	$res = SQL_Query_exec("SELECT torrent, COUNT(torrent) as c FROM comments WHERE torrent > 0 GROUP BY torrent");
	while ($row = mysqli_fetch_assoc($res)) {
		$torrents[$row["torrent"]]["comments"] = $row["c"];
	}
	$fields = explode(":", "comments:leechers:seeders");
	$res	= SQL_Query_exec("SELECT id, external, seeders, leechers, comments FROM torrents WHERE banned = 'no'");
	while ($row = mysqli_fetch_assoc($res)) {
		$id   = $row["id"];
		$torr = $torrents[$id];
		foreach ($fields as $field) {
			if (!isset($torr[$field]))
				$torr[$field] = 0;
		}
		$update = array();
		foreach ($fields as $field) {
			if ($row["external"] == "no" || $field == "comments") {
				if ($torr[$field] != $row[$field])
					$update[] = "$field = " . $torr[$field];
			}
		}
		if (count($update))
			SQL_Query_exec("UPDATE torrents SET " . implode(",", $update) . " WHERE id = $id");
	}
	
	//===|  LOCAL TORRENTS - MAKE NON-ACTIVE TORRENTS INVISIBLE
	$deadtime = gmtime() - $site_config["max_dead_torrent_time"];
	//SQL_Query_exec("UPDATE torrents SET visible='no' WHERE visible='yes' AND last_action < FROM_UNIXTIME($deadtime) AND seeders = '0' AND external !='yes'");
	SQL_Query_exec("UPDATE torrents SET visible='no' WHERE visible='yes' AND last_action < FROM_UNIXTIME($deadtime) AND seeders = '0' AND leechers = '0' AND external !='yes'");
	
	// Seedbonus
$qry = "SELECT DISTINCT userid as peer, (
SELECT DISTINCT COUNT( torrent )
FROM peers
WHERE seeder = 'yes'  AND userid = peer) AS count
FROM peers WHERE seeder = 'yes'";

$res = SQL_Query_exec($qry);
while ( $row = mysql_fetch_object($res) )
{
SQL_Query_exec("UPDATE users SET seedbonus = seedbonus + '" . ($site_config["bonuspertime"] * $row->count) . "' WHERE id = '" . $row->peer . "'");
}
// End
	
	//===| DELETE PENDING USER ACCOUNTS OVER TIMOUT AGE
	$deadtime = gmtime() - $site_config["signup_timeout"];
	SQL_Query_exec("DELETE FROM users WHERE status = 'pending' AND added < FROM_UNIXTIME($deadtime)");
	
	//===| DELETE OLD LOG ENTRIES
	$ts = gmtime() - $site_config["LOGCLEAN"];
	SQL_Query_exec("DELETE FROM log WHERE added < FROM_UNIXTIME($ts)");
	
	//===| Delete IP Log History
	$tip = gmtime() - $site_config["IPCLEAN"];
	SQL_Query_exec("DELETE FROM iplog WHERE lastused < FROM_UNIXTIME($tip)");
	
	//===| LEECHWARN USERS WITH LOW RATIO
	if ($site_config["ratiowarn_enable"]) {
		if (!$site_config["ratiofree_enable"]) {
			$minratio   = $site_config["ratiowarn_minratio"];
			$downloaded = $site_config["ratiowarn_mingigs"] * 1024 * 1024 * 1024;
			$length	 = $site_config["ratiowarn_daystowarn"];
			# ADD WARNING
			$res = SQL_Query_exec("SELECT id, username FROM users WHERE class < 4 AND enabled = 'yes' AND uploaded / downloaded < $minratio AND downloaded >= $downloaded");
			if (mysqli_num_rows($res) > 0):
				$timenow	= get_date_time();
				$subject	= "Warned for low ratio";
				$reason	 = "You have been warned because of having low ratio. You need to get a ratio at least " . $minratio . " before next " . $length . " days or your account will be disabled.";
				$expiretime = gmdate("Y-m-d H:i:s", gmtime() + (86400 * $length));
				while ($arr = mysqli_fetch_array($res)):
					$a = SQL_Query_exec("SELECT id FROM warnings WHERE userid ='" . $arr["id"] . "' AND type = 'Poor Ratio' AND active = 'yes'");
					if (mysqli_num_rows($a) < 1):
						SQL_Query_exec("INSERT INTO warnings (userid, reason, added, expiry, warnedby, type) VALUES ('" . $arr["id"] . "','" . $subject . "','" . $timenow . "','" . $expiretime . "','0','Poor Ratio')");
						SQL_Query_exec("UPDATE users SET warned='yes' WHERE id='" . $arr["id"] . "'");
						SQL_Query_exec("INSERT INTO messages (sender, receiver, added, subject, msg, poster) VALUES ('0', '" . $arr["id"] . "', '" . $timenow . "', " . sqlesc($subject) . ", " . sqlesc($reason) . ", '0')");
						write_log("<a href='account-details.php?id=" . $arr["id"] . "'>" . $arr["username"] . "</a> has been warned by the Auto Leech System because it has a low ratio");
					endif;
				endwhile;
			endif;
			# REMOVE WARNING
			$res1 = SQL_Query_exec("SELECT id, username FROM users WHERE warned = 'yes' AND enabled = 'yes' AND uploaded / downloaded >= $minratio AND downloaded >= $downloaded");
			if (mysqli_num_rows($res1) > 0):
				$timenow = get_date_time();
				$subject = "Warning for low ratio was removed";
				$reason  = "Your warning for low ratio has been removed. We highly recommend you to keep your ratio above 1.00 or higher at all times for not to be warned again.\n";
				while ($arr1 = mysqli_fetch_array($res1)):
					$a = SQL_Query_exec("SELECT id FROM warnings WHERE userid ='" . $arr1["id"] . "' AND type='Poor Ratio' AND active = 'yes'");
					if (mysqli_num_rows($a) > 0):
						write_log("Auto Leech warning has been removed for: <a href='account-details.php?id=" . $arr1["id"] . "'>" . $arr1["username"] . "</a> because it has rebuilt ratio");
						SQL_Query_exec("UPDATE users SET warned = 'no' WHERE id = '" . $arr1["id"] . "'");
						#SQL_Query_exec("DELETE FROM warnings WHERE userid = $arr1[id] AND type = 'Poor Ratio'");
						SQL_Query_exec("UPDATE warnings SET active = 'no' WHERE userid = $arr1[id] AND type = 'Poor Ratio'");
						SQL_Query_exec("INSERT INTO messages (sender, receiver, added, subject, msg, poster) VALUES ('0', '" . $arr1["id"] . "', '" . $timenow . "', " . sqlesc($subject) . ", " . sqlesc($reason) . ", '0')");
					endif;
				endwhile;
			endif;
			# BAN WARNED USERS
			$res = SQL_Query_exec("SELECT users.id, users.username, UNIX_TIMESTAMP(warnings.expiry) AS expiry FROM users INNER JOIN warnings ON users.id = warnings.userid WHERE type = 'Poor Ratio' AND active = 'yes' AND class < 4 AND enabled = 'yes' AND warned = 'yes' AND uploaded / downloaded < $minratio AND downloaded >= $downloaded");
			if (mysqli_num_rows($res) > 0) {
				$timenow = get_date_time();
				$expires = (86400 * $length);
				while ($arr = mysqli_fetch_assoc($res)) {
					if (gmtime() - $arr["expiry"] >= 0) {
						SQL_Query_exec("UPDATE users SET enabled= 'no', warned= 'no' WHERE id='" . $arr["id"] . "'");
						write_log("<a href='account-details.php?id=" . $arr["id"] . "'>" . $arr["username"] . "</a> account has been disabled by the <b>Auto Leech Warning System</b>");
					}
				}
			}
		}
	}
	//===| END LEECHWARN USERS WITH LOW RATIO
	
	//===| REMOVE WARNINGS
	$res = SQL_Query_exec("SELECT users.id, users.username, warnings.expiry FROM users INNER JOIN warnings ON users.id = warnings.userid WHERE type != 'Poor Ratio' AND type != 'HnR' AND warned = 'yes'  AND enabled='yes' AND warnings.active = 'yes' AND warnings.expiry < '" . get_date_time() . "'");
	while ($arr1 = mysqli_fetch_assoc($res)) {
		SQL_Query_exec("UPDATE users SET warned = 'no' WHERE id = $arr1[id]");
		SQL_Query_exec("UPDATE warnings SET active = 'no' WHERE userid = $arr1[id] AND expiry < '" . get_date_time() . "'");
		write_log("Removed warning for $arr1[username]. Expiry: $arr1[expiry]");
	}
	//===| WARN USERS THAT STILL HAVE ACTIVE WARNINGS
	SQL_Query_exec("UPDATE users SET warned = 'yes' WHERE warned = 'no' AND id IN (SELECT userid FROM warnings WHERE active = 'yes')");
	//===| END
	
	/*/===| START INVITES UPDATE
	# SET INVITE AMOUNTS ACCORDING TO RATIO/GIGS ETC
	# autoinvites(interval to give invites (days), min downloaded GB, max downloaded GB, min ratio, invites to give, max invites allowed (array))
	# $maxinvites[CLASS ID] = max # of invites;
	$maxinvites[1]  = 2; // User
	$maxinvites[2]  = 5; // Power User
	$maxinvites[3]  = 10; // Elite User
	$maxinvites[4]  = 20; // VIP
	$maxinvites[5]  = 30; // Uploader
	$maxinvites[6]  = 50; // Moderator
	$maxinvites[7]  = 50; // Super Moderator
	$maxinvites[8]  = 50; // Administrator
	$maxinvites[9]  = 50; // Team Leader
	$maxinvites[10] = 50; // Owner
	# Give 1 invite every 28 days to users with > 1GB downloaded AND < 4GB uploaded AND ratio > 0.50
	autoinvites(28, 1, 4, 0.50, 1, $maxinvites);
	autoinvites(21, 1, 4, 0.70, 2, $maxinvites);
	autoinvites(14, 4, 7, 0.90, 2, $maxinvites);
	$maxinvites[1] = 5; // User
	autoinvites(14, 7, 10, 1.00, 3, $maxinvites);
	$maxinvites[1] = 10; // User
	autoinvites(14, 10, 100000, 1.05, 4, $maxinvites);
	//===| END INVITES UPDATE //*/
	
	//===| Start member of the month
	if ($site_config['MOTM']) {
		$debug	   = 0;
		$motmdateget = SQL_Query_exec("SELECT win_month,year,credit from motm WHERE last_winner ='1'");
		$motmdategot = mysqli_fetch_array($motmdateget);
		$motmdate	= (int) $motmdategot[0];
		$motmyear	= $motmdategot[1];
		$mdate	   = date("m");
		$myear	   = date("y");
		if ($motmdate == 12 && $mdate > 1)
			$motmdate = 1;
		if ($motmdate == 0 || $motmdate == '')
			$motmdate = (date("m") - 1);
		$mdate1 = (date("m") - 1);
		if ($motmdate < $mdate) {
			$motmdateget1	  = SQL_Query_exec("SELECT win_month,year,credit from motm WHERE win_month = '$mdate'");
			$motmdategot1	  = mysqli_fetch_array($motmdateget1);
			$motcredit		 = $motmdategot1[2];
			$sql32			 = "SELECT id, points FROM motm WHERE points > '0' && year =" . $myear . " && month =" . $motmdate . " ORDER BY points DESC LIMIT 1";
			$mysqli_result_motm = SQL_Query_exec($sql32);
			while ($row_motm = mysqli_fetch_array($mysqli_result_motm)) {
				$nextmonth	= (date(m) + 1);
				$id_motm	  = $row_motm['id'];
				$pos		  = $row_motm["points"];
				$motmdateget3 = SQL_Query_exec("SELECT win_month from motm WHERE last_winner ='1'");
				$motmdategot3 = mysqli_fetch_array($motmdateget3);
				$motmdate3	= $motmdategot3[0];
				if ($motmdate3 == 12 && $mdate > 1)
					$motmdate3 = 1;
				if ($motmdate3 == 0 || $motmdate3 == '')
					$motmdate3 = (date("m") - 1);
				if ($motcredit != 'yes') {
					SQL_Query_exec("UPDATE motm SET last_winner = '0' WHERE last_winner = '1'");
					SQL_Query_exec("UPDATE motm SET win_month = '$mdate', last_winner_points = '$pos', last_winner = '1', credit='yes' WHERE id = '$id_motm' && month = $motmdate && year = " . $myear . "");
					SQL_Query_exec("UPDATE users SET seedbonus = seedbonus+1000 WHERE id = '$id_motm'");
					// SQL_Query_exec("UPDATE motm SET points = '0' where month!='$mdate'");
					SQL_Query_exec("UPDATE motm SET last_winner_points = '0' WHERE last_winner != '1'");
				} //$motcredit != 'yes'
			} //$row_motm = mysqli_fetch_array($mysqli_result_motm)
		} //$motmdate < $mdate
	}
	//===| End member of the month
	
	//===| Start Update users total seed time
	if ($site_config["ratiofree_enable"]) {
		$tstu = SQL_Query_exec("SELECT id, seedtime, lasttime FROM users WHERE enabled = 'yes'");
		while ($row = mysqli_fetch_assoc($tstu)) {
			$suid	 = $row["id"];
			$lasttime = $row["lasttime"];
			$seedtime = $row["seedtime"];
			$tst	  = SQL_Query_exec("SELECT (SUM(ltime)) AS totalseedtime FROM snatched WHERE uid = '$suid'");
			while ($row = mysqli_fetch_assoc($tst)) {
				$tstime = $row[totalseedtime];
				if (!$tstime)
					$tstime = 0;
				SQL_Query_exec("UPDATE users SET lasttime = $tstime WHERE id = $suid");
				$seeddif = $tstime - $lasttime;
				if ($seeddif < 1)
					$seeddif = 0;
				SQL_Query_exec("UPDATE users SET seedtime = $seedtime + $seeddif WHERE id = $suid");
			}
		}
	}
	//===| End Update users total seed time
   
   //===| Start Anti Hit and Run System
	if ($site_config['HNR']) {
		# Add H&R
		if (!$site_config["ratiofree_enable"]) {
			SQL_Query_exec("UPDATE snatched SET hnr = 'yes' WHERE hnr = 'no' AND done='no' AND uload < dload AND dload > $site_config[hnr_min_dload] AND ltime < $site_config[hnr_seedtime]");
		} else {
			SQL_Query_exec("UPDATE snatched SET hnr = 'yes' WHERE hnr = 'no' AND done='no' AND dload > $site_config[hnr_min_dload] AND ltime < $site_config[hnr_seedtime]");
		}
		# Remove H&R for users that meet seeding requirements
		if (!$site_config["ratiofree_enable"]) {
			SQL_Query_exec("UPDATE snatched SET hnr = 'no', done='yes' WHERE hnr = 'yes' AND done='no' AND uload >= dload AND ltime >= $site_config[hnr_seedtime]");
		}
		SQL_Query_exec("UPDATE snatched SET hnr = 'no', done='yes' WHERE hnr = 'yes' AND done='no' AND ltime >= $site_config[hnr_seedtime]");
		# Get user H&R data from snatched
		$a = SQL_Query_exec("SELECT DISTINCT uid FROM snatched WHERE hnr = 'yes' AND done = 'no'");
		if (mysqli_num_rows($a) > 0) {
			while ($b = mysqli_fetch_row($a)) {
				$user = $b[0];
				# Remove H&R for users that are at seeding
				$c	= SQL_Query_exec("SELECT tid FROM snatched WHERE uid = $user");
				while ($d = mysqli_fetch_row($c)) {
					$torrent = $d[0];
					$e	   = SQL_Query_exec("SELECT seeder FROM peers WHERE userid = $user AND torrent = $torrent");
					$f	   = mysqli_fetch_row($e);
					$seeder  = $f[0];
					if ($seeder == "yes") {
						SQL_Query_exec("UPDATE snatched SET hnr = 'no' WHERE hnr = 'yes' AND uid = $user AND tid = $torrent");
					}
				}
			}
		}
	}
	//===| End Anti Hit and Run System
	
	//===| OPTIMIZE TABLES
	$res = SQL_Query_exec("SHOW TABLES");
	while ($table = mysqli_fetch_row($res)) {
		// Get rid of overhead.
		SQL_Query_exec("REPAIR TABLE `$table[0]`;");
		// Analyze table for faster indexing.
		SQL_Query_exec("ANALYZE TABLE `$table[0]`;");
		// Optimize table to minimize thrashing.
		SQL_Query_exec("OPTIMIZE TABLE `$table[0]`;");
	}
	
	//===| Seedbonus
	$qry = "SELECT DISTINCT userid as peer, ( SELECT DISTINCT COUNT( torrent ) FROM peers WHERE seeder = 'yes' AND userid = peer) AS count FROM peers WHERE seeder = 'yes'";
	$res = SQL_Query_exec($qry);
	while ($row = mysqli_fetch_object($res)) 
	{
		SQL_Query_exec("UPDATE users SET seedbonus = seedbonus + '" . ($site_config["bonuspertime"] * $row->count) . "' WHERE id = '" . $row->peer . "'");
	}
	//===| End
	
	//===| Start deleting expired bans on shoutbox
	$res31 = SQL_Query_exec("SELECT id FROM users WHERE hideshoutbox='yes' AND hideshoutboxuntil < '" . get_date_time() . "' AND hideshoutboxuntil <> '0000-00-00 00:00:00'");
	if (mysqli_num_rows($res31) > 0) {
		$dt  = sqlesc(get_date_time());
		$msg = sqlesc("Your ban on shoutbox has been removed.\n");
		while ($arr31 = mysqli_fetch_assoc($res31)) {
			SQL_Query_exec("UPDATE users SET hideshoutbox = 'no', hideshoutboxuntil = '0000-00-00 00:00:00' WHERE id = $arr31[id]");
			SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, poster) VALUES(0, $arr31[id], $dt, $msg, 0)");
		}
	}
	//===| End deleting expired bans on shoutbox
	
	//===| Start deleting expired bans to PMs
	$respm = SQL_Query_exec("SELECT id FROM users WHERE pmbanned='yes' AND pmbanneduntil < '" . get_date_time() . "' AND pmbanneduntil <> '0000-00-00 00:00:00'");
	if (mysqli_num_rows($respm) > 0) {
		$dt  = sqlesc(get_date_time());
		$msg = sqlesc("Your ban on PMs has been removed.\n");
		while ($arrpm = mysqli_fetch_assoc($respm)) {
			SQL_Query_exec("UPDATE users SET pmbanned = 'no', pmbanneduntil = '0000-00-00 00:00:00' WHERE id = $arrpm[id]");
			SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, poster) VALUES(0, $arrpm[id], $dt, $msg, 0)");
		}
	}
	//===| End deleting expired bans to PMs
	
	//===| Start deleting expired bans on forum
	$res32 = SQL_Query_exec("SELECT id FROM users WHERE forumbanned='yes' AND forumbanneduntil < '" . get_date_time() . "' AND forumbanneduntil <> '0000-00-00 00:00:00'");
	if (mysqli_num_rows($res32) > 0) {
		$dt  = sqlesc(get_date_time());
		$msg = sqlesc("Your ban on forum has been removed.\n");
		while ($arr32 = mysqli_fetch_assoc($res32)) {
			SQL_Query_exec("UPDATE users SET forumbanned = 'no', forumbanneduntil = '0000-00-00 00:00:00' WHERE id = $arr32[id]");
			SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, poster) VALUES(0, $arr32[id], $dt, $msg, 0)");
		}
	}
	//===| End deleting expired bans on forum
	
	//===| Start deleting expired bans at comments
	$res33 = SQL_Query_exec("SELECT id FROM users WHERE commentbanned='yes' AND commentbanneduntil < '" . get_date_time() . "' AND commentbanneduntil <> '0000-00-00 00:00:00'");
	if (mysqli_num_rows($res33) > 0) {
		$dt  = sqlesc(get_date_time());
		$msg = sqlesc("Your ban at comments has been removed.\n");
		while ($arr33 = mysqli_fetch_assoc($res33)) {
			SQL_Query_exec("UPDATE users SET commentbanned = 'no', commentbanneduntil = '0000-00-00 00:00:00' WHERE id = $arr33[id]");
			SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, poster) VALUES(0, $arr33[id], $dt, $msg, 0)");
		}
	}
	//===| End deleting expired bans at comments
	
	//===| Remove unconfirmed Invites
	$deadtime = gmtime() - $site_config["invite_timeout"];
	$res	  = SQL_Query_exec("SELECT u.id, u.invited_by, u.added, i.invitees FROM users u LEFT JOIN users i ON u.invited_by = i.id WHERE u.status = 'pending' AND u.invited_by != '0' AND u.added < FROM_UNIXTIME($deadtime)");
	while ($row = mysqli_fetch_assoc($res)) {
		# We remove the invitee from the inviter and give them back there invite
		$invitees = str_replace("$row[id] ", "", $row["invitees"]);
		SQL_Query_exec("UPDATE `users` SET `invites` = `invites` + 1, `invitees` = '$invitees' WHERE `id` = '$row[invited_by]'");
		SQL_Query_exec("DELETE FROM `users` WHERE `id` = '$row[id]'");
	}
	//=== End
	
	//===| Start Auto Promote/Demote Users
	if (!$site_config["ratiofree_enable"]) {
		//===| config
		$gigs	  = 50 * 1073741824; # 50 GB  / Upload to promote Power Users
		$gigs2	 = 3000 * 1073741824; # 3000 GB / Upload to promote Elite Users
		$minratio  = 0.95; # Ratio to demote Power Users
		$minratio2 = 1.55; # Ratio to demote Elite Users
		$delay	 = sqlesc(get_date_time(gmtime() - 86400 * 30)); # Joined > 4 week  / for Power Users
		$delay2	= sqlesc(get_date_time(gmtime() - 86400 * 180)); # Joined > 6 month / for Elite Users
		//===| auto promote power users
		$res	   = SQL_Query_exec("SELECT id, username, modcomment FROM users WHERE class = 1 AND warned = 'no' AND added < $delay AND uploaded >= $gigs AND uploaded >= downloaded");
		$time	  = get_date_time();
		while ($arr = mysqli_fetch_assoc($res)) {
			$username	= $arr[username];
			$modcomment  = $arr[modcomment];
			$modcomment2 = gmdate("d-M-Y") . " - Has been promoted by System to Power User class \n";
			$modcomment  = $modcomment2 . "" . $modcomment;
			$modcom	  = sqlesc($modcomment);
			SQL_Query_exec("UPDATE users SET class = 2, modcomment = CONCAT($modcom,modcomment) WHERE id = $arr[id]");
			SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES(0, $arr[id], '$time', '[b]Congratulations[/b], you were automatically promoted to [b]Power User[/b] class. Please note that if your ratio drops below [b]" . $minratio . "[/b] at any time, you will be demoted back to [b]User[/b]', 'You have been promoted as Power User')");
			write_log("<a href=account-details.php?id=$arr[id]><b>$username</b></a> has been promoted by System to <b>Power User</b> class");
		}
		//===| auto demote power users
		$res = SQL_Query_exec("SELECT id, username, modcomment FROM users WHERE class = 2  AND uploaded / downloaded < $minratio");
		while ($arr = mysqli_fetch_assoc($res)) {
			$username	= $arr[username];
			$modcomment  = $arr[modcomment];
			$modcomment2 = gmdate("d-M-Y") . " - Has been demoted by System to User class \n";
			$modcomment  = $modcomment2 . "" . $modcomment;
			$modcom	  = sqlesc($modcomment);
			SQL_Query_exec("UPDATE users SET class = 1, modcomment = CONCAT($modcom,modcomment) WHERE id = $arr[id]");
			SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES(0, $arr[id], '$time', 'You were automatically demoted as [b]User[/b]. That happened because your ratio dropped below [b]" . $minratio . "[/b]', 'You have been demoted as User')");
			write_log("<a href=account-details.php?id=$arr[id]><b>$username</b></a> has been demoted by System to <b>User</b> class");
		}
		//===| auto promote elite users
		$res  = SQL_Query_exec("SELECT id, username, modcomment FROM users WHERE class = 2 AND warned = 'no' AND added < $delay2 AND uploaded >= $gigs2 AND uploaded >= (2*downloaded)");
		$time = get_date_time();
		while ($arr = mysqli_fetch_assoc($res)) {
			$username	= $arr[username];
			$modcomment  = $arr[modcomment];
			$modcomment2 = gmdate("d-M-Y") . " - Has been promoted by System to Elite User class \n";
			$modcomment  = $modcomment2 . "" . $modcomment;
			$modcom	  = sqlesc($modcomment);
			SQL_Query_exec("UPDATE users SET class = 3, modcomment = CONCAT($modcom,modcomment) WHERE id = $arr[id]");
			SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES(0, $arr[id], '$time', '[b]Congratulations[/b], you were automatically promoted to [b]Elite User[/b] class. Please note that if your ratio drops below [b]" . $minratio2 . "[/b] at any time, you will be demoted back to [b]Power User[/b]', 'You have been promoted as Elite User')");
			write_log("<a href=account-details.php?id=$arr[id]><b>$username</b></a> has been promoted by System to <b>Elite User</b> class");
		}
		//===| auto demote elite users
		$res = SQL_Query_exec("SELECT id, username, modcomment FROM users WHERE class = 3  AND uploaded / downloaded < $minratio2");
		while ($arr = mysqli_fetch_assoc($res)) {
			$username	= $arr[username];
			$modcomment  = $arr[modcomment];
			$modcomment2 = gmdate("d-M-Y") . " - Has been demoted by System to Power User class \n";
			$modcomment  = $modcomment2 . "" . $modcomment;
			$modcom	  = sqlesc($modcomment);
			SQL_Query_exec("UPDATE users SET class = 2, modcomment = CONCAT($modcom,modcomment) WHERE id = $arr[id]");
			SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES(0, $arr[id], '$time', 'You were automatically demoted as [b]Power User[/b]. That happened because your ratio dropped below [b]" . $minratio2 . "[/b]', 'You have been demoted as Power User')");
			write_log("<a href=account-details.php?id=$arr[id]><b>$username</b></a> has been demoted by System to <b>Power User</b> class");
		}
	} else {
		//===| config
		$seedp	= 86400 * 30; # 30  days of Seed Time to promote as Power User
		$mintimep = mkprettytime($seedp);
		$seede	= 86400 * 180; # 180 days of Seed Time to promote as Elite User
		$mintimee = mkprettytime($seede);
		//===| auto promote power users
		$res	  = SQL_Query_exec("SELECT id, username, seedtime, modcomment FROM users WHERE class = 1 AND warned = 'no' AND seedtime >= $seedp");
		$time	 = get_date_time();
		while ($arr = mysqli_fetch_assoc($res)) {
			$username	= $arr[username];
			$modcomment  = $arr[modcomment];
			$modcomment2 = gmdate("d-M-Y") . " - Has been promoted by System to Power User class \n";
			$modcomment  = $modcomment2 . "" . $modcomment;
			$modcom	  = sqlesc($modcomment);
			SQL_Query_exec("UPDATE users SET class = 2, modcomment = CONCAT($modcom,modcomment) WHERE id = $arr[id]");
			SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES(0, $arr[id], '$time', '[b]Congratulations[/b], you were automatically promoted to [b]Power User[/b] class. Please note that if your Seed Time drops below [b]" . $mintimep . "[/b] at any time, you will be demoted back to [b]User[/b]', 'You have been promoted as Power User')");
			write_log("<a href=account-details.php?id=$arr[id]><b>$username</b></a> has been promoted by System to <b>Power User</b> class");
		}
		//===| auto demote power users
		$res = SQL_Query_exec("SELECT id, username, seedtime, modcomment FROM users WHERE class = 2  AND seedtime < $seedp");
		while ($arr = mysqli_fetch_assoc($res)) {
			$username	= $arr[username];
			$modcomment  = $arr[modcomment];
			$modcomment2 = gmdate("d-M-Y") . " - Has been demoted by System to User class \n";
			$modcomment  = $modcomment2 . "" . $modcomment;
			$modcom	  = sqlesc($modcomment);
			SQL_Query_exec("UPDATE users SET class = 1, modcomment = CONCAT($modcom,modcomment) WHERE id = $arr[id]");
			SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES(0, $arr[id], '$time', 'You were automatically demoted as [b]User[/b]. That happened because your Seed Time dropped below [b]" . $mintimep . "[/b]', 'You have been demoted as User')");
			write_log("<a href=account-details.php?id=$arr[id]><b>$username</b></a> has been demoted by System to <b>User</b> class");
		}
		//===| auto promote elite users
		$res  = SQL_Query_exec("SELECT id, username, seedtime, modcomment FROM users WHERE class = 2 AND warned = 'no' AND seedtime >= $seede");
		$time = get_date_time();
		while ($arr = mysqli_fetch_assoc($res)) {
			$username	= $arr[username];
			$modcomment  = $arr[modcomment];
			$modcomment2 = gmdate("d-M-Y") . " - Has been promoted by System to Elite User class \n";
			$modcomment  = $modcomment2 . "" . $modcomment;
			$modcom	  = sqlesc($modcomment);
			SQL_Query_exec("UPDATE users SET class = 3, modcomment = CONCAT($modcom,modcomment) WHERE id = $arr[id]");
			SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES(0, $arr[id], '$time', '[b]Congratulations[/b], you were automatically promoted to [b]Elite User[/b] class. Please note that if your Seed Time drops below [b]" . $mintimee . "[/b] at any time, you will be demoted back to [b]Power User[/b]', 'You have been promoted as Elite User')");
			write_log("<a href=account-details.php?id=$arr[id]><b>$username</b></a> has been promoted by System to <b>Elite User</b> class");
		}
		//===| auto demote elite users
		$res = SQL_Query_exec("SELECT id, username, seedtime, modcomment FROM users WHERE class = 3  AND seedtime < $seede");
		while ($arr = mysqli_fetch_assoc($res)) {
			$username	= $arr[username];
			$modcomment  = $arr[modcomment];
			$modcomment2 = gmdate("d-M-Y") . " - Has been demoted by System to Power User class \n";
			$modcomment  = $modcomment2 . "" . $modcomment;
			$modcom	  = sqlesc($modcomment);
			SQL_Query_exec("UPDATE users SET class = 2, modcomment = CONCAT($modcom,modcomment) WHERE id = $arr[id]");
			SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, subject) VALUES(0, $arr[id], '$time', 'You were automatically demoted as [b]Power User[/b]. That happened because your Seed Time dropped below [b]" . $mintimee . "[/b]', 'You have been demoted as Power User')");
			write_log("<a href=account-details.php?id=$arr[id]><b>$username</b></a> has been demoted by System to <b>Power User</b> class");
		}
	}
	//===| End Auto Promote/Demote Users
	
	//===| Start Delete Inactive Torrents
	//---| Delete External Torrents ->
	if ($site_config["DEL_DEAD_EXT_TOR"]) {
		if ($site_config["ALLOWEXTERNAL"]) {
			$exdays = 1096; // Days to delete external torrents
			$dte	= sqlesc(get_date_time(gmtime() - ($exdays * 86400)));
			//-> Delete if seeders = 0
			// $res = SQL_Query_exec("SELECT id, name FROM torrents WHERE last_action < $dt AND seeders = '0' AND external !='no'");
			//-> Delete all torrents
			$res	= SQL_Query_exec("SELECT id, name FROM torrents WHERE last_action < $dte AND external !='no'");
			while ($arr = mysqli_fetch_assoc($res)) {
				$torrentid = $arr[id];
				write_log("External Torrent: <b>$arr[name]</b> | ID: <b>$arr[id]</b> | was deleted by System because has expired</b>");
				deletetorrent($torrentid);
			}
		}
	}
	//---| Delete Local Torrents ->
	if ($site_config["DEL_DEAD_LOC_TOR"]) {
		$locdays = 30; // Days to delete local torrents
		$dtl	 = sqlesc(get_date_time(gmtime() - ($locdays * 86400)));
		$res	 = SQL_Query_exec("SELECT id, name FROM torrents WHERE last_action < $dtl AND seeders = '0' AND external ='no'");
		while ($arr = mysqli_fetch_assoc($res)) {
			$torrentid = $arr[id];
			write_log("Local Torrent: <b>$arr[name]</b> | ID: <b>$arr[id]</b> | was deleted by System because is dead by over $locdays days</b>");
			deletetorrent($torrentid);
		}
	}
	//===| End Delete Inactive Torrents
	
	//===| Start Set fake values to external torrents (where they stats was not readed)
	$fake_completed = mt_rand(50, 500);
	$fake_leechers  = mt_rand(5, 50);
	$fake_seeders   = mt_rand(15, 150);
	$res			= SQL_Query_exec("SELECT id, external, times_completed, leechers, seeders FROM torrents WHERE banned = 'no' AND seeders = '0' AND external = 'yes'");
	while ($row = mysqli_fetch_assoc($res)) {
		$id = $row["id"];
		SQL_Query_exec("UPDATE torrents SET times_completed = $fake_completed, leechers = $fake_leechers, seeders = $fake_seeders WHERE id = $id");
	}
	//===| End Set fake values to external torrents //*/
	
	/*/===| Automatically sets all local torrents as free by size
	$torsize = 3 * 1073741824;		//==| GB limit
	SQL_Query_exec("UPDATE torrents SET freeleech = '0' WHERE size < $torsize AND external != 'yes'");
	SQL_Query_exec("UPDATE torrents SET freeleech = '1' WHERE size >= $torsize AND external != 'yes'");
	//===| End //*/
	
	/*/===| Automatically sets all local torrents as freeleech
	SQL_Query_exec("UPDATE torrents SET freeleech = '1' WHERE external != 'yes'");
	//===| End //*/
	
	//===| Automatically sets all external torrents as freeleech
	SQL_Query_exec("UPDATE torrents SET freeleech = '1' WHERE external = 'yes'");
	//===| End //*/
	
	/*/---| Change torrents category by size (Bluray to HD)
	$torsize = 15 * 1073741824; // Torrent size (in GB)
	$resb = SQL_Query_exec("SELECT id, size, category FROM torrents WHERE size < $torsize AND category = '26'");
	while ($arrb = mysqli_fetch_assoc($resb))
	{
		$tid = $arrb[id];
		SQL_Query_exec("UPDATE torrents SET category = '42' WHERE id = $tid");
	} //*/
	
	//===| Remove donor status if time up and set class to elite user
	$res = SQL_Query_exec("SELECT id, class, modcomment FROM users WHERE donor='yes' AND donoruntil < NOW() AND donoruntil <> '0000-00-00 00:00:00'");
	if (mysqli_num_rows($res) > 0) {
		$dt	  = sqlesc(get_date_time());
		$subject = sqlesc("VIP status removed by System.");
		$msg	 = sqlesc("Your VIP status has timed out and has been auto-removed by System. We would like to thank you once again for supporting " . $site_config['SITENAME'] . ". If you wish to re-new your VIP, you can do so by clicking [url=" . $site_config['SITEURL'] . "/donate_2.php][u]HERE[/u][/url]. Cheers!\n");
		while ($arr = mysqli_fetch_assoc($res)) {
			//--- Autosystem modcomment
			$modcomment = htmlspecialchars($arr["modcomment"]);
			$modcomment = gmdate("d-M-Y H:i") . " - VIP status removed by System.\n" . $modcomment;
			$modcom	 = sqlesc($modcomment);
			if ($arr["class"] > 4) {
				SQL_Query_exec("UPDATE users SET donor = 'no', donoruntil = '0000-00-00 00:00:00', modcomment = $modcom WHERE id = $arr[id]");
			} else {
				SQL_Query_exec("UPDATE users SET class = '3', donor = 'no', donoruntil = '0000-00-00 00:00:00', modcomment = $modcom WHERE id = $arr[id]");
			}
			SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, subject, poster) VALUES(0, $arr[id], $dt, $msg, $subject, 0)");
		}
	}
	
	//===| Clear funds after one month
	$secs = 30 * 86400;
	$dt   = sqlesc(get_date_time(gmtime() - $secs));
	SQL_Query_exec("DELETE FROM funds WHERE added < $dt");
	//===| End
	
	//===| Delete old recordings of reputation
	$delaytime = 1 * 3600;
	$delayed   = sqlesc(get_date_time(gmtime() - $delaytime));
	SQL_Query_exec("DELETE FROM simpaty WHERE respect_time < $delayed");
	//===| End
	
	//===| Delete old private messages
	$messages = gmtime() - 30 * 86400;
	SQL_Query_exec("DELETE FROM messages WHERE added < FROM_UNIXTIME($messages)");
	//===| End
	
	//===| Delete old messages from shoutbox
	$shoutmes = gmtime() - 7 * 86400;
	SQL_Query_exec("DELETE FROM shoutbox WHERE date < FROM_UNIXTIME($shoutmes)");
	//===| End
	
	//===| Start Delete Inactive Accounts |===//
	//===| Config
	$dtd	  = 365; //===| Days until the inactive accounts are disabled
	$ddd	  = 90; //===| Days until the disabled accounts are deleted
	$dnl	  = 7; //===| days to delete users who have not ever logged
	$deletina = sqlesc(get_date_time(gmtime() - ($dtd * 86400)));
	$deletdis = sqlesc(get_date_time(gmtime() - ($ddd * 86400)));
	$delnolog = sqlesc(get_date_time(gmtime() - ($dnl * 86400)));
	//===| Delete inactive accounts
	if ($site_config["DEL_INA_USERS"]) {
		$res4 = SQL_Query_exec("SELECT id, username FROM users WHERE id > '100' AND class < '4' AND last_access != '0000-00-00 00:00:00' AND last_access < $deletina");
		while ($arr4 = mysqli_fetch_assoc($res4)) {
			$userid = $arr4["id"];
			write_log("<b>$arr4[username]</b> account was deleted by System because has been inactive by over $dtd days");
			deleteaccount($userid);
		}
	}
	
	/*/===| Delete disabled accounts
	if ($site_config["DEL_DIS_USERS"]) {
	$res5 = SQL_Query_exec("SELECT id, username FROM users WHERE enabled = 'no' AND id > '100' AND class < '4' AND last_access != '0000-00-00 00:00:00' AND last_access < $deletdis");
	while ($arr5 = mysqli_fetch_assoc($res5))
		{
			$userid = $arr5["id"];
			write_log("<b>$arr5[username]</b> account was deleted by System because has been disabled by over $ddd days");
			deleteaccount($userid);
		}
	} //*/
	
	//===| Delete users who have not ever logged
	$res6 = SQL_Query_exec("SELECT id, username FROM users WHERE last_access = '0000-00-00 00:00:00' AND added < $delnolog");
	while ($arr6 = mysqli_fetch_assoc($res6)) {
		$userid = $arr6["id"];
		write_log("<b>$arr6[username]</b> account was deleted by System because has joined by over $dnl days but not ever login");
		deleteaccount($userid);
	}
	//===| End Delete Inactive Accounts |===//*/


	/*/===| Special tasks to run only once |===///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	---| Change all users theme to default
	SQL_Query_exec("UPDATE users SET stylesheet = 9 WHERE stylesheet >= 1"); /*/


} //===| End do_cleanup function
?>
