Login
Username: Password:
Remember me

[Sign Up] / [Recover Password]

Theme / Language

Popular
New Torrents
new name
Size: 18.40 MB
Most active
new name
S: 74 L: 3
New Posters
Clean Up Class
Controls ·  Search New posts · Mark unread

You are in: Forum / Forum / V4 / Downloads & Updates

2021-08-01 23:48:16
class.cleanup.php

<?
interface Tasks
{
   public function seedbonus();
   public function comments();
   public function checkexpiredwarns();
   public function ratiowarn();
   public function cleanlogs();
   public function autopromote();
   public function autofreeleech();
   public function autodemote();
   public function checkdead();
   public function pendingusers();
   public function privseeders();
   public function startsync();
   public function cleanshoutbox();
}

class Database
{
   public $pdo;
   
   public function __construct($db = 'db1', $username = 'user', $password = '', $host = 'localhost', $port = 3306, $options = [])
   {
       $dsn = "mysql:host=$host;dbname=$db;port=$port;charset=utf8mb4";
       try {
           $this->pdo = new PDO($dsn, $username, $password, $options);
       }
       catch (PDOException $e) {
           $this->log_exception($e->getMessage(), $e->getLine());
       }
   }
   
   private function log_exception($msg, $line)
   {
       $query = "INSERT INTO sql_logging(exception, added) VALUES(?, NOW())";
       $stt   = $this->pdo->prepare($query);
       $stt->bindValue(1, $msg . $line);
       $stt->execute();
   }
   
   public function get_date_time($timestamp = 0)
   {
       if ($timestamp)
           return date('Y-m-d H:i:s', $timestamp);
       else
           return gmdate('Y-m-d H:i:s');
   }
   
   public function preprocess($query, $get_id)
   {
       return $query;
   }
   
   public function write_log($text)
   {
       $this->query_params('INSERT INTO log (added, txt) VALUES(NOW(), :log)', array(
           'log' => $text
       ));
   }
   
   public function sql_timestamp_to_unix_timestamp($s)
   {
       return mktime(substr($s, 11, 2), substr($s, 14, 2), substr($s, 17, 2), substr($s, 5, 2), substr($s, 8, 2), substr($s, 0, 4));
   }
   
   public function gmtime()
   {
       return $this->sql_timestamp_to_unix_timestamp($this->get_date_time());
   }
   
   public function interval($s)
   {
       return sprintf("INTERVAL '%s'", $s);
   }
   
   public function query_params($query, $params = null, $get_id = null)
   {
       if (is_null($params)) {
           $params = array();
       }
       try {
           $query = $this->preprocess($query, $get_id);
           $stmt  = $this->pdo->prepare($query);
           foreach ($params as $key => $param) {
               if ($key == "data") {
                   $stmt->bindValue(':' . $key, $param, PDO::PARAM_LOB);
               } else if ($key == "limit") {
                   $stmt->bindValue(':' . $key, (int) trim($param), PDO::PARAM_INT);
               } else {
                   $stmt->bindValue(':' . $key, $param);
               }
           }
           $stmt->execute();
           $stmt->setFetchMode(PDO::FETCH_ASSOC);
           if (is_null($get_id)) {
               return $stmt;
           } else {
               return $this->get_last_id($stmt, $get_id);
           }
       }
       catch (PDOException $e) {
           $this->log_exception($e->getMessage(), $e->getLine());
       }
   }
}

class Cleanup extends Database implements Tasks
{
   public function cleanlogs()
   {
       $ts = $this->gmtime() - 28 * 86400; // 28 days * 24 hours
       $this->query_params('DELETE FROM log WHERE added < FROM_UNIXTIME(:ts)', array(
           'ts' => $ts
       ));
   }
   
   public function checkdead()
   {
       $deadtime  = $this->gmtime() - 21600; // 6 hours
       $founddead = $this->query_params('SELECT COUNT(torrent_id) AS dead FROM torrents WHERE seeders = 0 AND leechers = 0');
       $find      = $founddead->fetch();
       $check = $this->query_params("UPDATE torrents SET marked_dead = 'yes' WHERE visible = 'yes' AND last_action < FROM_UNIXTIME(:dead_time) AND seeders = '0' AND leechers = '0' AND external != 'yes'", array(
        'dead_time' => $deadtime
       ));
       if ($check) {
       $event = "$find[dead] torrents found dead";
   $this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
            'receiver' => 'NerbBot',
'event' => $event
));
       }        
   }
   
   public function seedbonus()
   {
       $res = $this->query_params("SELECT DISTINCT u.user_id as peer, u.username, (SELECT DISTINCT COUNT(torrent_id) FROM peers WHERE seeder = 'yes' AND user_id = peer) AS count FROM peers p LEFT JOIN users u ON u.user_id = p.user_id WHERE p.seeder = 'yes'");
       while ($row = $res->fetch()) {
           $update = $this->query_params('UPDATE users SET seedbonus = seedbonus + :bonustime_rowcount WHERE user_id = :peer', array(
               'bonustime_rowcount' => (0.5 * $row['count']),
               'peer' => $row['peer']
           ));
           /*
           if ($update) {
               $event = "+ Seed Bonus points granted for [url=https://domain.com/images/nerbbot/private_seeders.png[/img]";
               $this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
                   'receiver' => $row['username'],
                   'event' => $event
               ));
           }
           */
       }
   }
   
   public function autofreeleech()
   {
       $gigs  = 17179869184; // 16gb
       $query = $this->query_params("SELECT torrent_id, name FROM torrents WHERE banned = 'no' AND freeleech = '0' AND size >= :gigs", array(
           'gigs' => $gigs
       ));
       if ($query) {
           while ($row = $query->fetch()) {
               $event = "$row[name] cycled to Freeleech (16GB+)";
               $this->query_params("UPDATE torrents SET freeleech = '1' WHERE torrent_id = :torrent_id", array(
                   'torrent_id' => $row['torrent_id']
               ));
               $this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
                   'receiver' => 'NerbBot',
                   'event' => $event
               ));
               $this->write_log("Freeleech added on <a href='/details/$row[torrent_id]'>$row[name]</a> because it is larger than 16GB or larger.");
           }
       }
   }
   
   public function pendingusers()
   {
       $deadtime = $this->gmtime() - 259200; // 3 days * 72 hours
       $this->query_params("DELETE FROM users WHERE status = 'pending' AND added < FROM_UNIXTIME(:dead_time)", array(
           'dead_time' => $deadtime
       ));
   }
   
   public function cleanshoutbox()
   {
       $ts = $this->gmtime() - 1 * 86400; // 1 day * 24 hours
       $this->query_params('DELETE FROM shoutbox WHERE added < FROM_UNIXTIME(:ts)', array(
           'ts' => $ts
       ));
   }
   
   public function startsync() {
   
   // Synronize seeders/leechers from peer table => torrent table
   $collect = $this->query_params("SELECT t.torrent_id AS this, (SELECT COUNT(torrent_id) FROM peers WHERE seeder = 'yes' AND completed = 1 AND torrent_id = this) AS seeders, (SELECT COUNT(torrent_id) FROM peers WHERE seeder = 'no' AND completed = 0 AND torrent_id = this) AS leechers FROM peers LEFT JOIN torrents t ON t.torrent_id = peers.torrent_id");
   if (!is_null($collect)) {
   foreach ($collect as $row) {
   $sync = $this->query_params('UPDATE torrents SET seeders = :seeders, leechers = :leechers WHERE torrent_id = :torrent_id', array('seeders' => $row['seeders'], 'leechers' => $row['leechers'], 'torrent_id' => $row['this'])); // Update torrent table: seeders/leechers  
   }
   if ($sync) {
    $event    = "Syncing torrents completed";
$this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
'receiver' => 'System',
'event' => $event
));
        }
   }
   }
   
   public function privseeders()
   {
       $res      = $this->query_params("SELECT t.torrent_id, (SELECT COUNT(torrent_id) FROM peers WHERE seeder = 'yes' AND completed = 1) AS seeders, COUNT(seeders) AS c FROM torrents t LEFT JOIN peers p ON p.torrent_id = t.torrent_id WHERE t.banned = 'no' AND t.external = 'no'");
       $getcount = $res->fetch();
       $event    = "Bot: Found $getcount[c] Private Seeders";
       $this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
           'receiver' => 'NerbBot',
           'event' => $event
       ));
   }
   
   public function comments()
   {
       $getcount = $this->query_params('SELECT COUNT(torrent) as c FROM comments');
       $restotal = $getcount->fetch();
       $event    = "Bot: $restotal[c] comments posted";
       $this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
           'receiver' => 'NerbBot',
           'event' => $event
       ));
   }
   
   public function autopromote()
   {
       $limit    = 25 * 1024 * 1024 * 1024;
       $minratio = 1.05;
       $maxdt    = $this->get_date_time(time() - 86400 * 28); // 24 hours * 28 days
       $res      = $this->query_params('SELECT user_id, username FROM users WHERE class = 1 AND uploaded >= :limit AND uploaded / downloaded >= :minratio AND added < :maxdt', array(
           'limit' => $limit,
           'minratio' => $minratio,
           'maxdt' => $maxdt
       ));
       if ($res) {
           $dt  = $this->get_date_time();
           $msg = "Congratulations, you have been automatically promoted to Power User. You can now do more stuff.";
           while ($arr = $res->fetch()) {
               $this->query_params('UPDATE users SET class = 2 WHERE user_id = :user_id', array(
                   'user_id' => $arr['user_id']
               ));
               $txt   = "You have been promoted to Power User!";
               //$event = "$arr[username] has been promoted Power User";
               $this->query_params('INSERT INTO messages (sender, receiver, added, msg, poster, subject) VALUES(0, :user_id, NOW(), :message, 0, :subject)', array(
                   'user_id' => $arr['user_id'],
                   'message' => $txt,
                   'subject' => 'Promoted!'
               ));
               /*
               $this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
                   'receiver' => $arr['username'],
                   'event' => $event
               ));
               */
               $this->write_log("The user <a href=\"/user/?id=$arr[user_id]\">$arr[username]</a> was automatically promoted to power user.");
           }
       }
   }
   
   public function autodemote()
   {
       $minratio = 0.95;
       $res      = $this->query_params('SELECT user_id, username FROM users WHERE class = 2 AND uploaded / downloaded < :minratio', array(
           'minratio' => $minratio
       ));
       if ($res) {
           $dt  = $this->get_date_time();
           $msg = "You were automatically demoted from Power User to Regular because your share ratio fell below $minratio.";
           while ($arr = $res->fetch()) {
               $this->query_params('UPDATE users SET class = 1 WHERE user_id = :user_id', array(
                   'user_id' => $arr['user_id']
               ));
               $txt   = "You have been demoted to Regular.";
               //$event = "$arr[username] has been demoted to Regular";
               $this->query_params('INSERT INTO messages (sender, receiver, added, msg, poster, subject) VALUES(0, :user_id, NOW(), :message, 0, :subject)', array(
                   'user_id' => $arr['user_id'],
                   'message' => $txt,
                   'subject' => 'Demoted!'
               ));
               /*
               $this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
                   'receiver' => $arr['username'],
                   'event' => $event
               ));
               */
               $this->write_log("The user <a href=\"/user/?id=$arr[user_id]\">$arr[username]</a> was automatically promoted to power user.");
           }
       }
   }
   
   public function checkexpiredwarns()
   {
       $res = $this->query_params("SELECT users.user_id, users.username, warnings.expiry FROM users INNER JOIN warnings ON users.user_id=warnings.userid WHERE type != 'Poor Ratio' AND warned = 'yes' AND enabled='yes' AND warnings.active = 'yes' AND warnings.expiry < :date_time", array(
           'date_time' => $this->get_date_time()
       ));
       while ($arr1 = $res->fetch()) {
           $this->query_params("UPDATE users SET warned = 'no' WHERE user_id = :user_id", array(
               'user_id' => $arr1['user_id']
           ));
           $this->query_params("UPDATE warnings SET active = 'no' WHERE userid = :user_id AND expiry < :date_time", array(
               'user_id' => $arr1['user_id'],
               'date_time' => $this->get_date_time()
           ));
           $event = "Warning removed for $arr1[username]. Expiry: $arr1[expiry]";
           $this->write_log("Removed warning for $arr1[username]. Expiry: $arr1[expiry]");
       }
       $this->query_params("UPDATE users SET warned = 'yes' WHERE warned = 'no' AND user_id IN (SELECT userid FROM warnings WHERE active = 'yes')");
       while ($active = $res->fetch()) {
       /*
           $event = "Active warning renewed for $active[username]";
           $this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
               'receiver' => 'NerbBot',
               'event' => $event
           ));
           */
       }
   }
   
   public function ratiowarn()
   {
       //if ($this->CONFIG['ratiowarn_enable']) {
           $minratio   = 0.4;
$downloaded = 4 * 1024 * 1024 * 1024;
$length     = 14;
           $res        = $this->query_params("SELECT user_id, username FROM users WHERE class = 1 AND warned = 'no' AND enabled='yes' AND uploaded / downloaded < :minratio AND downloaded >= :downloaded", array(
               'minratio' => $minratio,
               'downloaded' => $downloaded
           ));
           if ($res) {
               $timenow    = $this->get_date_time();
               $reason     = "You have been warned because of having low ratio. You need to get a " . $minratio . " before next " . $length . " days or your account may be banned.";
               $expiretime = gmdate('Y-m-d H:i:s', $this->gmtime() + (86400 * $length));
               while ($arr = $res->fetch()) {
                   /*$warneduser = $arr['username'];
                   $event      = "Low ratio warning added for [url=https://www.switch-torrents.com/user/?id=$arr[user_id]]$arr[username][/url]";
                   $this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
                       'receiver' => $warneduser,
                       'event' => $event
                   ));
                   */
                   $this->query_params('INSERT INTO warnings (userid, reason, added, expiry, warnedby, type) VALUES (:user_id, :reason, NOW(), :expiretime, 0, :type)', array(
                       'user_id' => $arr['user_id'],
                       'reason' => $reason,
                       'expiretime' => $expiretime,
                       'type' => 'Poor Ratio'
                   ));
                   $this->query_params("UPDATE users SET warned = 'yes' WHERE user_id = :user_id", array(
                       'user_id' => $arr['user_id']
                   ));
                   $this->query_params('INSERT INTO messages (sender, receiver, added, msg, poster, subject) VALUES (0, :user_id, NOW(), :reason, 0, :subject)', array(
                       'user_id' => $arr['user_id'],
                       'reason' => $reason,
                       'subject' => 'Warning: Poor Ratio'
                   ));
                   $this->write_log("Auto Leech warning has been <b>added</b> for <a href='/user/?id=" . $arr["user_id"] . "'>" . $arr["username"] . "</a>");
               }
           }
           $res1 = $this->query_params("SELECT users.user_id, users.username FROM users INNER JOIN warnings ON users.user_id=warnings.userid WHERE type='Poor Ratio' AND active = 'yes' AND warned = 'yes' AND enabled='yes' AND uploaded / downloaded >= :minratio AND downloaded >= :downloaded", array(
               'minratio' => $minratio,
               'downloaded' => $downloaded
           ));
           if ($res1) {
               $timenow = $this->get_date_time();
               $reason  = "Your warning of low ratio has been removed. We highly recommend you to keep a your ratio up to not be warned again.\n";
               while ($arr1 = $res1->fetch()) {
                   /*$warnremoved = $arr1['username'];
                   $event       = "Low ratio warning removed for [url=https://www.switch-torrents.com/user/?id=$arr1[user_id]]$arr1[username][/url]";
                   $this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
                       'receiver' => $warnremoved,
                       'event' => $event
                   ));
                   */
                   $this->query_params("UPDATE users SET warned = 'no' WHERE user_id = :user_id", array(
                       'user_id' => $arr1['user_id']
                   ));
                   $this->query_params("UPDATE warnings SET expiry = :time_now, active = 'no' WHERE userid = :user_id", array(
                       'time_now' => $timenow,
                       'user_id' => $arr1['user_id']
                   ));
                   $this->query_params('INSERT INTO messages (sender, receiver, added, msg, poster, subject) VALUES (0, :user_id, NOW(), :reason, 0, :subject)', array(
                       'user_id' => $arr1['user_id'],
                       'reason' => $reason,
                       'subject' => 'Ratio Warning Removed'
                   ));
                   $this->write_log("Auto Leech warning has been removed for: <a href='/user/?id=" . $arr1["user_id"] . "'>" . $arr1["username"] . "</a>");
               }
           }
           $res = $this->query_params("SELECT users.user_id, users.username, users.limited, UNIX_TIMESTAMP(warnings.expiry) AS expiry FROM users INNER JOIN warnings ON users.user_id=warnings.userid WHERE type='Poor Ratio' AND active = 'yes' AND class = 1 AND enabled='yes' AND warned = 'yes' AND uploaded / downloaded < :minratio AND downloaded >= :downloaded", array(
               'minratio' => $minratio,
               'downloaded' => $downloaded
           ));
           if ($res->fetch() > 0) {
               $timenow = $this->get_date_time();
               $expires = (86400 * $length);
               while ($arr = $res->fetch()) {
                   if ($this->gmtime() - $arr['expiry'] >= 0) {
                       /*$limiteduser = $arr['username'];
                       $event       = "[url=https://www.switch-torrents.com/user/?id=$arr[user_id]]$arr[username][/url] has been limited (Auto Leech warning)";
                       $this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
                           'receiver' => $limiteduser,
                           'event' => $event
                       ));
                       */
                       $this->query_params("UPDATE users SET limited = 'yes', warned = 'no' WHERE user_id = :user_id", array(
                           'user_id' => $arr['user_id']
                       ));
                       $this->write_log("User <a href='/user/?id=" . $arr["user_id"] . "'>" . $arr["username"] . "</a> has been <b>limited</b> (Auto Leech warning)");
                   }
               }
           }
       //}
       $res = $this->query_params("SELECT users.user_id, users.username, warnings.expiry FROM users INNER JOIN warnings ON users.user_id=warnings.userid WHERE type != 'Poor Ratio' AND warned = 'yes' AND enabled='yes' AND warnings.active = 'yes' AND warnings.expiry < :date_time", array(
           'date_time' => $this->get_date_time()
       ));
       while ($arr1 = $res->fetch()) {
           $this->query_params("UPDATE users SET warned = 'no' WHERE user_id = :user_id", array(
               'user_id' => $arr1['user_id']
           ));
           $this->query_params("UPDATE warnings SET active = 'no' WHERE userid = :user_id AND expiry < :date_time", array(
               'user_id' => $arr1['user_id'],
               'date_time' => $this->get_date_time()
           ));
           $event = "Warning removed for $arr1[username]. Expiry: $arr1[expiry]";
           $this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
               'receiver' => 'NerbBot',
               'event' => $event
           ));
           $this->write_log("Removed warning for $arr1[username]. Expiry: $arr1[expiry]");
       }
       $this->query_params("UPDATE users SET warned = 'yes' WHERE warned = 'no' AND user_id IN (SELECT userid FROM warnings WHERE active = 'yes')");
       while ($active = $res->fetch()) {
           $event = "Active warning renewed for $active[username]";
           $this->query_params('INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, :receiver, :event, NOW(), 0)', array(
               'receiver' => 'NerbBot',
               'event' => $event
           ));
       }
   }
}


methods:

$task = new Cleanup;

$task->seedbonus();
$task->comments();
$task->checkexpiredwarns();
$task->ratiowarn();
$task->cleanlogs();
$task->autopromote();
$task->autofreeleech();
$task->autodemote();
$task->checkdead();
$task->pendingusers();
$task->privseeders();
$task->startsync();
$task->cleanshoutbox();
Last edited by STorrents2020 on 2021-08-01 23:51:05
2021-08-02 17:22:21
Thanks for sharing great work, compared to old cleanup so much better

Simple steps, which will guide me kept putting cleanup off cos of the spaghetti code

But it's been playing up here had to disable it think it has something to do with the 21,000 members going to prune every member with no password,  this won't effect posts so can be added back if someone ask - most of user table columns are empty with users who never logged in not sure how much that would effect it maybe just needs to be more efficient

Then I can time it better
Last edited by M-jay warn on 2021-08-02 17:36:43
2021-08-03 13:38:33
Anytime man, we needed it working so I produced this. I have mine set as a cron task every 10 minutes.

Almost 40K without issues.
2021-08-04 04:11:02
Also, there are several updates that can be applied as well, as I never updated the core routines, just updated the class to be current.

It has a lot to go yet. But I don’t know how long this will go as BitTorrent is partially dying out so we are just prepping for a transition toward a Reddit-like community with a rich database. The rest is smoke.
2021-08-04 21:30:33
not got far with this just stripped my code and speed test my querys before i place into methods it was still taking 8 seconds - so i got to 8 from 12 seconds.

i found optimizing the table was causing it. this must cause some overhead in huge sites with loads of peers and torrents i removed and now it takes milliseconds :plain
    public function optimize()
   {
       // OPTIMIZE TABLES
       $res = DB::run("SHOW TABLES");
       while ($table = $res->fetch(PDO::FETCH_LAZY)) {
           // Get rid of overhead.
           DB::run("REPAIR TABLE `$table[0]`;");
           // Analyze table for faster indexing.
           DB::run("ANALYZE TABLE `$table[0]`;");
           // Optimize table to minimize thrashing.
           DB::run("OPTIMIZE TABLE `$table[0]`;");
       }
   }
2021-08-05 04:08:39
I dont use this method at all, as I rely on InnoDB and do nightly SQL backups all the same (so it skips this step). Im glad it has worked for you, and more specially on MyISAM database engines.
2021-08-05 04:10:42
Side note: I tried 4 solutions before comitting to MariaDB and all it provides. Each was overly exotic approaches to the PHP code, highly complex queries that rely on SQL "custom functions" and plain old "connect directly and attempt to optimize", even CLI failed.. take my advice, and update the engine to InnoDB.
2021-08-05 04:26:52
i updated to innodb but switched back same with phpmailer because you sometimes have to install yourself - i try removing 3rd party installs

This also applies to sql/php settings like short tags and no_default_zero_date  to make the project plug and play - even thought about removing bootstrap because its a third party but its so useful so i added more custom css and i try use css wherever possible leaving bootstrap for the grids/forms etc to make mobile friendly
2021-08-07 00:17:00
Trust me.. I plan to completely remove libraries altogether, they are just easy roads to pure code (which as we know compiles much faster than a library will). I speak for JS.

I don’t know how many hired devs have tried so hard to convince me to convert my project to Laravel. I’m so against it  :rofl
Users online

No users online

Search



Statistics

    Torrents

  • Tracking: 3
  • Todays torrents: 0
  • Seeders: 0
  • Leechers: 0
  • Peers: 0
  • Downloaded: 89.96 GB
  • Uploaded: 9.86 GB

  • Members

  • We have: 838
  • New today: 0
  • Guest today: 9

  • Online

  • Total online: 3
  • Members: 0
  • Guests online: 3
  • Comments: 3
  • Messages: 1,728