#!/usr/bin/perl -w
# index.pl:
# Main code for Neighbourhood Fix-It
#
# Copyright (c) 2006 UK Citizens Online Democracy. All rights reserved.
# Email: matthew@mysociety.org. WWW: http://www.mysociety.org
#
# $Id: index.cgi,v 1.44 2006-10-10 17:59:56 matthew Exp $
# TODO
# Nothing is done about the update checkboxes - not stored anywhere on anything!
# Nothing is done with fixed checkbox either
use strict;
require 5.8.0;
# Horrible boilerplate to set up appropriate library paths.
use FindBin;
use lib "$FindBin::Bin/../perllib";
use lib "$FindBin::Bin/../../perllib";
use Error qw(:try);
use File::Slurp;
use Image::Magick;
use LWP::Simple;
use RABX;
use POSIX qw(strftime);
use CGI::Carp;
use Digest::MD5 qw(md5_hex);
use Page;
use mySociety::AuthToken;
use mySociety::Config;
use mySociety::DBHandle qw(dbh select_all);
use mySociety::Email;
use mySociety::GeoUtil;
use mySociety::Util;
use mySociety::MaPit;
use mySociety::VotingArea;
use mySociety::Web qw(ent NewURL);
BEGIN {
mySociety::Config::set_file("$FindBin::Bin/../conf/general");
mySociety::DBHandle::configure(
Name => mySociety::Config::get('BCI_DB_NAME'),
User => mySociety::Config::get('BCI_DB_USER'),
Password => mySociety::Config::get('BCI_DB_PASS'),
Host => mySociety::Config::get('BCI_DB_HOST', undef),
Port => mySociety::Config::get('BCI_DB_PORT', undef)
);
if (!dbh()->selectrow_array('select secret from secret for update of secret')) {
local dbh()->{HandleError};
dbh()->do('insert into secret (secret) values (?)', {}, unpack('h*', mySociety::Util::random_bytes(32)));
}
dbh()->commit();
mySociety::MaPit::configure();
}
# Main code for index.cgi
sub main {
my $q = shift;
my $out = '';
my $title = '';
if ($q->param('submit_problem')) {
$title = 'Submitting your problem';
$out = submit_problem($q);
} elsif ($q->param('submit_update')) {
$title = 'Submitting your update';
$out = submit_update($q);
} elsif ($q->param('submit_map')) {
$title = 'Reporting a problem';
$out = display_form($q);
} elsif ($q->param('id')) {
$title = 'Viewing a problem';
$out = display_problem($q);
} elsif ($q->param('pc')) {
$title = 'Map';
$out = display($q);
} else {
$out = front_page($q);
}
print Page::header($q, $title);
print $out;
print Page::footer();
}
Page::do_fastcgi(\&main);
# Display front page
sub front_page {
my ($q, $error) = @_;
my $pc_h = ent($q->param('pc') || '');
my $out = <Report, view, or discuss local problems
like graffiti, fly tipping, broken paving slabs, or street lighting
EOF
$out .= '
' . $error . 'Please try again.
' if ($error);
$out .= <
Reports are sent directly to the local council – at the moment, we only cover Newham, Lewisham, and Islington councils. The rest of the UK is coming soon!
Reporting a problem is very simple:
Enter a postcode or street name;
Locate the problem on a high-scale map;
Enter details of the problem;
Submit to your council.
EOF
return $out;
}
sub submit_update {
my $q = shift;
my @vars = qw(id name email update updates fixed);
my %input = map { $_ => $q->param($_) || '' } @vars;
my @errors;
push(@errors, 'Please enter a message') unless $input{update};
push(@errors, 'Please enter your name') unless $input{name};
push(@errors, 'Please enter your email') unless $input{email};
return display_problem($q, @errors) if (@errors);
my $template = File::Slurp::read_file("$FindBin::Bin/../templates/emails/update-confirm");
my $id = dbh()->selectrow_array("select nextval('comment_id_seq');");
dbh()->do("insert into comment
(id, problem_id, name, email, website, text, state)
values (?, ?, ?, ?, ?, ?, 'unconfirmed')", {},
$id, $input{id}, $input{name}, $input{email}, '', $input{update});
my %h = ();
$h{update} = $input{update};
$h{name} = $input{name};
$h{url} = mySociety::Config::get('BASE_URL') . '/C/' . mySociety::AuthToken::store('update', $id);
dbh()->commit();
my $email = mySociety::Email::construct_email({
_template_ => $template,
_parameters_ => \%h,
From => [mySociety::Config::get('CONTACT_EMAIL'), 'Neighbourhood Fix-It'],
To => [[$input{email}, $input{name}]],
});
my $result = mySociety::Util::send_email($email, mySociety::Config::get('CONTACT_EMAIL'), $input{email});
my $out;
if ($result == mySociety::Util::EMAIL_SUCCESS) {
$out = <Nearly Done! Now check your email...
The confirmation email may take a few minutes to arrive — please be patient.
If you use web-based email or have 'junk mail' filters, you may wish to check your bulk/spam mail folders: sometimes, our messages are marked that way.
You must now click on the link within the email we've just sent you -
if you do not, your update will not be posted.
(Don't worry - we'll hang on to your update while you're checking your email.)
EOF
} else {
$out = <I'm afraid something went wrong when we tried to send your email. Please click Back, check your details, and try again.
EOF
}
return $out;
}
sub submit_problem {
my $q = shift;
my @vars = qw(title detail name email phone pc easting northing updates);
my %input = map { $_ => $q->param($_) || '' } @vars;
my @errors;
push(@errors, 'Please enter a title') unless $input{title};
push(@errors, 'Please enter some details') unless $input{detail};
push(@errors, 'Please enter your name') unless $input{name};
push(@errors, 'Please enter your email') unless $input{email};
return display_form($q, @errors) if (@errors);
my $template = File::Slurp::read_file("$FindBin::Bin/../templates/emails/problem-confirm");
my $id = dbh()->selectrow_array("select nextval('problem_id_seq');");
my $image;
if (my $fh = $q->upload('photo')) {
my $ct = $q->uploadInfo($fh)->{'Content-Type'};
my $cd = $q->uploadInfo($fh)->{'Content-Disposition'};
$q->delete('photo');
return display_form($q, ('Please upload an image only')) unless
($ct eq 'image/jpeg' || $ct eq 'image/pjpeg');
$image = Image::Magick->new;
$image->Read(file=>$fh);
close $fh;
$image->Scale(geometry=>"250x250>");
my @blobs = $image->ImageToBlob();
undef $image;
$image = $blobs[0];
}
# This is horrid
my $s = dbh()->prepare("insert into problem
(id, postcode, easting, northing, title, detail, name, email, phone, photo, state)
values
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'unconfirmed')");
$s->bind_param(1, $id);
$s->bind_param(2, $input{pc});
$s->bind_param(3, $input{easting});
$s->bind_param(4, $input{northing});
$s->bind_param(5, $input{title});
$s->bind_param(6, $input{detail});
$s->bind_param(7, $input{name});
$s->bind_param(8, $input{email});
$s->bind_param(9, $input{phone});
$s->bind_param(10, $image, { pg_type => DBD::Pg::PG_BYTEA });
$s->execute();
my %h = ();
$h{title} = $input{title};
$h{detail} = $input{detail};
$h{name} = $input{name};
$h{url} = mySociety::Config::get('BASE_URL') . '/P/' . mySociety::AuthToken::store('problem', $id);
dbh()->commit();
my $email = mySociety::Email::construct_email({
_template_ => $template,
_parameters_ => \%h,
From => [mySociety::Config::get('CONTACT_EMAIL'), 'Neighbourhood Fix-It'],
To => [[$input{email}, $input{name}]],
});
my $result = mySociety::Util::send_email($email, mySociety::Config::get('CONTACT_EMAIL'), $input{email});
my $out;
if ($result == mySociety::Util::EMAIL_SUCCESS) {
$out = <Nearly Done! Now check your email...
The confirmation email may take a few minutes to arrive — please be patient.
If you use web-based email or have 'junk mail' filters, you may wish to check your bulk/spam mail folders: sometimes, our messages are marked that way.
You must now click on the link within the email we've just sent you -
if you do not, your problem will not be posted on the site.
(Don't worry - we'll hang on to your information while you're checking your email.)
EOF
} else {
$out = <I'm afraid something went wrong when we tried to send your email. Please click Back, check your details, and try again.
EOF
}
return $out;
}
sub display_form {
my ($q, @errors) = @_;
my ($pin_x, $pin_y, $pin_tile_x, $pin_tile_y);
my @vars = qw(title detail name email phone updates pc easting northing x y skipped);
my %input = map { $_ => $q->param($_) || '' } @vars;
my %input_h = map { $_ => $q->param($_) ? ent($q->param($_)) : '' } @vars;
my @ps = $q->param;
foreach (@ps) {
($pin_tile_x, $pin_tile_y, $pin_x) = ($1, $2, $q->param($_)) if /^tile_(\d+)\.(\d+)\.x$/;
$pin_y = $q->param($_) if /\.y$/;
}
return display($q)
unless $input{skipped} || ($pin_x && $pin_y)
|| ($input{easting} && $input{northing});
my $out = '';
if ($input{skipped}) {
$out .= <
Reporting a problem
Please fill in the form below with details of the problem, and
describe the location as precisely as possible in the details box.
EOF
} else {
my ($px, $py, $easting, $northing);
if ($pin_x && $pin_y) {
# Map was clicked on
$pin_x = click_to_tile($pin_tile_x, $pin_x);
$pin_y = click_to_tile($pin_tile_y, $pin_y, 1);
$px = tile_to_px($pin_x, $input{x});
$py = tile_to_px($pin_y, $input{y});
$easting = tile_to_os($pin_x);
$northing = tile_to_os($pin_y);
} else {
# Normal form submission
$px = os_to_px($input{easting}, $input{x});
$py = os_to_px($input{northing}, $input{y});
$easting = $input_h{easting};
$northing = $input_h{northing};
}
# XXX: How to do this for not London?
# Needs to return all council types, so passing in an array of types would be good
# And then display choice to user
my $council = mySociety::MaPit::get_voting_area_by_location_en($easting, $northing, 'polygon', 'LBO');
my $areas_info = mySociety::MaPit::get_voting_areas_info($council);
$council = join(', ', map { $areas_info->{$_}->{name} } @$council);
my $pins = display_pin($q, $px, $py, 'purple');
$out .= display_map($q, $input{x}, $input{y}, 2, 1, $pins);
if ($px && $py) {
$out .= <
drag_x = $px - 254; drag_y = 254 - $py;
EOF
}
$out .= '
Reporting a problem
';
$out .= '
You have located the problem at the location marked with a yellow pin on the map, which is within '
. $council . '. If this is not the correct location, simply click on the map again.
Please fill in details of the problem below. Your council won\'t be able
to help unless you leave as much detail as you can, so please describe the
exact location of the problem (ie. on a wall or the floor), and so on.
EOF
$out .= display_map_end(1);
return $out;
}
sub display {
my ($q, @errors) = @_;
my @vars = qw(pc x y);
my %input = map { $_ => $q->param($_) || '' } @vars;
my %input_h = map { $_ => $q->param($_) ? ent($q->param($_)) : '' } @vars;
my($error, $x, $y, $name);
try {
if (mySociety::Util::is_valid_postcode($input{pc})) {
($name, $x, $y) = postcode_check($input{pc}, $input{x}, $input{y});
} else {
$x = $input{x}; $y = $input{y};
$x ||= 0; $x += 0;
$y ||= 0; $y += 0;
if (!$x && !$y) {
my @loc = split /\s*,\s*/, $input{pc};
#if (2 == @loc) {
# my $url = 'http://geo.localsearchmaps.com/?country=UK&cb=cb&cbe=cbe&address='.$loc[0].'&city='.$loc[1];
# my $js = LWP::Simple::get($url);
my $cache_dir = mySociety::Config::get('GEO_CACHE');
if (1 == @loc) {
my $url = 'http://geo.localsearchmaps.com/?country=UK&format=xml&address='.$loc[0].'&city=London';
my $cache_file = $cache_dir . md5_hex($url);
my $js;
if (-e $cache_file) {
$js = File::Slurp::read_file($cache_file);
} else {
$js = LWP::Simple::get($url);
File::Slurp::write_file($cache_file, $js);
}
if ($js =~ /^\s+(.*?)\s+<\/response>$/s) {
my $response = $1;
my ($e) = $response =~ /(.*?)<\/error>/;
my ($lat) = $response =~ /(.*?)<\/latitude>/;
my ($lon) = $response =~ /(.*?)<\/longitude>/;
my ($level) = $response =~ /(.*?)<\/matchlevel>/;
if ($e) {
$error = $e;
} elsif ($level =~ /city/i) {
$error = 'Could not understand that currently, sorry. ';
} else {
my ($easting,$northing) = mySociety::GeoUtil::wgs84_to_national_grid($lat, $lon, 'G');
$x = int(os_to_tile($easting))-1;
$y = int(os_to_tile($northing))-1;
}
} else {
$error = 'Could not understand that currently, sorry. ';
}
} else {
$error = 'Could not understand that currently, sorry. ';
}
}
}
} catch RABX::Error with {
my $e = shift;
if ($e->value() == mySociety::MaPit::BAD_POSTCODE
|| $e->value() == mySociety::MaPit::POSTCODE_NOT_FOUND) {
$error = 'That postcode was not recognised, sorry. ';
} else {
$error = $e;
}
} catch Error::Simple with {
my $e = shift;
$error = $e;
};
return front_page($q, $error) if ($error);
my $pins = '';
my $min_e = tile_to_os($x);
my $min_n = tile_to_os($y);
my $mid_e = tile_to_os($x+1);
my $mid_n = tile_to_os($y+1);
my $max_e = tile_to_os($x+2);
my $max_n = tile_to_os($y+2);
my $current_map = select_all(
"select id,title,easting,northing from problem where state='confirmed'
and easting>=? and easting and northing>=? and northing
order by created desc limit 5", $min_e, $max_e, $min_n, $max_n);
my @ids = ();
foreach (@$current_map) {
push(@ids, $_->{id});
my $px = os_to_px($_->{easting}, $x);
my $py = os_to_px($_->{northing}, $y);
$pins .= display_pin($q, $px, $py, 'red');
}
my $current = select_all(
"select id, title, easting, northing, distance
from problem_find_nearby(?, ?, 10) as nearby, problem
where nearby.problem_id = problem.id
and state = 'confirmed'" . (@ids ? ' and id not in (' . join(',' , @ids) . ')' : '') . "
order by created desc limit 5", $mid_e, $mid_n);
foreach (@$current) {
my $px = os_to_px($_->{easting}, $x);
my $py = os_to_px($_->{northing}, $y);
$pins .= display_pin($q, $px, $py, 'red');
}
my $fixed = select_all(
"select easting, northing from problem where state='fixed'
order by created desc limit 5");
foreach (@$fixed) {
my $px = os_to_px($_->{easting}, $x);
my $py = os_to_px($_->{northing}, $y);
$pins .= display_pin($q, $px, $py, 'green');
}
my $out = '';
$out .= display_map($q, $x, $y, 1, 1, $pins);
$out .= '
Click on the map to report a problem
';
if (@errors) {
$out .= '
' . join('
', @errors) . '
';
}
my $skipurl = NewURL($q, 'submit_map'=>1, skipped=>1);
$out .= <If you cannot see a map – if you have images turned off,
or are using a text only browser, for example – and you
wish to report a problem, please
skip this step and we will ask you
to describe the location of your problem instead.
EOF
$out .= <
';
# Display updates
my $updates = select_all(
"select id, name, extract(epoch from whenposted) as whenposted, text
from comment where problem_id = ? and state='confirmed'
order by whenposted desc", $input{id});
if (@$updates) {
$out .= '
Updates
';
foreach my $row (@$updates) {
$out .= "
Posted by $row->{name} at " . prettify_epoch($row->{whenposted}) . '';
$out .= ' ' . $row->{text} . '
';
}
$out .= '
';
}
$out .= '
Provide an update
';
if (@errors) {
$out .= '
' . join('
', @errors) . '
';
}
$updates = (!defined($q->param('updates')) || $input{updates}) ? ' checked' : '';
my $fixed = ($input{fixed}) ? ' checked' : '';
# XXX: Should we have website too?
$out .= <
EOF
$out .= display_map_end(0);
return $out;
}
# display_map Q X Y TYPE COMPASS PINS
# X,Y is bottom left tile of 2x2 grid
# TYPE is 1 if the map is clickable, 0 if not
# COMPASS is 1 to show the compass, 0 to not
# PINS is HTML of pins to show
sub display_map {
my ($q, $x, $y, $type, $compass, $pins) = @_;
$pins ||= '';
my $url = mySociety::Config::get('TILES_URL');
my $tiles_url = $url . $x . '-' . ($x+1) . ',' . $y . '-' . ($y+1) . '/RABX';
my $tiles = LWP::Simple::get($tiles_url);
throw Error::Simple("Unable to get tiles from URL $tiles_url\n") if !$tiles;
my $tileids = RABX::unserialise($tiles);
my $tl = $x . '.' . ($y+1);
my $tr = ($x+1) . '.' . ($y+1);
my $bl = $x . '.' . $y;
my $br = ($x+1) . '.' . $y;
my $tl_src = $url . $tileids->[0][0];
my $tr_src = $url . $tileids->[0][1];
my $bl_src = $url . $tileids->[1][0];
my $br_src = $url . $tileids->[1][1];
my $out = '';
my $img_type;
if ($type) {
my $encoding = '';
$encoding = ' enctype="multipart/form-data"' if ($type==2);
my $pc_enc = ent($q->param('pc'));
$out .= <
EOF
$img_type = '
var x = $x - 2; var y = $y - 2;
var drag_x = 0; var drag_y = 0;