##############################################################
## MOD Title: External Torrents Mod
## MOD Author: RoadTrain < N/A >  http://torrentpier.info/viewtopic.php?f=8&t=1105
## MOD Version: 0.1.1
## :     
## Installation Level: Easy
## Installation Time: 10 Minutes
## Files To Edit: torrent.php
##				  includes/functions_torrent.php
##				  language/lang_russian/lang_main.php
##				  attach_mod/displaying_torrent.php
##				  viewforum.php
##				  tracker.php
##                templates/default/viewtopic_attach.tpl
##                templates/default/viewtopic_torrent.tpl
##                templates/default/viewforum.tpl
##                templates/default/tracker.tpl
## Included Files:  none
## License: http://opensource.org/licenses/gpl-license.php GNU General Public License v2
##############################################################
## For security purposes, please check: http://www.phpbb.com/mods/
## for the latest version of this MOD. Although MODs are checked
## before being allowed in the MODs Database there is no guarantee
## that there are no security problems within the MOD. No support
## will be given for MODs not found within the MODs Database which
## can be found at http://www.phpbb.com/mods/
##############################################################
## Author Notes:
## nah & poh
##############################################################
## MOD History:
##    2008-11-01 - Version 0.1.1
##    	- minor fixes
##    2008-09-13 - Version 0.1.0
##    	- initial release
##
##############################################################
## Before Adding This MOD To Your Forum, You Should Back Up All Files Related To This MOD
##############################################################

# 
#-----[ SQL QUERY ]---------------------------------
# 
ALTER TABLE bb_bt_torrents ADD (
`external` tinyint(1) NOT NULL default '0',
`tracker_url` text,
`last_scraped` int(11) NOT NULL default '0',
`seeders_ext` mediumint(8) NOT NULL default '0',
`leechers_ext` mediumint(8) NOT NULL default '0'
);

# 
#-----[ OPEN ]---------------------------------
# 
torrent.php

#
#-----[ FIND ]---------------------------------
#
// Unregister torrent from tracker
if ($mode == 'unreg')
{
	tracker_unregister($attach_id, 'request');
	exit;
}

#
#-----[ AFTER, ADD ]---------------------------------
#
// Scrape
if ($mode == 'scrape')
{	
	scrape_tracker($attach_id);
	redirect("viewtopic.$phpEx?t=$topic_id");
}

#
#-----[ FIND ]---------------------------------
#
	// Freeze/Unfreeze torrent
	if ($_POST['tor_action'] === 'freeze' || $_POST['tor_action'] === 'unfreeze')
	{
		$new_tor_status = ($_POST['tor_action'] === 'freeze') ? TOR_STATUS_FROZEN : TOR_STATUS_NORMAL;
		change_tor_status($attach_id, $new_tor_status);
		redirect("viewtopic.$phpEx?t=$topic_id");
	}
# 
#-----[ AFTER, ADD ]---------------------------------
#
	// Make external/internal torrent
	if ($_POST['tor_action'] === 'make_ext' || $_POST['tor_action'] === 'make_int')
	{
		$external = ($_POST['tor_action'] === 'make_ext') ? 1 : 0;
		change_type($attach_id, $external);
		redirect("viewtopic.$phpEx?t=$topic_id");	
	}	
# 
#-----[ OPEN ]---------------------------------
# 
includes/functions_torrent.php

# 
#-----[ FIND ]---------------------------------
#
function tracker_register ($attach_id, $mode = '')

# 
#-----[ BEFORE, ADD ]---------------------------------
#
//External
function change_type ($attach_id, $new_type)
{
	global $db, $attach_config, $topic_id;

	$attach_id = (int) $attach_id;
	$new_tor_status = (int) $new_type;

	if (!$torrent = get_torrent_info($attach_id))
	{
		bb_die('Torrent not found');
	}

	$topic_id = $torrent['topic_id'];

	torrent_auth_check($torrent['forum_id'], $torrent['poster_id']);

	$filename = get_attachments_dir() .'/'. $torrent['physical_filename'];

	if (!is_file($filename))
	{
		torrent_error_exit('File name error');
	}

	if (!file_exists($filename))
	{
		torrent_error_exit('File not exists');
	}

	if (!$tor = bdecode_file($filename))
	{
		torrent_error_exit('This is not a bencoded file');
	}

	$ann = (@$tor['announce']) ? $tor['announce'] : 'http://tracker.prq.to/announce';	

	$db->query("
		UPDATE ". BT_TORRENTS_TABLE ." SET
			external = " . $new_type . ", tracker_url = '" . $ann . "'
		WHERE attach_id = " . $attach_id . "
		LIMIT 1");
}
function escape_url($url) {
	$ret = '';
	for($i = 0; $i < strlen($url); $i+=2)
	$ret .= '%'.$url[$i].$url[$i + 1];
	return $ret;
}
function scrape_tracker($attach_id) {
	global $db, $attach_config, $topic_id;
	
	if (!$torrent = get_torrent_info($attach_id))
	{
		bb_die('Torrent not found');
	}
	$topic_id = $torrent['topic_id'];
	
	$sql = "
		SELECT info_hash, tracker_url 
		FROM
			". BT_TORRENTS_TABLE      ."
		WHERE
			    attach_id = $attach_id
		LIMIT 1
	";

	if (!$tdata = $db->fetch_row($sql))
	{
		message_die(GENERAL_ERROR, 'Invalid attach_id');
	}

	//$hash = bin2hex($tdata['info_hash']);
	$scrape = str_replace('announce', 'scrape', $tdata['tracker_url']);
	ini_set('default_socket_timeout',10); 
	@$fp = file_get_contents($scrape.'?info_hash='.urlencode($tdata['info_hash']));
	$ret = array();
	if(!$fp) {
		$seeds = 0;
		$peers = 0;
	}else{
		$stats = BDecode($fp);
		//$binhash = addslashes(pack("H*", $hash));
		$binhash = $tdata['info_hash'];
		@$seeds = 0 + $stats['files'][$binhash]['complete'];
		@$peers = 0 + $stats['files'][$binhash]['incomplete'];
		@$downloaded = $stats['files'][$binhash]['downloaded'];
	}
	$time = time();
	$query  = "UPDATE ". BT_TORRENTS_TABLE ." SET ";
	$query .= "seeders_ext = " . $seeds;
	$query .= ", leechers_ext = " . $peers;
	if ($downloaded) {
		$query .= ", complete_count = " . $downloaded;
	}
	if ($seeds > 0) {
		$query .= ", seeder_last_seen = " . $time;
	}
	$query .= ", last_scraped = " . $time;
	$query .= " WHERE attach_id = " . $attach_id . " LIMIT 1";
	if (!$db->query($query)) {
		message_die(GENERAL_ERROR, 'Could not scrape this tracker', '', __LINE__, __FILE__, $sql);
	}	
	return;
}

# 
#-----[ FIND ]---------------------------------
#
	$passkey_url = (!$userdata['session_logged_in'] || isset($_GET['no_passkey'])) ? '' : "?$passkey_key=$passkey_val&";

# 
#-----[ AFTER, ADD ]---------------------------------
#
	$external = $db->fetch_row("
			SELECT external, tracker_url
			FROM ". BT_TORRENTS_TABLE ."
			WHERE attach_id = $attach_id
		");
		
# 
#-----[ FIND ]---------------------------------
#
	// Replace original announce url with tracker default
	if ($board_config['bt_replace_ann_url'] || !@$tor['announce'])
	{
		$tor['announce'] = strval($ann_url . $passkey_url);
	}

#
#-----[ REPLACE WITH ]---------------------------------
#
	// Replace original announce url with tracker default
	if (($board_config['bt_replace_ann_url'] || !@$tor['announce']) && !$external['external'])
	{
		$tor['announce'] = strval($ann_url . $passkey_url);
	}
	else
	{
		$tor['announce'] = strval($external['tracker_url']);
	}

# 
#-----[ OPEN ]---------------------------------
# 
language/lang_russian/lang_main.php


# 
#-----[ FIND ]---------------------------------
#
$lang['IS_REGISTERED'] = '';


# 
#-----[ AFTER, ADD ]---------------------------------
#
//External Torrents
$lang['TYPE'] = '';
$lang['EXT'] = '<b>EXT:</b>';
$lang['EXTERNAL'] = '<b></b>';
$lang['EXTERNAL_T'] = ' ';
$lang['INTERNAL'] = '<b></b>';
$lang['MAKE_EXTERNAL'] = ' ';
$lang['MAKE_INTERNAL'] = ' ';
$lang['LAST_SCRAPED'] = ' ';
$lang['LAST_SCRAPED_AGO'] = '';
$lang['SCRAPE'] = '';
# 
#-----[ OPEN ]---------------------------------
# 
attach_mod/displaying_torrent.php

# 
#-----[ FIND ]---------------------------------
# 
			'REGED_TIME'      => create_date($bb_cfg['default_dateformat'], $tor_info['reg_time'], $bb_cfg['board_timezone']),

#
#-----[ AFTER, ADD ]---------------------------------
#
			//External torrents
			'TYPE'            => $tor_info['external'] ? '<a href="'.$tor_info['tracker_url'].'" target="_blank">'.$lang['EXTERNAL'].'</a>' : $lang['INTERNAL'],
			'MAKE'            => $tor_info['external'] ? 'make_int' : 'make_ext',
			'MAKE_TEXT'       => $tor_info['external'] ? $lang['MAKE_INTERNAL'] : $lang['MAKE_EXTERNAL'],


#
#-----[ FIND ]---------------------------------
#
			'TOR_COMPLETED' => declension($tor_info['complete_count'], 'times'),

# 
#-----[ BEFORE, ADD ]---------------------------------
#
			'EXTERNAL'      => $tor_info['external'],
			'ATTACH_ID'     => $attach_id,
			'LAST_SCRAPED'  => create_date($bb_cfg['post_date_format'], $tor_info['last_scraped']),
			'LAST_SCRAPED_AGO'=> delta_time($tor_info['last_scraped']),
			'SEED_EXT'      => $tor_info['external'] ? $tor_info['seeders_ext'] : '0',
			'LEECH_EXT'     => $tor_info['external'] ? $tor_info['leechers_ext'] : '0',
			
# 
#-----[ OPEN ]---------------------------------
# 
viewforum.php

# 
#-----[ FIND ]---------------------------------
# 
tor.size AS tor_size, tor.reg_time, tor.complete_count, tor.seeder_last_seen, tor.attach_id, tor.tor_status,

# 
#-----[ AFTER, ADD ]---------------------------------
#
tor.external, tor.seeders_ext, tor.leechers_ext,

# 
#-----[ FIND ]---------------------------------
# 
		'HREF_TOPIC_ID'    => ($moved) ? $topic['topic_moved_id'] : $topic['topic_id'],

# 
#-----[ BEFORE, ADD ]---------------------------------
#
		//external torrents
		'EXT'              => isset($topic['external']) ? ($topic['external'] ? $lang['EXT'] : '') : '',

#
#-----[ FIND ]---------------------------------
#
			'SEEDERS'    => (int) $topic['seeders'],
			'LEECHERS'   => (int) $topic['leechers'],
#
#-----[ REPLACE WITH ]---------------------------------
#
			'SEEDERS'    => $topic['external'] ? (int) $topic['seeders_ext'] : (int) $topic['seeders'],
			'LEECHERS'   => $topic['external'] ? (int) $topic['leechers_ext'] : (int) $topic['leechers'],
# 
#-----[ OPEN ]---------------------------------
# 
tracker.php

# 
#-----[ FIND ]---------------------------------
# 
tor.topic_id, tor.post_id, tor.attach_id, tor.size, tor.reg_time, tor.complete_count, tor.seeder_last_seen, tor.tor_status,

# 
#-----[ IN-LINE AFTER, ADD ]---------------------------------
#
tor.external, tor.seeders_ext, tor.leechers_ext,

# 
#-----[ FIND ]---------------------------------
# 
				'TOPIC_TITLE'  => wbr($tor['topic_title']),

# 
#-----[ AFTER, ADD ]---------------------------------
#
				//external
				'EXT'          => $tor['external'] ? $lang['EXT'] : '',

#
#-----[ FIND ]---------------------------------
#
			$seeds  = $tor['seeders'];
			$leechs = $tor['leechers'];
#
#-----[ REPLACE WITH ]---------------------------------
#
			$seeds  = $tor['external'] ? $tor['seeders_ext'] : $tor['seeders'];
			$leechs = $tor['external'] ? $tor['leechers_ext'] : $tor['leechers'];
# 
#-----[ OPEN ]---------------------------------
# 
templates/default/viewtopic_attach.tpl	  

# 
#-----[ FIND ]---------------------------------
#
<td width="15%" rowspan="%1" class="tCenter pad_6">

# 
#-----[ INCREMENT ]---------------------------------
#
%1 + 1

# 
#-----[ FIND ]---------------------------------
#
	<tr class="row1">
		<td>{L_IS_REGISTERED}:</td>
		<td>{postrow.attach.tor_reged.REGED_TIME}</td>
	</tr>
	
# 
#-----[ AFTER, ADD ]---------------------------------
#
	<tr class="row1">
		<td>{L_TYPE}:</td>
		<td>{postrow.attach.tor_reged.TYPE}</td>
	</tr>	
# 
#-----[ FIND ]---------------------------------
#
				<option value="freeze">{L_FREEZE_TORRENT}</option>
				<!-- ENDIF -->
# 
#-----[ AFTER, ADD ]---------------------------------
#
				<option value="{postrow.attach.tor_reged.MAKE}">{postrow.attach.tor_reged.MAKE_TEXT}</option>
# 
#-----[ OPEN ]---------------------------------
# 
templates/default/viewtopic_torrent.tpl	  

#
#-----[ FIND ]---------------------------------
#
	<td colspan="2" class="catTitle"><a href="{DL_LIST_HREF}">
	
#
#-----[ REPLACE WITH ]---------------------------------
#
	<td colspan="2" class="catTitle"><a href="<!-- IF not EXTERNAL -->{DL_LIST_HREF}<!-- ENDIF -->">	

#
#-----[ FIND ]---------------------------------
#
				<!-- IF not SEED_COUNT -->
#
#-----[ REPLACE WITH ]---------------------------------
#
				<!-- IF not SEED_COUNT && not EXTERNAL -->

#
#-----[ FIND ]---------------------------------
#
				<!-- IF SEED_COUNT || LEECH_COUNT -->

#
#-----[ REPLACE WITH ]---------------------------------
#
				<!-- IF SEED_COUNT || LEECH_COUNT || EXTERNAL -->

#
#-----[ FIND ]---------------------------------
#
				<!-- IF SEED_COUNT -->
				<tr class="seed">

#
#-----[ REPLACE WITH ]---------------------------------
#
				<!-- IF SEED_COUNT && not EXTERNAL -->
				<tr class="seed">	

#
#-----[ FIND ]---------------------------------
#
				<!-- IF LEECH_COUNT -->
				<tr>

#
#-----[ REPLACE WITH ]---------------------------------
#
				<!-- IF LEECH_COUNT && not EXTERNAL -->
				<tr>
				
#
#-----[ FIND ]---------------------------------
#
				<tr class="seed">
					<td><b>{L_SEEDERS}:</b></td>
					<td>[&nbsp; <b>{SEED_COUNT}</b> &nbsp;|&nbsp; {TOR_SPEED_UP} &nbsp;]</td>
				</tr>

#
#-----[ AFTER, ADD ]---------------------------------
#
				<!-- ELSEIF EXTERNAL -->
				<tr class="seed">
					<td><b>{L_SEEDERS}:</b></td>
					<td>[&nbsp; <b>{SEED_EXT}</b> &nbsp;]</td>
				</tr>

#
#-----[ FIND ]---------------------------------
#
				<tr>
					<td class="leech"><b>{L_LEECHERS}:</b></td>
					<td class="leech">[&nbsp; <b>{LEECH_COUNT}</b> &nbsp;|&nbsp; {TOR_SPEED_DOWN} &nbsp;]</td>
				</tr>
#
#-----[ AFTER, ADD ]---------------------------------
#
				<!-- ELSEIF EXTERNAL -->
				<tr>
					<td class="leech"><b>{L_LEECHERS}:</b></td>
					<td class="leech">[&nbsp; <b>{LEECH_EXT}</b> &nbsp;]</td>
				</tr>
#
#-----[ FIND ]---------------------------------
#
				<!-- ENDIF / SEED_COUNT || LEECH_COUNT -->
#
#-----[ AFTER, ADD ]---------------------------------
#
				<!-- IF EXTERNAL -->
				<i>{L_LAST_SCRAPED}<b>{LAST_SCRAPED_AGO}</b> {L_LAST_SCRAPED_AGO} ({LAST_SCRAPED})</i><br />
				<form method="POST" action="torrent.php?mode=scrape">
					<input type="hidden" name="id" value="{ATTACH_ID}" />
					<input type="submit" name="submit" value="{L_SCRAPE}">
				</form>
				<!-- ENDIF -->
#
#-----[ FIND ]---------------------------------
#
<!-- IF PEERS_FULL_LINK && PEER_EXIST -->

#
#-----[ REPLACE WITH ]---------------------------------
#
<!-- IF PEERS_FULL_LINK && PEER_EXIST && not EXTERNAL -->

# 
#-----[ OPEN ]---------------------------------
# 
templates/default/viewforum.tpl	  

#
#-----[ FIND ]---------------------------------
#
<a href="{TOPIC_URL}{t.HREF_TOPIC_ID}" class="torTopic"><b>{t.TOPIC_TITLE}</b></a>

#
#-----[ IN-LINE BEFORE, ADD ]---------------------------------
#    
#<span title="{L_EXTERNAL_T}">{t.EXT}</span> <a href="{TOPIC_URL}{t.HREF_TOPIC_ID}" class="torTopic"><b>{t.TOPIC_TITLE}</b></a>

<span title="{L_EXTERNAL_T}">{t.EXT}</span> 

# 
#-----[ OPEN ]---------------------------------
# 
templates/default/tracker.tpl

#
#-----[ FIND ]---------------------------------
#
<a class="{tor.DL_CLASS}<!-- IF AJAX_TOPICS --> folded2 tLink<!-- ENDIF -->" <!-- IF AJAX_TOPICS -->onclick="ajax.view_post({tor.POST_ID}, this); return false;"<!-- ENDIF --> href="{TOPIC_URL}{tor.TOPIC_ID}"><!-- IF tor.TOR_FROZEN -->{tor.TOPIC_TITLE}<!-- ELSE --><b>{tor.TOPIC_TITLE}</b><!-- ENDIF --></a>

#
#-----[ REPLACE WITH ]---------------------------------
# 		
<span title="{L_EXTERNAL_T}">{tor.EXT}</span> <a class="{tor.DL_CLASS}<!-- IF AJAX_TOPICS --> folded2 tLink<!-- ENDIF -->" <!-- IF AJAX_TOPICS -->onclick="ajax.view_post({tor.POST_ID}, this); return false;"<!-- ENDIF --> href="{TOPIC_URL}{tor.TOPIC_ID}"><!-- IF tor.TOR_FROZEN -->{tor.TOPIC_TITLE}<!-- ELSE --><b>{tor.TOPIC_TITLE}</b><!-- ENDIF --></a>


#
#-----[ SAVE/CLOSE ALL FILES ]---------------------------------
#
# EoM
