<?
/**
*
* @package ppkBB3cker
* @version $Id: importtorrents.php 1.000 20089-02-05 20:59:00 PPK $
* @copyright (c) 2008, 2009 PPK, Based On skytracker, torrenttrader
* http://ppkbb3cker.rx22.ru, http://protoneutron.narod.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
	exit;
}

require_once($phpbb_root_path."tracker/include/benc.$phpEx");

function torrents_import($data, $id)
{
	global $config, $phpbb_root_path, $db, $user, $phpEx;

	$tmpname = $phpbb_root_path.$config['upload_path'].'/'.$data['physical_filename'];

	if(!file_exists($tmpname))
	{
		return "[1] Torrent Error";
	}

	if(!filesize($tmpname))
	{
		return "[2] Torrent Error";
	}

	$dict = bdec_file($tmpname, $data['filesize']);
	if (!isset($dict))
	{
		return "[3] Torrent Error";
	}

	list($info) = dict_check($dict, "info");
	list($dname, $plen, $pieces) = dict_check($info, "name(string):piece length(integer):pieces(string)");

	/*if (!in_array($ann, $announce_urls, 1))
		return "[0] Torrent Error";*/

	if (strlen($pieces) % 20 != 0)
	{
		return "[4] Torrent Error";
	}

	$filelist = array();
	$totallen = dict_get($info, "length", "integer");
	if ($totallen!==false)
	{
		$filelist[] = array($dname, $totallen);
		$type = "single";
	}
	else
	{
		$flist = dict_get($info, "files", "list");
		if ($flist===false)
		{
			return "[5] missing both length and files";
		}
		if (!sizeof($flist))
		{
			return "[6] no files";
		}
		$totallen = 0;
		foreach ($flist as $fn)
		{
			list($ll, $ff) = dict_check($fn, "length(integer):path(list)");
			$totallen += $ll;
			$ffa = array();
			foreach ($ff as $ffe)
			{
				if($ffe["type"] != "string")
				{
					return "[7] filename error";
				}
				$ffa[] = $ffe["value"];
			}
			if(!sizeof($ffa))
			{
				return "[8] filename error";
			}
			$ffe = implode("/", $ffa);
			$filelist[] = array($ffe, $ll);
			if($ffe == 'Thumbs.db')
		        	{
		            	return "[9] Torrent Error";
		        	}
		}
		$type = "multi";
	}

	if(!$config['ppkbb_announce_url'])
	{
		$config['ppkbb_announce_url']=$config['script_path'].'/tracker/announce.'.$phpEx;
	}
	$forum_url=$config['server_protocol'].$config['server_name'];
	$announce_url=$forum_url.$config['ppkbb_announce_url'];
	$dict['value']['announce']=bdec(benc_str($announce_url));  // change announce url to local
	if($config['ppkbb_tprivate_flag'])
	{
		$dict['value']['info']['value']['private']=bdec('i1e');  // add private tracker flag
	}
	else
	{
		$dict['value']['info']['value']['private']=bdec('i0e');  // remove private tracker flag
	}
	$dict['value']['info']['value']['source']=bdec(benc_str( "{$forum_url} [{$config['server_name']}]")); // add link for bitcomet users
	unset($dict['value']['announce-list']); // remove multi-tracker capability
	unset($dict['value']['nodes']); // remove cached peers (Bitcomet & Azareus)
	unset($dict['value']['info']['value']['crc32']); // remove crc32
	unset($dict['value']['info']['value']['ed2k']); // remove ed2k
	unset($dict['value']['info']['value']['md5sum']); // remove md5sum
	unset($dict['value']['info']['value']['sha1']); // remove sha1
	unset($dict['value']['info']['value']['tiger']); // remove tiger
	unset($dict['value']['azureus_properties']); // remove azureus properties
	$dict=bdec(benc($dict)); // double up on the becoding solves the occassional misgenerated infohash
	$dict['value']['comment']=bdec(benc_str("{$user->lang['TORRENT_CREATED_FOR']} '{$config['server_name']}'")); // change torrent comment
	$dict['value']['created by']=bdec(benc_str("{$user->data['username']}")); // change created by
	$dict['value']['publisher']=bdec(benc_str("{$user->data['username']}")); // change publisher
	$dict['value']['publisher.utf-8']=bdec(benc_str("{$user->data['username']}")); // change publisher.utf-8
	$dict['value']['publisher-url']=bdec(benc_str("{$forum_url}memberlist.$phpEx?mode=viewprofile&u={$user->data['user_id']}")); // change publisher-url
	$dict['value']['publisher-url.utf-8']=bdec(benc_str("{$forum_url}memberlist.$phpEx?mode=viewprofile&u={$user->data['user_id']}")); // change publisher-url.utf-8
	list($info) = dict_check($dict, "info");

	$infohash = sha1($info["string"]);

	$res=$db->sql_query("SELECT id, post_msg_id, topic_id FROM ".TRACKER_TORRENTS_TABLE." WHERE info_hash='". $db->sql_escape($infohash) ."' LIMIT 1");
	$data=$db->sql_fetchrow($res);

	if($data['id'])
	{
		$q="SELECT p.post_approved, t.topic_id FROM ".POSTS_TABLE." p, ".TOPICS_TABLE." t WHERE t.topic_id='{$data['topic_id']}' AND p.topic_id=t.topic_id AND p.post_id='{$data['post_msg_id']}' LIMIT 1";
		$res=$db->sql_query($q);
		$data2=$db->sql_fetchrow($res);
		if($data2['topic_id'])
		{
			return "[10] Torrent Error: <a href='".$config['server_protocol'].$config['server_name'].$config['script_path'].'/viewtopic.php?t='.$data2['topic_id']."'>Duplicated Torrent</a>, Approved: <b>".($data2['post_approved'] ? 'Yes' : 'No').'</b>';
		}
		else
		{
			$r=$db->sql_query("DELETE FROM ".TRACKER_TORRENTS_TABLE." WHERE id='{$data['id']}'");
			$r=$db->sql_query("DELETE FROM ".TRACKER_FILES_TABLE." WHERE id='{$data['id']}'");
			$r=$db->sql_query("DELETE FROM ".TRACKER_THANKS_TABLE." WHERE torrent_id='{$data['id']}'");
			$r=$db->sql_query("DELETE FROM ".TRACKER_SNATCHED_TABLE." WHERE torrent='{$data['id']}'");
			$r=$db->sql_query("DELETE FROM ".TRACKER_PEERS_TABLE." WHERE torrent='{$data['id']}'");
		}
	}

	$tsize=0;

	foreach($filelist as $file)
	{
		$tsize+=$file[1];
		$db->sql_query("INSERT INTO ".TRACKER_FILES_TABLE." (id, filename, size) VALUES ('$id', '". $db->sql_escape($file[0]) ."', '{$file[1]}')");
	}

	$db->sql_query("INSERT INTO ".TRACKER_TORRENTS_TABLE." (id, info_hash, numfiles, type, size, last_cleanup, added) VALUES ('$id', '". $db->sql_escape($infohash) ."', '".sizeof($filelist)."', '$type', '$tsize', '".time()."', '".time()."')");

	$fp = fopen($tmpname, "w");
	if($fp)
	{
		@fwrite($fp, benc($dict), strlen(benc($dict)));
		fclose($fp);
	}

	return true;
}

function dict_check($d, $s)
{
	if($d["type"] != "dictionary")
	{
		return false;
	}
	$a = explode(":", $s);
	$dd = $d["value"];
	$ret = array();
	foreach($a as $k)
	{
		unset($t);
		if(preg_match('/^(.*)\((.*)\)$/', $k, $m))
		{
			$k = $m[1];
			$t = $m[2];
		}
		if(!isset($dd[$k]))
		{
			return false;
		}
		if(isset($t))
		{
			if($dd[$k]["type"] != $t)
			{
				return false;
			}
			$ret[] = $dd[$k]["value"];
		}
		else
		{
			$ret[] = $dd[$k];
		}
	}
	return $ret;
}

function dict_get($d, $k, $t)
{
	if($d["type"] != "dictionary")
	{
		return false;
	}
	$dd = $d["value"];
	if(!isset($dd[$k]))
	{
		return false;
	}
	$v = $dd[$k];
	if($v["type"] != $t)
	{
		return false;
	}
	return $v["value"];
}
?>