#!/usr/bin/perl

use MIME::Base64;
use Compress::Zlib;
use CGI;
use Digest::MD5;

sub clean_exit {
   ($text = "@_") =~ s/\s+/ /mg;
    $text ||= "[an unexpected error occured]";
    print "Content-Type: text/html; charset=ISO-8859-1\n\n";
    print <<END_HTML;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-AU">
<head>
 <title>Galerie Belage ERROR!</title>
 <link rel="stylesheet" type="text/css" href="/styles/style.css" />
</head>
<body>
   <div id="container">
 <div id="logo">
 <img src="/images/plain_logo.jpg" width="787" height="251" title="Galerie BelAge" alt="" />
 </div>

<div id="navlist">
<ul>
<li><a href="/" class="active">Home</a></li>
</ul>
</div>

<div id="content">

<div style="position:absolute;left:200px;top:259px;display:block;border:0px;margin:0px;padding:0px;" id="error">

ERROR: $text

</div>

</div>

<div class="br"></div>
<div id="footer">
<p class="center">Copyright &copy; 2008 Galerie BelAge</p>
<br />
</div>
</div>
</body>
</html>

END_HTML

    exit 0;
}

$tempname = '/home/www/galeriebelage.com/uploads/picture.dummy';

if (eval {$query = new CGI}) {
    if (eval {$query->param ("eventupsubmit")}) {
        if (not eval {$md5 = new Digest::MD5}) {
            clean_exit ("Unable to use Digest::MD5!");
        } elsif ($ENV{'CONTENT_LENGTH'} > 4194302) {
            clean_exit ("File is too big!");
        } elsif (eval {$filename = $query->param ("eventup")}) {
            eval {$type = $query->uploadInfo ($filename)->{'Content-Type'}};
            if (open (RANDOM, '/dev/urandom')) {
                if (read (RANDOM, $salt, 40, 0)) {
                    close (RANDOM);
                   ($random = encode_base64 ($salt, "")) =~ s/\W+//mg;
                } else {
                    $random = rand ($$);
                }
            } else {
                $random = rand ($$);
            }
            $tempname = "/home/www/galeriebelage.com/uploads/$random";
            if (eval {$upload_filehandle = $query->upload ("eventup")}) {
                if (open (UPLOADFILE, ">$tempname")) {
                    flock (UPLOADFILE, 2);
                    binmode UPLOADFILE;
                    while (<$upload_filehandle>) {
                        print UPLOADFILE;
                        eval {$md5->add ($_)};
                    }
                    close (UPLOADFILE);
                    clean_exit ("MD5 signature is empty!") if (not eval {$checksum = $md5->hexdigest});
                } else {
                    clean_exit ("Cannot open file handle!");
                }
            } else {
                clean_exit ("Cannot get upload handle!");
            }
        } else {
            clean_exit ("You need to upload some!");
        }
    } else {
        clean_exit ("Wrong input!");
    }
} else {
     clean_exit ("CGI.pm is not loaded!");
}

exit 0;
