<?php
if (isset($_GET['ajax'])) {
	define('AJAX','1');
}
require_once('global.php');

!$windid && Showmsg('not_login');
InitGP(array('action'));

$template = 'ajax_operate';

if (empty($_POST['step']) && !defined('AJAX')) {
	require_once(R_P.'require/header.php');
	$template = 'operate';
}

if ($action == 'showping') {

	require_once(R_P.'require/msg.php');
	require_once(R_P.'require/forum.php');
	require_once(R_P.'require/bbscode.php');
	InitGP(array('selid','pid','page'));
	if (empty($selid) && empty($pid)) {
		Showmsg('selid_illegal');
	}
	empty($selid) && $selid = array($pid);
	$pids = $atcdb = array();
	$ptpc = '';
	foreach ($selid as $key => $val) {
		if (is_numeric($val)) {
			$pids[] = $val;
		} else {
			$ptpc = 1;
		}
	}
	$pw_tmsgs = GetTtable($tid);
	$atc = $db->get_one("SELECT t.fid,t.author,t.authorid,t.postdate,t.subject,t.anonymous,t.ptable,tm.ifmark FROM pw_threads t LEFT JOIN $pw_tmsgs tm ON tm.tid=t.tid WHERE t.tid=".pwEscape($tid));
	$fid = $atc['fid'];
	$ptpc && $atcdb['tpc'] = $atc;
	$pw_posts = GetPtable($atc['ptable']);

	if ($pids) {
		$pids = pwImplode($pids);
		$query = $db->query("SELECT pid,fid,author,authorid,postdate,subject,ifmark,anonymous,content FROM $pw_posts WHERE pid IN($pids) AND tid=".pwEscape($tid));
		while ($rt = $db->fetch_array($query)) {
			if (!$rt['subject']) {
				$rt['subject'] = 'RE:'.$atc['subject'];
			}
			$atcdb[$rt['pid']] = $rt;
		}
	}
	empty($atcdb) && Showmsg('data_error');

	$foruminfo = $db->get_one("SELECT name,f_type,style,password,allowvisit,allowhtm,cms,forumadmin,fupadmin FROM pw_forums WHERE fid=".pwEscape($fid)." AND type<>'category'");
	!$foruminfo && Showmsg('data_error');
	wind_forumcheck($foruminfo);
	list($minper,$maxper) = explode(",",$_G['marklimit']);
	!$minper && $minper=0;
	!$maxper && $maxper=0;

	if ($winddb['groups']) {
		$gids = array();
		foreach (explode(',',$winddb['groups']) as $key=>$gid) {
			is_numeric($gid) && $gids[] = $gid;
		}
		if ($gids) {
			$mright = array();
			$gids = pwImplode($gids);
			require_once(R_P.'require/pw_func.php');
			$query = $db->query("SELECT gid,rkey,rvalue FROM pw_permission WHERE uid='0' AND fid='0' AND gid IN($gids) AND rkey IN ('maxcredit','marklimit','markctype','markdt','markable') AND type='basic'");
			while ($rt = $db->fetch_array($query)) {
				$mright[$rt['gid']][$rt['rkey']] = $rt['rvalue'];
			}
			foreach ($mright as $key=>$p) {
				if (is_array($p) && $p['maxcredit'] && $p['markable']) {
					$p['markable'] > $_G['markable'] && $_G['markable'] = $p['markable'];
					is_numeric($p['maxcredit']) && $p['maxcredit'] > $_G['maxcredit'] && $_G['maxcredit'] = $p['maxcredit'];
					$s = explode(',',$p['marklimit']);
					is_numeric($s[0]) && $s[0] < $minper && $minper = $s[0];
					is_numeric($s[1]) && $s[1] > $maxper && $maxper = $s[1];
					$s['markdt']===0 && $_G['markdt'] = 0;
				}
			}
		}
	}
	$admincheck = admincheck($foruminfo['forumadmin'],$foruminfo['fupadmin'],$windid);

	if ((!$admincheck && !$_G['markable']) || !$_G['markctype'] || ($minper==0 && $maxper==0)) {
		Showmsg('no_markright');
	}
	$anonymous = 0;
	foreach ($atcdb as $key => $atc) {
		if ($db_pingtime && $timestamp-$atc['postdate']>$db_pingtime*3600 && $gp_gptype!='system') {
			Showmsg('pingtime_over');
		}
		if ($winduid == $atc['authorid'] && !CkInArray($windid,$manager)) {
			Showmsg('masigle_manager');
		}
		if ($_POST['step'] == 1 && $_G['markable']<2 && !$admincheck && strpos($atc['ifmark'],'('.$windid.')')!==false) {
			Showmsg('no_markagain');
		}
		if ($_POST['step'] > 1 && strpos($atc['ifmark'],"(".$windid.")")===false) {
			Showmsg('have_not_showping');
		}
		$atc['anonymous'] && $anonymous++;
	}
	require_once(R_P.'require/credit.php');
	$credittype = explode(',',$_G['markctype']);
	$mcredit	= $db->get_one('SELECT credit FROM pw_memberinfo WHERE uid='.pwEscape($winduid));
	$count		= count($atcdb);

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

		$creditselect = '';
		foreach ($credittype as $key => $cid) {
			if (isset($credit->cType[$cid])) {
				$creditselect .= '<option value="'.$cid.'">'.$credit->cType[$cid].'</option>';
			}
		}
		if ($_G['maxcredit']) {
			$creditdb = explode("\t",$mcredit['credit']);
			if ($creditdb[0] >= $tdtime) {
				$leavepoint = abs($_G['maxcredit']-$creditdb[1]);
				$leavepoint == 0 && Showmsg('masigle_nopoint');
			} else {
				$leavepoint = $_G['maxcredit'];
			}
		}
		$reason_sel = '';
		$reason_a = explode("\n",$db_adminreason);
		foreach ($reason_a as $k => $v) {
			if ($v = trim($v)) {
				$reason_sel .= "<option value=\"$v\">$v</option>";
			} else {
				$reason_sel .= "<option value=\"\">-------</option>";
			}
		}
		if ($anonymous == $count && $groupid!='3') {
			$check_Y = 'disabled';
			$check_N = 'checked';
		} else {
			$check_Y = 'checked';
			$check_N = '';
		}
		require_once PrintEot($template);footer();

	} elseif ($_POST['step'] == 1) {

		PostCheck();
		InitGP(array('cid','addpoint','ifmsg','atc_content'),'P');
		!in_array($cid,$credittype) && Showmsg('masigle_credit_right');

		if (isset($credit->cType[$cid])) {
			$name = $credit->cType[$cid];
			$unit = $credit->cUnit[$cid];
		} else {
			Showmsg('all_credit_error');
		}
		$addpoint = (int)$addpoint;
		$addpoint == 0 && Showmsg('member_credit_error');
		$allpoint = $addpoint * $count;

		if ($addpoint > $maxper || $addpoint < $minper) {
			Showmsg('masigle_creditlimit');
		}
		if ($_G['maxcredit']) {
			$creditdb = explode("\t",$mcredit['credit']);
			if ($creditdb[0] < $tdtime) {
				$creditdb[0] = $tdtime;
				$creditdb[1] = abs($allpoint);
				if ($creditdb[1] > $_G['maxcredit']) {
					$leavepoint = max(0,$_G['maxcredit']-$creditdb[1]);
					Showmsg('masigle_point');
				}
			} else {
				if ($creditdb[1] + abs($allpoint) > $_G['maxcredit']) {
					$leavepoint = max(0,$_G['maxcredit']-$creditdb[1]);
					Showmsg('masigle_point');
				} else {
					$creditdb[0] = $timestamp;
					$creditdb[1]+= abs($allpoint);
				}
			}
			$newcreditdb = $creditdb[0]."\t".$creditdb[1];
			if ($mcredit) {
				$db->update('UPDATE pw_memberinfo SET credit='.pwEscape($newcreditdb,false).' WHERE uid='.pwEscape($winduid));
			} else {
				$db->update("INSERT INTO pw_memberinfo SET " .pwSqlSingle(array('uid'=>$winduid,'credit'=>$newcreditdb),false));
			}
		}
		if ($_G['markdt'] && $allpoint > 0) {
			$credit->get($winduid,$cid) < $allpoint && Showmsg('credit_enough');
			$credit->set($winduid,$cid,-$allpoint,false);
		}

		foreach ($atcdb as $pid => $atc) {
			!$atc['subject'] && $atc['subject'] = substrs(strip_tags(convert($atc['content'])),35);
			$credit->addLog('credit_showping',array($cid => $addpoint),array(
				'uid'		=> $atc['authorid'],
				'username'	=> $atc['author'],
				'ip'		=> $onlineip,
				'operator'	=> $windid,
				'tid'		=> $tid,
				'subject'	=> $atc['subject'],
				'reason'	=> $atc_content
			));
			$credit->set($atc['authorid'],$cid,$addpoint,false);
			if ($db_autoban && $addpoint < 0) {
				require_once(R_P.'require/autoban.php');
				autoban($atc['authorid']);
			}
			$newmark = $name.':'.($addpoint>0 ? '+' : '').$addpoint.'('.addslashes($windid).") ".substrs($atc_content,24);
			$ifmark	 = $atc['ifmark'] ? $newmark."\t".addslashes($atc['ifmark']) : $newmark;
			if (strlen($ifmark)>240) {
				$ifmark = substr($ifmark,0,240);
				$ifmark = substr($ifmark,0,strrpos($ifmark,"\t"));
			}
			if (!is_numeric($pid)) {
				$db->update("UPDATE pw_threads SET ifmark=ifmark+".pwEscape($addpoint)." WHERE tid=".pwEscape($tid));
				$db->update("UPDATE $pw_tmsgs SET ifmark=".pwEscape($ifmark)." WHERE tid=".pwEscape($tid));
			} else {
				$db->update("UPDATE $pw_posts SET ifmark=".pwEscape($ifmark)." WHERE pid=".pwEscape($pid));
			}
			$atcdb[$pid]['ifmark'] = $ifmark;

			if ($ifmsg && !$atc['anonymous']) {
				$msg = array(
					'toUser'	=> $atc['author'],
					'fromUid'	=> $winduid,
					'fromUser'	=> $windid,
					'subject'	=> 'ping_title',
					'content'	=> 'ping_content',
					'other'		=> array(
						'manager'	=> $windid,
						'fid'		=> $atc['fid'],
						'tid'		=> $tid,
						'subject'	=> $atc['subject'],
						'postdate'	=> get_date($atc['postdate']),
						'forum'		=> strip_tags($foruminfo['name']),
						'affect'    => "$name:$addpoint",
						'admindate'	=> get_date($timestamp),
						'reason'	=> stripslashes($atc_content)
					)
				);
				pwSendMsg($msg);
			}
		}
		$credit->runsql();

		if ($foruminfo['allowhtm'] && $page==1) {
			require_once(R_P.'require/template.php');
		}
		if (defined('AJAX')) {
			echo "success";
			foreach ($atcdb as $pid=>$atc) {
				echo "\t".$pid."\t";
				$ifmark = explode("\t",$atc['ifmark']);
				foreach ($ifmark as $key => $value) {
					echo "<li>$value</li>";
				}
			}
			ajax_footer();
		} else {
			refreshto("read.php?tid=$tid&page=$page",'enter_thread');
		}
	} else {

		PostCheck();
		$groupid == 'guest' && Showmsg('not_login');
		InitGP(array('ifmsg','atc_content'));

		foreach ($atcdb as $pid => $atc) {
			$markdb = explode("\t",$atc['ifmark']);
			$cid = '';
			foreach ($markdb as $key => $mark) {
				if (strpos($mark,"(".$windid.")") !== false) {
					$cName = substr($mark,0,strpos($mark,":"));
					list($addpoint) = explode("(",substr($mark,strpos($mark,":")+1));
					$addpoint = (int) $addpoint;
					unset($markdb[$key]);
					foreach ($credit->cType as $k => $v) {
						if ($v == $cName) {
							$cid = $k;break;
						}
					}
					break;
				}
			}
			!$cid && Showmsg('all_credit_error');
			!$atc['subject'] && $atc['subject'] = substrs(strip_tags(convert($atc['content'])),35);
			$addpoint = $addpoint>0 ? -$addpoint : abs($addpoint);

			$credit->addLog('credit_delping',array($cid => $addpoint),array(
				'uid'		=> $atc['authorid'],
				'username'	=> $atc['author'],
				'ip'		=> $onlineip,
				'operator'	=> $windid,
				'tid'		=> $tid,
				'subject'	=> $atc['subject'],
				'reason'	=> $atc_content
			));
			$credit->set($atc['authorid'],$cid,$addpoint);

			$ifmark = implode("\t",$markdb);
			if (!is_numeric($pid)) {
				$db->update('UPDATE pw_threads SET ifmark=ifmark+'.pwEscape($addpoint).' WHERE tid='.pwEscape($tid));
				$db->update("UPDATE $pw_tmsgs SET ifmark=".pwEscape($ifmark)." WHERE tid=".pwEscape($tid));
			} else {
				$db->update("UPDATE $pw_posts SET ifmark=".pwEscape($ifmark)." WHERE pid=".pwEscape($pid));
			}
			$atcdb[$pid]['ifmark'] = $markdb;

			if ($ifmsg) {
				$msg = array(
					'toUser'	=> $atc['author'],
					'fromUid'	=> $winduid,
					'fromUser'	=> $windid,
					'subject'	=> 'delping_title',
					'content'	=> 'delping_content',
					'other'		=> array(
						'manager'	=> $windid,
						'fid'		=> $atc['fid'],
						'tid'		=> $tid,
						'subject'	=> $atc['subject'],
						'postdate'	=> get_date($atc['postdate']),
						'forum'		=> strip_tags($foruminfo['name']),
						'affect'    => "{$cName}:$addpoint",
						'admindate'	=> get_date($timestamp),
						'reason'	=> stripslashes($atc_content)
					)
				);
				pwSendMsg($msg);
			}
		}

		if ($foruminfo['allowhtm'] && $page==1) {
			require_once(R_P.'require/template.php');
		}
		if (defined('AJAX')) {
			echo "success";
			foreach ($atcdb as $pid=>$atc) {
				echo "\t".$pid."\t";
				foreach ($atc['ifmark'] as $key=>$value) {
					echo "<li>$value</li>";
				}
			}
			ajax_footer();
		} else {
			refreshto("read.php?tid=$tid&page=$page",'enter_thread');
		}
	}

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

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

		$atcinfo  = $db->get_one("SELECT subject,author,anonymous FROM pw_threads WHERE tid=".pwEscape($tid));
		$atcinfo['anonymous'] && $atcinfo['author'] = $db_anonymousname;
		$atc_name = $atcinfo['subject'];
		require_once PrintEot($template);footer();

	} elseif ($_POST['step'] == 1) {

		PostCheck(1,$db_gdcheck & 16);
		InitGP(array('sendtoname'));
		InitGP(array('subject','atc_content'),'P');
		require_once(R_P.'require/msg.php');

		$userdb = '';
		if ($sendtoname) {
			$userdb = $db->get_one("SELECT username FROM pw_members WHERE username=".pwEscape($sendtoname));
		}
		if (!$userdb) {
			$errorname = $sendtoname;
			Showmsg('user_not_exists');
		}
		if (!$subject || !$atc_content) {
			Showmsg('tofriend_msgerror');
		}
		$msgdb = array(
			'toUser'	=> $userdb['username'],
			'fromUid'	=> $winduid,
			'fromUser'	=> $windid,
			'subject'	=> stripslashes($subject),
			'content'	=> stripslashes($atc_content),
		);
		pwSendMsg($msgdb);
		Showmsg('operate_success');

	} else {

		PostCheck(1,$db_gdcheck & 16);
		InitGP(array('subject','atc_content','sendtoemail','sendtoname'));

		if (empty($subject)) {
			Showmsg('sendeamil_subject_limit');
		}
		if (empty($atc_content) || strlen($atc_content)<=20) {
			Showmsg('sendeamil_content_limit');
		} elseif (!ereg("^[-a-zA-Z0-9_\.]+\@([0-9A-Za-z][0-9A-Za-z-]+\.)+[A-Za-z]{2,5}$",$sendtoemail)) {
			Showmsg('illegal_email');
		}
		if ($timestamp-GetCookie('lastwrite')<=60) {//$_G['postpertime']
			Showmsg('sendeamil_limit');
		}
		Cookie('lastwrite',$timestamp);
		require_once(R_P.'require/sendemail.php');
		$fromemail	= $winddb['email'];
		$fromname	= $windid;
		$sendinfo	= sendemail($sendtoemail,$subject,$atc_content,'email_additional');

		if ($sendinfo === true) {
			Showmsg('operate_success');
		} else {
			Showmsg(is_string($sendinfo) ? $sendinfo : 'mail_failed');
		}
	}

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

	!$_G['allowreport'] && Showmsg('report_right');
	InitGP(array('pid','page'),'GP',2);
	$rt  = $db->get_one("SELECT tid FROM pw_report WHERE uid=".pwEscape($winduid).' AND tid='.pwEscape($tid).' AND pid='.pwEscape($pid));
	$rt && Showmsg('have_report');

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

		require_once PrintEot($template);footer();

	} else {

		PostCheck();
		InitGP(array('ifmsg','type','reason'),'P');

		$pwSQL = pwSqlSingle(array(
			'tid'	=> $tid,
			'pid'	=> $pid,
			'uid'	=> $winduid,
			'type'	=> $type,
			'reason'=> $reason
		));
		$db->update("INSERT INTO pw_report SET $pwSQL");

		if ($ifmsg) {
			if ($pid > 0) {
				$pw_posts = GetPtable('N',$tid);
				$sqlsel = "t.content as subject,t.postdate,";
				$sqltab = "$pw_posts t";
				$sqladd = 'WHERE t.pid='.pwEscape($pid);
			} else {
				$sqlsel = "t.subject,t.postdate,";
				$sqltab = "pw_threads t";
				$sqladd = 'WHERE t.tid='.pwEscape($tid);
			}
			$rs = $db->get_one("SELECT $sqlsel t.fid,f.forumadmin FROM $sqltab LEFT JOIN pw_forums f USING(fid) $sqladd");

			if ($rs['forumadmin']) {
				include_once(D_P.'data/bbscache/forum_cache.php');
				require_once(R_P.'require/msg.php');
				$admin_a = explode(',',$rs['forumadmin']);
				$msg = array(
					'toUser'	=> $admin_a,
					'fromUid'	=> $winduid,
					'fromUser'	=> $windid,
					'subject'	=> 'report_title',
					'content'	=> 'report_content_'.$type,
					'other'		=> array(
						'fid'		=> $rs['fid'],
						'tid'		=> $tid.'#'.$pid,
						'postdate'	=> get_date($rs['postdate']),
						'forum'		=> $forum[$rs['fid']]['name'],
						'subject'	=> $rs['subject'],
						'admindate'	=> get_date($timestamp),
						'reason'	=> stripslashes($reason)
					)
				);
				pwSendMsg($msg);
			}
		}
		if (defined('AJAX')) {
			Showmsg('report_success');
		} else {
			refreshto("read.php?tid=$tid&page=$page",'report_success');
		}
	}
}else{
	Showmsg('undefined_action');
}
?>