#!/usr/bin/perl

###############################################################################
# comments.pl - this code displays comments for a particular story id 
#
# Copyright (C) 1997 Rob "CmdrTaco" Malda
# malda@slashdot.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
#
#  $Id: comments.pl,v 1.4 2000/02/01 20:49:58 CaptTofu Exp $
###############################################################################

use Date::Manip;
use lib ("../");
use strict 'vars';
use Slash;

##################################################################
sub main
{
	getSlash();
	# hack horrivel por causa do squid
	($ENV{REMOTE_ADDR}) = split /\s+/, $ENV{HTTP_X_FORWARDED_FOR}; 
	# Seek Section for Appropriate L&F
	my $sct=$dbh->quote($$F{sid}) || "''";
	my ($s,$title,$commentstatus)=
		sqlSelect("section,title,commentstatus","newstories","sid=$sct");
	my $SECT=getSection($s);
	$$F{pid}||="0";
	$title||="Comments";
	
	header("$$SECT{title}:$title",$$SECT{section});

	if($$U{uid} < 1 and length($$F{upasswd}) > 1) {
		print "<P><B>A tentativa de Login para \"$$F{unickname}\" falhou</B>.  
			Por favor tente outra vez. $$F{op}<BR><P>";
		$$F{op}="Preview";
	}

	if($$U{uid} < 1 and ( $$F{op} eq "Submeter")) {
		print "<P><B>  Só os utilizadores registados podem submeter comentários.
			<BR><P>";
		$$F{op}="Preview";
	}

	unless($$F{sid}) {
		# Posting from outside discussions...
		$$F{sid} = crypt $ENV{HTTP_REFERER}, 0 if $ENV{HTTP_REFERER};
		my $story_time = sqlSelect("time","stories","sid = '$$F{sid}'"); 
		$story_time ||= "now()";
		unless(sqlSelect("title","discussions","sid='$$F{sid}'")) {
			sqlInsert("discussions", { sid=>$$F{sid}, title=>'', -ts=>'$story_time', url=>$ENV{HTTP_REFERER} } );

		}
	}

#AJC	
	$$U{threshold} = -1 if ($$U{threshold}<-1);
	$$U{threshold} = -2 if (($$U{aseclev}>99) or ($$U{points}>0));
	if($$F{op} eq "Submeter" ) {

		($$U{karma})=sqlSelect("karma","users_info","uid=$$U{uid}") if $$U{uid} > 0;
		submitComment();
	} elsif($$F{op} eq "Edit" or $$F{op} eq "post" 
		or $$F{op} eq "Antever" or $$F{op} eq "Responder") {

		($$U{karma})=sqlSelect("karma","users_info","uid=$$U{uid}") if $$U{uid} > 0;
		editComment();
  	} elsif($$F{op} eq "delete" and ($$U{aseclev}>10000)) {

		($$U{karma})=sqlSelect("karma","users_info","uid=$$U{uid}") if $$U{uid} > 0;
                titlebar("99%","Delete $$F{cid}");
                my $delCount=deleteThread($$F{sid},$$F{cid});
                $dbh->do("UPDATE stories SET
                        commentcount=commentcount-$delCount,writestatus=1
                        WHERE sid=".$dbh->quote($$F{sid}));
                print "Foram apagados $delCount elementos do artigo $$F{sid}\n";
        } elsif($$F{op} eq "moderar") {
		($$U{karma})=sqlSelect("karma","users_info","uid=$$U{uid}") if $$U{uid} > 0;
                titlebar("99%","Moderação de $$F{sid}");
                moderate();   
		printComments($$F{sid},$$F{pid},$$F{cid},$commentstatus);
	} elsif($$F{op} eq "Mudar") {
		saveChanges() if $$U{uid} > 0;
		printComments($$F{sid},$$F{cid},$$F{cid},$commentstatus);
	} elsif($$F{cid}) {
        	printComments($$F{sid},$$F{cid},$$F{cid},$commentstatus);
	} elsif($$F{sid}) {
        	printComments($$F{sid},$$F{pid},"",$commentstatus);
	} else {
		commentIndex();
	}
	writelog("comments",$$F{sid});

	footer();
}


##################################################################
# Index of recent discussions: Used if comments.pl is called w/ no
# parameters
sub commentIndex
{
	titlebar "90%", "Várias Discussões Activas";
	print "<MULTICOL cols=2>";
	my $c=sqlSelectMany("sid,title,url","discussions where ts <= now() order by ts desc LIMIT 50");
	while(my $C=$c->fetchrow_hashref()) {
		$$C{title}||="untitled";
		print "<LI><A href=$rootdir/comments.pl?sid=$$C{sid}>$$C{title}</A> (<A href=$$C{url}>referer</A>)\n";

	}
	print "</MULTICOL>";
	$c->finish();
}


##################################################################
# Save users preferences is they change them, and click the "Save" checkbox
sub saveChanges
{
	return unless $$U{uid} > 0;

	sqlUpdate("users_comments", { 
		threshold=>$$U{threshold}, 
		mode=>$$U{mode},
		commentsort=>$$U{commentsort} },
		  "uid=$$U{uid}") if defined $query->param("savechanges");
}


##################################################################
# Welcome to one of the ancient beast functions.  The comment editor
# is the form in whcih you edit a comment.
sub editComment
{
	$$U{points}=0;

	my $reply=sqlSelectHashref(Slash::getDateFormat("date","time").",
		subject,comments.points as points,comment,realname,nickname,fakeemail,homepage,cid,sid,
		users.uid as uid",
		"comments,users,users_info,users_comments",
		"sid=".$dbh->quote($$F{sid})."
		  AND cid=".$dbh->quote($$F{pid})."
		  AND users.uid=users_info.uid 
		  AND users.uid=users_comments.uid 
		  AND users.uid=comments.uid");

	# Display parent comment if we got one
	if($$F{pid}) {
		titlebar("95%", " $$reply{subject}");
		print "<TABLE border=0 cellpadding=0 cellspacing=0 
			width=95% align=center>"; 
		Slash::dispComment($reply);
		print "</TABLE><P>";
	}
	
	if($$F{postercomment}) {
		titlebar("95%","Antevisão de Comentário"); 
		previewForm();
		print "<P>\n";
	}

       	titlebar("95%","Submissão de Comentário");
	print "\n<FORM
	    action=\"$ENV{SCRIPT_NAME}\" 
            method=post>\n";
	print "<input type=hidden name=sid value=\"$$F{sid}\">
		<input type=hidden name=pid value=\"$$F{pid}\">
		<INPUT type=hidden name=mode value=$$U{mode}>
		<INPUT type=hidden name=startat value=$$U{startat}>
		<INPUT type=hidden name=threshold value=$$U{threshold}>
		<INPUT type=hidden name=commentsort value=$$U{commentsort}>";
	print "<table border=0 cellspacing=0 cellpadding=1>\n";
	print "<TR><TD> </TD><TD>
      Não está admitido no sistema. Pode ser admitido usando
      os campos abaixo, ou
		<A href=\"$rootdir/users.pl\">Abrindo uma Conta</A>.
		Submissões sem um registo no sistema não são permitidas.
		
		<INPUT type=hidden name=rlogin value=userlogin>
		<TR><TD align=right>Alcunha</TD><TD><INPUT
		type=text name=unickname VALUE=\"$$F{unickname}\"></TD></TR>
		<TR><TD align=right>Chave</TD><TD>
		<INPUT type=password name=upasswd></TD></TR>" if $$U{uid} < 1;

#		Submissões sem um registo no sistema são identificadas como
#		<B>$$U{nickname}</B></TD></TR>

	my ($quota) = sqlSelect("quota","users_comments","uid=$$U{uid}");
print STDERR "quota = $quota\n";
	if ($quota>0) {					# AJC
	  print "<b>Hoje ainda pode escrever $quota comentários</b><br>";
	} else {
	  print "<b>Esgotou a sua quota de comentários para hoje. Os que escrever agora ficarão em quarentena até algum moderador resolva liberta-los.</b>";
	}
	
	print "<tr><td width=130 align=right>Nome</td><td
		width=500><A href=\"$rootdir/users.pl\">$$U{nickname}</A> [";
	if($$U{uid} > 0) {
		print " <A href=\"$rootdir/users.pl?op=userclose\">Sair</A> ";
	} else {
		print " <A href=\"$rootdir/users.pl\">Criar Conta</A> ";
	}
			
	print " ] </TD></TR>\n";
	print "<tr><td align=right>Email</td>
		<td>$$U{fakeemail}</td></tr>\n" if $$U{fakeemail};
			
	print "<tr><td align=right>URL</td><TD><A
		href=\"$$U{homepage}\">$$U{homepage}</A>
		</TD></TR>\n" if $$U{homepage};
	print "<tr><td align=right>Assunto</td>";

	if($$F{pid} and not $$F{postersubj}) { 
		$$F{postersubj}=$$reply{subject};
		$$F{postersubj}=~s/^Re://i;
		$$F{postersubj}=~s/\s\s/ /g;
		$$F{postersubj}="Re:$$F{postersubj}";
	} 
                
	print "<td>",
		$query->textfield(-name=>'postersubj', 
			-default=>$$F{postersubj}, 
			-size=>50, -maxlength=>50),
		"</td></tr>\n";
	print "<tr><td align=right valign=top>Comentário</td>";
	print "<td><textarea wrap=virtual name=postercomment rows=10 cols=50>";
	print stripByMode($$F{postercomment}, 'literal');
	print "</textarea><BR>(Use o botão de Antevisão! Verifique os URLs!  
		Não esquecer o http://!)</td></tr>\n";
	print "<tr><td> </TD><TD>\n";

	my $checked = $$F{nobonus} ? 'CHECKED' : '';
	print qq[<INPUT TYPE="checkbox" $checked NAME="nobonus"> Sem Pontuação +1 Bonus<br> ]
		if $$U{karma} > 25 and $$U{uid} > 0;

	$checked = $$F{postanon} ? 'CHECKED' : '';
#	print qq[<INPUT TYPE="checkbox" $checked NAME="postanon"> Submeter
#Anonimamente<BR>]
#		if $$U{karma} > -1 and $$U{uid} > 0;


	$checked = $$F{noreplies} ? 'CHECKED' : '';
	print qq[<INPUT TYPE="checkbox" $checked NAME="noreplies"> Não aceita respostas<br>];

	print "<input type=submit name=op value=\"Submeter\">" if ($$U{uid}>0);
	print "<input type=submit name=op value=\"Antever\">\n"; 

	if ($$F{posttype}) {
	  selectGeneric("postmodes","posttype","code","name",$$F{posttype});
	} else {
	  selectGeneric("postmodes","posttype","code","name",$$U{posttype});
	}
	print "</td></tr><TR><TD valign=top align=right>HTML Permitido</TD><TD><FONT size=1>\n";
	foreach my $tag (@approvedtags) { print "&lt;$tag&gt; \n"; }
	print "</FONT></TD></TR></table>\n\n";
	print "</FORM>\n";
	print " <B>Elementos Importantes:</B>
		<LI>Por favor tente manter-se no tópico
		<LI>tente responder aos outros comentários em vez de iniciar
          novas linhas, 
		<LI>leia as mensagens dos outros antes de submeter a sua para evitar
				reproduzir o que já foi dito por outros.
		<LI>Escolha um tema claro que descreva bem o conteúdo da sua mensagem.
		<LI>Comentários Fora do Tema, Raivosos, Inapropriados, Ilegais,
          ou Ofensivos podem vir a ser moderados. (Tudo pode ser lido,
          inclusíve comentários moderados, pelo ajuste da visibilidade na
			 Página de Preferências do Utilizador)
	       <P><font size=2>Problemas relacionados com contas ou com a
			 submissão de comentários devem ser enviados 
	       para <A href=\"mailto:$adminmail\">$siteadmin_name</A>.</FONT>";
}

##################################################################
# Validate comment, looking for errors
sub validateComment
{
	my($comm, $subj, $preview) = @_;

        if(isTroll()) {
		print "Esta conta ou IP foi temporariamente desactivada.
         Isto quer dizer que este IP, ou esta conta, foram moderados
         negativamente mais de 5+ vezes nas últimas 24 horas.
         Se acha que isto é injusto, deve contactar $adminmail.
         Se se está a portar como um chato, então é altura
         de crescer, ou de mudar de IP.";
print STDERR "trolled: uid   $$U{uid}\n";
		return;
	}

	unless($comm && $subj) {
		print "O gato comeu-lhe a lingua ? (aparentemente alguma
      coisa importante está em falta no seu comentário. Algo
      como o próprio comentário ou o assunto!";
		return;
	}

	$subj =~ s/\(Score(.*)//i;
	$subj =~ s/Pontos:(.*)//i;
	
	{  # fix unclosed tags
		my %tags;
		my $match = 'B|I|A|OL|UL|EM|TT|STRONG|BLOCKQUOTE|DIV';

		while ($comm =~ m|(<(/?)($match)\b[^>]*>)|igo) { # loop over tags
			my($tag, $close, $whole) = (uc $3, $2, $1);

			if ($close) {
				$tags{$tag}--;

				# remove orphaned close tags if count < 0
				while ($tags{$tag} < 0) {
					my $p = pos($comm) - length($whole);
					$comm =~ s|^(.{$p})</$tag>|$1|si;
					$tags{$tag}++;
				}

			} else {
				$tags{$tag}++;

				if (($tags{UL} + $tags{OL}) > 3) {
					editComment() and return unless $preview;
					print "Só pode submeter listas embricadas até 3 níveis 
						de profundidade. Por favor corriga os tags UL ou OL.";
					return;
				}
			}	
		}

		for my $tag (keys %tags) {
			# add extra close tags
			while ($tags{$tag} > 0) {
				$comm .= "</$tag>";
				$tags{$tag}--;
			}
		}
	}

	my($dupRows) = sqlSelect(
		'count(*)', 'comments', 'sid=' . $dbh->quote($$F{sid}) .
		' AND comment=' . $dbh->quote($$F{postercomment})
	);

	if ($dupRows || !$$F{sid}) { 
		# $r->log_error($ENV{SCRIPT_NAME}." ".$insline);
		editComment() and return unless $preview;
		print "Algo está errado: parent=$$F{pid} 
			dups=$dupRows discussion=$$F{sid}
		      <UL>\n";
		print "<LI>Escapou o assunto?" unless $$F{postersubj};
		print "<LI>Duplicado. Submeteu duas vezes?" if $dupRows;
		print "<LI>A Pipi das Meias Altas comeu os seus dados." unless $$F{sid};
		print "<LI>Avise-nos se algo excepcionalmente estranho ocorrer\n";
		print "</UL>";
		return;
	}

	if (length($$F{postercomment}) > 100) {
		local $_ = $$F{postercomment};
		my($w,$br); # Whitespace & BRs
		$w++ while m/[\w]/g;
		$br++ while m/<BR>/gi;

		if (($w / ($br+1)) < 7) {
			editComment() and return unless $preview;
			return;
		}
	}

	if ($$F{postersubj} =~ /\w{80}/ || $$F{postercomment} =~ /\w{80}/) {
		editComment() and return unless $preview;
		print "Filtro de trengos activado.  Submissão cancelada.";
		return;
	}
	return($comm, $subj);
}

##################################################################
# Previews a comment for submission
sub previewForm
{
	$$U{sig} = "" if $$F{postanon};

	my $tempComment = stripByMode($$F{postercomment}, $$F{posttype});
	my $tempSubject = stripByMode($$F{postersubj}, 'nohtml',
		$$U{aseclev}, 'B');

	($tempComment, $tempSubject) = validateComment($tempComment, $tempSubject, 1);

	$tempComment .= '<BR>' . $$U{sig};

       	my $preview = {
		nickname  => $$F{postanon} ? 'Cobarde Anónimo' : $$U{nickname},
		pid	  => $$F{pid},
		homepage  => $$F{postanon} ? '' : $$U{homepage},
		fakeemail => $$F{postanon} ? '' : $$U{fakeemail},
		'time'	  => 'em breve',
		subject	  => $tempSubject,
		comment	  => $tempComment
	};

        print qq[<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0" ] . 
	      qq[WIDTH="95%" ALIGN="CENTER">\n];

	my $tm = $$U{mode};
	$$U{mode} = 'archive';
	Slash::dispComment($preview);       
	$$U{mode} = $tm;

	print "</TABLE>\n";
}


##################################################################
# Saves the Comment
sub submitComment
{
	$$F{postersubj} = stripByMode($$F{postersubj}, 'nohtml',
		$$U{aseclev}, '');
	$$F{postercomment} = stripByMode($$F{postercomment}, $$F{posttype});

	($$F{postercomment}, $$F{postersubj}) =
		validateComment($$F{postercomment}, $$F{postersubj})
		or return;

	titlebar("95%","Comentário Enviado");

	my $ident = $ENV{REMOTE_ADDR};
	my $pts = 0;

	# AJC
	my ($qtime) = sqlSelect("unix_timestamp(quarantine)","users","uid=$$U{uid}");
	my ($quota) = sqlSelect("quota","users_comments","uid=$$U{uid}");
	my $quarantined =  (((time()<$qtime) || ($quota<1)) && ($$U{aseclev}<99)); 		
	$quarantined ||= 0;			# not empty	

	my $accreply = 1;	# comment accepts reply
	$accreply = 0 if ($$F{noreplies});

	$pts = -1 if (($$U{uid} < 0) || ($$F{postanon}));  # AJC
	if($$U{uid} > 0 && !$$F{postanon} ) {
		$pts = $$U{defaultpoints};
		$pts-- if $$U{karma} < -10;
		$pts++ if $$U{karma} > 25 and !$$F{nobonus}
	}

	$dbh->do("LOCK TABLES comments WRITE");
	my ($maxCid)=sqlSelect("max(cid)","comments",
		"sid=".$dbh->quote($$F{sid}));

	$maxCid++; # This is gonna cause troubles
	my $insline="INSERT into comments values (".
                          $dbh->quote($$F{sid}).",$maxCid,".
			  $dbh->quote($$F{pid}).",
			  now(),'$ident',".
                          $dbh->quote($$F{postersubj}).",".
                          $dbh->quote($$F{postercomment}).",".
                          ($$F{postanon}?-1:$$U{uid}).",$pts,-1,0,$quarantined,$accreply)";

	# don't allow pid to be passed in the form . 
	# This will keep a pid from being replace by 
	# with other comment's pid
	if($$F{pid} >= $maxCid or $$F{pid} < 0) {
                print "Não tem nada mais útil para fazer na vida?";
                return;
        }


	if($dbh->do($insline)) {
		$dbh->do("UNLOCK TABLES");
      		print "Comentário Enviado. Vai decorrer um atraso
         até que o comentário faça parte da página estática.
         Aquilo que submeteu aparece abaixo. Se há algum erro,
         então devia ter usado o botão de Antevisão!<P>";

		# AJC: update quota
		sqlUpdate("users_comments",{quota=>$quota-1},"uid=$$U{uid}")
  		   if (($quota>0) && $$U{aseclev}<99);

		# Update discussion
		my ($dtitle)=sqlSelect('title','discussions',
			"sid=".$dbh->quote($$F{sid}));
		print "my $dtitle" if $$U{uid} == 1;
		unless($dtitle) {
			sqlUpdate("discussions",{ title=>$$F{postersubj} },"sid=".$dbh->quote($$F{sid} ) ) if $$F{sid};
		}
		  
		my ($ws)=sqlSelect("writestatus","stories",
			"sid=".$dbh->quote($$F{sid}));

		if($ws==0) {
			sqlUpdate("stories",{ writestatus=>1 }, 
				"sid=".$dbh->quote($$F{sid}));
		}

		sqlUpdate("users_info",
			{ -totalcomments=>'totalcomments+1' },
			"uid=".$dbh->quote($$U{uid}) ,1);

		my ($tc,$mp,$cpp)=
			getvars("totalComments","maxPoints","commentsPerPoint");
			
		setvar("totalComments",++$tc);

		undoModeration($$F{sid}) if ($$U{seclev}<99);
		printComments($$F{sid},$maxCid,$maxCid);

	} else {
		$dbh->do("UNLOCK TABLES");
		$r->log_error("$DBI::errstr $insline");
		print "<p>Ocorreu um erro desconhecido na submissão.<br>";
			
	}
}

##################################################################
# Handles moderation
sub moderate
{
        my $totalDel=0;
	if(hasPosted($$F{sid}) and not ($$U{aseclev}>100) ) { #ajc
		print "Já submeteu algo nesta discussão<BR>";
		return;
	}

        print "<ul>\n";
        # Handle Deletions, Points & Reparenting
        foreach (sort keys %$F) {
                if(/\Adel_(.*)/ and $$U{points}) {
                        my $delCount=deleteThread($$F{sid},$1);
                        $totalDel+=$delCount;
			sqlUpdate("stories", { -commentcount=>"commentcount-$delCount",
				writestatus=>1 },
                                "sid=".$dbh->quote($$F{sid}), 1);
                        print "<li>Foram apagados $delCount elementos do
              artigo $$F{sid} debaixo do comentário $$F{$_}\n" if $totalDel;
                } elsif(/\Areason_(.*)/) {
			moderateCid($$F{sid},$1,$$F{"reason_".$1});
		}
        }
        print "</ul>\n";
        if($$U{aseclev} and $totalDel) {
                my ($cc)=sqlSelect("count(sid)","comments",
                        "sid=".$dbh->quote($$F{sid}));
                sqlUpdate("stories",{commentcount=>$cc},"sid=".$dbh->quote($$F{sid}));
                print "$totalDel comentários apagados. Número de comentários
passa a ser $cc<br>\n";
        }
}              

##################################################################
# Handles moderation
# Moderates a specific comment
sub moderateCid
{
        my($sid,$cid,$reason)=@_;
        # Check if $uid has seclev and Credits
	return unless $reason;
	
	unless($$U{points} or ($$U{aseclev}>100) ) {# ajc
		print "Você não tem nenhuns pontos de moderação.";
		return;
	}

        my ($cuid,$ppid,$subj,$points,$oldreason)
		=sqlSelect("uid,pid,subject,points,reason","comments",
		"cid=$cid and sid='$sid'");

	my $modreason=$reason;
	my $val="-1";
	if($reason == 9) { # Overrated
		$val="-1";
		$val="+0" if $points < 0;
		$reason=$oldreason;
	} elsif ($reason == 10) { # Underrated
		$val="+1";
		$val="+0" if $points > 1;
		$reason=$oldreason;
	} elsif ($reason > $badreasons) {
		$val="+1";
	}

 	my $strsql="UPDATE comments SET
       	        	points=points$val,
			reason=$reason,
			lastmod=$$U{uid}
                      	WHERE sid=".$dbh->quote($sid)."
			  AND cid=$cid 
			  AND points ".
			  ($val<0?" > -2":"").	
			  ($val>0?" < 5":"").
		          " AND lastmod<>$$U{uid}";

	if($val ne "+0" and $dbh->do($strsql)) {
		sqlInsert("moderatorlog", {
			uid=>$$U{uid},
			val=>$val,
			sid=>$sid,
			cid=>$cid,
			reason=>$modreason,
			-ts=>'now()' } );

		# Adjust comment posters karma
		sqlUpdate("users_info", {-karma=>"karma$val" }, 
			"uid=$cuid") if $val and $cuid > 0;

		# tokens for the user	(AJC)
		addTokens($cuid,"+2") if ($val eq "+1");
		addTokens($cuid,"-2") if ($val eq "-1");
		
		# Adjust moderators total mods
		sqlUpdate("users_info", { -totalmods=>'totalmods+1' }, 
			"uid=$$U{uid}");


		# tokens for the moderator	(AJC)
		addTokens($$U{uid},"+2") if ($val eq "+1");
		addTokens($$U{uid},"-2") if ($val eq "-1");

		# AJC: update quota
		sqlUpdate("users_comments",{-quota=>"quota+1"},"uid=$cuid")
			if ($val eq "+1");

		# And deduct a point.
		$$U{points}-=1;
		sqlUpdate("users_comments", {-points=>$$U{points} }, 
			"uid=$$U{uid}") if ($$U{aseclev}<=100);

               	print "<LI>$val ($reasons[$reason]) $subj 
			($sid-$cid, <B>$$U{points}</B> 
			pontos em sobra)\n";
	}
}

##################################################################
# Given an SID & A CID this will delete a comment, and all its replies
sub deleteThread
{
    my($sid,$cid)=@_;
    my $delCount=1;

	return unless $$U{aseclev} > 100;

	print "Apagando $cid de $sid, ";
	print STDERR  "Apagando comentário $cid de $sid (aid=$$U{aid})\n";
	my $delkids=sqlSelectMany("cid","comments","sid='$sid' and pid='$cid'");
        while(my ($scid)=$delkids->fetchrow_array) {
                $delCount+=deleteThread($sid,$scid);
        }
        $delkids->finish();
        $dbh->do("delete from comments
                WHERE sid=".$dbh->quote($sid)." and cid=".$dbh->quote($cid));

	print "<BR>";
        return $delCount;
}                         

##################################################################
# Checks if this user has posted in this discussion or not (to determine
# if they can moderate or not)
sub hasPosted
{
	my($sid)=@_;
	my ($c)=sqlSelect("count(*)","comments",
		"sid=".$dbh->quote($sid)." and uid=$$U{uid}");
	return $c;
}

##################################################################
# If you moderate, and then post, all your moderation is undone.
sub undoModeration
{
	my ($sid)=@_;
	return if $$U{uid}==-1;
	return if $$U{aseclev} > 100;
	my $c=sqlSelectMany("cid,val","moderatorlog",
		"uid=$$U{uid} and sid=".$dbh->quote($sid));
	while( my ($cid,$val)=$c->fetchrow() ) {
		$dbh->do("delete from moderatorlog where
			cid=$cid and uid=$$U{uid} and sid=".$dbh->quote($sid) );
		sqlUpdate("comments", { -points=>"points+".(-1*$val) },
			  "cid=$cid and sid=".$dbh->quote($sid) );
		print "Desfazendo a moderação ao Comentário \#$cid<BR>";
	}	
	$c->finish();
}

##################################################################
# Troll Detection: essentially checks to see if this IP or UID has been abusing
# the system in the last 24 hours.
# 1=Troll 0=Good Little Goober
sub isTroll
{

   my ($badIP,$badUID)=0;
   return 0 if $$U{uid} > 0 and $$U{karma} > -1;
   # Anonymous only checsk HOST
   ($badIP)=sqlSelect("sum(val)","comments,moderatorlog",
                "comments.sid=moderatorlog.sid AND comments.cid=moderatorlog.cid
                 AND host_name='$ENV{REMOTE_ADDR}' 
		 AND (to_days(now()) - to_days(ts) < 3) GROUP BY host_name");

    return 1 if $badIP < $down_moderations; 

    if($$U{uid} > 0) {
        ($badUID)=sqlSelect("sum(val)","comments,moderatorlog",
                "comments.sid=moderatorlog.sid AND comments.cid=moderatorlog.cid
                 AND comments.uid=$$U{uid}
		 AND (to_days(now()) - to_days(ts) < 3)  GROUP BY comments.uid");
    }
    return 1 if $badUID < -6;
    return 0;
}

main;
0;
