<?php
/*
////////////////////////////////////////////////////////////////////////////
//                                                                        //
//                     Ralphie BitTorrent Tracker                         //
//                                                                        //
////////////////////////////////////////////////////////////////////////////
//                                                                        //
// This File is part of NVTracker and TBTracker is based on BTSource,     //
// originally by RedBeard of TorrentBits, extensively modified by         //
// Ralphie                                                                //
//                                                                        //
////////////////////////////////////////////////////////////////////////////
//                                                                        //
// Obige Zeilen dürfen nicht enfernt werden!   Do not remove above lines! //
//                                                                        //
////////////////////////////////////////////////////////////////////////////
 */

require_once("include/bittorrent.php");

function docleanup()
{
    set_time_limit(0);
    ignore_user_abort(1);

    while (1) {
        // Collect all torrent ids from database
        $res = mysql_query("SELECT id FROM torrents");
        $all_torrents = array();
        while ($row = mysql_fetch_array($res)) {
            $id = $row[0];
            $all_torrents[$id] = 1;
        }
    
        // Open torrent directory for scanning
        $dp = @opendir($GLOBALS["TORRENT_DIR"]);
        if (!$dp)
            break;
    
        // Collect all .torrent files matching "id.torrent" filename pattern
        $all_files = array();
        while (($file = readdir($dp)) !== false) {
            if (!preg_match('/^(\d+)\.torrent$/', $file, $m))
                continue;
            $id = $m[1];
            $all_files[$id] = 1;
            
            // If no database entry exists, delete the orphaned file
            if (!isset($all_torrents[$id]) || $all_torrents[$id] == 0)
                unlink($GLOBALS["TORRENT_DIR"] . "/$file");
        }
        closedir($dp);
    
        // Open bitbucket directory for scanning
        $dp = @opendir($GLOBALS["BITBUCKET_DIR"]);
        if (!$dp)
            break;
    
        // Collect all NFO files matching "nfo-id.png" filename pattern
        while (($file = readdir($dp)) !== false) {
            if (!preg_match('/^nfo-(\d+)\.png$/', $file, $m))
                continue;
            $id = $m[1];
            
            // If no database entry exists, delete the orphaned file
            if (!isset($all_torrents[$id]) || $all_torrents[$id] == 0)
                unlink($GLOBALS["BITBUCKET_DIR"] . "/$file");
        }
        closedir($dp);
        
        // No torrents or files to consider
        if (!count($all_torrents) && !count($all_files))
            break;
    
        // Enumerate and delete torrents which have no according .torrent file
        $delids = array();
        foreach (array_keys($all_torrents) as $k) {
            if (isset($all_files[$k]) && $all_files[$k])
                continue;
            $delids[] = $k;
            unset($all_torrents[$k]);
        }
        if (count($delids))
            mysql_query("DELETE FROM torrents WHERE id IN (" . join(",", $delids) . ")");
    
        // Enumerate and delete peers which have no according torrent in the DB
        $res = mysql_query("SELECT torrent FROM peers GROUP BY torrent");
        $delids = array();
        while ($row = mysql_fetch_array($res)) {
            $id = $row[0];
            if (isset($all_torrents[$id]) && $all_torrents[$id])
                continue;
            $delids[] = $id;
        }
        if (count($delids))
            mysql_query("DELETE FROM peers WHERE torrent IN (" . join(",", $delids) . ")");
    
        // Enumerate and delete file entries which have no according torrent in the DB
        $res = mysql_query("SELECT torrent FROM files GROUP BY torrent");
        $delids = array();
        while ($row = mysql_fetch_array($res)) {
            $id = $row[0];
            if ($all_torrents[$id])
                continue;
            $delids[] = $id;
        }
        if (count($delids))
            mysql_query("DELETE FROM files WHERE torrent IN (" . join(",", $delids) . ")");
    
        // Enumerate and delete wait time overrides which have no according torrent in the DB
        $res = mysql_query("SELECT torrent_id FROM nowait GROUP BY torrent_id");
        $delids = array();
        while ($row = mysql_fetch_array($res)) {
            $id = $row[0];
            if ($all_torrents[$id])
                continue;
            $delids[] = $id;
        }
        if (count($delids))
            mysql_query("DELETE FROM nowait WHERE torrent_id IN (" . join(",", $delids) . ")");
            
        break;
    }
    
    // Delete inactive peers
    $deadtime = deadtime();
    mysql_query("DELETE FROM peers WHERE last_action < FROM_UNIXTIME($deadtime)");

    // Mark inactive torrents dead
    $deadtime -= $GLOBALS["MAX_DEAD_TORRENT_TIME"] * 86400;
    mysql_query("UPDATE torrents SET visible='no' WHERE visible='yes' AND last_action < FROM_UNIXTIME($deadtime)");

    // Delete newly registered user accounts which were not activated
    $deadtime = time() - $GLOBALS["SIGNUP_TIMEOUT"] * 3600;
    mysql_query("DELETE FROM users WHERE status = 'pending' AND added < FROM_UNIXTIME($deadtime) AND last_login < FROM_UNIXTIME($deadtime) AND last_access < FROM_UNIXTIME($deadtime)");

    // Update torrent stats (leechers, seeders, comments)
    $torrents = array();
    $res = mysql_query("SELECT torrent, seeder, COUNT(*) AS c FROM peers GROUP BY torrent, seeder");
    while ($row = mysql_fetch_assoc($res)) {
        if ($row["seeder"] == "yes")
            $key = "seeders";
        else
            $key = "leechers";
        $torrents[$row["torrent"]][$key] = $row["c"];
    } 

    $res = mysql_query("SELECT torrent, COUNT(*) AS c FROM comments GROUP BY torrent");
    while ($row = mysql_fetch_assoc($res)) {
        $torrents[$row["torrent"]]["comments"] = $row["c"];
    } 

    $fields = explode(":", "comments:leechers:seeders");
    $res = mysql_query("SELECT id, seeders, leechers, comments FROM torrents");
    while ($row = mysql_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 ($torr[$field] != $row[$field])
                $update[] = "$field = " . $torr[$field];
        } 
        if (count($update))
            mysql_query("UPDATE torrents SET " . implode(",", $update) . " WHERE id = $id");
    } 
    
    //delete old login attempts
    $secs = 1*86400; // Delete failed login attempts per one day.
    $dt = sqlesc(get_date_time(gmtime() - $secs)); // calculate date.
    mysql_query("DELETE FROM loginattempts WHERE banned='no' AND added < $dt"); // do job.






//lotterie mod by kp wemm
$res = mysql_query("SELECT * FROM lottery_config") or sqlerr(__FILE__, __LINE__);
while ($arr = mysql_fetch_assoc($res))
$arr_config[$arr['name']] = $arr['value'];

if ($arr_config['enable'] == 1)
{
if (get_date_time() > $arr_config['end_date'])
{
if ($arr_config["ticket_amount_type"] == GB)
$arr_config['ticket_amount'] = 1024 * 1024 * 1024 * $arr_config['ticket_amount'];
else if ($arr_config["ticket_amount_type"] == MB)
$arr_config['ticket_amount'] = 1024 * 1024 * $arr_config['ticket_amount'];
$size = $arr_config['ticket_amount'];

if ($arr_config["ticket_amount_type"] == GB)
$arr_config['prize_fund'] = 1024 * 1024 * 1024 * $arr_config['prize_fund'];
else if ($arr_config["ticket_amount_type"] == MB)
$arr_config['prize_fund'] = 1024 * 1024 * $arr_config['prize_fund'];
$prize_fund = $arr_config['prize_fund'];

$total = mysql_num_rows(mysql_query("SELECT * FROM tickets"));
if ($arr_config["use_prize_fund"])
{
$pot = $prize_fund / $arr_config['total_winners'];
$res = mysql_query("SELECT user FROM tickets ORDER BY RAND() LIMIT $arr_config[total_winners]") or sqlerr();
$who_won = array();
$msg = sqlesc("Glückwunsch, Du hast ".mksize($pot)." gewonnen. Dies wurde Deinem Acc. gutgeschrieben. Danke, dass Du in der Lotterie gespielt hast.");
while ($arr = mysql_fetch_assoc($res))
{
//$res2 = mysql_query("SELECT modcomment FROM users WHERE userid = $arr[user]") or sqlerr(__FILE__, __LINE__);
//$arr2 = mysql_fetch_assoc($res2);
//$modcomment = $arr2['modcomment'];
//$modcom = sqlesc("User won the lottery: " . mksize($pot) . " at " . get_date_time() . "\n" . $modcomment);
mysql_query("UPDATE users SET uploaded = uploaded + $pot WHERE id = $arr[user]") or sqlerr();
sendPersonalMessage(0, $arr['user'], "Du hast in der Lotterie gewonnen", $msg, PM_FOLDERID_SYSTEM, 0);
write_modcomment($arr['user'], 0, "User hat in der Lotterie gewonnen.");
$who_won[] = $arr['user'];
}
}
else
{
$pot = $total * $size / $arr_config['total_winners'];
$res = mysql_query("SELECT user FROM tickets ORDER BY RAND() LIMIT $arr_config[total_winners]") or sqlerr();
$who_won = array();
$msg = sqlesc("Glückwunsch, Du hast ".mksize($pot)." gewonnen. Dies wurde Deinem Acc. gutgeschrieben. Danke, dass Du in der Lotterie gespielt hast.");
while ($arr = mysql_fetch_assoc($res))
{
//$res2 = mysql_query("SELECT modcomment FROM users WHERE id = $arr[user]") or sqlerr(__FILE__, __LINE__);
//$arr2 = mysql_fetch_assoc($res2);
//$modcomment = $arr2['modcomment'];
//$modcom = sqlesc("User won the lottery: " . mksize($pot) . " at " . get_date_time() . "\n" . $modcomment);
mysql_query("UPDATE users SET uploaded = uploaded + $pot WHERE id = $arr[user]") or sqlerr();
sendPersonalMessage(0, $arr['user'], "Du hast in der Lotterie gewonnen", $msg, PM_FOLDERID_SYSTEM, 0);
write_modcomment($arr['user'], 0, "User hat in der Lotterie gewonnen");
$who_won[] = $arr['user'];
}
}
$who_won = implode("|", $who_won);
$who_won_date = get_date_time();
$who_won_prize = $pot;
mysql_query("TRUNCATE TABLE tickets") or sqlerr(__FILE__, __LINE__);
if ($who_won != '')
{
mysql_query("UPDATE lottery_config SET value = '$who_won' WHERE name = 'lottery_winners'") or sqlerr(__FILE__, __LINE__);
mysql_query("UPDATE lottery_config SET value = '$who_won_prize' WHERE name = 'lottery_winners_amount'") or sqlerr(__FILE__, __LINE__);
mysql_query("UPDATE lottery_config SET value = '$who_won_date' WHERE name = 'lottery_winners_time'") or sqlerr(__FILE__, __LINE__);
}
mysql_query("UPDATE lottery_config SET value = '0' WHERE name = 'enable'") or sqlerr(__FILE__, __LINE__);
}
}
// ende lotterie mod by kp wemm

//begin:Account Parken by volcem
        mysql_query("DELETE FROM users WHERE parked='no' AND status='confirmed' AND class <= $maxclass AND last_access < $dt");

        //lösche geparkte user
       $secs = 175*86400; // diese zahl legt fest wann ein geparkter user gelöscht werdenn soll
       $dt = sqlesc(get_date_time(gmtime() - $secs));
       $maxclass = UC_POWER_USER;
       mysql_query("DELETE FROM users WHERE parked='yes' AND status='confirmed' AND class <= $maxclass AND last_access < $dt");
       //ENDE: Account Parken by volcem

/////////Update Seederbonus/////////
   $res = mysql_query("SELECT DISTINCT userid FROM peers WHERE seeder = 'yes'") or sqlerr(__FILE__, __LINE__);
   if (mysql_num_rows($res) > 0)
   {
       while ($arr = mysql_fetch_assoc($res))
       {
       mysql_query("UPDATE users SET seedbonus = seedbonus+1.000 WHERE id = $arr[userid]") or sqlerr(__FILE__, __LINE__);
       }
   }  
/////////Update Seederbonus End////////

    
    // delete disabled and inactive user accounts
    $secs = $GLOBALS["INACTIVE_TIMEOUT"] * 86400;
    $dt = sqlesc(get_date_time(time() - $secs));
    $secs = $GLOBALS["DISABLED_TIMEOUT"] * 86400;
    $dit = sqlesc(get_date_time(time() - $secs));
    $maxclass = UC_POWER_USER;
    $res = mysql_query("SELECT id FROM users WHERE status='confirmed' AND ((enabled='yes' AND class <= $maxclass AND last_access < $dt) OR (enabled='no' AND last_access < $dit))");
    while ($arr = mysql_fetch_assoc($res))
        delete_acct($arr["id"]); 
    
    // lock topics where last post was made more than x days ago
    if ($GLOBALS["THREAD_LOCK_TIMEOUT"]) {
        $secs = $GLOBALS["THREAD_LOCK_TIMEOUT"] * 86400;
        $res = mysql_query("SELECT topics.id FROM topics JOIN posts ON topics.lastpost = posts.id AND topics.sticky = 'no' WHERE " . time() . " - UNIX_TIMESTAMP(posts.added) > $secs") or sqlerr(__FILE__, __LINE__);
        while ($arr = mysql_fetch_assoc($res))
            mysql_query("UPDATE topics SET locked='yes' WHERE id=$arr[id]") or sqlerr(__FILE__, __LINE__);
    } 
    
// remove expired warnings
    $res = mysql_query("SELECT id,username FROM users WHERE warned='yes' AND systemwarn = 'no' AND warneduntil < NOW() AND warneduntil <> '0000-00-00 00:00:00'") or sqlerr(__FILE__, __LINE__);
    if (mysql_num_rows($res) > 0) {
        $dt = sqlesc(get_date_time());
        $msg = "Deine Verwarnung wurde automatisch entfernt, und die Moderatoren darüber informiert, um evtl. gestellte Bedingungen erneut zu prüfen.\n";
        while ($arr = mysql_fetch_assoc($res)) {
            $mod_msg = "[b]Eine Verwarnung ist abgelaufen![/b]\n\nBenutzer [url=userdetails.php?id=$arr[id]]" . $arr["username"] . "[/url] (".$GLOBALS["DEFAULTBASEURL"]."/userdetails.php?id=$arr[id])\n\nBitte die Verwarnungsbedingungen erneut prüfen und entsprechend reagieren.";
            mysql_query("UPDATE users SET warned = 'no', warneduntil = '0000-00-00 00:00:00' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
            sendPersonalMessage(0, $arr["id"], "Deine Verwarnung ist abgelaufen", $msg, PM_FOLDERID_SYSTEM, 0);
            sendPersonalMessage(0, 0, "Die Verwarnung für '$arr[username]' ist abgelaufen", $mod_msg, PM_FOLDERID_MOD, 0, "open");
            write_log("remwarn", "Die Verwarnung für Benutzer '<a href=\"userdetails.php?id=$arr[id]\">$arr[username]</a>' ist abgelaufen und wurde vom System zurückgenommen.");
            write_modcomment($arr["id"], 0, "Verwarnung abgelaufen.");
        } 
    }

//Automatischer Ban wenn man eine Ratio von 0.2 und drunter hat und 8gb geleecht

//Ratio niedriger als $GLOBALS["AUTO_WARN_MIN_RATIO"]
$minratio = $GLOBALS["AUTO_BAN_MIN_RATIO"];

//Download mehr als $GLOBALS["AUTO_WARN_DOWN"] Gigabytes
$downloaded = $GLOBALS["AUTO_BAN_DOWN"]*1024*1024*1024;



// Wir nutzen die NetVision Source und bei uns ist die KLasse User zur Zeit mit der Id 0 versehen wenn es bei euch anders sein sollte dann Tragt statt 0 eure id ein :)

$res = mysql_query("SELECT id,ip,username FROM users WHERE class = 0 AND enabled = 'yes' AND downloaded >= $downloaded AND uploaded / downloaded < $minratio") or sqlerr(__FILE__, __LINE__);
while ($arr = mysql_fetch_assoc($res))
        {
            
            
        mysql_query("UPDATE users SET enabled = 'no' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
                mysql_query("INSERT INTO ban (ip, userid) VALUES('$arr[ip]', '$arr[id]')") or sqlerr(__FILE__, __LINE__);
                write_log("autoban", "Der Benutzer '<a href=\"userdetails.php?id=$arr[id]\">$arr[username]</a>' wurde automatisch gebannt weil er einen download von >= 8GB hatte und eine Ratio von =< 0.2.");
}

//Verwarnen bei schlechter Ratio by S4NE für die Netvision Source thx to fedepeco for the code

//Ratio niedriger als $GLOBALS["AUTO_WARN_MIN_RATIO"]
$minratio = $GLOBALS["AUTO_WARN_MIN_RATIO"];

//Download mehr als $GLOBALS["AUTO_WARN_DOWN"] Gigabytes
$downloaded = $GLOBALS["AUTO_WARN_DOWN"]*1024*1024*1024;

//verwarnungslänge $GLOBALS["AUTO_WARN_LÄNGE"] Wochen
$length = $GLOBALS["AUTO_WARN_LÄNGE"]*7;

// Wir nutzen die NetVision Source und bei uns ist die KLasse User zur Zeit mit der Id 0 versehen wenn es bei euch anders sein sollte dann Tragt statt 0 eure id ein :)

$res = mysql_query("SELECT id, username, lastwarned FROM users WHERE class = 0 AND enabled = 'yes' AND downloaded >= $downloaded AND warned = 'no' AND uploaded / downloaded < $minratio") or sqlerr(__FILE__, __LINE__);
    
if (mysql_num_rows($res) > 0)
    {
        $dt = sqlesc(get_date_time());
        $msg = sqlesc("Du wurdest für " . $GLOBALS["AUTO_WARN_LÄNGE"] . " Wochen verwarnt wegen einer zu niedrigen Ratio.Deine Ratio muss mindestens " . $GLOBALS["AUTO_REM_MIN_RATIO"] . " betragen damit die Verwarnung wieder zurück genommen wird. Bitte lies die FAQ.");
                
            $until = sqlesc(get_date_time(gmtime() + (($length+1)*86400)));

        while ($arr = mysql_fetch_assoc($res))
        {
        mysql_query("UPDATE users SET permban = 'yes', systemwarn = 'yes', warned = 'yes', warneduntil = ".$until.", timeswarned = timeswarned+1, lastwarned = ".$dt.", warnedby = 'System' WHERE id=$arr[id]") or sqlerr(__FILE__, __LINE__);    
        sendPersonalMessage(0, $arr["id"], "Verwarnt vom System - Grund schlechte Ratio", $msg, PM_FOLDERID_SYSTEM, 0);
        write_log("autowarn", "Der Benutzer '<a href=\"userdetails.php?id=$arr[id]\">$arr[username]</a>' wurde automatisch für " . $GLOBALS["AUTO_WARN_LÄNGE"] . " Wochen vom System verwarnt - Grund schlechte Ratio.");
        write_modcomment($arr["id"], 0, "Automatische Verwarnung vom System.");
}
}
    

//Ende verwarnen...

//Verwarnung wegnehmen bei erfüllten Auflagen by S4NE für die Netvision Source thx to fedepeco

//Ratio ratio die benötigt wird damit die Verwarnung zurück genommen wird(im Moment 0.6)
$minratio = $GLOBALS["AUTO_REM_MIN_RATIO"];

$res = mysql_query("SELECT id, username FROM users WHERE class = 0 AND enabled = 'yes' AND systemwarn = 'yes' AND uploaded / downloaded >= $minratio AND warned = 'yes' AND permban = 'yes' AND warnedby = 'System'") or sqlerr(__FILE__, __LINE__);

if (mysql_num_rows($res) > 0)
{
$dt = sqlesc(get_date_time());
$msg = sqlesc("Deine verwarnung wurde vom System zurück genommen. Damit so etwas nicht noch einmal passiert halte deine Ratio über " . $GLOBALS["AUTO_REM_MIN_RATIO"] . " .\n");
while ($arr = mysql_fetch_assoc($res))
{
mysql_query("UPDATE users SET warned = 'no', systemwarn = 'no', permban = 'no' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
sendPersonalMessage(0, $arr["id"], "Warnung entfernt - Grund Auflagen erfüllt", $msg, PM_FOLDERID_SYSTEM, 0);
write_log("autodewarn", "Dem Benutzer '<a href=\"userdetails.php?id=$arr[id]\">$arr[username]</a>' wurde automatisch seine Verwarnung entfernt.");
write_modcomment($arr["id"], 0, "Automatische Verwarnung vom System zurück genommen.");

}
}

//End MOD...

//Automatischer Ban nach ablauf der Verwarnung und nicht erfüllten Auflagen by S4NE für die Netvision Source thx to fedepeco

//User selektieren
$ret = mysql_query("SELECT id, username, warneduntil FROM users WHERE class = 0 AND systemwarn = 'yes' AND enabled = 'yes' AND warned = 'yes'") or sqlerr(__FILE__, __LINE__);
$tar = mysql_fetch_assoc($ret);

if ($tar['warneduntil'] != '0000-00-00 00:00:00'){

//Set the variable of how much left...
$secs = 1*86400; // 1 day
$length = sqlesc(get_date_time(gmtime() + $secs)); // less than 1 day of warning left


//Aktion
$res = mysql_query("SELECT id, ip FROM users WHERE class = 0 AND warned = 'yes' AND systemwarn = 'yes' AND enabled = 'yes' AND warneduntil < $length AND id = " . $tar['id'] . "") or sqlerr(__FILE__,__LINE__);
while ($arr = mysql_fetch_assoc($res)) {

mysql_query("UPDATE users SET enabled = 'no' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
mysql_query("INSERT INTO ban (ip, userid) VALUES('$arr[ip]', '$arr[id]')") or sqlerr(__FILE__, __LINE__);
write_log("autoban", "Der Benutzer '<a href=\"userdetails.php?id=$arr[id]\">$arr[username]</a>' wurde automatisch gebannt wegen schlechter Ratio.");
write_modcomment($arr["id"], 0, "Automatischer Ban vom System - Grund schlechte Ratio.");

}
}
//End MOD... 
    
    // promote power users
    $limit = 25 * 1024 * 1024 * 1024;
    $minratio = 1.05;
    $maxdt = sqlesc(get_date_time(time() - 86400 * 28));
    $res = mysql_query("SELECT id,username FROM users WHERE class = 0 AND uploaded >= $limit AND uploaded / downloaded >= $minratio AND added < $maxdt") or sqlerr(__FILE__, __LINE__);
    if (mysql_num_rows($res) > 0) {
        $dt = sqlesc(get_date_time());
        $msg = sqlesc("Glückwunsch, Du wurdest automatisch zum [b]Power User[/b] befördert. :)\nDu kannst Dir nun NFOs ansehen.\n");
        while ($arr = mysql_fetch_assoc($res)) {
            mysql_query("UPDATE users SET class = 1 WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
            sendPersonalMessage(0, $arr["id"], "Du wurdest zum 'Power User' befördert", $msg, PM_FOLDERID_SYSTEM, 0);
            write_log("promotion", "Der Benutzer '<a href=\"userdetails.php?id=$arr[id]\">$arr[username]</a>' wurde automatisch zum Power User befördert.");
            write_modcomment($arr["id"], 0, "Automatische Beförderung zum Power User.");
        } 
    } 
    
    // demote power users
    $minratio = 0.95;
    $res = mysql_query("SELECT id,username FROM users WHERE class = 1 AND uploaded / downloaded < $minratio") or sqlerr(__FILE__, __LINE__);
    if (mysql_num_rows($res) > 0) {
        $dt = sqlesc(get_date_time());
        $msg = sqlesc("Du wurdest automatisch vom [b]Power User[/b] zum [b]User[/b] degradiert, da Deine Share-Ratio unter $minratio gefallen ist.\n");
        while ($arr = mysql_fetch_assoc($res)) {
            mysql_query("UPDATE users SET class = 0 WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
            sendPersonalMessage(0, $arr["id"], "Du wurdest zum 'User' degradiert", $msg, PM_FOLDERID_SYSTEM, 0);
            write_log("demotion", "Der Benutzer '<a href=\"userdetails.php?id=$arr[id]\">$arr[username]</a>' wurde automatisch zum User degradiert.");
            write_modcomment($arr["id"], 0, "Automatische Degradierung zum User.");
        } 
    } 
    // Update stats
    $seeders = get_row_count("peers", "WHERE seeder='yes'");
    $leechers = get_row_count("peers", "WHERE seeder='no'");
 $peaklevl = get_row_count("peers", "");
    mysql_query("UPDATE avps SET value_u=$peaklevl WHERE arg='peak' AND value_u < $peaklevl") or sqlerr(__FILE__, __LINE__); 
    mysql_query("UPDATE avps SET value_u=$seeders WHERE arg='seeders'") or sqlerr(__FILE__, __LINE__);
    mysql_query("UPDATE avps SET value_u=$leechers WHERE arg='leechers'") or sqlerr(__FILE__, __LINE__); 
    // update forum post/topic count
    $forums = mysql_query("select id from forums");
    while ($forum = mysql_fetch_assoc($forums)) {
        $postcount = 0;
        $topiccount = 0;
        $topics = mysql_query("select id from topics where forumid=$forum[id]");
        while ($topic = mysql_fetch_assoc($topics)) {
            $res = mysql_query("select count(*) from posts where topicid=$topic[id]");
            $arr = mysql_fetch_row($res);
            $postcount += $arr[0];
            ++$topiccount;
        } 
        mysql_query("update forums set postcount=$postcount, topiccount=$topiccount where id=$forum[id]");
    } 
    
    // Delete old/dead and not activated torrents
    if ($GLOBALS["MAX_TORRENT_TTL"]) {
        $days = $GLOBALS["MAX_TORRENT_TTL"];
        $dt = sqlesc(get_date_time(time() - ($days * 86400)));
        $deadtime = deadtime() - $GLOBALS["MAX_DEAD_TORRENT_TIME"] * 86400;
        $res = mysql_query("SELECT id, name, owner FROM torrents WHERE (added < $dt OR `activated`='no') AND `last_action` < FROM_UNIXTIME($deadtime)");
        while ($arr = mysql_fetch_assoc($res)) {
            deletetorrent($arr["id"]);
            $msg = sqlesc("Dein Torrent '$arr[name]' wurde automatisch vom System gelöscht. (Inaktiv und älter als $days Tage).\n");
            sendPersonalMessage(0, $arr["owner"], "Einer Deiner Torrents wurde gelöscht", $msg, PM_FOLDERID_SYSTEM, 0);
            write_log("torrentdelete", "Torrent $arr[id] ($arr[name]) wurde vom System gelöscht (Inaktiv und älter als $days Tage)");
        } 
    } 
    
    // Delete old entries from start/stop log
    mysql_query("DELETE FROM startstoplog WHERE UNIX_TIMESTAMP(`datetime`) < (UNIX_TIMESTAMP()-864000)");
    
    // Delete orphaned entries from completed list (either torrent or user doesn't exist anymore)
    $res = mysql_query("SELECT completed.id FROM completed LEFT JOIN torrents ON completed.torrent_id=torrents.id LEFT JOIN users ON completed.user_id=users.id WHERE torrents.id IS NULL OR users.id IS NULL");
    $idlist = "";
    while ($id = mysql_fetch_assoc($res)) {
    	if ($idlist != "") $idlist .= ",";
        $idlist .= $id["id"];
    }
    if ($idlist != "") mysql_query("DELETE FROM completed WHERE id IN ($idlist)");
    
    // Delete orphaned friends
    $query = "SELECT `friends`.`id` AS `id` FROM `friends` LEFT JOIN `users` AS `myuser` ON `friends`.`userid`=`myuser`.`id` LEFT JOIN `users` AS `myfriend` ON `friends`.`userid`=`myfriend`.`id` WHERE `myuser`.`username` IS NULL OR `myfriend`.`username` IS NULL";
    $res = mysql_query($query);
    $idlist = "";
    while ($id = mysql_fetch_assoc($res)) {
    	if ($idlist != "") $idlist .= ",";
        $idlist .= $id["id"];
    }
    if ($idlist != "") mysql_query("DELETE FROM `friends` WHERE `id` IN ($idlist)");
    
    // Delete orphaned mod comments
    $res = mysql_query("SELECT `modcomments`.`userid` AS `id` FROM `modcomments` LEFT JOIN `users` ON `modcomments`.`userid`=`users`.`id` WHERE `users`.`id` IS NULL");
    $idlist = "";
    while ($id = mysql_fetch_assoc($res)) {
    	if ($idlist != "") $idlist .= ",";
        $idlist .= $id["id"];
    }
    if ($idlist != "") mysql_query("DELETE FROM `modcomments` WHERE `userid` IN ($idlist)");
    
} 

?>