#!/usr/local/bin/perl5.00502

# Copyright (c) 1998, 1999               The RIPE NCC
#
# All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of the author not be
# used in advertising or publicity pertaining to distribution of the
# software without specific, written prior permission.
#
# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS; IN NO EVENT SHALL
# AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
# AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#------------------------------------------------------------------------------
# Filename          : web141.pl.cgi
# Version           : 1.0.1
# Purpose           : Allow user to generate a plain text RIPE 141 address
# 	request form, and have it syntax checked
# Author            : Maldwyn GT Morris <maldwyn@ripe.net>
# Date              : 19990210
# Description       : Takes input from web form. One button will put this data
# 	into a plain text RIPE 141 form, ready for email to RIPE NCC. Another
# 	button will syntax check this data using the RIPE NCC syntax checker,
# 	autohm.
# Language Version  : Tested with Perl 5.00502
# OSs Tested        : BSDI BSD/OS 3.1 - No knownOS dependencies.
# Command Line      : None
# Input Files       : CGI,
#   cats standard header file: header.html
#   points to form explanations in: explanations.html
#   points to ripe 142 doc at: ripe-142.html
# Output Files      : stdout, temp file for autohm to read, error file for
# 	autohm output
# External Programs : whois, autohm
# Problems          : can't come back to same place on form when press
#	add or delete line buttons
# To Do             : 
# Comments          : Simple but long-winded
# 					: Disclaimer: http://winn.com/bs/disclaimer.html
#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
# Module Change History
# Author            : MGTM
# Date              : 19990223
# Changes           : 
# 	Make spaces in template headers consistent, inserted missing text
#       ( 'TEMPLATE' ! ) and other minor syntax errors
# 	Made Notify, MntBy, Changed fields allow wider input
#   Tidied handling of Request Overview multi-line fields
# Comments          : 
#------------------------------------------------------------------------------

# tested with perl 5.00502
# syntax checked with perl 5.00307
require 5;

# unbuffer stdout
$| = 1;
$ENV{'PATH'} = "/bin:/usr/bin:/usr/ucb";

# always !
use strict;

# for the form
use CGI;

# resists DOS by large posts
$CGI::POST_MAX=1024 * 1000;  	# max 1000K posts
$CGI::DISABLE_UPLOADS = 1;  	# no file uploads
       

#------------------------------------------------------------------------------
# globals 

my $debug;		# global flag
# $debug=1;  	# DEBUG

my $query = new CGI;	# global object

my $myself;		# global pointer to this form

my $goto;	# used to set # part of url to jump back to the
			# section where we added or deleted a line

my $errors;		# global error messages

my ( $MAXLINES ) = 5;	# max amount lines

my ( $title ) = 'European IP Address Space Request Syntax Checker';
if ( $debug ) { $title .= ' - TEST'; }

# array of filled-in usages
my ( @usages );

# constants
# !! CHANGE THESE TO MATCH YOUR SITE !!

# RIPE NCC standard HTML header - has a <BODY> and a <BLOCKQUOTE> in it
my $STANDARDHEADERPATH = '/.../standard.html';

my $RIPE141URL = 'http://.../ripe-141.html';
my $RIPE142URL = 'http://.../ripe-142.html';
my $TEMPDIR = '/.../tmp';
my $AUTOHMPATH = '/.../auto-hmweb.pl';
my $WHOISPATH = '/.../whois';

my $WHOIS_NOTFOUND_REG = 'No\s+entries\s+found';		# INSENSITIVE
my $FATAL_ERROR_EXIT_TXT = '-=- EXITED WITH FATAL ERROR -=-';   # autohm error

#------------------------------------------------------------------------------
# List of routines
#
# Major ones :
#
# main			: look at query url and decide what to do based on params set:
#	- reload a filled in form
#	- add a line to one of the multi-line entries
#	- delete a line from one of the multi-line entries
#	- convert request to plain text
#	- run syntax checks on request
#	else just show the form
#
# displayPage	: form and show the HTML of the page
# doCall		: send plain text of page to autohm and show results 
# showPlainText : show form data as plain text RIPE 141 form
# 
# Minor Ones :
#
# header, footer	: print the top and bottom of the form
# showFormControls	: print the submit and reset buttons
# getparam		: get value of a query param or return '' - not undef
# moveField		: move a multi-line entry field
# dprint		: show debug message if debugging
# error			: show error message in HTML
#


#------------------------------------------------------------------------------
# Main routine
# Purpose           : shows web form or acts on it
# Side Effects      : none
# Comments          : too long

{
# get url called with
my ( $my_url ) = $query->url(-path_info=>1,-query=>1);

# if any params, handle form
if ( $query->param )
	# handle form
	{
	my ( $reload ) = $query->param( -name=>'reload' );
	my ( $convert ) = $query->param( -name=>'Convert' );

	my ( $addUsage ) = $query->param( -name=>'AddUsageLine' );
	my ( $deleteUsage ) = $query->param( -name=>'DeleteUsageLine' );

	my ( $addRequest ) = $query->param( -name=>'AddRequestLine' );
	my ( $deleteRequest ) = $query->param( -name=>'DeleteRequestLine' );

	my ( $addPerson ) = $query->param( -name=>'AddPersonLine' );
	my ( $deletePerson ) = $query->param( -name=>'DeletePersonLine' );

	my ( $addNetwork ) = $query->param( -name=>'AddNetworkLine' );
	my ( $deleteNetwork ) = $query->param( -name=>'DeleteNetworkLine' );

	# what are we doing here ?

	if ( defined $reload ) 
		# reload is set when we want to go back to *filled in* form
		{
		# debug - show url called with
		my $extra;
		if ( $debug )
			{
			$extra = "$my_url<br>\n";
			}
		&header( $extra);

		displayPage( $query, '' );

		&footer();
		}
	elsif ( defined $addUsage ) 
		# add usage line
		{
		# debug - show url called with
		my $extra;
		if ( $debug )
			{
			$extra = "Add $my_url<br>\nAdding usage line.<br>\n";
			}
		&header( $extra);

		my $addUsageLine;
                if ( $addUsage =~ /^Add\sUsage\sLine\s(\d+)$/ )
                        {
                        $addUsageLine = $1;
                        }
                else
                        {
                        error( "addUsage = $addUsage ? so don\'t understand self URL $my_url" );
                        return;
			}

		# new number of lines
		$query->param( "UsageCount", $addUsageLine );

		dprint( "<br>addUsage = $addUsage, addLine = UsageCount = $addUsageLine <br>\n" );

		# show it
		displayPage( $query, '' );

		&footer();
		}
	elsif ( defined $deleteUsage ) 
		# delete usage line
		{
		# debug - show url called with
		my $extra;
		if ( $debug )
			{
			$extra = "$my_url<br>\n";
			}
		&header( $extra);

		my $deleteUsageLine;
		if ( $deleteUsage =~ /^Delete\sUsage\sLine\s(\d+)$/ )
			{
			$deleteUsageLine = $1;
			}
		else
			{
			error( "deleteUsage = $deleteUsage ? so don\'t understand self URL $my_url" ); 
			return;
			}

		# how many lines now ?
		my $lastLine = $query->param( "UsageCount" );

		dprint( "<br>deleteUsage = $deleteUsageLine lastLine = $lastLine<br>\n" );

		# remove line by moving next ones down over it	
		my $line;
		for ( $line = $deleteUsageLine; $line<$lastLine; $line++ ) 
			{
			# move the fields down by one line
			moveField( ( "Prefix" . ($line + 1) ), ( "Prefix" . ($line) ) );
			moveField( ( "Mask" . ($line + 1) ), ( "Mask" . ($line) ) );
			moveField( ( "Size" . ($line + 1) ), ( "Size" . ($line) ) );
			moveField( ( "Current" . ($line + 1) ), ( "Current" . ($line) ) );
			moveField( ( "OneYear" . ($line + 1) ), ( "OneYear" . ($line) ) );
			moveField( ( "TwoYear" . ($line + 1) ), ( "TwoYear" . ($line) ) );
			moveField( ( "Description" . ($line + 1) ), ( "Description" . ($line) ) );
			}
			
		# now set last line one less
		$query->param( "UsageCount", $lastLine-1 );


		# show it
		displayPage( $query, '' );

		&footer();
		}
	elsif ( defined $addRequest ) 
		# add request line
		{
		&header();

		my $addRequestLine;
                if ( $addRequest =~ /^Add\sRequest\sLine\s(\d+)$/ )
                        {
                        $addRequestLine = $1;
                        }
                else
                        {
                        error( "addRequest = $addRequest ? so don\'t understand self URL $my_url" );
                        return;
			}

		# new number of lines
		$query->param( "RequestCount", $addRequestLine );

		dprint( "<br>addRequest = $addRequest, addLine = RequestCount = $addRequestLine <br>\n" );

		# show it
		displayPage( $query, '' );

		&footer();
		}
	elsif ( defined $deleteRequest ) 
		# delete request line
		{
		&header();

		my $deleteRequestLine;
		if ( $deleteRequest =~ /^Delete\sRequest\sLine\s(\d+)$/ )
			{
			$deleteRequestLine = $1;
			}
		else
			{
			error( "deleteRequest = $deleteRequest ? so don\'t understand self URL $my_url" ); 
			return;
			}

		# how many lines now ?
		my $lastLine = $query->param( "RequestCount" );

		dprint( "<br>deleteRequest = $deleteRequestLine lastLine = $lastLine<br>\n" );

		# remove line by moving next ones down over it	
		my $line;
		for ( $line = $deleteRequestLine; $line<$lastLine; $line++ ) 
			{
			# move the fields down by one line
			moveField( ( "RequestPrefix" . ($line + 1) ), ( "RequestPrefix" . ($line) ) );
			moveField( ( "RequestMask" . ($line + 1) ), ( "RequestMask" . ($line) ) );
			moveField( ( "RequestSize" . ($line + 1) ), ( "RequestSize" . ($line) ) );
			moveField( ( "RequestImmediate" . ($line + 1) ), ( "RequestImmediate" . ($line) ) );
			moveField( ( "RequestOneYear" . ($line + 1) ), ( "RequestOneYear" . ($line) ) );
			moveField( ( "RequestTwoYear" . ($line + 1) ), ( "RequestTwoYear" . ($line) ) );
			moveField( ( "RequestDescription" . ($line + 1) ), ( "RequestDescription" . ($line) ) );
			}
			
		# now set last line one less
		$query->param( "RequestCount", $lastLine-1 );

		# show it
		displayPage( $query, '' );

		&footer();
		}
	elsif ( defined $addPerson ) 
		# add person line
		{
		# debug - show url called with
		my $extra;
		if ( $debug )
			{
			$extra = "AddP $my_url<br>\nAdding person line.<br>\n";
			}
		&header( $extra);

		my $addPersonLine;
                if ( $addPerson =~ /^Add\sPerson\sLine\s(\d+)$/ )
                        {
                        $addPersonLine = $1;
                        }
                else
                        {
                        error( "addPerson = $addPerson ? so don\'t understand self URL $my_url" );
                        return;
			}

		# new number of lines
		$query->param( "PersonCount", $addPersonLine );

		dprint( "<br>addPerson = $addPerson, addLine = PersonCount = $addPersonLine <br>\n" );

		# show it
		displayPage( $query, '' );

		&footer();
		}
	elsif ( defined $deletePerson ) 
		# delete usage line
		{
		# debug - show url called with
		my $extra;
		if ( $debug )
			{
			$extra = "DeleteP $my_url<br>\n";
			}
		&header( $extra);

		my $deletePersonLine;
		if ( $deletePerson =~ /^Delete\sPerson\sLine\s(\d+)$/ )
			{
			$deletePersonLine = $1;
			}
		else
			{
			error( "deletePerson = $deletePerson ? so don\'t understand self URL $my_url" ); 
			return;
			}

		# how many lines now ?
		my $lastLine = $query->param( "PersonCount" );

		dprint( "<br>deletePerson = $deletePersonLine lastLine = $lastLine<br>\n" );

		# remove line by moving next ones down over it	
		my $line;
		for ( $line = $deletePersonLine; $line<$lastLine; $line++ ) 
			{
			# move fields down by one line

			moveField( ( "PersonName" . ($line + 1) ), ( "PersonName" . ($line) ) );
			moveField( ( "PersonAddress" . ($line + 1) ), ( "PersonAddress" . ($line) ) );
			moveField( ( "PersonEmail" . ($line + 1) ), ( "PersonEmail" . ($line) ) );
			moveField( ( "PersonPhone" . ($line + 1) ), ( "PersonPhone" . ($line) ) );
			moveField( ( "PersonFax" . ($line + 1) ), ( "PersonFax" . ($line) ) );
			moveField( ( "PersonNicHdl" . ($line + 1) ), ( "PersonNicHdl" . ($line) ) );
			moveField( ( "PersonNotify" . ($line + 1) ), ( "PersonNotify" . ($line) ) );
			moveField( ( "PersonMntBy" . ($line + 1) ), ( "PersonMntBy" . ($line) ) );
			moveField( ( "PersonChanged" . ($line + 1) ), ( "PersonChanged" . ($line) ) );
			}
			
		# now set last line one less
		$query->param( "PersonCount", $lastLine-1 );

		# show it
		displayPage( $query, '' );

		&footer();
		}
	elsif ( defined $addNetwork ) 
		# add person line
		{
		# debug - show url called with
		my $extra;
		if ( $debug )
			{
			$extra = "AddN $my_url<br>\nAdding person line.<br>\n";
			}
		&header( $extra);

		my $addNetworkLine;
                if ( $addNetwork =~ /^Add\sNetwork\sLine\s(\d+)$/ )
                        {
                        $addNetworkLine = $1;
                        }
                else
                        {
                        error( "addNetwork = $addNetwork ? so don\'t understand self URL $my_url" );
                        return;
			}

		# new number of lines
		$query->param( "NetworkCount", $addNetworkLine );

		dprint( "<br>addNetwork = $addNetwork, addLine = NetworkCount = $addNetworkLine <br>\n" );

		# show it
		displayPage( $query, '' );

		&footer();
		}
	elsif ( defined $deleteNetwork ) 
		# delete usage line
		{
		# debug - show url called with
		my $extra;
		if ( $debug )
			{
			$extra = "DeleteN $my_url<br>\n";
			}
		&header( $extra);

		my $deleteNetworkLine;
		if ( $deleteNetwork =~ /^Delete\sNetwork\sLine\s(\d+)$/ )
			{
			$deleteNetworkLine = $1;
			}
		else
			{
			error( "deleteNetwork = $deleteNetwork ? so don\'t understand self URL $my_url" ); 
			return;
			}

		# how many lines now ?
		my $lastLine = $query->param( "NetworkCount" );

		dprint( "<br>deleteNetwork = $deleteNetworkLine lastLine = $lastLine<br>\n" );

		# remove line by moving next ones down over it	
		my $line;
		for ( $line = $deleteNetworkLine; $line<$lastLine; $line++ ) 
			{
			moveField( ( "NetName" . ($line + 1) ), ( "NetName" . ($line) ) );
			moveField( ( "NetDescription" . ($line + 1) ), ( "NetDescription" . ($line) ) );
			moveField( ( "NetCountry" . ($line + 1) ), ( "NetCountry" . ($line) ) );
			moveField( ( "NetAdminC" . ($line + 1) ), ( "NetAdminC" . ($line) ) );
			moveField( ( "NetTechC" . ($line + 1) ), ( "NetTechC" . ($line) ) );
			moveField( ( "NetNotify" . ($line + 1) ), ( "NetNotify" . ($line) ) );
			moveField( ( "NetMntBy" . ($line + 1) ), ( "NetMntBy" . ($line) ) );
			#moveField( ( "NetChanged" . ($line + 1) ), ( "NetChanged" . ($line) ) );
	
			}
			
		# now set last line one less
		$query->param( "NetworkCount", $lastLine-1 );

		# show it
		displayPage( $query, '' );

		&footer();
		}
	elsif ( defined $convert )
		# convert to plain text
		{
		# syntax checks not done
		my $fh = \*STDOUT;
		showPlainText( $fh, $query, 0 );
		}
	else
		# submit
		# form was submitted - want to handle form
		{
		$query->param( 'reload', '1' );
		$myself = $query->self_url;

		# debug - show url called with
		my $extra;
		if ( $debug )
			{
			$extra = "$my_url<br>\n";
			}
		&header( $extra);

		# handle form input
		&doCall( $query );

		&footer();
		}
	}
else 
	# no params, show form
	{
	# debug - show url called with
	my $extra;
	if ( $debug )
		{
		$extra = "$my_url<br>\n";
		}
	&header( $extra );

	displayPage( $query, '' );

	&footer();
	}

# done
exit( 0 );
}


#------------------------------------------------------------------------------
# page header
sub header 
	{
	my ( $extraText ) = @_;		# ARGS: extra stuff to show or empty

	print $query->header;
#	print $query->start_html(
#		-title => $title,
#		-dtd => '-//W3C//DTD HTML 4.0 Transitional//EN'
#		);

	# do it ourselves as CGI.pm inserts <BODY> as does RIPE header
	print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML>';
	print "\n<HEAD><TITLE> $title </TITLE> </HEAD>\n\n";

	# RIPE standard header
	open ( STDHDR, "<$STANDARDHEADERPATH" )
		or error( "could not open standard header file $STANDARDHEADERPATH." );
	my @standardHeader = <STDHDR>;
	close STDHDR;

	print "@standardHeader\n";

	print "$extraText\n";

	return;
	}


#------------------------------------------------------------------------------
# page footer
sub footer 
	{
	# RIPE standard header has <BLOCKQUOTE>, so
	print "</BLOCKQUOTE>\n";

	print $query->end_html;

	return;
	}


#------------------------------------------------------------------------------
sub showFormControls
	{
	print "<CENTER>";
	print $query->submit( -name=>'Check', -value=>'Syntax Check this Request' );
	print $query->submit( -name=>'Convert', -value=>'Convert this Request to plain text' );
	print $query->reset( -value=>'Reset all the fields' );
	print "</CENTER>";

	return;
	}


#------------------------------------------------------------------------------
# Purpose           : generates web form HTML
# Side Effects      : none
# Comments          : too long

sub displayPage
	{
	my ( $query, $add, %errors ) = @_;

	print "<H2>$title</H2>\n\n";

	print "<P>\n";

	my $oururl = $query->url;

	my ( $addUsage ) = $query->param( -name=>'AddUsageLine' );
	my ( $deleteUsage ) = $query->param( -name=>'DeleteUsageLine' );
	my ( $addRequest ) = $query->param( -name=>'AddRequestLine' );
	my ( $deleteRequest ) = $query->param( -name=>'DeleteRequestLine' );
	my ( $addPerson ) = $query->param( -name=>'AddPersonLine' );
	my ( $deletePerson ) = $query->param( -name=>'DeletePersonLine' );
	my ( $addNetwork ) = $query->param( -name=>'AddNetworkLine' );
	my ( $deleteNetwork ) = $query->param( -name=>'DeleteNetworkLine' );

	if ( $addUsage || $deleteUsage )
		{ $goto = '#USAGE'; }
	elsif ( $addRequest || $deleteRequest )
		{ $goto = '#REQUEST'; }

	print $query->start_form(
		-method=>'POST',
		-action=>"$oururl$goto"
		);

#----

	if ( defined %errors )
		{
                print "<H2><font color=red>Errors were found in your request </font> </H2>"; 
		print "<font color=red>Please correct them and re-submit the form </font>\n"; 
		}

#----

print <<EOINTROTEXT

Use this form to syntax check your IP Address Space Request in <A HREF=\"$RIPE141URL\"> RIPE 141 </A> format or to convert it to formatted plain text with no checking. 
<P>
The RIPE 141 format is explained in <A HREF=\"$RIPE142URL\">RIPE 142</A>
<P>
Note that only syntax checks will be performed and nothing will be done with your request. To actually be given addresses, you must send the plain text version of your request by email to hostmaster\@ripe.net and you must be <A HREF=\"http://www.ripe.net/lir/registries/index.html">registered with RIPE NCC</A> .  Further automatic and human checks must also be passed.
<P>

EOINTROTEXT
;

	showFormControls();

#----
	print "<hr><H2> I. General Information </H2>";
	print "<BLOCKQUOTE>";

	print "<H3> #[ OVERVIEW OF ORGANISATION TEMPLATE ]# </H3> ";
	print "Please fill in a description of your company and what the addresses will be used for.<br>\n";

	print "<A HREF=\"$RIPE142URL#toc6\"> Help with this section </A><br>\n";

	print $query->textarea(
		-name=>'OrganisationDescription',
		-cols=>80,
		-rows=>3,
		-value=>getparam( 'OrganisationDescription' )
		);
	if ( $errors{ 'OrganisationDescription' } )
                {
                print "<TD><font color=red><small>$errors{ 'OrganisationDescription' } </small> </font> </TD>";
                }
	print "<br>\n";

#----
	print "<hr><H3> #[ REQUESTER TEMPLATE ]# </H3> ";

	print "<A HREF=\"$RIPE142URL#toc7\">Help with this section</A><br>\n";

	print "<TABLE>";

	print "<TR>";
	print "<TD>Requester Name</TD>";
	print "<TD>";
	print $query->textfield(
                -name=>"RequesterName",
                -size=>64,
                -maxlength=>256,
                -value=>getparam( 'RequesterName' ),
                );
	print "</TD>";
	if ( $errors{ 'RequesterName' } )
                {
                print "<TD><font color=red><small>$errors{ 'RequesterName' } </small> </font></TD>";
                }
	print "</TR>";

	print "<TR>";
	print "<TD>RequesterOrganisation</TD>";
	print "<TD>";
	print $query->textfield(
                -name=>"RequesterOrganisation",
                -size=>64,
                -maxlength=>256,
                -value=>getparam( "RequesterOrganisation" ),
                );
	print "</TD>";
	if ( $errors{ 'RequesterOrganisation' } )
                {
                print $errors{ 'RequesterOrganisation' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>RequesterCountry</TD>";
	print "<TD>";
	print $query->textfield(
                -name=>"RequesterCountry",
                -size=>2,
                -maxlength=>2,
                -value=>getparam( "RequesterCountry" ),
                );
	print "</TD>";
	if ( $errors{ 'RequesterCountry' } )
                {
                print $errors{ 'Country' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>Requester Telephone Number</TD>";
	print "<TD>";
	print $query->textfield(
                -name=>"RequesterPhone",
                -size=>17,
                -maxlength=>256,
                -value=>getparam( "RequesterPhone" ),
                );
	print "</TD>";
	if ( $errors{ 'RequesterPhone' } )
                {
                print $errors{ 'RequesterPhone' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>Fax Number</TD>";
	print "<TD>";
	print $query->textfield(
                -name=>"RequesterFax",
                -size=>17,
                -maxlength=>256,
                -value=>( getparam( "RequesterFax" ) ),
                );
	print "</TD>";
	if ( $errors{ 'RequesterFax' } )
                {
                print $errors{ 'RequesterFax' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>Email Address</TD>";
	print "<TD>";
	print $query->textfield(
                -name=>"RequesterEmail",
                -size=>32,
                -maxlength=>256,
                -value=>( getparam( "RequesterEmail" ) ),
                );
	print "</TD>";
	if ( $errors{ 'RequesterEmail' } )
                {
                print $errors{ 'RequesterEmail' };
                }
	print "</TR>";

	print "</TABLE>";


#----
	print "<hr><H3> #[ USER TEMPLATE ]# </H3> ";
	print "Please fill in contact information about your organisation.<br>\n";

	print "<A HREF=\"$RIPE142URL#toc7\">Help with this section</A><br>\n";

	print "<TABLE>";

	# something to jump to
	print "<A NAME=USER></A>\n";

	print "<TR>";
	print "<TD>Contact Name</TD>";
	print "<TD>";
	print $query->textfield(
                -name=>"UserName",
                -size=>64,
                -maxlength=>256,
                -value=>getparam( 'UserName' ),
                );
	print "</TD>";
	if ( $errors{ 'UserName' } )
                {
                print "<TD><font color=red><small>$errors{ 'UserName' } </small> </font></TD>";
                }
	print "</TR>";

	print "<TR>";
	print "<TD>UserOrganisation</TD>";
	print "<TD>";
	print $query->textfield(
                -name=>"UserOrganisation",
                -size=>64,
                -maxlength=>256,
                -value=>getparam( "UserOrganisation" ),
                );
	print "</TD>";
	if ( $errors{ 'UserOrganisation' } )
                {
                print $errors{ 'UserOrganisation' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>UserCountry</TD>";
	print "<TD>";
	print $query->textfield(
                -name=>"UserCountry",
                -size=>2,
                -maxlength=>2,
                -value=>getparam( "UserCountry" ),
                );
	print "</TD>";
	if ( $errors{ 'UserCountry' } )
                {
                print $errors{ 'Country' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>User Telephone Number</TD>";
	print "<TD>";
	print $query->textfield(
                -name=>"UserPhone",
                -size=>64,
                -maxlength=>256,
                -value=>getparam( "UserPhone" ),
                );
	print "</TD>";
	if ( $errors{ 'UserPhone' } )
                {
                print $errors{ 'UserPhone' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>Fax Number</TD>";
	print "<TD>";
	print $query->textfield(
                -name=>"UserFax",
                -size=>64,
                -maxlength=>256,
                -value=>( getparam( "UserFax" ) ),
                );
	print "</TD>";
	if ( $errors{ 'UserFax' } )
                {
                print $errors{ 'UserFax' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>Email Address</TD>";
	print "<TD>";
	print $query->textfield(
                -name=>"UserEmail",
                -size=>32,
                -maxlength=>256,
                -value=>( getparam( "UserEmail" ) ),
                );
	print "</TD>";
	if ( $errors{ 'UserEmail' } )
                {
                print $errors{ 'UserEmail' };
                }
	print "</TR>";

	print "</TABLE>";


#----
	print "<hr>\n";
	print "<H3> #[ CURRENT ADDRESS SPACE USAGE TEMPLATE ]# </H3> ";

	# something to jump to
	print "<A NAME=USAGE></A>\n";



	print "<A HREF=\"$RIPE142URL#toc8\"> Help with this section </A><br>\n";

	# hidden field to store number of current usage lines
	my $usageCount;	
	print $query->hidden( 'UsageCount', getparam( "UsageCount" ) );
	$usageCount = getparam( "UsageCount" ) ;
	if ( $usageCount eq '' ) { $usageCount = 0; }	# make numeric
	dprint( "<br>count:$usageCount<br>\n" );

	my $nextFree = $usageCount + 1;

	print "<TABLE>";

	# header1
	print "<TR>";
	print "<TD></TD>";
	print "<TD></TD>";
	print "<TD></TD>";
	print "<TD></TD>";
	print "<TD colspan=3> <CENTER> Addresses Used </CENTER> </TD>";
	print "</TR>";
	
	# header2
	print "<TR>";
	print "<TD>";
        print $query->submit(
                -name=>'AddUsageLine',
		-value=>"Add Usage Line $nextFree",
                );
        print "</TD>";
	print "<TD>Prefix</TD>";
	print "<TD>Subnet Mask</TD>";
	print "<TD>Size</TD>";
	print "<TD>Current</TD>";
	print "<TD>One Year</TD>";
	print "<TD>Two Year</TD>";
	print "<TD>Description</TD>";
	print "</TR>";

	# data

	# show up to and including last line
	my $line;
	for ( $line=0; $line <= $usageCount; $line++ )
		{
        	print "<TR>";

        	print "<TD>";
		print $query->submit(
                	-name=>"DeleteUsageLine",
                	-value=>"Delete Usage Line $line",
                	);
        	print "</TD>";

        	print "<TD>";
		print $query->textfield(
                	-name=>"Prefix$line",
                	-size=>15,
                	-maxlength=>15,
			-value=>(getparam( "Prefix$line" )),
                	);
        	print "</TD>";

		print "<TD>";
                print $query->textfield(
                        -name=>"Mask$line",
                        -size=>15,
                        -maxlength=>15,
                        -value=>(getparam( "Mask$line" )),
                        );
                print "</TD>";

		print "<TD>";
		print $query->textfield(
			-name=>"Size$line",
			-size=>4,
			-maxlength=>8,
                        -value=>(getparam( "Size$line" )),
			);
		print "</TD>";

		print "<TD>";
		print $query->textfield(
			-name=>"Current$line",
			-size=>4,
			-maxlength=>8,
                        -value=>(getparam( "Current$line" )),
			);
		print "</TD>";

		print "<TD>";
		print $query->textfield(
			-name=>"OneYear$line",
			-size=>4,
			-maxlength=>8,
                        -value=>(getparam( "OneYear$line" )),
			);
		print "</TD>";

		print "<TD>";
		print $query->textfield(
			-name=>"TwoYear$line",
			-size=>4,
			-maxlength=>8,
                        -value=>(getparam( "TwoYear$line" )),
			);
		print "</TD>";

		print "<TD>";
		print $query->textfield(
			-name=>"Description$line",
			-size=>40,
			-maxlength=>256,
                        -value=>(getparam( "Description$line" )),
			);
		print "</TD>";

        print "</TR>";
		}

    print "<TR>";
    print "<TD colspan=10>";
    print "Please use this section if you find it easier to just paste in your current usage.  It will also be put in the 141 form and syntax checked.";
    print "</TD>";
    print "</TR>";

    print "<TR>";
    print "<TD>";
    print "</TD>";
    print "<TD colspan=10>";
    print $query->textarea(
		-name=>'FreeFormUsage',
		-cols=>80,
		-rows=>3,
		-value=>getparam( 'FreeFormUsage' )
		);
    print "</TD>";
    print "</TR>";

	print "</TABLE>";

	print "</BLOCKQUOTE>";
	
#-----------------------------------------

	print "<hr>\n";
	print"<H2>II. The Request</H2><br>\n";

	print "<BLOCKQUOTE>";

	print "<H3> #[ REQUEST OVERVIEW TEMPLATE ]# </H3> ";

	print "<P>";

	print "Please answer the following questions about your request.<br>\n";

	print "<A HREF=\"$RIPE142URL#toc9\"> Help with this section </A><br>\n";

	print "<P>";

	print "<TABLE>";


#-----

	print "<TR>";
	print "<TD width=\"40%\"> When will you connect to the Internet and to whom ? </TD>";
	print "<TD>";
	print $query->textfield(
		-name=>'WhenConnect',
		-size=>48,
		-maxlength=>256,
		-value=>(getparam( 'WhenConnect' )),
		);
	print "</TD>";
	if ( $errors{ 'WhenConnect' } )
                {
                print $errors{ 'WhenConnect' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>What country is the headquarters located ? </TD>";
	print "<TD>";
	print $query->textfield(
		-name=>'WhichCountry',
		-size=>2,
		-maxlength=>2,
		-value=>(getparam( 'WhichCountry' )),
		);
	print "</TD>";
	if ( $errors{ 'WhichCountry' } )
                {
                print $errors{ 'WhichCountry' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>Have you considered using private addresses ? </TD>";
	print "<TD>";
	print $query->radio_group(
		-name=>'PrivateAddresses',
		-'values'=>['Yes','No'],
		#-value=>getparam( 'PrivateAddresses' )
		-default=>'No',
		);
	print "</TD>";
	if ( $errors{ 'PrivateAddresses' } )
                {
                print $errors{ 'PrivateAddresses' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD> Has the request been refused in the past ? </TD>";
	print "<TD>";
	print $query->radio_group(
		-name=>'Refused',
		-'values'=>['Yes','No'],
		#-value=>getparam( 'Refused' )
		-default=>'No',
		);
	print "</TD>";
	if ( $errors{ 'Refused' } )
                {
                print $errors{ 'Refused' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>If yes, why, and how has the situation changed ? </TD>";
	print "<TD>";
	print $query->textarea(
		-name=>'WhyRefused',
		-cols=>80,
		-rows=>3,
		-value=>getparam( 'WhyRefused' )
		);
	print "</TD>";
	if ( $errors{ 'WhyRefused' } )
                {
                print $errors{ 'WhyRefused' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>Are you requesting Provider Independent addresses ? </TD>";
	print "<TD>";
	print $query->radio_group(
		-name=>'PI',
		-'values'=>['Yes','No'],
		#-value=>getparam( 'PI' )
		-default=>'No',
		);
	print "</TD>";
	if ( $errors{ 'PI' } )
                {
                print $errors{ 'PI' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>Are you returning addresses ? </TD>";
	print "<TD>";
	print $query->radio_group(
		-name=>'Returning',
		-'values'=>['Yes','No'],
		#-value=>getparam( 'Returning' ),
		-default=>'No',
		);
	print "</TD>";
	if ( $errors{ 'Returning' } )
                {
                print $errors{ 'Returning' };
                }
	print "</TR>";

	print "<TR>";
	print "<TD>If yes, please fill in what range will be returned on what dates to what provider ? </TD>";
	print "<TD>";
	print $query->textarea(
		-name=>'WhatReturn',
		-cols=>80,
		-rows=>3,
		-value=>getparam( 'WhatReturn' )
		);
	print "</TD>";
	if ( $errors{ 'WhatReturn' } )
                {
                print $errors{ 'WhatReturn' };
                }
	print "</TR>";

	print "</TABLE>";

	print "<P><br>\n";

#----

	print"<hr> <H3> #[ ADDRESSING PLAN TEMPLATE ]# </H3> <br>\n";

	print "<A HREF=\"$RIPE142URL#toc11\"> Help with this section </A><br>\n";


	print "<A NAME=REQUEST></A>\n";

	# hidden field to store number of request lines
	my $requestCount;	
	print $query->hidden( 'RequestCount', getparam( "RequestCount" ) );
	$requestCount = getparam( "RequestCount" ) ;
	if ( $requestCount eq '' ) { $requestCount = 0; }	# make numeric
	dprint( "<br>count:$requestCount<br>\n" );

	my $nextRequestFree = $requestCount + 1;

	print "<TABLE>";

	print "<TR>";
	print "<TD>";
        print $query->submit(
                -name=>'AddRequestLine',
		-value=>"Add Request Line $nextRequestFree",
                );
	print "<TD>Relative Prefix</TD>";	# back
	print "<TD>Subnet Mask</TD>";
	print "<TD>Size </TD>";
	print "<TD>Hosts Immediate</TD>";
	print "<TD>Hosts Year One</TD>";
	print "<TD>Hosts Year Two</TD>";
	print "<TD>Description</TD>";
	print "</TR>";

	# show up to and including last line
	my $requestLine;
	dprint( "<br>count:$requestCount<br>\n" );
	for ( $requestLine= 0; $requestLine <= $requestCount; $requestLine ++ )
		{
        	print "<TR>";

        	print "<TD>";
		print $query->submit(
                	-name=>"DeleteRequestLine",
                	-value=>"Delete Request Line $requestLine",
                	);
        	print "</TD>";

		print "<TD>";
		if ( $requestLine == 0 )
			{
			print "0.0.0.0";
			}
		else
			{
			print $query->textfield(
				-name=>"RequestPrefix$requestLine",
				-size=>15,
				-maxlength=>15,
                        	-value=>(getparam( "RequestPrefix$requestLine" )),
				);
			}
		print "</TD>";

	       	print "<TD>";
		print $query->textfield(
			-name=>"RequestMask$requestLine",
			-size=>15,
			-maxlength=>15,
                        -value=>(getparam( "RequestMask$requestLine" )),
			);
		print "</TD>";

	       	print "<TD>";
		print $query->textfield(
			-name=>"RequestSize$requestLine",
			-size=>4,
			-maxlength=>8,
                        -value=>(getparam( "RequestSize$requestLine" )),
			);
		print "</TD>";

		print "<TD>";
		print $query->textfield(
			-name=>"RequestImmediate$requestLine",
			-size=>4,
			-maxlength=>8,
                        -value=>(getparam( "RequestImmedaite$requestLine" )),
			);
		print "</TD>";

		print "<TD>";
		print $query->textfield(
			-name=>"RequestOneYear$requestLine",
			-size=>4,
			-maxlength=>8,
                        -value=>(getparam( "RequestOneyear$requestLine" )),
			);
		print "</TD>";

		print "<TD>";
		print $query->textfield(
			-name=>"RequestTwoYear$requestLine",
			-size=>4,
			-maxlength=>8,
                        -value=>(getparam( "RequestTwoyear$requestLine" )),
			);
		print "</TD>";

		print "<TD>";
		print $query->textfield(
			-name=>"RequestDescription$requestLine",
			-size=>40,
			-maxlength=>256,
                        -value=>(getparam( "RequestDescription$requestLine" )),
			);
		print "</TD>";

        	print "</TR>";
		}

    print "<TR>";
    print "<TD colspan=10>";
    print "Please use this section if you find it easier to just paste in your addressing plan.  It will also be put in the 141 form and syntax checked.";
    print "</TD>";
    print "</TR>";

    print "<TR>";
    print "<TD>";
    print "</TD>";
    print "<TD colspan=10>";
    print $query->textarea(
		-name=>'FreeFormRequest',
        -cols=>80,
        -rows=>3,
        -value=>getparam( 'FreeFormRequest' )
        );
    print "</TD>";
    print "</TR>";

	print "</TABLE>";

	print "<P><br>\n";

	print "</BLOCKQUOTE>";
	
#----------------------------------

	print "<hr>\n";
	print "<H2> III. Database Information </H2>";

	print "<BLOCKQUOTE>";
	print "<H3> #[ NETWORK TEMPLATE ]# </H3> ";

	print "<A HREF=\"$RIPE142URL#toc13\"> Help with this section </A><br>\n";

        # hidden field to store number of network lines
        my $networkCount;
        print $query->hidden( 'NetworkCount', getparam( 'NetworkCount' ) );
        $networkCount = getparam( "NetworkCount" ) ;
        if ( $networkCount eq '' ) { $networkCount = 0; } # make numeric

        my $nextFreeNetwork = $networkCount + 1;

	print "<TABLE>";

        print "<TR>";
        print "<TD>";
        print $query->submit(
                -name=>'AddNetworkLine',
                -value=>"Add Network Line $nextFreeNetwork",
                );
        print "</TD>";
        print "</TR>";

        my $networkLine;
        for ( $networkLine= 0; $networkLine <= $networkCount; $networkLine++ )
                {
# delete button, name
                print "<TR>";

                print "<TD>";
                print $query->submit(
                       -name=>"DeleteNetworkLine",
                       -value=>"Delete Network Line $networkLine",
                       );
                print "</TD>";
                print "</TR>";
		


       	print "<TR>";
       	print "<TD>Net Name</TD>";
       	print "<TD>";
	print $query->textfield(
               	-name=>"NetName$networkLine",
               	-size=>32,
               	-maxlength=>80,
		-value=>(getparam( "NetName$networkLine" )),
               	);
       	print "</TD>";
       	print "</TR>";


       	print "<TR>";
       	print "<TD>Description</TD>";
       	print "<TD>";
	print $query->textarea(
               	-name=>"NetDescription$networkLine",
		-cols=>80,
		-rows=>3,
		-value=>(getparam( "NetDescription$networkLine" )),
               	);
       	print "</TD>";
	print "</TR>";

       	print "<TR>";
       	print "<TD>Country</TD>";
       	print "<TD>";
	print $query->textfield(
               	-name=>"NetCountry$networkLine",
               	-size=>2,
               	-maxlength=>2,
		-value=>(getparam( "NetCountry$networkLine" )),
               	);
       	print "</TD>";
	print "</TR>";

       	print "<TR>";
       	print "<TD>Administrative Contact</TD>";
       	print "<TD>";
	print $query->textfield(
               	-name=>"NetAdminC$networkLine",
               	-size=>15,
              	-maxlength=>255,
		-value=>(getparam( "NetAdminC$networkLine" )),
               	);
       	print "</TD>";
	print "</TR>";

       	print "<TR>";
       	print "<TD>Technical Contact</TD>";
       	print "<TD>";
	print $query->textfield(
               	-name=>"NetTechC$networkLine",
               	-size=>15,
               	-maxlength=>255,
		-value=>(getparam( "NetTechC" )),
               	);
       	print "</TD>";
	print "</TR>";

       	print "<TR>";
       	print "<TD>Notify</TD>";
       	print "<TD>";
	print $query->textfield(
               	-name=>"NetNotify$networkLine",
               	-size=>15,
               	-maxlength=>64,
		-value=>(getparam( "NetNotify" )),
               	);
       	print "</TD>";
	print "</TR>";

       	print "<TR>";
       	print "<TD>Mnt-By</TD>";
       	print "<TD>";
	print $query->textfield(
               	-name=>"NetMntBy$networkLine",
               	-size=>15,
               	-maxlength=>64,
		-value=>(getparam( "NetMntBy" )),
               	);
       	print "</TD>";
	print "</TR>";

  #     	print "<TR>";
  #     	print "<TD>Changed</TD>";
  #     	print "<TD>";
#	print $query->textfield(
#               	-name=>"NetChanged$networkLine",
#               	-size=>15,
#               	-maxlength=>64,
#		-value=>(getparam( "NetChanged" )),
#               	);
#       	print "</TD>";
#	print "</TR>";

		}

 	print "</TABLE>";

 	print "<P>";

#-----

	print "<hr><H3> #[ PERSON TEMPLATE ]# </H3> ";

	print "Please fill in one template for each person that is not yet registered in the RIPE database and does not have a nic handle.<br>\n";

	print "<A HREF=\"$RIPE142URL#toc14\"> Help with this section </A><br>\n";

	print "<P>";

	# hidden field to store number of person lines
	my $personCount;	
	print $query->hidden( 'PersonCount', getparam( 'PersonCount' ) );
	$personCount = getparam( "PersonCount" ) ;
	if ( $personCount eq '' ) { $personCount = 0; }	# make numeric

	my $nextFreePerson = $personCount + 1;

	# something to jump to
	print "<A NAME=PERSON></A>\n";

	print "<TABLE>";

	print "<TR>";
	print "<TD>";
        print $query->submit(
                -name=>'AddPersonLine',
		-value=>"Add Person Line $nextFreePerson",
                );
	print "</TD>";
	print "</TR>";

	my $personLine;
	for ( $personLine= 0; $personLine <= $personCount; $personLine++ )
		{
# delete button, name
       	print "<TR>";

        	print "<TD>";
			print $query->submit(
                	-name=>"DeletePersonLine",
                	-value=>"Delete Person Line $personLine",
                	);
        	print "</TD>";

			my $LOOKUPNICHDLMESSAGE;
			if ( ( -f $WHOISPATH ) && ( -x $WHOISPATH ) )
				{
				$LOOKUPNICHDLMESSAGE = "If you fill in an existing Nic Handle here, the other person fields will be automatically filled in for you in the plain text form.";
				}
			else
				{
				$LOOKUPNICHDLMESSAGE = "Nic Handles will not be looked up";
				}
			
			print "<TD> Nic-Hdl </TD>";

			print "<TD colspan=4>";

			print "<TABLE border=0 cellspacing=0 cellpadding=0>";
			print "<TR>";

			print "<TD>";
			print $query->textfield(
				-name=>"PersonNicHdl$personLine",
				-size=>15,
				-maxlength=>15,
				-value=>(getparam( "PersonNicHdl$personLine" )),
				);
			print "</TD>";

			print "<TD>&nbsp;</TD><TD>$LOOKUPNICHDLMESSAGE</TD>";


			print "</TR>";
			print "</TABLE>";

        print "</TR>";

 		print "<TR>";

			print "<TD></TD>";

       		print "<TD>Name</TD>";
			print "<TD>";
			print $query->textfield(
                	-name=>"PersonName$personLine",
                	-size=>32,
                	-maxlength=>64,
					-value=>(getparam( "PersonName$personLine" )),
                	);
        	 print "</TD>";

		print "</TR>";

# address

		print "<TR>";

			print "<TD></TD>";

			print "<TD>Address</TD>";

        	print "<TD>";
			print $query->textarea(
                	-name=>"PersonAddress$personLine",
			-cols=>80,
			-rows=>3,
			-value=>(getparam( "PersonAddress$personLine" )),
                	);
			print "</TD>";

		print "</TR>";

# email, phone, fax

	       	print "<TR>";

        	 print "<TD></TD>";
        	 print "<TD>Email</TD>";

		 print "<TD>";

		 print "<TABLE border=0 cellspacing=0 cellpadding=0>";

        	   print "<TR>";

        	     print "<TD>";
 		     print $query->textfield(
                	-name=>"PersonEmail$personLine",
                	-size=>32,
                	-maxlength=>64,
			-value=>(getparam( "PersonEmail$personLine" )),
                	);
        	     print "</TD>";

        	     print "<TD>&nbsp; Phone &nbsp; </TD>";
        	     print "<TD>";
		     print $query->textfield(
                	-name=>"PersonPhone$personLine",
                	-size=>15,
                	-maxlength=>64,
			-value=>(getparam( "PersonPhone$personLine" )),
                	);
        	     print "</TD>";

        	     print "<TD>&nbsp; Fax &nbsp; </TD>";
        	     print "<TD>";
		     print $query->textfield(
                	-name=>"PersonFax$personLine",
                	-size=>15,
                	-maxlength=>64,
			-value=>(getparam( "PersonFax$personLine" )),
                	);
        	     print "</TD>";

		   print "</TR>";

		print "</TABLE>";

		print "</TD>";

		print "</TR>";

# nic-hdl, notify, mnt-by, changed

		print "<TR>";

		print "<TD></TD>";
		print "<TD>Notify</TD>";

		  print "<TD>";

		  print "<TABLE border=0 cellspacing=0 cellpadding=0>";

		    print "<TR>";


        	      print "<TD>";
		      print $query->textfield(
                	-name=>"PersonNotify$personLine",
                	-size=>15,
                	-maxlength=>64,
			-value=>(getparam( "PersonNotify$personLine" )),
                	);
        	      print "</TD>";

         	      print "<TD>&nbsp; Mnt-by &nbsp; </TD>";
        	      print "<TD>";
		      print $query->textfield(
                	-name=>"PersonMntBy$personLine",
                	-size=>15,
                	-maxlength=>64,
			-value=>(getparam( "PersonMntBy$personLine" )),
                	);
        	      print "</TD>";

         	      print "<TD>&nbsp; Changed  &nbsp; </TD>";
        	      print "<TD>";
		      print $query->textfield(
                	-name=>"PersonChanged$personLine",
                	-size=>15,
                	-maxlength=>64,
			-value=>(getparam( "PersonChanged$personLine" )),
	               	);
        	      print "</TD>";

		    print "</TR>";

		  print "</TABLE>";

		  print "</TD>";

		print "</TR>";

		print "\n";
		}

	print "</TABLE>";

	print "</BLOCKQUOTE>";

#----------------------------------

	print "<hr>";

	print "<H2>IV. Optional Information</H2>";

	print "<BLOCKQUOTE>";

        print "<A HREF=\"$RIPE142URL#toc15\"> Help with this section </A><br>\n";

	print "Any additional information may be entered here. It will not be checked by the robot.";

        print $query->textarea(
                -name=>'Comments',
                -cols=>80,
                -rows=>3,
                -value=>getparam( 'Comments' )
                );
        if ( $errors{ 'Comments' } )
                {
                print "<TD><font color=red><small>$errors{ 'Comments' } </small> </font> </TD>";
                }
        print "<br>\n";

	print "</BLOCKQUOTE>";

#----

	print "<hr>";

	showFormControls();

#----
	print $query->end_form, "\n";

	print "<P>";

	return;
	}


#------------------------------------------------------------------------------
# Purpose           : return param value or ''
#						main use is to prevent probs with undef
# Side Effects      : none
# Comments          : 

sub getparam
	{
	my ( $name ) = @_;	# ARGS: param name

	my $val = $query->param( -name=> $name );

	if ( defined $val )
		{
		return $val;
		}
	else
		{
		return '';	
		}
	}



#------------------------------------------------------------------------------
# Purpose           : calls autohmweb.pl, echos response in html to stdout
# Side Effects      : none
# Comments          : HTML output

sub doCall
	{	
	my ( $query ) = @_;


	# put plain text in a file, call autohm-web.pl to check it,
	# and put the STDOUT from that on web page
	# cehck STDERR in err file for error message

	my ( $sec, $min, $hour, $day, $month, $year ) = localtime( time );
	my $YYYYMMDDhhmmss = sprintf ( "%04d%02d%02d%02d%02d%02d",
                $year, $month, $day, $hour, $min, $sec );

	my $errfile = "web141err.$YYYYMMDDhhmmss.$$";
	my $errpath = "$TEMPDIR/$errfile";

	my $tempfile = "$TEMPDIR/web141temp.$YYYYMMDDhhmmss.$$";
	
	open ( ATEMP, "> $tempfile" );

	showPlainText( \*ATEMP, $query, 0 );

	close( ATEMP );
	
	my $autohmwebOutput;
	my $autohmErr;

	if ( ! -f $tempfile )
		{
		error( "error creating temp file" );
		}
	else
		{
		if ( ! -x $AUTOHMPATH )
			{
			error( "Cannot access syntax checking program $AUTOHMPATH" );
			}
		else
			{
			open ( DOCHECK, "$AUTOHMPATH -web < $tempfile 2>$errpath |" )
				or error( "Error running syntax checking program $AUTOHMPATH" );

			# read stdout on pipe
			my $line; 
			while ( defined ( $line = <DOCHECK> ) )
				{
				$autohmwebOutput .= "$line<br>\n";
				}

			$autohmErr = close ( DOCHECK );
			}
		}

	# read stderr from file

	my $autohmwebErrors;
	if ( open ( ERRFILE, "$errpath" ) )
		{
		my $errLine;
		while ( defined ( $errLine = <ERRFILE> ) )
			{
			$autohmwebErrors .= $errLine;
			}
		close ERRFILE;
		}

	# show stuff
	my $autohmwebResult = 1;	# 1 for pass, 0 for errors

	# in html format

	# errors ?
	if ( ( $autohmwebErrors =~ /FATAL_ERROR_EXIT_TXT/ )
		|| ( $autohmErr ne 1) )
		# yes
		{
		print <<EOERRORTXT
<P>
Internal Error: Error $autohmErr from the syntax checking robot
<P>
Please contact the <A HREF=mailto:ncc\@ripe.net> RIPE NCC </A>, mentioning the URL of this page and file $errfile.
<P>
Your request in plain text suitable for mailing to hostmaster\@ripe.net follows, and should still be accurate, although it may fail syntax checks.

EOERRORTXT
;

                print "<hr>\n";
		print "<pre>";
                showPlainText( \*STDOUT, $query, $autohmwebResult );
                print "</pre>";
 
		# keep temp file
		# keep err file
		}
	else
		# no errors
		{
		print $autohmwebOutput;

		print "<P>";

		print "<hr>\n";
		print "<pre>";
		showPlainText( \*STDOUT, $query, $autohmwebResult );
		print "</pre>";	

		# remove temp file
		if ( !$debug )
			{
			unlink ( $tempfile );
			}

		# remove err file
		unlink ( $errfile );
		}


	# done
	return;
	}



#------------------------------------------------------------------------------
# Purpose           : print entered data in plain text form for cut and paste
#					into a mail to RIPE NCC
# Side Effects      : none
# Comments          : too long
sub showPlainText
	{
	my ( $fh, $query, $autohmChecked ) = @_;	# file handle, query
						# checkflag: 1 if checked & OK,
                                                #	else 0
	my ( $my_url ) = $query->self_url;
	
	my $checkedText;
	if ( $autohmChecked )
		{
		$checkedText = 'Please note that this text has been checked only for syntax errors\nand may fail other checks of the RIPE NCC Address Checking Robot.';
		}	
	else
		{
		$checkedText = 'Please note that this text may fail the syntax or other checks of the RIPE NCC Address Checking Robot.';

		}

	# split url into fields
	my %fields;

	my @fields = $query->param;

	my $field;
	foreach $field ( @fields )
		{
		my ( $value ) = $query->param( "$field" );
		$fields{ $field } = $value;
		}


	# get address part of url
	$my_url =~ s/^([^\?]*)\?.*$/$1/;

	my $organisationDescription = getparam( "OrganisationDescription" );


	print $fh <<EOGENERALTEXT

Address Request Form text automatically generated by the web page:

    $my_url

You may paste this text into an email, which you should send to hostmaster\@ripe.net. 

$checkedText

I. General Information

#[ OVERVIEW OF ORGANISATION TEMPLATE ]#

$fields{ 'OrganisationDescription' }

#[ REQUESTER TEMPLATE ]#

      name: $fields{ 'RequesterName' }
      organisation: $fields{ 'RequesterOrganisation' }
      country: $fields{ 'RequesterCountry' }
      phone:  $fields{ 'RequesterPhone' }
      fax-no: $fields{ 'RequesterFax' }
      e-mail: $fields{ 'RequesterEmail' }

#[ USER TEMPLATE ]#

      name: $fields{ 'UserName' }
      organisation: $fields{ 'UserOrganisation' }
      country: $fields{ 'UserCountry' }
      phone:  $fields{ 'UserPhone' }
      fax-no: $fields{ 'UserFax' }
      e-mail: $fields{ 'UserEmail' }

#[ CURRENT ADDRESS SPACE USAGE TEMPLATE ]#


                                               Addresses Used 
      Prefix          Subnet Mask      Size  Current 1-yr  2-yr  Description

EOGENERALTEXT
;

	my ( $totalSize, $totalCurrent, $totalOneYear, $totalTwoYear ) = (0,0,0,0);

	# show numbers from fixed lines part and add to totals

	my $line = 0;
	for ( $line=0; defined $fields{ "Prefix$line" }; $line++ )
		{
		printf $fh
			"      %-15s %-15s  %5d %5d   %5d %5d %-s\n",
			$fields{ "Prefix$line" },
			$fields{ "Mask$line" },
			$fields{ "Size$line" },
			$fields{ "Current$line" },
			$fields{ "OneYear$line" },
			$fields{ "TwoYear$line" },
			$fields{ "Description$line" } 
			;
	
		$totalSize    += $fields{ "Size$line" };
		$totalCurrent += $fields{ "Current$line" };
		$totalOneYear += $fields{ "OneYear$line" };
		$totalTwoYear += $fields{ "TwoYear$line" };
		}

	# get numbers from free form part

	my @freePrefix;
	my @freeMask;
	my @freeSize;
	my @freeCurrent;
	my @freeOneYear;
	my @freeTwoYear;
	my @freeDescription;

	# go through correctly written free form lines, stop at bad or empty one

	my $freeIndex = 0;
	while( $fields{ 'FreeFormUsage' } =~ /^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.*)$/mg )
		{
		$freePrefix[ $freeIndex ] = $1;
		$freeMask[ $freeIndex ] = $2;
		$freeSize[ $freeIndex ] = $3;
		$freeCurrent[ $freeIndex ] = $4;
		$freeOneYear[ $freeIndex ] = $5;
		$freeTwoYear[ $freeIndex ] = $6;
		$freeDescription[ $freeIndex ] = $7;

		$freeIndex++;
		}

	# show the numbers from free form part  and add to totals

	for ( $line=0; $line <= $#freePrefix; $line++ )
		{
		printf $fh
			"      %-15s %-15s  %5d %5d   %5d %5d %-s\n",
			$freePrefix[ $line],
			$freeMask[ $line ],
			$freeSize[ $line ],
			$freeCurrent[ $line ],
			$freeOneYear[ $line ],
			$freeTwoYear[ $line ],
			$freeDescription[ $line ],
			;

		$totalSize    += $freeSize[ $line ];
		$totalCurrent += $freeCurrent[ $line ];
		$totalOneYear += $freeOneYear[ $line ];
		$totalTwoYear += $freeTwoYear[ $line ];
		}

	print $fh "\n";
	printf $fh
		"      %-15s %15s  %5d %5d   %5d %5d %-s\n",
		'',
		'',
		$totalSize,
		$totalCurrent,
		$totalOneYear,
		$totalTwoYear,
		'Totals'
		;

	# total up request lines for showing in request overview
	# as well as in addressing plan

	my ( $totalRequestSize, $totalRequestImmediate, $totalRequestOneYear, $totalRequestTwoYear ) = (0,0,0,0);

	my( $subnetsImmediate, $subnetsYear1, $subnetsYear2 ) = (0,0,0);

	# get numbers from fixed field part of request

	my $requestLine = 0;
	for ( $requestLine=0; defined $fields{ "RequestSize$requestLine" }; $requestLine++ )
		{
		$totalRequestSize    += $fields{ "RequestSize$requestLine" };
		$totalRequestImmediate += $fields{ "RequestImmediate$requestLine" };
		$totalRequestOneYear += $fields{ "RequestOneYear$requestLine" };
		$totalRequestTwoYear += $fields{ "RequestTwoYear$requestLine" };

		if ( $fields{ "RequestImmediate$requestLine" } > 0 )
			{
			$subnetsImmediate++;
			}

        if ( $fields{ "RequestOneYear$requestLine" } > 0 )
			{
			$subnetsYear1++;
			}

        if ( $fields{ "RequestTwoYear$requestLine" } > 0 )
			{
			$subnetsYear2++;
			}

		}

	# get numbers from free form part of request

	my @freeRequestPrefix;
	my @freeRequestMask;
	my @freeRequestSize;
	my @freeRequestImmediate;
	my @freeRequestOneYear;
	my @freeRequestTwoYear;
	my @freeRequestDescription;

	# go through correctly written free form lines, adding to totals
	# stop at bad or empty one

	my $freeRequestIndex = 0;
	while( $fields{ 'FreeFormRequest' } =~ /^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.*)$/mg )
		{
		$freeRequestPrefix[ $freeRequestIndex ] = $1;
		$freeRequestMask[ $freeRequestIndex ] = $2;
		$freeRequestSize[ $freeRequestIndex ] = $3;
		$freeRequestImmediate[ $freeRequestIndex ] = $4;
		$freeRequestOneYear[ $freeRequestIndex ] = $5;
		$freeRequestTwoYear[ $freeRequestIndex ] = $6;
		$freeRequestDescription[ $freeRequestIndex ] = $7;

		$totalRequestSize    += $freeRequestSize[ $freeRequestIndex ];
        $totalRequestImmediate += $freeRequestImmediate[ $freeRequestIndex ];
        $totalRequestOneYear += $freeRequestOneYear[ $freeRequestIndex ];
        $totalRequestTwoYear += $freeRequestTwoYear[ $freeRequestIndex ];

		if ( $freeRequestImmediate[ $freeRequestIndex ] > 0 )
            {
            $subnetsImmediate++;
            }

        if ( $freeRequestOneYear[ $freeRequestIndex ] > 0 )
            {
            $subnetsYear1++;
            }

        if ( $freeRequestTwoYear[ $freeRequestIndex ] > 0 )
            {
            $subnetsYear2++;
            }

		$freeRequestIndex++;
		}


	# add explanation fields to yes/no fields...

	$fields{ "Refused" } = $fields{ "Refused" } . "\n" . $fields{ "WhyRefused" };
	$fields{ "Returning" } = $fields{ "Returning" } . "\n" . $fields{ "WhatReturn" };

	# ...remove trailing blanks...

	$fields{ "Refused" }   =~ s/\n\s*\Z//mg; 	# remove trailing blank lines
	$fields{ "Returning" } =~ s/\n\s*\Z//mg;   # remove trailing blank lines

	# ...and insert labels

	$fields{ "Refused" }   =~ s/^/      request-refused:         /mg;
	$fields{ "Returning" } =~ s/^/      address-space-returned:  /mg;


	# show request overview

	print $fh <<EOREQUESTTEXT

II. The Request

#[ REQUEST OVERVIEW TEMPLATE ]#

      request-size:            $totalRequestSize
      addresses-immediate:     $totalRequestImmediate
      addresses-year-1:        $totalRequestOneYear    
      addresses-year-2:        $totalRequestTwoYear      
      subnets-immediate:       $subnetsImmediate
      subnets-year-1:          $subnetsYear1
      subnets-year-2:          $subnetsYear2
      inet-connect:            $fields{ "WhenConnect" }     
      country-net:             $fields{ "WhichCountry" }      
      private-considered:      $fields{ "PrivateAddresses" }       
$fields{ "Refused" }
      PI-requested:            $fields{ "PI" }      
$fields{ "Returning" }

#[ ADDRESSING PLAN TEMPLATE ]#

                                                Addresses Used 
      Prefix          Subnet Mask      Size  Immediate 1-yr  2-yr  Description

EOREQUESTTEXT
;

	# show address plan lines

	$fields{ "RequestPrefix0" } = '0.0.0.0';

	# show the numbers from fixed field lines

	for ( $requestLine=0; defined $fields{ "RequestSize$requestLine" }; $requestLine++ )
		{
		printf $fh
			"      %-15s %-15s  %5d %5d   %5d %5d %-s\n",

			$fields{ "RequestPrefix$requestLine" },

			$fields{ "RequestMask$requestLine" },

			$fields{ "RequestSize$requestLine" },

			$fields{ "RequestImmediate$requestLine" },
			$fields{ "RequestOneYear$requestLine" },
			$fields{ "RequestTwoYear$requestLine" },

			$fields{ "RequestDescription$requestLine" } 
			;
		}

	# show the numbers from free form part

	for ( $line=0; $line <= $#freeRequestPrefix; $line++ )
		{
		printf $fh
			"      %-15s %-15s  %5d %5d   %5d %5d %-s\n",
			$freeRequestPrefix[ $line],
			$freeRequestMask[ $line ],
			$freeRequestSize[ $line ],
			$freeRequestImmediate[ $line ],
			$freeRequestOneYear[ $line ],
			$freeRequestTwoYear[ $line ],
			$freeRequestDescription[ $line ],
			;

		}

 	# show address plan totals

	print $fh "\n";
	printf( $fh
		"      %-15s %15s  %5d %5d   %5d %5d %-s\n",
		'',
		'',
		$totalRequestSize,
		$totalRequestImmediate,
		$totalRequestOneYear,
		$totalRequestTwoYear,
		'Totals'
		);

	
	# the database objects

	print $fh "\nIII. Database Information\n\n";

	# do all the network objects
	# network object should not exist until approval, so no lookup

	my $networkStatus;
	if ( $fields{ "PI" } eq 'Yes' )
		{
		$networkStatus = 'ASSIGNED PI';
		}
	else
		{
		$networkStatus = 'ASSIGNED PA';
		}

	my $networkLine;
	for ( $networkLine=0; defined $fields{ "NetName$networkLine" }; $networkLine++ )
		{
		# make description multiline into multiple lines
		my $desciptionLines = $fields{ "NetDescription$networkLine" };
		$desciptionLines =~ s/^/\tdescr: /mg;

		print $fh <<EONETTEXT
#[ NETWORK TEMPLATE ]# 

	inetnum: 
	netname:  $fields{ "NetName$networkLine" }
$desciptionLines
	country:  $fields{ "NetCountry$networkLine" }
	admin-c:  $fields{ "NetAdminC$networkLine" }
	tech-c:   $fields{ "NetTechC$networkLine" }
	status:   $networkStatus
	notify:   $fields{ "NetNotify$networkLine" }
	mnt-by:   $fields{ "NetMntBy$networkLine" }
	changed:  $fields{ "NetChanged$networkLine" }
	source:   RIPE

EONETTEXT
;
		}

	# do all the person objects

	# if they give us a valid nic handle show the data for that, else show
	# what they type

	my $personLine = 0;
	for ( 	$personLine=0;
			( defined $fields{ "PersonName$personLine" } ) || ( defined $fields{ "PersonNicHdl$personLine" } );
			$personLine++ )
		{
		# look up the nic handle with whois
		my $nichdl = $fields{ "PersonNicHdl$personLine" };

		my $found;
		my $whoisOutput;

		if ( ( $nichdl !~ /auto-1/i ) && ( $nichdl ne '' ) && ( -f $WHOISPATH ) && ( -x $WHOISPATH ) )
			# lookup and use whois data
    		{
    		if ( open ( WHOIS, "$WHOISPATH -T person $nichdl 2>&1 |" ) )
    			{
				my $line;
    			while ( $line=<WHOIS> )
        			{
        			if ( $line =~ /^WHOIS_NOTFOUND_REG$/i )
						# not found in whois
            			{
						$found = 0;
            			last;
            			}
					elsif ( ( $line !~ /^\s*%/ ) && (  $line !~ /^\s*$/ ) )
						# not blank or comment
						{
						$whoisOutput .= "\t$line";
						}

					if ( $line =~ /^person:.*$/ )
						# count the number found
						{
						$found += 1;
						}
        			}
    			close WHOIS;
				}
			else
  				{
				error( "Could not run whois" );
				}
    		}


		print $fh "#[ PERSON TEMPLATE ]#\n\n";

		# found how many in whois ?
	
		if ( $found == 1 )
			# just one found - show em
			{
			print $fh $whoisOutput;
			print $fh "\n";
			}
		else
			# too many or two few found ? - show entered data
			{
			# use entered data
	
			# make address multiline into multiple lines
			my $addressLines = $fields{ "PersonAddress$personLine" };
			$addressLines =~ s/^/\taddress: /mg;
	
			# show it
			print $fh <<EOPERSONTEXT
	person:  $fields{ "PersonName$personLine" }
$addressLines
	phone:   $fields{ "PersonPhone$personLine" }
	fax-no:  $fields{ "PersonFax$personLine" }
	e-mail:  $fields{ "PersonEmail$personLine" }
	nic-hdl: $fields{ "PersonNicHdl$personLine" }
	notify:  $fields{ "PersonNotify$personLine" }
	mnt-by:  $fields{ "PersonMntBy$personLine" }
	changed: $fields{ "PersonChanged$personLine" }
	source:  RIPE

EOPERSONTEXT
;
			}
		}


	print $fh <<EOENDTEXT

#[TEMPLATES END]#

IV. Optional Information

$fields{ "Comments" }

EOENDTEXT
;
	return;
	}


#------------------------------------------------------------------------------
# Purpose           : move field over another
# Side Effects      : none
# Comments          : 

sub moveField()
	{
	my ( $oldfield, $newfield ) = @_; # ARGS: names of the fields

	dprint( "<br>moving $oldfield (" . ( getparam( $oldfield ) ) . ") over $newfield (" . ( getparam( $newfield ) ) . ") <br>\n" );
	$query->param( $newfield, $query->param($oldfield) );

	# clear old field
	$query->param( $oldfield, undef );

	return;
	}

#------------------------------------------------------------------------------
# Purpose           : print error message if debugging
# Side Effects      : none
# Comments          : HTML output

sub dprint
	{
	my ( $text ) = @_;

	if ( $debug )
		{
		print $text;
		}

	return;
	}


#------------------------------------------------------------------------------
# Purpose           : print error message to go in web page
# Side Effects      : none
# Comments          : HTML output

sub error
        {
        my ( $text ) = @_;

        print "<P>\nInternal Error: $text<P>" . 'Please contact the RIPE NCC, mentioning the URL of this page. <A HREF=mailto:ncc@ripe.net> RIPE NCC </A> </P>';

        return;
        }

__END__

# code end ---------------------------------------------------------------------

# POD Help

=head1 NAME

B<web141> - allow user to enter RIPE 141 requests into a web form and convert them to plain text or syntax check them.

=head1 SYNOPSIS

Perl/CGI script that generates a web form that the user fills out. User can convert the form to plain text RIPE 141 address request, suitable for emailing to RIPE NCC, or syntax check the request with the autohm robot if available.

No command line args.

=head1 DESCRIPTION

When called with no HTML params, will show the empty form for the user to fill out, with the fields mapping to those of the RIPE 141 form. There are buttons to add extra fields which set params telling the code to act differently when these are set. There main buttons set params telling the code to print out a plain text RIPE 141 form based on the data, or to pass the data to the autohm syntax checking robot and show the response in HTML and plain text.

If whois is available, it will query that to fill out person objects for given NIC handles.

The program will not submit the request to the RIPE NCC. The user must do that by cutting the plain text and pasting it into an email to hostmaster@ripe.net. It may still fail some checks as the autohm robot there does additional checks not done to data submitted by this form.

=head1 FILES

ripe-141.html - RIPE 141 form specification

ripe-142.html - explanation of RIPE 141 form

autohm.pl - syntax checker

whois - RIPE NCC whois client

=head1 REQUIRES

Perl5, CGI.pm

=head1 BUGS

When user press a button to add an extra multi-entry section, the page does not show that section on reloading, but instead returns to the top of the page. This is annoying.

=head1 SEE ALSO

whois(1), autohm(1), CGI(1)

=head1 AUTHOR

Maldwyn G.T. Morris <maldwyn@ripe.net> 

=cut

