head     1.1;
branch   ;
access   ;
symbols  ;
locks    ; strict;
comment  @# @;


1.1
date     95.03.07.14.18.41;  author yonah;  state Exp;
branches ;
next     ;


desc
@madlibs!
@



1.1
log
@Initial revision
@
text
@#!/usr/athena/bin/perl


print("Content-Type: text/html\n\n");

$query = $ENV{'QUERY_STRING'};
&do_madlib($query);

sub do_madlib {
    local($query) = @@_;

    $mname = $ENV{'PATH_INFO'};
    $mname =~ s%^/%%;

    if($query){
	&returnmadlib($mname,$query);
    }
    else{
	&givemadlib($mname);
    }
}

sub returnmadlib {
    local($madlib, $fillins) = @@_;

    if(!$madlib){
	&givemadlib($fillins);
	return;
    }

    %table = &parseform($fillins);

    open(ML, "/var/local/www/madlibs/$madlib");
    while(<ML>){
	$mltext .=$_;
    }
    close(ML);
    for $word (keys %table){
	$mltext=~s/\*\*\*$word\/[^\*]+\*\*\*/$table{$word}/g;
    }

    print $mltext;
    $mltext=~s/<[^>]*>//g;
    open(ZW, "|/usr/athena/bin/zwrite -d -n -q -c madlib -i http://www.mit.edu:8001/");
    print(ZW $mltext);
    close(ZW);
	print("<p><h2>Give me <a href=\"http://www.mit.edu:8001/madlib\">another madlib</a>, or <a href=\"http://www.mit.edu:8001/\">the MIT SIPB Home Page</a></h2>\n");
    alarm 0;
}

sub givemadlib {
    local($madlib) = @@_;

    srand(time);

	opendir(DIR, "/var/local/www/madlibs");
	@@libs = readdir(DIR);
	close(DIR);
    
	@@libs = @@libs[2..$#libs];
    $n = rand($#libs+1);
	&givemadliblist if ($madlib eq "list");
    $libs[$n] = $madlib if $madlib;
    print("<title>Madlibs</title>\n");
    print("<h1>Madlib!</h1>\n");
    print("Madlib name: \"$libs[$n]\"<br>Reload to get a new <a href=\"/madlib\">random madlib</a> or see <a href=\"/madlib/list\">the list of madlibs</a>");
    open(LIB, "/var/local/www/madlibs/".$libs[$n]) || print "hey!! what gives?";
    while(<LIB>){
	$lib .=$_;
    }
    close(LIB);
    print("<hr>\n");
    print("<form action=\"http://www.mit.edu:8001/madlib/$libs[$n]\">\n");

    while($lib=~/\*\*\*([A-Z0-9]+)\/([^\*]+)\*\*\*/g){
	push(@@output,"$2: <input size=40 name=$1><p>\n");

    }
    $no = $#output;
    for $i (0..$no){
	$n = rand($#output+1);
	print($output[$n]);
	splice(@@output,$n,1);
    }
    print("<input type=\"submit\" value=\"Submit Madlib\">\n");
	print("</form>\n");
	print("<h2><a href=\"http://www.mit.edu:8001/\">The MIT SIPB Home Page</a></h2>\n");
    alarm 0;
}

sub givemadliblist {
	print "<title>Madlib List</title>\n";
	print("<h1>Madlib List</h1>\n");
	print "<ol>\n";
	for $mname (@@libs) {
		print("<li><a href=\"$mname\">$mname</a>\n");
	}
	print("</ol>\n");
exit;
}
sub parseform {
    local($formthing) = @@_;     # Expects something like:
                                # foo=wow%21&bar=hello&baz=blah

    (@@fields) = split('&', $formthing);
    for $f (@@fields){
        ($name, $value) = split('=', $f);
	$value =~ s/\+/ /g;
        $value =~ s/%([\da-f]{1,2})/pack(C,hex($1))/eig; # remove % escapes
        $lookup{$name} = $value;
    }

    %lookup;
}

1;
@
