#!/usr/bin/perl

#DB
#-------------------
#Title
#Algorithms(*)
#Applications(*)
#Platforms(*)
#Development Tools(*)
#Special input requirements
#Special output requirements
#Abstract
#Authors
#outside viewing?
#URL
#Snapshot
#Password
#Your email address
#Record number
#
#UI
#-------------------
#Add to database
#Edit records
#View database
#        Flat list
#        Simple search
#        Graphical view
#

############################################################
###############  Database format description ###############
############################################################
# The database is a simple flat file, with each record
# seperated by a ^X charachter (\030), and each field
# delimited by a ^Y charachter (\027).
############################################################

############################################################
##################  Configuration info  ####################
############################################################
# Where the database is
$db = "/home/httpd/nmmdir/nmmdb";

# The database descriptions for for the type fields
$dbdesc = "/home/httpd/nmmdir/nmmdbdesc";
############################################################
############################################################

############################################################
####################  Primary dispatch #####################
############################################################
print "Content-type: text/html\n\n";

# First figure out what we are doing
$cmd = $ENV{'PATH_INFO'};
$this=  $ENV{'SCRIPT_NAME'};

if($ENV{'REQUEST_METHOD'} eq "POST"){
    $post = 1;
    read(STDIN, $q, $ENV{'CONTENT_LENGTH'});
}
else{
    $post = 0;
    $q = $ENV{'QUERY_STRING'};
}

%form = &parseform($q);

# Now do it, whatever it is
if($cmd eq ""){
    &displayMainPage;
}
elsif($cmd eq "/add"){
    &readDBDesc;
    if($post){
	&addPage($form{'recnum'});
	&displayViewPage;
    }
    else{
	$action = "add";
        &displayAddPage;
    }
}
elsif($cmd eq "/edit"){
    if($post){
	&fetchRecordNumber($form{'recnum'});
	if(($r_user eq $form{'olduser'}) && ($r_password eq $form{'oldpw'})){
	    &removeRecordNumber($form{'recnum'});
	    &addPage($form{'recnum'});
	    &displayViewPage;
	}
	else{
	    print "Authorization failure $r_password/$form{'oldpw'}\n";
	}
    }
    else{
        if($form{'user'}){
	    &fetchRecord($form{'user'});
	    if($r_password eq $form{'pw'}){
		$edit_extra = <<EOEE;
<input type=hidden name=oldpw value=$r_password>	       
<input type=hidden name=olduser value=$r_user>	       
<input type=hidden name=recnum value=$r_rec>	       
EOEE
    $action = "edit";
    &readDBDesc;
    &displayAddPage;
	    }
	    else{
		print "Wrong password, try again\n";
	    }
        }
        else{
            &displayEditPage;
        }
    }
}
elsif($cmd eq "/view"){
    if($post){

    }
    else{
        &displayViewPage;
    }
}
else{
    &displayMainPage;
}
############################################################


############################################################
############################################################
############################################################

############################################################
##################  Page display routines ##################
############################################################
sub displayMainPage {
    print <<EOMainPage;
You can:<br>
<a href="$this/add"><strong>Submit</strong> your project to the database</a><br>
<a href="$this/edit">Edit your project entry</a><br>
<a href="$this/view">View projects in the database</a>
EOMainPage
}
############################################################
sub displayAddPage {

    $applicationselect = "<select name=applications multiple size=3>";
    $ct=-1;    
    foreach $a (@application){
	$ct++;
	next unless $a;
	$sel = "";
	$sel = "SELECTED" if($r_applications =~ /\b$ct\b/);
        $applicationselect .= "<option value=$ct $sel>$a\n";
    }
    $applicationselect .= "</select><br>\n";

    $algorithmselect = "<select name=algorithms multiple size=3>";
    $ct=-1;
    foreach $a (@algorithm){
        $ct++;
	next unless $a;
	$sel = "";
	$sel = "SELECTED" if($r_algorithms =~ /\b$ct\b/);
        $algorithmselect .= "<option value=$ct $sel>$a\n";
    }
    $algorithmselect .= "</select><br>\n";

    $platformselect = "<select name=platforms multiple size=3>";
    $ct=-1;
    foreach $a (@platform){
        $ct++;
	next unless $a;
	$sel = "";
	$sel = "SELECTED" if($r_platforms =~ /\b$ct\b/);
        $platformselect .= "<option value=$ct $sel>$a\n";
    }
    $platformselect .= "</select><br>\n";

    $toolselect = "<select name=tools multiple size=3>";
    $ct=-1;
    foreach $a (@tool){
        $ct++;
	next unless $a;
	$sel = "";
	$sel = "SELECTED" if($r_tools =~ /\b$ct\b/);
        $toolselect .= "<option value=$ct $sel>$a\n";
    }
    $toolselect .= "</select><br>\n";

    $checked = "";
    $checked = "CHECKED" if ($r_outside eq "no");
    print <<EOAddPage;
<form method=POST action=$action>
<table width=80% align=center>
<tr bgcolor=white>
<td colspan=2 align=center><h1>Nature of Mathematical Modeling Database<br>Add an Entry</h1></td>
</tr>
<tr>
<td colspan=1 width=25% align=right>Project Title:</td><td colspan=1 width=75%><input name=title size=40 value="$r_title"></td></tr>
<tr><td colspan=2 bgcolor=black><font color=white size=+1>Algorithms</font></td></tr>
<tr>
<td valign=top>Algorithms used by your project:</td>
<td>Add currently unlisted algorithm:</td>
</tr>
<tr>
<td>
$algorithmselect
<td><input name=newalgorithm size=40></td></tr>

<tr><td colspan=2 bgcolor=black><font color=white size=+1>Applications</font></td></tr>
<tr><td>Intended Applications:</td>
<td>Add currently unlisted application:</td>
</tr>
<tr>
<td>
$applicationselect
</td>
<td><input size=40 name=newapplication></td>

<tr><td colspan=2 bgcolor=black><font color=white size=+1>Platforms</font></td></tr>
<tr><td>Target Platforms:</td>
<td>Add currently unlisted platform:</td>
</tr>
<tr>
<td>
$platformselect
</td>
<td><input size=40 name=newplatform></td>

<tr><td colspan=2 bgcolor=black><font color=white size=+1>Development Tools</font></td></tr>
<tr><td>Development Tools used:</td>
<td>Add currently unlisted development tool:</td>
</tr>
<tr>
<td>
$toolselect
</td>
<td><input size=40 name=newapplication></td>

<tr><td colspan=2 bgcolor=black><font color=white size=+1>Special Requirements</font></td></tr>

<tr>
<td>Special Input requirements?:</td><td><input name=specialinput size=40 value="$r_specialinput"></td>
</tr>
<tr>
<td>Special Output requirements?:</td><td><input name=specialoutput size=40 value="$r_specialoutput"></td>
<tr><td colspan=2 bgcolor=black><font color=white size=+1>Abstract</font></td></tr>
<tr><td colspan=2><textarea rows=6 cols=60 name=abstract>$r_abstract</textarea></td></tr>
<tr><td colspan=2 bgcolor=black><font color=white size=+1>Other Information</font></td></tr>
<tr>
<td>Full Name of Author(s):</td><td><input name=authors value="$r_authors"></td>
</tr>
<tr>
<td>Should people outside the Media Lab be able to see this project?</td>
<td><input name=outside type=checkbox $checked> (click for yes)</td>
</tr>
<tr>
<td>Project URL:</td><td><input name=url size=40 value="$r_url"></td>
</tr>
<tr>
<td>Please supply a URL for a 100x100 image that is representative of your project:</td>
<td><input name=snapshot size=40 value="$r_snapshot"></td>
</tr>
<tr>
<td>Password to use for later editing:</td><td><input name=password type=password value="$r_password">$edit_extra</td>
</tr>
<tr>
<td>Your email address:</td><td><input name=email value="$form{'user'}"></td>
</tr>
<tr>
<td></td><td align=right><input type=submit></td>
</table>
</form>

EOAddPage
}
############################################################
sub displayEditPage {
    print <<EOEditPage;
<h1>Edit a project</h1>
<form>
Email address: <input name=user><br>
Password: <input name=pw type=password><br>
<input type=submit>
</form>
EOEditPage
}
############################################################
sub displayViewPage {
    print <<EOViewPage;
Eventually, you will be able to browse this in sundry ways, but
right now, you get a very handsome list.
<p>
EOViewPage
    open(DB, $db);
    $slash = $/;
    $/ = "\030";
    print "<ul>\n";
    while(<DB>){
	@d = split("\027", $_);
	$title = $d[0];
	$author = $d[8];
	$outside = $d[9];
	$url = $d[10];
	$snapshot = "";
	$ssi="";
	$snapshot = $d[11];
	$ssi = "<img height=50 width=50 src=$snapshot>" if ($snapshot =~ /http/i);
	if(($outside == "yes") || ($ENV{'REMOTE_ADDR'} =~ /^18\.85\./)){
	    print "<li> $ssi".$author."'s <a href=$url>$title</a>\n";
	}
    }
    $/ = $slash;
    print "</ul>\n";
    print "<a href=$this>Take me back to the top page</a>\n";
}
############################################################
############################################################


############################################################
####################  Utility routines #####################
############################################################
# This subroutine takes a url-encoded string and 
# turns it into an associative array. 
sub parseform 
{ 
   local($formthing) = @_; 
   local( %lookup) = "";
   
   # Expects something like: 
   # foo=wow%21&bar=hello&baz=blah 
   
   # Split the string into each of the key-value pairs 
   (@fields) = split('&', $formthing); 
   
   # For each of these key-value pairs, decode the value 
   for $field (@fields) 
   { 
   
     # Split the key-value pair on the equal sign. 
     ($name, $value) = split('=', $field); 
   
     # Change all plus signs to spaces. This is an 
     # remnant of ISINDEX 
     $value =~ y/\+/ /; 
   
     # Decode the value & removes % escapes. 
     $value =~ s/%([\da-f]{1,2})/pack(c,hex($1))/eig; 
   
     # Create the appropriate entry in the 
     # associative array lookup 
     if(defined $lookup{$name}) 


     { 
       # If there are multiple values, separate 
       # them by newlines 
       $lookup{$name} .= "\n".$value; 
     } 
 else 
     { 
       $lookup{$name} = $value; 
     } 
   } 
   
   # Return the associative array 
   %lookup; 
} 
############################################################
sub readDBDesc {
    open(DBD, $dbdesc);
    while(<DBD>){
        ($type, $num, @text) = split;
        $text = join(" ", @text);
        $max{$type} = ($max{$type} > $num) ? $max{$type}:$num;

        if($type eq "algorithm"){
            $algorithm[$num] = $text;
        }
        elsif($type eq "application"){
            $application[$num] = $text;
        }
        elsif($type eq "platform"){
            $platform[$num] = $text;
        }
        elsif($type eq "tool"){
            $tool[$num] = $text;
        }
    }
    close(DBD);
}
############################################################
sub highestRecordNum {
    open(DB, $db);
    $max = 0;
    $slash = $/;
    $/ = "\030";
    while(<DB>){
	split("\027", $_);
	$num = $_[14];
	$max = $num > $max ? $num:$max;
    }
    $/ = $slash;
    $max;
}
############################################################
sub writeDBDesc {
    rename($dbdesc, $dbdesc.".old");
    open(DBD, ">$dbdesc");

    $ct = 0;
    foreach $a (@algorithm){
	print DBD "algorithm $ct $algorithm[$ct]\n";
	$ct++;
    }
    $ct = 0;
    foreach $a (@application){
	print DBD "application $ct $application[$ct]\n";
	$ct++;
    }
    $ct = 0;
    foreach $a (@platform){
	print DBD "platform $ct $platform[$ct]\n";
	$ct++;
    }
    $ct = 0;
    foreach $a (@tool){
	print DBD "tool $ct $tool[$ct]\n";
	$ct++;
    }
    close(DBD);
}

sub fetchRecord {
    $who = shift;
    open(DB, $db);
    $slash = $/;
    $/ = "\030";
    while(<DB>){
	split("\027", $_);
	if($who eq $_[13]){
	    $r_title = $_[0];
	    $r_algorithms = $_[1];
	    $r_applications = $_[2];
	    $r_platforms = $_[3];
	    $r_tools = $_[4];
	    $r_specialinput = $_[5];
	    $r_specialoutput = $_[6];
	    $r_abstract = $_[7];
	    $r_authors = $_[8];
	    $r_outside = $_[9];
	    $r_url = $_[10];
	    $r_snapshot = $_[11];
	    $r_password = $_[12];
	    $r_user = $_[13];
	    $r_rec = $_[14];
	}
    }
    close(DB);
    $/ = $slash;
}

sub fetchRecordNumber {
    $who = shift;
    open(DB, $db);
    $slash = $/;
    $/ = "\030";
    while(<DB>){
	split("\027", $_);
	if($who eq $_[14]){
	    $r_title = $_[0];
	    $r_algorithms = $_[1];
	    $r_applications = $_[2];
	    $r_platforms = $_[3];
	    $r_tools = $_[4];
	    $r_specialinput = $_[5];
	    $r_specialoutput = $_[6];
	    $r_abstract = $_[7];
	    $r_authors = $_[8];
	    $r_outside = $_[9];
	    $r_url = $_[10];
	    $r_snapshot = $_[11];
	    $r_password = $_[12];
	    $r_user = $_[13];
	    $r_rec = $_[14];
	}
    }
    close(DB);
    $/ = $slash;
}

sub removeRecordNumber {
    $who = shift;
    open(DB, $db);
    open(NDB, ">$db.$$");
    $slash = $/;
    $/ = "\030";
    while(<DB>){
	$record = $_;
	split("\027", $_);
	if($who != $_[14]){
	    print NDB $record;
	}
    }
    close(DB);
    close(NDB);
    rename("$db.$$", $db);
    $/ = $slash;
}

sub addPage{
    $rn = shift;

        $entry = $form{'title'};
        $entry .= "\027";
        $form{'algorithms'} =~ s/\n/ /g;
	$max = $#algorithm+1;
	if($form{'newalgorithm'}){
	    $form{'algorithms'} .= $max;
	}
        $entry .= $form{'algorithms'};
        $entry .= "\027";
        $form{'applications'} =~ s/\n/ /g;
	$max = $#application+1;
	if($form{'newapplication'}){
	    $form{'applications'} .= $max;
	}
        $entry .= $form{'applications'};
        $entry .= "\027";
        $form{'platforms'} =~ s/\n/ /g;
	$max = $#platform+1;
	if($form{'newplatform'}){
	    $form{'platforms'} .= $max;
	}
        $entry .= $form{'platforms'};
        $entry .= "\027";
        $form{'tools'} =~ s/\n/ /g;
	$max = $#tool+1;
	if($form{'newtool'}){
	    $form{'tools'} .= $max;
	}
        $entry .= $form{'tools'};
        $entry .= "\027";
        $entry .= $form{'specialinput'};
        $entry .= "\027";
        $entry .= $form{'specialoutput'};
        $entry .= "\027";
        $entry .= $form{'abstract'};
        $entry .= "\027";
        $entry .= $form{'authors'};
        $entry .= "\027";
        $outside = "no";
        $outside = "yes" if($form{'outside'});
        $entry .= $outside;
        $entry .= "\027";
        $entry .= $form{'url'};
        $entry .= "\027";
        $entry .= $form{'snapshot'};
        $entry .= "\027";
        $entry .= $form{'password'};
        $entry .= "\027";
        $entry .= $form{'email'};
        $entry .= "\027";
	
	if($form{'newalgorithm'}){
		$algorithm[$#algorithm+1] = $form{'newalgorithm'};
	}
	if($form{'newapplication'}){
		$application[$#application+1] = $form{'newapplication'};
	}
	if($form{'newplatform'}){
		$platform[$#platform+1] = $form{'newplatform'};
	}
	if($form{'newtool'}){
		$tool[$#tool+1] = $form{'newtool'};
	}

	&readDBDesc;
	&writeDBDesc;
    $h = $rn;
    $h = &highestRecordNum unless $rn;

    print "Writing record $h\n";
	$entry .= ($h+1);
        $entry .= "\030";
	

	open(DB, ">>$db");
	print DB $entry;
	close(DB);

}
############################################################



