<?

	$need = array(
		'php' => array(
			'db' => true
		)
	);

	$template = 'centered';
	$height = '100%';

	require_once( 'scripts/start.php' );

	function testMessageForSPAM( &$msg ){
		$points = 0;
		$newmsg = strip_tags(stripslashes($msg),'<b><i><h1><h2><h3><h4>');
		$d = strlen($msg) - strlen($newmsg);
		if( $d > 0 ){
			$p = round(100/strlen($msg) * $d);
			$points += round(5/100*$p);
		}
		$msg = $newmsg;
		$newmsg = preg_replace('#\[(url|link)=[^\]]+\].*?\[/(link|url)\]#i','',$msg);
		if( strlen($newmsg) != strlen($msg) ){
			$points += 1;
		}
		$msg = $newmsg;
		if( preg_match_all(
				'/asd|sdf|dfg|fgh|ghj|hjk|jkl|lkj|kjh|jhg|hgf|gfd'.
				'|fds|dsa|ads|sfd|dgf|fhg|gjh|hkj|jlk|ljk|khj|jgh'.
				'|hfg|gdf|fsd|das|zxc|xcv|cvb|vbn|bnm|mnb|nbv|bvc'.
				'|vcx|cxz/',
				$msg,
				$found
			) ){
			$found = reset($found);
			if( ($c=count($found)) > 3 ){
				$points += $c;
			}
		}
		if( preg_match('/valium|sex|sexy|girls|blonde|fuck|dick|cock|pussy|buy|viagra|discount|cialis/i',$msg) ){
			$points += 5;
		}
		if( $points > 3 ){
			return $points;
		}else{
			return 0;
		}
	}

	if( $DB && 0 ){

		if( $_REQUEST['request'] == 'thanks' ){
			echo '
				<div>
					<h1>Thank you..</h1>
					<h5>Your message has been received</h5>
					<p>
					Thanks a lot for taking the time to say something, there currently isn\'t a way
					to view comments just yet.. but there will be soon. I\'ll keep you all posted (excuse the pun).
					</p>
					<br />
					<p><a href="index.html">[ back home ]</a></p>
					<p><a href="news.html">[ news ]</a></p>
					<p><a href="setup.html">[ play demo ]</a></p>
				</div>
				';
			require_once( 'scripts/end.php' );
			exit;
		}else if( $_REQUEST['msg'] && $_REQUEST['chk'] ){

			$msg			= $_REQUEST['msg'];
			$thanks			= false;
			$markAsSPAM		= false;
			$markREGS		= false;
			$requestIPS		= false;

			if($_SERVER['REMOTE_ADDR'] == '81.187.46.163'){
				$markAsSPAM = preg_match( '/^MARK AS SPAM (.+)$/', $msg, $markREGS );
				$requestIPS = preg_match( '/^REQUEST IPS$/', $msg );
			}
			if( $requestIPS ){
				$res = $DB->query( 'SELECT `ip` FROM `comment` WHERE `display`="" AND NOT `spam` AND `visible`=1');
				$err = '';
				$first = true;
				while( $ip = $DB->fetch($res,false,true) ){
					$err .= ( $err ? ',' : '' ).$ip;
				}
				if($err){
					$err = 'MARK AS SPAM '.$err;
				}else{
					$err = 'No IPs to display';
				}
			}else if( $markAsSPAM && $markREGS[1] ){
				$ips = explode(',',$markREGS[1]);
				$sql = '';
				foreach( $ips AS $key => $ip ){
					$sql .= ( $sql ? ' OR ' : '' ) . 'ip="'.$DB->mes(trim($ip)).'"';
				}
				$DB->query( 'UPDATE `comment` SET `spam`=5,`visible`=0 WHERE '.$sql.'');
				if( $n = $DB->affected() ){
					$err = $n . ' Messages marked as SPAM';
				}else{
					$err = 'MARK AS SPAM failed..';
				}
			}else if( $isSpamIP = $DB->fetchQuery('SELECT 1 FROM `comment` WHERE `ip`="'.mes($_SERVER['REMOTE_ADDR']).'" AND `spam`!=0 LIMIT 0,1',false,true) ){
				$err = 'Your message has been flagged as SPAM!<br />sorry i do not tolerate IDIOTS..';
			}else if( strlen($_REQUEST['msg'])>500 ){
				$err = 'Sorry your message is to long.. it needs to be under 500 letters';
				if( $isSPAM = testMessageForSPAM( $_REQUEST['msg'] ) ){
					$DB->query('INSERT INTO `comment` SET `datetime`=NOW(),`message`="SPAMMER",`spam`="'.$DB->mes( $isSPAM ).'",`visible`=0,`ip`="'.$DB->mes( $_SERVER['REMOTE_ADDR'] ).'"');
				}
				$isSPAM = 'oversized';
			}else{
				if( !$_REQUEST['prv'] ){
					$isSPAM = 10;
				}else{
					$isSPAM = testMessageForSPAM( $msg );
				}
				$ts = new tsession( $DB );
				if( $ts->useOnce( $_REQUEST['chk'], 'check:comment' ) ){
					$ts->clearSpecific($_REQUEST['chk']);
					if( $_REQUEST['prv'] && ($fp = @fopen('http://www.icicle.me.uk/sentience.php?check='.urlencode($_REQUEST['chk']).'&code='.urlencode($_REQUEST['prv']),'r')) ){
						$codecheck = @fread($fp,6); @fclose($fp);
						if( $codecheck != 'passed' ){
							$isSPAM = 10;
						}
					}
					$DB->query(
						'INSERT INTO `comment` SET '.
							'`message`="'.$DB->mes( $msg ).'", '.
							'`datetime`=NOW(), '.
							'`ip`="'.$DB->mes( $_SERVER['REMOTE_ADDR'] ).'", '.
							'`uniques`="'.$DB->mes( $_COOKIE['gju'] ).'", '.
							'`spam`="'.(is_numeric($isSPAM)?$isSPAM:'0').'"'.
						''
					);
					$thanks = true;
				}else{
					$err = 'Sorry your message could not be authorized. SENDER UNKNOWN';
					$ts->clearSpecific($_REQUEST['chk']);
				}
			}

			if( $isSpamIP ){
				sleep(10);
				header('location:thanks.php');
				exit;
			}else if( $isSPAM ){
				sleep(10);
			}else{
				$body = ''.
					'Hi,'."\n\n".
					'Someone has left a new comment:'."\n\n".
					$msg."\n\n".'---'."\n\n".
					'Thanks,'."\n\n".
					'Mr Script'."\n".'---'."\n".'gravityjam.co.uk'.
				'';
				mail( 'phil@unabacus.net', 'New Comment', $body, 'From: Gravity Jam <script@gravityjam.co.uk>','-fscript@gravityjam.co.uk' );
			}

			if( $thanks ){
				header('location:comments.php?request=thanks');
				exit;
			}

		}

		$ts = new tsession( $DB );
		$ts->create( 'check:comment', 1 );

		echo '
			<div>
				<h1>Leave a Comment..</h1>
				<h5>just so i know i\'m not the only one out here??</h5>
				<p>
				Yep, whilst talking to - and building games for - myself; is all well and good it would
				be even nicer to see that people are actually playing GravityJAM at all..? any one there?
				ps. if there is anyone not out there then bear in mind this message is especially for you :)
				</p>
				<p>pps. oh please limit your message to under 500 characters as letters are a finite resource, some people don\'t even have enough to complete a full sentence... thanks</p>
				<p>ppps. also.. please don\'t use HTML or BBCode tags as they will increase the likely hood of your message being marked as spam</p>
				'.($err?'<p style="font-size: 14px; color: red; font-weight: bold; text-align: center;">'.$err.'</p>':'').'
				<br />
				<form action="comments.php" method="post">
					<div style="position: absolute"><div style="position: relative; left: -72px; top: 2px; width: 50px; border: 1px dotted white; padding: 2px; text-align: right; color: white;" id="outp"></div></div>
					<textarea name="msg" onkeyup="var elm=document.getElementById(\'outp\');outp.innerHTML=this.value.length+\' / 500\';" onparse="var elm=document.getElementById(\'outp\');outp.innerHTML=node.value.length+\' / 500\';" style="width: 100%; height: 100px; padding: 10px; font-size: 12px;">'.$_REQUEST['msg'].'</textarea>
					<div style="margin-top: 16px; margin-bottom: 16px;" sentience="{ident:\''.$ts->session.'\',field:\'sentience\',textColor:\'FFFFFF\',flashListener:\'auto\'}"><center style="font-size: 13px; color: red;">If you see this message you need to install flash (otherwise you can\'t comment)</center></div>
					<input type="text" name="prv" value="" style="width: 100%;" />
					<input type="hidden" name="chk" value="'.$ts->session.'" />
					<div style="margin-top: 10px;">
						<div style="width: 55%; float: left; text-align: left;">
							message will be tagged with:<br />'.$_SERVER['REMOTE_ADDR'].' '.date('Y-m-d H:i:s').'
						</div>
						<div style="width: 40%; float: right; text-align: right;">
							<input type="submit" value="Post Comment" style="padding: 10px;" />
						</div>
					</div>
				</form>
				<div class="clear"></div>
			</div>
		';

		$qry = $DB->query( 'SELECT * FROM `comment` WHERE `visible`=1 AND `spam`=0' );
		$comments = '';
		while( $f = $DB->fetch( $qry ) ){
			$comments .= '<p><h5>'.$f['datetime'].'</h5></p>';
			$comments .= '<p>'.htmlspecialchars(stripslashes($f['message'])).'</p>';
			$comments .= '<p style="font-size: 9px; color: grey;">left by <b>'.($f['display']?$f['display']:$f['ip']).'</b></p>';
			$comments .= '<br /><br />';
		}

		if( $comments ){

			echo '
				<br /><br /><br /><br />
				<div>
					<h1>Existing Comments..</h1>
					<h5>words of wisdom from you lot "out there"</h5>
					<br />
					'.$comments.'
				</div>
			';

		}

		/*
		echo '
			<br />
			<p><a href="javascript:history.back();">[ back ]</a></p>
			<p><a href="index.html">[ back home ]</a></p>
			<p><a href="news.html">[ news ]</a></p>
			<p><a href="setup.html">[ play demo ]</a></p>
		';
		*/

	}
  else {
    echo '<div>Comments disabled for now...</div>';
  }

	require_once( 'scripts/end.php' );

?>