#!/usr/bin/perl -w

#<head><title>comments.pl</title>
#<meta name="category" content="pl,perl">
#<meta name="description" content="Perl cgi script wich acts like a guestbook, comment.">
#<meta name="begun" content="Sat Apr 26 20:07:19 MEST 2003">
#</head>

use Time::HiRes qw( usleep ualarm gettimeofday tv_interval );
my $start=[gettimeofday];

use strict;
use Server;
use Text::Textile qw(textile);
use Data::Dumper;
use HTML::Template;
use Date::Manip;
use jip;

# cgi
use CGI;
my $q=new CGI;
print $q->header;

# about
my $about=$q->param('about') || $q->referer;
my $debug=$q->param('debug') || '';

my $now=time;

# `echo $now > /tmp/lastupdate`;

use Lok;

#$about="/Gfx/jiprood.gif";
#my $l=Lok->new( '/Gfx//2003/2003Week17/dscn9775.LedigErf.jpg.html' );
#print "<pre>".Dumper($l)."</pre>";

#exit 1;

# captcha
use Authen::Captcha;
my $captchafolder = '/var/www/www.kwark.org/docs/2005/captcha';
my $captcha = Authen::Captcha->new(
				   data_folder => $captchafolder,
				   output_folder => $captchafolder,
				  );
# dbh
my $server;
unless (defined($server)){
    $server = Server->instance();
    die $server->ERROR unless defined $server;
    print "<pre>" . Dumper($server) if $debug;

#    print Dumper($server->{'dbh'}) if $debug;
}
my $dbh=$server->{'dbh'};
my $config=$server->{'config'};

my $aboutid=$about;

if (defined($about)){
    $about =~ s!http://www.kwark.org!!;
    my $abouts = $server->a2id($about);
    $about =$abouts if $abouts;
  
}

# 200604
my $spam='';
if ($about && $q->referer && !($q->referer =~ m!$about!i)){
 $spam .= 'refer ';
}

my $code        =$q->param('code') || '';
# add
if (defined($q->param('action')) && $q->param('action') eq 'add'){
    my $md5sum      =$q->param('md5sum');
    my $qname       =$dbh->quote($q->param('name'));
    my $qemail      =$dbh->quote($q->param('email'));
    my $qabout      =$dbh->quote($about);
    my $qabouttitle =$dbh->quote($q->param('abouttitle'));
    my $qurl        =$dbh->quote($q->param('url'));
    my $qcomment    =$dbh->quote($q->param('comment'));
    my $qip         =$dbh->quote($ENV{REMOTE_HOST} || $ENV{REMOTE_IP} || $ENV{REMOTE_ADDR}
 );
    my $qbrowser    =$dbh->quote($ENV{'HTTP_USER_AGENT'});


    # 20050619
    my $captcharesult = $captcha->check_code($code,$md5sum);
    unless ($captcharesult == '1'){
      $spam .= 'captcha ';
      sleep rand(4);
      print "<h1>Sorry, invalid code $code</h1>\n";
      sleep rand(8);
    }else{
      my $query="INSERT INTO comments(name,email,url,about,abouttitle,comment,ip,browser)
                VALUES($qname,$qemail,$qurl,$qabout,$qabouttitle,$qcomment,$qip,$qbrowser)
              ";
      print $query if $debug;
      my ($sth,$error)=$server->doq($query);
      if ($error){
	print "err:$error";
      }else{
	print " Added comment.<br /> ";
      }
    }
  

} # end add


if ($spam){ 
 my $spamip   = $ENV{REMOTE_ADDR} || '';
 my $spamhost = $ENV{REMOTE_HOST} || '';
 my $refer    = $q->referer       || '';
 warn "$spamip $spamhost invalid captcha: \'$code\' $refer spam:$spam";
 sleep rand(5);
}



#
# queyr show all
#
my @comments;
my $table    =$config->{'db.table'};
my $query    ="SELECT * FROM $table ORDER BY timestamp desc LIMIT 50";
my ($sth,$error)=$server->doq($query);
while ( my $row = $sth->fetchrow_hashref){
  print Dumper $row if $debug;
  my $timestamp=$row->{'timestamp'};
  my $about    =$row->{'about'};

  if ($about){
    my $lok = Lok->new($about);
    # warn ($about);
    #warn Dumper($lok);
    if ($lok->{'row'}){
      my @loka;
      push @loka,$lok->{'row'} if $lok->{'row'};
      $row->{'lok'} = \@loka;
    }
  }      
  
  #print Dumper($row->{'lok'});
  
  my $date=&ParseDate($timestamp);
  my $datel=&Date_ConvTZ($date,"",'MEST');
  $date=&UnixDate($datel,'%a %d %b %Y %H:%M');
  print "timestamp: $timestamp d:$date " if $debug;
  $row->{'date'}=$date;
  my $html = textile($row->{'comment'} . " ");
  $html =~ s!(http\:\/\/.*?)\s!<a href="$1">$1</a>!;
  $html =~ s!^\<p\>!!;
  $html =~ s!\<\/p\>$!!;
  $row->{'html'} = $html;
  push @comments,$row;
}


#
# queyr show about hak hak
#
my $atable=$config->{'db.table'};
my @commentsabout;
my $qabout=$dbh->quote($about);
my $aquery="SELECT * FROM $table WHERE about=$qabout ORDER BY timestamp desc";
my ($asth,$aerror)=$server->doq($aquery);
print $aquery if $debug;
while ( my $row = $asth->fetchrow_hashref){
  print Dumper $row if $debug;
  my $timestamp = $row->{'timestamp'};
  my $about     = $row->{'about'};

  # date
  my $date=&ParseDate($timestamp);
  my $datel=&Date_ConvTZ($date,"",'MEST');
  $date=&UnixDate($datel,'%a %d %b %Y %H:%M');
  print "timestamp: $timestamp d:$date " if $debug;
  $row->{'date'}=$date;

  #about
  foreach my $th ( @{$config->{'hostnames'}} ){
      if ( $about =~ m!^$th.*! ){
	  print " On localhost. " if $debug;
      }
  }

  my $html = textile($row->{'comment'} . " ");
  $html =~ s!(http\:\/\/.*?)\s!<a href="$1">$1</a>!;
  $html =~ s!^\<p\>!!;
  $html =~ s!\<\/p\>$!!;
  $row->{'html'} = $html;
  push @commentsabout,$row;
}


#
# display about
#
my $sabout=$about;
my $tll=Lok->new($about);
my $abouts =  $tll->{'row'}->{'comment'} ||  $tll->{'row'}->{'xurl'};
$sabout =$abouts if $abouts;
my $space = '<span style="font-size: .001px"> </span>';
$sabout =~ s!(/|&)!$1$space!gis  if $sabout;


my $abouttitle=$q->param('abouttitle') || '';




# template
my $template = HTML::Template->new(
				   die_on_bad_params => 0,
				   filename => $server->{'config'}->{'templatedir'} . '/comments-view.template',
				   cache    => 1,
				  );



my @aboutdata;
#my $about="/Gfx//2003/2003Week17/dscn9775.LedigErf.jpg.html";
if ($about){
    my $lok = Lok->new($about);
    # warn ($about);
    #warn Dumper($lok);
    if ($lok->{'row'}){
	my $aarow=$lok->{'row'};
	push @aboutdata, $aarow;
    }
}      

#print "<pre>";
#print Dumper(@row);
#print Dumper(@comments);


#exit;


my $md5sum = $captcha->generate_code(4);

for my $var ($q->param() ){
  $template->param( "cgi_" . $var => $q->param($var) );
}

my $end=[gettimeofday];
my $elapsed = tv_interval ( $start, $end );
#print " Time:$elapsed seconds.";

$template->param(
		 md5sum     => $md5sum,
		 lok        => \@aboutdata,
		 elapsed    => $elapsed,
		 comments   => \@comments,
		 commentsabout => \@commentsabout,
		 refer      => $about,
		 about      => $about,
		 sabout     => $sabout,
		 abouttitle => $abouttitle,
		 hoofd      => hoofd('comments'),
		 voet       => voet2('comments'),
		 );

#print Dumper($template);
print $template->output;

# kla













