#!/usr/bin/perl
# vim:set ai ts=4 sw=4 tw=0:

# lib-path for cyberia
#use lib qw( /schweizr/cgi-bin/lib /www/matrix/schweizr/cgi-bin/lib );

use CGI qw(:standard);
use CGI::Carp qw/fatalsToBrowser/;

#use Fcntl ':flock'; # import LOCK_* constants
#use Image::Size;
use Socket;	# import AF_* constants

$CGI::POST_MAX=1024 * 500;  # max 500K posts

###########################
### configuration stuff ###
###########################
# files must be writeable by webserver process (-rw-rw-rw-)
# do NOT use .shtml-files (security)
my %Files = (
     'textpage'    => '/www/schotter/docs/nippes/text.html'    ,
     'loeffelpage' => '/www/schotter/docs/nippes/loeffel.html'
);

my %URI = (
     'textpage'    => 'http://www.schotter.com/nippes/text.html'       ,
     'loeffelpage' => 'http://www.schotter.com/nippes/loeffel.html'    ,
     'imageerror'  => 'http://www.schotter.com/nippes/imageerror.html' ,
     'default'     => 'http://www.schotter.com/nippes/form.html'
);

my $Imagedir = '/www/schotter/docs/nippes/loeffel/';
my $WebImagedir = '/nippes/loeffel/';

#my @Imagetypes = ( qw/ GIF JPG / );

my $uri = $URI{'default'};

#################
### main part ###
#################
my $query = new CGI;
my $scriptname = $query->script_name;

my $printform = $query->param('printform') || 0;

##########################################
########## PAGE STARTS HERE ##############
##########################################

if( $printform )
{
   print $query->header;
   print $query->start_html(-TITLE=>'Gib den Löffel ab!',
						 -AUTHOR=>'schweizr@schweizr.com',
						 -BGCOLOR=>'#e0e0e0',
						 -TEXT=>'#000000',
						 -LINK=>'#7e00c3',
						 -VLINK=>'#5c0095',
						 -ALINK=>'#ff0000');

   # Start a multipart form.
   print $query->start_multipart_form(),
      'Name:',
      $query->textfield(-name=>'name',
                        -size=>30),br,"\n",
      'eMail:',
      $query->textfield(-name=>'email',
                        -size=>30),br,"\n",
      'Web:',
      $query->textfield(-name=>'web',
                        -size=>30),br,"\n",
      'Titel:',
      $query->textfield(-name=>'title',
                        -size=>50),br,"\n",

      $query->textarea(-name=>'text',
                       -rows=>10,
                       -columns=>50),br,"\n",

      $query->radio_group(-name=>'type',
                          -'values'=>['textpage','loeffelpage'],
                          -labels=>{'textpage' => 'Textseite',
						            'loeffelpage' => 'Löffelseite'},
                          -linebreak=>'true',
                          -default=>'textpage'),br,"\n",

      'Bilddatei:',
      $query->filefield(-name =>'filename',
                        -size =>20),br,"\n",

      $query->reset(-value => 'Reset'),
      $query->submit(-value => 'Nimm!'),
      $query->endform,
      $query->end_html;
}

$type = $query->param('type');
if ( defined($type) && exists($Files{$type}) ) 
{
	my($name,$email,$web,$title,$text)=('','','','','');
	my($file,$tmpfile,$imagefilename,$imagetype)=('','','','');
	my($width,$height,$imagesize,$mimetype)=(0,0,0,'');

	# handle upload-file
	if ( $file = $query->param('filename') ) 
	{
		$tmpfile = $query->tmpFileName($file);
		$mimetype = $query->uploadInfo($file)->{'Content-Type'} || '';

		open(TMPFILE, "$tmpfile") or die("can't open '$tmpfile': $!");
		my($imagedata, $bytesread, $buffer);
		while ($bytesread = read(TMPFILE,$buffer,1024)) {
			$imagedata .= $buffer;
		}
		close(TMPFILE);

#		($width, $height, $imagetype) = imgsize(\$imagedata);
#		if( grep { $imagetype eq $_ } @Imagetypes )
#		{
#		  $imagefilename = time . '.' . lc($imagetype);
#
#		  # save image to somewhere else
#		  open (IMAGE,">$Imagedir/$imagefilename")
#		    or die("can't create '$Imagedir/$imagefilename': $!");
#		  print IMAGE $imagedata;
#		  close(IMAGE);
#		  $imagesize = sprintf("%.2f k",length($imagedata)/1024);
#		}
#		else
#		{
#		  $uri = $URI{'imageerror'};
#		}
	}

   # map form-variables
   $name  = $query->param('name')  || 'N/A';
   $email = $query->param('email') || 'N/A';
   $web   = $query->param('web')   || 'N/A';
   $title = $query->param('title') || 'N/A';
   $text  = $query->param('text')  || 'N/A';

   $text =~ s/$/<BR>/mg;
   $text =~ s/^<BR>$/<P>/mg;

   # select redirect-uri
   $uri = $URI{$type};

   # select html-file
   $htmlfile = $Files{$type};

   # select format-file
   $formatfile = $htmlfile . '.fmt';

   open(FORMATFILE, "$formatfile") or die "Can't open $formatfile: $!";
   @formatlines = <FORMATFILE>;
   close(FORMATFILE);

   my $format = join('',@formatlines);

   # open html-page read/write
   open(HTMLFILE, "+<$htmlfile") or die "Can't open $htmlfile: $!";

   # get excl. lock
   flock(HTMLFILE,2);
   @htmllines = <HTMLFILE>;  # sluuuuurp

   # seek to position 0
   seek(HTMLFILE,0,0);

   my $insert = 1;
   foreach $line ( @htmllines ) {
     print HTMLFILE $line;
	 if ( $insert && $line =~ m/^<!--insert_here-->$/ ) {
	   print HTMLFILE eval "return qq{$format}";
	   $insert = 0;
	 }
   }
   flock(HTMLFILE,8);
   close(HTMLFILE);
}

# redirect...
print $query->redirect(-uri => $uri);

exit 0;
###########
### END ###
###########

#-----
my $host = $query->remote_host || 'unknown';
my $user_agent  = $query->user_agent || 'unknown';
my $user_name   = $query->user_name || 'unknown';

if ($remote_host =~ /^\d+\.\d+\.\d+\.\d+$/) {
  # resolve address (apache defaults to NOT resolve the address...)
  $hostname = gethostbyaddr(inet_aton($remote_host),AF_INET);
  $hostname = "[$remote_host]" if ( !defined($hostname) );
} else {
  $hostname = $remote_host;
}
