<?php
!function_exists('adminmsg') && exit('Forbidden');

@include_once(D_P.'data/bbscache/o_config.php');

if (empty($action)) {

	if (empty($_POST['step'])) {

		require_once(R_P.'require/credit.php');
		ifcheck($o_open,'open');
		ifcheck($o_remove,'remove');
		ifcheck($o_newcolony,'newcolony');
		ifcheck($o_virement,'virement');
		$moneyname = $credit->cType[$o_moneytype];

		$creategroup = ''; $num = 0;
		foreach ($ltitle as $key => $value) {
			if ($key != 1 && $key != 2) {
				$num++;
				$htm_tr = $num % 4 == 0 ? '</tr><tr>' : '';
				$g_checked = strpos($o_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 PrintMode('groups');

	} else {

		InitGP(array('config'),'GP',0);
		InitGP(array('groups'),'GP',2);

		foreach ($config as $key => $value) {
			switch ($key) {
				case 'moneytype':
					$config[$key] = Char_cv($value);break;
				case 'rate':
					$config[$key] = (double)$value;break;
				default:
					$config[$key] = (int)$value;
			}
		}
		$config['groups'] = is_array($groups) ? ','.implode(',',$groups).',' : '';

		$updatecache = false;
		foreach ($config as $key => $value) {
			if (${'o_'.$key} != $value) {
				$db->pw_update(
					'SELECT hk_name FROM pw_hack WHERE hk_name=' . pwEscape("o_$key"),
					'UPDATE pw_hack SET ' . pwSqlSingle(array('hk_value' => $value, 'vtype' => 'string')) . ' WHERE hk_name=' . pwEscape("o_$key"),
					'INSERT INTO pw_hack SET ' . pwSqlSingle(array('hk_name' => "o_$key", 'vtype' => 'string', 'hk_value' => $value))
				);
				$updatecache = true;
			}
		}
		$updatecache && updatecache_conf('o',true);
		adminmsg('operate_success',$j_url);
	}

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

	!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_cnc();
	adminmsg('operate_success',$j_url);

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

	$o_classdb = array();
	$query = $db->query('SELECT * FROM pw_cnclass ORDER BY cid');
	while ($rt = $db->fetch_array($query)) {
		$rt['cnsum'] = (int)$rt['cnsum'];
		$o_classdb[] = $rt;
	}
	$db->free_result($query);
	require_once PrintMode('groups');

} 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') {

	!is_array($o_classdb) && $o_classdb = 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'] ? $o_classdb[$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 PrintMode('groups');

} 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)) {
			Delcnimg($rt['cnimg']);
			pwFtpClose($ftp);
			$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']));
		}
	}
	updatecache_cnc();
	adminmsg('operate_success',"$basename&action=colony");

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

	if ($_POST['step'] != 'del') {

		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 PrintMode('groups');
	} 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') {
		$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));
		}
		pwFtpClose($ftp);
		adminmsg('operate_success',"$basename&action=cache");
	} else {
		require_once PrintMode('groups');
	}
} 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 {
		empty($o_classdb) && $o_classdb = array();
		foreach($o_classdb as $key => $value){
			$classoption .= '<option value="'.$key.'">'.$value[cname].'</option>';
		}
	}
	require_once PrintMode('groups');
}
function Delcnimg($filename) {
	if (strpos($filename,'..') !== false) {
		return false;
	}
	pwDelatt("cn_img/$filename",$GLOBALS['db_ifftp']);
}

function updatecache_cnc() {
	global $db;
	$classdb = array();
	$query = $db->query('SELECT cid,cname FROM pw_cnclass ORDER BY cid');
	while ($rt = $db->fetch_array($query)) {
		$classdb[$rt['cid']] = $rt['cname'];
	}
	$classdb = serialize($classdb);
	$db->pw_update(
		"SELECT hk_name FROM pw_hack WHERE hk_name='o_classdb'",
		'UPDATE pw_hack SET ' . pwSqlSingle(array('hk_value' => $classdb, 'vtype' => 'array')) . " WHERE hk_name='o_classdb'",
		'INSERT INTO pw_hack SET ' . pwSqlSingle(array('hk_name' => 'o_classdb', 'vtype' => 'array', 'hk_value' => $classdb))
	);
	updatecache_conf('o',true);
}
?>