# searchme.pl - safeperl CGI example program
#
# Search data file and display paragraphs that match a search term.
#
# Ray Miller <raym@herald.ox.ac.uk>
#
# Copyright (C) 1999 University of Oxford.
#
# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

# The file to be searched (path is relative to ~/cgi)
my $data = "../public_html/data";

sub Die {
    my $body = join("\n", @_);
    print <<"EOT";
<html>
<head>
<title>Form Error</title>
</head>
<body>
$body
</body>
</html>
EOT
    exit;
}

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

my %query = parsed_query();

unless (defined $query{search}) {
    Die("<h1>Serious Form Error</h1>",
	"An invalid search term was specified.",
	"Has the URL been accessed via a form as it should be?");
}

#
# safeperl will catch attempts to open prohibited files
#
open (DATAFILE, $data)
    or Die("<h1>System Error</h1>",
	   "<p>An error occurred when opening the data file.",
	   "<p>Please report this to the administrator of this site.");

my @results;

{
    local $/ = ""; # Entries in the data file are separated by two or more newlines
    while (<DATAFILE>) {
	push(@results, $_) if /\Q$query{search}\E/io;
    }
}

print <<EOT;
<html>
<head>
<title>Search results</title>
</head>
<body>
<h1>Search Results</h1>
EOT

if (@results == 0) {
    print "<p> No matches were found.\n";
} else {
    my $num = @results;
    print "<p> Found $num match", $num == 1 ? "" : "es", "\n<p>\n";
    foreach (@results) {
	print "<p><hr>$_\n";
    }
}

print <<EOT;
<p>
<hr>
<p>Use the <em>back</em> feature of your browser to return to the previous page.
</body>
</html>
EOT
