source: trunk/npemap.org.uk/cgi/submit.fcgi @ 47

Last change on this file since 47 was 47, checked in by Dominic Hargreaves, 15 years ago

Use a config file for the DB parameters

  • Property svn:executable set to *
File size: 5.5 KB
Line 
1#!/usr/bin/perl
2
3use strict;
4use warnings;
5
6use DBI;
7use CGI::Fast qw/:standard -debug/;
8use Geo::Postcode;
9use Date::Format;
10
11use vars qw($dbname $dbhost $dbuser $dbpass);
12
13sub print_err;
14sub setup_dbh;
15
16# Read in database config
17my $config = 'npemap.conf';
18do $config or die "Can't read $config!\n";
19
20# Set up database handler to try and make sure it's ready for the first
21# request
22# No point in handling errors here since they'll get handled by the request
23# handler
24my $dbh;
25setup_dbh();
26
27
28my @fields = qw(easting northing postcode);
29my $returnBaseURL = 'http://www.npemap.org.uk';
30
31my $cgi;
32# Process incoming requests
33REQUEST: while ($cgi = new CGI::Fast) {
34
35    # If we're given return URL parameters, basic sanity check to stop
36    # funny business
37   
38    my $returnlink = '<a href="/tiles/map.html?' .int($cgi->param('easting')/1000). ",".int($cgi->param('northing')/1000)  . ',1">Go back</a>';   
39
40    if (defined $cgi->param('returnX') and ($cgi->param('returnX') =~ /\d+/) and
41        defined $cgi->param('returnY') and ($cgi->param('returnY') =~ /\d+/) ) {
42        $returnlink = '<a href="' . $returnBaseURL . '/tiles/map.html?' . $cgi->param('returnX') . ',' . $cgi->param('returnY') . ',1">Go back to the map</a>';
43    }
44
45
46    # In case the database went away, make sure we have a connection
47    unless (setup_dbh()) {
48        print_err('Error setting up database connection', $returnlink);
49        next REQUEST;
50    }
51
52    my ($easting, $northing);
53
54    # Input validation
55    foreach my $field (@fields) {
56        unless (defined $cgi->param($field)) {
57            print_err ("Parameter '$field' missing", $returnlink);
58            next REQUEST;
59        }
60    }
61
62    # Is the Easting in a valid range?
63    if (($cgi->param('easting') > 700000) or
64        ($cgi->param('easting') < 0)) {
65        print_err ("Parameter 'easting' must be an integer between 0 and 700,000", $returnlink);
66        next REQUEST;
67    } else {
68        $easting = $cgi->param('easting');
69    }
70
71    # Is the Northing in a valid range?
72    if (($cgi->param('northing') > 1300000) or
73        ($cgi->param('northing') < 0)) {
74        print_err("Parameter 'northing' must be an integer between 0 and 1,300,000", $returnlink);
75        next REQUEST;
76    } else {
77        $northing = $cgi->param('northing');
78    }
79
80    my $sth;
81
82    # Now validate the postcode input format
83    my $raw_postcode = $cgi->param('postcode');
84    my $trimmed_postcode = $raw_postcode; 
85    $trimmed_postcode =~ s/^\s+//;
86    $trimmed_postcode =~ s/\s+$//;
87    my $postcode = Geo::Postcode->new($trimmed_postcode);
88    my ($first, $second, $third, $fourth) = @{$postcode->fragments};
89    my ($outward, $inward);
90
91    if ($postcode->valid) {
92        # We have a complete postcode; input it straight into the database
93        $outward = $first . $second;
94        $inward = $third . $fourth;
95    } elsif($postcode->valid_fragment) {
96        # We have a valid fragment; let's build up what we can
97        # We are guaranteed to have the first two
98        $outward = $first . $second;
99        $inward = '';
100        $inward .= $third if defined $third;
101        $inward .= $fourth if defined $fourth;
102    } else {
103        print_err("The postcode format is not valid", $returnlink);
104        next REQUEST;
105    }
106
107    # Check for a duplicate.
108    # We want to collect duplicates from different IP addresses as a kind of
109    # corroboration factor; this just catches accidental double-submission
110    # really.
111    $sth = $dbh->prepare('SELECT raw_postcode FROM postcodes WHERE raw_postcode = ? AND easting = ? AND northing = ? AND ip = ?');
112    unless ($sth->execute($raw_postcode, $easting, $northing, $ENV{'REMOTE_ADDR'})) {
113        print_err('Database error when checking for duplicate data :(', $returnlink);
114        next REQUEST;
115    }
116
117    if ($sth->rows) {
118        print_err('You, or someone with the same IP address, have already submitted this postcode with these co-ordinates.', $returnlink);
119        next REQUEST;
120    }
121
122    $sth = $dbh->prepare('INSERT INTO postcodes (outward, inward, raw_postcode, easting, northing, ip, created_at, source) VALUES (?, ?, ?, ?, ?, ?, ?, 0)');
123    if ($sth->execute($outward, $inward, $raw_postcode, $easting, $northing, $ENV{'REMOTE_ADDR'}, time2str('%Y-%m-%d %H:%M:%S', time))) {
124        print "Content-type: text/html\n\n";
125        print "<html><head><title>Thank you</title></head>\n";
126        print "<body><p>Thank you for telling us where your post code is!</p>\n";
127        print "<p>$returnlink</p>\n";
128        print "</body></html>";
129        next REQUEST;
130    } else {
131        print STDERR "DB error: " . $dbh->errstr . "\n";
132        print_err("Database error when adding your data :(", $returnlink);
133        next REQUEST;
134    }
135}
136
137# No more requests to serve, so tidy up
138$dbh->disconnect;
139
140# Helper routines
141sub print_err($$) {
142    my $err = shift;
143    my $returnlink = shift;
144    print "Content-type: text/html\n\n";
145    print "<html><head><title>Error submitting</title></head>\n";
146    print "<body><p>The following error occurred whilst submitting data:\n";
147    print CGI::escapeHTML($err);
148    print "</p><p>Your input was:</p>\n<ul>";
149    foreach my $field (@fields) {
150        my $param = $cgi->param($field) || '';
151        print "<li>$field: " . $param . "</li>\n";
152    }
153    print "</ul>\n";
154    print "<p>$returnlink</p>\n";
155    print "</body></html>\n";
156}
157
158sub setup_dbh {
159    # $dbh is global
160    my $data_source = "dbi:Pg:dbname=$dbname";
161    $data_source .= ";host=$dbhost" if $dbhost;
162    return $dbh = DBI->connect_cached($data_source, $dbuser, $dbpass);
163}
164
Note: See TracBrowser for help on using the repository browser.