]> git.sesse.net Git - foosball/blob - www/add-single-result.pl
76edbd043286c37011975375fbe977a7737e99cb
[foosball] / www / add-single-result.pl
1 #! /usr/bin/perl
2 use strict;
3 use warnings;
4 use DBI;
5 use CGI;
6 use CGI::Carp qw(fatalsToBrowser);
7 require '../foosball.pm';
8
9 my $cgi = CGI->new;
10
11 my $username1 = $cgi->param('username1');
12 $username1 =~ /^([a-z][a-z0-9]*)$/ or die "Invalid user name 1";
13 $username1 = $1;
14
15 my $username2 = $cgi->param('username2');
16 $username2 =~ /^([a-z][a-z0-9]*)$/ or die "Invalid user name 2";
17 $username2 = $1;
18
19 my $score1 = $cgi->param('score1');
20 $score1 =~ /^([0-9]|10)$/ or die "Invalid score 1";
21 $score1 = $1;
22
23 my $score2 = $cgi->param('score2');
24 $score2 =~ /^([0-9]|10)$/ or die "Invalid score 2";
25 $score2 = $1;
26
27 my $dbh = foosball::db_connect();
28 $dbh->{AutoCommit} = 0;
29
30 foosball::create_user_if_not_exists($dbh, $username1);
31 foosball::create_user_if_not_exists($dbh, $username2);
32 $dbh->commit;
33
34 # fetch the previous single ratings
35 my ($rating1, $rd1) = foosball::find_single_rating($dbh, $username1);
36 my ($rating2, $rd2) = foosball::find_single_rating($dbh, $username2);
37
38 my $q = $foosball::q;
39
40 my ($newr1, $newrd1) = foosball::calc_rating($rating1, $rd1, $rating2, $rd2, $score1, $score2);
41 my ($newr2, $newrd2) = foosball::calc_rating($rating2, $rd2, $rating1, $rd1, $score2, $score1);
42
43 $dbh->do('INSERT INTO single_results (gametime,username1,username2,score1,score2) VALUES (CURRENT_TIMESTAMP,?,?,?,?)',
44         undef, $username1, $username2, $score1, $score2);
45 $dbh->do('INSERT INTO single_rating (username,ratetime,rating,rd) VALUES (?,CURRENT_TIMESTAMP,?,?,?)',
46         undef, $username1, $newr1, $newrd1, $newr1-$rating1);
47 $dbh->do('INSERT INTO single_rating (username,ratetime,rating,rd) VALUES (?,CURRENT_TIMESTAMP,?,?,?)',
48         undef, $username2, $newr2, $newrd2, $newr2-$rating2);
49
50 $dbh->commit;
51
52 print $cgi->header(-status=>'303 See Other',
53                    -location=>'http://foosball.sesse.net/');
54