<?php
define('THIS_SCRIPT', 'recycle');
require_once 'global.php';
$lang = load_lang($lang, 'recycle' );
include_once $fsetting['manageurl'].'inc/page.class.php';
$stats = $lang['forum.info1'];
$arrNavMenu = array(
		 0=>array('linktitle'=>$stats)
	);
head(1,0,0,$arrNavMenu);

unset($username, $flag);
$recycle = false;
$username = $db->scalar("SELECT username FROM {$dv}user WHERE userid='$userid'");
$flag = $db->scalar("SELECT flag FROM {$dv}admin WHERE adduser='$username'");
if($flag) {
	$flag = explode(',', $flag);
	if($flag[27] == 23) {
		$recycle = true;
	}
}
global $lang,$doaction;
$doaction= $_POST['doaction'];
if ($master !== true && $superboardmaster !== true && $recycle !== true){
	showmsg($lang['err.info1']);
}
switch($action){
	case 'view':
		view();
		break;
	case 'delpic':
		if ($master !== true){showmsg($lang['err.info5']);}
		delpic();
		break;
	case 'manage':
		if($doaction==$lang['tpl.str48']){
			manage();
		}
		elseif($doaction==$lang['tpl.str54']){
			forever_delete_topic();
		}
		break;
	case 'alldel':
		if ($master !== true){showmsg($lang['err.info5']);}
		alldel();
		break;
	default:
		main();
		break;
}

footer();

function main(){
	global $dv,$db,$action,$lang,$_DCACHE;
	global $bid,$tableid,$keyword,$page,$topiccount,$fsetting;
	global $page_size,$page,$page_count,$offset,$p; 
	if ($bid == '' || !is_numeric($bid)){$bid = 0;}
	if ($page == '' || !is_numeric($page)){$page = 1;}
	if ($tableid == '' || !is_numeric($tableid)){$tableid = 0;}
	$posttable = $dv. 'topic';
	$tbquery=$db->query("Select id,tablename,tabletype From {$dv}tablelist");
	if ($tableid != 0){
		while ($tb =& $db->fetch_array($tbquery)){
			if ($tableid == $tb['id']){
				$posttable = $tb['tablename'];
				break;
			}
		}
	}
	if ($posttable == $dv.'topic'){$tableid = 0;}

	if ($keyword != ''){
		if ($tableid == 0){
			$kstr = "and (title like '%{$keyword}%' or postusername='{$keyword}')";
		}else{
			$kstr = "and (topic like '%{$keyword}%' or username='{$keyword}')";
		}
	}
	if ($bid != 0){
		$bstr = "and locktopic={$bid}";
	}
	if ($tableid == 0){
		$sql = "Select /*!40001 SQL_CACHE*/ topicid as id,topicid as replyid,title as topic,locktopic as bid,postusername as username,postuserid as userid,posttable,dateandtime From {$posttable} Where boardid=444 {$bstr} {$kstr} order by topicid desc";
		$sql_c = "Select Count(*) as length From {$posttable} Where boardid=444 {$bstr} {$kstr}";
	}else{
		$sql = "Select /*!40001 SQL_CACHE*/ rootid as id,topic,body,locktopic as bid,username,postuserid as userid,announceid as replyid,dateandtime,parentid From {$posttable} Where boardid=444 {$bstr} {$kstr} order by announceid desc";
		$sql_c = "Select Count(*) as length From {$posttable} Where boardid=444 {$bstr} {$kstr}";
	}
	$topiccount=$db->scalar($sql_c);
	$page_size=30;
	$tsquery = $db->query($sql,array('absolutePage'=>$page,'pageSize'=>$page_size));
	if ($page=="" or $page<1)
		$page=1;
	 $page_count=ceil($topiccount/$page_size);
	if ($page>$page_count)
		$page=$page_count;
	$offset=$page;
	if( $offset < 1 ) $offset = 1;
	if( empty($_DCACHE['all_forums']) ){
		include_once CACHE_PATH.'board/board_all.php';
	}
	require_once printout('recycle');
}


function forever_delete_topic(){//永久删除主题贴子
	global $db,$dv,$lang,$id,$replyid,$boardid;
	$postidarr=array();
	$postidarr=$id;
	foreach ($postidarr as $postidset){
		$cutid=explode('_',$postidset);
		$postidstr.=$cutid[0].',';
	}
	$postidstr=substr($postidstr,0,-1);
	$postidarrlist=explode(',',$postidstr);
	foreach ($postidarrlist as $postidarr_id){
		del_ft($postidarr_id); // 删除全文索引相关数据
		$sql=$db->query("select boardid,posttable from {$dv}topic where topicid={$postidarr_id}");
		$arr=$db->fetch_array($sql);
		$posttable=$arr['posttable'];
		$topicboardid=$arr['boardid'];
		$db->query("delete From {$posttable} Where rootid IN ({$postidstr}) and forumtype=0");
		delupfiles($topicboardid, $postidarr_id.'|'); // 删除附件
	}
	$db->query("delete from {$dv}topic where topicid IN ({$postidstr})");
	showmsg($lang['tpl.str55']);
	exit;
}
function view(){
	global $dv,$db,$action,$lang,$master;
	global $id,$replyid;
	if ($replyid == '' || !is_numeric($replyid)){$replyid = 0;}
	if ($id == '' || !is_numeric($id)){showmsg($lang['err.info3']);}
	$query=$db->query("Select posttable,boardid From {$dv}topic Where topicid={$id}");
	if ($ts =& $db->fetch_array($query)){
		$boardid = $ts['boardid'];
		if ($replyid == 0){
			$query_1=$db->query("Select announceid,rootid,parentid,topic,body,username,postuserid,dateandtime From {$ts[posttable]} where rootid={$id} and parentid=0 and boardid=444 and forumtype=0");
		}else{
			$query_1=$db->query("Select announceid,parentid,boardid,username,postuserid,topic,body,dateandtime,length,rootid,layer,orders,isbest,ip,expression,locktopic,signflag,emailflag,isagree,isaudit,isupload,postbuyuser,ubblist,getmoney,usetools,getmoneytype From {$ts[posttable]} where rootid={$id} and boardid=444 and forumtype=0");				
		}
		if ($ps = $db->fetch_array($query_1)){
			$ps['dateandtime'] = gmdate("Y-m-d H:i:s",$ps['dateandtime']+getUserTimeZoneOffset());
		}else{
			showmsg($lang['err.info4']);
		}
	}else{
		showmsg($lang['err.info4']);
	}
	require_once printout('recycle');
}

function delpic(){
	global $dv,$db,$lang,$id,$replyid;
	if ($id == '' || !is_numeric($id)){showmsg($lang['err.info3']);}
	if ($replyid != '' && !is_numeric($replyid)){showmsg($lang['err.info3']);}
	$query=$db->query("Select posttable,boardid,title,isvote,pollid,locktopic From {$dv}topic Where topicid={$id}");
	if ($ts =& $db->fetch_array($query)){
		$boardid = $ts['boardid'];
		$posttable = $ts['posttable'];
		$title = $ts['title'];
		$isvote = $ts['isvote'];
		$pollid = $ts['pollid'];
	}else{
		showmsg($lang['err.info4']);
	}
	if ($replyid == ''){
		if ($boardid != 444){showmsg($lang['err.info6']);}
		$db->query("delete From {$posttable} Where rootid={$id} and forumtype=0");
		$db->query("delete From {$dv}topic where topicid={$id}");
		del_ft($id); // 删除全文索引相关数据
		delupfiles($ts['locktopic'], $id.'|'); // 删除附件
		tolog($lang['forum.info2'].$title);
	}else{
		$query=$db->query("select parentid,isbest,locktopic,boardid From {$posttable} where announceid={$replyid}");
		if ($ts =& $db->fetch_array($query)){
			if ($ts['parentid'] == 0){
				if ($boardid != 444){showmsg($lang['err.info6']);}
				if ($isvote == 1){
					$db->query("delete From {$dv}vote Where voteid={$pollid}");
					$db->query("delete From {$dv}voteuser Where voteid={$pollid}");
				}
				if (intval($ts['isbest']) == 1){
					$db->query("delete from {$dv}besttopic Where announceid={$replyid}");
				}
				$db->query("delete From {$posttable} Where rootid={$id} and forumtype=0");
				$db->query("delete From {$dv}topic where topicid={$id}");
				del_ft($id); // 删除全文索引相关数据
				delupfiles($ts['locktopic'], $id.'|'); // 删除附件
				tolog($lang['forum.info2'].$title);
			}else{
				$db->query("delete From {$posttable} Where rootid={$id} and announceid={$replyid}");
				tolog(str_replace('{$title}',$title,$lang['forum.info3']));
			}
		}else{
			showmsg($lang['err.info4']);
		}
	}
	showmsg($lang['suc.info1']);
}

function manage(){
	global $dv,$db,$lang,$action,$id;
	if ($id == ''){showmsg($lang['err.info3']);exit;}
	$allpost = $alltopic = 0;
	foreach($id AS $val){
		$topicid = explode('_',$val);
		if (is_numeric($topicid[0]) && $topicid[0] != ''){
			if ($topicid[1] == ''){
				$topicid[1] == $topicid[0];
			}
			$query=$db->query("select boardid,locktopic,posttable,title From {$dv}topic Where topicid='{$topicid[0]}' and boardid<>777");
			if ($ts =& $db->fetch_array($query)){
				$posttable = $ts['posttable'];
				$locktopic = $ts['boardid'];
				$boardid = $ts['locktopic'];
				if ($topicid[0] == $topicid[1]){
					if ($locktopic == 444){
						$child=$db->scalar("Select Count(*) From {$posttable} where boardid<>777 and rootid={$topicid[0]} and forumtype=0");
						if (is_null($child)){$child = 1;}
						$child = $child - 1;
						$allpost += $child;
						$alltopic += 1;
						$msginfo .= '|||' .str_replace('{$topicid}',$topicid[0],$lang['forum.info6']);
						$db->query("update {$posttable} set boardid={$boardid},locktopic=0 Where boardid<>777 and rootid={$topicid[0]} and forumtype=0"); // 还原
						$db->query("update {$dv}topic Set boardid={$boardid},locktopic=0,child={$child} Where topicid={$topicid[0]}"); // 还原
						restore_ft($topicid[0], $boardid, $locktopic); // 还原全文索引相关数据
					}else{
						$msginfo .= '|||' .str_replace('{$topicid}',$topicid[0],$lang['forum.info5']);
					}
				}else{
					$query=$db->query("Select parentid From {$posttable} where boardid=444 and rootid={$topicid[0]} and announceid='{$topicid[1]}'");
					if ($ps =& $db->fetch_array($query)){
						if ($ps['parentid'] == 0){
							$child = 0;
							if ($locktopic != 444){
								$boardid = $locktopic;
							}
							$alltopic += 1;
							$msginfo .= '|||' .str_replace('{$topicid}',$topicid[0],$lang['forum.info6']);
							$db->query("update {$dv}topic Set boardid={$boardid},locktopic=0,child={$child} Where topicid={$topicid[0]}"); // 还原
							$db->query("update {$posttable} set boardid={$boardid},locktopic=0 Where rootid={$topicid[0]} and announceid={$topicid[1]}"); // 还原
							restore_ft($topicid[0], $boardid, $locktopic); // 还原全文索引相关数据
						}else{
							if ($locktopic != 444){
								$boardid = $locktopic;
								$allpost += 1;
								$db->query("update {$posttable} set boardid={$boardid},locktopic=0 Where rootid={$topicid[0]} and announceid={$topicid[1]}");
								$db->query("update {$dv}topic Set boardid={$boardid},locktopic=0,child=child+1  Where topicid={$topicid[0]}");
								restore_ft($topicid[0], $boardid, $locktopic); // 还原全文索引相关数据
								$msginfo .= '|||' .str_replace('{$topicid}',$topicid[1],$lang['forum.info9']);
							}else{
								$msginfo .= '|||' .str_replace('{$topicid}',$topicid[1],$lang['forum.info8']);
							}
						}
					}else{
						$msginfo .= '|||' .str_replace('{$topicid}',$topicid[1],$lang['forum.info7']);
					}
				}
			}else{
				$msginfo .= '|||' .str_replace('{$topicid}',$topicid[0],$lang['forum.info4']);
			}
		}
	}
	$lang['forum.info10'] = str_replace('{$allpost}',$allpost,$lang['forum.info10']);
	$lang['forum.info10'] = str_replace('{$alltopic}',$alltopic,$lang['forum.info10']);
	showmsg($lang['forum.info10'].'|||'.$msginfo);
	exit;
}

function alldel(){
	global $dv,$db,$action,$lang,$maxcount;
	$isdo = 0;
	if ($maxcount != '' && is_numeric($maxcount)){
		$isdo = 1;
		$i = 0;
		require_once printout('recycle');
		$query=$db->query("SELECT topicid, posttable,isvote,pollid,isbest,boardid,locktopic From {$dv}topic Where boardid = 444 ORDER BY topicid Limit {$maxcount}");
		while ($ts =& $db->fetch_array($query)){
			$i++;
			$db->query("DELETE FROM {$ts[posttable]} WHERE rootid={$ts[topicid]} and forumtype=0");
			$db->query("DELETE From {$dv}topic WHERE topicid={$ts[topicid]}");
			del_ft($ts['topicid']); // 删除全文索引相关数据
			delupfiles($ts['locktopic'], $id.'|'); // 删除附件
			if ($ts['isvote'] == 1){
				$db->query("delete From {$dv}vote Where voteid={$ts[pollid]}");
				$db->query("delete From {$dv}voteuser Where voteid={$ts[pollid]}");
			}
			if (intval($ts['isbest']) == 1){
				$db->query("delete From {$dv}besttopic Where rootid={$ts[topicid]}");
			}
		}
		$k = ceil( (float)$i / 100 );
		for ($ii=0; $ii<$i; $ii++){
			$lang['forum.info13'] = str_replace('{$i}',$ii+1,$lang['forum.info13']);
			echo "<script language=\"javascript\" type=\"text/javascript\">plantext('{$lang['forum.info13']}');</script>";
			flush();
			if ($k > 0){
				if( ($ii+1) % $k == 0 || ($ii+1) == $i ){
					$inow = ceil( (float)(($ii+1) / $i)*100 );
					echo "<script language=\"javascript\" type=\"text/javascript\">planwidth({$inow});</script>";
					flush();
				}
			}else{
				if (($ii+1) == $i){
					$inow = ceil( (float)(($ii+1) / $i)*100 );
					echo "<script language=\"javascript\" type=\"text/javascript\">planwidth({$inow});</script>";
					flush();
				}
			}
		}
		if ($i == 0){
			DelAllRepost();
			echo "<script language=\"javascript\" type=\"text/javascript\">plantext('{$lang['forum.info11']}');</script>";
			flush();
		}else{
			$delcount=$db->scalar("SELECT Count(*) From {$dv}topic Where boardid = 444");
			if ($delcount == 0){
				DelAllRepost();
				$lang['forum.info14'] = str_replace('{$i}',$i,$lang['forum.info14']);
				tolog($lang['forum.info14']);
				echo "<script language=\"javascript\" type=\"text/javascript\">plantext('{$lang['forum.info14']}');</script>";
				flush();
			}else{
				$lang['forum.info15'] = str_replace('{$i}',$i,$lang['forum.info15']);
				$lang['forum.info16'] = str_replace('{$i}',$i,$lang['forum.info16']);
				$lang['forum.info16'] = str_replace('{$ii}',$delcount,$lang['forum.info16']);
				tolog($lang['forum.info15']);
				echo "<script language=\"javascript\" type=\"text/javascript\">plantext('{$lang['forum.info16']}');</script>";
				flush();
			}
		}
	}
	if ($maxcount = '' || !is_numeric($maxcount)){
		$maxcount = 500;
		require_once printout('recycle');
	}
}
function DelAllRepost(){
	global $dv,$db,$lang;
	$query=$db->query("Select tablename From {$dv}tablelist");
	while($ts =& $db->fetch_array($query)){
		$db->query("Delete From {$ts[tablename]} where boardid=444");
		$lang['forum.info12'] = str_replace('{$tablename}',$ts['tablename'],$lang['forum.info12']);
		echo "<script language=\"javascript\" type=\"text/javascript\">plantext('{$lang['forum.info12']}');</script>";
		flush();
		tolog($lang['forum.info12']);
	}
}

function tolog($info){
	global $dv,$db,$lang,$membername,$usertrueip;
	$info = i_addslashes($info);
	$db->query("Insert Into {$dv}log (l_announceid,l_boardid,l_touser,l_username,l_content,l_ip,l_type) values (0,0,'{$lang['forum.info1']}','$membername','$info','$usertrueip',0)");
}

function del_ft($argtopicid) // 删除全文索引相关数据
{
	if ($argtopicid <= 0) {
		return false;
	}
	global $dv, $db;
	$db->query("delete From {$dv}topic_ft where topicid={$argtopicid}", array('type'=>'SILENT')); // 删除全文索引
	$db->query("delete From {$dv}bbs_ft where rootid={$argtopicid}", array('type'=>'SILENT')); // 删除全文索引
}
function restore_ft($argtopicid,$argboardid,$arglocktopic) // 还原全文索引相关数据
{
	if ($argtopicid <= 0 OR $argboardid <= 0) {
		return false;
	}
	global $dv, $db;
	$db->query("UPDATE {$dv}topic_ft SET boardid='{$argboardid}',locktopic='{$arglocktopic}' WHERE topicid='{$argtopicid}'", array('type'=>'SILENT')); // 还原主题全文索引表的数据
	$db->query("UPDATE {$dv}bbs_ft SET boardid='{$argboardid}',locktopic='{$arglocktopic}' WHERE rootid='{$argtopicid}'", array('type'=>'SILENT')); // 还原帖子全文索引表的数据
}
function delupfiles($F_BoardID,$F_announceID) // 删除附件
{
	global $dv, $db;
	$documentroot = realpath(getenv('DOCUMENT_ROOT'));
	if ($query = $db->query("SELECT f_id, f_filename, f_viewname FROM {$dv}upfile WHERE f_boardid='{$F_BoardID}' AND f_announceid LIKE '{$F_announceID}%' AND f_flag=0")) {
		$fidlist = '';
		$comma = '';
		while ($dbinfo =& $db->fetch_array($query)) {
			$fidlist .= "{$comma}{$dbinfo['f_id']}";
			$comma = ',';
			if (!empty($dbinfo['f_filename'])) {
				if ($filepath = realpath($documentroot.'/'.$dbinfo['f_filename'])) {
					FileHandle::unlink($filepath);
				}
			}
			if (!empty($dbinfo['f_filename'])) {
				if ($viewfilepath = realpath($documentroot.'/'.$dbinfo['f_viewname'])) {
					FileHandle::unlink($viewfilepath);
				}
			}
		}
		if ($fidlist !== '') {
			$db->query("DELETE FROM {$dv}upfile WHERE f_id IN({$fidlist})");
		}
	}
}
?>