#! /usr/local/bin/perl
#
# Script for users to upload their links.
# + returns a link addition form if called with no parameter.
# + adds the suggested link if called w/ ?section=add (POST method used).
#
#
#############################################################################
#  
#   GLOBAL VARIABLES
#
#############################################################################

$Directory="/cgi-bin/Turkiye";
$images="/Turkiye/images";  # unused here
$WhatsNew="whatsnew.links";
$Uploads="upload.links";
$MainData="Main.Links";    # unused here
$addScript="$Directory/add.pl";
$mainScript=$addScript;
$currentDir="/";
$password="january";

$title="<header><title>A Passage To Turkiye</title></header>\n";
$signature="<hr><address><a href=http://www.cis.syr.edu/~balsoy>Ozgur Balsoy</a></address>\n";

$version="v0.03";
# 0.03 - Mirror input field added.
# 0.02 - Description field added.
# 0.01 - Starting version.
#############################################################################
#  
#   MAIN FUNCTION
#
#############################################################################

&ReadEntry;
&printResults;

#############################################################################
#  
#   SUBROUTINES
#
#############################################################################


sub ReadEntry {
   &Parse(&Read);     # Read arguments passed from fill-out form
   return 1;
}


sub printResults {

&printHeader;
$currentDir=$ENV{'PATH_INFO'};# if (defined(${'dir'}));
$longDir = $currentDir;
$currentDir =~ s/_/ /g;
$currentDir = "/" if ($currentDir eq "");

if ($in eq "") { &intro; }

elsif ($in{"section"} eq "add") {
      &addLink;
}

elsif ($in{"section"} eq "dirlist") {
      &dirList;
}

elsif ($in{"section"} eq "server") {
      if ($in{"code"} eq "") { print "Error Something's wrong!\n" }
      else { &receiveSlides; }
}

elsif ($in{"section"} eq "client") {
      if ($in{"code"} eq "") { print "Error Something's wrong!\n"; }
      else { &sendSlides; }
}

#  &Parse(&Read);
#  print join(" - ", %in);
#  return 1;

&printFooter;

}

##############################################################################
#
#  Get information from fill-out form.
#
##############################################################################


# Returns the magic line which tells WWW that this is an HTML document
sub printHeader {
  print "Content-type: text/html\n\n";
  print "<html> $title<body>";
}

sub printFooter {
  print "$signature </body></html>\n";
}

# reads the arguments passed from the form
sub Read {
    local ($i, $loc, $key, $val);

    if ($ENV{'REQUEST_METHOD'} eq "GET") {                      # Read in text
       $in = $ENV{'QUERY_STRING'};
    } elsif ($ENV{'REQUEST_METHOD'} eq "POST") {
      for ($i = 0; $i < $ENV{'CONTENT_LENGTH'}; $i++) {
        $in .=getc;
      }
    }
    return $in;
}

sub Parse {
    $in = $_[0];
    local ($i, $loc, $key, $val);

    @in = split(/&/,$in);

    foreach $i (0 .. $#in) {
      $in[$i] =~ s/\+/ /g;                          # Convert pluses to spaces
      $in[$i] =~ s/%(..)/pack("c",hex($1))/ge;
                                # Convert %XX from hex numbers to alphanumeric
      $loc = index($in[$i], "=");                  # Split onto key and value.
      $key = substr($in[$i],0,$loc);
      $val = substr($in[$i],$loc+1);
#      $in{$key} .= '\0' if (defined($in{$key})); # \0 is the multiple separator
#      $in{$key} .= $val;
      $in{$key} = $val;
   }
   return 1; 
}


##############################################################################
#
#  Sub programs
#
##############################################################################

# Introduction
# Send a fill out form to find out whether to teach or browse.
sub intro {

$currentDir=$ENV{'PATH_INFO'};
print "<h1>A Passage To Turkiye</h1>\n";
print "<h2>Link addition page $version</h2><hr>";

print "<form method=post action=$addScript>\n";
print "<input type=hidden name=section value=add>\n";
print "<input type=hidden name=placetoadd value=$currentDir>\n";
print "<b>Title of the page(s):</b><br>";
print "<input name=title size=50><br>\n"; 
print "<b>URL to the title page:</b><br>";
print "<input name=url size=50 value=\"http://\"><br>\n";
print "<b>Authors' name:</b><br>";
print "<input name=author size=50><br>\n";
print "<b>Contact address:</b><br>";
print "<input name=email size=50><br>\n\n";
print "<b>Brief Description:</b><br>";
print "<input name=desc size=50><br>\n\n";
print "<b>Mirror Site:</b><br>";
print "<input name=mirror size=50><br>\n\n";

print "<b>Added by</b><br>";
print "<input name=addedby size=50 value=\"Ozgur Balsoy\"><br>\n"; 
print "<b>Add the link into the directory</b><br>";
print "<input name=addto size=50 value=\"$longDir\"><br>\n"; 

print "<input TYPE =submit VALUE = Add>";
print "<input type =reset  value = Clear>";
print "</form>\n";

}

sub addLink {
    local($addto);
    $lockfile="$Uploads.lock";
    while (-e $lockfile) {};
    unless (symlink ($ENV{'REMOTE_ADDR'}, $lockfile)) {
        &errorUploads;
	return;
    };

$date=`date`;
chop($date);
open(UPLOAD, ">>$Uploads");
$addto = $in{'addto'};
$addto =~ s/_/ /g;
print UPLOAD "$addto:|:$in{'title'}:|:$in{'url'}:|:$in{'author'}:|:";
print UPLOAD "$in{'email'}:|:$date:|:$ENV{'REMOTE_HOST'}:|:$ENV{'REMOTE_ADDR'}:|:";
print UPLOAD "$in{'addedby'}:|:$in{'desc'}:|:$in{'mirror'}\n";
close(UPLOAD);
unlink($lockfile);

print "Link added: <br>".join(" - ",%in);

}

sub errorUploads {

print "<h1>Error</h1>Could not add your link. Please go back, and try again!";

}

sub errorRepeatTeach {

print "<h1>Error!</h1>\n";
print "Please enter at least the lecture code.\n<hr>";
&beginTeach;

}

sub dirList {
local (@protocol, @fields);

if ($in{'password'} eq $password) {
   print "<h2>Uploaded Links</h2><hr><dl>\n";
   print "<table><tr><th>Directory</th><th>Page</th><th>Author</th>";
   print "<th>Date</th><th>Host</th><th>Added by</th></tr>\n";

   open(UPLOAD, "$Uploads");
   while (<UPLOAD>) {
       chop;
       @fields=split(/:\|:/);
       print "<tr><td>$fields[0]</td>";
       print "<td><a href=\"$fields[2]\">$fields[1]</a></td>";
       print "<td><a href=";
       @protocol=split(/:/, $fields[4]);
       if ($protocol[0] ne "http") { 
          print "mailto:";
       }
       print "$fields[4]>$fields[3]</a></td><td>$fields[5]</td>";
       print "<td>$fields[6]</td><td>$fields[8]</td></tr>\n";
   }
   print "</table>";
   close (UPLOAD);
} else {
   print "<h1>You are not authorized to see this list!</h1>";
}
}

sub prepareSession {

$session = $sessionDirectory."/".$in{'code'};
if (-r $sessionDirectory && -w $sessionDirectory) {
   if (-r $session && -w $session) {
       print "<h1>Error</h1><h2>This session already been taught!</h2>\n"; }
   elsif (mkdir($session, 0755)) {
       $date=`date`;
       open (INFO, "> $session/$sessionInfoFile");
       print INFO "code=$in{'code'}&title=$in{'title'}&instructor=$in{'instructor'}&";
       print INFO "host=$ENV{'REMOTE_HOST'}&addr=$ENV{'REMOTE_ADDR'}&";
       print INFO "server=$ENV{'SERVER_NAME'}&date=$date";
       close(INFO);
       return 1;
   } else { print "<h1>Error</h1><h2>Can't create a session directory!</h2>\n"; }
} elsif (mkdir($sessionDirectory, 0755)) {
       return &prepareSession;   
} else { print "<h1>Error</h1><h2>Can't create the session directory!</h2>\n"; }
return 0;
}

sub checkSession {

$session = $_[0];
if (-r $sessionDirectory && -w $sessionDirectory) {
   if (-r $session && -w $session) { return 1; }
}
return 0;
} # checkSession

sub receiveSlides {

$session = $sessionDirectory."/".$in{'code'};
if (&checkSession($session)) {
   if (open(DATA, "> $session/$sessionDataFile")) {
      print DATA $in{'information'};
      close(DATA);
      if (open(LAST, "> $session/$sessionLastConn")) {
         print LAST `date`;
         close(LAST);
      }
      print "OK";
   } else { print "not-OK"; }
} else { print "not-OK"; }
} # receiveSlides

sub sendSlides {

$session = $sessionDirectory."/".$in{'code'};
if (&checkSession($session)) {
   if (open(DATA, "$session/$sessionDataFile")) {
      while ($line=<DATA>) {
        chop($line);
	print "$line\n";
      }
      close(DATA);
   } else { print "Error not-OK"; }
} else { print "Error not-OK"; }
} # sendSlides

sub beginBrowse {

print "<h2>Please enter your name, choose a lecture to browse,\n";
print " and hit the submit button.</h2><hr>\n";
print "<form method=post action=$mainScript>";
print "<input type=hidden name=section value=browse>\n";
print "Your name: <input name=name size=20>\n";
print "<p><table border=1 cellspacing=0 cellpadding=5>";
print "<th></th><th>Course</th><th>Course Title</th><th>Instructor</th>";
print "<th>Instructor's Machine</th><th>Beginning Date</th>";
print "<th>Last Connection</th></tr>\n";

if (opendir(LECTS, $sessionDirectory)) {
   foreach $session (sort readdir(LECTS)) {
      if (($session eq ".") || ($session eq "..")) { next; }
      if (open(INFO, "$sessionDirectory/$session/$sessionInfoFile" )) {
         $data=<INFO>;
	 chop($data);
	 close(INFO);
	 &Parse($data);
	 print "<tr><td><input type=radio name=code value=$in{'code'}></td>\n";
	 print "<td>$session</td><td>$in{'title'}</td><td>$in{'instructor'}</td>\n";
	 if (($host=$in{'host'}) eq "") { $host=$in{'addr'}; }
	 print "<td>$host</td><td>$in{'date'}</td>";
	 if (open(LAST, "$sessionDirectory/$session/$sessionLastConn")) {
            $date=<LAST>;
	    chop($date);
	    close(LAST);
	    print "<td>$date</td>";
	 } else { print "<td>No info.</td>"; }
	 print "</tr>\n\n";
      } else { print "<tr><td colspan=6>Can't reach $session information.</td></tr>\n"; }
  }
} else { print "<tr><td colspan=6>Can't reach the sessions.</td></tr>\n"; }

print "</table><hr>";
print "<input TYPE =submit VALUE = Submit>";
print "</form>";

}

sub errorRepeatBrowse {

print "<h1>Error!</h1>\n";
print "Please choose one of the course(s).\n<hr>";
&beginBrowse;

}











