<?

require_once("bittorrent.inc.php");
function hexesc($matches) {
			return sprintf("%02x", ord($matches[0]));
		}

if (!function_exists('file_get_contents'))
{
    function file_get_contents($filename, $use_include_path = 1)
    {
        $file = @fopen($filename, 'rb', $use_include_path);
        if ($file)
        {
            if ($fsize = @filesize($filename))
            {
                $data = @fread($file, $fsize);
            }
            else
            {
                while (!feof($file))
                {
                    $data .= @fread($file, 32768);
                }
            }
            @fclose($file);
        }
        return $data;
    }
}
   

function docleanup() {
	global $torrent_dir, $signup_timeout, $max_dead_torrent_time;

	@set_time_limit(0);
	ignore_user_abort(1);

	do {
		$res = mysql_query("SELECT id FROM torrents");
		$ar = array();
		while ($row = mysql_fetch_array($res)) {
			$id = $row[0];
			$ar[$id] = 1;
		}

		if (!count($ar))
			break;

		$dp = @opendir($torrent_dir);
		if (!$dp)
			break;

		$ar2 = array();
		while (($file = readdir($dp)) !== false) {
			if (!preg_match('/^(\d+)\.torrent$/', $file, $m))
				continue;
			$id = $m[1];
			$ar2[$id] = 1;
			if (isset($ar[$id]) && $ar[$id])
				continue;
			$ff = $torrent_dir . "/$file";
			unlink($ff);
		}
		closedir($dp);

		if (!count($ar2))
			break;

		$delids = array();
		foreach (array_keys($ar) as $k) {
			if (isset($ar2[$k]) && $ar2[$k])
				continue;
			$delids[] = $k;
			unset($ar[$k]);
		}
		if (count($delids))
			mysql_query("DELETE FROM torrents WHERE id IN (" . join(",", $delids) . ")");

		$res = mysql_query("SELECT torrent FROM peers GROUP BY torrent");
		$delids = array();
		while ($row = mysql_fetch_array($res)) {
			$id = $row[0];
			if (isset($ar[$id]) && $ar[$id])
				continue;
			$delids[] = $id;
		}
		if (count($delids))
			mysql_query("DELETE FROM peers WHERE torrent IN (" . join(",", $delids) . ")");

		$res = mysql_query("SELECT torrent FROM files GROUP BY torrent");
		$delids = array();
		while ($row = mysql_fetch_array($res)) {
			$id = $row[0];
			if (@$ar[$id])
				continue;
			$delids[] = $id;
		}
		if (count($delids))
			mysql_query("DELETE FROM files WHERE torrent IN (" . join(",", $delids) . ")");
	} while (0);

	$deadtime = deadtime();
	mysql_query("DELETE FROM peers WHERE last_action < FROM_UNIXTIME($deadtime)");

	$deadtime -= $max_dead_torrent_time;
	mysql_query("UPDATE torrents SET visible='no' WHERE visible='yes' AND last_action < FROM_UNIXTIME($deadtime)");

	$deadtime = time() - $signup_timeout;
	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)");

	$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"];
	}
// i thing it is here that modifications need to be made !
	$fields = explode(":", "comments:leechers:seeders");
	$res = mysql_query("SELECT id, seeders, leechers, comments FROM torrents");
	if (mysql_num_rows($res)) 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];
		}
		// temporary fix :(
		//if (count($update)) 
			//mysql_query("UPDATE torrents SET " . implode(",", $update) . " WHERE id = $id");
			

    } 		
			
			$sql = 'SELECT id FROM torrents'; 

// on envoie la requete 
$req = mysql_query($sql) ; 

// on fait une boucle qui va faire un tour pour chaque enregistrements 
while($data = mysql_fetch_array($req)) 
    {
	$id = $data["id"];
	
	$row[0] = '?' ; 
	$row[1] = '?' ; 
    // on affiche les informations de l'enregistrements en cours 
	$sql2 = "SELECT info_hash,scrape_url FROM torrents WHERE id = $id";
	$req2 = mysql_query($sql2) ;
	$dat = mysql_fetch_array($req2);
	$hash = preg_replace_callback('/./s', "hexesc", hash_pad($dat["info_hash"]));
	
     $scrape = file_get_contents('http://torrentstats.phpsoft.org/bytestats.php?tracker='.$dat["scrape_url"].'&infohash='.$hash);
	
	
	$rest = substr($scrape, 2); 
	$row = explode('#-#',$rest);
	//echo "<br>http://torrentstats.phpsoft.org/bytestats.php?tracker=".$dat["scrape_url"]."&infohash=".$hash ;
	//echo "<br>".$row[0];
	//echo "<br>".$row[1];
	
	mysql_query("UPDATE torrents SET seeders=$row[0]  WHERE id = $id");
	
	mysql_query("UPDATE torrents SET leechers=$row[1]  WHERE id = $id");
	}
		
		
	
 ;
}


?>
