#!/usr/bin/perl

# Script by Douglas Christensen, Jr
# With translation table by Loren Peace
# Code additions by Tim Herr (tim@gaminginfinity.com)
# and tons and tons of help from
# all them cool guys (and girls) at
# the console browsers Yahoo! group.
#
# VMU Uploading is now set free!


##########
# Version History:
#
# TODO: - Nothing?
#
# 1.03: 7-27-01 - Modification by Tim Herr
#               - Fixed CHMOD for new directory creation
#
# 1.02: 7-26-01 - Modifications by Tim Herr
#               - Returns error if a VMU file has not been selected in the HTML form before hitting Upload.
#
# 1.01: 7-25-01 - Modifications by Tim Herr
#		- Changed upload directory to a variable to allow easier customization
#               - Script creates upload directory if it does not already exist
#		- Filenames converted to uppercase, and all non-alphanumeric characters are purged
#               - Returns error if filename has already been used, or is not one to eight characters long
#               - Cleaned up the look of the output pages
#               - Version history added
#
# 1.00: 7-22-01 - Author: Douglas Christensen, Jr.
#               - Initial public release.
##########


## Path to upload directory - No trailing slash. ##
my $updir = "./uploads";

## Grab needed libraries ##
require "table.lib";
require "cgi-lib.pl";
use MIME::Base64;
$cgi_lib'maxdata = 110000; 

## Get Form Data (part of cgi-lib) ##
$ret = &ReadParse;

## Error Checking - Tim Herr (tim@gaminginfinity.com) - 7-25-01 ##

$saveas = uc($in{'name'});  # Convert filename to upper case
$saveas =~ s/\W//g;         # Remove all non-alphanumeric characters from the entered filename

if (!(-e "$updir"))         # Create the upload directory if it doesn't already exist
{
   mkdir($updir,0755);
}

my $validname = 0;
my $doesnotexist = 0;
my $fileselected = 0;

if (length($saveas) > 0 && length($saveas) < 9)    # Make sure filename is 1 - 8 characters long.
{
   $validname = 1;
}

if (!(-e "$updir/$saveas.VMS"))                    # Make sure file doesn't already exist.
{
   $doesnotexist = 1;
}

if ($ENV{'CONTENT_LENGTH'} > 500)                  # If the content being sent to the script is less than 500 bytes, no file was sent.
{
   $fileselected = 1;
}

if ($validname == 1 && $doesnotexist == 1 && $fileselected == 1)  # Proceed only if filename is valid and does not already exist, and a file was actually uploaded
{
   ## Split the Data into 3 sections ##
   ## Section 1 is header info ##
   ## Section 2 is blank ##
   ## Section 3 is the save/game data ##
   @vmudata = split (/\n/, $in{'upfile'}, 3);

   $header = @vmudata[0];
   @content = split (//, @vmudata[2]);

   ## Get the Translation table ##
   &gettable;

   ## Parse the VMU Header ##
   @qd = split (/&/, $header);
   foreach $qd (@qd)
   {
    ($name, $value) = split (/=/, $qd);
    $vmuhead{$name} = $value;
   }

   ## Get the date from the header ##
   if ($vmuhead{'tm'} =~ /(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d)/)
   {
    $year = $1;
    $month = $2;
    $date = $3;
    $hr = $4;
    $min = $5;
    $sec = $6;
    $day = $7;
    @days = ("Sun","Mon","Tue","Wed","Thr","Fri","Sat");
    $day2 = @days[$day];
   }

   ## Base shift it using transation table ##
   for ($i=0; @content[$i] ne ""; $i++)
   {
    @newcontent[$i] = $trantable{@content[$i]} if (@content[$i] !~ /[\n\r]/);
    @newcontent[$i] = @content[$i] if (@content[$i] =~ /[\n\r]/);
   }

   ## Decode it from Base64 to ASCII          ##
   ## This is what is saved to the .VMS file! ##
   $decoded = decode_base64(join('',@newcontent));

   open(DA, ">$updir/$saveas.VMS");
   print DA $decoded;
   close(DA);

   $originalname = $vmuhead{'filename'};
   $filesize = $vmuhead{'fs'};

   @saveas = split (//, $saveas);
   @originalname = split (//, $originalname);

   for ($i=0; @saveas[$i]; $i++)
   {
    @saveas[$i] = ord(@saveas[$i]);
    @saveas[$i] = 0 if (@saveas[$i] eq "");
   }

   for ($i=0; $i < 12; $i++)
   { @originalname[$i] = ord(@originalname[$i]); }
   $newfilesize = $filesize / 256;
   @filesize = (0,$newfilesize,0,0);

   @set01 = (65,68,68,64,80,108,97,110,101,116,119,101,98,32,66,114,111,119,115,101,114,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,80,108,97,110,101,116,119,101,98,44,32,73,110,99,46,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,206,7,12,25,12,0,0,5,0,0,1,0);
   @set02 = (0,0,0,0);

   $originalname2 = join('', @originalname);

   for ($i=0; $i < 80; $i++)
   { @set01[$i] = chr(@set01[$i]); }
   for ($i=0; $i < 8; $i++)
   { @saveas[$i] = chr(@saveas[$i]); }
   for ($i=0; $i < 12; $i++)
   { @originalname[$i] = chr(@originalname[$i]); }
   for ($i=0; $i < 4; $i++)
   { @set02[$i] = chr(@set02[$i]); }
   for ($i=0; $i < 4; $i++)
   { @filesize[$i] = chr(@filesize[$i]); }

   open(DA, ">$updir/$saveas.vmi");
   print DA @set01;
   print DA @saveas;
   print DA @originalname;
   print DA @set02;
   print DA @filesize;
   close(DA);

   print "Content-type: text/html\n\n";
   print "<html><body>";
   print "File successfully uploaded to: <a href=$updir/$saveas.vmi>$updir/$saveas.vmi</a><br><br>";
   print "<a href=javascript\:history.go(-1)>Go Back</a>\n";
   print "</html></body>";
}

## Display errors if filename did not pass error checks.
else
{
   print "Content-type: text/html\n\n";
   print "<html><body>";

   if ($validname == 0)
   {
      print "<i>Error: Invalid filename given.</i><br>\n";
      print "Filename must be one to eight characters long, and may only contain letters and numbers.  Please go back and enter a new name.<br><br>\n\n";
   }

   if ($doesnotexist == 0)
   {
      print "<i>Error: File already exists.</i><br>\n";
      print "The filename you have given is already in use.  Please go back and enter a different name.";
   }

   if ($fileselected == 0)
   {
      print "<i>Error: File not selected.</i><br>\n";
      print "Before clicking upload, you must first click Browse to select a VMU file to upload.  Please go back and select a file.<br><br>\n\n";
   }

   print "<a href=javascript:history.go(-1)>Go Back</a>\n";
   print "</html></body>";
}

0;
