!/usr/bin/perl
# Einfaches Script fuer File-Upload

use strict;
use CGI qw(:standard);

# Upload Dir, kein Slash am Ende!
my $updir = "/home/httpd/htdocs/upload";

# Referer (mit .htaccess geschuetztes Verzeichnis wo Formular liegt)
my $ref = "http://atlas.ee.fhm.edu/ups/upload.html";

my $data; # Lesepuffer
my %FORM = ();

##### BITTE BEACHTEN ######################################################
# Die Felder des Formulars
#   <form action="/cgi-bin/ups.pl" method="post" enctype="multipart/form-data">
#   Lokaler Dateiname:
#   <input type="file" name="datei" size=40><BR>
#   Dateiname auf dem Server:
#   <input type="Submit" value="Upload">
#   <input type="reset" value="L&ouml;schen">
#   </form>

# Dokumenten-Kopf
print "Content-type: text/html\n\n";

print "<Html><Head><Title>FIle-Upload</Title></Head>";
print "<Body>";

if ($ENV{'HTTP_REFERER'} ne $ref)
  {
  print "<H1>Fehler!</H1>\n";
  print "Es wurde versucht, ohne Erlaubnis hochzuladen! Abbruch...";
#  print $ENV{'HTTP_REFERER'};
  print "</BODY></HTML>\n";
  exit;
  }

&parse_form;
my $datei = FORM{'datei'};
my $dateiname = "upload" .

if (! $datei or ! $dateiname)
  {
  print "<H1>Fehler!</H1>\n";
  print "Datei oder Dateiname fehlt! Abbruch...";
  print "</BODY></HTML>\n";
  exit;
  }

if (! open WF, ">$updir/$dateiname")
  {
  print "<H1>Fehler!</H1>\n";
  print "Datei kann nicht geschrieben werden! Abbruch...";
  print "</BODY></HTML>\n";
  exit;
  }

binmode $datei;
binmode WF;
while(read $datei,$data,1024)
  { print WF $data; }
close WF;


print "<H1>Upload O. K.</H1>\n";
print "Die Datei wurde hochgeladen.<BR>\n";
print "Remote Path and Filename: $updir/$dateiname\n";

print "</BODY></HTML>\n";
exit;

sub parse_form 
    {
    my ($buffer, @pairs, $pair, $name, $value);
    # Read in text
    if ($ENV{'REQUEST_METHOD'} eq "POST")
      {
      read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
      }
    else
      {
      $buffer = $ENV{'QUERY_STRING'};
      }
    @pairs = split(/&/, $buffer);
    foreach $pair (@pairs)
      {
      ($name, $value) = split(/=/, $pair);
      $value =~ tr/+/ /;
      $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
      $FORM{$name} = $value;
      }
    }

sub timestamp
  {
  my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
  $mon = $mon + 1;
  return ("$year"."$mon"."$mday"."-"."$hour"."$min"."$sec");
  }