source: trunk/npemap.org.uk/cgi/bad-postcode.fcgi @ 238

Last change on this file since 238 was 238, checked in by Dominic Hargreaves, 14 years ago

Make CGIs use shared error functions.

  • Property svn:executable set to *
File size: 2.4 KB
Line 
1#!/usr/bin/perl
2#
3# Copyright (c) 2006 Dominic Hargreaves
4# See accompanying file "LICENCE" for licence details
5
6use strict;
7use warnings;
8
9use DBI;
10use CGI::Fast qw/:standard -debug/;
11
12# Find our private perl libraries
13use FindBin;
14use lib "$FindBin::Bin/../perllib";
15use NPEMap;
16
17# Set up database handler to try and make sure it's ready for the first
18# request
19# No point in handling errors here since they'll get handled by the request
20# handler
21my $dbh = setup_dbh();
22
23my $returnBaseURL = '';
24
25my $cgi;
26# Process incoming requests
27REQUEST: while ($cgi = new CGI::Fast) {
28
29    # If we're given return URL parameters, basic sanity check to stop
30    # funny business
31    my $returnURL= '/tiles/map.html';
32    if (defined $ENV{HTTP_REFERER}) {
33        $returnURL = $ENV{HTTP_REFERER};
34    }
35
36    my $returnlink = "<a href='$returnURL'>Go back to the map</a>";
37
38    # In case the database went away, make sure we have a connection
39    unless ($dbh = setup_dbh()) {
40        print_html_err('Error setting up database connection', $returnlink);
41        next REQUEST;
42    }
43
44    # Input validation
45    unless (defined $cgi->param('postcode')) {
46        print_html_err ("Postcode identifier not supplied", $returnlink);
47        next REQUEST;
48    }
49
50    # Check that the requested ID exists
51    my $sth = $dbh->prepare('SELECT id FROM postcodes WHERE id = ? AND NOT deleted');
52    unless ($sth->execute($cgi->param('postcode'))) {
53        print_html_err('Database error when checking for the postcode', $returnlink);
54        next REQUEST;
55    }
56
57    unless ($sth->rows) {
58        print_html_err('A postcode with that identifier does not exist, or has already been deleted.', $returnlink);
59        next REQUEST;
60    }
61
62    $sth = $dbh->prepare('INSERT INTO bad_postcodes (postcode, ip, reason, reporter_email) VALUES (?, ?, ?, ?)');
63    if ($sth->execute($cgi->param('postcode'), $ENV{'REMOTE_ADDR'}, $cgi->param('reason') || undef, $cgi->param('email') || undef)) {
64        print "Content-type: text/html\n\n";
65        print "<html><head><title>Thank you</title></head>\n";
66        print "<body><p>Thank you for reporting the bad post code!</p>\n";
67        print "<p>$returnlink</p>\n";
68        print "</body></html>";
69        next REQUEST;
70    } else {
71        print STDERR "DB error: " . $dbh->errstr . "\n";
72        print_html_err("Database error when adding your data :(", $returnlink);
73        next REQUEST;
74    }
75}
76
77# No more requests to serve, so tidy up
78$dbh->disconnect;
Note: See TracBrowser for help on using the repository browser.