<?php
!function_exists('readover') && exit('Forbidden');
@include_once(D_P.'data/bbscache/cn_config.php');

if (empty($action)) {

	require_once(R_P.'require/credit.php');
	ifcheck($cn_open,'open');
	ifcheck($cn_remove,'remove');
	ifcheck($cn_newcolony,'newcolony');
	ifcheck($cn_virement,'virement');

	$creategroup = ''; $num = 0;
	foreach ($ltitle as $key => $value) {
		if ($key!=1 && $key!=2) {
			$num++;
			$htm_tr = $num % 4 == 0 ? '</tr><tr>' : '';
			$g_checked = strpos($cn_groups,",$key,")!==false ? 'checked' : '';
			$creategroup .= "<td><input type=\"checkbox\" name=\"groups[]\" value=\"$key\" $g_checked>$value</td>$htm_tr";
		}
	}
	$creategroup && $creategroup = "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\" align=\"center\"><tr>$creategroup</tr></table>";

	require_once PrintHack('admin');

} elseif ($action == 'setting') {

	@include_once(D_P.'data/bbscache/cn_config.php');
	!is_array($config = $_POST['config']) && $config = array();
	foreach ($config as $key => $value) {
		if ($value) {
			$isint = false;
			if ($_POST['step']=='basic') {
				if ($key=='name' || $key=='moneytype') {
					$config[$key] = Char_cv($value);
				} elseif ($key=='rate') {
					$config[$key] = (double)$value;
				} else {
					$isint = true;
				}
			} else {
				$isint = true;
			}
			$isint && $config[$key] = (int)$value;
		}
	}
	if ($_POST['step']=='basic') {
		!is_array($groups = $_POST['groups']) && $groups = array();
		$config['groups'] = ','.implode(',',$groups).',';
	}
	$updatecache = false;
	foreach ($config as $key => $value) {
		if (${'cn_'.$key}!=$value) {
			$db->pw_update(
				"SELECT hk_name FROM pw_hack WHERE hk_name=".pwEscape("cn_$key"),
				"UPDATE pw_hack SET hk_value=".pwEscape($value)."WHERE hk_name=".pwEscape("cn_$key"),
				"INSERT INTO pw_hack SET hk_name=".pwEscape("cn_$key").",hk_value=".pwEscape($value)
			);
			$updatecache = true;
		}
	}
	$j_url = '';
	if ($_POST['step']=='updatecache') {
		$updatecache = true;
		$j_url = "$basename&action=cache";
	} elseif ($_POST['step']=='photo') {
		$j_url = "$basename&action=photo";
	}
	$updatecache && updatecache_cy();
	adminmsg('operate_success',$j_url);

} elseif ($action == 'photo') {

	@include_once(D_P.'data/bbscache/cn_config.php');
	require_once(R_P.'require/credit.php');

	!in_array($cn_mkdir,array(1,2,3)) && $cn_mkdir = 1;
	${'mkdir'.$cn_mkdir} = 'checked';

	ifcheck($cn_phopen,'phopen');
	require_once PrintHack('admin');

} elseif ($action == 'class') {

	@include_once(D_P.'data/bbscache/cn_config.php');
	$cnclassdb = array();
	$query = $db->query('SELECT * FROM pw_cnclass ORDER BY cid');
	while ($rt = $db->fetch_array($query)) {
		$rt['cnsum'] = (int)$rt['cnsum'];
		$cnclassdb[] = $rt;
	}
	$db->free_result($query);
	require_once PrintHack('admin');

} elseif ($action == 'update_cl') {

	$updatecache = false;
	$j_url = "$basename&action=class";
	InitGP(array('step'),'GP',1);
	if ($step=='add') {
		!is_array($cname = $_POST['cname']) && $cname = array();
		$insert = '';
		$cnames = array();
		foreach ($cname as  $key => $value) {
			if (is_numeric($key)) {
				$value = Char_cv(trim($value));
				if ($value) {
					$cnames[] = $value;
					$insert .= ",('$value')";
				}
			}
		}
		if ($cnames) {
			$query = $db->query("SELECT cname FROM pw_cnclass WHERE cname IN (".pwImplode($cnames).")");
			while ($rt = $db->fetch_array($query,MYSQL_NUM)) {
				$rt[0] = addslashes($rt[0]);
				$insert = str_replace(",('$rt[0]')",'',$insert);
			}
		}
		if ($insert) {
			$updatecache = true;
			$db->update('INSERT INTO pw_cnclass (cname) VALUES '.substr($insert,1));
		}
	} elseif ($step=='edit') {
		!is_array($selid = $_POST['selid']) && $selid = array();
		foreach ($selid as  $key => $value) {
			if (is_numeric($key)) {
				$value = Char_cv(trim($value));
				if ($value && !$db->get_value("SELECT cid FROM pw_cnclass WHERE cname=".pwEscape($value)."AND cid!=".pwEscape($key))) {
					$updatecache = true;
					$db->update("UPDATE pw_cnclass SET cname=".pwEscape($value)."WHERE cid=".pwEscape($key));
				}
			}
		}
	} elseif ($step=='del') {
		$id = (int)$_GET['id'];
		if ($id) {
			$updatecache = true;
			$db->update("UPDATE pw_colonys SET classid='' WHERE classid=".pwEscape($id));
			$db->update("DELETE FROM pw_cnclass WHERE cid=".pwEscape($id));
		}
	} elseif ($step=='updatecache') {
		$db->update("UPDATE pw_cnclass SET cnsum='0'");
		$query = $db->query("SELECT id,classid,COUNT(*) FROM pw_colonys WHERE classid>0 GROUP BY classid");
		while ($rt = $db->fetch_array($query,MYSQL_NUM)) {
			if (!$db->get_value("SELECT COUNT(*) FROM pw_cnclass WHERE cid=".pwEscape($rt[1],false))) {
				$db->update("UPDATE pw_colonys SET classid='0' WHERE id=".pwEscape($rt[0],false));
			} else {
				$db->update("UPDATE pw_cnclass SET cnsum=".pwEscape($rt[2],false)."WHERE cid=".pwEscape($rt[1],false));
			}
		}
		$updatecache = true;
		$j_url = "$basename&action=cache";
	}
	$updatecache && updatecache_cnc();
	adminmsg('operate_success',$j_url);

} elseif ($action == 'colony') {

	@include_once(D_P.'data/bbscache/cn_config.php');
	@include_once(D_P.'data/bbscache/cn_class.php');
	!is_array($cnclassdb) && $cnclassdb = array();

	$pages = '';
	$db_perpage = 20;
	$colonys = array();
	InitGP(array('page'),'GP',2);
	$page<1 && $page = 1;
	$id = ($page-1)*$db_perpage;
	$query = $db->query("SELECT id,cname,classid FROM pw_colonys".pwLimit($id,$db_perpage));
	while ($rt = $db->fetch_array($query)) {
		$rt['cname'] = trim($rt['cname']);
		$rt['classname'] = $rt['classid'] ? $cnclassdb[$rt['classid']] : '';
		$colonys[] = $rt;
	}
	$db->free_result($query);
	$count = $db->get_value('SELECT COUNT(*) FROM pw_colonys');
	if ($count > $db_perpage) {
		require_once(R_P.'require/forum.php');
		$pages = numofpage($count,$page,ceil($count/$db_perpage),"$basename&action=colony&");
	}
	require_once PrintHack('admin');

} elseif ($action == 'update_c') {

	InitGP(array('step'),'GP',1);
	if ($step=='edit') {
		!is_array($cid = $_POST['cid']) && $cid = array();
		!is_array($cname = $_POST['cname']) && $cname = array();
		$sleep = 0;
		foreach ($cname as  $key => $value) {
			$value = Char_cv(trim($value));
			if (is_numeric($key) && $value && !$db->get_value("SELECT COUNT(*) FROM pw_colonys WHERE cname=".pwEscape($value)."AND id!=".pwEscape($key))) {
				$newcid = (int)$cid[$key];
				$oldcid = $db->get_value("SELECT classid FROM pw_colonys WHERE id=".pwEscape($key));
				if ($newcid!=$oldcid) {
					$sleep%20==0 && sleep(1);
					$sleep++;
					$db->update("UPDATE pw_cnclass SET cnsum=cnsum-1 WHERE cid=".pwEscape($oldcid));
					$db->update("UPDATE pw_cnclass SET cnsum=cnsum+1 WHERE cid=".pwEscape($newcid));
				}
				$db->update("UPDATE pw_colonys SET".pwSqlSingle(array('cname'=>$value,'classid'=>$newcid))."WHERE id=".pwEscape($key));
			}
		}
	} elseif ($step=='del') {
		$id = (int)$_GET['id'];
		$rt = $db->get_one("SELECT classid,cnimg FROM pw_colonys WHERE id=".pwEscape($id));
		if (!empty($rt)) {
			$ftp = null;
			if ($db_ifftp) {
				require_once(R_P.'require/ftp.php');
				$ftp = new FTP($ftp_server,$ftp_port,$ftp_user,$ftp_pass,$ftp_dir);
			}
			Delcnimg($rt['cnimg']);
			$db->update("DELETE FROM pw_argument WHERE gid=".pwEscape($id));
			$db->update("DELETE FROM pw_cmembers WHERE colonyid=".pwEscape($id));
			$db->update("DELETE FROM pw_colonys  WHERE id=".pwEscape($id));
			$db->update("UPDATE pw_cnclass SET cnsum=cnsum-1 WHERE cid=".pwEscape($rt['classid']));
			if ($ftp) {
				$ftp->close(); unset($ftp);
			}
		}
	}
	updatecache_cnc();
	adminmsg('operate_success',"$basename&action=colony");
} elseif ($action=='log') {
	if ($_POST['step']!='del') {
		@include_once(D_P.'data/bbscache/cn_config.php');
		require_once GetLang('logtype');
		InitGP(array('keyword','page'));
		$db_perpage = 20;
		$logdb = array();
		$pages = $sqladd = $addpages = '';
		if ($keyword) {
			$sqladd = " AND descrip LIKE ".pwEscape("%$keyword%");
			$addpages = "&keyword=".rawurlencode($keyword);
		}
		(int)$page<1 && $page = 1;
		$id = ($page-1)*$db_perpage;
		$query = $db->query("SELECT id,type,field2,field3,username1,timestamp,descrip FROM pw_forumlog WHERE type LIKE 'cy\_%' $sqladd".pwLimit($id,$db_perpage));
		while ($rt = $db->fetch_array($query)) {
			$rt['timestamp'] = get_date($rt['timestamp']);
			$rt['descrip'] = str_replace(array('[b]','[/b]'),array('<b>','</b>'),$rt['descrip']);
			$logdb[] = $rt;
		}
		$db->free_result($query);
		$count = $db->get_value("SELECT COUNT(*) FROM pw_forumlog WHERE type LIKE 'cy\_%' $sqladd");
		if ($count > $db_perpage) {
			require_once(R_P.'require/forum.php');
			$pages = numofpage($count,$page,ceil($count/$db_perpage),"$basename&action=log$addpages&");
		}
		require_once PrintHack('admin');
	} else {
		InitGP(array('selid'),'P',1);
		if (!($selid = checkselid($selid))) {
			$basename = 'javascript:history.go(-1);';
			adminmsg('operate_error');
		}
		$selid && $db->update("DELETE FROM pw_forumlog WHERE type LIKE 'cy\_%' AND id IN($selid)");
		adminmsg('operate_success',"$basename&action=log");
	}
} elseif ($action=='cache') {
	if ($_POST['step']=='delcolony') {
		$ftp = null;
		if ($db_ifftp) {
			require_once(R_P.'require/ftp.php');
			$ftp = new FTP($ftp_server,$ftp_port,$ftp_user,$ftp_pass,$ftp_dir);
		}
		$query = $db->query("SELECT id,cnimg FROM pw_colonys WHERE classid<1");
		while ($rt = $db->fetch_array($query,MYSQL_NUM)) {
			Delcnimg($rt[1]);
			$db->update("DELETE FROM pw_argument WHERE gid=".pwEscape($rt[0],false));
			$db->update("DELETE FROM pw_cmembers WHERE colonyid=".pwEscape($rt[0],false));
			$db->update("DELETE FROM pw_colonys  WHERE id=".pwEscape($rt[0],false));
		}
		if ($ftp) {
			$ftp->close(); unset($ftp);
		}
		adminmsg('operate_success',"$basename&action=cache");
	} else {
		@include_once(D_P.'data/bbscache/cn_config.php');
		require_once PrintHack('admin');
	}
} elseif ($action=='argument'){
	InitGP(array(step));
	if($step == 'list'){
		InitGP(array('page','cid','author','ckauthor','keyword','ktype','ttype','ckkeyword','postdate1','postdate2','topped','orderby','sc','perpage'));
		if((int)$cid > 0){
			$sql .= ($sql ? " AND" : "")." c.classid=".pwEscape($cid);
			$addpage .= "cid=$cid&";
		}

		if((int)$ttype > 0){
			if($ttype == 1){
				$sql .= ($sql ? " AND" : "")." a.tpcid='0'";
			}elseif($ttype == 2){
				$sql .= ($sql ? " AND" : "")." a.tpcid>'0'";
			}
		}

		if(strlen($author) > 0){
			if($ckauthor){
				$sql .= ($sql ? " AND" : "")." a.author=".pwEscape($author);
				$addpage .="author=$author&ckauthor=$ckauthor&";
			}else{
				$sql .= ($sql ? " AND" : "")." a.author LIKE ".pwEscape("%".str_replace('*','%',$author)."%");
				$addpage .="author=$author&";
			}
		}
		if(strlen($keyword) > 0){
			if($ktype == 'subject'){
				if($ckkeyword){
					$sql .= ($sql ? " AND" : "")." a.subject=".pwEscape($keyword);
					$addpage .="subject=$keyword&ckkeyword=$ckkeyword&";
				}else{
					$sql .= ($sql ? " AND" : "")." a.subject LIKE ".pwEscape("%".str_replace('*','%',$keyword)."%");
					$addpage .="subject=$keyword&";
				}
			}elseif($ktype == 'content'){
				if($ckkeyword){
					$sql .= ($sql ? " AND" : "")." a.content=".pwEscape($keyword);
					$addpage .="content=$keyword&ckkeyword=$ckkeyword&";
				}else{
					$sql .= ($sql ? " AND" : "")." a.content LIKE ".pwEscape("%".str_replace('*','%',$keyword)."%");
					$addpage .="content=$keyword&";
				}
			}
		}

		if (strlen($postdate1) > 0 || strlen($postdate2) > 0) {
			if ($postdate1) {
				!is_numeric($postdate1) && $postdate1 = PwStrtoTime($postdate1);
				$sql .= ($sql ? ' AND' : '')." a.postdate>".pwEscape($postdate1);
				$addpage .= "postdate1=$postdate1&";
			}
			if ($postdate2) {
				!is_numeric($postdate2) && $postdate2 = PwStrtoTime($postdate2);
				$sql .= ($sql ? ' AND' : '')." a.postdate<".pwEscape($postdate2);
				$addpage .= "postdate2=$postdate2&";
			}
		}

		if ($topped > 0){
			$sql .= ($sql ? " AND" : "")." a.topped=".pwEscape($topped);
			$addpage .= "topped=$topped&";
		}
		$where = $sql ? "WHERE ".$sql : "";
		$orderby = $orderby == 'postdate' ? 'ORDER BY a.postdate' : 'ORDER BY a.authorid';
		$sc != 'ASC' && $sc = 'DESC';
		!$perpage && $perpage = $db_perpage;
		(int)$page<1 && $page = 1;
		$limit = pwLimit(($page-1)*$perpage,$perpage);
		$query = $db->query("SELECT a.tid,a.tpcid,a.gid,a.author,a.authorid,a.postdate,a.topped,a.subject,c.cname FROM pw_argument a LEFT JOIN pw_colonys c ON a.gid=c.id $where $orderby $sc $limit");
		while($rt = $db->fetch_array($query)){
			$rt['postdate'] = get_date($rt['postdate'],'Y-m-d');
			$rt['baktid'] = $rt['tid'];
			$rt['tpcid'] != 0 && $rt['baktid'] = $rt['tpcid'];
			$argumentdb[] = $rt;
		}
		$db->free_result($query);
		@extract($db->get_one("SELECT COUNT(*) AS count FROM pw_argument a LEFT JOIN pw_colonys c ON a.gid=c.id $where"));
		if ($count > $perpage) {
			require_once(R_P.'require/forum.php');
			$pages = numofpage($count,$page,ceil($count/$perpage),"$basename&action=argument&step=list&$addpage");
		}
	}elseif($step == 'delete'){
		$selids = '';
		InitGP(array('selid'),'P',1);
		if (is_array($selid)) {
			foreach ($selid as $value) {
				if (is_numeric($value)) {
					$selids[] = $value;
				}
			}
			$selids = pwImplode($selids);
		}
		!$selids && adminmsg('selid_illegal');
		$selids = strpos($selids,',')!==false ? "IN ($selids)" : "= $selids";
		$db->update("DELETE FROM pw_argument WHERE tid $selids");
		$db->update("DELETE FROM pw_argument WHERE tpcid $selids");
		adminmsg('operate_success',"$basename&action=argument&");
	}else{
		@include_once(D_P.'data/bbscache/cn_class.php');
		empty($cnclassdb) && $cnclassdb = array();
		foreach($cnclassdb as $key => $value){
			$classoption .= '<option value="'.$key.'">'.$value[cname].'</option>';
		}
	}
	require_once PrintHack('admin');
}
function Delcnimg($filename){
	global $attachdir,$db_ftpweb,$ftp;
	if (strpos($filename,'..')!==false) {
		return false;
	}
	if (file_exists("$attachdir/cn_img/$filename")) {
		P_unlink("$attachdir/cn_img/$filename");
	} elseif ($db_ftpweb) {
		$ftp->delete("cn_img/$filename");
	}
}

function updatecache_cnc(){
	global $db;
	$cnclassdb = array();
	$query = $db->query('SELECT cid,cname,cnsum FROM pw_cnclass ORDER BY cid');
	while ($rt = $db->fetch_array($query)) {
		$cnclassdb[$rt['cid']] = array('cname' => $rt['cname'],'cnsum' => $rt['cnsum']);
	}
	writeover(D_P."data/bbscache/cn_class.php","<?php\r\n\$cnclassdb=".pw_var_export($cnclassdb).";\r\n?>");
}
?>