<?php
!defined('M_P') && exit('Forbidden');
!$winduid && Showmsg('not_login');
include_once(D_P.'data/bbscache/o_config.php');

InitGP(array('a'));
InitGP(array('cyid'), null, 2);

$colony = $db->get_one("SELECT c.*,cm.id AS ifcyer,cm.ifadmin FROM pw_colonys c LEFT JOIN pw_cmembers cm ON c.id=cm.colonyid AND cm.uid=" . pwEscape($winduid) . ' WHERE c.id=' . pwEscape($cyid));
empty($colony) && Showmsg('data_error');

if ($colony['cnimg']) {
	list($cnimg,$colony['imgtype']) = geturl("cn_img/$colony[cnimg]",'lf');
} else {
	$cnimg = $pwModeImg.'/nophoto.gif';
}
$a_key = 'index';
$ifadmin = ($colony['ifadmin'] == '1' || $colony['admin'] == $windid || $groupid == 3);

if (empty($a)) {

	require_once(R_P.'require/showimg.php');
	$colony['annouce'] = nl2br($colony['annouce']);

	$newphoto = array();
	$query = $db->query("SELECT cp.pid,cp.path,cp.ifthumb FROM pw_cnalbum ca LEFT JOIN pw_cnphoto cp ON ca.aid=cp.aid WHERE ca.atype='1' AND ca.ownerid=" . pwEscape($cyid) . ' ORDER BY cp.pid DESC LIMIT 4');
	while ($rt = $db->fetch_array($query)) {
		$rt['path'] = getphotourl($rt['path'], $rt['ifthumb']);
		$newphoto[] = $rt;
	}
	$memdb = array();
	$query = $db->query("SELECT cm.uid,cm.username,m.icon FROM pw_cmembers cm LEFT JOIN pw_members m ON cm.uid=m.uid WHERE cm.colonyid=" . pwEscape($cyid) . ' ORDER BY cm.ifadmin DESC LIMIT 0,15');
	while ($rt = $db->fetch_array($query)) {
		//list($rt['icon']) = showfacedesign($rt['icon'],1);
		$memdb[] = $rt;
	}
	$argdb = array();
	$query = $db->query("SELECT tid,author,authorid,postdate,lastpost,subject,topped,toppedtime FROM pw_argument WHERE gid=" . pwEscape($cyid) . " AND tpcid='0' ORDER BY topped DESC,lastpost DESC LIMIT 0,10");
	while ($rt = $db->fetch_array($query)) {
		$rt['postdate']	= get_date($rt['postdate'],'m-d');
		$rt['lastpost'] = get_date($rt['lastpost']);
		$argdb[] = $rt;
	}
	$db->free_result($query);
	require_once(R_P.'require/header.php');
	require_once PrintEot('m_group');
	footer();

} elseif ($a == 'thread') {

	$a_key = 'thread';
	InitGP(array('page'), null, 2);
	$page < 1 && $page = 1;
	$db_perpage = 20;
	$count = $db->get_value("SELECT COUNT(*) AS sum FROM pw_argument WHERE gid=" . pwEscape($cyid) . " AND tpcid='0'");
	$pages = numofpage($count, $page, ceil($count/$db_perpage), "{$basename}q=$q&a=$a&");
	$limit = pwLimit(($page-1)*$db_perpage,$db_perpage);
	$argdb = array();
	$query = $db->query("SELECT tid,author,authorid,lastpost,subject,topped,toppedtime FROM pw_argument WHERE gid=" . pwEscape($cyid) . " AND tpcid='0' ORDER BY topped DESC,lastpost DESC $limit");
	while ($rt = $db->fetch_array($query)) {
		if ($rt['topped']>0 && $rt['toppedtime'] && ($timestamp > $rt['toppedtime'])) {
			$db->update("UPDATE pw_argument SET topped='0',toppedtime='0' WHERE tid=".pwEscape($rt['tid']));
		}
		$rt['lastpost'] = get_date($rt['lastpost']);
		$argdb[] = $rt;
	}
	$db->free_result($query);
	require_once(R_P.'require/header.php');
	require_once PrintEot('m_group');
	footer();

} elseif ($a == 'read') {

	$a_key = 'thread';
	InitGP(array('tid','page'), null, 2);
	$db_perpage = 20;
	$page < 1 && $page = 1;
	$lou = ($page - 1) * $db_perpage;

	$readdb = array();
	$tpc = $db->get_one("SELECT am.*,m.icon FROM pw_argument am LEFT JOIN pw_members m ON am.authorid=m.uid WHERE am.tid=" . pwEscape($tid) . " AND am.tpcid='0'");
	!$tpc && Showmsg('data_error');

	require_once(R_P.'require/showimg.php');
	require_once(R_P.'require/bbscode.php');
	$reply = ($tpc['postdate'] == $tpc['lastpost']);
	if ($page == 1) {
		$tpc['lou'] = 0;
		list($tpc['icon']) = showfacedesign($tpc['icon'],1);
		$tpc['postdate'] = get_date($tpc['postdate']);
		$tpc['content']  = convert(nl2br($tpc['content']),$db_windpost);
		$readdb[] = $tpc;
	}
	if ($reply) {
		$count = $db->get_value("SELECT COUNT(*) AS sum FROM pw_argument WHERE gid=" . pwEscape($cyid) . " AND tpcid=" . pwEscape($tid));
		$pages = numofpage($count, $page, ceil($count/$db_perpage), "{$basename}q=$q&a=$a&cyid=$cyid&tid=$tid&");
		$query = $db->query("SELECT * FROM pw_argument WHERE gid=" . pwEscape($cyid) . " AND tpcid=" . pwEscape($tid) . " ORDER BY postdate " . pwLimit(($page - 1) * $db_perpage, $db_perpage));
		while ($rt = $db->fetch_array($query)) {
			$rt['lou'] = ++$lou;
			list($rt['icon']) = showfacedesign($rt['icon'],1);
			$rt['postdate']	= get_date($rt['postdate']);
			$rt['content']	= convert(nl2br($rt['content']),$db_windpost);
			$readdb[] = $rt;
		}
	}
	require_once(R_P.'require/header.php');
	require_once PrintEot('m_group');
	footer();

} elseif ($a == 'post') {

	$a_key = 'thread';

	if (empty($_POST['step'])) {
		require_once(R_P.'require/header.php');
		require_once PrintEot('m_group');
		footer();

	} else {

		InitGP(array('subject','content'), 'P');
		if (empty($subject) || empty($content)) {
			Showmsg('colony_posterror');
		}
		strlen($subject) > 50 && Showmsg('colony_subject');
		require_once(R_P.'require/postfunc.php');

		$content = autourl($content);
		$db->update("INSERT INTO pw_argument SET " . pwSqlSingle(array(
				'tpcid'		=> 0,
				'gid'		=> $cyid,
				'author'	=> $windid,
				'authorid'	=> $winduid,
				'postdate'	=> $timestamp,
				'lastpost'	=> $timestamp,
				'subject'	=> $subject,
				'content'	=> $content
		)));
		$tid = $db->insert_id();
		countPosts('grouppost');
		refreshto("{$basename}q=$q&a=read&cyid=$cyid&tid=$tid",'colony_postsuccess');
	}
} elseif ($a == 'reply') {

	InitGP(array('tid'), null, 2);
	InitGP(array('content'));
	if (empty($content)) {
		Showmsg('colony_posterror');
	}
	$tpc = $db->get_one("SELECT gid FROM pw_argument WHERE tid=" . pwEscape($tid) . " AND tpcid='0'");
	if (empty($tpc) || $tpc['gid'] != $cyid) {
		Showmsg('data_error');
	}
	require_once(R_P.'require/postfunc.php');

	$content = autourl($content);
	$db->update("INSERT INTO pw_argument SET " . pwSqlSingle(array(
			'tpcid'		=> $tid,
			'gid'		=> $cyid,
			'author'	=> $windid,
			'authorid'	=> $winduid,
			'postdate'	=> $timestamp,
			'lastpost'	=> $timestamp,
			'subject'	=> $subject,
			'content'	=> $content
	)));
	countPosts('groupreply');
	refreshto("{$basename}q=$q&a=read&cyid=$cyid&tid=$tid",'colony_postsuccess');

} elseif ($a == 'member') {

	$a_key = 'member';

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

		InitGP(array('page'), null, 2);
		require_once(R_P.'require/showimg.php');
		$page < 1 && $page = 1;
		$db_perpage = 20;
		$total = $db->get_value("SELECT COUNT(*) AS sum FROM pw_cmembers WHERE colonyid=" . pwEscape($cyid));
		$pages = numofpage($total, $page, ceil($total/$db_perpage), "{$basename}q=$q&a=member&cyid=$cyid&");
		$memdb = array();
		$query = $db->query("SELECT cm.*,m.icon FROM pw_cmembers cm LEFT JOIN pw_members m ON cm.uid=m.uid WHERE cm.colonyid=" . pwEscape($cyid) . ' ORDER BY cm.ifadmin DESC' . pwLimit(($page - 1) * $db_perpage, $db_perpage));
		while ($rt = $db->fetch_array($query)) {
			list($rt['icon']) = showfacedesign($rt['icon'],1);
			$memdb[] = $rt;
		}
		require_once(R_P.'require/header.php');
		require_once PrintEot('m_group');
		footer();

	} else {

		!$ifadmin && Showmsg('undefined_action');

		InitGP(array('selid'), 'P', 2);
		if (!$selid || !is_array($selid)) {
			Showmsg('id_error');
		}
		$msgdb = array(
			'toUser'	=> array(),
			'fromUid'	=> 0,
			'fromUser'	=> '',
			'subject'	=> 'o_' . $_POST['step'] . '_title',
			'content'	=> 'o_' . $_POST['step'] . '_content',
			'other'		=> array(
				'cname'	=> Char_cv($colony['cname']),
				'curl'	=> "$db_bbsurl/{$basename}q=group&cyid=$cyid"
			)
		);
		switch ($_POST['step']) {
			case 'addadmin':
				$colony['admin'] != $windid && Showmsg('colony_manager');
				$query = $db->query("SELECT username FROM pw_cmembers WHERE colonyid=" . pwEscape($cyid) . ' AND uid IN(' . pwImplode($selid) . ") AND ifadmin!='1'");
				while ($rt = $db->fetch_array($query)) {
					$msgdb['toUser'][] = $rt['username'];
				}
				$db->update("UPDATE pw_cmembers SET ifadmin='1' WHERE colonyid=" . pwEscape($cyid) . ' AND uid IN(' . pwImplode($selid) . ") AND ifadmin!='1'");
				break;
			case 'deladmin':
				$colony['admin'] != $windid && Showmsg('colony_manager');
				$query = $db->query("SELECT username FROM pw_cmembers WHERE colonyid=" . pwEscape($cyid) . ' AND uid IN(' . pwImplode($selid) . ") AND ifadmin='1'");
				while ($rt = $db->fetch_array($query)) {
					$colony['admin'] == $rt['username'] && Showmsg('colony_delladminfail');
					$msgdb['toUser'][] = $rt['username'];
				}
				$db->update("UPDATE pw_cmembers SET ifadmin='0' WHERE colonyid=" . pwEscape($cyid) . ' AND uid IN(' . pwImplode($selid) . ") AND ifadmin='1'");
				break;
			case 'check':
				$query = $db->query("SELECT username FROM pw_cmembers WHERE colonyid=" . pwEscape($cyid) . ' AND uid IN(' . pwImplode($selid) . ") AND ifadmin='-1'");
				while ($rt = $db->fetch_array($query)) {
					$msgdb['toUser'][] = $rt['username'];
				}
				$db->update("UPDATE pw_cmembers SET ifadmin='0' WHERE colonyid=" . pwEscape($cyid) . ' AND uid IN(' . pwImplode($selid) . ") AND ifadmin='-1'");
				break;
			case 'del':
				$query = $db->query("SELECT username,ifadmin FROM pw_cmembers WHERE colonyid=" . pwEscape($cyid) . ' AND uid IN(' . pwImplode($selid) . ")");
				while ($rt = $db->fetch_array($query)) {
					if ($rt['username'] == $colony['admin']) {
						Showmsg('colony_delfail');
					}
					if ($rt['ifadmin'] == '1' && $colony['admin'] != $windid) {
						Showmsg('colony_manager');
					}
					$msgdb['toUser'][] = $rt['username'];
				}
				$db->update("DELETE FROM pw_cmembers WHERE colonyid=" . pwEscape($cyid) . " AND uid IN(" . pwImplode($selid) . ")");
				$count = $db->affected_rows();
				$db->update("UPDATE pw_colonys SET members=members-" . pwEscape($count,false) . " WHERE id=" . pwEscape($cyid));
				break;
			default:
				Showmsg('undefined_action');
		}
		if ($msgdb['toUser']) {
			require_once(R_P.'require/msg.php');
			pwSendMsg($msgdb);
		}
		refreshto("{$basename}q=$q&a=$a&cyid=$cyid",'operate_success');
	}

} elseif ($a == 'uintro') {

	$a_key = 'uintro';

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

		InitGP(array('uid'), null, 2);
		InitGP(array('job'));
		empty($uid) && $uid = $winduid;

		$uinfo = $db->get_one("SELECT uid,username,realname,gender,tel,email,address,introduce FROM pw_cmembers WHERE colonyid=" . pwEscape($cyid) . ' AND uid=' . pwEscape($uid));
		!$uinfo && Showmsg('data_error');
		$select_0 = $select_1 = $select_2 = '';
		${'select_' . $uinfo['gender']} = 'selected';
		require_once(R_P.'require/header.php');
		require_once PrintEot('m_group');
		footer();

	} else {

		InitGP(array('realname','tel','email','address','introduce'),'P');
		InitGP(array('gender'), null, 2);

		if (!empty($email) && !ereg("^[-a-zA-Z0-9_\.]+\@([0-9A-Za-z][0-9A-Za-z-]+\.)+[A-Za-z]{2,5}$",$email)) {
			Showmsg('illegal_email');
		}
		$db->update("UPDATE pw_cmembers SET " . pwSqlSingle(array(
				'realname'	=> $realname,
				'gender'	=> $gender,
				'tel'		=> $tel,
				'email'		=> $email,
				'address'	=> $address,
				'introduce'	=> $introduce,
			)) . " WHERE colonyid=" . pwEscape($cyid) . " AND uid=".pwEscape($winduid)
		);
		refreshto("{$basename}q=$q&a=$a&cyid=$cyid",'colony_cardsuccess');
	}

} elseif ($a == 'set') {

	$a_key = 'set';

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

		$options = '';
		foreach ($o_classdb as $key => $value) {
			$options .= "<option value=\"$key\"" . ($key == $colony['classid'] ? ' selected' : '') . ">$value</option>";
		}
		$ifcheck_0 = $ifcheck_1 = $ifcheck_2 = $ifopen_Y = $ifopen_N = $albumopen_Y = $albumopen_N = '';
		${'ifcheck_'.$colony['ifcheck']} = 'selected';
		${'ifopen_'.($colony['ifopen'] ? 'Y' : 'N')} = 'checked';
		${'albumopen_'.($colony['albumopen'] ? 'Y' : 'N')} = 'checked';
		require_once(R_P.'require/header.php');
		require_once PrintEot('m_group');
		footer();

	} else {

		InitGP(array('cname','annouce','descrip'),'P');
		!$cname && Showmsg('colony_emptyname');
		strlen($cname) > 20 && Showmsg('colony_cnamelimit');
		(!$descrip || strlen($descrip) > 255) && Showmsg('colony_descriplimit');

		$annouce = explode("\n",$annouce,5);
		end($annouce);
		$annouce[key($annouce)] = str_replace(array("\r","\n"),'',current($annouce));
		$annouce = implode("\r\n",$annouce);
		strlen($annouce) > 255 && Showmsg('colony_annoucelimit');

		if ($colony['cname'] != $cname && $db->get_value("SELECT id FROM pw_colonys WHERE cname=" . pwEscape($cname))) {
			Showmsg('colony_samename');
		}
		InitGP(array('cid','ifcheck','ifopen','albumopen'), 'P', 2);

		require_once(R_P.'require/postfunc.php');
		$db_uploadfiletype = array();
		$db_uploadfiletype['gif'] = $db_uploadfiletype['jpg'] = $db_uploadfiletype['jpeg'] = $db_uploadfiletype['bmp'] = $db_uploadfiletype['png'] = $o_imgsize;

		$uploaddb = UploadFile($cyid,'cnlogo');
		pwFtpClose($ftp);

		$pwSQL = array(
			'cname'		=> $cname,
			'classid'	=> $cid,
			'ifcheck'	=> $ifcheck,
			'albumopen'	=> $albumopen,
			'annouce'	=> $annouce,
			'ifopen'	=> $ifopen,
			'descrip'	=> $descrip
		);
		if ($uploaddb[0]['attachurl']) {
			$pwSQL['cnimg'] = substr(strrchr($uploaddb[0]['attachurl'],'/'),1);
		}
		$db->update("UPDATE pw_colonys SET " . pwSqlSingle($pwSQL) . ' WHERE id=' . pwEscape($cyid));

		refreshto("{$basename}q=$q&cyid=$cyid",'colony_setsuccess');
	}
} elseif ($a == 'del') {

	define('AJAX',1);
	InitGP(array('tid'), null, 2);
	$rt = $db->get_one("SELECT tpcid,authorid FROM pw_argument WHERE tid=" . pwEscape($tid) . ' AND gid=' . pwEscape($cyid));

	if (empty($rt) || $rt['authorid'] != $winduid && !$ifadmin) {
		Showmsg('data_error');
	}
	if (empty($_POST['step'])) {

		require_once PrintEot('m_ajax');
		ajax_footer();

	} else {

		$db->update("DELETE FROM pw_argument WHERE tid=" . pwEscape($tid));
		if ($rt['tpcid'] == 0) {
			$db->update("DELETE FROM pw_argument WHERE gid=" . pwEscape($cyid) . ' AND tpcid=' . pwEscape($tid));
			echo 'jump';
		} else {
			echo "del\t$tid";
		}
		ajax_footer();
	}
} elseif ($a == 'edit') {

	define('AJAX',1);
	InitGP(array('tid'), null, 2);
	$rt = $db->get_one("SELECT tpcid,authorid,subject,content FROM pw_argument WHERE tid=" . pwEscape($tid) . ' AND gid=' . pwEscape($cyid));

	if (empty($rt) || $rt['authorid'] != $winduid && !$ifadmin) {
		Showmsg('data_error');
	}

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

		require_once PrintEot('m_ajax');
		ajax_footer();

	} else {

		InitGP(array('subject','content'));

		if ($rt['tpcid'] == 0) {
			empty($subject) && Showmsg('colony_posterror');
			strlen($subject) > 50 && Showmsg('colony_subject');
		} else {
			$subject = '';
		}
		empty($content) && Showmsg('colony_posterror');

		$db->update("UPDATE pw_argument SET " . pwSqlSingle(array(
			'subject'	=> $subject,
			'content'	=> $content
		)) . ' WHERE tid=' . pwEscape($tid));

		require_once(R_P.'require/bbscode.php');
		$out = "edit\t$tid\t";
		$rt['tpcid'] == 0 && $out .= stripslashes($subject) . "\t";
		$out .= stripslashes(convert(nl2br($content),$db_windpost));
		echo $out;
		ajax_footer();
	}
} elseif ($a == 'join') {

	define('AJAX',1);
	$groupid == 'guest' && Showmsg('not_login');
	$colony['ifcyer'] && Showmsg('colony_alreadyjoin');

	if (!$colony['ifcheck']) {
		Showmsg('colony_joinrefuse');
	}
	if ($o_memberfull > 0 && $colony['members'] >= $o_memberfull) {
		Showmsg('colony_memberlimit');
	}
	if ($o_joinmoney > 0) {
		require_once(R_P.'require/credit.php');
		$moneyname = $credit->cType[$o_moneytype];
		if ($o_joinmoney > $credit->get($winduid,$o_moneytype)) {
			Showmsg('colony_joinfail');
		}
	}
	if ($o_allowjoin > 0 && $o_allowjoin <= $db->get_value("SELECT COUNT(*) as sum FROM pw_cmembers WHERE uid=" . pwEscape($winduid))) {
		Showmsg('colony_joinlimit');
	}

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

		require_once PrintEot('m_ajax');
		ajax_footer();

	} else {

		if ($o_joinmoney > 0) {
			$credit->addLog('hack_cyjoin',array($o_moneytype => -$o_joinmoney),array(
				'uid'		=> $winduid,
				'username'	=> $windid,
				'ip'		=> $onlineip,
				'cnname'	=> $colony['cname']
			));
			$credit->set($winduid, $o_moneytype, -$o_joinmoney);
		}

		$db->update("INSERT INTO pw_cmembers SET " . pwSqlSingle(array(
			'uid'		=> $winduid,
			'username'	=> $windid,
			'ifadmin'	=> $colony['ifcheck'] == 2 ? '0' : '-1',
			'colonyid'	=> $cyid,
			'addtime'	=> $timestamp
		)));

		pwAddFeed($winduid, 'colony', '', array(
			'lang'		=> 'colony_pass',
			'colonyid'	=> $cyid,
			'cname'		=> $colony['cname'],
			'link'		=> "{$db_bbsurl}/{$basename}q=group&cyid=$cyid"
		));
		$db->update("UPDATE pw_colonys SET members=members+1 WHERE id=" . pwEscape($cyid));

		Showmsg('colony_joinsuccess');
	}
} elseif ($a == 'out') {

	define('AJAX',1);
	!$colony['ifcyer'] && Showmsg('undefined_action');

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

		require_once PrintEot('m_ajax');
		ajax_footer();

	} else {

		if ($windid == $colony['admin']) {

			if ($db->get_value("SELECT COUNT(*) as sum FROM pw_cnalbum WHERE atype=1 AND ownerid=" . pwEscape($cyid)) > 0) {
				Showmsg('colony_del_photo');
			}
			if ($colony['cnimg']) {
				pwDelatt("cn_img/$colony[cnimg]",$db_ifftp);
				pwFtpClose($ftp);
			}
			$db->update("DELETE FROM pw_cmembers WHERE colonyid=" . pwEscape($cyid));
			$db->update("DELETE FROM pw_colonys WHERE id=" . pwEscape($cyid));
			$db->update("UPDATE pw_cnclass SET cnsum=cnsum-1 WHERE cid=" . pwEscape($colony['classid']) . " AND cnsum>0");
			$db->update("DELETE FROM pw_argume WHERE gid=" . pwEscape($cyid));
			Showmsg('colony_cancelsuccess');

		} else {

			$db->update("UPDATE pw_colonys SET members=members-1 WHERE id=" . pwEscape($cyid));
			$db->update("DELETE FROM pw_cmembers WHERE colonyid=" . pwEscape($cyid) . " AND uid=" . pwEscape($winduid));
			Showmsg('colony_outsuccess');
		}
	}
}
?>