votes.cgi 13 KB
Newer Older
1
#!/usr/bin/perl -wT
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Terry Weissman <terry@mozilla.org>
#                 Stephan Niemz  <st.n@gmx.net>
#                 Christopher Aillon <christopher@aillon.com>
#                 Gervase Markham <gerv@gerv.net>
25
#                 Frédéric Buclin <LpSolit@gmail.com>
26 27

use strict;
28
use lib qw(. lib);
29

30
use Bugzilla;
31
use Bugzilla::Constants;
32 33
use Bugzilla::Util;
use Bugzilla::Error;
34
use Bugzilla::Bug;
35
use Bugzilla::User;
36
use Bugzilla::Product;
37

38 39
use List::Util qw(min);

40
my $cgi = Bugzilla->cgi;
41
local our $vars = {};
42

43 44 45 46 47 48 49 50
# If the action is show_bug, you need a bug_id.
# If the action is show_user, you can supply a userid to show the votes for
# another user, otherwise you see your own.
# If the action is vote, your votes are set to those encoded in the URL as 
# <bug_id>=<votes>.
#
# If no action is defined, we default to show_bug if a bug_id is given,
# otherwise to show_user.
51 52
my $bug_id = $cgi->param('bug_id');
my $action = $cgi->param('action') || ($bug_id ? "show_bug" : "show_user");
53 54

if ($action eq "show_bug" ||
55
    ($action eq "show_user" && defined $cgi->param('user_id')))
56
{
57
    Bugzilla->login();
58 59
}
else {
60
    Bugzilla->login(LOGIN_REQUIRED);
61 62 63 64 65 66 67 68
}

################################################################################
# Begin Data/Security Validation
################################################################################

# Make sure the bug ID is a positive integer representing an existing
# bug that the user is authorized to access.
69

70 71 72 73
if (defined $bug_id) {
    my $bug = Bugzilla::Bug->check($bug_id);
    $bug_id = $bug->id;
}
74 75 76 77 78 79

################################################################################
# End Data/Security Validation
################################################################################

if ($action eq "show_bug") {
80
    show_bug($bug_id);
81 82
} 
elsif ($action eq "show_user") {
83
    show_user($bug_id);
84 85
}
elsif ($action eq "vote") {
86
    record_votes() if Bugzilla->params->{'usevotes'};
87
    show_user($bug_id);
88 89
}
else {
90
    ThrowCodeError("unknown_action", {action => $action});
91 92 93 94 95 96
}

exit;

# Display the names of all the people voting for this one bug.
sub show_bug {
97
    my ($bug_id) = @_;
98
    my $cgi = Bugzilla->cgi;
99
    my $dbh = Bugzilla->dbh;
100
    my $template = Bugzilla->template;
101

102 103
    ThrowCodeError("missing_bug_id") unless defined $bug_id;

104
    $vars->{'bug_id'} = $bug_id;
105
    $vars->{'users'} =
106 107 108
        $dbh->selectall_arrayref('SELECT profiles.login_name,
                                         profiles.userid AS id,
                                         votes.vote_count
109 110 111 112 113 114
                                    FROM votes
                              INNER JOIN profiles 
                                      ON profiles.userid = votes.who
                                   WHERE votes.bug_id = ?',
                                  {'Slice' => {}}, $bug_id);

115
    print $cgi->header();
116 117
    $template->process("bug/votes/list-for-bug.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
118 119 120 121 122
}

# Display all the votes for a particular user. If it's the user
# doing the viewing, give them the option to edit them too.
sub show_user {
123
    my ($bug_id) = @_;
124
    my $cgi = Bugzilla->cgi;
125
    my $dbh = Bugzilla->dbh;
126
    my $user = Bugzilla->user;
127
    my $template = Bugzilla->template;
128

129
    # If a bug_id is given, and we're editing, we'll add it to the votes list.
130
    $bug_id ||= "";
131

132 133
    my $who_id = $cgi->param('user_id') || $user->id;
    my $who = Bugzilla::User->check({ id => $who_id });
134

135 136
    my $canedit = (Bugzilla->params->{'usevotes'} && $user->id == $who->id) 
                  ? 1 : 0;
137

138
    $dbh->bz_start_transaction();
139

140 141 142
    if ($canedit && $bug_id) {
        # Make sure there is an entry for this bug
        # in the vote table, just so that things display right.
143 144
        my $has_votes = $dbh->selectrow_array('SELECT vote_count FROM votes 
                                               WHERE bug_id = ? AND who = ?',
145
                                               undef, ($bug_id, $who->id));
146 147
        if (!$has_votes) {
            $dbh->do('INSERT INTO votes (who, bug_id, vote_count) 
148
                      VALUES (?, ?, 0)', undef, ($who->id, $bug_id));
149 150
        }
    }
151

152
    my @all_bug_ids;
153
    my @products;
154 155 156 157 158
    my $products = $user->get_selectable_products;
    # Read the votes data for this user for each product.
    foreach my $product (@$products) {
        next unless ($product->votes_per_user > 0);

159
        my @bugs;
160
        my @bug_ids;
161 162
        my $total = 0;
        my $onevoteonly = 0;
163 164 165

        my $vote_list =
            $dbh->selectall_arrayref('SELECT votes.bug_id, votes.vote_count,
166
                                             bugs.short_desc
167 168 169 170 171
                                        FROM votes
                                  INNER JOIN bugs
                                          ON votes.bug_id = bugs.bug_id
                                       WHERE votes.who = ?
                                         AND bugs.product_id = ?
172
                                    ORDER BY votes.bug_id',
173
                                      undef, ($who->id, $product->id));
174 175

        foreach (@$vote_list) {
176
            my ($id, $count, $summary) = @$_;
177
            $total += $count;
178

179 180 181 182
            # Next if user can't see this bug. So, the totals will be correct
            # and they can see there are votes 'missing', but not on what bug
            # they are. This seems a reasonable compromise; the alternative is
            # to lie in the totals.
183
            next if !$user->can_see_bug($id);
184

185 186
            push (@bugs, { id => $id, 
                           summary => $summary,
187
                           count => $count });
188 189
            push (@bug_ids, $id);
            push (@all_bug_ids, $id);
190
        }
191 192 193 194

        $onevoteonly = 1 if (min($product->votes_per_user,
                                 $product->max_votes_per_bug) == 1);

195
        # Only add the product for display if there are any bugs in it.
196 197
        if ($#bugs > -1) {
            push (@products, { name => $product->name,
198
                               bugs => \@bugs,
199
                               bug_ids => \@bug_ids,
200 201
                               onevoteonly => $onevoteonly,
                               total => $total,
202 203
                               maxvotes => $product->votes_per_user,
                               maxperbug => $product->max_votes_per_bug });
204 205 206
        }
    }

207
    $dbh->do('DELETE FROM votes WHERE vote_count <= 0');
208
    $dbh->bz_commit_transaction();
209 210

    $vars->{'canedit'} = $canedit;
211
    $vars->{'voting_user'} = { "login" => $who->name };
212
    $vars->{'products'} = \@products;
213
    $vars->{'bug_id'} = $bug_id;
214
    $vars->{'all_bug_ids'} = \@all_bug_ids;
215

216
    print $cgi->header();
217 218
    $template->process("bug/votes/list-for-user.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
219 220 221 222 223 224 225 226
}

# Update the user's votes in the database.
sub record_votes {
    ############################################################################
    # Begin Data/Security Validation
    ############################################################################

227
    my $cgi = Bugzilla->cgi;
228
    my $dbh = Bugzilla->dbh;
229
    my $template = Bugzilla->template;
230

231 232 233
    # Build a list of bug IDs for which votes have been submitted.  Votes
    # are submitted in form fields in which the field names are the bug 
    # IDs and the field values are the number of votes.
234 235

    my @buglist = grep {/^[1-9][0-9]*$/} $cgi->param();
236 237 238 239

    # If no bugs are in the buglist, let's make sure the user gets notified
    # that their votes will get nuked if they continue.
    if (scalar(@buglist) == 0) {
240
        if (!defined $cgi->param('delete_all_votes')) {
241
            print $cgi->header();
242 243
            $template->process("bug/votes/delete-all.html.tmpl", $vars)
              || ThrowTemplateError($template->error());
244 245
            exit();
        }
246
        elsif ($cgi->param('delete_all_votes') == 0) {
247
            print $cgi->redirect("votes.cgi");
248 249 250 251
            exit();
        }
    }

252
    # Call check() on each bug ID to make sure it is a positive
253 254 255 256
    # integer representing an existing bug that the user is authorized 
    # to access, and make sure the number of votes submitted is also
    # a non-negative integer (a series of digits not preceded by a
    # minus sign).
257
    my %votes;
258
    foreach my $id (@buglist) {
259 260
      my $bug = Bugzilla::Bug->check($id);
      $id = $bug->id;
261 262
      $votes{$id} = $cgi->param($id);
      detaint_natural($votes{$id}) 
263
        || ThrowUserError("votes_must_be_nonnegative");
264 265 266 267 268
    }

    ############################################################################
    # End Data/Security Validation
    ############################################################################
269
    my $who = Bugzilla->user->id;
270 271 272 273 274

    # If the user is voting for bugs, make sure they aren't overstuffing
    # the ballot box.
    if (scalar(@buglist)) {
        my %prodcount;
275
        my %products;
276 277
        # XXX - We really need a $bug->product() method.
        foreach my $bug_id (@buglist) {
278
            my $bug = new Bugzilla::Bug($bug_id);
279
            my $prod = $bug->product;
280
            $products{$prod} ||= new Bugzilla::Product({name => $prod});
281
            $prodcount{$prod} ||= 0;
282 283
            $prodcount{$prod} += $votes{$bug_id};

284
            # Make sure we haven't broken the votes-per-bug limit
285
            ($votes{$bug_id} <= $products{$prod}->max_votes_per_bug)
286
              || ThrowUserError("too_many_votes_for_bug",
287 288 289
                                {max => $products{$prod}->max_votes_per_bug,
                                 product => $prod,
                                 votes => $votes{$bug_id}});
290 291 292 293
        }

        # Make sure we haven't broken the votes-per-product limit
        foreach my $prod (keys(%prodcount)) {
294
            ($prodcount{$prod} <= $products{$prod}->votes_per_user)
295
              || ThrowUserError("too_many_votes_for_product",
296 297
                                {max => $products{$prod}->votes_per_user,
                                 product => $prod,
298
                                 votes => $prodcount{$prod}});
299 300 301 302 303 304 305 306 307 308
        }
    }

    # Update the user's votes in the database.  If the user did not submit 
    # any votes, they may be using a form with checkboxes to remove all their
    # votes (checkboxes are not submitted along with other form data when
    # they are not checked, and Bugzilla uses them to represent single votes
    # for products that only allow one vote per bug).  In that case, we still
    # need to clear the user's votes from the database.
    my %affected;
309
    $dbh->bz_start_transaction();
310 311
    
    # Take note of, and delete the user's old votes from the database.
312 313 314 315
    my $bug_list = $dbh->selectcol_arrayref('SELECT bug_id FROM votes
                                             WHERE who = ?', undef, $who);

    foreach my $id (@$bug_list) {
316 317
        $affected{$id} = 1;
    }
318 319 320 321
    $dbh->do('DELETE FROM votes WHERE who = ?', undef, $who);

    my $sth_insertVotes = $dbh->prepare('INSERT INTO votes (who, bug_id, vote_count)
                                         VALUES (?, ?, ?)');
322 323
    # Insert the new values in their place
    foreach my $id (@buglist) {
324
        if ($votes{$id} > 0) {
325
            $sth_insertVotes->execute($who, $id, $votes{$id});
326 327 328
        }
        $affected{$id} = 1;
    }
329

330
    # Update the cached values in the bugs table
331
    print $cgi->header();
332 333 334 335 336 337 338 339
    my @updated_bugs = ();

    my $sth_getVotes = $dbh->prepare("SELECT SUM(vote_count) FROM votes
                                      WHERE bug_id = ?");

    my $sth_updateVotes = $dbh->prepare("UPDATE bugs SET votes = ?
                                         WHERE bug_id = ?");

340
    foreach my $id (keys %affected) {
341 342 343 344
        $sth_getVotes->execute($id);
        my $v = $sth_getVotes->fetchrow_array || 0;
        $sth_updateVotes->execute($v, $id);

345
        my $confirmed = CheckIfVotedConfirmed($id);
346
        push (@updated_bugs, $id) if $confirmed;
347
    }
348
    $dbh->bz_commit_transaction();
349

350
    $vars->{'type'} = "votes";
351
    $vars->{'mailrecipients'} = { 'changer' => Bugzilla->user->login };
352
    $vars->{'title_tag'} = 'change_votes';
353 354 355 356 357 358 359 360

    foreach my $bug_id (@updated_bugs) {
        $vars->{'id'} = $bug_id;
        $template->process("bug/process/results.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
        # Set header_done to 1 only after the first bug.
        $vars->{'header_done'} = 1;
    }
361 362
    $vars->{'votes_recorded'} = 1;
}