<?

require_once ("include/bittorrent.php");

gzip ();

dbconn ( false );
$trailer = $_GET ['trailer'];
if ($trailer == 'yes')
	$trailer = 'yes';
else
	$trailer = 'no';
if ($trailer == 'no')
	validcan ( false, 'can_browse', true );
else
	validcan ( false, 'can_browsetr', true );
if ($_GET ['view'] > - 1) {
	if ($trailer == 'yes' && $_COOKIE ['trailerview'] != $_GET ['view'])
		setcookie ( "trailerview", ( int ) $_GET ['view'] );
	elseif ($trailer != 'yes' && $_COOKIE ['browseview'] != $_GET ['view'])
		setcookie ( "browseview", ( int ) $_GET ['view'] );
	$view = $_GET ['view'];
}
if (! isset ( $view )) {
	if ($trailer == 'yes')
		$view = ( int ) $_COOKIE ['trailerview'];
	else
		$view = ( int ) $_COOKIE ['browseview'];
}
parked ();
global $CURGROUP;
$cats = genrelist ();
/// MOD INCAT ///
$incats = ingenrelist ();
/// MOD INCAT ///
$searchstr = unesc ( $_GET ["search"] );
$cleansearchstr = htmlspecialchars_uni ( $searchstr );
if (empty ( $cleansearchstr ))
	unset ( $cleansearchstr );
	
// sorting by MarkoStamcar


if ($_GET ['sort'] && $_GET ['type']) {
	
	$column = '';
	$ascdesc = '';
	
	switch ($_GET ['sort']) {
		case '1' :
			$column = "name";
			break;
		case '2' :
			$column = "numfiles";
			break;
		case '3' :
			$column = "comments";
			break;
		case '4' :
			$column = "added";
			break;
		case '5' :
			$column = "size";
			break;
		case '6' :
			$column = "times_completed";
			break;
		case '7' :
			$column = "seeders";
			break;
		case '8' :
			$column = "leechers";
			break;
		case '9' :
			$column = "owner";
			break;
		case '10' :
			if ($CURGROUP ['can_editltor'])
				$column = "moderatedby";
			break;
		default :
			$column = "id";
			break;
	}
	
	switch ($_GET ['type']) {
		case 'asc' :
			$ascdesc = "ASC";
			$linkascdesc = "asc";
			break;
		case 'desc' :
			$ascdesc = "DESC";
			$linkascdesc = "desc";
			break;
		default :
			$ascdesc = "DESC";
			$linkascdesc = "desc";
			break;
	}
	
	$orderby = "ORDER BY torrents." . $column . " " . $ascdesc;
	$pagerlink = "sort=" . intval ( $_GET ['sort'] ) . "&type=" . $linkascdesc . "&";

} else {
	
	$orderby = "ORDER BY torrents.sticky ASC, torrents.id DESC";
	$pagerlink = "";

}

$addparam = "";
$wherea = array ();
$wherecatina = array ();
/// MOD INCAT ///
$wherecatinain = array ();
/// MOD INCAT ///
if ($_GET ["incldead"] == 1) {
	$addparam .= "incldead=1&amp;";
	if (! isset ( $CURUSER ) || ! $CURGROUP ['can_viewbanned'])
		$wherea [] = "banned != 'yes'";
} elseif ($_GET ["incldead"] == 2) {
	$addparam .= "incldead=2&amp;";
	$wherea [] = "visible = 'no'";
} elseif ($_GET ["incldead"] == 3) {
	$addparam .= "incldead=3&amp;";
	$wherea [] = "free = 'yes'";
	$wherea [] = "visible = 'yes'";
} elseif ($_GET ["incldead"] == 4) {
	$addparam .= "incldead=4&amp;";
	$wherea [] = "seeders = 0";
	$wherea [] = "visible = 'yes'";
} else
	$wherea [] = "visible = 'yes'";

$category = ( int ) $_GET ["cat"];

$all = $_GET ["all"];
//// MOD INCAT ////
$incategory = ( int ) $_GET ["incat"];
if ($incategory) {
	$act = "incat";
	if (! $all)
		if (! $_GET && $CURUSER ["notifs"]) {
			$all = True;
			foreach ( $incats as $incat ) {
				$all &= $incat [id];
				if (strpos ( $CURUSER ["notifs"], "[incat" . $incat [id] . "]" ) !== False) {
					$wherecatinain [] = $incat [id];
					$addparam .= "inc$incat[id]=1&amp;";
				}
			}
		} elseif ($incategory) {
			if (! is_valid_id ( $incategory ))
				stderr ( $tracker_lang ['error'], "Invalid category ID." );
			$wherecatinain [] = $incategory;
			$addparamin .= "incat=$incategory&amp;";
		} else {
			$all = True;
			foreach ( $incats as $incat ) {
				$all &= $_GET ["inc$incat[id]"];
				if ($_GET ["inc$incat[id]"]) {
					$wherecatinain [] = $incat [id];
					$addparam .= "inc$incat[id]=1&amp;";
				}
			}
		}
} else {
	$act = "category";
	if (! $all)
		if (! $_GET && $CURUSER ["notifs"]) {
			$all = True;
			foreach ( $cats as $cat ) {
				$all &= $cat [id];
				if (strpos ( $CURUSER ["notifs"], "[cat" . $cat [id] . "]" ) !== False) {
					$wherecatina [] = $cat [id];
					$addparam .= "c$cat[id]=1&amp;";
				}
			}
		} elseif ($category) {
			if (! is_valid_id ( $category ))
				stderr ( $tracker_lang ['error'], "Invalid category ID." );
			$wherecatina [] = $category;
			$addparam .= "cat=$category&amp;";
		} else {
			$all = True;
			foreach ( $cats as $cat ) {
				$all &= $_GET ["c$cat[id]"];
				if ($_GET ["c$cat[id]"]) {
					$wherecatina [] = $cat [id];
					$addparam .= "c$cat[id]=1&amp;";
				}
			}
		}

}
//// MOD INCAT ////
if ($all) {
	$wherecatina = array ();
	$addparam = "";
}
/// MOD INCAT ///
if (count ( $wherecatina ) > 1)
	$wherecatin = implode ( ",", $wherecatina );
elseif (count ( $wherecatina ) == 1)
	$wherea [] = "$act = $wherecatina[0]";
elseif (count ( $wherecatinain ) == 1)
	$wherea [] = "$act = $wherecatinain[0]";
elseif (count ( $wherecatinain ) > 1)
	$wherecatin = implode ( ",", $wherecatinain );
	/// MOD INCAT ///
$wherebase = $wherea;

if (isset ( $cleansearchstr )) {
	$wherea [] = "torrents.name LIKE '%" . sqlwildcardesc ( $searchstr ) . "%'";
	$addparam .= "search=" . urlencode ( $searchstr ) . "&amp;";
}
$where = implode ( " AND ", $wherea );
$where .= ($where ? ' AND' : "") . ' trailer=' . sqlesc ( $trailer );
/// MOD INCAT ///
if ($wherecatin)
	$where .= ($where ? " AND " : "") . "$act IN (" . $wherecatin . ")";
	/// MOD INCAT ///
if ($where != "")
	$where = "WHERE $where";
$res = sql_query ( "SELECT COUNT(*) FROM torrents $where" ) or sqlerr ( __FILE__, __LINE__ );
$row = mysql_fetch_array ( $res );
$count = $row [0];
$num_torrents = $count;

if (! $count && isset ( $cleansearchstr )) {
	$wherea = $wherebase;
	//$orderby = "ORDER BY id DESC";
	$searcha = explode ( " ", $cleansearchstr );
	$sc = 0;
	foreach ( $searcha as $searchss ) {
		if (strlen ( $searchss ) <= 1)
			continue;
		$sc ++;
		if ($sc > 5)
			break;
		$ssa = array ();
		$ssa [] = "torrents.name LIKE '%" . sqlwildcardesc ( $searchss ) . "%'";
	}
	if ($sc) {
		$where = implode ( " AND ", $wherea );
		$where .= ($where ? ' AND' : "") . ' trailer=' . sqlesc ( $trailer );
		if ($where != "")
			$where = "WHERE $where";
		$res = sql_query ( "SELECT COUNT(*) FROM torrents $where" );
		$row = mysql_fetch_array ( $res );
		$count = $row [0];
	}
}

$torrentsperpage = $CURUSER ["torrentsperpage"];
if (! $torrentsperpage)
	$torrentsperpage = 25;

if ($count) {
	if ($addparam != "") {
		if ($pagerlink != "") {
			if ($addparam {strlen ( $addparam ) - 1} != ";") { // & = &amp;
				$addparam = $addparam . "&" . $pagerlink;
			} else {
				$addparam = $addparam . $pagerlink;
			}
		}
	} else {
		$addparam = $pagerlink;
	}
	/// MOD INCAT TRAILER///
	list ( $pagertop, $pagerbottom, $limit ) = pager ( $torrentsperpage, $count, "browse.php?" . $addparam );
	$query = "SELECT torrents.id, torrents.moderated, torrents.moderatedby, torrents.hide, torrents.genre, torrents.category, torrents.incat, torrents.leechers, torrents.seeders, torrents.poster, torrents.free, torrents.name, torrents.times_completed, torrents.size, torrents.added, torrents.comments, torrents.numfiles, torrents.filename, torrents.sticky, torrents.owner," . "IF(torrents.numratings < $minvotes, NULL, ROUND(torrents.ratingsum / torrents.numratings, 1)) AS rating, categories.name  AS cat_name, incat.name AS cat_namein, incat.image AS cat_picin, incat.id AS cat_id, incat.incat_cat AS cat_incat, categories.image AS cat_pic, users.username, users.`group` FROM torrents LEFT JOIN categories ON category = categories.id LEFT JOIN incat ON (torrents.incat = incat.id) AND (incat = incat.id) LEFT JOIN users ON torrents.owner = users.id $where $orderby $limit";
	$res = sql_query ( $query ) or sqlerr ( __FILE__, __LINE__ );
	/// MOD INCAT TRAILER///
} else
	unset ( $res );
if (isset ( $cleansearchstr ))
	stdhead ( $tracker_lang ['search_results_for'] . " \"$searchstr\"" );
else
	stdhead ( $tracker_lang ['browse'] );

?>

<STYLE TYPE="text/css" MEDIA=screen>
a.catlink:link,a.catlink:visited {
	text-decoration: none;
}

a.catlink:hover {
	color: #A83838;
}
</STYLE>
<?
begin_frame ( "Список раздач" );
?><table class="embedded" cellspacing="0" cellpadding="5" width="100%">
	<tr>
		<td>
		<form method="get" action="browse.php"><input type='hidden'
			name='trailer' value='<?=$trailer?>'>
		<table class="embedded" align="center">
			<tr>
				<td class="bottom">
				<table class="bottom">
					<tr><?
					$i = 0;
					$catsperrow = 5;
					foreach ( $cats as $cat ) {
						if ($i == $catsperrow) {
							print ( "</tr><tr>" );
							$i = 0;
						}
						print ( "<td class=\"a\"><a class=\"catlink\" href=\"browse.php?cat=$cat[id]\"><input name=\"c$cat[id]\" type=\"checkbox\" " . (in_array ( $cat [id], $wherecatina ) ? "checked " : "") . "value=\"1\">" . htmlspecialchars_uni ( $cat [name] ) . "</a>\n" );
						//// MOD INCAT ///
						foreach ( $incats as $incat )
							if ($cat ['id'] == $incat ['incat_cat'])
								print ( "<li><a class=\"catlink\" href=\"browse.php?incat=$incat[id]\"><input name=\"inc$incat[id]\" type=\"checkbox\" " . (in_array ( $incat [id], $wherecatinain ) ? "checked " : "") . "value=\"1\">" . htmlspecialchars_uni ( $incat [name] ) . "</a>\n" );
							//// MOD INCAT ///
						print ( "</td>" );
						$i ++;
						//// MOD INCAT ///
					//// MOD INCAT ///
					}
					$alllink = "</tr><div align=\"left\">(<a href=\"browse.php?all=1\"><b>" . $tracker_lang ['show_all'] . "</b></a>)</div>";
					
					$ncats = count ( $cats );
					$nrows = ceil ( $ncats / $catsperrow );
					$lastrowcols = $ncats % $catsperrow;
					
					if ($lastrowcols != 0) {
						if ($catsperrow - $lastrowcols != 1) {
							print ( "<tr><td class=\"bottom\" rowspan=\"" . ($catsperrow - $lastrowcols - 1) . "\">&nbsp;</td></tr>" );
						}
					}
					?>
				
				
				
				</table>
				<a href="browse.php"><input type="button" value="Снять отметки"></a>
				</td>
			</tr>
		</table>
		</form>
		</td>
	</tr>
	<tr>
		<td class="embedded">
		<form method="get" action="browse.php">
		<center><input class="search" id="searchinput" name="search"
			type="text" size="34" autocomplete="off"
			ondblclick="suggest(event.keyCode,this.value);"
			onkeyup="suggest(event.keyCode,this.value);"
			onkeypress="return noenter(event.keyCode);"
			value="<?=htmlspecialchars_uni ( $searchstr )?>" /> &nbsp; <select
			name="incldead">
			<option value="0"><?=$tracker_lang ['active'];?></option>
			<option value="1"
				<?
				print ( $_GET ["incldead"] == 1 ? " selected" : "" );
				?>><?=$tracker_lang ['including_dead'];?></option>
			<option value="2"
				<?
				print ( $_GET ["incldead"] == 2 ? " selected" : "" );
				?>><?=$tracker_lang ['only_dead'];?></option>
			<option value="3"
				<?
				print ( $_GET ["incldead"] == 3 ? " selected" : "" );
				?>><?=$tracker_lang ['golden_torrents'];?></option>
			<option value="4"
				<?
				print ( $_GET ["incldead"] == 5 ? " selected" : "" );
				?>><?=$tracker_lang ['no_seeds'];?></option>
		</select> <select name="cat">
			<option value="0">(<?=$tracker_lang ['all_types'];?>)</option>
<?

//$cats = genrelist();
$catdropdown = "";
foreach ( $cats as $cat ) {
	$catdropdown .= "<option value=\"" . $cat ["id"] . "\"";
	if ($cat ["id"] == $_GET ["cat"])
		$catdropdown .= " selected=\"selected\"";
	$catdropdown .= ">" . htmlspecialchars_uni ( $cat ["name"] ) . "</option>\n";
}
/// MOD INCAT ///
foreach ( $incats as $incat ) {
	$catdropdown .= "<option value=\"" . $incat ["id"] . "\"";
	if ($cat ["id"] == $_GET ["incat"])
		$catdropdown .= " selected=\"selected\"";
	$catdropdown .= ">" . htmlspecialchars_uni ( $incat ["name"] ) . "</option>\n";
}
/// MOD INCAT ///
?>
<?=

$catdropdown?>
</select> <select name="view">
			<option value="-1">(Вид)</option>
			<option value="0" <?=(! $view ? " selected" : "")?>>Древовидный</option>
			<option value="1" <?=($view ? " selected" : "")?>>В строку</option>
		</select> <input type="submit" value="Искать" /></center>
		</form>
		<script language="JavaScript" src="js/suggest.js"
			type="text/javascript"></script>
		<div id="suggcontainer"
			style="text-align: left; width: 520px; display: none;">
		<div id="suggestions"
			style="cursor: default; position: absolute; background-color: #FFFFFF; border: 1px solid #777777;"></div>
		</div>
		</td>
	</tr>

<?

if (isset ( $cleansearchstr ))
	print ( "<tr><td class=\"index\" colspan=\"12\">" . $tracker_lang ['search_results_for'] . " \"" . htmlspecialchars_uni ( $searchstr ) . "\"</td></tr>\n" );

if ($num_torrents) {
	
	print ( "<tr><td style=\"border: 0px;\" colspan=\"12\">" );
	print ( $pagertop );
	print ( "</td></tr>" );
	
	torrenttable ( $res, "index", $view );
	
	print ( "<tr><td style=\"border: 0px;\" colspan=\"12\">" );
	print ( $pagerbottom );
	print ( "</td></tr>" );

} else {
	if (isset ( $cleansearchstr )) {
		print ( "<tr><td style=\"border: 0px;\" colspan=\"12\">" . $tracker_lang ['nothing_found'] . "</td></tr>\n" );
		//print("<p>Попробуйте изменить запрос поиска.</p>\n");
	} else {
		print ( "<tr><td style=\"border: 0px;\" colspan=\"12\">" . $tracker_lang ['nothing_found'] . "</td></tr>\n" );
		//print("<p>Извините, данная категория пустая.</p>\n");
	}
}
print ( "</table>" );

end_frame ();
if ($trailer == 'no') {
	begin_frame ( "Раздачи, нуждающиеся в сидерах" );
	print ( "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"10\"><tr><td class=\"text\">" );
	$res = sql_query ( "SELECT id, name, seeders, leechers FROM torrents WHERE (leechers > 0 AND seeders = 0) OR (leechers / seeders >= 4) ORDER BY leechers DESC LIMIT 20" ) or sqlerr ( __FILE__, __LINE__ );
	if (mysql_num_rows ( $res ) > 0) {
		while ( $arr = mysql_fetch_assoc ( $res ) ) {
			$torrname = $arr ['name'];
			if (strlen ( $torrname ) > 55)
				$torrname = substr ( $torrname, 0, 55 ) . "...";
			print ( "<b>" . $CURGROUP ['can_details'] ? "<a href=\"details.php?id=" . $arr ['id'] . "&hit=1\" alt=\"" . $arr ['name'] . "\" title=\"" . $arr ['name'] . "\">" . $torrname . "</a>" : $torrname . "</b><font color=\"#0099FF\"><b> (Раздают: " . number_format ( $arr ['seeders'] ) . " Качают: " . number_format ( $arr ['leechers'] ) . ")</b></font><br />\n" );
		}
	} else
		print ( "<center><b> " . $tracker_lang ['no_need_seeding'] . " </b></center>\n" );
	print ( "</font>
</b>
</td></tr></table>" );
	end_frame ();
}
stdfoot ();

?>
