#!/usr/local/bin/perl
##########################################################################
# Script Name:    yeast2007-abstract  
# Authors:        Shuai Weng <shuai@genome.stanford.edu>
#                 Mike Cherry <cherry@genome.stanford.edu>
# Date:           October 2006
# 
# Description :   This script is based on Mike's original 
#                 yeast2007-late-abstract.html, yeast2007-absproof, and yeast2007-absfinal.
#
#                 It provides form for user to submit an abstract for
#                 Yeast Genetics & Molecular Biology meeting. It also 
#                 proofreads and processes the user's inputs.
#                
#                             
#########################################################################
use strict;
use CGI qw/:all/;

use lib '/share/wine/www-data_sgd/lib';
use Tools::TextUtil qw (delete_unwanted_char delete_html_tag);
use Tools::Report;
use lib '/share/bread/www-data_sgd/lib';
use Config::URL;
use Config::File;

my $configUrl = Config::URL->new;
my $configPath = Config::File->new;

my $dataDir = '/share/bread/www-data_go/data/princeton-goc/';

my $descConf = $dataDir.'conf/description.conf';
my $researchTopicConf = $dataDir.'conf/research_topic.conf';

my $subnumfile = $dataDir.'abstemp/abstract.number';
my $subnumlock = '/tmp/abstractnum.lock.$$';
my $abstractsfile = $dataDir.'abstemp/princeton-registration';
my $mailtmp = "/tmp/mailtmp.abs.$$";

my $maxAuthorNum = 16;
my $maxAbstractLength = 1500;
my $year = '2007';
my $ygmAbsInputEmail = 'princeton-registration';
my @errReportEmail = ('cherry');

my $lockfile = '/tmp/abstractwrite.lock.$$';

if (!param || param('reset')) {

    &displayForm;

}
elsif (!param('final')) {

    &proofReadInfo;

}
else {

    &processInfo;

}

exit;


#########################################################################
sub displayForm {
#########################################################################

    my ($header, $title, $style, $newstyle, $note, $description) 
	= &readDescriptionFile;

    print header;

    print start_html(-title=>"$header",-style=>{-src=>$style,-code=>$newstyle});

    print "<script src='http://db.yeastgenome.org/javascript/obfuscate.js'></script>";

    print center(h1(b($title)));

    print center($description), p, hr;

    print start_form;
    
    &printSection2;

    &printSection4;

    &printSection3;

    &printSubmit;

    &printFooter;

    print end_form, end_html;

}

#########################################################################
sub proofReadInfo {
#########################################################################

    my %info;

    &checkInfo(\%info);

    my $title = "Proof your registration";

    print header;

    print start_html(-title=>$title);

    print center(h1(b($title)));

    print start_form;

    ### print hidden variables

    print hidden(-name=>'final',
		 -value=>1);

    foreach my $key (sort (keys %info) ) {

	### force it to overwrite each parameter
	param("$key", $info{$key});

	print hidden(-name=>"$key",
		     -value=>$info{$key});

    }

    if ($info{"consortium-meeting"} eq "ON") {
	$info{"consortium-meeting"} = "Yes";
    } else {
	$info{"consortium-meeting"} = "No";
    }

    if ($info{"sab-meeting"} eq "ON") {
	$info{"sab-meeting"} = "Yes";
    } else {
	$info{"sab-meeting"} = "No";
    }

    if ($info{"refgenome-meeting"} eq "ON") {
	$info{"refgenome-meeting"} = "Yes";
    } else {
	$info{"refgenome-meeting"} = "No";
    }

    print "Once you press the Submit button the summary will be submitted.  A confirmation email will be sent to the address you stated.",p;

    print "Title = $info{\"presenter_title\"}",br;
    print "Firstname = $info{\"presenter_fname\"}",br;
    print "Lastname = $info{\"presenter_lname\"}",br;

    print "EMAIL = $info{\"presenter_email\"}",br;
    print "Department = $info{\"department\"}",br;
    print "Institution = $info{\"institution\"}",br;

    print "Consortium Meeting = $info{\"consortium-meeting\"}",br;
    print "SAB Meeting = $info{\"sab-meeting\"}",br;
    print "RefGenome Meeting = $info{\"refgenome-meeting\"}",p;

    print submit(-name=>'submit',
		 -value=>'Complete Registration');

    print end_form;

    print end_html;

}

#########################################################################
sub processInfo {
#########################################################################

    my %info;

    &checkInfo(\%info);

    my $title = "Registration completed for GOC Princeton Meetings";

    print header;

    print start_html(-title=>$title);

    print center(h1(b($title)));

    my $abstractNum = &readAbstractNumber;

    &sendResult($abstractNum);

    if ($info{"consortium-meeting"} eq "ON") {
	$info{"consortium-meeting"} = "Yes";
    } else {
	$info{"consortium-meeting"} = "No";
    }

    if ($info{"sab-meeting"} eq "ON") {
	$info{"sab-meeting"} = "Yes";
    } else {
	$info{"sab-meeting"} = "No";
    }

    if ($info{"refgenome-meeting"} eq "ON") {
	$info{"refgenome-meeting"} = "Yes";
    } else {
	$info{"refgenome-meeting"} = "No";
    }

    print hr, font({-color=>'red'},
	"Confirmation Number: ".tt($abstractNum)).p.
	    basefont({-size=>3},
	table({-width=>500, -border=>1, -cellpadding=>10},
	      Tr(th("Name"),td($info{"presenter_title"}." ".$info{"presenter_fname"}." ".$info{"presenter_lname"})),
	      Tr(th("EMAIL"),td($info{"presenter_email"})),
	      Tr(th("Department"),td($info{"department"})),
	      Tr(th("Institution"),td($info{"institution"})),
	      Tr(th("Consortium Meeting"),td($info{"consortium-meeting"})),
	      Tr(th("SAB Meeting"),td($info{"sab-meeting"})),
	      Tr(th("Ref Genome Meeting"),td($info{"refgenome-meeting"})))),br;

    print hr;
    
    print h3("Your registration is complete. A copy has also just been sent to your email address."),p;

    print end_html;

}

#########################################################################
sub printSection2 {
#########################################################################

    print center(h2("Participant Contact Information:"));

    print h3("Please enter your information to help us plan for the meeting. Many of the fields have maximum size limits, so you must fit your information within the space provided.");

    print table(
		Tr(td({-align=>'right'},
		      b("Title:")).
		   td(textfield(-name=>'presenter_title',
				-size=>40).
		      " ".i("e.g.,")." Mrs., Ms., Mr., Dr., Prof. (required)")).
		Tr(td({-align=>'right'},
		      b("First (Given) Name:")).
		   td(textfield(-name=>'presenter_fname',
				-size=>40).
		      " ".i("e.g.,")." Kaitlyn ".i("or")." J. Graeme ".
		      i("or")." Marcus R. (required)")).
		Tr(td({-align=>'right'},
		      b("Last (Family) Name(s):")).
		   td(textfield(-name=>'presenter_lname',
				-size=>40).
		      " ".i("e.g.,")." Smyth ".i("or").
		      " Van Buren (required)")).
		Tr(td({-align=>'right'},
		      b("Email:")).
		   td(textfield(-name=>'presenter_email',
				-size=>40)." (required)")).
		Tr(td({-align=>'right'},
		      b("Department:")).
		   td(textfield(-name=>'department',
				-size=>40)." (optional)")).
		Tr(td({-align=>'right'},
		      b("Institution:")).
		   td(textfield(-name=>'institution',
				-size=>40)." (required)"))),
		hr;
}

#########################################################################
sub printSection3 {
#########################################################################

    print center(h2("Lodging for the Meetings:")),p,
    b("A block of rooms has been reserved at the Nassau Inn:"),p,
    "Note that participants must make their own hotel reservations",
    p,
    "Contact the Inn at:",p,
    '<ul>',
    "Nassau Inn",br,
    "10 Palmer Sq E",br,
    "Princeton, NJ 08542",br,
    "+1 (609) 921-7500", br,
    '</ul>',p,
    "Group Name: Princeton University - Gene Ontology Consortium Group",br,
    "Group Reference Reservation Number: 9202",
    hr;
}

#########################################################################
sub printSection4 {
#########################################################################

    print center(h2("Meetings you will be attending")),
    p,
    checkbox(-name=>'consortium-meeting',
             -checked=>0,
             -value=>'ON',
             -label=>'Consortium Meeting, Sept 23rd & 24th'),
    br,
    checkbox(-name=>'sab-meeting',
             -checked=>0,
             -value=>'ON',
             -label=>'Scientific Advisory Board Meeting, Sept 25th'),
    br,
    checkbox(-name=>'refgenome-meeting',
             -checked=>0,
             -value=>'ON',
             -label=>'Reference Genome Working Group Meeting, Sept 26th & 27th',),
    hr;
}

#########################################################################
sub printSubmit {
#########################################################################

    print submit(-name=>'submit',
		 -value=>'Proofread Information')." ".
	  reset(-name=>'Clear and Reset Form'),hr;

}

#########################################################################
sub printFooter {
#########################################################################

    print "Comments and bug reports for this submission form should be sent to <script type=\"text/javascript\">obfuscate(\"geneontology.org\",\"gohelp\",\"\")</script>";

}

#########################################################################
sub checkInfo {
#########################################################################
    my ($infoHashRef) = @_;

    &populateHash($infoHashRef, 'presenter_title');

    &populateHash($infoHashRef, 'presenter_lname');
    
    &populateHash($infoHashRef, 'presenter_fname');
    
    &populateHash($infoHashRef, 'presenter_email');

    &populateHash($infoHashRef, 'department');
    
    &populateHash($infoHashRef, 'institution');
    
    &populateHash($infoHashRef, 'consortium-meeting');

    &populateHash($infoHashRef, 'sab-meeting');

    &populateHash($infoHashRef, 'refgenome-meeting');

    if (!$$infoHashRef{presenter_title} ||
	!$$infoHashRef{presenter_lname} ||
	!$$infoHashRef{presenter_fname} ||
	!$$infoHashRef{institution}) {

	&err_report("You omitted your title, first or last name, or institution."); 

    }

    if (!$$infoHashRef{presenter_email}) {

	&err_report("Please enter your Email address."); 

    }

} 

#########################################################################
sub processText {
#########################################################################
    my ($textRef) = @_;
    
    if (!$$textRef) { return; }

    &delete_unwanted_char($textRef);

    $$textRef =~ s/[\t\r\n]/ /g;
    $$textRef =~ s/ +/ /g;
    $$textRef =~ s/, , /, /g;	
    $$textRef =~ s/[, ]+$//;

    if ($$textRef) { $$textRef .= "."; }

    $$textRef =~ s/\.+/\./g;

    &hideUsefulTag($textRef);

    &delete_html_tag($textRef);

    &saveBackUsefulTag($textRef);

    $$textRef =~ s/\"/\'/g;

}

#########################################################################
sub hideUsefulTag {
#########################################################################
    my ($stringRef) = @_;

    $$stringRef =~ s+<sup>+#sup#+gi;
    $$stringRef =~ s+</sup>+#/sup#+gi;
    
    $$stringRef =~ s+<sub>+#sub#+gi;
    $$stringRef =~ s+</sub>+#/sub#+gi;

    $$stringRef =~ s+<i>+#i#+gi;
    $$stringRef =~ s+</i>+#/i#+gi;

    $$stringRef =~ s+<b>+#b#+gi;
    $$stringRef =~ s+</b>+#/b#+gi;

    $$stringRef =~ s+<a +#a +gi;
    $$stringRef =~ s+</a>+#/a#+gi;
    
}

#########################################################################
sub saveBackUsefulTag {
#########################################################################
    my ($stringRef) = @_;

    $$stringRef =~ s+#sup#+<sup>+gi;
    $$stringRef =~ s+#/sup#+</sup>+gi;
    
    $$stringRef =~ s+#sub#+<sub>+gi;
    $$stringRef =~ s+#/sub#+</sub>+gi;

    $$stringRef =~ s+#i#+<i>+gi;
    $$stringRef =~ s+#/i#+</i>+gi;

    $$stringRef =~ s+#b#+<b>+gi;
    $$stringRef =~ s+#/b#+</b>+gi;

    $$stringRef =~ s+#a +<a +gi;
    $$stringRef =~ s+#/a#+</a>+gi;
    
}

#########################################################################
sub populateHash {
#########################################################################
    my ($hashRef, $keyName) = @_;

    my $value = param("$keyName");

    if ($value) {
    
	&delete_unwanted_char(\$value);

    }

    $$hashRef{"$keyName"} = $value;

}

#########################################################################
sub sendResult {
#########################################################################
    my ($abstractNum) = @_;

    my %info;

    &checkInfo(\%info);

    if ($info{"consortium-meeting"} eq "ON") {
	$info{"consortium-meeting"} = "Yes";
    } else {
	$info{"consortium-meeting"} = "No";
    }

    if ($info{"sab-meeting"} eq "ON") {
	$info{"sab-meeting"} = "Yes";
    } else {
	$info{"sab-meeting"} = "No";
    }

    if ($info{"refgenome-meeting"} eq "ON") {
	$info{"refgenome-meeting"} = "Yes";
    } else {
	$info{"refgenome-meeting"} = "No";
    }

    open (mailtmp, ">$mailtmp") || 
        die "Can't create output file $mailtmp.\n";

    print mailtmp "Confirmation_Number = \"$abstractNum\"\n";

    print mailtmp "Presenter_Title = \"", param('presenter_title'), "\"\n";
 
    print mailtmp "Presenter_First_Name = \"", param('presenter_fname'), "\"\n";
 
    print mailtmp "Presenter_Last_Name = \"", param('presenter_lname'), "\"\n";

    print mailtmp "Presenter_Email = \"", param('presenter_email'), "\"\n";

    print mailtmp "Department = \"", param('department'), "\"\n"; 

    print mailtmp "Institution = \"", param('institution'), "\"\n"; 

    print mailtmp "REMOTE_ADDR = ", $ENV{REMOTE_ADDR}, "\n";

    print mailtmp "Meeting = Consortium Sept 23-24\t$info{'consortium-meeting'}\n";

    print mailtmp "Meeting = SAB Sept 25\t$info{'sab-meeting'}\n";

    print mailtmp "Meeting = RefGenome Sept 26-27\t$info{'refgenome-meeting'}\n";

    close mailtmp;

    my $subject = "GOC Registration Confirmation Number $abstractNum";

    my $presenterEmail = param('presenter_email');

    my $absFileNotWritten = 1;

    while ($absFileNotWritten) {
	unless (-e $lockfile) {
	    open (MAILTMP, $mailtmp) || die "Cannot open $mailtmp for reading: $!\n";
	    open (ABSFILE, ">>$abstractsfile") || die "Cannot open $abstractsfile for writing: $!\n";
	    open (MAILYGM, "|/usr/ucb/Mail -s \'$subject\' $ygmAbsInputEmail");
	    open (MAILPRESENT, "|/usr/ucb/Mail -s \'$subject\' $presenterEmail");

	    $absFileNotWritten = 0;

	    while (<MAILTMP>) {
		print ABSFILE "$_";
		print MAILYGM "$_";
		print MAILPRESENT "$_";
	    }

	    print ABSFILE "\n\n---\n\n";

	    close (MAILTMP);
	    close (ABSFILE);
	    close (MAILYGM);
	    close (MAILPRESENT);
	}
    }

    unlink($mailtmp);

}

#########################################################################
sub readAbstractNumber {
#########################################################################

    my $check = 1;

    my $abstractNum;
    
    while($check) {

	my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, 
	    $mtime, $ctime, $blksize, $blocks) = stat "$subnumlock";

	if (!$atime) {
	    
	    open(LOCK, ">$subnumlock") or print "princeton-registration: could not open lockfile '$subnumlock' for writing:$!";

            open(COUNT, "$subnumfile") or print "princeton-registration: could not open abstractNumfile '$subnumlock' for reading:$!";
	       
       	    read(COUNT, $abstractNum, 4);
	    
	    if (!$abstractNum) { 

		my $errorMessage = "Error obtaining your registration number.";

		my $err = Tools::Report->send_email(program_name=>url,
						    message=>$errorMessage,
						    email_receiver=>\@errReportEmail);

		print "Error obtaining your registration number. Please try again.<p>If you have seen this message before there is likely a problem on the server.<p>We apologize for the inconvenence but you will need to wait and try later. The person responsible for maintaining this software has been notified.",p;
		
		unlink($subnumlock);

		exit;

	    }
	    
	    close(COUNT);

	    $abstractNum++;

	    open(COUNT, ">$subnumfile") or warn "princeton-registration: could not open lockfile '$subnumlock' for writing:$!";
	    
	    $abstractNum = sprintf "%4s", $abstractNum;
	
	    $abstractNum =~ s/ /0/g;

	    print COUNT $abstractNum, "\n";

	    close(COUNT);

	    close(LOCK);

	    unlink($subnumlock);

	    $check = 0;

	    
	}
	else { sleep 1; }
	    
    }

    return $abstractNum;

}

#########################################################################
sub readResearchAreaAndTopic {
#########################################################################

    open(TEXT, "$researchTopicConf") ||
	die "Can't open '$researchTopicConf' for reading:$!";

    my @researchArea;
    my %researchTopic4area;
    my ($preArea, $i);    

    while(<TEXT>) {

	chomp;

	### ignore comment line or empty line 
	if (/^\#/ || /^ *$/) { next; }

	my ($area, $topic) = split(/=/);

	$area =~ s/^ *(.+) *$/$1/;
	$topic =~ s/^ *\"(.+)\" *$/$1/;
	
	if ($area ne $preArea) {

	    push(@researchArea, $area);

	    $preArea = $area;
	    
	    $i = 0;

	}

	$researchTopic4area{$area}->[$i++] = $topic;
 
    }
    
    close(TEXT);

    return (\@researchArea, \%researchTopic4area);
    
}

#########################################################################
sub readDescriptionFile {
#########################################################################

    open(TEXT, "$descConf") || 
	die "Can't open '$descConf' for reading:$!";

    my ($header, $title, $style, $newstyle, @subtitle, $note, $description);

    while(<TEXT>) {

	chomp;

	if (/^\#/ || /^ *$/) { next; }

	if (/^header = \"([^\"]+)\"/i) {

	    $header = $1;
	    
	    next;

	}

	if (/^title = \"([^\"]+)\"/i) {

	    $title = $1;

	    next;

	}

	if (/^style = \"([^\"]+)\"/i) {

	    $style = $1;

	    next;

	}

	if (/^newstyle = \"([^\"]+)\"/i) {

	    $newstyle = $1;

	    next;

	}

	if (/^subtitle = \"([^\"]+)\"/i) {

	    push(@subtitle, $1);

	    next;

	}
	
	if (/^note = \"([^\"]+)\"/i) {

	    $note = $1;

	    next;
	}
	
	if (/^description = \"([^\"]+)\"?$/i) {

	    $description = $1;

        }
	else { $description .= " ".$_; }

    }
    
    close(TEXT);

    $description =~ s/\"$//;

#    if (!$header) { $header = $title; }
#    elsif (!$title) { $title = $header; }
    
    $title .= "<p>".join('<br>', @subtitle);

    return ($header, $title, $style, $newstyle, $note, $description);
    
}

########################################################################
sub abstractTooLong {
########################################################################
    
    my ($length) = @_;

    print header;

    print start_html(-title=>'Bio/Summary is too long'); 

    print p, h1("BIO/SUMMARY IS TOO LONG");

    print h3("The maximum length is $maxAbstractLength characters. Your bio/summary is $length characters in length. Please press the BACK button to return to the form and shorten the text."), "\n";

    print end_html;

    exit;

} 

########################################################################
sub err_report {
########################################################################

    my ($err) = @_;

    print header;

    print start_html(-title=>'Error Report');

    print h1("Form Error -- More Information is Needed");

    print $err, " Please press the BACK button and add the missing information.",p;

    print end_html;

    exit;

}

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













