#!/usr/bin/perl -T
#  register.cgi  --  Process a new user subscription requests.
use CGI;
use lib '/usr/local/apache/lib';
use AuthDB;

my $inputform = '<HTML><BODY> <H1>New subscriber registration</H1>

<FORM ACTION="register.cgi" method="post">

account name <INPUT TYPE="text" NAME="name"  VALUE="$form->{name}">  <BR>
   first name <INPUT TYPE="text" NAME="first" VALUE="$form->{first}"> <BR>
   last name <INPUT TYPE="text" NAME="last"  VALUE="$form->{last}">  <BR>
       email <INPUT TYPE="text" NAME="email" VALUE="$form->{email}"> <BR>
    password <INPUT TYPE="password" NAME="pass_1"> <BR>
      confirm <INPUT TYPE="password" NAME="pass_2"> <BR>

<P><INPUT TYPE="SUBMIT" VALUE="Submit request"></FORM></BODY></HTML>';

my $thanksform = '<HTML><BODY> <H2>Thanks, $form->{"first"}</H2>

    You can now access the 
      <a href="/members/update.cgi">subscriber area.</a>


my $form;

unless ($ENV{"CONTENT_LENGTH"}) {
# No input? We're being asked to provide the form.

} else {
    my $msg = '';

# If any fields are empty or incorrect,
# send a resend the form with more instructions.

    $q = new CGI;
    $form = $q->Vars;

    if (create_account() != 0) {
    # Something was wrong, send more instructions.

    } else {

sub create_account {
    my $error = 0;
    my $username;

    $form->{"name"} =~ s/[^\w]//g; # delete funny characters
    $username = $form->{"name"};

    # Check to see if there is already a user registered with this name.
    if (authdb_get($username)) {
      $msg .= "This account name is already in use, choose another.<BR>\n";

    # Check to make sure the rest of the fields are filled in, too.
    foreach (sort keys %$form) { 
      $error++ unless $form->{$_}; 

    if ($error) {
      $msg .= "You must enter something in each field.
               Fill in the rest of the form and re-submit it.<BR>\n";

    } elsif ($form->{"pass_1"} ne $form->{"pass_2"}) {
      $msg .= "Your password fields did not match;
               you have to enter the same password in both fields. <BR>\n";

    if (!$error) {
      # Everything is okay; write the new record.

      my $cryptedpass = crypt($form->{"pass_1"}, salt());

      delete $form->{"name"};   # storing this would be redundant
      delete $form->{"pass_1"}; # don't record plaintext password
      delete $form->{"pass_2"};

      authdb_put($username, $cryptedpass, %$form);

    return $error;

#  Given a string containing an HTML form,
#  eval it to fill in the fields, and send it.

sub send_page {
    my $page = shift;
    $page =~ s/([\"\@])/\\$1/g; # escape quotes and @ signs
    print "Content-type: text/html\n\n" . eval "\"$page\"";