#!/usr/bin/perl
#
#$Id: WebRman,v 1.2 1997/10/26 19:54:56 root Exp root $
#
################################################################################
#                                                                              #
# WebRman v1.1 - the CGI interface to RosettaMan                               #
#                                                                              #
################################################################################
# Written by Olivier Bourquin <bourquin@bluewin.ch>, inspired by               #
# rman.pl by Alexander Gagin <gagin@cvxct0.jinr.dubna.su> and                  #
# http-rman by Fredrik Lundh <fredrik_lundh@ivab.se>.                          #
#                                                                              #
# Many many thanks to Thomas A. Phelps (phelps@ACM.org) for                    #
# his magnificent RosettaMan.                                                  #
# RosettaMan is available at                                                   #
# ftp://ftp.cs.berkeley.edu/ucb/people/phelps/tcltk/rman.tar.Z                 #
#                                                                              #
# NOTE: Version 3.0 of rman or higher is required!!!                           #
#                                                                              #
# Copyright (C) 1997-2000 Olivier Bourquin                                     #
# All Rights Reserved.                                                         #
#                                                                              #
# Here some word of advise...                                                  #
#                                                                              #
# PERMISSION IS GRANTED TO DISTRIBUTE THIS SOFTWARE FREELY, WITH THE           #
# EXCEPTION THAT ONE MAY NOT CHARGE FOR IT OR INCLUDE IT WITH SOFTWARE         #
# WHICH IS SOLD.  Permission to use, copy, modify, and distribute this         #
# software and its documentation for educational, research, internal           #
# corporate and non-profit purposes, without fee, and without a written        #
# agreement is hereby granted for all cases that do not conflict with          #
# the restriction in the first sentence of this paragraph, provided that       #
# the above copyright notice, this paragraph, and the following three          #
# paragraphs appear in all copies.                                             #
#                                                                              #
# Permission to incorporate this software into commercial products may         #
# be obtained from the author Olivier Bourquin <bourquin@bluewin.ch>.          #
#                                                                              #
# IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,    #
# SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF      #
# THIS SOFTWARE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF     #
# SUCH DAMAGE.                                                                 #
#                                                                              #
# THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED #
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR   #
# PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE     #
# AUTHOR HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,           #
# ENHANCEMENTS, OR MODIFICATIONS.                                              #
#                                                                              #
#                                                                              #
################################################################################
#                                                                              #
# Configurable section - Change the values below...                            #
#                                                                              #
################################################################################

# URL of the background picture desired
$background="/images/help-back.jpg";

# Name of the person to be contacted
$webmaster='the webmaster';

# and his/her mail address
$webmail='webmaster@oli.isoe.ch';

# path to the 'man' program
$man='/usr/bin/man';

# colon separated list of paths to man directories
$manpath='/usr/man:/usr/X11R6/man:/usr/local/man:/usr/openwin/man'; 

# path to RosettaMan program.
$rman='/usr/bin/rman';

# footpage of every produced html document
$footpage='
<hr><A HREF="http://gromit.isoe.ch/help/man">Look up another man page</a><br>
<A HREF="http://gromit.isoe.ch/help">Back to Gromit\'s Help Page</a><br>
<A HREF="http://gromit.isoe.ch/">Back to Gromit\'s Homepage</a><br>
<a href="mailto:webmaster@gromit.isoe.ch">Send a mail to the Webmaster</a> 
';

# $form defines what the query form should look like.
# The form must have three fields:
# "topic"   : text field where the topic searched is entered
# "section" : possibles man sections, and "all"
# "keyword" : check box allowing "apropos" (man -k)
#
#  Check the action as well (method=GET and action=URL to the program)!

$form='
<H1>WebRman - THE Gateway to Manual pages</H1>
<FORM METHOD="GET" ACTION="/cgi-bin/WebRman">
<table cellpadding=10><tr><td>Enter a command:</td><td>
<INPUT NAME="topic" SIZE="30">
<BR></td></tr><tr><td>
choose a manual-section:</td><td>
<select name="section">
<option VALUE="all">All sections
<option VALUE="1">User commands
<option VALUE="2">System calls
<option VALUE="3">Library functions
<option VALUE="4">Special devices
<option VALUE="5">Fileformats
<option VALUE="6">Games
<option VALUE="7">Misc
<option VALUE="8">Commands for sysadmin
<option VALUE="9">Filesystem
<option VALUE="n">New
</select></td></tr>
<tr><td>
<INPUT TYPE="checkbox" NAME="keyword">  or search only for keyword<br>
(section will be ignored then)</td></tr></table><p>... and ...
<INPUT TYPE="submit" VALUE="            Search!            ">
</FORM>
';



################################################################################
#                                                                              #
# End of configation                                                           #
#                                                                              #
# from here on, I am on my own...

$tail=$footpage . '<hr><font size=-2>WebRman &copy; 1997-2000, <a href=
      mailto:bourquin@bluewin.ch>Olivier Bourquin</a><br>
      RosettaMan &copy; 1993-1996, <a href=mailto:"phelps@ACM.org">
      Thomas A. Phelps</a> </font>';

$script=$ENV{'SCRIPT_NAME'};

&parse_form;
$topic=$FORM{'topic'};
$section=$FORM{'section'};
$keyword=$FORM{'keyword'};


if( $ENV{'QUERY_STRING'} eq "" ){
	&print_header("Entry-form");
    print $form;
    print $tail;
	exit;
}

&return_error(500,"No topic!","Please enter what you're looking for...")
unless (($topic) ne "");

if ($keyword eq "on"){
	&search_keyword;
}

else { 
	&show_page;
}

################################################################################
# sub to return the man -k

sub search_keyword {
	
	open(MANK,"$man -M $manpath -k $topic |") ||
		&return_error (500,"System error",
			"Can't open pipe $man -M $manpath -k $topic |: $!\n");
	read(MANK,$x,100);
	&return_error(500,"Nothing found",
		 "Nothing could be found for <em>$topic</em>.")
		if ($x =~ /nothing appro/i);

	&print_header("Keyword search results for $topic");
	print "<h1>Keyword search results for <em>$topic</em></h1>\n";
	print "<table border=0 cellpadding=2>\n";
	
	while(<MANK>) {
		if ($_=~/^(.+) \((\S+)\)\s+\- (.+)$/) {
		print "<tr><td><tt>";
		print "<A HREF=\"$script?topic=$1\&section=$2\">";
		print "<b>$1 ($2)</b></a></tt></td>";
		print "<td>&nbsp;&nbsp;&nbsp; - &nbsp;&nbsp;&nbsp;</td>";
		print "<td>$3</td></tr>\n";
		}
	}
	print "</table>\n";
	print $tail;
	exit;
}

################################################################################
# sub to return the manual page

sub show_page {

	$|=1;
    $section="" if ($section eq "all");

	open(MAN,"$man -M $manpath $section $topic |") ||
		&return_error (500,"System error",
			"Can't open pipe $man -M $manpath -k $topic |: $!\n");

	read( MAN,$x,100);
	if ($x=~ /^no manu/i){
		&return_error(500,"Man page not found",
			"The manual page of <em>$topic ($section)</em> doesn't exist!");
	}

	print "Content-type: text/html\n\n";

	open (RMAN,"| $rman -f html -b -r \"$script?topic=%s\&section=%s\" -l \"$topic ($section) Manual Page\"") ||
		&return_error (500,"System error",
			"Can't open pipe | $rman : $!\n");

	my $err=0;
	while (<MAN>){
		print RMAN $_;
	}
	close MAN;
	close RMAN;
	print $tail;

}

################################################################################
# Sub to parse the form data

sub parse_form {

   if ($ENV{'REQUEST_METHOD'} eq 'GET') {
      # Split the name-value pairs
      @pairs = split(/&/, $ENV{'QUERY_STRING'});
   } 
   else {
      &return_error (500, "Server Error", "Server uses unsupported method");
    }

   foreach $pair (@pairs) {

      ($name, $value) = split(/=/, $pair);
 
      $name =~ tr/+/ /;
      $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

      $value =~ tr/+/ /;
      $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

      # If they try to include server side includes, erase them, so they
      # arent a security risk if the html gets returned. 
      $value =~ s/<!--(.|\n)*-->//g;
      $FORM{$name} = $value;
   }
}

################################################################################
# Sub that returns the header

sub print_header  {

    local ($title,$nocache) = @_;
    print "Content-type: text/html\n\n";
    print "<HTML><HEAD>\n";
    print "<TITLE>WebRman - $title</TITLE></HEAD>\n";
    print "<BODY background=$background>";
}


################################################################################
# Sub to return nice errors

sub return_error {
    local ($status, $keyword, $message) = @_;

    print "Content-type: text/html\n";
    print "Status: ", $status, " ", $keyword, "\n\n";

    print <<"End_of_Error";
<head>
<title>WebRman - Error</title>
</head>
<body background=$background>
<h1>$keyword</h1>
<h4>$message</h4>
Please contact <a href=mailto:$webmail>$webmaster</a> for more information.

End_of_Error

	print $tail;
    exit -1;
}


