Farid Hajji: Perl - Einführung, Anwendungen, Referenz
2., aktualisierte und erweiterte Auflage
Addison-Wesley Longman, ISBN 3-8273-1535-2
wf
#!/usr/local/bin/perl -w
# wf -- a web-forum cgi script
# (C) 1998/07/21 Farid Hajji /address.html
# $Id: wf.html,v 1.5 2006/05/18 12:55:49 farid Exp $
# See the POD documentation at the end of this file (call: perldoc wf)
# for usage, configuration and installation instructions.
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI::Cookie;
use SDBM_File;
use Fcntl qw(:DEFAULT :flock);
use strict;
# ----- BEGIN CONFIGURATION SECTION ------------------------------------------
#### Set the following parameters!
my $SPOOLDIR = "/var/wf"; # spool directory. CHANGE THIS!
my $COOKIE_TTL = "+1h"; # expiration time of cookies
my $AUTHOR = 'wf@somewhere.com'; # email address of local wf-guru
#### Customize wf's output.
my $BGCOLOR = "black"; # overall background color
my $TEXTCOLOR = "yellow"; # color of normal text
my $ART_COLOR = "white"; # color of article text
my $ART_FACE = "courier"; # font face of article text
my $ART_SIZE = "+1"; # font size of article text
my $AL_F_COLOR = "gray"; # color of author in article list
my $AL_F_FACE = "helvetica"; # font face of author in article list
my $AL_F_SIZE = "-1"; # font size of author in article list
my $AL_D_COLOR = "gray"; # color of date in article list
my $AL_D_FACE = "courier"; # font face of date in article list
my $AL_D_SIZE = "-1"; # font size of date in article list
my $ERR_COLOR = "red"; # color of error message
my $LINK_COLOR = "blue"; # color of new links
my $VLINK_COLOR = "lime"; # color of visited links
my $ALINK_COLOR = "fuchsia"; # color of currently active link
my $DFL_BODY = "Your message here..."; # default body message
my $DFL_SUBJECT = "(no subject)"; # default subject line when missing
my $DFL_GEMPTY = "No articles yet"; # default text to describe empty group
my $CPY_IDCOL = "gray"; # color of RCS Version string
my $CPY_COLOR = "green"; # color of copyright string
# ----- END CONFIGURATION SECTION --------------------------------------------
# ----- other non-configurable parameters ------------------------------------
my $CTLDIR = $SPOOLDIR . "/.ctl";
my $GROUPDESCR = $CTLDIR . "/newsgroups";
my $USERDB = $CTLDIR . "/userdb";
my $COOKIEDB = $CTLDIR . "/cookies";
my $ARTICLEDESCR = ".summary";
# ----- global variables -----------------------------------------------------
my $cgi; # handle to a CGI object from &initialize()
my $funcptr; # returned by &dispatcher()
my %cookiedb; # tie()ed to $COOKIEDB in &initialize()
my %userdb; # tie()ed to $USERDB in &initialize()
my %groupdescr; # tie()ed to $GROUPDESCR in &initialize()
# ----- main program ---------------------------------------------------------
$cgi = &initialize(); # init all global variables
$funcptr = &dispatcher($cgi); # select action
&$funcptr($cgi); # call appropriate handler
exit 0; # that's all, folks!
# initialize() all global variables
# side effects: %cookiedb, %userdb and %groupdescr tie()ed,
# $SPOOLDIR subdirectories created if necessary
# returns an instantiated CGI object.
sub initialize {
my $g;
# first check if all directories are accessible
if ((not -d $SPOOLDIR) or
(not -r $SPOOLDIR) or (not -x $SPOOLDIR) or (not -w $SPOOLDIR)) {
die "Spool directory $SPOOLDIR not present or unaccessible\n";
}
# create control and other directories if necessary
if (not -e $CTLDIR) {
mkdir($CTLDIR, 0700)
or die "Can't create control directory $CTLDIR: $!\n";
}
# tie the %cookiedb hash to $COOKIEDB
tie(%cookiedb, 'SDBM_File', $COOKIEDB, O_RDWR | O_CREAT, 0600)
or die "Can't tie() cookie hash to $COOKIEDB: $!\n";
# tie the %userdb hash to $USERDB
tie(%userdb, 'SDBM_File', $USERDB, O_RDWR | O_CREAT, 0600)
or die "Can't tie() user hash to $USERDB: $!\n";
# tie the %groupdescr hash to $USERDB
tie(%groupdescr, 'SDBM_File', $GROUPDESCR, O_RDWR | O_CREAT, 0600)
or die "Can't tie() group descr file to $GROUPDESCR: $!\n";
# create a new CGI object
$g = new CGI;
return $g;
}
# dispatcher() parses the CGI input arguments and dispatches to the
# appropriate action.
# returns reference of handler function that should be called.
sub dispatcher {
my $g = shift; # instantiated CGI object
# dispatcher() checks for the presense of various CGI parameters
# by using CGI.pm's param() method.
# It then returns the reference of the appropriate handler.
# NOTE: the relative order of checks is important here!
# All users, even non-registered, can see COPYRIGHT conditions
return \©right_screen if defined $g->param('COPYRIGHT');
# Users submitting a REGISTRATION form don't have a valid cookie yet.
# Other parameters: 'USER-ID' or 'USER-ID-REQUEST', 'USER-PW'.
return \&do_registration if defined $g->param('REGISTRATION');
# Always check user's cookie or 'REGISTERAGAIN' request before
# proceeding any further. Display registration form if necessary.
return \®ister_user
if (not &valid_cookie($g)) or
defined $g->param('REGISTERAGAIN');
if (defined $g->param('NEW-GROUP-NAME')) {
# User requested the creation of a new group descr 'NEW-GROUP-NAME'
$funcptr = \&new_group;
} elsif (defined $g->param('GROUP-ID-LIST-REQUEST')) {
# Display list of articles of group ID 'GROUP-ID-LIST-REQUEST'
$funcptr = \&group_list_id;
} elsif (defined $g->param('NEW-SUBJECT') and
defined $g->param('GROUP')) {
# User requested an article entry form for a new article
# in the GROUP descr. having an editable subject of NEW-SUBJECT.
$funcptr = \&new_article_request;
} elsif (defined $g->param('SUBJECT') and
defined $g->param('GROUP')) {
# User filled and submitted the article entry form for an article in
# the GROUP descr. having this SUBJECT. Save it to local filesystem!
$funcptr = \&new_article;
} elsif (defined $g->param('ARTICLE-ID') and
defined $g->param('GROUP-ID')) {
# User requested display of article having as ID ARTICLE-ID
# belonging to the group with the ID GROUP-ID.
# If user wants to REPLY to GROUP-ID/ARTICLE-ID, send an article
# entry form prefilled with the quoted contents of that article.
$funcptr = defined $g->param('REPLY') ?
\&reply_article : \&show_article;
} else {
# Default is welcome screen which lists all active groups
$funcptr = \&welcome_screen;
}
return $funcptr;
}
# register_user() sends a registration form containing:
# a list of already registered aliases to select from (ALIAS_ID_REQUEST),
# a password entry field for the selected alias (USER-PW),
# a text entry field for a new alias (USER-ID),
# a text message explaining the use of the registration form.
sub register_user {
my $g = shift; # instantiated CGI object
my @aliases;
# print welcome message
print
$g->header(),
&wf_start_html($g, 'Web-Forum User Registration Form'), "\n",
$g->h1('Web-Forum User Registration Form'), "\n",
"Please select an (eventually new) alias and a password.\n",
$g->p(), "\n",
"The articles you'll post will be tagged by your alias.\n",
"The alias you selected belong only to you! Users must enter\n",
"a valid password before using an existing alias.\n",
$g->strong("Don't forget your Password!"), "\n",
$g->p(), "\n";
# print list of already registered alias names
push(@aliases, sort keys %userdb); # get list of registered users
print
$g->startform(), "\n",
$g->hidden("REGISTRATION", "VALUE-DOESNT-MATTER"), "\n";
if (@aliases) {
print
"Existing aliases: \n",
$g->scrolling_list("-name" => 'USER-ID-REQUEST',
"-values" => \@aliases,
"-size" => 1),
$g->p(), "\n";
}
# print the new alias text entry and a password entry field
print
$g->table({"-cellpadding" => 5, "-cellspacing" => 5},
$g->Tr({"-align"=>'CENTER',"-valign"=>'CENTER'},
$g->td([ "Alias",
$g->textfield("-name" => "USER-ID",
"-size" => 20,
"-maxsize" => 30)]),
$g->td([ "Password",
$g->password_field("-name" => "USER-PW",
"-size" => 10,
"-maxsize" => 20)]))),
$g->p, $g->submit, $g->reset,
$g->endform(), "\n";
# print an informative message about possible cookie expiration
print
"If you've already chosen an alias before, the session cookie\n",
"probably expired. You can get a new session cookie by selecting\n",
"your old alias and providing the\n",
$g->em("same"), "\n",
"password you've already used for this alias.\n",
$g->p(),
"If you're presented this registration form again and again\n",
"making it impossible for you to proceed any further,\n",
"please ascertain that you've configured your browser to\n",
"accept and use cookies.\n",
$g->br(),
$g->em("This CGI script requires cookies! They're mandatory!"), "\n";
print
&wf_end_html($g);
}
# welcome_screen() sends a welcome page consisting of:
# a clickable list of already existing groups (GROUP-ID-LIST-REQUEST)
# an input textfield for adding new groups (NEW-GROUP-NAME)
# a link to permit user to select a new alias (REGISTERAGAIN)
# WARNING: This function differs from other handlers:
# it can be called from dispatcher() [no 2nd parameter]
# it can be called from do_registration() [2nd param: new NS-Cookie]
# in which case it sends the cookie via header() back to the browser.
sub welcome_screen {
my $g = shift; # instantiated CGI object
my $ns_cookie = shift; # undef if called via dispatcher()
# new ns-cookie if called from do_registration()
my ($user_id, $g_descr, @group_list);
# The HTTP-Header may contain a Set-Cookie: $nscookie request or not.
print defined $ns_cookie ?
$g->header("-cookie" => $ns_cookie) :
$g->header();
# Find out who we are (user-id), based on the cookie.
# please note the special handling here...
$user_id = defined $ns_cookie ?
$cookiedb{$ns_cookie->value()} :
&get_user_from_cookie($g);
# start the HTML output
print
&wf_start_html($g, "WF Welcome Page"), "\n",
$g->h1("WF Welcome Page"), "\n",
"Welcome, ",
$g->strong(&wf_escapeHTML($user_id)),
$g->p(), "\n",
"Please select a group from the list of active groups below\n",
"or add the description for a new group.\n",
$g->p(), "\n";
# retrieve and print the list of active groups
# the keys are group descriptions, the values are the group IDs.
# sorting keys leads to a sorted list of group descriptions.
# CHANGE THIS if using C-News/INN or NNTP and no %groupdescr
@group_list = ();
foreach $g_descr (sort keys %groupdescr) {
push(@group_list,
$g->li(
$g->a({"-href" =>
$g->url() . "?GROUP-ID-LIST-REQUEST=$groupdescr{$g_descr}"},
&wf_escapeHTML($g_descr))));
}
print $g->ul(join("\n", @group_list)), "\n" if @group_list;
# print form for adding new groups
print
$g->startform(),
$g->table({"-cellpadding" => 5,
"-cellspacing" => 5},
$g->Tr({"-align"=>'CENTER',"-valign"=>'CENTER'},
$g->td([ "Add new group:",
$g->textfield("-name" => 'NEW-GROUP-NAME',
"-length" => 60,
"-maxlength"=> 70),
$g->submit]))), "\n",
$g->endform(), "\n";
print
$g->a({"-href" => $g->url() . "?REGISTERAGAIN=yes"},
"Use another alias"),
&wf_end_html($g);
}
# group_list_id() lists all articles belonging to the group
# with the ID 'GROUP-ID-LIST-REQUEST'.
# this function also generates a form to add new articles containing:
# * A new subject textfield: 'NEW-SUBJECT'
# * The hidden group descripton of the current group: 'GROUP'
sub group_list_id {
my $g = shift; # instantiated CGI object
my $g_id = $g->param('GROUP-ID-LIST-REQUEST'); # numerical Group-ID.
my ($user_id, $g_descr, @artlist, @sorted_list, $HTMLtable);
# gather informations for display page
$user_id = &get_user_from_cookie($g);
&wf_error($g, "No group ID submitted\n")
if not defined $g_id;
$g_descr = &reverse_lookup(\%groupdescr, $g_id);
&wf_error($g, "No group with ID $g_id defined!\n")
if not defined $g_descr;
# fetch group list
@artlist = &fetch_articlelist($g, $g_id);
# present this list in a HTML table
@sorted_list = &sort_artlist(\@artlist);
$HTMLtable = &create_artlist_table($g, \@sorted_list, $g_id);
# output everything:
print
$g->header(),
&wf_start_html($g, "WF List of articles"), "\n",
$g->h1("Group: " . &wf_escapeHTML($g_descr)), "\n",
"Welcome ", $g->strong(&wf_escapeHTML($user_id)), $g->p, "\n",
$g->a({"-href" => $g->url()}, "Back to WF's Home"), "\n",
$g->hr, "\n",
$g->startform(), "\n",
$g->hidden('GROUP', $g_descr), "\n",
"Add a new article: ",
$g->textfield("-name" => 'NEW-SUBJECT',
"-size" => 50,
"-maxsize" => 70), "\n",
$g->submit("-name" => 'Compose it!'), $g->reset(), "\n",
$g->endform(), "\n";
print
$g->hr, "\n",
(@artlist ? $HTMLtable : &wf_escapeHTML($DFL_GEMPTY)), "\n";
print
$g->hr, "\n",
$g->a({"-href" => $g->url()}, "Back to WF's Home"), "\n";
print
&wf_end_html($g);
}
# show_article() fetches a specific article by group-id and article-id
# from the $SPOOLDIR and displays the following:
# * the whole article, including it's header
# * a link to REPLY to this specific article.
# * navigational links.
sub show_article {
my $g = shift; # instantiated CGI object
my $g_id = $g->param('GROUP-ID'); # wanted group id of article
my $a_id = $g->param('ARTICLE-ID'); # wanted article id of article
my ($g_descr, $line, @lines);
# fetch article contents into @lines, HTML-escaping on-the-fly
foreach $line (&fetch_article($g, $g_id, $a_id)) {
push(@lines, &wf_escapeHTML($line));
}
# get the group description belonging to the numerical $group_id
$g_descr = &reverse_lookup(\%groupdescr, $g_id);
# print the article
print
$g->header(),
&wf_start_html($g, 'Web-Forum Article Display Page'),
$g->h1('Web-Forum Article Display Page'), "\n",
"Contents of article ID ", $g->em($a_id),
" from the group ", $g->em(&wf_escapeHTML($g_descr)), ":\n",
$g->hr,
$g->font({ "-color" => $ART_COLOR,
"-face" => $ART_FACE,
"-size" => $ART_SIZE },
$g->pre(join('', @lines))),
$g->hr, "\n";
# print navigation links
print
$g->a({"-href" =>
$g->url() . "?REPLY=yes&GROUP-ID=$g_id&ARTICLE-ID=$a_id"},
"Reply to Article"),
$g->br, "\n",
$g->a({"-href" => $g->url() . "?GROUP-ID-LIST-REQUEST=$g_id"},
"Back to the list of articles"),
$g->br, "\n",
$g->a({"-href" => $g->url()}, "Back to WF's Home"), "\n";
print
&wf_end_html($g);
}
# reply_article() is called when the user wants to reply to an article
# specified by it's GROUP-ID and ARTICLE-ID.
# reply_article() fetches the specified article and uses its contents
# to fill in an article entry form by setting the following parameters:
# Group Description : GROUP
# Re: quoted Subject : NEW-SUBJECT
# > ******* quoted body : NEW-BODY
# and then calling &new_article_request() DIRECTLY (!).
sub reply_article {
my $g = shift; # instantiated CGI object
my $g_id = $g->param('GROUP-ID'); # requested group-id
my $a_id = $g->param('ARTICLE-ID'); # id of article to reply to
my ($in_body, $line, @body_lines);
my ($subject, $old_subject, $from, $date);
# parse the article contents, searching for 'From: ', 'Subject: '
# and 'Date: ' headers, The body begins after the first empty line.
$in_body = 0; # flag indicating wether we are alread in body.
@body_lines = (); # lines of the article body
foreach $line (&fetch_article($g, $g_id, $a_id)) {
chop $line;
if ($in_body) {
push(@body_lines, "> " . $line . "\n");
} else {
if ($line =~ /^Subject:\s+(.*)\s*$/i) {
$old_subject = $subject = $1;
$subject = "Re: " . $subject
if $old_subject !~ /^Re:\s/;
$subject .= "\n";
next;
} elsif ($line =~ /^From:\s+(.*)\s*$/i) {
$from = $1;
next;
} elsif ($line =~ /^Date:\s+(.*)\s*$/i) {
$date = $1;
next;
} elsif ($line =~ /^$/) {
$in_body = 1;
next;
}
}
}
unshift(@body_lines, "$from wrote $date:\n");
# prepare parameters for *DIRECT* call to &new_article_request()
# which will send a filled article entry form back to the user.
$g->param('GROUP', &reverse_lookup(\%groupdescr, $g_id));
$g->param('NEW-SUBJECT', $subject);
$g->param('NEW-BODY', join('', @body_lines));
&new_article_request($g);
}
# new_group() creates a new group with the description 'NEW-GROUP-NAME'
# by adding a new group directory to $SPOOLDIR.
# Change this if using C-News/INN or NNTP!
sub new_group {
my $g = shift; # instantiated CGI handle
my $g_descr = $g->param('NEW-GROUP-NAME'); # new group's description
my ($g_id, $user_id, @group_ids);
# check if the new group does already exist.
&wf_error($g, "Invalid new group: $g_descr!")
if not defined $g_descr
or $g_descr eq ''
or defined $groupdescr{$g_descr};
# create a new id for this group. This ought to be atomic
open (LOCKHANDLE, ">> $GROUPDESCR" . ".lock")
or &wf_error($g, "Can't create lock handle $GROUPDESCR.lock");
&wf_lock(\*LOCKHANDLE);
@group_ids = values %groupdescr;
$g_id = &get_next_free_id(\@group_ids);
mkdir("$SPOOLDIR/$g_id", 0700)
or &wf_error("can't create $SPOOLDIR/$g_id: $!");
# postpone tie() with create or $SPOOLDIR/$g_id/$ARTICLEDESCR
# to the first access of the group list
$groupdescr{$g_descr} = $g_id; # register locally
&wf_unlock(\*LOCKHANDLE);
close (LOCKHANDLE);
# Confirm the group was successfully created.
$user_id = &get_user_from_cookie($g);
print
$g->header(),
wf_start_html($g, "WF - New group successfully added"),
$g->h1("WF - New group successfully added"), "\n",
$g->strong(&wf_escapeHTML($user_id)),
", you successfully created the new group", "\n",
$g->p(), $g->em(&wf_escapeHTML($g_descr)), $g->p(), "\n",
$g->hr(),
$g->a({"-href" => $g->url()}, "Back to WF's Home-Page"),
&wf_end_html($g);
}
# new_article_request() generates a prefilled article entry form
# with the following contents:
# From: <Alias obtained from valid cookie> (READ-ONLY) WF-COOKIE
# Newsgroups: <Group Description from 'GROUP'> (READ-ONLY) 'GROUP'
# Date: <GMT Date derived from system time> (READ-ONLY) 'TIMESTAMP'
# Subject: <Contents of 'NEW-SUBJECT'> (TEXTFIELD) 'SUBJECT'
# Body <Contents of 'NEW-BODY' or $DFL_BODY> (TEXTAREA) 'BODY'
sub new_article_request {
my $g = shift; # instantiated CGI object
my $user_id = &get_user_from_cookie($g); # alias of the poster
my $subject = $g->param('NEW-SUBJECT'); # prefilled subject line
my $group = $g->param('GROUP'); # requested group descr.
my $body = $g->param('NEW-BODY'); # [optional] default body
my $now = gmtime();
$body = defined $body ? $body : $DFL_BODY;
# print the article entry form:
print
$g->header(),
wf_start_html($g, "WF - Article Entry Form"), "\n",
$g->h1("WF - Article Entry Form"), "\n",
$g->startform(), "\n",
$g->hidden('GROUP', $group), "\n",
$g->hidden('TIMESTAMP', $now), "\n",
$g->table({"-cellpadding" => 3, "-cellspacing" => 3},
$g->Tr($g->td([ "From:",
&wf_escapeHTML($user_id) ])), "\n",
$g->Tr($g->td([ "Newsgroups:",
&wf_escapeHTML($group) ])), "\n",
$g->Tr($g->td([ "Date:",
"$now GMT" ])), "\n",
$g->Tr($g->td([ "Subject:",
$g->textfield("-name" => 'SUBJECT',
"-value" => $subject,
"-size" => 50,
"-maxsize" => 70) ]), "\n")),
$g->p,
$g->textarea("-name" => 'BODY',
"-default" => $body,
"-rows" => 15,
"-columns" => 70,
"-wrap" => 'off'), "\n",
$g->p,
$g->submit("-name" => 'SendIt!'), $g->reset,
$g->endform(),
&wf_end_html($g);
}
# new_article() creates a new article with the following contents:
# From: <Alias name derived from Cookie> (WF-COOKIE)
# Newsgroups: <Description of the group> (GROUP)
# Date: <Timestamp of new article in GMT> (TIMESTAMP)
# Subject: <Subject of the new article> (SUBJECT)
# <empty line>
# <Body of the message, HTML-escaped> (BODY)
# This article is then saved with &post_article() and a confirmation
# is sent to the user.
sub new_article {
my $g = shift; # instantiated CGI object
my $subject = $g->param('SUBJECT'); # Subject of article
my $g_descr = $g->param('GROUP'); # Group descr. of article
my $timestamp = $g->param('TIMESTAMP'); # Date of article
my $user_id = &get_user_from_cookie($g); # Poster of article
my $body = $g->param('BODY'); # HTML-escaped body of article
my ($g_id, @a_contents);
# sanity check that the group already exists
$g_id = $groupdescr{$g_descr};
&wf_error($g, "Invalid group: $g_descr!")
if not defined $g_id;
# sanity check that the subject line is not empty or blank
$subject = ($subject !~ /^\s*$/) ? $subject : $DFL_SUBJECT;
# compose message
@a_contents = ();
push(@a_contents, "From: $user_id\n");
push(@a_contents, "Newsgroups: $g_descr\n");
push(@a_contents, "Date: $timestamp GMT\n");
push(@a_contents, "Subject: $subject\n");
push(@a_contents, "\n");
push(@a_contents, $body);
# save message permanently
&post_article($g, $g_id, $user_id, $timestamp, $subject, \@a_contents);
# confirm the article was successfully created and saved/posted.
print
$g->header(),
wf_start_html($g, "WF - article successfully added"), "\n",
$g->h1("Article successfully added"), "\n",
$g->em(&wf_escapeHTML($user_id)), "\n",
"the article you submitted with the subject line:\n",
$g->br, $g->em(&wf_escapeHTML($subject)), $g->br, "\n",
"to the group:\n",
$g->br, $g->em(&wf_escapeHTML($g_descr)), $g->br, "\n",
"was successfully added.\n",
$g->hr, "\n";
print
$g->a({"-href" => $g->url()}, "Back to WF's Home"),
$g->br,
$g->a({"-href" => $g->url() . "?GROUP-ID-LIST-REQUEST=$g_id"},
"Back to the list of articles");
print
&wf_end_html($g);
}
# valid_cookie() checks the presence of a valid netscape cookie WF-COOKIE
# returns true if the cookie is valid, else false.
sub valid_cookie {
my $g = shift; # inst. CGI handle
my $ns_cookie = $g->cookie("-name" => 'WF-COOKIE'); # value of cookie
# check if $ns_cookie was saved locally in %cookiedb
return 0 if not defined $ns_cookie; # missing cookie
return 0 if not defined $cookiedb{$ns_cookie}; # cookie not registered
return 0 if not defined $userdb{$cookiedb{$ns_cookie}}; # user not known
# okay, the cookie is valid and belongs to a registered user.
return 1;
}
# do_registration() registers a new alias and cookie in the user/cookie DB
# This function gets its parameters from the registration form as:
# * New alias (USER-ID) or existing alias (USER-ID-REQUEST)
# * Password for the alias (USER-PW).
# A new random cookie is generated as well and sent to the browser
# by calling &welcome_screen() with this cookie as an optional parameter.
# Existing aliases can't be registered again, but if the password is okay,
# a new cookie is generated anyway.
sub do_registration {
my $g = shift; # inst. CGI object.
my $user_id = (defined $g->param('USER-ID') # new/existing alias
and $g->param('USER-ID') ne '') ?
$g->param('USER-ID') :
$g->param('USER-ID-REQUEST');
my $user_pw = $g->param('USER-PW'); # the password.
my ($ns_cookie, $cookie_value);
# check user and password fields
&wf_error($g, "You did not specify an alias!")
if not defined $user_id or $user_id eq '';
&wf_error($g, "You did not specify a password for user $user_id!")
if not defined $user_pw or $user_pw eq '';
# check the password of existing user or register new user in %userdb
if (defined ($userdb{$user_id})) {
&wf_error($g, "User $user_id doesn't have that password!")
if ($userdb{$user_id} ne $user_pw);
} else {
$userdb{$user_id} = $user_pw;
}
# generate a new random session cookie
# and save its VALUE, associated with user alias on server side.
$ns_cookie = &generate_random_cookie($g);
$cookiedb{$ns_cookie->value()} = $user_id;
# send the (whole) random session cookie (not only it's value)
# the the browser by DIRECTLY calling &welcome_screen() with
# this additional parameter.
&welcome_screen($g, $ns_cookie); # direct call, bypassing dispatcher()
}
# generate_random_cookie() generates a random cookie
# * named 'WF-COOKIE'
# * that will expire in $COOKIE_TTL
# The returned value of the generated random cookie
# is guaranteed to be unique on the server-side.
sub generate_random_cookie {
my $g = shift; # instantiated CGI object
my ($ns_cookie, $cookie_val);
do {
$cookie_val = rand(30000);
} while defined $cookiedb{$cookie_val};
$ns_cookie = new CGI::Cookie("-name" => 'WF-COOKIE',
"-value" => $cookie_val,
"-expires" => $COOKIE_TTL,
"-path" => $g->url("-absolute" => 1));
return $ns_cookie;
}
# wf_error() prints an error message and exists.
sub wf_error {
my $g = shift; # instantiated CGI object
my $message = shift; # error message, NOT HTML-escaped
print
$g->header(),
&wf_start_html($g, "<WF> Error"), "\n",
$g->h1("An error occured in " .
$g->em(&wf_escapeHTML("<WF>")) .
"!"), "\n", $g->br,
"The message error is: \n",
$g->p,
$g->font({"-color" => $ERR_COLOR,
"-face" => "courier",
"-size" => "+1"},
&wf_escapeHTML($message)),
"\n";
print
$g->p,
$g->a({"-href" => $g->url()},
"Back to WF's Home"),
&wf_end_html($g);
exit 0;
}
# get_next_free_id(\@list) returns a unique ID, that is not yet
# present in @list (@list must contain only numerical values)
# The algorithm selected is: ++max(@list)
sub get_next_free_id {
my $listp = shift; # \@list_of_numerical_id
my $maxval = (reverse sort { $a <=> $b } @$listp)[0];
return ++$maxval;
}
# get_user_from_cookie() returns the alias associated with the
# cookie 'WF-COOKIE' contained in the CGI handle by looking in
# the server-side %cookiedb.
sub get_user_from_cookie {
my $g = shift; # inst. CGI handle
my $c_val = $g->cookie("-name" => 'WF-COOKIE'); # value of cookie
return $cookiedb{$c_val}; # associated alias
}
# reverse_lookup() looks in a hash for a key matching the submitted value.
# the first matching value is returned or undef if no match occured.
sub reverse_lookup {
my $hashp = shift; # \%lookup_hash
my $value = shift; # the search value
my $key;
foreach $key (keys %$hashp) {
return $key if $hashp->{$key} eq $value;
}
return undef;
}
# wf_lock() attempts to obtain an exclusive lock on an open file(handle)
# this function blocks until a lock is obtained.
sub wf_lock {
my $fhandle = shift; # filehandle of a lock file opened for writing
flock($fhandle, LOCK_EX);
}
# wf_unlock() unlocks the exclusive lock obtained from &wf_lock().
sub wf_unlock {
my $fhandle = shift; # filehandle of a locked lockfile as returned
# by wf_lock()
flock($fhandle, LOCK_UN);
}
# wf_start_html() returns a customized html header as a string.
sub wf_start_html {
my $g = shift; # instantiated CGI handle
my $title = shift; # title of the Web-Document
return $g->start_html("-title" => $title,
"-author" => $AUTHOR,
"-bgcolor" => $BGCOLOR,
"-link" => $LINK_COLOR,
"-vlink" => $VLINK_COLOR,
"-alink" => $ALINK_COLOR,
"-TEXT" => $TEXTCOLOR);
}
# wf_end_html() is a replacement for CGI's end_html() method.
# This will add a (copyright-)trailer to all HTML pages and then
# closes the HTML output.
sub wf_end_html {
my $g = shift; # instantiated CGI handle
return
$g->hr . "\n" .
$g->font({"-color" => $CPY_IDCOL,
"-face" => 'courier',
"-size" => '-1'},
&wf_escapeHTML('$Id: wf.html,v 1.5 2006/05/18 12:55:49 farid Exp $')) . "\n" .
$g->br . "\n" .
$g->font({"-color" => $CPY_COLOR,
"-face" => 'helvetica',
"-size" => '-1'},
"Copyright " . $g->a({"-href" => $g->url() . "?COPYRIGHT=yes"},
"©") . " 1998 by ",
$g->a({"-href" => '/address.html'},
"Farid Hajji")) . "\n" .
$g->end_html();
}
# sort_artlist() sorts a list of articles according to some criteria.
# Each entry of the list is a string in the form: "from\0date\0subject"
# One possible criterion may be to thread the subjects (Re: ...).
# returns the sorted list.
# Currently reverse sorting on the numerical article ID.
sub sort_artlist {
my $alistp = shift; # \@list to be sorted
# sort on the numerica ID of the article.
# put most recent articles (with higher IDs) at the top
return sort { $b <=> $a } @$alistp;
}
# create_artlist_table() creates a HTML-3 table containg a list of
# articles of the group with the ID $g_id.
# returns a html string containing the table.
sub create_artlist_table {
my $g = shift; # instantiated CGI object
my $alistp = shift; # \@list_of_entries "article-id\0from\0date\0subject"
my $g_id = shift; # numeric group-id of the actual group
my ($output, $tcontents, $entry);
my ($a_id, $a_from, $a_date, $a_subject);
$tcontents = ""; # no rows yet.
foreach $entry (@$alistp) {
($a_id, $a_from, $a_date, $a_subject) = split(/\0/, $entry);
$tcontents .= $g->Tr($g->td([
$g->font({"-color" => $AL_F_COLOR,
"-face" => $AL_F_FACE,
"-size" => $AL_F_SIZE},
&wf_escapeHTML($a_from)),
$g->a({"-href" => $g->url() .
"?ARTICLE-ID=$a_id" .
"&GROUP-ID=$g_id"},
&wf_escapeHTML($a_subject)),
$g->font({"-color" => $AL_D_COLOR,
"-face" => $AL_D_FACE,
"-size" => $AL_D_SIZE},
&wf_escapeHTML($a_date)) ])) . "\n";
}
$output = $g->table({"-cellpadding" => 2}, $tcontents);
return $output;
}
# fetch_article() fetches a specific article by group-id and article-id.
# Returns an array consisting of all lines of the article, including
# the article header. All lines are "\n"-terminated!
# Change this if using C-News/INN or NNTP Server!
sub fetch_article {
my $g = shift; # instantiated CGI object
my $g_id = shift; # wanted group id
my $a_id = shift; # wanted article id
my ($fname, @flines);
# ascertain that $a_id and $g_id consist solely of digits
# to deter '../../etc/passwd' hacks
$a_id =~ s/\D//g;
$g_id =~ s/\D//g;
# the real filename of the desired article
$fname = $SPOOLDIR . "/" . $g_id . "/" . $a_id;
&wf_error($g, "Article with specified ID and group-ID non-existant " .
"or non-readable")
if not -e $fname or not -r $fname;
# fetch the article
open (ARTICLE, "< $fname")
or &wf_error($g, "Can't fetch article $g_id/$a_id from $fname: $!");
@flines = <ARTICLE>;
close (ARTICLE);
# return all contents
return @flines;
}
# post_article() saves a new article to permanent storage. (R = registration)
# Change this, if using C-News/INN or NNTP!
sub post_article {
my $g = shift; # instantiated CGI object
my $g_id = shift; # group-id for the article
my $user_id = shift; # alias of article poster (HTML-escaped) R
my $timestamp = shift; # date of article in GMT R
my $subject = shift; # subject of article (HTML-escaped) R
my $a_contents = shift; # ref. to @a_lines (all HTML-escaped)
# @a_lines = header + body !!!
my ($fname_summary, %articles, $a_id, @existing_a_id, $fname_a);
# sanity checks to prevent a ../../etc/passwd hack
$g_id =~ s/\D//g;
# connect to the article database of the group with the ID $g_id:
$fname_summary = $SPOOLDIR . "/" . $g_id . "/" . $ARTICLEDESCR;
tie (%articles, 'SDBM_File', $fname_summary, O_RDWR, 0)
or wf_error($g, "can't tie() to summary $fname_summary: $!");
# create, register and save a new ID for this article in $a_id.
# This ought to be atomic.
open (LOCKHANDLE, ">> $fname_summary" . ".lock")
or &wf_error($g, "can't create $fname_summary.lock");
&wf_lock(\*LOCKHANDLE);
# -- create new unique article ID
@existing_a_id = keys %articles;
$a_id = &get_next_free_id(\@existing_a_id);
# -- register article in article summary
$articles{$a_id} = join("\0", $user_id, $timestamp, $subject);
# -- save new article
$fname_a = $SPOOLDIR . "/" . $g_id . "/" . $a_id;
open (ARTFILE, "> $fname_a")
or &wf_error($g, "can't create article file: $fname_a: $!");
print ARTFILE @$a_contents;
close(ARTFILE);
&wf_unlock(\*LOCKHANDLE);
untie(%articles);
}
# fetch_articlelist() fetches a list of all current articles belonging
# to group with a specified numerical ID.
# returns a list of entries in the form: "Art-ID\0From\0Date\0Subject"
# Change this if using C-News/INN or NNTP!
sub fetch_articlelist {
my $g = shift; # instantiated CGI object
my $g_id = shift; # Numerical ID of the selected group
my (%articles, @retval, $fname_summary, $key);
# sanity checks to prevent a ../../etc/passwd hack
$g_id =~ s/\D//g;
# connect to the article database of the group with the ID $g_id:
$fname_summary = $SPOOLDIR . "/" . $g_id . "/" . $ARTICLEDESCR;
tie (%articles, 'SDBM_File', $fname_summary, O_RDWR | O_CREAT, 0600)
or wf_error($g, "can't tie() to summary $fname_summary: $!");
# compose the output list
@retval = ();
foreach $key (sort {$a <=> $b} keys %articles) {
push(@retval, "$key\0" . $articles{$key});
}
untie(%articles);
return @retval;
}
# copyright_screen() prints a screenful of copyright conditions
# for the wf program.
sub copyright_screen {
my $g = shift; # instantiated CGI object.
my $WF_COPYRIGHT_STRING = <<'END_OF_COPYRIGHT';
wf is Copyright (C) 1998 by Farid Hajji /address.html
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-------------------------------------------------------------------------
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
675 Mass Ave, Cambridge, MA 02139, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble:
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it in
new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software,
and (2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a
notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program",
below, refers to any such program or work, and a "work based on
the Program" means either the Program or any derivative work under
copyright law: that is to say, a work containing the Program or a
portion of it, either verbatim or with modifications and/or
translated into another language. (Hereinafter, translation is
included without limitation in the term "modification".) Each
licensee is addressed as "you".
Activities other than copying, distribution and modification are
not covered by this License; they are outside its scope. The act
of running the Program is not restricted, and the output from the
Program is covered only if its contents constitute a work based on
the Program (independent of having been made by running the
Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any
warranty; and give any other recipients of the Program a copy of
this License along with the Program.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange
for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a. You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b. You must cause any work that you distribute or publish, that
in whole or in part contains or is derived from the Program
or any part thereof, to be licensed as a whole at no charge
to all third parties under the terms of this License.
c. If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display
an announcement including an appropriate copyright notice and
a notice that there is no warranty (or else, saying that you
provide a warranty) and that users may redistribute the
program under these conditions, and telling the user how to
view a copy of this License. (Exception: if the Program
itself is interactive but does not normally print such an
announcement, your work based on the Program is not required
to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the
Program, and can be reasonably considered independent and separate
works in themselves, then this License, and its terms, do not
apply to those sections when you distribute them as separate
works. But when you distribute the same sections as part of a
whole which is a work based on the Program, the distribution of
the whole must be on the terms of this License, whose permissions
for other licensees extend to the entire whole, and thus to each
and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or
contest your rights to work written entirely by you; rather, the
intent is to exercise the right to control the distribution of
derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the
Program with the Program (or with a work based on the Program) on
a volume of a storage or distribution medium does not bring the
other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms
of Sections 1 and 2 above provided that you also do one of the
following:
a. Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of
Sections 1 and 2 above on a medium customarily used for
software interchange; or,
b. Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange; or,
c. Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with
such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete
source code means all the source code for all modules it contains,
plus any associated interface definition files, plus the scripts
used to control compilation and installation of the executable.
However, as a special exception, the source code distributed need
not include anything that is normally distributed (in either
source or binary form) with the major components (compiler,
kernel, and so on) of the operating system on which the executable
runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this
License. However, parties who have received copies, or rights,
from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify
or distribute the Program or its derivative works. These actions
are prohibited by law if you do not accept this License.
Therefore, by modifying or distributing the Program (or any work
based on the Program), you indicate your acceptance of this
License to do so, and all its terms and conditions for copying,
distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program
subject to these terms and conditions. You may not impose any
further restrictions on the recipients' exercise of the rights
granted herein. You are not responsible for enforcing compliance
by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent
issues), conditions are imposed on you (whether by court order,
agreement or otherwise) that contradict the conditions of this
License, they do not excuse you from the conditions of this
License. If you cannot distribute so as to satisfy simultaneously
your obligations under this License and any other pertinent
obligations, then as a consequence you may not distribute the
Program at all. For example, if a patent license would not permit
royalty-free redistribution of the Program by all those who
receive copies directly or indirectly through you, then the only
way you could satisfy both it and this License would be to refrain
entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable
under any particular circumstance, the balance of the section is
intended to apply and the section as a whole is intended to apply
in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of
any such claims; this section has the sole purpose of protecting
the integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is
willing to distribute software through any other system and a
licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed
to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces,
the original copyright holder who places the Program under this
License may add an explicit geographical distribution limitation
excluding those countries, so that distribution is permitted only
in or among countries not thus excluded. In such case, this
License incorporates the limitation as if written in the body of
this License.
9. The Free Software Foundation may publish revised and/or new
versions of the General Public License from time to time. Such
new versions will be similar in spirit to the present version, but
may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies a version number of this License which applies
to it and "any later version", you have the option of following
the terms and conditions either of that version or of any later
version published by the Free Software Foundation. If the Program
does not specify a version number of this License, you may choose
any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the
author to ask for permission. For software which is copyrighted
by the Free Software Foundation, write to the Free Software
Foundation; we sometimes make exceptions for this. Our decision
will be guided by the two goals of preserving the free status of
all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
END_OF_COPYRIGHT
print
$g->header(),
&wf_start_html($g, "WF Copyright conditions"), "\n",
$g->h1("WF copyright conditions"),
$g->font({ "-color" => $ART_COLOR,
"-face" => $ART_FACE,
"-size" => "+0" },
$g->pre(&wf_escapeHTML($WF_COPYRIGHT_STRING))),
$g->hr,
$g->a({"-href" => $g->url()},
"Back to WF's Home"), "\n";
print
&wf_end_html($g);
}
# wf_escapeHTML() translates all html-special chars into their equivalent.
# shamelessly borrowed from internal CGI::escapeHTML() of CGI.pm
sub wf_escapeHTML {
my $toencode = shift; # non HTML-escaped string
$toencode =~ s/&/&/g;
$toencode =~ s/\"/"/g;
$toencode =~ s/>/>/g;
$toencode =~ s/</</g;
# add here other encodings if you wish (e.g. ü ... for german text)
return $toencode;
}
__END__
=head1 NAME
wf -- A simple Web-Forum <WF> CGI-Script
=head1 USAGE
wf is intended to be called from a Web server over a CGI/1.0
compliant interface.
=head1 DESCRIPTION
wf is a web-based tool that simulates many blackboards called groups.
Users are allowed to post articles to groups and can also read
the articles already posted and stored in each group.
Users start by identifying themselves to wf by specifying a
pseudonym termed "alias" or "user-id". Existing aliases are
protected by password and are only usable by users knowing
that specific password. New aliases can also be created on-the-fly
if the user specifies an unused alias and a new password.
Upon receiving a correct alias/password combination, wf generates
a random session cookie that will expire in $COOKIE_TTL. This
session cookie is stored on the server-side, where it is associated
with the chosen alias and is also sent back to the browser. The
browser is expected to accept and store this cookie as well as to
send it transparently as part of the HTTP headers for each subsequent
request to wf.
Each following request to wf must be accompanied by a *valid* cookie.
wf checks the presence and validity of the cookie before allowing
the user to perform any action other than registering an alias. If
the cookie were missing, invalid or expired, wf would present the
user the same registration form she used to acquire her
previous cookie. If the cookie is valid, wf recognizes the alias
from it's server-side association and knows to whom it talks.
The default action of wf is to send a welcome screen to the user.
This welcome screen echoes the alias belonging to the session
cookie, presents a clickable list of active groups and
a text field allowing the user to create a new group on-the-fly.
For those using a PC in a PC-Pool, an option to switch to another
alias is presented as well. This last options is useful in the
case the previous cookie had not expired yet.
The welcome screen is the center of all activities in wf. Unless
the session cookie expires, the user can always return back here.
Upon selecting an existing group, the user is presented with the
group's contents in an article list page. The selected group
contains a series of articles the current user or other users
posted to. The articles are presented in tabular overview consiting
for each article of the poster's alias name, the clickable
subject line as well as the posting timestamp.
The article list page also contains a text field and a Compose
button that will, when depressed, present the user an article
entry from.
In the article list page, the user can select a specific article
by clicking on it's subject line. wf retrieves the article from
it's filesystem store and displays it in an article display page.
The article consists of a header (From:, Newsgroups:, Date:
and Subject:) followed by an empty line, followed by the body
of the message. Articles are in this sense compliant to
USENET news articles.
The article display page also presents the user with the possibility
to reply to that specific article, to return to the article list page
or to return to WF's welcome page (WF's Home).
Should the user either select to reply to an existing article
(from the article display page) or to post a new article
(from the article list page), an article composition form is
presented.
The article compositon form is already partially filled with
information wf had available. The header is almost complete.
From the header, only the subject field is editable. It is
filled with the contents of the text field from the article
list page if the user choose to post a new article or
filled with the contents of the subject of the article
being replied to, prepended with a "Re: " if the user
decided to reply to an existing article. No more that one
consecutive "Re: " is automatically generated though. In both
cases, the contents of the subject textfield can be overridden.
The article composition from also contains a large textarea
field. The user is expected to enter the body of the article
in this textarea field. The textarea is initally set to
the contents of $DFL_BODY if the user opted to post a new article,
or to quoted contents of the article's body being replied to.
The whole old contents are quoted with "> " prepended to each line.
The user is supposed to trim the quotations as necessary and
add it's own text WITHOUT "> " quotes. wf doesn't check for
this though.
The article is actually posted as soon as the user depresses
the "Send" button. A posted article cannot be subsequentially
modified or removed by wf's users. They remain in the $SPOOLDIR
as long as the system administrator of the machine decides.
It is the responsability of the system administrator to run
a cron(1) job that periodically expires (i.e. removes) articles
that are older than a configurable threshold and to also
expire empty old groups.
=head1 INSTALLATION
Install wf in a CGI directory of the Web-Server (Apache Users:
see ScriptAlias). wf must be executable by the HTTP user executing
CGI Scripts. Create $SPOOLDIR and make it readable, writable and
executable by the HTTP user. Install additional required software
where necessary (see section REQUIRED SOFTWARE below).
Finally add a link to wf in some other page.
=head1 CONFIGURATION
The wf program consists of a single perl script which carries
a CONFIGURATION SECTION at its very beginning.
Other parts of the file are not considered configurable and
should probably not be touched.
The following parameters can or should be customized:
=over 4
=item $SPOOLDIR
The variable $SPOOLDIR sets the top directory for the spooling
area of the active or generated groups, the articles belonging
to these groups and the control directory containing the User-,
Cookie- and Group-Databases.
The variable $SPOOLDIR may possibly be the only parameter that
needs to be adapted to local requirements. Set this variable
to the absolute pathname of a directory on the server's machine.
This directory (like /var/wf) must be readable, executable and
writable by the user running the <wf> script, typically the
http user.
Other subdirectories and control directories of $SPOOLDIR
are created automatically the first time they are needed.
The directory hierarchy under $SPOOLDIR MUST reside on the same
machine than the one executing the wf CGI script! The reason
for this is that wf uses file locking on the .summary files
and group description database to protect it's data structures
while posting an article or adding a new group. File locking
is performed internally by the flock() function, acquiring
an exclusive lock on these files. Although flock() is
generally implemented in terms of the fcntl() call which
is NFS aware, not all OS are that forgiving on NFS locks.
=item $COOKIE_TTL
wf establishes a session with remote browsers by means of
HTTP-level cookies. When wf misses a valid cookie, it sends
a user registration form to the browser. Random generated
cookies are stored both on the server side (in the SDBM-File
specified by $COOKIEDB) as well as on the browser's side.
Cookies authorize the user sending them to use a specific
alias name. They should not however remain valid for a
too long time. PC-Pools are an example of an environment,
where cookies could be "stolen" when another user uses
the same client machine. For this reason, cookies "expire"
after a specified time slice.
The time in which a cookie is valid is specified
in $COOKIE_TTL. It is typically set to "+1h", requesting the user to
reregister her alias every hour. Reducing this value
increases the security but requires the user to reregister
more frequently. Increasing it requires less reregistrations,
but decreses the protection of that specific alias.
=item $AUTHOR
Set this to the email address of the local maintainer of wf at
your site! This information is added to each HTML document returned
by wf in it's <HEAD> section as LINK REV=MADE and can be used
in identifying the person responsible for a Web page.
=item $BGCOLOR
Set this to the desired backgroud color of all pages generated by
wf. Please note that not all colors are always available to all
browsers. Don't forget to change the other color attributes as
well!
=item $TEXTCOLOR
Set this to the color of normal text of all pages generated by wf.
The caveats of $BGCOLOR hold true here too.
=item $ART_COLOR
Set this to the color of the article text being displayed
in the article display page.
=item $ART_FACE
Set this to the typeface (font) of the article text being displayed
in the article display page. It may be a good idea to choose
a non-proportional font like "courier" here, since the user
may have formatted her input based on this assumption.
=item $ART_SIZE
Set this to the size modification parameter of the font used
in the article text being displayed in the article display page.
=item $AL_F_COLOR, $AL_F_FACE, $AL_F_SIZE
Color, typeface and size of the "Author" Entry in the list of articles
=item $AL_D_COLOR, $AL_D_FACE, $AL_D_SIZE
Color, typeface and size of the "Date" entry in the list of articles
=item $ERR_COLOR
Set this to the color of the error message. Be sure that this color
matches the selected $BGCOLOR.
=item $LINK_COLOR, $VLINK_COLOR, $ALINK_COLOR
Set these to the colors of the new hyperlinks, visited hyperlinks
and active hyperlinks respectively.
The caveats in $BGCOLOR hold true here too.
=item $DFL_BODY
Set this to a default text that will be displayed in the textarea
of the article composition form when posting a new article.
This variable may for example be empty or contain a small
text like "Your message here...". It is probably better
to set $DFL_BODY to the empty string.
=item $DFL_SUBJECT
Set this to a default subject line. This value will be used if the
user did not submit a subject line when posting an article.
$DFL_SUBJECT should be non-empty, so that articles without subject
remain clickable in the article list.
=item $DFL_GEMPTY
Set this to the text that should be displayed, if a group doesn't
have any articles (yet).
=item $CPY_IDCOL
Set this to the color of the RCS Version string of wf.
This should match $BGCOLOR.
=item $CPY_COLOR
Set this to the color of the Copyright String that will be placed
at the end of each wf-generated HTML page. Choose this color so,
that it is still visible when used with $BGCOLOR. THE COPYRIGHT
STRING *MUST* REMAIN VISIBLE!
=back
=head1 REQUIRED SOFTWARE
As a perl script, wf requires the following components
to work:
=over 4
=item Perl 5
wf is a perl 5 script. It won't even compile with any earlier
version of perl. wf was developed with perl 5_004_04. wf assumes
that the perl 5 executable is installed in
/usr/local/bin/perl, otherwise change the she-bang at the beginning
of the script.
=item CGI.pm
wf uses CGI.pm to interact with the CGI/1.0 interface. It also
uses this freely available module for producing HTML output.
wf was developed with CGI.pm version 2.42 and accompanying
CGI::* Modules. You can freely obtain CGI.pm from CPAN.
See http://www.perl.com/ for more details.
=item RFC2109-compliant browsers
wf uses HTTP-Cookies as specified in RFC-2109.
The web-browsers using wf MUST accept, store and return these cookies.
Netscape browsers are RFC-2109 aware. It may be necessary though,
to configure the browser to actually accept, store and return
these HTTP-Cookies.
wf needs per browser (i.e. user) only one cookie named WF-COOKIE
containing a random wf-generated string. It is aware not to overflow
the local cookie database with crap.
wf doesn't need JavaScript or Java on the browser. It does however
expect a HTML-3 compliant browser to produce a decent display of
tables.
wf in it's current implementation also doesn't need nor use frames.
=back
=head1 KNOWN BUGS
wf is just a demo of a web forum system. As such, it probably
contains a lot of bugs. Some of the bugs include:
=over 4
=item
Cookies expire only on the client side. The server-side cookie-DB
should be regularly cleaned up, possibly by means of a cron(1)-job.
=item
Articles without Subject: line should not be allowed. Eventhough
it is currently possible to post articles with an empty subject
line, doing so is not recommended. Since the articles are typically
retrieved by clicking on the subject line, an empty line means
that there would be nothing to click at! To avoid these problems,
set $DFL_SUBJECT to a non-empty string.
=item
Empty groups should be expired after a preset time.
This should probably be done by the means of a cron(1)-job.
=item
Old articles should probably be expired after a preset time.
This should probably be done by the means of a cron(1)-job.
=item
The registration of a user alias is currently an anonymous process.
Although this may be positive in the sense that it encourages
free speech, it can be dangerous for service providers NOT to
keep a log of real user id's for legal reasons.
The registration should probably ask for user's e-mail address,
check this address via MX-Records and SMTP VRFY and/or send an
authorizing password to the requesting user via e-mail only.
It may be also wise to keep the IP-Address of the requesting browser
(or proxy) together with each article posted.
The author of 'wf' doesn't encourage these restrictive measures
and would prefer admins to stick to the current anonymous solution
of a self-organizing responsible community.
=back
=head1 IMPLEMENTATION ALTERNATIVES
Implementing wf could have been done using one of the following three
alternatives:
=over 4
=item Filesystem
The solution adopted for 'wf' is a plain old filesystem approach.
Groups are associated to UNIX directories, and articles are
saved in single files within the corresponding group directories.
A minimal amount of overhead had to be added in the form of
SDBM-Files containing overview Information of Groups and Articles.
That was mainly done for efficiency's sake.
The filesystem approach also presents another advantage over the
other two methods: One can easily implement a search function
over the contents of all articles by indexing all the files
from the $SPOOLDIR. Just use freely available indexing tools
like freeWAIS-sf and SFgate to index $SPOOLDIR.
Expiring groups or articles is left to the administrator of the
machine hosting $SPOOLDIR. These chores should probably be cron(1)-jobs.
The programs for expiring articles and groups are *not* provided with wf.
You'll have to write them yourself. Sorry!
=item C-News or INN
The management of groups and articles closely match the organization
of newsgroups and messages of existing systems like C-News or INN.
It would have been possible to use C-News or INN for the storage
and retrieval of articles and for the creation of new groups.
The main advantage over the simple filesystem solution would have
been an integration with other news readers, as well as
automatic expiration of articles.
The C-News or INN solutions were not chosen in wf for the simple
practical reason, that not every machine running a web server does currently
have C-News of INN installed (and that is not always trivial to do!
Just think about the site dependent location of the various directories.
wf would have to be configured accordingly or dynamically determine
the actual site configuration of the underlying news system).
=item NNTP Server
A step further than the C-News or INN solutions would have been
to post new articles on a remote NNTP news server and to
retrieve a list of groups or single articles from that same news
server. wf would have been a web based news reader (front-end?).
Although elegant, the NNTP-Server approach had to be rejected for
several reasons:
=over 4
=item
Posted articles generally don't show up immediately in their
corresponding newsgroups, but only after a latency period ranging
from a few minutes to many hours depending on the site configuration
of the remote news system. A nearly interactive "conversation" with
other users whould have been impossible.
=item
Adding new groups falls in the domain of a News-Administrator,
not of NNTP-Clients. It would have been impossible to add new
groups on-the-fly. The only work-around would have been to request
the creation of a new group by sending a machine-readable e-mail
to the news-admin or to an "auto-generate-group@somewhere.com"
e-mail address. This is clearly too cumbersome to do.
=back
=back
=head1 AUTHORS
wf was originally written by Farid Hajji /address.html
Suggestions, bug reports and fixes as well as improvements
are always welcome and appreciated.
=head1 COPYRIGHT
wf is Copyright (C) 1998 by Farid Hajji /address.html
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
=cut
[Prev] [Up] [Relevant Chapter] [Next]
[Alte Quelle]
| Last modified: $Date: 2006/05/18 12:55:49 $ FH. Search :: Sitemap :: Disclaimer :: Copyright :: Privacy |
|