<?php
/*
 ########################################################################
#                                                                        #
#           Version 4       /                        /   /               #
#          -----------__---/__---__------__----__---/---/-               #
#           | /| /  /___) /   ) (_ `   /   ) /___) /   /                 #
#          _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___               #
#                       Free Content / Management System                 #
#                                   /                                    #
#                                                                        #
#                                                                        #
#   Copyright 2005-2006 by webspell.org                                  #
#                                                                        #
#   visit webSPELL.org, webspell.info to get webSPELL for free           #
#   - Script runs under the GNU GENERAL PUBLIC LICENSE                   #
#   - It's NOT allowed to remove this copyright-tag                      #
#   -- http://www.fsf.org/licensing/licenses/gpl.html                    #
#                                                                        #
#   Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at),   #
#   Far Development by Development Team - webspell.org                   #
#                                                                        #
#   visit webspell.org                                                   #
#                                                                        #
 ########################################################################
*/

if($_POST['savevisitorcomment']) {
  include("_mysql.php");
	include("_settings.php");
	include("_functions.php");
	
	$name = $_POST['name'];
	$mail = $_POST['mail'];
	$url = $_POST['url'];
	$parentID = $_POST['parentID'];
  $type = $_POST['type'];
  $message = $_POST['message'];
  $ip = $_SERVER['REMOTE_ADDR'];
	$CAPCLASS = new Captcha;	
	
	setcookie("visitor_info", $name."--||--".$mail."--||--".$url, time()+(3600*24*365));
	$query = safe_query("SELECT nickname, username FROM ".PREFIX."user ORDER BY nickname");
	while($ds=mysql_fetch_array($query)) {
		$nicks[] = $ds[nickname];
		$nicks[] = $ds[username];
	}
	
	if(in_array(trim($name), $nicks)) header("Location: ".$_POST['referer']."&error=nickname#addcomment");
	elseif(!($CAPCLASS->check_captcha($_POST['captcha'], $_POST['captcha_hash']))) header("Location: ".$_POST['referer']."&error=captcha#addcomment");
	else {
		$date=time();
		safe_query("INSERT INTO ".PREFIX."comments ( parentID, type, nickname, date, comment, url, email, ip )
		            values( '$parentID', '$type', '".mysql_escape_string($name)."', '$date', '".mysql_escape_string($message)."', '".mysql_escape_string($url)."', '".mysql_escape_string($mail)."', '$ip' ) ");
		header("Location: ".$_POST['referer']);
	}
}
elseif($_POST['saveusercomment']) {
  include("_mysql.php");
	include("_settings.php");
	include("_functions.php");
  if(!$userID) die('Not logged in.');

	$parentID = $_POST['parentID'];
  $type = $_POST['type'];
  $message = $_POST['message'];

	$date=time();
	safe_query("INSERT INTO ".PREFIX."comments ( parentID, type, userID, date, comment ) values( '$parentID', '$type', '$userID', '$date', '".mysql_escape_string($message)."' ) ");
	header("Location: ".$_POST['referer']);
}
elseif($_GET['delete']) {
  include("_mysql.php");
	include("_settings.php");
	include("_functions.php");
  if(!isanyadmin($userID)) die('No access.');
	foreach($_POST['commentID'] as $id) {
		safe_query("DELETE FROM ".PREFIX."comments WHERE commentID='$id'");
	}
	header("Location: ".$_POST['referer']);
}
elseif($_GET['editcomment']) {
	$id=$_GET['id'];
	$referer=$_GET['ref'];
	if(isfeedbackadmin($userID) OR iscommentposter($userID,$id)) {
		if(!empty($id)) {
			$dt = safe_query("SELECT * FROM ".PREFIX."comments WHERE commentID='".$id."'");
			if(mysql_num_rows($dt)) {
				$ds = mysql_fetch_array($dt);
				$poster='<a href="index.php?site=profile&id='.$ds[userID].'"><b>'.getnickname($ds[userID]).'</b></a>';
				$message=getinput($ds[comment]);
				$message=preg_replace("#\n\[br\]\[br\]\[hr]\*\*(.+)#si", '', $message);
				$message=preg_replace("#\n\[br\]\[br\]\*\*(.+)#si", '', $message);
				
				eval("\$comment_edit = \"".gettemplate("comment_edit")."\";");
				echo $comment_edit;
			} else {
				redirect($referer, "No database entry matching commentID - redirecting", 2);
			}		
		} else {
			redirect($referer, "No commentID specified - redirecting", 2);
		}
	} else {
		redirect($referer, "Access denied.", 2);
	}
}
elseif($_POST['saveeditcomment']) {
  include("_mysql.php");
	include("_settings.php");
	include("_functions.php");
	
	if(!isfeedbackadmin($userID) AND !iscommentposter($userID,$_POST[commentID])) die('No access');
	
	$message=$_POST['message'];
	$author=$_POST['authorID'];
	$referer=urldecode($_POST['referer']);

	// check if any admin edited the post
	if(safe_query("UPDATE ".PREFIX."comments SET comment='".mysql_escape_string($message)."' WHERE commentID='".$_POST[commentID]."'")) {
		header("Location: $referer");
	}
}
else {
  $page = $_GET['page'];
  $sort = $_GET['sort'];
  $sorttype = $_GET['sorttype'];
  if($_GET['parentID']) $parentID = $_GET['parentID'];
  if($_GET['type']) $type = $_GET['type'];

	$alle=safe_query("SELECT commentID FROM ".PREFIX."comments WHERE parentID='$parentID' AND type='$type'");
  $gesamt=mysql_num_rows($alle);
	$pages=1;
	if(!isset($page)) $page = 1;
	if(!isset($sort)) $sort = "date";
	if(!isset($sorttype)) $sorttype = "DESC";
		
	$max=$maxfeedback;
		
	for ($n=$max; $n<=$gesamt; $n+=$max) {
	    if($gesamt>$n) $pages++;
	}
		
	if($pages>1) $page_link = makepagelink("$referer&sorttype=$sorttype", $page, $pages);
		
	if ($page == "1") {
		$ergebnis = safe_query("SELECT * FROM ".PREFIX."comments WHERE parentID='$parentID' AND type='$type' ORDER BY date $sorttype LIMIT 0,$max");
		if($sorttype=="DESC") $n=$gesamt;
		else $n=1;
	}
	else {
		$start=$page*$max-$max;
		$ergebnis = safe_query("SELECT * FROM ".PREFIX."comments WHERE parentID='$parentID' AND type='$type' ORDER BY date $sorttype LIMIT $start,$max");
		if($sorttype=="DESC") $n = $gesamt-($page-1)*$max;
		else $n = ($page-1)*$max+1;
	}
	if($gesamt) {
		echo'<h2>comments:</h2><form name="form" method="post" action="comments.php?delete=true">';
		
		if($sorttype=="ASC") {
			echo'<a href="'.$referer.'&page='.$page.'&sorttype=DESC">Sort:</a> <img src="images/icons/asc.gif" width="9" height="7" border="0">&nbsp;&nbsp;&nbsp;';
		} else {
			echo'<a href="'.$referer.'&page='.$page.'&sorttype=ASC">Sort:</a> <img src="images/icons/desc.gif" width="9" height="7" border="0">&nbsp;&nbsp;&nbsp;';
		}
		
		if($pages>1) echo $page_link;
		echo'<br><br>';
			
		while($ds=mysql_fetch_array($ergebnis)) {
			$n%2 ? $bg1=BG_1 : $bg1=BG_3;
			
			$date=date("d.m.Y - H:i", $ds[date]);
				
			if($ds[userID]) {
				$ip='';
				$poster='<a class="titlelink" href="index.php?site=profile&id='.$ds[userID].'"><b>'.getnickname($ds[userID]).'</b></a>';
				if(isclanmember($ds[userID])) $member=' <img src="images/icons/member.gif" width="6" height="11" alt="Clanmember">';

				$quotemessage = str_replace("'", "`", $ds[comment]);
				$quotemessage = str_replace('"', '', $quotemessage);
        $quote='<a href="javascript:AddCode(\'[quote]'.getnickname($ds[userID]).' wrote: [br]'.$quotemessage.'[/quote]\')"><img src="images/icons/quote.gif" border="0" alt="quote"></a>';
				
				$country='[flag]'.getcountry($ds[userID]).'[/flag]';
				$country=flags($country);

				if (getemail($ds[userID])) $email = '<a href="mailto:'.getemail($ds[userID]).'"><img src="images/icons/email.gif" border="0" width="15" height="11" alt="email"></a>';
        if (gethomepage($ds[userID]) != "" && gethomepage($ds[userID]) != "http://" && gethomepage($ds[userID]) != "http:///" && gethomepage($ds[userID]) != "n/a") $hp = '<a href="'.gethomepage($ds[userID]).'" target="_blank"><img src="images/icons/hp.gif" border="0" width="14" height="14" alt="homepage"></a>';
        if(isonline($ds[userID])=="offline") $statuspic='<img src="images/icons/offline.gif" width="7" height="7" alt="offline">';
				else $statuspic='<img src="images/icons/online.gif" width="7" height="7" alt="online">';

				if(getavatar($ds[userID])) $avatar='<img src="images/avatars/'.getavatar($ds[userID]).'" align="left">';

				if($loggedin && $ds[userID] != $userID) {
					$pm='<a href="index.php?site=messenger&action=touser&touser='.$ds['userID'].'"><img src="images/icons/pm.gif" border="0" width="12" height="13" alt="messenger"></a>';
					if(isignored($userID, $ds[userID])) $buddy='<a href="buddys.php?action=readd&id='.$ds[userID].'&userID='.$userID.'"><img src="images/icons/buddy_readd.gif" width="16" height="16" border="0" alt="back to buddy-list"></a>';
					elseif(isbuddy($userID, $ds[userID])) $buddy='<a href="buddys.php?action=ignore&id='.$ds[userID].'&userID='.$userID.'"><img src="images/icons/buddy_ignore.gif" width="16" height="16" border="0" alt="ignore user"></a>';
					elseif($userID==$ds[userID]) $buddy='';
					else $buddy='<a href="buddys.php?action=add&id='.$ds[userID].'&userID='.$userID.'"><img src="images/icons/buddy_add.gif" width="16" height="16" border="0" alt="add to buddylist"></a>';
				}
			}
			else {
				$ds[nickname] = strip_tags($ds[nickname]);
				$ds[nickname] = htmlspecialchars($ds[nickname]);
				$poster = $ds[nickname];
				
				$ds[email] = strip_tags($ds[email]);
				$ds[email] = htmlspecialchars($ds[email]);
				if($ds[email]) $email = '<a href="mailto:'.$ds[email].'"><img src="images/icons/email.gif" border="0" width="15" height="11" alt="email"></a>';
				
				$ds[url] = strip_tags($ds[url]);
				$ds[url] = htmlspecialchars($ds[url]);
				if($ds[url]!="http://" && $ds[url]!="") $hp = '<a href="'.$ds[url].'" target="_blank"><img src="images/icons/hp.gif" border="0" width="14" height="14" alt="homepage"></a>';
				$ip = 'IP: ';
				if(isfeedbackadmin($userID)) $ip.=$ds[ip];
				else $ip.='saved';
				
				$quotemessage = str_replace("'", "`", $ds[comment]);
				$quotemessage = str_replace('"', '', $quotemessage);
				$quote='<a href="javascript:AddCode(\'[quote]'.$ds[nickname].' wrote: [br]'.$quotemessage.'[/quote]\')"><img src="images/icons/quote.gif" border="0" alt="quote"></a>';
			}

			$content = cleartext($ds[comment]);
			$content = toggle($content, $ds[commentID]);
			
			if(isfeedbackadmin($userID) OR iscommentposter($userID,$ds[commentID])) {
				$edit = '<a href="index.php?site=comments&editcomment=true&id='.$ds[commentID].'&ref='.urlencode($referer).'" title="edit comment"><img src="images/icons/edit.gif" border="0"></a>';
			}
			
			if(isfeedbackadmin($userID)) $actions='<input class="input" type="checkbox" name="commentID[]" value="'.$ds[commentID].'">';
			
			eval ("\$comments = \"".gettemplate("comments")."\";");
      echo $comments;
				
			unset($member);
			unset($quote);
			unset($country);
			unset($email);
			unset($hp);
			unset($avatar);
			unset($pm);
			unset($buddy);
			unset($ip);
			unset($edit);
			
			if(isfeedbackadmin($userID)) 
				$submit='<input type="hidden" name="referer" value="'.$referer.'">
						 <input class="input" type="checkbox" name="ALL" value="ALL" onClick="SelectAll(this.form);"> select all
						 <input type="submit" value="delete selected">';
			
			if($sorttype=="DESC") $n--;
			else $n++;
		}
		echo'<table width="100%" border="0" cellspacing="0" cellpadding="0">
  			<tr>
    		<td>'.$page_link.'</td>
    		<td align="right">'.$submit.'</td>
  			</tr>
			</table></form>';
    }
	
	if($comments_allowed) {
		if($loggedin) {
			eval ("\$comments_add_user = \"".gettemplate("comments_add_user")."\";");
			echo $comments_add_user;
		}
		elseif($comments_allowed == 2) {
			$ip = getenv(REMOTE_ADDR);
			if (isset($visitor_info)) {
				$visitor = explode("--||--", $visitor_info);
				$name = $visitor[0];
				$mail = $visitor[1];
				$url = $visitor[2];
			}
			else $url = "http://";
			
			if($_GET['error']=="nickname") $error = 'YOU ARE NOT ALLOWED TO USE THIS NICKNAME';
			elseif($_GET['error']=="captcha") $error = 'The security code is wrong!';
			
			$CAPCLASS = new Captcha;
			$captcha = $CAPCLASS->create_captcha();
			$hash = $CAPCLASS->get_hash();
			$CAPCLASS->clear_oldcaptcha();
			
			eval ("\$comments_add_visitor = \"".gettemplate("comments_add_visitor")."\";");
			echo $comments_add_visitor;
		}
		else echo'<br><br>To add your comment you have to be registered and logged in!<br><br>
	              &#8226; <a href="index.php?site=register">register now</a><br>
		          &#8226; <a href="index.php?site=login">log in</a>';
	}
	else echo'<br><br><b>comments disabled.</b>';
}

?>
