<?php

/*
	[SupeSite/X-Space] (C)2001-2006 Comsenz Inc.
	回复评论处理

	$RCSfile: batch.comment.php,v $
	$Revision: 1.58 $
	$Date: 2007/07/05 17:52:16 $
*/

include_once('./include/main.inc.php');
include_once(S_ROOT.'./include/common.inc.php');
include_once(S_ROOT.'./language/batch.lang.php');
include_once(S_ROOT.'./function/spacecp.func.php');

$action = empty($_GET['action'])?'':$_GET['action'];

if(!empty($_POST['submitcomment'])) {

	if(!submitcheck('submitcomment', 1)) {
		print<<<EOF
		<script language="javascript">
		if(parent.document.getElementById('xspace-seccode')) {
			parent.document.getElementById('xspace-seccode').value = "";
			parent.document.getElementById('xspace-seccode').focus();
		}
		</script>
EOF;
		jsmessage('error', 'seccode_error');
	}
	
	if(empty($_COOKIE)) {
		setcookie('supe_last_comment', $_SGLOBAL['timestamp']);
		jsmessage('error', 'comment_too_much');
	}
	if(!empty($_COOKIE['supe_last_comment'])) {
		$_COOKIE['supe_last_comment'] = intval($_COOKIE['supe_last_comment']);
		if($_SGLOBAL['timestamp'] - $_COOKIE['supe_last_comment'] < $_SCONFIG['commenttime']) {
			jsmessage('error', 'comment_too_much');
		}
	}
	setcookie('supe_last_comment', $_SGLOBAL['timestamp']);
	
	getcookie(1);
	$author = $_SGLOBAL['supe_username'];
	if(empty($_SGLOBAL['supe_uid'])) {
		if(empty($_SCONFIG['allowguest'])) {
			jsmessage('error', 'no_login', geturl('action/login'));
		}
		if(!empty($_POST['nickname'])) {
			$author = addslashes(cutstr(shtmlspecialchars(stripslashes($_POST['nickname'])), 15));
		}
	}
	
	if(empty($_POST['itemid'])) $_POST['itemid'] = 0;
	$_POST['itemid'] = intval($_POST['itemid']);
	if(empty($_POST['itemid'])) {
		jsmessage('error', 'system_error');
	}
	
	$_POST['message'] = shtmlspecialchars(trim($_POST['message']));
	if(strlen($_POST['message']) < 2 || strlen($_POST['message']) >5000) {
		jsmessage('error', 'message_length_error');
	}
	
	$_POST['message' ] = censor($_POST['message']);
	
	//是否允许回复
	$query = $_SGLOBAL['db']->query('SELECT i.*, it.typename, it.viewperm, it.replyperm, it.getattachperm FROM '.tname('spaceitems').' i LEFT JOIN '.tname('itemtypes').' it ON it.typeid=i.itemtypeid WHERE i.itemid=\''.$_POST['itemid'].'\' AND i.allowreply=\'1\' AND i.folder=\'1\' AND i.tid=\'0\'');
	if($item = $_SGLOBAL['db']->fetch_array($query)) {
		if($item['type'] != 'news') {
			if(!checkfriend($item['replyperm'], $item['uid'])) {
				jsmessage('error', 'no_reply');
			}
		}
	} else {
		jsmessage('error', 'no_reply');
	}

	//引用处理
	$_POST['message'] = str_replace('[quote]', '<div class="xspace-quote">', $_POST['message']);
	$_POST['message'] = str_replace('[/quote]', '</div>', $_POST['message']);

	$setsqlarr = array(
		'itemid' => $item['itemid'],
		'type' => $item['type'],
		'uid' => $item['uid'],
		'authorid' => $_SGLOBAL['supe_uid'],
		'author' => $author,
		'ip' => $_SGLOBAL['onlineip'],
		'dateline' => $_SGLOBAL['timestamp'],
		'rates' => 0,
		'message' => $_POST['message']
	);
	inserttable('spacecomments', $setsqlarr);
	$_SGLOBAL['db']->query('UPDATE '.tname('spaceitems').' SET lastpost=\''.$_SGLOBAL['timestamp'].'\', replynum=replynum+1 WHERE itemid=\''.$item['itemid'].'\'');
	
	if($item['type'] != 'news') clearspacecache($item['uid'], 'comment');

	$item['replynum']++;
	$html = getcomments($item);
	$html = jsstrip($html);
	
	print<<<EOF
	<script language="javascript">
	parent.document.getElementById('xspace-commentmsg').value = "";
	if(parent.document.getElementById('xspace-seccode') != null) parent.document.getElementById('xspace-seccode').value = "";
	parent.document.getElementById('xspace-itemreply').innerHTML = "$html";
	if(parent.document.getElementById('xspace-imgseccode') != null) parent.document.getElementById('xspace-imgseccode').src='$siteurl/batch.seccode.php?'+Math.random(1);
	parent.document.getElementById('xspace-itemreply').scrollIntoView();
	</script>
EOF;

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

	$itemid = empty($_GET['itemid'])?0:intval($_GET['itemid']);
	if(empty($itemid)) showxml('the_model_can_not_detect_comments');
	$query = $_SGLOBAL['db']->query('SELECT * FROM '.tname('spaceitems').' WHERE itemid=\''.$itemid.'\' AND folder=\'1\' AND tid=\'0\'');
	if(!$item = $_SGLOBAL['db']->fetch_array($query)) showxml($blang['the_model_can_not_detect_comments']);

	$html = getcomments($item);
	
	showxml($html);

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

	getcookie(1);
	$cid = empty($_GET['cid'])?0:intval($_GET['cid']);
	if(empty($cid) || empty($_SGLOBAL['supe_uid'])) showxml($blang['message_no_permission']);
	
	$query = $_SGLOBAL['db']->query('SELECT * FROM '.tname('spacecomments').' WHERE cid=\''.$cid.'\'');
	if($value = $_SGLOBAL['db']->fetch_array($query)) {

		//检查权限
		if($value['uid'] != $_SGLOBAL['supe_uid'] && empty($_SGLOBAL['group']['allowcheckitem'])) showxml($blang['message_no_permission']);

		deletetable('spacecomments', array('cid'=>$cid));

		if($value['rates']>0) {
			$goodrate = $value['rates'];
			$badrate = 0;
			$rates = 0 - $value['rates'];
		} elseif($value['rates'] < 0) {
			$goodrate = 0;
			$badrate = 0 - $value['rates'];
			$rates = 0 - $value['rates'];
		} else {
			$goodrate = 0;
			$badrate = 0;
			$rates = 0;
		}
		$_SGLOBAL['db']->query('UPDATE '.tname('spaceitems').' SET replynum=replynum-1,goodrate=goodrate-'.$goodrate.',badrate=badrate-'.$badrate.' WHERE itemid=\''.$value['itemid'].'\'');
		
		//积分
		if(!empty($_SCONFIG['credit_rule']['allowrate'])) {
			batchcredit($value['uid'], $rates);
		}
	
		if($value['type'] != 'news') clearspacecache($_SGLOBAL['supe_uid'], 'comment');
		showxml($blang['message_delete_ok']);
	} else {
		showxml($blang['message_no_permission']);
	}
} elseif ($action == 'rate') {
	
	//快捷评分
	$rates = empty($_GET['rates'])?0:intval($_GET['rates']);
	$mode = empty($_GET['mode'])?'':'xml';
	
	if(!in_array($rates, array(-5, -3, -1, 1, 3, 5))) {
		if(empty($mode)) {
			jsmessage('error', $blang['the_score_was_not_correct_designation']);
		} else {
			showxml($blang['the_score_was_not_correct_designation']);
		}
	}
	
	$itemid = empty($_GET['itemid'])?0:intval($_GET['itemid']);
	$item = array();
	if(!empty($itemid)) {
		dbconnect();
		$query = $_SGLOBAL['db']->query("SELECT i.uid, i.type, i.itemid, it.typename, it.viewperm, it.replyperm, it.getattachperm FROM ".tname('spaceitems')." i LEFT JOIN ".tname('itemtypes')." it ON it.typeid=i.itemtypeid WHERE i.itemid='$itemid' AND i.folder=1 AND i.allowreply=1 AND i.tid=0");
		$item = $_SGLOBAL['db']->fetch_array($query);
	}

	if(empty($item)) {
		if(empty($mode)) {
			jsmessage('error', $blang['information_was_not_scoring']);
		} else {
			showxml($blang['information_was_not_scoring']);
		}
	}
	
	getcookie(1);
	if(empty($_SCONFIG['allowguest']) && empty($_SGLOBAL['supe_uid'])) {
		if(empty($mode)) {
			jsmessage('error', $blang['visitors_can_participate_score']);
		} else {
			showxml($blang['visitors_can_participate_score']);
		}
	}
	
	if($item['uid'] == $_SGLOBAL['supe_uid']) {
		if(empty($mode)) {
			jsmessage('error', $blang['not_on_their_scores']);
		} else {
			showxml($blang['not_on_their_scores']);
		}
	}

	if(!empty($item['replyperm'])) {
		if(!checkfriend($item['replyperm'], $item['uid'])) {
			if(empty($mode)) {
				jsmessage('error', $blang['only_friends_can_score']);
			} else {
				showxml($blang['only_friends_can_score']);
			}
		}
	}
	
	include_once(S_ROOT.'./include/common.inc.php');
	if(empty($_SGLOBAL['supe_uid'])) {
		$author = 'Guest';
		$query = $_SGLOBAL['db']->query('SELECT COUNT(*) FROM '.tname('spacecomments').' WHERE itemid=\''.$item['itemid'].'\' AND ip=\''.$_SGLOBAL['onlineip'].'\' AND rates!=0');
	} else {
		$author = $_SGLOBAL['supe_username'];
		$query = $_SGLOBAL['db']->query('SELECT COUNT(*) FROM '.tname('spacecomments').' WHERE itemid=\''.$item['itemid'].'\' AND authorid=\''.$_SGLOBAL['supe_uid'].'\' AND rates!=0');
	}
	$ratenum = $_SGLOBAL['db']->result($query, 0);
	if($ratenum > 0) {
		if(empty($mode)) {
			jsmessage('error', $blang['have_too_much_commentary']);
		} else {
			showxml($blang['have_too_much_commentary']);
		}
	}

	//添加回复
	$setsqlarr = array(
		'itemid' => $item['itemid'],
		'type' => $item['type'],
		'uid' => $item['uid'],
		'authorid' => $_SGLOBAL['supe_uid'],
		'author' => $author,
		'ip' => $_SGLOBAL['onlineip'],
		'dateline' => $_SGLOBAL['timestamp'],
		'rates' => $rates
	);
	inserttable('spacecomments', $setsqlarr);
	if($rates>0) {
		$goodrate = $rates;
		$badrate = 0;
	} elseif($rates < 0) {
		$goodrate = 0;
		$badrate = 0 - $rates;
	} else {
		$goodrate = 0;
		$badrate = 0;
	}
	$_SGLOBAL['db']->query('UPDATE '.tname('spaceitems').' SET lastpost=\''.$_SGLOBAL['timestamp'].'\', replynum=replynum+1,goodrate=goodrate+'.$goodrate.',badrate=badrate+'.$badrate.' WHERE itemid=\''.$item['itemid'].'\'');
	if($item['type'] != 'news') clearspacecache($item['uid'], 'comment');
	
	//积分
	if(!empty($_SCONFIG['credit_rule']['allowrate'])) {
		batchcredit($item['uid'], $rates);
	}

	//评分完成
	if(empty($mode)) {
		$item['replynum']++;
		$html = getcomments($item);
		$html = jsstrip($html);
		
		print<<<EOF
		<script language="javascript">
		parent.document.getElementById('xspace-itemreply').innerHTML = "$html";
		parent.document.getElementById('xspace-itemreply').scrollIntoView();
		parent.document.getElementById('xspace-phpframe').src = "about:blank";
		</script>
EOF;
	} else {
		showxml($blang['rates_succeed']);
	}
} elseif ($action == 'modelrate') {
	//快捷评分
	$rates = 1;
	$resultmodels = array();
	
	$_GET['name'] = !empty($_GET['name']) ? trim($_GET['name']) : '';
	if(empty($_GET['name']) || !preg_match("/^[a-z0-9]{2,20}$/i", $_GET['name'])) {
		showxml($blang['not_found']);
	}
	include_once(S_ROOT.'./function/model.func.php');
	$cacheinfo = getmodelinfoall('modelname', $_GET['name']);
	if(empty($cacheinfo['models'])) {
		showxml($blang['not_found']);
	}
	$resultmodels = $cacheinfo['models'];

	$itemid = empty($_GET['itemid'])?0:intval($_GET['itemid']);
	$item = array();
	if(!empty($resultmodels['allowrate'])) {
		if(!empty($itemid)) {
			dbconnect();
			$query = $_SGLOBAL['db']->query("SELECT i.uid, i.itemid, i.rates FROM ".tname($_GET['name'].'items')." i WHERE i.itemid='$itemid' AND i.tid=0");
			$item = $_SGLOBAL['db']->fetch_array($query);
		}
	}

	if(empty($item)) {
		showxml($blang['information_was_not_scoring']);
	}
	
	getcookie(1);
	if(empty($_SCONFIG['allowguest']) && empty($_SGLOBAL['supe_uid'])) {
		showxml($blang['visitors_can_participate_score']);
	}

	if($item['uid'] == $_SGLOBAL['supe_uid']) {
		showxml($blang['not_on_their_scores']);
	}

	include_once(S_ROOT.'./include/common.inc.php');
	if(empty($_SGLOBAL['supe_uid'])) {
		$author = 'Guest';
		$query = $_SGLOBAL['db']->query('SELECT COUNT(*) FROM '.tname($_GET['name'].'rates').' WHERE itemid=\''.$item['itemid'].'\' AND ip=\''.$_SGLOBAL['onlineip'].'\'');
	} else {
		$author = $_SGLOBAL['supe_username'];
		$query = $_SGLOBAL['db']->query('SELECT COUNT(*) FROM '.tname($_GET['name'].'rates').' WHERE itemid=\''.$item['itemid'].'\' AND authorid=\''.$_SGLOBAL['supe_uid'].'\'');
	}
	$ratenum = $_SGLOBAL['db']->result($query, 0);
	if($ratenum > 0) {
		showxml($blang['have_too_much_commentary']);
	}

	//添加记录
	$setsqlarr = array(
		'itemid' => $item['itemid'],
		'authorid' => $_SGLOBAL['supe_uid'],
		'author' => $author,
		'ip' => $_SGLOBAL['onlineip'],
		'dateline' => $_SGLOBAL['timestamp']
	);
	inserttable($_GET['name'].'rates', $setsqlarr);

	$_SGLOBAL['db']->query('UPDATE '.tname($_GET['name'].'items').' SET lastpost=\''.$_SGLOBAL['timestamp'].'\', rates=rates+1 WHERE itemid=\''.$item['itemid'].'\'');
	
	//评分完成
	showxml('rates_succeed');
}

function jsmessage($type, $message, $url='') {
	
	include_once(S_ROOT.'./language/message.lang.php');
	if(!empty($mlang[$message])) $message = $mlang[$message];
	$message = addslashes($message);
	
	$siteurl = S_URL;
	
	$jumpjs = '';
	if($url) {
		$jumpjs = 'OpenWindow("'.$url.'", "login", 800, 400);';
	}

	print<<<EOF
	<script language="javascript">

	function OpenWindow(url, winName, width, height) {
		xposition=0; yposition=0;
		if ((parseInt(navigator.appVersion) >= 4 )) {
			xposition = (screen.width - width) / 2;
			yposition = (screen.height - height) / 2;
		}
		theproperty= "width=" + width + ","
		+ "height=" + height + ","
		+ "location=0,"
		+ "menubar=0,"
		+ "resizable=1,"
		+ "scrollbars=1,"
		+ "status=0,"
		+ "titlebar=0,"
		+ "toolbar=0,"
		+ "hotkeys=0,"
		+ "screenx=" + xposition + "," //仅适用于Netscape
		+ "screeny=" + yposition + "," //仅适用于Netscape
		+ "left=" + xposition + "," //IE
		+ "top=" + yposition; //IE 
		window.open(url, winName, theproperty);
	}
	if(parent.document.getElementById('xspace-imgseccode') != null) parent.document.getElementById('xspace-imgseccode').src='$siteurl/batch.seccode.php?'+Math.random(1);
	parent.document.getElementById('xspace-phpframe').src = "about:blank";
	alert('$message');
	$jumpjs
	</script>
EOF;
	exit();
}

function getcomments($item) {
	global $_SCONFIG, $_GET, $_SGLOBAL;

	$itemid = $item['itemid'];
	
	$perpage = $_SCONFIG['viewspace_pernum'];
	$commentlist = array();
	$multipage = '';
	$page = empty($_GET['page'])?1:intval($_GET['page']);
	$page = ($page<2)?1:$page;
	$start = ($page-1)*$perpage;


	$listcount = $item['replynum'] + $item['trackbacknum'];
	if($listcount) {
		$query = $_SGLOBAL['db']->query('SELECT u.*, c.* FROM '.tname('spacecomments').' c LEFT JOIN '.tname('userspaces').' u ON u.uid=c.authorid WHERE c.itemid=\''.$itemid.'\' ORDER BY c.dateline DESC LIMIT '.$start.','.$perpage);
		while ($value = $_SGLOBAL['db']->fetch_array($query)) {
			$value['photo'] = getphoto($value['authorid'], $value['photo']);
			$commentlist[] = $value;
		}
		$multipage = multi($listcount, $perpage, $page, 'PAGE');
	}

	if($multipage) {
		$multipage = preg_replace("/\"PAGE\?page\=(\d+?)\"/", '"javascript:;" onclick="javascript:showcomment(\\1);"', $multipage);
	}

	$html = '';
	if($commentlist) {
		include_once(S_ROOT.'./include/common.inc.php');
		include_once(S_ROOT.'./include/supe_bbcode.inc.php');
		$html = getcommenthtml($commentlist);
		$html .= "<div id=\"xspace-multipage-div\" class=\"xspace-multipage\">$multipage</div>";
	} else {
		$html .= "<div id=\"xspace-multipage-div\" class=\"xspace-multipage\">$blang[message_no_reply]</div>";
	}
	
	return $html;
}

?>