process_bug.cgi 40.8 KB
Newer Older
1
#!/usr/bin/perl -wT
2
# -*- Mode: perl; indent-tabs-mode: nil -*-
terry%netscape.com's avatar
terry%netscape.com committed
3
#
4 5 6 7 8 9 10 11 12 13
# 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.
#
terry%netscape.com's avatar
terry%netscape.com committed
14
# The Original Code is the Bugzilla Bug Tracking System.
15
#
terry%netscape.com's avatar
terry%netscape.com committed
16
# The Initial Developer of the Original Code is Netscape Communications
17 18 19 20
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
terry%netscape.com's avatar
terry%netscape.com committed
21
# Contributor(s): Terry Weissman <terry@mozilla.org>
22
#                 Dan Mosedale <dmose@mozilla.org>
23
#                 Dave Miller <justdave@syndicomm.com>
24
#                 Christopher Aillon <christopher@aillon.com>
25
#                 Myk Melez <myk@mozilla.org>
26
#                 Jeff Hedlund <jeff.hedlund@matrixsi.com>
27
#                 Frédéric Buclin <LpSolit@gmail.com>
28
#                 Lance Larsh <lance.larsh@oracle.com>
29
#                 Akamai Technologies <bugzilla-dev@akamai.com>
30
#                 Max Kanat-Alexander <mkanat@bugzilla.org>
terry%netscape.com's avatar
terry%netscape.com committed
31

32 33 34 35 36 37 38 39 40 41 42 43
# Implementation notes for this file:
#
# 1) the 'id' form parameter is validated early on, and if it is not a valid
# bugid an error will be reported, so it is OK for later code to simply check
# for a defined form 'id' value, and it can assume a valid bugid.
#
# 2) If the 'id' form parameter is not defined (after the initial validation),
# then we are processing multiple bugs, and @idlist will contain the ids.
#
# 3) If we are processing just the one id, then it is stored in @idlist for
# later processing.

44 45
use strict;

46
use lib qw(. lib);
47

48
use Bugzilla;
49
use Bugzilla::Constants;
50
use Bugzilla::Bug;
51
use Bugzilla::BugMail;
52
use Bugzilla::Mailer;
53
use Bugzilla::User;
54
use Bugzilla::Util;
55
use Bugzilla::Error;
56
use Bugzilla::Field;
57
use Bugzilla::Product;
58
use Bugzilla::Component;
59
use Bugzilla::Keyword;
60
use Bugzilla::Flag;
61
use Bugzilla::Status;
62

63 64
use Storable qw(dclone);

65
my $user = Bugzilla->login(LOGIN_REQUIRED);
66
local our $whoid = $user->id;
67
my $grouplist = $user->groups_as_string;
68

69
my $cgi = Bugzilla->cgi;
70
my $dbh = Bugzilla->dbh;
71
my $template = Bugzilla->template;
72
local our $vars = {};
73
$vars->{'valid_keywords'} = [map($_->name, Bugzilla::Keyword->get_all)];
74
$vars->{'use_keywords'} = 1 if Bugzilla::Keyword::keyword_count();
75

76 77
my @editable_bug_fields = editable_bug_fields();

78
my $requiremilestone = 0;
79
local our $PrivilegesRequired = 0;
80

81 82 83 84
######################################################################
# Subroutines
######################################################################

85 86 87 88 89 90 91 92 93 94 95 96 97 98
# Used to send email when an update is done.
sub send_results {
    my ($bug_id, $vars) = @_;
    my $template = Bugzilla->template;
    if (Bugzilla->usage_mode == USAGE_MODE_EMAIL) {
         Bugzilla::BugMail::Send($bug_id, $vars->{'mailrecipients'});
    }
    else {
        $template->process("bug/process/results.html.tmpl", $vars)
            || ThrowTemplateError($template->error());
    }
    $vars->{'header_done'} = 1;
}

99 100 101
# Tells us whether or not a field should be changed by process_bug, by
# checking that it's defined and not set to dontchange.
sub should_set {
102 103 104 105 106
    # check_defined is used for custom fields, where there's another field
    # whose name starts with "defined_" and then the field name--it's used
    # to know when we did things like empty a multi-select or deselect
    # a checkbox.
    my ($field, $check_defined) = @_;
107
    my $cgi = Bugzilla->cgi;
108 109 110 111
    if (( defined $cgi->param($field) 
          || ($check_defined && defined $cgi->param("defined_$field")) )
        && ( !$cgi->param('dontchange') 
             || $cgi->param($field) ne $cgi->param('dontchange')) )
112 113 114 115 116 117
    {
        return 1;
    }
    return 0;
}

118 119 120 121 122
sub comment_exists {
    my $cgi = Bugzilla->cgi;
    return ($cgi->param('comment') && $cgi->param('comment') =~ /\S+/) ? 1 : 0;
}

123 124 125 126 127 128 129 130
######################################################################
# Begin Data/Security Validation
######################################################################

# Create a list of IDs of all bugs being modified in this request.
# This list will either consist of a single bug number from the "id"
# form/URL field or a series of numbers from multiple form/URL fields
# named "id_x" where "x" is the bug number.
131 132
# For each bug being modified, make sure its ID is a valid bug number 
# representing an existing bug that the user is authorized to access.
133
my (@idlist, @bug_objects);
134 135 136 137 138 139 140 141
if (defined $cgi->param('id')) {
  my $id = $cgi->param('id');
  ValidateBugID($id);

  # Store the validated, and detainted id back in the cgi data, as
  # lots of later code will need it, and will obtain it from there
  $cgi->param('id', $id);
  push @idlist, $id;
142
  push(@bug_objects, new Bugzilla::Bug($id));
143
} else {
144
    foreach my $i ($cgi->param()) {
145
        if ($i =~ /^id_([1-9][0-9]*)/) {
146 147 148
            my $id = $1;
            ValidateBugID($id);
            push @idlist, $id;
149 150
            # We do this until we have Bugzilla::Bug->new_from_list.
            push(@bug_objects, new Bugzilla::Bug($id));
151
        }
152 153 154
    }
}

155
# Make sure there are bugs to process.
156
scalar(@idlist) || ThrowUserError("no_bugs_chosen", {action => 'modify'});
157

158
# Build a bug object using the first bug id, for validations.
159
my $bug = $bug_objects[0];
160

161 162
# Make sure form param 'dontchange' is defined so it can be compared to easily.
$cgi->param('dontchange','') unless defined $cgi->param('dontchange');
163

164 165 166
# Make sure the 'knob' param is defined; else set it to 'none'.
$cgi->param('knob', 'none') unless defined $cgi->param('knob');

167
$cgi->param('comment', $bug->_check_comment($cgi->param('comment')));
168

169 170 171 172 173 174
# If the bug(s) being modified have dependencies, validate them
# and rebuild the list with the validated values.  This is important
# because there are situations where validation changes the value
# instead of throwing an error, f.e. when one or more of the values
# is a bug alias that gets converted to its corresponding bug ID
# during validation.
175 176 177 178 179
if ($cgi->param('id') && (defined $cgi->param('dependson')
                          || defined $cgi->param('blocked')) )
{
    $bug->set_dependencies(scalar $cgi->param('dependson'),
                           scalar $cgi->param('blocked'));
180 181 182 183 184
}
# Right now, you can't modify dependencies on a mass change.
else {
    $cgi->delete('dependson');
    $cgi->delete('blocked');
185 186
}

187 188
# do a match on the fields if applicable

189 190
# The order of these function calls is important, as Flag::validate
# assumes User::match_field has ensured that the values
191
# in the requestee fields are legitimate user email addresses.
192
&Bugzilla::User::match_field($cgi, {
193 194 195 196
    'qa_contact'                => { 'type' => 'single' },
    'newcc'                     => { 'type' => 'multi'  },
    'masscc'                    => { 'type' => 'multi'  },
    'assigned_to'               => { 'type' => 'single' },
197
    '^requestee(_type)?-(\d+)$' => { 'type' => 'multi'  },
198
});
199 200 201 202

# Validate flags in all cases. validate() should not detect any
# reference to flags if $cgi->param('id') is undefined.
Bugzilla::Flag::validate($cgi, $cgi->param('id'));
203

204 205 206 207
######################################################################
# End Data/Security Validation
######################################################################

208
print $cgi->header() unless Bugzilla->usage_mode == USAGE_MODE_EMAIL;
209
$vars->{'title_tag'} = "bug_processed";
210 211 212 213

# Set the title if we can see a mid-air coming. This test may have false
# negatives, but never false positives, and should catch the majority of cases.
# It only works at all in the single bug case.
214
if (defined $cgi->param('id')) {
215 216
    if (defined $cgi->param('delta_ts')
        && $cgi->param('delta_ts') ne $bug->delta_ts)
217
    {
218
        $vars->{'title_tag'} = "mid_air";
219 220
        ThrowCodeError('undefined_field', {field => 'longdesclength'})
          if !defined $cgi->param('longdesclength');
221 222
    }
}
223

224
# Set up the vars for navigational <link> elements
225
my @bug_list;
226
if ($cgi->cookie("BUGLIST") && defined $cgi->param('id')) {
227
    @bug_list = split(/:/, $cgi->cookie("BUGLIST"));
228 229 230
    $vars->{'bug_list'} = \@bug_list;
}

231 232 233 234 235 236 237 238 239 240
my $product_change; # XXX Temporary until all of process_bug uses update()
if (should_set('product')) {
    # We only pass the fields if they're defined and not set to dontchange.
    # This is because when you haven't changed the product, --do-not-change--
    # isn't a valid component, version, or target_milestone. (When you're
    # doing a mass-change, some bugs might already be in the new product.)
    my %product_fields;
    foreach my $field (qw(component version target_milestone)) {
        if (should_set($field)) {
            $product_fields{$field} = $cgi->param($field);
terry%netscape.com's avatar
terry%netscape.com committed
241
        }
242
    }
243

244 245 246 247 248 249 250
    foreach my $b (@bug_objects) {
        my $changed = $b->set_product(scalar $cgi->param('product'),
            { %product_fields,
              change_confirmed => scalar $cgi->param('confirm_product_change'),
              other_bugs => \@bug_objects,
            });
        $product_change ||= $changed;
terry%netscape.com's avatar
terry%netscape.com committed
251 252 253
    }
}

254 255
# Confirm that the reporter of the current bug can access the bug we are duping to.
sub DuplicateUserConfirm {
256
    my ($dupe, $original) = @_;
257 258 259 260
    my $cgi = Bugzilla->cgi;
    my $dbh = Bugzilla->dbh;
    my $template = Bugzilla->template;

261
    # if we've already been through here, then exit
262
    if (defined $cgi->param('confirm_add_duplicate')) {
263 264 265
        return;
    }

266
    if ($dupe->reporter->can_see_bug($original)) {
267
        $cgi->param('confirm_add_duplicate', '1');
268 269
        return;
    }
270 271 272 273 274 275
    elsif (Bugzilla->usage_mode == USAGE_MODE_EMAIL) {
        # The email interface defaults to the safe alternative, which is
        # not CC'ing the user.
        $cgi->param('confirm_add_duplicate', 0);
        return;
    }
276

277 278 279
    $vars->{'cclist_accessible'} = $dbh->selectrow_array(
        q{SELECT cclist_accessible FROM bugs WHERE bug_id = ?},
        undef, $original);
280
    
281 282 283
    # Once in this part of the subroutine, the user has not been auto-validated
    # and the duper has not chosen whether or not to add to CC list, so let's
    # ask the duper what he/she wants to do.
284
    
285
    $vars->{'original_bug_id'} = $original;
286
    $vars->{'duplicate_bug_id'} = $dupe->bug_id;
287 288 289
    
    # Confirm whether or not to add the reporter to the cc: list
    # of the original bug (the one this bug is being duped against).
290
    print Bugzilla->cgi->header();
291
    $template->process("bug/process/confirm-duplicate.html.tmpl", $vars)
292
      || ThrowTemplateError($template->error());
293
    exit;
294
}
295

296 297 298 299 300 301 302
my @set_fields = qw(op_sys rep_platform priority bug_severity
                    component target_milestone version
                    bug_file_loc status_whiteboard short_desc
                    deadline remaining_time estimated_time);
push(@set_fields, 'assigned_to') if !$cgi->param('set_default_assignee');
push(@set_fields, 'qa_contact')  if !$cgi->param('set_default_qa_contact');

303 304 305 306 307 308 309
my %methods = (
    bug_severity => 'set_severity',
    rep_platform => 'set_platform',
    short_desc   => 'set_summary',
    bug_file_loc => 'set_url',
);
foreach my $b (@bug_objects) {
310 311 312
    # Component, target_milestone, and version are in here just in case
    # the 'product' field wasn't defined in the CGI. It doesn't hurt to set
    # them twice.
313
    foreach my $field_name (@set_fields) {
314
        if (should_set($field_name)) {
315 316 317 318 319
            my $method = $methods{$field_name};
            $method ||= "set_" . $field_name;
            $b->$method($cgi->param($field_name));
        }
    }
320 321
    $b->reset_assigned_to if $cgi->param('set_default_assignee');
    $b->reset_qa_contact  if $cgi->param('set_default_qa_contact');
terry%netscape.com's avatar
terry%netscape.com committed
322 323
}

324 325
my $action = trim($cgi->param('action') || '');

326
$::query = "UPDATE bugs SET";
327
$::comma = "";
328
local our @values;
329 330 331 332 333
umask(0);

sub DoComma {
    $::query .= "$::comma\n    ";
    $::comma = ",";
terry%netscape.com's avatar
terry%netscape.com committed
334 335
}

336
# Add custom fields data to the query that will update the database.
337 338
foreach my $field (Bugzilla->get_fields({custom => 1, obsolete => 0})) {
    my $fname = $field->name;
339
    if (should_set($fname, 1)) {
340
        $_->set_custom_field($field, [$cgi->param($fname)]) foreach @bug_objects;
341 342 343
    }
}

344
my ($product, @newprod_ids);
345
if ($cgi->param('product') ne $cgi->param('dontchange')) {
346 347
    $product = Bugzilla::Product::check_product(scalar $cgi->param('product'));
    @newprod_ids = ($product->id);
348
} else {
349 350 351 352 353 354
    @newprod_ids = @{$dbh->selectcol_arrayref("SELECT DISTINCT product_id
                                               FROM bugs 
                                               WHERE bug_id IN (" .
                                                   join(',', @idlist) . 
                                               ")")};
    if (scalar(@newprod_ids) == 1) {
355
        $product = new Bugzilla::Product($newprod_ids[0]);
356
    }
357 358
}

359
my (@cc_add, @cc_remove);
360

361
# Certain changes can only happen on individual bugs, never on mass-changes.
362
if (defined $cgi->param('id')) {
363 364 365 366 367 368 369 370 371 372 373 374 375 376
    my $bug = $bug_objects[0];
    
    # Since aliases are unique (like bug numbers), they can only be changed
    # for one bug at a time.
    if (Bugzilla->params->{"usebugaliases"} && defined $cgi->param('alias')) {
        $bug->set_alias($cgi->param('alias'));
    }

    # reporter_accessible and cclist_accessible--these are only set if
    # the user can change them and there are groups on the bug.
    # (If the user can't change the field, the checkboxes don't appear
    #  on show_bug, thus it would look like the user was trying to
    #  uncheck them, which would then be denied by the set_ functions,
    #  throwing a confusing error.)
377
    if (scalar @{$bug->groups_in}) {
378 379 380 381
        $bug->set_cclist_accessible($cgi->param('cclist_accessible'))
            if $bug->check_can_change_field('cclist_accessible', 0, 1);
        $bug->set_reporter_accessible($cgi->param('reporter_accessible'))
            if $bug->check_can_change_field('reporter_accessible', 0, 1);
382
    }
383 384 385 386 387 388 389 390
    
    # You can only mark/unmark comments as private on single bugs. If
    # you're not in the insider group, this code won't do anything.
    foreach my $field (grep(/^defined_isprivate/, $cgi->param())) {
        $field =~ /(\d+)$/;
        my $comment_id = $1;
        $bug->set_comment_is_private($comment_id,
                                     $cgi->param("isprivate_$comment_id"));
391 392
    }
}
393

394 395 396 397
# We need to check the addresses involved in a CC change before we touch 
# any bugs. What we'll do here is formulate the CC data into two arrays of
# users involved in this CC change.  Then those arrays can be used later 
# on for the actual change.
398 399 400 401
if (defined $cgi->param('newcc')
    || defined $cgi->param('addselfcc')
    || defined $cgi->param('removecc')
    || defined $cgi->param('masscc')) {
402
        
403 404 405
    # If masscc is defined, then we came from buglist and need to either add or
    # remove cc's... otherwise, we came from bugform and may need to do both.
    my ($cc_add, $cc_remove) = "";
406 407 408 409 410
    if (defined $cgi->param('masscc')) {
        if ($cgi->param('ccaction') eq 'add') {
            $cc_add = join(' ',$cgi->param('masscc'));
        } elsif ($cgi->param('ccaction') eq 'remove') {
            $cc_remove = join(' ',$cgi->param('masscc'));
411 412
        }
    } else {
413
        $cc_add = join(' ',$cgi->param('newcc'));
414 415
        # We came from bug_form which uses a select box to determine what cc's
        # need to be removed...
416 417
        if (defined $cgi->param('removecc') && $cgi->param('cc')) {
            $cc_remove = join (",", $cgi->param('cc'));
418 419 420
        }
    }

421 422 423 424 425 426 427 428
    push(@cc_add, split(/[\s,]+/, $cc_add)) if $cc_add;
    push(@cc_add, Bugzilla->user) if $cgi->param('addselfcc');

    push(@cc_remove, split(/[\s,]+/, $cc_remove)) if $cc_remove;
}

foreach my $b (@bug_objects) {
    $b->remove_cc($_) foreach @cc_remove;
429
    $b->add_cc($_) foreach @cc_add;
430 431 432 433 434 435 436 437 438
    # Theoretically you could move a product without ever specifying
    # a new assignee or qa_contact, or adding/removing any CCs. So,
    # we have to check that the current assignee, qa, and CCs are still
    # valid if we've switched products, under strict_isolation. We can only
    # do that here. There ought to be some better way to do this,
    # architecturally, but I haven't come up with it.
    if ($product_change) {
        $b->_check_strict_isolation();
    }
439 440
}

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
if ($action eq Bugzilla->params->{'move-button-text'}) {
    Bugzilla->params->{'move-enabled'} || ThrowUserError("move_bugs_disabled");

    $user->is_mover || ThrowUserError("auth_failure", {action => 'move',
                                                       object => 'bugs'});

    my @multi_select_locks  = map {'bug_' . $_->name . " WRITE"}
        Bugzilla->get_fields({ custom => 1, type => FIELD_TYPE_MULTI_SELECT,
                               obsolete => 0 });

    $dbh->bz_lock_tables('bugs WRITE', 'bugs_activity WRITE', 'duplicates WRITE',
                         'longdescs WRITE', 'profiles READ', 'groups READ',
                         'bug_group_map READ', 'group_group_map READ',
                         'user_group_map READ', 'classifications READ',
                         'products READ', 'components READ', 'votes READ',
                         'cc READ', 'fielddefs READ', 'bug_status READ',
                         'status_workflow READ', 'resolution READ', @multi_select_locks);

    # First update all moved bugs.
    foreach my $bug (@bug_objects) {
        $bug->add_comment(scalar $cgi->param('comment'),
                          { type => CMT_MOVED_TO, extra_data => $user->login });
463
    }
464 465 466 467 468 469 470
    # Don't export the new status and resolution. We want the current ones.
    local $Storable::forgive_me = 1;
    my $bugs = dclone(\@bug_objects);
    foreach my $bug (@bug_objects) {
        my ($status, $resolution) = $bug->get_new_status_and_resolution('move');
        $bug->set_status($status);
        $bug->set_resolution($resolution);
471
    }
472 473 474 475 476 477 478 479 480
    $_->update() foreach @bug_objects;
    $dbh->bz_unlock_tables();

    # Now send emails.
    foreach my $id (@idlist) {
        $vars->{'mailrecipients'} = { 'changer' => $user->login };
        $vars->{'id'} = $id;
        $vars->{'type'} = "move";
        send_results($id, $vars);
481
    }
482 483 484 485 486 487 488 489 490 491 492 493 494 495
    # Prepare and send all data about these bugs to the new database
    my $to = Bugzilla->params->{'move-to-address'};
    $to =~ s/@/\@/;
    my $from = Bugzilla->params->{'moved-from-address'};
    $from =~ s/@/\@/;
    my $msg = "To: $to\n";
    $msg .= "From: Bugzilla <" . $from . ">\n";
    $msg .= "Subject: Moving bug(s) " . join(', ', @idlist) . "\n\n";

    my @fieldlist = (Bugzilla::Bug->fields, 'group', 'long_desc',
                     'attachment', 'attachmentdata');
    my %displayfields;
    foreach (@fieldlist) {
        $displayfields{$_} = 1;
496
    }
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513

    $template->process("bug/show.xml.tmpl", { bugs => $bugs,
                                              displayfields => \%displayfields,
                                            }, \$msg)
      || ThrowTemplateError($template->error());

    $msg .= "\n";
    MessageToMTA($msg);

    # End the response page.
    unless (Bugzilla->usage_mode == USAGE_MODE_EMAIL) {
        $template->process("bug/navigate.html.tmpl", $vars)
            || ThrowTemplateError($template->error());
        $template->process("global/footer.html.tmpl", $vars)
            || ThrowTemplateError($template->error());
    }
    exit;
514
}
515

516

517 518 519 520
if (($cgi->param('set_default_assignee') || $cgi->param('set_default_qa_contact'))
    && Bugzilla->params->{'commentonreassignbycomponent'} && !comment_exists())
{
        ThrowUserError('comment_required');
521 522 523 524
}

my $duplicate; # It will store the ID of the bug we are pointing to, if any.

525 526 527 528 529
# Make sure the bug status transition is legal for all bugs.
my $knob = scalar $cgi->param('knob');
# Special actions (duplicate, change_resolution and clearresolution) are outside
# the workflow.
if (!grep { $knob eq $_ } SPECIAL_STATUS_WORKFLOW_ACTIONS) {
530 531
    # Make sure the bug status exists and is active.
    check_field('bug_status', $knob);
532
    my $bug_status = new Bugzilla::Status({name => $knob});
533 534
    $_->check_status_transition($bug_status) foreach @bug_objects;

535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    # Fill the resolution field with the correct value (e.g. in case the
    # workflow allows several open -> closed transitions).
    if ($bug_status->is_open) {
        $cgi->delete('resolution');
    }
    else {
        $cgi->param('resolution', $cgi->param('resolution_knob_' . $bug_status->id));
    }
}
elsif ($knob eq 'change_resolution') {
    # Fill the resolution field with the correct value.
    $cgi->param('resolution', $cgi->param('resolution_knob_change_resolution'));
}
else {
    # The resolution field is not in use.
    $cgi->delete('resolution');
terry%netscape.com's avatar
terry%netscape.com committed
551 552
}

553 554 555 556 557 558 559
# The action is a valid one.
trick_taint($knob);
# Some information is required for checks.
$vars->{comment_exists} = comment_exists();
$vars->{bug_id} = $cgi->param('id');
$vars->{dup_id} = $cgi->param('dup_id');
$vars->{resolution} = $cgi->param('resolution') || '';
560
Bugzilla::Bug->check_status_change_triggers($knob, \@bug_objects, $vars);
561 562

# Some triggers require extra actions.
563
$duplicate = $vars->{dup_id} if ($knob eq 'duplicate');
564
$requiremilestone = $vars->{requiremilestone};
565 566
# $vars->{DuplicateUserConfirm} is true only if a single bug is being edited.
DuplicateUserConfirm($bug, $duplicate) if $vars->{DuplicateUserConfirm};
567

568
my $any_keyword_changes;
569
if (defined $cgi->param('keywords')) {
570 571 572 573 574
    foreach my $b (@bug_objects) {
        my $return =
            $b->modify_keywords(scalar $cgi->param('keywords'),
                                scalar $cgi->param('keywordaction'));
        $any_keyword_changes ||= $return;
575 576 577
    }
}

578
if ($::comma eq ""
579
    && !$any_keyword_changes
580
    && defined $cgi->param('masscc') && ! $cgi->param('masscc')
581
    ) {
582
    if (!defined $cgi->param('comment') || $cgi->param('comment') =~ /^\s*$/) {
583
        ThrowUserError("bugs_not_changed");
terry%netscape.com's avatar
terry%netscape.com committed
584 585 586
    }
}

587
my $basequery = $::query;
588

589
local our $delta_ts;
590 591
sub SnapShotBug {
    my ($id) = (@_);
592
    my $dbh = Bugzilla->dbh;
593
    my @row = $dbh->selectrow_array(q{SELECT delta_ts, } .
594
                join(',', editable_bug_fields()).q{ FROM bugs WHERE bug_id = ?},
595
                undef, $id);
596
    $delta_ts = shift @row;
597

598
    return @row;
terry%netscape.com's avatar
terry%netscape.com committed
599 600
}

601 602
my $timestamp;

603 604
my %bug_objects = map {$_->id => $_} @bug_objects;

605 606 607
# This loop iterates once for each bug to be processed (i.e. all the
# bugs selected when this script is called with multiple bugs selected
# from buglist.cgi, or just the one bug when called from
608 609
# show_bug.cgi).
#
610
foreach my $id (@idlist) {
611
    my $query = $basequery;
612
    my @bug_values = @values;
613 614
    # XXX We really have to get rid of $::comma.
    my $comma = $::comma;
615
    my $old_bug_obj = new Bugzilla::Bug($id);
616

617
    my ($status, $everconfirmed);
618
    my $resolution = $old_bug_obj->resolution;
619 620 621
    # We only care about the resolution field if the user explicitly edits it
    # or if he closes the bug.
    if ($knob eq 'change_resolution' || $cgi->param('resolution')) {
622 623
        $resolution = $cgi->param('resolution');
    }
624 625
    ($status, $resolution, $everconfirmed) =
      $old_bug_obj->get_new_status_and_resolution($knob, $resolution);
626 627 628 629 630 631 632 633 634 635 636

    if ($status ne $old_bug_obj->bug_status) {
        $query .= "$comma bug_status = ?";
        push(@bug_values, $status);
        $comma = ',';
    }
    if ($resolution ne $old_bug_obj->resolution) {
        $query .= "$comma resolution = ?";
        push(@bug_values, $resolution);
        $comma = ',';
    }
637 638 639 640 641
    if ($everconfirmed ne $old_bug_obj->everconfirmed) {
        $query .= "$comma everconfirmed = ?";
        push(@bug_values, $everconfirmed);
        $comma = ',';
    }
642

643
    my $bug_changed = 0;
644 645
    my $write = "WRITE";        # Might want to make a param to control
                                # whether we do LOW_PRIORITY ...
646 647 648 649 650

    my @multi_select_locks  = map {'bug_' . $_->name . " $write"}
        Bugzilla->get_fields({ custom => 1, type => FIELD_TYPE_MULTI_SELECT,
                               obsolete => 0 });

651
    $dbh->bz_lock_tables("bugs $write", "bugs_activity $write", "cc $write",
652
            "profiles READ", "dependencies $write", "votes $write",
653
            "products READ", "components READ", "milestones READ",
654
            "keywords $write", "longdescs $write", "fielddefs READ",
655
            "bug_group_map $write", "flags $write", "duplicates $write",
656
            "user_group_map READ", "group_group_map READ", "flagtypes READ",
657 658
            "flaginclusions AS i READ", "flagexclusions AS e READ",
            "keyworddefs READ", "groups READ", "attachments READ",
659
            "bug_status READ", "group_control_map AS oldcontrolmap READ",
660
            "group_control_map AS newcontrolmap READ",
661 662
            "group_control_map READ", "email_setting READ", 
            "classifications READ", @multi_select_locks);
663

664
    # It may sound crazy to set %formhash for each bug as $cgi->param()
665 666
    # will not change, but %formhash is modified below and we prefer
    # to set it again.
667
    my $i = 0;
668 669 670
    my @oldvalues = SnapShotBug($id);
    my %oldhash;
    my %formhash;
671
    foreach my $col (@editable_bug_fields) {
672
        # Consider NULL db entries to be equivalent to the empty string
673 674 675
        $oldvalues[$i] = defined($oldvalues[$i]) ? $oldvalues[$i] : '';
        # Convert the deadline taken from the DB into the YYYY-MM-DD format
        # for consistency with the deadline provided by the user, if any.
676 677
        # Else Bug::check_can_change_field() would see them as different
        # in all cases.
678 679 680
        if ($col eq 'deadline') {
            $oldvalues[$i] = format_time($oldvalues[$i], "%Y-%m-%d");
        }
681
        $oldhash{$col} = $oldvalues[$i];
682
        $formhash{$col} = $cgi->param($col) if defined $cgi->param($col);
683 684
        $i++;
    }
685 686 687 688
    # The status and resolution are defined by the workflow.
    $formhash{'bug_status'} = $status;
    $formhash{'resolution'} = $resolution;

689
    # This hash is required by Bug::check_can_change_field().
690
    my $cgi_hash = {'dontchange' => scalar $cgi->param('dontchange')};
691
    foreach my $col (@editable_bug_fields) {
692 693
        # XXX - Ugly workaround which has to go away before 3.1.3.
        next if ($col eq 'assigned_to' || $col eq 'qa_contact');
694
        if (exists $formhash{$col}
695 696
            && !$old_bug_obj->check_can_change_field($col, $oldhash{$col}, $formhash{$col},
                                                     \$PrivilegesRequired, $cgi_hash))
697 698 699 700
        {
            my $vars;
            if ($col eq 'component_id') {
                # Display the component name
701
                $vars->{'oldvalue'} = $old_bug_obj->component;
702
                $vars->{'newvalue'} = $cgi->param('component');
703 704 705 706 707
                $vars->{'field'} = 'component';
            } else {
                $vars->{'oldvalue'} = $oldhash{$col};
                $vars->{'newvalue'} = $formhash{$col};
                $vars->{'field'} = $col;
708
            }
709
            $vars->{'privs'} = $PrivilegesRequired;
710
            ThrowUserError("illegal_change", $vars);
711 712
        }
    }
713
    
714
    $oldhash{'product'} = $old_bug_obj->product;
715
    if (!Bugzilla->user->can_edit_product($oldhash{'product_id'})) {
716
        ThrowUserError("product_edit_denied",
717
                      { product => $oldhash{'product'} });
718 719
    }

720 721 722 723 724 725 726 727 728 729
    my $new_product = $bug_objects{$id}->product_obj;
    # musthavemilestoneonaccept applies only if at least two
    # target milestones are defined for the product.
    if ($requiremilestone
        && scalar(@{ $new_product->milestones }) > 1
        && $bug_objects{$id}->target_milestone
           eq $new_product->default_milestone)
    {
        ThrowUserError("milestone_required", { bug_id => $id });
    }
730 731
    if (defined $cgi->param('delta_ts') && $cgi->param('delta_ts') ne $delta_ts)
    {
732
        ($vars->{'operations'}) =
733
            Bugzilla::Bug::GetBugActivity($id, undef, $cgi->param('delta_ts'));
734

735
        $vars->{'start_at'} = $cgi->param('longdesclength');
736 737 738 739

        # Always sort midair collision comments oldest to newest,
        # regardless of the user's personal preference.
        $vars->{'comments'} = Bugzilla::Bug::GetComments($id, "oldest_to_newest");
740

741
        $cgi->param('delta_ts', $delta_ts);
742 743 744
        
        $vars->{'bug_id'} = $id;
        
745
        $dbh->bz_unlock_tables(UNLOCK_ABORT);
746 747
        
        # Warn the user about the mid-air collision and ask them what to do.
748
        $template->process("bug/process/midair.html.tmpl", $vars)
749
          || ThrowTemplateError($template->error());
750 751 752
        exit;
    }

753
    if ($cgi->param('comment') || $cgi->param('work_time') || $duplicate) {
754 755
        my $type = $duplicate ? CMT_DUPE_OF : CMT_NORMAL;

756
        $bug_objects{$id}->add_comment(scalar($cgi->param('comment')),
757
            { isprivate => scalar($cgi->param('commentprivacy')),
758
              work_time => scalar $cgi->param('work_time'), type => $type, 
759
              extra_data => $duplicate});
760 761
        $bug_changed = 1;
    }
762 763 764 765 766 767 768 769
    
    #################################
    # Start Actual Database Updates #
    #################################
    
    $timestamp = $dbh->selectrow_array(q{SELECT NOW()});

    $bug_objects{$id}->update($timestamp);
770

771 772
    $bug_objects{$id}->update_keywords($timestamp);
    
773
    $query .= " WHERE bug_id = ?";
774
    push(@bug_values, $id);
775 776

    if ($comma ne '') {
777
        $dbh->do($query, undef, @bug_values);
terry%netscape.com's avatar
terry%netscape.com committed
778
    }
779

780 781
    # Check for duplicates if the bug is [re]open or its resolution is changed.
    if ($resolution ne 'DUPLICATE') {
782
        $dbh->do(q{DELETE FROM duplicates WHERE dupe = ?}, undef, $id);
783
    }
784

785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
    # First of all, get all groups the bug is currently restricted to.
    my $initial_groups =
      $dbh->selectcol_arrayref('SELECT group_id, name
                                  FROM bug_group_map
                            INNER JOIN groups
                                    ON groups.id = bug_group_map.group_id
                                 WHERE bug_id = ?', {Columns=>[1,2]}, $id);
    my %original_groups = @$initial_groups;
    my %updated_groups = %original_groups;

    # Now let's see which groups have to be added or removed.
    foreach my $gid (keys %{$new_product->group_controls}) {
        my $group = $new_product->group_controls->{$gid};
        # Leave inactive groups alone.
        next unless $group->{group}->is_active;

801 802 803
        # Only members of a group can add/remove the bug to/from it,
        # unless the bug is being moved to another product in which case
        # non-members can also edit group restrictions.
804
        if ($group->{membercontrol} == CONTROLMAPMANDATORY
805 806
            || ($product_change && $group->{othercontrol} == CONTROLMAPMANDATORY
                && !$user->in_group_id($gid)))
807 808
        {
            $updated_groups{$gid} = $group->{group}->name;
809
        }
810
        elsif ($group->{membercontrol} == CONTROLMAPNA
811 812
               || ($product_change && $group->{othercontrol} == CONTROLMAPNA
                   && !$user->in_group_id($gid)))
813 814
        {
            delete $updated_groups{$gid};
815
        }
816 817
        # When editing several bugs at once, only consider groups which
        # have been displayed.
818
        elsif (($user->in_group_id($gid) || $product_change)
819 820
               && ((defined $cgi->param('id') && Bugzilla->usage_mode != USAGE_MODE_EMAIL)
                   || defined $cgi->param("bit-$gid")))
821
        {
822 823 824 825 826 827 828
            if (!$cgi->param("bit-$gid")) {
                delete $updated_groups{$gid};
            }
            # Note that == 1 is important, because == -1 means "ignore this group".
            elsif ($cgi->param("bit-$gid") == 1) {
                $updated_groups{$gid} = $group->{group}->name;
            }
829 830
        }
    }
831 832 833 834
    # We also have to remove groups which are not legal in the new product.
    foreach my $gid (keys %updated_groups) {
        delete $updated_groups{$gid}
          unless exists $new_product->group_controls->{$gid};
835
    }
836
    my ($removed, $added) = diff_arrays([keys %original_groups], [keys %updated_groups]);
837

838 839 840 841 842 843 844 845 846 847 848
    # We can now update the DB.
    if (scalar(@$removed)) {
        $dbh->do('DELETE FROM bug_group_map WHERE bug_id = ?
                  AND group_id IN (' . join(', ', @$removed) . ')',
                  undef, $id);
    }
    if (scalar(@$added)) {
        my $sth = $dbh->prepare('INSERT INTO bug_group_map
                                 (bug_id, group_id) VALUES (?, ?)');
        $sth->execute($id, $_) foreach @$added;
    }
849

850 851 852 853 854 855
    # Add the changes to the bug_activity table.
    if (scalar(@$removed) || scalar(@$added)) {
        my @removed_names = map { $original_groups{$_} } @$removed;
        my @added_names = map { $updated_groups{$_} } @$added;
        LogActivityEntry($id, 'bug_group', join(',', @removed_names),
                         join(',', @added_names), $whoid, $timestamp);
856 857
        $bug_changed = 1;
    }
858

859 860
    my ($cc_removed) = $bug_objects{$id}->update_cc($timestamp);
    $cc_removed = [map {$_->login} @$cc_removed];
861

862 863 864 865 866 867 868 869
    my ($dep_changes) = $bug_objects{$id}->update_dependencies($timestamp);
    
    # Convert the "changes" hash into a list of all the bug ids, then
    # convert that into a hash to eliminate duplicates. ("map {@$_}" collapses
    # an array of arrays.)
    my @all_changed_deps = map { @$_ } @{$dep_changes->{'dependson'}};
    push(@all_changed_deps, map { @$_ } @{$dep_changes->{'blocked'}});
    my %changed_deps = map { $_ => 1 } @all_changed_deps;
870

871
    # get a snapshot of the newly set values out of the database,
872 873 874
    # and then generate any necessary bug activity entries by seeing 
    # what has changed since before we wrote out the new values.
    #
875
    my $new_bug_obj = new Bugzilla::Bug($id);
876
    my @newvalues = SnapShotBug($id);
877 878
    my %newhash;
    $i = 0;
879
    foreach my $col (@editable_bug_fields) {
880
        # Consider NULL db entries to be equivalent to the empty string
881
        $newvalues[$i] = defined($newvalues[$i]) ? $newvalues[$i] : '';
882 883 884 885
        # Convert the deadline to the YYYY-MM-DD format.
        if ($col eq 'deadline') {
            $newvalues[$i] = format_time($newvalues[$i], "%Y-%m-%d");
        }
886 887 888
        $newhash{$col} = $newvalues[$i];
        $i++;
    }
889 890 891

    # $msgs will store emails which have to be sent to voters, if any.
    my $msgs;
892 893
    my %notify_deps;
    
894
    foreach my $c (@editable_bug_fields) {
895 896
        my $col = $c;           # We modify it, don't want to modify array
                                # values in place.
897 898 899
        my $old = shift @oldvalues;
        my $new = shift @newvalues;
        if ($old ne $new) {
900

901 902
            # Bugzilla::Bug does these for us already.
            next if grep($_ eq $col, qw(keywords op_sys rep_platform priority
903
                                        product_id component_id version
904
                                        target_milestone assigned_to qa_contact
905
                                        bug_severity short_desc alias
906
                                        deadline estimated_time remaining_time
907
                                        reporter_accessible cclist_accessible
908 909
                                        status_whiteboard bug_file_loc),
                                     Bugzilla->custom_field_names);
910

911
            if ($col eq 'product') {
912 913 914 915 916
                # If some votes have been removed, RemoveVotes() returns
                # a list of messages to send to voters.
                # We delay the sending of these messages till tables are unlocked.
                $msgs = RemoveVotes($id, 0,
                          "This bug has been moved to a different product");
917 918

                CheckIfVotedConfirmed($id, $whoid);
919
            }
920

921 922
            # If this bug has changed from opened to closed or vice-versa,
            # then all of the bugs we block need to be notified.
923
            if ($col eq 'bug_status' 
924
                && is_open_state($old) ne is_open_state($new))
925
            {
926
                $notify_deps{$_} = 1 foreach (@{$bug_objects{$id}->blocked});
927
            }
928

929 930
            LogActivityEntry($id,$col,$old,$new,$whoid,$timestamp);
            $bug_changed = 1;
terry%netscape.com's avatar
terry%netscape.com committed
931 932
        }
    }
933
    # Set and update flags.
934
    Bugzilla::Flag::process($new_bug_obj, undef, $timestamp, $cgi, $vars);
935

936
    if ($bug_changed) {
937 938
        $dbh->do(q{UPDATE bugs SET delta_ts = ? WHERE bug_id = ?},
                 undef, $timestamp, $id);
939
    }
940
    $dbh->bz_unlock_tables();
941

942 943
    # Now is a good time to send email to voters.
    foreach my $msg (@$msgs) {
944
        MessageToMTA($msg);
945 946
    }

947
    if ($duplicate) {
948 949 950 951 952
        # If the bug was already marked as a duplicate, remove
        # the existing entry.
        $dbh->do('DELETE FROM duplicates WHERE dupe = ?',
                  undef, $cgi->param('id'));

953 954
        my $dup = new Bugzilla::Bug($duplicate);
        my $reporter = $new_bug_obj->reporter;
955 956
        my $isoncc = $dbh->selectrow_array(q{SELECT who FROM cc
                                           WHERE bug_id = ? AND who = ?},
957 958
                                           undef, $duplicate, $reporter->id);
        unless (($reporter->id == $dup->reporter->id) || $isoncc
959
                || !$cgi->param('confirm_add_duplicate')) {
960 961 962
            # The reporter is oblivious to the existence of the original bug
            # and is permitted access. Add him to the cc (and record activity).
            LogActivityEntry($duplicate,"cc","",$reporter->name,
963
                             $whoid,$timestamp);
964
            $dbh->do(q{INSERT INTO cc (who, bug_id) VALUES (?, ?)},
965
                     undef, $reporter->id, $duplicate);
966
        }
967
        # Bug 171639 - Duplicate notifications do not need to be private.
968
        $dup->add_comment("", { type => CMT_HAS_DUPE,
969 970
                                extra_data => $new_bug_obj->bug_id });
        $dup->update($timestamp);
971

972 973
        $dbh->do(q{INSERT INTO duplicates VALUES (?, ?)}, undef,
                 $duplicate, $cgi->param('id'));
974 975 976 977 978 979
    }

    # Now all changes to the DB have been made. It's time to email
    # all concerned users, including the bug itself, but also the
    # duplicated bug and dependent bugs, if any.

980 981 982 983 984 985
    my $orig_qa = $old_bug_obj->qa_contact;
    $vars->{'mailrecipients'} = {
        cc        => $cc_removed,
        owner     => $old_bug_obj->assigned_to->login,
        qacontact => $orig_qa ? $orig_qa->login : '',
        changer   => Bugzilla->user->login };
986 987

    $vars->{'id'} = $id;
988
    $vars->{'type'} = "bug";
989 990 991
    
    # Let the user know the bug was changed and who did and didn't
    # receive email about the change.
992 993
    send_results($id, $vars);
 
994
    if ($duplicate) {
995
        $vars->{'mailrecipients'} = { 'changer' => Bugzilla->user->login }; 
996

997 998 999
        $vars->{'id'} = $duplicate;
        $vars->{'type'} = "dupe";
        
1000 1001 1002
        # Let the user know a duplication notation was added to the 
        # original bug.
        send_results($duplicate, $vars);
1003 1004
    }

1005 1006 1007 1008 1009
    my %all_dep_changes = (%notify_deps, %changed_deps);
    foreach my $id (sort { $a <=> $b } (keys %all_dep_changes)) {
        $vars->{'mailrecipients'} = { 'changer' => Bugzilla->user->login };
        $vars->{'id'} = $id;
        $vars->{'type'} = "dep";
1010

1011 1012 1013 1014 1015
        # Let the user (if he is able to see the bug) know we checked to
        # see if we should email notice of this change to users with a 
        # relationship to the dependent bug and who did and didn't 
        # receive email about it.
        send_results($id, $vars);
1016
    }
terry%netscape.com's avatar
terry%netscape.com committed
1017 1018
}

1019 1020 1021 1022 1023 1024
# Determine if Patch Viewer is installed, for Diff link
# (NB: Duplicate code with show_bug.cgi.)
eval {
    require PatchReader;
    $vars->{'patchviewerinstalled'} = 1;
};
1025

1026 1027 1028 1029 1030 1031
if (defined $cgi->param('id')) {
    $action = Bugzilla->user->settings->{'post_bug_submit_action'}->{'value'};
} else {
    # param('id') is not defined when changing multiple bugs
    $action = 'nothing';
}
1032

1033 1034 1035 1036
if (Bugzilla->usage_mode == USAGE_MODE_EMAIL) {
    # Do nothing.
}
elsif ($action eq 'next_bug') {
1037 1038 1039 1040 1041 1042 1043
    my $next_bug;
    my $cur = lsearch(\@bug_list, $cgi->param("id"));
    if ($cur >= 0 && $cur < $#bug_list) {
        $next_bug = $bug_list[$cur + 1];
    }
    if ($next_bug) {
        if (detaint_natural($next_bug) && Bugzilla->user->can_see_bug($next_bug)) {
1044
            my $bug = new Bugzilla::Bug($next_bug);
1045
            ThrowCodeError("bug_error", { bug => $bug }) if $bug->error;
1046

1047 1048
            $vars->{'bugs'} = [$bug];
            $vars->{'nextbug'} = $bug->bug_id;
1049

1050 1051 1052 1053 1054
            $template->process("bug/show.html.tmpl", $vars)
              || ThrowTemplateError($template->error());

            exit;
        }
1055
    }
1056
} elsif ($action eq 'same_bug') {
1057
    if (Bugzilla->user->can_see_bug($cgi->param('id'))) {
1058
        my $bug = new Bugzilla::Bug($cgi->param('id'));
1059
        ThrowCodeError("bug_error", { bug => $bug }) if $bug->error;
1060

1061
        $vars->{'bugs'} = [$bug];
1062

1063 1064
        $template->process("bug/show.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
1065

1066 1067
        exit;
    }
1068 1069
} elsif ($action ne 'nothing') {
    ThrowCodeError("invalid_post_bug_submit_action");
terry%netscape.com's avatar
terry%netscape.com committed
1070
}
1071

1072
# End the response page.
1073
unless (Bugzilla->usage_mode == USAGE_MODE_EMAIL) {
1074 1075 1076
    # The user pref is 'Do nothing', so all we need is the current bug ID.
    $vars->{'bug'} = {bug_id => scalar $cgi->param('id')};

1077 1078 1079 1080 1081 1082 1083
    $template->process("bug/navigate.html.tmpl", $vars)
        || ThrowTemplateError($template->error());
    $template->process("global/footer.html.tmpl", $vars)
        || ThrowTemplateError($template->error());
}

1;