<?php

# line prefix for code comments, for lines added into uploaded files
$commentprefix = "--";


#$names = array('Testy');

function printhead() {
  print <<<END
<!doctype HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Staecker MA 151 code submit page</title>
<link rel=stylesheet type="text/css" href="../../pcs.css" title="Staecker's Styles">
<style type="text/css">
  span.error {
    color: #FF0000;
    font-weight: bold;
  }
</style>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="keywords" lang="en" content="staecker,christopher staecker,nielsen theory,nielsen fixed point theory,class wiki">
</head>
<body bgcolor="#FFFFFF">
END;
}

#submission page
# parameters for default input in the form
# $errors is an associative array of booleans, possibilities are:
#  $errors['noname'] - no name selected
#  $errors['nosubmission'] - no file or pasted text to submit
#  $errors['twosubmissions'] - both file and pasted text

function printform($text, $name, $errors) { 
   $s = $_SERVER['PHP_SELF'];


   print "<h1>Staecker MA 151 code submit page</h1>\n";

   if ($errors) {
     print "<p><span class=error>Something's wrong with your submission. Fix it up and try again.</span></p>";
   }

   $time = date("G:i:s M j Y");


   print <<<END
<p>Here's where you can submit your completed code assignments. You can either paste your code text into the box, or upload your code file directly.</p>

<p>When you loaded this page, the date and time was: $time.</p>

<form name="code" action="$s" method="post" enctype="multipart/form-data">

<p>Your name:
<select name="name">

END;
#'


   # First bogus option
   print "<option value='' ";
   if (! $name) {
      print "selected";
   }
   print ">[Choose a name!]</option>\n";

   # Actual names come from file "names.txt"
   # each line has a name, and that's it'
   $names = explode("\n", rtrim(file_get_contents("names.txt")));   

   # Actual names
   foreach ($names as $n) {
      print "<option value='$n' ";
      if ($name == $n) {
         print "selected";
      }
      print ">$n</option>";
   }

   print "</select>\n";

   if ($errors['noname']) {
      print "<span class=error>Choose your name!</span>";
   }


   print <<<END
</p>

<p>Upload a file: <input type="file" name="file" size="40"></p>

<p>OR, paste your code below:<br>

END;

   print "<textarea name='text' rows=24 cols=80>$text</textarea></p>\n";

   if ($errors['nosubmission']) {
      print "<p><span class=error>Either choose a file to upload or paste in your code.</span></p>";
   } else if ($errors['twosubmissions']) {
      print "<p><span class=error>Either choose a file upload or paste in your code, but not both.\n</span></p>";
   }

   print <<<END

<p>Check over everything, and click here:
<input type="submit" value="submit">
</p>
<p>Your submission is not complete until you see the broccoli.</p>

<p>Something wrong? Click here to blank out the form: 
<input type="reset" onclick="this.form.elements['text'].value=''; this.form.reset()">
</p>
</form>


END;
}

function printsubmitted($submiterrors) {
  $time = date("G:i:s M j Y");
  $s = $_SERVER['PHP_SELF'];

  if ($submiterrors) {
    print <<<END
<h1>Submission failed!</h1>
<p>You submission failed because something on the server is messed up. This is probably not your fault. If you see this error while you're trying to submit something, please email the submission to the professor instead. </p>
END;
#'

    print "<p>Please tell the professor that an error occured, and paste in the output:<br><pre>";
    $e = print_r($submiterrors, true);
    print htmlspecialchars($e);
    print '</pre>';

    print "<p>Sorry for the inconvenience!</p>";

  } else {
    print <<<END
<h1>Submission successful</h1>
<p><img src="broccoli.jpg" width=400 height=267 alt="Submission successful broccoli"></p>
<p><span class=small>Submission successful broccoli image licenced <a href="http://creativecommons.org/licenses/by-nc/3.0/">CC BY-NC</a> by <a href="http://commons.wikimedia.org/wiki/User:Fir0002">fir0002/Flagstaffotos</a> at <a href="http://commons.wikimedia.org/wiki/File:Broccoli_bunches.jpg">Wikimedia Commons</a></span></p>
<p>Your file was successfully uploaded at $time.<br>
There is no way to retrieve or edit your submission. If you decide to make changes, you can re-upload your file at any time, and the professor will grade the latest one received at the due time.</p>
<p>If you're worried about which version the professor should grade, just send an email explaining everything.</p>
<p>Thanks!</p>
<p>You can close your browser window now, or visit another page.</p>

END;
#'
  }
}

#print_r($_FILES);
#print_r($errors);
#print_r($_POST);

$file = $_FILES['file']['name'];
$text = $_POST['text'];
$name = $_POST['name'];

printhead();


if (! $_POST) {
   printform('','',array());
} else {

   # validate the form.

   # $errors is an associative array of booleans, possibilities are:
   #  $errors['noname'] - no name selected
   #  $errors['nosubmission'] - no file or pasted text to submit
   #  $errors['twosubmissions'] - both file and pasted text

   $errors = array();

   if (! $name) {
      $errors['noname'] = true;
   }

   if ($text && $file) {
      $errors['twosubmissions'] = true;
   }

   if ((! $text) && (! $file)) {
      $errors['nosubmission'] = true;
   }

   # if errors, print the form again
   if ($errors) {
      printform($text, $name, $errors);
   } else {
     # valid submission

     # errors for the submission. These could be:
     #  'filemoveerror', tmp upload file not copied to final destination
     #  'otherupload', some other error from uploaded file, value from $_FILES['file']['error']
     #  'texterror', some error from pasted text

     $submiterrors = array();

     # prepare destination filename and path
     # path is: uploads/
     # filename is the username and timestamp, e.g. staecker20130812231254.hs
     $filepath = "uploads/";
     $filename = $name . date("YmdHis") . ".hs";

     # pasted code
     if ($text) {
       # returns # of bytes written, or FALSE if failed
       $b = file_put_contents($filepath . $filename, $text);
       if (! $b) {
	 $submiterrors['texterror'] = error_get_last();
       }
     }

     # uploaded source file
     if ($_FILES['file']['name']) {
       //Filename as it was on the client computer.
       $oldfilename  = $_FILES['file']['name'];
       //filetype 
       $filetype  = $_FILES['file']['type'];
       //error codes from the upload.
       $fileerror = $_FILES['file']['error'];
       //tempname as it is given by the host when uploaded.
       $filetemp  = $_FILES['file']['tmp_name'];


       if(is_uploaded_file($filetemp)) {
	 if(move_uploaded_file($filetemp, $filepath . $filename)) {
#
	 }
	 else {
	   $submiterrors['filemoveerror'] = true;
         }
       }
       else {
#	 print_r($_FILES);
	 $submiterrors['otherupload'] = $_FILES['file']['error'];
       }

     }

     # annotate file
     # at the head of the file goes text in Haskell comments
     # with time of submission, method of submission (paste or upload)
     # IP address of submitter, original file name if uploaded
     if (! $submiterrors) {
       global $commentprefix;
       $cp = $commentprefix;

       $time = date("G:i:s M j Y");
       $s = "$cp Submitted by $name at $time\n";

       if ($text) {
	 $s = $s . "$cp submitted as pasted text\n";
       } else if ($_FILES['file']['name']) {
	 $s = $s . "$cp submitted as file upload, filename $oldfilename\n";
       }

       $s = $s . "$cp submitted from " . $_SERVER['REMOTE_ADDR'] . "\n";
       $s = $s . "\n--------------------------------\n\n";

       $old = file_get_contents($filepath . $filename);
       file_put_contents($filepath . $filename, $s . $old);

       unlink($filepath . $name . "latest.hs");
       symlink($filename, $filepath . $name . "latest.hs");
     }

     # dump out the results page
     printsubmitted($submiterrors);
	 
   }

}
print "</body></html>";
?>