<?php

/**
 *		[Discuz!] (C)2001-2099 Comsenz Inc.
 *		This is NOT a freeware, use is subject to license terms
 *
 *		$Id: cloud_security.php 589 2011-12-13 05:01:44Z songlixin $
 */
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
	exit('Access Denied');
}

$op = trim($_G['gp_op']);

$_G['gp_anchor'] = in_array($_G['gp_anchor'], array('index', 'setting', 'thread', 'post', 'reportOperation')) ? $_G['gp_anchor'] : 'index';
$pt = in_array($_G['gp_anchor'], array('thread', 'post')) ? $_G['gp_anchor'] : 'thread';

$current = array($_G['gp_anchor'] => 1);

$operateresultmap = array(
						'0' => 1,
						'-1' => 0,
						'-5' => 0
						);

$nooperategroup = array(4, 5, 6, 7, 8, 9);

$securitynav = array();

$securitynav[0] = array('security_index', 'cloud&operation=security&anchor=index', $current['index']);
$securitynav[1] = array('security_blanklist', 'cloud&operation=security&anchor=setting', $current['setting']);
$securitynav[2] = array('security_thread_list', 'cloud&operation=security&anchor=thread', $current['thread']);
$securitynav[3] = array('security_post_list', 'cloud&operation=security&anchor=post', $current['post']);

if (!$_G['inajax']) {
	cpheader();
	shownav('navcloud', 'menu_cloud_security', 'security_'.$_G['gp_anchor'].'_list');
	showsubmenu('menu_cloud_security', $securitynav);
}

$tpp = !empty($_G['gp_tpp']) ? $_G['gp_tpp'] : '20';
$start_limit = ($page - 1) * $tpp;
require_once libfile('function/discuzcode');
require_once libfile('function/core');
$datas = $data = $eviluids = $evilPids = $evilTids = $members = $thread = $post = '';

if ($_G['gp_anchor'] == 'index') {
	$signUrl = generateSiteSignUrl();
	headerLocation($cloudDomain.'/security/stats/list/?'.$signUrl);
} elseif ($_G['gp_anchor'] == 'setting') {

	if (!submitcheck('settingsubmit')) {

		$evilthreads = DB::result_first("SELECT svalue FROM " . DB::table('common_setting') . " WHERE skey = 'cloud_security_stats_thread'");
		$evilposts = DB::result_first("SELECT svalue FROM " . DB::table('common_setting') . " WHERE skey = 'cloud_security_stats_post'");
		$evilmembers = DB::result_first("SELECT svalue FROM " . DB::table('common_setting') . " WHERE skey = 'cloud_security_stats_member'");

		$usergroupswhitelist = unserialize($_G['setting']['security_usergroups_white_list']);
		$groupselect = array();
		$usergroupid = isset($_G['gp_usergroupid']) && is_array($_G['gp_usergroupid']) ? $_G['gp_usergroupid'] : array();
		$query = DB::query("SELECT type, groupid, grouptitle, radminid FROM ".DB::table('common_usergroup')." WHERE groupid NOT IN ('6', '7') ORDER BY (creditshigher<>'0' || creditslower<>'0'), creditslower, groupid");
		while($group = DB::fetch($query)) {
			$group['type'] = $group['type'] == 'special' && $group['radminid'] ? 'specialadmin' : $group['type'];
			$groupselect[$group['type']] .= "<option value=\"$group[groupid]\" ".(in_array($group['groupid'], $usergroupswhitelist) ? 'selected' : '').">$group[grouptitle]</option>\n";
		}
		$groupselect = '<optgroup label="'.$lang['usergroups_member'].'">'.$groupselect['member'].'</optgroup>'.
			($groupselect['special'] ? '<optgroup label="'.$lang['usergroups_special'].'">'.$groupselect['special'].'</optgroup>' : '').
			($groupselect['specialadmin'] ? '<optgroup label="'.$lang['usergroups_specialadmin'].'">'.$groupselect['specialadmin'].'</optgroup>' : '').
			'<optgroup label="'.$lang['usergroups_system'].'">'.$groupselect['system'].'</optgroup>';

		$forumswhitelist = unserialize($_G['setting']['security_forums_white_list']);
		require_once libfile('function/forumlist');
		loadcache('forums');
		$forumselect = str_replace('%', '%%', forumselect(FALSE, 0, $forumswhitelist, TRUE));

		showformheader('cloud&operation=security&anchor=setting');
		showtableheader('security_white_list_setting', '', '', 2);
		showsetting('security_usergroup_white_list', '', '', '<select name="groupid[]" multiple="multiple" size="10">'.$groupselect.'</select>');
		showsetting('security_forum_white_list', '', '', '<select name="fid[]" multiple="multiple" size="10">'.$forumselect.'</select>');
		showsubmit('settingsubmit');
		showtablefooter();
		showformfooter();

	} else {

		$usergroups = $_POST['groupid'];
		$forums = $_POST['fid'];

		DB::query("REPLACE INTO ".DB::table('common_setting')." (`skey`, `svalue`) VALUES ('security_usergroups_white_list', '".serialize($usergroups)."'), ('security_forums_white_list', '".serialize($forums)."')");
		updatecache('setting');

		cpmsg('setting_update_succeed', 'action=cloud&operation=security&anchor='.$_G['gp_anchor'], 'succeed');
	}

} elseif ($_G['gp_anchor'] == 'thread') {
	$count = DB::result_first("SELECT count(*) FROM ".DB::table('security_evilpost')." WHERE type = '1'");
	$multipage = multi($count, $tpp, $page, ADMINSCRIPT.'?action=cloud&operation=security&anchor=thread');
	list($datas, $evilTids) = getEvilList('thread', $start_limit, $tpp);
	echo "<p><a href='{$adminscript}?action=recyclebin&operation=search&formhash=".formhash()."&security=1&searchsubmit=1' target='_blank'>{$lang['security_recyclebin_thread']}</a></p>";
	showtableheader('', '', 'id = "security_list"');
	showsubtitle(array('security_subject', 'security_forum', 'security_author', 'security_thread_status'));

	foreach($datas as $key => $value) {

		if(!$value['message']) {
			$subjectstyle = 'class = "threadopt"';
		} else {
			$subjectstyle = '';
		}
		$value['message'] = convertMessage($value);
		$modthreadkey = modauthkey($value['tid']);
		$viewlink = $value['message'] ? '<a href="forum.php?mod=redirect&goto=findpost&ptid='.$value['tid'].'&pid='.$value['pid'].'&modthreadkey='.$modthreadkey.'" target="_blank" title="'.$lang['security_view_thread'].'">'.$value['subject'].'</a>' : '';

		$thread = array(convertSubjectandIP($value, $viewlink), getNamebyFid($value['fid']), convertAuthorAndDate($value), //convertIdtoStr($value['eviltype']),
		convertIdtoStr($value['invisible'], 'adminoperate'));
		showtagheader('tbody', '', true, 'hover');
		showtablerow($subjectstyle, array('width = "400px"'), $thread);
		$value['message'] ? showtablerow('class="threadopt" style = "display: none;" id = "mod_'.$value['tid'].'_row_'.$key.'"', 'colspan = "6"', $value['message']) : '';
		showtagfooter('tbody');
	}
	if ($multipage) {
		showtablerow('', 'colspan = "6"', $multipage);
	}
	showtablefooter();

} elseif($_G['gp_anchor'] == 'post') {

	$count = DB::result_first("SELECT count(*) FROM ".DB::table('security_evilpost')." WHERE type = '0'");
	$multipage = multi($count, $tpp, $page, ADMINSCRIPT.'?action=cloud&operation=security&anchor=post');
	list($datas, $evilPids) = getEvilList('post', $start_limit, $tpp);
	echo "<p><a href='{$adminscript}?action=recyclebinpost&operation=search&formhash=".formhash()."&security=1&searchsubmit=1' target='_blank'>{$lang['security_recyclebin_post']}</a></p>";
	showtableheader('', '', 'id = "security_list"');
	showsubtitle(array('security_subject', 'security_forum', 'security_author', 'security_post_status'));

	foreach($datas as $key => $value) {

		if(!$value['message']) {
			$subjectstyle = 'class = "threadopt"';
		} else {
			$subjectstyle = '';
		}
		$value['message'] = convertMessage($value);
		$modthreadkey = modauthkey($value['tid']);
		$thread = array(convertSubjectandIP($value), getNamebyFid($value['fid']), convertAuthorAndDate($value), //convertIdtoStr($value['eviltype']),
		convertIdtoStr($value['invisible'], 'adminoperate'), $viewlink);
		showtagheader('tbody', '', true, 'hover');
		showtablerow($subjectstyle,array('width = "400px"'), $thread);
		$value['message'] ? showtablerow('class="threadopt" style="display: none;" id = "mod_'.$value['tid'].'_row_'.$key.'"', 'colspan = "6"', $value['message']) : '';
		showtagfooter('tbody');
	}
	if ($multipage) {
		showtablerow('', 'colspan = "6"', $multipage);
	}
	showtablefooter();

} elseif($_G['gp_anchor'] == 'member') {
	$memberperpage = $_G['setting']['memberperpage'];
	$start_limit = ($page - 1) * $memberperpage;
	$count = DB::result_first('SELECT count(*) FROM ' . DB::table('security_eviluser'));
	$multipage = multi($count, $memberperpage, $page, ADMINSCRIPT.'?action=cloud&operation=security&anchor=member');

	list($datas, $eviluids) = getEvilList('user', $start_limit, $memberperpage);
	showtableheader();
	showsubtitle(array('security_members_name', 'members_edit_info', 'security_members_eviltype', 'security_thread_member'));
	foreach($datas as $value) {
		if ($value['username']) {
			$username = '<a href="' . ADMINSCRIPT . '?action=members&operation=group&uid='.$value['uid'].'" target="_blank" title="'.$title.'">'.$value['username'].'</a>';
		} else {
			$username = $lang['security_userdeleted']."(uid:{$value['uid']})";
		}
		$member = array($username, convertMemberInfo($value), convertIdtoStr($value['eviltype']), $value['grouptitle']);
		showtablerow('',array('width = "220px"'),$member);
	}
	if ($multipage) {
		showtablerow('','colspan = "5"',$multipage);
	}

	showtablefooter();
}

$jsScript = <<<EOF
		<script type='text/javascript'>

			function toggle_mod(id) {
				if($(id).style.display == 'none') {
					$(id).style.display = '';
				} else {
					$(id).style.display = 'none';
				}
				return false;
			}
			function security_foldall() {
				var trs = $('security_list').getElementsByTagName('TR');

				for(var i in trs) {
					if(trs[i].id && trs[i].id.match(/mod_(\d+)_row_(\d+)/) != null) {
						trs[i].style.display = "none";
					}
				}
			}
			function security_exfoldall() {
				var trs = $('security_list').getElementsByTagName('TR');

				for(var i in trs) {
					if(trs[i].id && trs[i].id.match(/mod_(\d+)_row_(\d+)/) != null) {
						trs[i].style.display = "";
					}
				}
			}
		</script>
EOF;
echo $jsScript;

function convertIdtoStr($id, $type = 'security_type', $subtype = 'thread') {
	global $lang;
	if ($type == 'security_type') {
		$id = min(6, $id);
		$result = $lang['security_type_'.$id];
	} elseif($type == 'checkreported') {
		$result = $id ? $lang['security_isreported_yes'] : $lang['security_isreported_no'];
	} elseif($type == 'adminoperate') {

		if ($id === null) {
			return $lang['security_opreateresult_2'];
		}

		if (in_array($subtype, array('thread', 'post'))) {
			global $operateresultmap;

			$result = $lang['security_opreateresult_'.$operateresultmap[$id]];
		} elseif ($subtype == 'member') {

			global $nooperategroup;
			if (in_array($id, $nooperategroup)) {
				$result = $lang['security_opreateresult_0'];
			} else {
				$result = $lang['security_opreateresult_1'];
			}
		}
	}
	return $result;
}

function convertMemberInfo($value) {
	global $lang;
	$result = '';
	if ($value['username']) {
		$result = $lang['members_edit_regdate'] . ': ' . dgmdate($value['regdate']) . '<br/>';
		$result .= $lang['members_edit_regip'] . ': ' . $value['regip'] . ' ' . convertip($value['regip']) . '<br/>';
		$result .= 'Email: ' . $value['email'];
	} else {
		$result = '<p style="margin:14px 0;">' . $lang['security_userdeleted'] . '</p>';
	}
	return $result;
}

function convertOperate($id = 0) {
	$ids = array('1' => 'delete',
				 '2' => 'restore');
	if (!$ids[$id]) {
		return false;
	}
	return $ids[$id];
}

function getEvilList($type, $start, $ppp) {
	$datas = $data = $evilids = '';

	if ($type == 'member') {
		$type = 'user';
	}

	if ($type == 'user') {
		$query = DB::query("SELECT * FROM ".DB::table('security_eviluser')." ORDER BY createtime DESC LIMIT $start, $ppp ");
		$idtype = 'uid';
	} elseif($type == 'thread') {
		$query = DB::query("SELECT * FROM ".DB::table('security_evilpost')." WHERE type = '1' ORDER BY createtime DESC LIMIT $start, $ppp ");
		$idtype = 'pid';
	} elseif($type == 'post') {
		$query = DB::query("SELECT * FROM ".DB::table('security_evilpost')." WHERE type = '0' ORDER BY createtime DESC LIMIT $start, $ppp ");
		$idtype = 'pid';
	}
	while ($data = DB::fetch($query)) {
		$datas[$data[$idtype]] = $data;
		$evilids[] = $data[$idtype];
		if ($data['tid']) {
			$evilTids[] = $data['tid'];
			$threadPid[$data['tid']][] = $data['pid'];
		}
	}

	if (is_array($evilids) && count($evilids) > 0) {
		$evilids = dimplode($evilids);
	}
	if (is_array($evilTids)) {
		$evilTids = array_unique($evilTids);
		$evilTids = dimplode($evilTids);
	}

	if (!$evilids) {
		return false;
	}
	if ($type == 'user') {

		$usergroups = array();
		$query = DB::query("SELECT groupid, grouptitle FROM ".DB::table('common_usergroup'));
		while($group = DB::fetch($query)) {
			$usergroups[$group['groupid']] = $group['grouptitle'];
		}

		$query = DB::query("SELECT m.uid, m.email, m.username, m.regdate, m.groupid, ms.regip
							FROM ".DB::table('common_member')." m
							LEFT JOIN ".DB::table('common_member_status')." ms ON m.uid = ms.uid
							WHERE m.uid IN ($evilids)");


	} elseif($type == 'thread' || $type == 'post') {
		$query = DB::query("SELECT * FROM ".DB::table('forum_thread')." WHERE tid IN ($evilTids)");
	}

	while ($data = DB::fetch($query)) {
		if ($type == 'thread' || $type == 'post') {
			foreach($threadPid[$data['tid']] as $pid) {
				$isFirst = ($type == 'thread') ? 1 : 0;
				$posttable = $data['posttableid'] ? "forum_post_{$data['posttableid']}" : 'forum_post';
				$postData = DB::fetch_first("SELECT * FROM ".DB::table($posttable)." WHERE tid = '{$data[tid]}' AND pid = '$pid' AND first = '$isFirst'");
				if ($postData['pid']) {
					$datas[$postData['pid']] = array_merge($datas[$postData['pid']], $postData);
					if ($type == 'post') {
						$datas[$postData['pid']]['subject'] = $data['subject'];
					}
				}
			}
		} else {
			$data['grouptitle'] = $usergroups[$data['groupid']];
			$datas[$data[$idtype]] = array_merge($datas[$data[$idtype]], $data);
		}
	}
	return array($datas, $evilids);
}

function getNamebyFid($fid) {
	global $_G;
	if (!$fid) {
		return false;
	}
	$name = DB::result_first("SELECT name FROM ".DB::table('forum_forum')." WHERE fid = '$fid'");
	$name = "<a href='forum.php?mod=forumdisplay&fid=$fid' target='_blank'>".$name."</a>";
	return $name;
}

function convertSubjectandIP($value, $viewlink = '') {
	global $lang;
	if ($viewlink) {
		$result = '<h3>'.$viewlink.'</h3>';
	} else {
		$result = '<h3><a title="'.$lang['security_clicktotoggle'].'" href="javascript:;" onclick="return toggle_mod(\'mod_'.$value['tid'].'_row_'.$value['pid'].'\');" target="_blank">'.$value['subject'].'</a></h3>';
	}

	$result .= '<p>'.$value['useip'].' '.convertip($value['useip']).' ( pid : '.$value['pid'].' )</p>';
	if (!$value['message']) {
		return $lang['security_postdeleted']."(tid:{$value['tid']} pid:{$value['pid']})";
	}
	return $result;
}

function convertMessage($value) {
	global $lang;
	if (!$value['message']) {
		return false;
	}
	$value['message'] = discuzcode($value['message'], 0, 0, sprintf('%00b', $value['htmlon']), 1, 1, 1, 0);
	$value['message'] = '<div style="overflow: auto; overflow-x: hidden; max-height:120px; height:auto !important; height:100px; word-break: break-all;">'.$value['message'].'</div>';
	return $value['message'];
}

function convertAuthorAndDate($value) {
	if (!$value['author']) {
		return false;
	}
	$result = "<a href='home.php?mod=space&uid={$value[authorid]}&do=profile' target='_blank'>" . $value['author'] . "</a>" . '<p>';
	$result .= dgmdate($value['dateline']);
	$result .= '</a>';
	return $result;
}

function getDataToReport($operateType, $datatosync, $datas) {
	$datatoreport = array();
	foreach($datatosync as $operateresult => $ids) {
		foreach($ids as $id) {
			if(!$datas[$id]['isreported']) {
				$data = array(
						'operateType' => $operateType,
						'operate' => $operateresult == 'validate' ? 'restore' : 'delete',
						'operateId' => $id,
						'uid' => $datas[$id]['authorid'] ? $datas[$id]['authorid'] : $datas[$id]['uid'],
						);
				$data['openId'] = getOpenId($data['uid']);
				$data['clientIp'] = $datas[$id]['userip'] ? $datas[$id]['userip'] : getMemberIp($data['uid']);
				if ($operateType != 'member') {
					$data['tid'] = $datas[$id]['tid'];
					$data['pid'] = $datas[$id]['pid'];
					$data['fid'] = $datas[$id]['fid'];
				}
				array_push($datatoreport, $data);
			}
		}
	}
	return $datatoreport;
}

?>