votes.cgi 13.5 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 25 26 27 28
# -*- 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>

use strict;
use lib ".";

29
use Bugzilla;
30
use Bugzilla::Constants;
31
use Bugzilla::Bug;
32

33
require "globals.pl";
34

35
my $cgi = Bugzilla->cgi;
36 37
my $template = Bugzilla->template;
my $vars = {};
38

39 40 41 42 43 44 45 46
# 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.
47 48
my $bug_id = $cgi->param('bug_id');
my $action = $cgi->param('action') || ($bug_id ? "show_bug" : "show_user");
49 50

if ($action eq "show_bug" ||
51
    ($action eq "show_user" && defined $cgi->param('user')))
52
{
53
    Bugzilla->login();
54 55
}
else {
56
    Bugzilla->login(LOGIN_REQUIRED);
57 58 59 60 61 62 63 64
}

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

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

ValidateBugID($bug_id) if defined $bug_id;
67 68 69 70 71 72 73 74 75 76 77 78

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

if ($action eq "show_bug") {
    show_bug();
} 
elsif ($action eq "show_user") {
    show_user();
}
elsif ($action eq "vote") {
79
    record_votes() if Param('usevotes');
80 81 82
    show_user();
}
else {
83
    ThrowCodeError("unknown_action", {action => $action});
84 85 86 87 88 89
}

exit;

# Display the names of all the people voting for this one bug.
sub show_bug {
90
    my $cgi = Bugzilla->cgi;
91
    my $dbh = Bugzilla->dbh;
92

93 94
    ThrowCodeError("missing_bug_id") unless defined $bug_id;

95
    $vars->{'bug_id'} = $bug_id;
96 97 98 99 100 101 102 103
    $vars->{'users'} =
        $dbh->selectall_arrayref('SELECT profiles.login_name, votes.vote_count 
                                    FROM votes
                              INNER JOIN profiles 
                                      ON profiles.userid = votes.who
                                   WHERE votes.bug_id = ?',
                                  {'Slice' => {}}, $bug_id);

104
    print $cgi->header();
105 106
    $template->process("bug/votes/list-for-bug.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
107 108 109 110 111 112
}

# 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 {
    GetVersionTable();
113

114
    my $cgi = Bugzilla->cgi;
115
    my $dbh = Bugzilla->dbh;
116
    my $user = Bugzilla->user;
117

118
    # If a bug_id is given, and we're editing, we'll add it to the votes list.
119 120
    $bug_id ||= "";
    
121
    my $name = $cgi->param('user') || $user->login;
122
    my $who = DBNameToIdAndCheck($name);
123
    my $userid = $user->id;
124
    
125
    my $canedit = (Param('usevotes') && $userid == $who) ? 1 : 0;
126 127 128

    $dbh->bz_lock_tables('bugs READ', 'products READ', 'votes WRITE',
             'cc READ', 'bug_group_map READ', 'user_group_map READ',
129
             'group_group_map READ',
130 131
             'cc AS selectVisible_cc READ', 'groups READ');

132 133 134
    if ($canedit && $bug_id) {
        # Make sure there is an entry for this bug
        # in the vote table, just so that things display right.
135 136 137 138 139 140
        my $has_votes = $dbh->selectrow_array('SELECT vote_count FROM votes 
                                               WHERE bug_id = ? AND who = ?',
                                               undef, ($bug_id, $who));
        if (!$has_votes) {
            $dbh->do('INSERT INTO votes (who, bug_id, vote_count) 
                      VALUES (?, ?, 0)', undef, ($who, $bug_id));
141 142 143 144 145 146 147
        }
    }
    
    # Calculate the max votes per bug for each product; doing it here means
    # we can do it all in one query.
    my %maxvotesperbug;
    if($canedit) {
148 149 150 151
        my $products = $dbh->selectall_arrayref('SELECT name, maxvotesperbug 
                                                 FROM products');
        foreach (@$products) {
            my ($prod, $max) = @$_;
152 153 154 155 156 157 158 159 160 161 162 163 164
            $maxvotesperbug{$prod} = $max;
        }
    }
    
    my @products;
    
    # Read the votes data for this user for each product
    foreach my $product (sort(keys(%::prodmaxvotes))) {
        next if $::prodmaxvotes{$product} <= 0;
        
        my @bugs;
        my $total = 0;
        my $onevoteonly = 0;
165 166 167 168 169 170 171 172 173 174 175 176 177

        my $vote_list =
            $dbh->selectall_arrayref('SELECT votes.bug_id, votes.vote_count,
                                             bugs.short_desc, bugs.bug_status 
                                        FROM  votes
                                  INNER JOIN bugs ON votes.bug_id = bugs.bug_id
                                  INNER JOIN products ON bugs.product_id = products.id 
                                       WHERE votes.who = ? AND products.name = ?
                                    ORDER BY votes.bug_id',
                                      undef, ($who, $product));

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

180 181 182 183
            # 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.
184 185
            next if !$user->can_see_bug($id);            

186 187 188 189 190 191
            push (@bugs, { id => $id, 
                           summary => $summary,
                           count => $count,
                           opened => IsOpenedState($status) });
        }
        
192 193 194 195
        # In case we didn't populate this earlier (i.e. an error, or
        # a not logged in user viewing a users votes)
        $maxvotesperbug{$product} ||= 0;

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

210
    $dbh->do('DELETE FROM votes WHERE vote_count <= 0');
211
    $dbh->bz_unlock_tables();
212 213

    $vars->{'canedit'} = $canedit;
214
    $vars->{'voting_user'} = { "login" => $name };
215
    $vars->{'products'} = \@products;
216
    $vars->{'bug_id'} = $bug_id;
217

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

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

229
    my $cgi = Bugzilla->cgi;
230
    my $dbh = Bugzilla->dbh;
231

232 233 234
    # 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.
235 236

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

    # 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) {
241
        if (!defined $cgi->param('delete_all_votes')) {
242
            print $cgi->header();
243 244
            $template->process("bug/votes/delete-all.html.tmpl", $vars)
              || ThrowTemplateError($template->error());
245 246
            exit();
        }
247
        elsif ($cgi->param('delete_all_votes') == 0) {
248
            print $cgi->redirect("votes.cgi");
249 250 251 252 253 254 255 256 257
            exit();
        }
    }

    # Call ValidateBugID on each bug ID to make sure it is a positive
    # 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).
258
    my %votes;
259 260
    foreach my $id (@buglist) {
      ValidateBugID($id);
261 262
      $votes{$id} = $cgi->param($id);
      detaint_natural($votes{$id}) 
263
        || ThrowUserError("votes_must_be_nonnegative");
264 265 266 267 268 269 270 271
    }

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

    GetVersionTable();

272
    my $who = Bugzilla->user->id;
273 274 275 276

    # If the user is voting for bugs, make sure they aren't overstuffing
    # the ballot box.
    if (scalar(@buglist)) {
277 278 279 280 281 282 283 284
        my $product_vote_settings =
            $dbh->selectall_arrayref('SELECT bugs.bug_id, products.name,
                                             products.maxvotesperbug
                                        FROM bugs
                                  INNER JOIN products
                                          ON products.id = bugs.product_id
                                       WHERE bugs.bug_id IN
                                             (' . join(', ', @buglist) . ')');
285 286

        my %prodcount;
287 288
        foreach (@$product_vote_settings) {
            my ($id, $prod, $max) = @$_;
289
            $prodcount{$prod} ||= 0;
290
            $prodcount{$prod} += $votes{$id};
291 292
            
            # Make sure we haven't broken the votes-per-bug limit
293
            ($votes{$id} <= $max)               
294 295 296
              || ThrowUserError("too_many_votes_for_bug",
                                {max => $max, 
                                 product => $prod, 
297
                                 votes => $votes{$id}});
298 299 300 301
        }

        # Make sure we haven't broken the votes-per-product limit
        foreach my $prod (keys(%prodcount)) {
302 303 304 305 306
            ($prodcount{$prod} <= $::prodmaxvotes{$prod})
              || ThrowUserError("too_many_votes_for_product",
                                {max => $::prodmaxvotes{$prod}, 
                                 product => $prod, 
                                 votes => $prodcount{$prod}});
307 308 309 310 311 312 313 314 315 316
        }
    }

    # 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;
317
    $dbh->bz_lock_tables('bugs WRITE', 'bugs_activity WRITE',
318 319
                         'votes WRITE', 'longdescs WRITE',
                         'products READ', 'fielddefs READ');
320 321
    
    # Take note of, and delete the user's old votes from the database.
322 323 324 325
    my $bug_list = $dbh->selectcol_arrayref('SELECT bug_id FROM votes
                                             WHERE who = ?', undef, $who);

    foreach my $id (@$bug_list) {
326 327
        $affected{$id} = 1;
    }
328 329 330 331
    $dbh->do('DELETE FROM votes WHERE who = ?', undef, $who);

    my $sth_insertVotes = $dbh->prepare('INSERT INTO votes (who, bug_id, vote_count)
                                         VALUES (?, ?, ?)');
332 333
    # Insert the new values in their place
    foreach my $id (@buglist) {
334
        if ($votes{$id} > 0) {
335
            $sth_insertVotes->execute($who, $id, $votes{$id});
336 337 338
        }
        $affected{$id} = 1;
    }
339

340
    # Update the cached values in the bugs table
341
    print $cgi->header();
342 343 344 345 346 347 348 349
    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 = ?");

350
    foreach my $id (keys %affected) {
351 352 353 354
        $sth_getVotes->execute($id);
        my $v = $sth_getVotes->fetchrow_array || 0;
        $sth_updateVotes->execute($v, $id);

355
        my $confirmed = CheckIfVotedConfirmed($id, $who);
356
        push (@updated_bugs, $id) if $confirmed;
357
    }
358
    $dbh->bz_unlock_tables();
359

360 361 362 363 364 365 366 367 368 369
    $vars->{'type'} = "votes";
    $vars->{'mailrecipients'} = { 'changer' => $who };

    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;
    }
370 371
    $vars->{'votes_recorded'} = 1;
}