Bug.pm 167 KB
Newer Older
1 2 3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
#
5 6
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.
7

8
package Bugzilla::Bug;
9

10
use 5.10.1;
11
use strict;
12
use warnings;
13

14
use Bugzilla::Attachment;
15
use Bugzilla::Constants;
16
use Bugzilla::Field;
17 18
use Bugzilla::Flag;
use Bugzilla::FlagType;
19
use Bugzilla::Hook;
20
use Bugzilla::Keyword;
21
use Bugzilla::Milestone;
22
use Bugzilla::User;
23
use Bugzilla::Util;
24
use Bugzilla::Version;
25
use Bugzilla::Error;
26
use Bugzilla::Product;
27 28
use Bugzilla::Component;
use Bugzilla::Group;
29
use Bugzilla::Status;
30
use Bugzilla::Comment;
31
use Bugzilla::BugUrl;
32
use Bugzilla::BugUserLastVisit;
33

34
use List::MoreUtils qw(firstidx uniq part);
35
use List::Util qw(min max first);
36
use Storable qw(dclone);
37
use Scalar::Util qw(blessed);
38

39
use parent qw(Bugzilla::Object Exporter);
40
@Bugzilla::Bug::EXPORT = qw(
41
    bug_alias_to_id
42
    LogActivityEntry
43
    editable_bug_fields
44 45
);

46 47 48 49
#####################################################################
# Constants
#####################################################################

50 51
use constant DB_TABLE   => 'bugs';
use constant ID_FIELD   => 'bug_id';
52
use constant NAME_FIELD => 'bug_id';
53
use constant LIST_ORDER => ID_FIELD;
54
# Bugs have their own auditing table, bugs_activity.
55
use constant AUDIT_CREATES => 0;
56
use constant AUDIT_UPDATES => 0;
57 58
# This will be enabled later
use constant USE_MEMCACHED => 0;
59 60 61 62

# This is a sub because it needs to call other subroutines.
sub DB_COLUMNS {
    my $dbh = Bugzilla->dbh;
63 64
    my @custom = grep {$_->type != FIELD_TYPE_MULTI_SELECT}
                      Bugzilla->active_custom_fields;
65
    my @custom_names = map {$_->name} @custom;
66

67
    my @columns = (qw(
68
        assigned_to
69 70 71 72 73 74
        bug_file_loc
        bug_id
        bug_severity
        bug_status
        cclist_accessible
        component_id
75
        creation_ts
76 77 78
        delta_ts
        estimated_time
        everconfirmed
79
        lastdiffed
80 81 82
        op_sys
        priority
        product_id
83
        qa_contact
84 85 86 87 88 89 90 91 92 93 94
        remaining_time
        rep_platform
        reporter_accessible
        resolution
        short_desc
        status_whiteboard
        target_milestone
        version
    ),
    'reporter    AS reporter_id',
    $dbh->sql_date_format('deadline', '%Y-%m-%d') . ' AS deadline',
95
    @custom_names);
96
    
97
    Bugzilla::Hook::process("bug_columns", { columns => \@columns });
98 99
    
    return @columns;
100 101
}

102
sub VALIDATORS {
103

104 105
    my $validators = {
        alias          => \&_check_alias,
106
        assigned_to    => \&_check_assigned_to,
107
        blocked        => \&_check_dependencies,
108
        bug_file_loc   => \&_check_bug_file_loc,
109
        bug_severity   => \&_check_select_field,
110 111
        bug_status     => \&_check_bug_status,
        cc             => \&_check_cc,
112
        comment        => \&_check_comment,
113
        component      => \&_check_component,
114
        creation_ts    => \&_check_creation_ts,
115
        deadline       => \&_check_deadline,
116
        dependson      => \&_check_dependencies,
117
        dup_id         => \&_check_dup_id,
118
        estimated_time => \&_check_time_field,
119 120 121
        everconfirmed  => \&Bugzilla::Object::check_boolean,
        groups         => \&_check_groups,
        keywords       => \&_check_keywords,
122
        op_sys         => \&_check_select_field,
123 124
        priority       => \&_check_priority,
        product        => \&_check_product,
125
        qa_contact     => \&_check_qa_contact,
126
        remaining_time => \&_check_time_field,
127
        rep_platform   => \&_check_select_field,
128
        resolution     => \&_check_resolution,
129 130
        short_desc     => \&_check_short_desc,
        status_whiteboard => \&_check_status_whiteboard,
131 132 133 134 135
        target_milestone  => \&_check_target_milestone,
        version           => \&_check_version,

        cclist_accessible   => \&Bugzilla::Object::check_boolean,
        reporter_accessible => \&Bugzilla::Object::check_boolean,
136 137
    };

138
    # Set up validators for custom fields.    
139
    foreach my $field (Bugzilla->active_custom_fields) {
140 141 142 143
        my $validator;
        if ($field->type == FIELD_TYPE_SINGLE_SELECT) {
            $validator = \&_check_select_field;
        }
144 145 146
        elsif ($field->type == FIELD_TYPE_MULTI_SELECT) {
            $validator = \&_check_multi_select_field;
        }
147 148 149
        elsif ($field->type == FIELD_TYPE_DATETIME) {
            $validator = \&_check_datetime_field;
        }
150 151 152
        elsif ($field->type == FIELD_TYPE_DATE) {
            $validator = \&_check_date_field;
        }
153
        elsif ($field->type == FIELD_TYPE_FREETEXT) {
154 155
            $validator = \&_check_freetext_field;
        }
156 157 158
        elsif ($field->type == FIELD_TYPE_BUG_ID) {
            $validator = \&_check_bugid_field;
        }
159 160 161
        elsif ($field->type == FIELD_TYPE_TEXTAREA) {
            $validator = \&_check_textarea_field;
        }
162 163 164
        elsif ($field->type == FIELD_TYPE_INTEGER) {
            $validator = \&_check_integer_field;
        }
165 166 167
        else {
            $validator = \&_check_default_field;
        }
168
        $validators->{$field->name} = $validator;
169
    }
170

171
    return $validators;
172 173
};

174 175 176 177 178 179 180
sub VALIDATOR_DEPENDENCIES {
    my $cache = Bugzilla->request_cache;
    return $cache->{bug_validator_dependencies} 
        if $cache->{bug_validator_dependencies};

    my %deps = (
        assigned_to      => ['component'],
181
        blocked          => ['product'],
182
        bug_status       => ['product', 'comment', 'target_milestone'],
183
        cc               => ['component'],
184
        comment          => ['creation_ts'],
185
        component        => ['product'],
186
        dependson        => ['product'],
187
        dup_id           => ['bug_status', 'resolution'],
188 189
        groups           => ['product'],
        keywords         => ['product'],
190
        resolution       => ['bug_status', 'dependson'],
191 192 193 194 195
        qa_contact       => ['component'],
        target_milestone => ['product'],
        version          => ['product'],
    );

196 197 198
    foreach my $field (@{ Bugzilla->fields }) {
        $deps{$field->name} = [ $field->visibility_field->name ]
            if $field->{visibility_field_id};
199
    }
200

201 202
    $cache->{bug_validator_dependencies} = \%deps;
    return \%deps;
203 204
};

205
sub UPDATE_COLUMNS {
206 207
    my @custom = grep {$_->type != FIELD_TYPE_MULTI_SELECT}
                      Bugzilla->active_custom_fields;
208
    my @custom_names = map {$_->name} @custom;
209
    my @columns = qw(
210
        assigned_to
211 212 213
        bug_file_loc
        bug_severity
        bug_status
214
        cclist_accessible
215
        component_id
216 217
        deadline
        estimated_time
218 219 220
        everconfirmed
        op_sys
        priority
221
        product_id
222
        qa_contact
223
        remaining_time
224
        rep_platform
225
        reporter_accessible
226 227 228
        resolution
        short_desc
        status_whiteboard
229 230
        target_milestone
        version
231
    );
232
    push(@columns, @custom_names);
233 234
    return @columns;
};
235

236 237 238 239 240
use constant NUMERIC_COLUMNS => qw(
    estimated_time
    remaining_time
);

241
sub DATE_COLUMNS {
242 243 244
    my @fields = (@{ Bugzilla->fields({ type => [FIELD_TYPE_DATETIME,
                                                 FIELD_TYPE_DATE] })
                   });
245 246 247
    return map { $_->name } @fields;
}

248 249 250 251
# Used in LogActivityEntry(). Gives the max length of lines in the
# activity table.
use constant MAX_LINE_LENGTH => 254;

252 253 254 255 256
# This maps the names of internal Bugzilla bug fields to things that would
# make sense to somebody who's not intimately familiar with the inner workings
# of Bugzilla. (These are the field names that the WebService and email_in.pl
# use.)
use constant FIELD_MAP => {
257
    blocks           => 'blocked',
258
    commentprivacy   => 'comment_is_private',
259
    creation_time    => 'creation_ts',
260
    creator          => 'reporter',
261
    description      => 'comment',
262 263
    depends_on       => 'dependson',
    dupe_of          => 'dup_id',
264
    id               => 'bug_id',
265 266 267
    is_confirmed     => 'everconfirmed',
    is_cc_accessible => 'cclist_accessible',
    is_creator_accessible => 'reporter_accessible',
268 269 270 271 272 273 274 275 276
    last_change_time => 'delta_ts',
    platform         => 'rep_platform',
    severity         => 'bug_severity',
    status           => 'bug_status',
    summary          => 'short_desc',
    url              => 'bug_file_loc',
    whiteboard       => 'status_whiteboard',
};

277 278 279 280 281
use constant REQUIRED_FIELD_MAP => {
    product_id   => 'product',
    component_id => 'component',
};

282 283 284
# Creation timestamp is here because it needs to be validated
# but it can be NULL in the database (see comments in create above)
#
285 286 287 288 289 290 291 292 293 294 295 296 297
# Target Milestone is here because it has a default that the validator
# creates (product.defaultmilestone) that is different from the database
# default.
#
# CC is here because it is a separate table, and has a validator-created
# default of the component initialcc.
#
# QA Contact is allowed to be NULL in the database, so it wouldn't normally
# be caught by _required_create_fields. However, it always has to be validated,
# because it has a default of the component.defaultqacontact.
#
# Groups are in a separate table, but must always be validated so that
# mandatory groups get set on bugs.
298
use constant EXTRA_REQUIRED_FIELDS => qw(creation_ts target_milestone cc qa_contact groups);
299

300 301
#####################################################################

302
sub new {
303 304 305 306
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
    my $param = shift;

307 308 309 310 311
    # Remove leading "#" mark if we've just been passed an id.
    if (!ref $param && $param =~ /^#(\d+)$/) {
        $param = $1;
    }

312 313
    # If we get something that looks like a word (not a number),
    # make it the "name" param.
314
    if (!defined $param
315 316
        || (!ref($param) && $param !~ /^\d+$/)
        || (ref($param) && $param->{id} !~ /^\d+$/))
317
    {
318
        if ($param) {
319 320 321 322 323 324 325 326 327 328
            my $alias = ref($param) ? $param->{id} : $param;
            my $bug_id = bug_alias_to_id($alias);
            if (! $bug_id) {
                my $error_self = {};
                bless $error_self, $class;
                $error_self->{'bug_id'} = $alias;
                $error_self->{'error'}  = 'InvalidBugId';
                return $error_self;
            }
            $param = { id => $bug_id,
329
                       cache => ref($param) ? $param->{cache} : 0 };
330 331
        }
        else {
332
            # We got something that's not a number.
333 334 335 336 337 338
            my $error_self = {};
            bless $error_self, $class;
            $error_self->{'bug_id'} = $param;
            $error_self->{'error'}  = 'InvalidBugId';
            return $error_self;
        }
339 340
    }

341 342 343 344 345 346 347
    unshift @_, $param;
    my $self = $class->SUPER::new(@_);

    # Bugzilla::Bug->new always returns something, but sets $self->{error}
    # if the bug wasn't found in the database.
    if (!$self) {
        my $error_self = {};
348 349 350 351 352 353 354 355
        if (ref $param) {
            $error_self->{bug_id} = $param->{name};
            $error_self->{error}  = 'InvalidBugId';
        }
        else {
            $error_self->{bug_id} = $param;
            $error_self->{error}  = 'NotFound';
        }
356 357
        bless $error_self, $class;
        return $error_self;
358
    }
359 360

    return $self;
361 362
}

363 364 365 366
sub initialize {
    $_[0]->_create_cf_accessors();
}

367
sub object_cache_key {
368
    my $class = shift;
369
    my $key = $class->SUPER::object_cache_key(@_)
370 371 372 373
      || return;
    return $key . ',' . Bugzilla->user->id;
}

374 375
sub check {
    my $class = shift;
376
    my ($param, $field) = @_;
377

378 379
    # Bugzilla::Bug throws lots of special errors, so we don't call
    # SUPER::check, we just call our new and do our own checks.
380 381 382 383 384 385
    my $id = ref($param)
        ? ($param->{id} = trim($param->{id}))
        : ($param = trim($param));
    ThrowUserError('improper_bug_id_field_value', { field => $field }) unless defined $id;

    my $self = $class->new($param);
386 387

    if ($self->{error}) {
388 389 390 391
        # For error messages, use the id that was returned by new(), because
        # it's cleaned up.
        $id = $self->id;

392 393 394 395 396 397 398 399 400 401
        if ($self->{error} eq 'NotFound') {
             ThrowUserError("bug_id_does_not_exist", { bug_id => $id });
        }
        if ($self->{error} eq 'InvalidBugId') {
            ThrowUserError("improper_bug_id_field_value",
                              { bug_id => $id,
                                field  => $field });
        }
    }

402
    unless ($field && $field =~ /^(dependson|blocked|dup_id)$/) {
403
        $self->check_is_visible($id);
404 405 406
    }
    return $self;
}
407

408 409 410 411 412 413 414 415 416 417
sub check_for_edit {
    my $class = shift;
    my $bug = $class->check(@_);

    Bugzilla->user->can_edit_product($bug->product_id)
        || ThrowUserError("product_edit_denied", { product => $bug->product });

    return $bug;
}

418
sub check_is_visible {
419 420
    my ($self, $input_id) = @_;
    $input_id ||= $self->id;
421
    my $user = Bugzilla->user;
422 423

    if (!$user->can_see_bug($self->id)) {
424 425
        # The error the user sees depends on whether or not they are
        # logged in (i.e. $user->id contains the user's positive integer ID).
426 427
        # If we are validating an alias, then use it in the error message
        # instead of its corresponding bug ID, to not disclose it.
428
        if ($user->id) {
429
            ThrowUserError("bug_access_denied", { bug_id => $input_id });
430
        } else {
431
            ThrowUserError("bug_access_query", { bug_id => $input_id });
432 433
        }
    }
434 435
}

436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
sub match {
    my $class = shift;
    my ($params) = @_;

    # Allow matching certain fields by name (in addition to matching by ID).
    my %translate_fields = (
        assigned_to => 'Bugzilla::User',
        qa_contact  => 'Bugzilla::User',
        reporter    => 'Bugzilla::User',
        product     => 'Bugzilla::Product',
        component   => 'Bugzilla::Component',
    );
    my %translated;

    foreach my $field (keys %translate_fields) {
        my @ids;
        # Convert names to ids. We use "exists" everywhere since people can
        # legally specify "undef" to mean IS NULL (even though most of these
        # fields can't be NULL, people can still specify it...).
        if (exists $params->{$field}) {
            my $names = $params->{$field};
            my $type = $translate_fields{$field};
            my $param = $type eq 'Bugzilla::User' ? 'login_name' : 'name';
            # We call Bugzilla::Object::match directly to avoid the
            # Bugzilla::User::match implementation which is different.
            my $objects = Bugzilla::Object::match($type, { $param => $names });
            push(@ids, map { $_->id } @$objects);
        }
        # You can also specify ids directly as arguments to this function,
        # so include them in the list if they have been specified.
        if (exists $params->{"${field}_id"}) {
            my $current_ids = $params->{"${field}_id"};
            my @id_array = ref $current_ids ? @$current_ids : ($current_ids);
            push(@ids, @id_array);
        }
        # We do this "or" instead of a "scalar(@ids)" to handle the case
        # when people passed only invalid object names. Otherwise we'd
        # end up with a SUPER::match call with zero criteria (which dies).
        if (exists $params->{$field} or exists $params->{"${field}_id"}) {
            $translated{$field} = scalar(@ids) == 1 ? $ids[0] : \@ids;
        }
    }

    # The user fields don't have an _id on the end of them in the database,
    # but the product & component fields do, so we have to have separate
    # code to deal with the different sets of fields here.
    foreach my $field (qw(assigned_to qa_contact reporter)) {
        delete $params->{"${field}_id"};
        $params->{$field} = $translated{$field} 
            if exists $translated{$field};
    }
    foreach my $field (qw(product component)) {
        delete $params->{$field};
        $params->{"${field}_id"} = $translated{$field} 
            if exists $translated{$field};
    }

    return $class->SUPER::match(@_);
}

496 497 498 499 500 501 502 503 504 505 506 507
# Helps load up information for bugs for show_bug.cgi and other situations
# that will need to access info on lots of bugs.
sub preload {
    my ($class, $bugs) = @_;
    my $user = Bugzilla->user;

    # It would be faster but MUCH more complicated to select all the
    # deps for the entire list in one SQL statement. If we ever have
    # a profile that proves that that's necessary, we can switch over
    # to the more complex method.
    my @all_dep_ids;
    foreach my $bug (@$bugs) {
508 509 510
        push @all_dep_ids, @{ $bug->blocked }, @{ $bug->dependson };
        push @all_dep_ids, @{ $bug->duplicate_ids };
        push @all_dep_ids, @{ $bug->_preload_referenced_bugs };
511 512 513
    }
    @all_dep_ids = uniq @all_dep_ids;
    # If we don't do this, can_see_bug will do one call per bug in
514
    # the dependency and duplicate lists, in Bugzilla::Template::get_bug_link.
515
    $user->visible_bugs(\@all_dep_ids);
516 517 518 519 520 521 522 523 524
}

# Helps load up bugs referenced in comments by retrieving them with a single
# query from the database and injecting bug objects into the object-cache.
sub _preload_referenced_bugs {
    my $self = shift;

    # inject current duplicates into the object-cache first
    foreach my $bug (@{ $self->duplicates }) {
525
        $bug->object_cache_set() unless Bugzilla::Bug->object_cache_get($bug->id);
526 527 528
    }

    # preload bugs from comments
529 530
    my $referenced_bug_ids = _extract_bug_ids($self->comments);
    my @ref_bug_ids = grep { !Bugzilla::Bug->object_cache_get($_) } @$referenced_bug_ids;
531 532

    # inject into object-cache
533 534
    my $referenced_bugs = Bugzilla::Bug->new_from_list(\@ref_bug_ids);
    $_->object_cache_set() foreach @$referenced_bugs;
535

536
    return $referenced_bug_ids;
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
}

# Extract bug IDs mentioned in comments. This is much faster than calling quoteUrls().
sub _extract_bug_ids {
    my $comments = shift;
    my @bug_ids;

    my $params = Bugzilla->params;
    my @urlbases = ($params->{'urlbase'});
    push(@urlbases, $params->{'sslbase'}) if $params->{'sslbase'};
    my $urlbase_re = '(?:' . join('|', map { qr/$_/ } @urlbases) . ')';
    my $bug_word = template_var('terms')->{bug};
    my $bugs_word = template_var('terms')->{bugs};

    foreach my $comment (@$comments) {
        if ($comment->type == CMT_HAS_DUPE || $comment->type == CMT_DUPE_OF) {
            push @bug_ids, $comment->extra_data;
            next;
        }
        my $s = $comment->already_wrapped ? qr/\s/ : qr/\h/;
        my $text = $comment->body;
        # Full bug links
        push @bug_ids, $text =~ /\b$urlbase_re\Qshow_bug.cgi?id=\E(\d+)(?:\#c\d+)?/g;
        # bug X
        my $bug_re = qr/\Q$bug_word\E$s*\#?$s*(\d+)/i;
        push @bug_ids, $text =~ /\b$bug_re/g;
        # bugs X, Y, Z
        my $bugs_re = qr/\Q$bugs_word\E$s*\#?$s*(\d+)(?:$s*,$s*\#?$s*(\d+))+/i;
        push @bug_ids, $text =~ /\b$bugs_re/g;
        # Old duplicate markers
        push @bug_ids, $text =~ /(?<=^\*\*\*\ This\ bug\ has\ been\ marked\ as\ a\ duplicate\ of\ )(\d+)(?=\ \*\*\*\Z)/;
    }
569 570
    # Make sure to filter invalid bug IDs.
    @bug_ids = grep { $_ < MAX_INT_32 } @bug_ids;
571
    return [uniq @bug_ids];
572 573
}

574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
sub possible_duplicates {
    my ($class, $params) = @_;
    my $short_desc = $params->{summary};
    my $products = $params->{products} || [];
    my $limit = $params->{limit} || MAX_POSSIBLE_DUPLICATES;
    $limit = MAX_POSSIBLE_DUPLICATES if $limit > MAX_POSSIBLE_DUPLICATES;
    $products = [$products] if !ref($products) eq 'ARRAY';

    my $orig_limit = $limit;
    detaint_natural($limit) 
        || ThrowCodeError('param_must_be_numeric', 
                          { function => 'possible_duplicates',
                            param    => $orig_limit });

    my $dbh = Bugzilla->dbh;
    my $user = Bugzilla->user;
    my @words = split(/[\b\s]+/, $short_desc || '');
591 592 593 594
    # Remove leading/trailing punctuation from words
    foreach my $word (@words) {
        $word =~ s/(?:^\W+|\W+$)//g;
    }
595 596 597 598 599 600 601 602 603
    # And make sure that each word is longer than 2 characters.
    @words = grep { defined $_ and length($_) > 2 } @words;

    return [] if !@words;

    my ($where_sql, $relevance_sql);
    if ($dbh->FULLTEXT_OR) {
        my $joined_terms = join($dbh->FULLTEXT_OR, @words);
        ($where_sql, $relevance_sql) = 
604
            $dbh->sql_fulltext_search('bugs_fulltext.short_desc', $joined_terms);
605 606 607 608 609 610
        $relevance_sql ||= $where_sql;
    }
    else {
        my (@where, @relevance);
        foreach my $word (@words) {
            my ($term, $rel_term) = $dbh->sql_fulltext_search(
611
                'bugs_fulltext.short_desc', $word);
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
            push(@where, $term);
            push(@relevance, $rel_term || $term);
        }

        $where_sql = join(' OR ', @where);
        $relevance_sql = join(' + ', @relevance);
    }

    my $product_ids = join(',', map { $_->id } @$products);
    my $product_sql = $product_ids ? "AND product_id IN ($product_ids)" : "";

    # Because we collapse duplicates, we want to get slightly more bugs
    # than were actually asked for.
    my $sql_limit = $limit + 5;

    my $possible_dupes = $dbh->selectall_arrayref(
        "SELECT bugs.bug_id AS bug_id, bugs.resolution AS resolution,
                ($relevance_sql) AS relevance
           FROM bugs
                INNER JOIN bugs_fulltext ON bugs.bug_id = bugs_fulltext.bug_id
          WHERE ($where_sql) $product_sql
633 634
       ORDER BY relevance DESC, bug_id DESC " .
          $dbh->sql_limit($sql_limit), {Slice=>{}});
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653

    my @actual_dupe_ids;
    # Resolve duplicates into their ultimate target duplicates.
    foreach my $bug (@$possible_dupes) {
        my $push_id = $bug->{bug_id};
        if ($bug->{resolution} && $bug->{resolution} eq 'DUPLICATE') {
            $push_id = _resolve_ultimate_dup_id($bug->{bug_id});
        }
        push(@actual_dupe_ids, $push_id);
    }
    @actual_dupe_ids = uniq @actual_dupe_ids;
    if (scalar @actual_dupe_ids > $limit) {
        @actual_dupe_ids = @actual_dupe_ids[0..($limit-1)];
    }

    my $visible = $user->visible_bugs(\@actual_dupe_ids);
    return $class->new_from_list($visible);
}

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
# Docs for create() (there's no POD in this file yet, but we very
# much need this documented right now):
#
# The same as Bugzilla::Object->create. Parameters are only required
# if they say so below.
#
# Params:
#
# C<product>     - B<Required> The name of the product this bug is being
#                  filed against.
# C<component>   - B<Required> The name of the component this bug is being
#                  filed against.
#
# C<bug_severity> - B<Required> The severity for the bug, a string.
# C<creation_ts>  - B<Required> A SQL timestamp for when the bug was created.
# C<short_desc>   - B<Required> A summary for the bug.
# C<op_sys>       - B<Required> The OS the bug was found against.
# C<priority>     - B<Required> The initial priority for the bug.
# C<rep_platform> - B<Required> The platform the bug was found against.
# C<version>      - B<Required> The version of the product the bug was found in.
#
675
# C<alias>        - An alias for this bug.
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
# C<target_milestone> - When this bug is expected to be fixed.
# C<status_whiteboard> - A string.
# C<bug_status>   - The initial status of the bug, a string.
# C<bug_file_loc> - The URL field.
#
# C<assigned_to> - The full login name of the user who the bug is
#                  initially assigned to.
# C<qa_contact>  - The full login name of the QA Contact for this bug. 
#                  Will be ignored if C<useqacontact> is off.
#
# C<estimated_time> - For time-tracking. Will be ignored if 
#                     C<timetrackinggroup> is not set, or if the current
#                     user is not a member of the timetrackinggroup.
# C<deadline>       - For time-tracking. Will be ignored for the same
#                     reasons as C<estimated_time>.
691
sub create {
692
    my ($class, $params) = @_;
693 694
    my $dbh = Bugzilla->dbh;

695 696
    $dbh->bz_start_transaction();

697 698 699 700 701 702 703 704 705 706 707 708 709 710
    # These fields have default values which we can use if they are undefined.
    $params->{bug_severity} = Bugzilla->params->{defaultseverity}
      unless defined $params->{bug_severity};
    $params->{priority} = Bugzilla->params->{defaultpriority}
      unless defined $params->{priority};
    $params->{op_sys} = Bugzilla->params->{defaultopsys}
      unless defined $params->{op_sys};
    $params->{rep_platform} = Bugzilla->params->{defaultplatform}
      unless defined $params->{rep_platform};
    # Make sure a comment is always defined.
    $params->{comment} = '' unless defined $params->{comment};

    $class->check_required_create_fields($params);
    $params = $class->run_create_validators($params);
711

712
    # These are not a fields in the bugs table, so we don't pass them to
713
    # insert_create_data.
714
    my $bug_aliases      = delete $params->{alias};
715 716 717 718 719 720
    my $cc_ids           = delete $params->{cc};
    my $groups           = delete $params->{groups};
    my $depends_on       = delete $params->{dependson};
    my $blocked          = delete $params->{blocked};
    my $keywords         = delete $params->{keywords};
    my $creation_comment = delete $params->{comment};
721
    my $see_also         = delete $params->{see_also};
722

723 724
    # We don't want the bug to appear in the system until it's correctly
    # protected by groups.
725
    my $timestamp = delete $params->{creation_ts}; 
726

727
    my $ms_values = $class->_extract_multi_selects($params);
728 729
    my $bug = $class->insert_create_data($params);

730 731 732
    # Add the group restrictions
    my $sth_group = $dbh->prepare(
        'INSERT INTO bug_group_map (bug_id, group_id) VALUES (?, ?)');
733 734
    foreach my $group (@$groups) {
        $sth_group->execute($bug->bug_id, $group->id);
735 736
    }

737 738
    $dbh->do('UPDATE bugs SET creation_ts = ? WHERE bug_id = ?', undef,
             $timestamp, $bug->bug_id);
739 740
    # Update the bug instance as well
    $bug->{creation_ts} = $timestamp;
741

742
    # Add the CCs
743 744 745 746 747
    my $sth_cc = $dbh->prepare('INSERT INTO cc (bug_id, who) VALUES (?,?)');
    foreach my $user_id (@$cc_ids) {
        $sth_cc->execute($bug->bug_id, $user_id);
    }

748 749 750 751 752 753 754
    # Add in keywords
    my $sth_keyword = $dbh->prepare(
        'INSERT INTO keywords (bug_id, keywordid) VALUES (?, ?)');
    foreach my $keyword_id (map($_->id, @$keywords)) {
        $sth_keyword->execute($bug->bug_id, $keyword_id);
    }

755 756 757
    # Set up dependencies (blocked/dependson)
    my $sth_deps = $dbh->prepare(
        'INSERT INTO dependencies (blocked, dependson) VALUES (?, ?)');
758 759
    my $sth_bug_time = $dbh->prepare('UPDATE bugs SET delta_ts = ? WHERE bug_id = ?');

760 761 762 763
    foreach my $depends_on_id (@$depends_on) {
        $sth_deps->execute($bug->bug_id, $depends_on_id);
        # Log the reverse action on the other bug.
        LogActivityEntry($depends_on_id, 'blocked', '', $bug->bug_id,
764
                         $bug->{reporter_id}, $timestamp);
765
        $sth_bug_time->execute($timestamp, $depends_on_id);
766 767 768 769 770
    }
    foreach my $blocked_id (@$blocked) {
        $sth_deps->execute($blocked_id, $bug->bug_id);
        # Log the reverse action on the other bug.
        LogActivityEntry($blocked_id, 'dependson', '', $bug->bug_id,
771
                         $bug->{reporter_id}, $timestamp);
772
        $sth_bug_time->execute($timestamp, $blocked_id);
773 774
    }

775 776 777 778 779 780 781 782 783 784
    # Insert the values into the multiselect value tables
    foreach my $field (keys %$ms_values) {
        $dbh->do("DELETE FROM bug_$field where bug_id = ?",
                undef, $bug->bug_id);
        foreach my $value ( @{$ms_values->{$field}} ) {
            $dbh->do("INSERT INTO bug_$field (bug_id, value) VALUES (?,?)",
                    undef, $bug->bug_id, $value);
        }
    }

785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
    # Insert any see_also values
    if ($see_also) {
        my $see_also_array = $see_also;
        if (!ref $see_also_array) {
            $see_also = trim($see_also);
            $see_also_array = [ split(/[\s,]+/, $see_also) ];
        }
        foreach my $value (@$see_also_array) {
            $bug->add_see_also($value);
        }
        foreach my $see_also (@{ $bug->see_also }) {
            $see_also->insert_create_data($see_also);
        }
        foreach my $ref_bug (@{ $bug->{_update_ref_bugs} || [] }) {
            $ref_bug->update();
        }
        delete $bug->{_update_ref_bugs};
    }

804 805 806 807 808 809
    # Comment #0 handling...

    # We now have a bug id so we can fill this out
    $creation_comment->{'bug_id'} = $bug->id;

    # Insert the comment. We always insert a comment on bug creation,
810
    # but sometimes it's blank.
811
    Bugzilla::Comment->insert_create_data($creation_comment);
812

813 814 815 816 817 818 819
    # Set up aliases
    my $sth_aliases = $dbh->prepare('INSERT INTO bugs_aliases (alias, bug_id) VALUES (?, ?)');
    foreach my $alias (@$bug_aliases) {
        trick_taint($alias);
        $sth_aliases->execute($alias, $bug->bug_id);
    }

820
    Bugzilla::Hook::process('bug_end_of_create', { bug => $bug,
821 822 823
                                                   timestamp => $timestamp,
                                                 });

824 825 826 827 828
    $dbh->bz_commit_transaction();

    # Because MySQL doesn't support transactions on the fulltext table,
    # we do this after we've committed the transaction. That way we're
    # sure we're inserting a good Bug ID.
829
    $bug->_sync_fulltext( new_bug => 1 );
830

831 832 833
    return $bug;
}

834 835
sub run_create_validators {
    my $class  = shift;
836
    my $params = $class->SUPER::run_create_validators(@_);
837

838 839 840 841 842 843 844 845 846 847 848
    # Add classification for checking mandatory fields which depend on it
    $params->{classification} = $params->{product}->classification->name;

    my @mandatory_fields = @{ Bugzilla->fields({ is_mandatory => 1,
                                                 enter_bug    => 1,
                                                 obsolete     => 0 }) };
    foreach my $field (@mandatory_fields) {
        $class->_check_field_is_mandatory($params->{$field->name}, $field,
                                          $params);
    }

849
    my $product = delete $params->{product};
850
    $params->{product_id} = $product->id;
851
    my $component = delete $params->{component};
852
    $params->{component_id} = $component->id;
853

854
    # Callers cannot set reporter, creation_ts, or delta_ts.
855
    $params->{reporter} = $class->_check_reporter();
856
    $params->{delta_ts} = $params->{creation_ts};
857 858 859 860

    if ($params->{estimated_time}) {
        $params->{remaining_time} = $params->{estimated_time};
    }
861

862 863
    $class->_check_strict_isolation($params->{cc}, $params->{assigned_to},
                                    $params->{qa_contact}, $product);
864

865
    # You can't set these fields.
866 867
    delete $params->{lastdiffed};
    delete $params->{bug_id};
868
    delete $params->{classification};
869

870
    Bugzilla::Hook::process('bug_end_of_create_validators',
871 872
                            { params => $params });

873 874 875 876 877
    # And this is not a valid DB field, it's just used as part of 
    # _check_dependencies to avoid running it twice for both blocked 
    # and dependson.
    delete $params->{_dependencies_validated};

878
    return $params;
879 880
}

881 882
sub update {
    my $self = shift;
883 884
    my $dbh  = Bugzilla->dbh;
    my $user = Bugzilla->user;
885 886 887

    # XXX This is just a temporary hack until all updating happens
    # inside this function.
888
    my $delta_ts = shift || $dbh->selectrow_array('SELECT LOCALTIMESTAMP(0)');
889

890 891
    $dbh->bz_start_transaction();

892
    my ($changes, $old_bug) = $self->SUPER::update(@_);
893

894 895 896 897
    Bugzilla::Hook::process('bug_start_of_update',
        { timestamp => $delta_ts, bug => $self,
           old_bug => $old_bug, changes => $changes });

898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
    # Certain items in $changes have to be fixed so that they hold
    # a name instead of an ID.
    foreach my $field (qw(product_id component_id)) {
        my $change = delete $changes->{$field};
        if ($change) {
            my $new_field = $field;
            $new_field =~ s/_id$//;
            $changes->{$new_field} = 
                [$self->{"_old_${new_field}_name"}, $self->$new_field];
        }
    }
    foreach my $field (qw(qa_contact assigned_to)) {
        if ($changes->{$field}) {
            my ($from, $to) = @{ $changes->{$field} };
            $from = $old_bug->$field->login if $from;
            $to   = $self->$field->login    if $to;
            $changes->{$field} = [$from, $to];
        }
    }

918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
    # CC
    my @old_cc = map {$_->id} @{$old_bug->cc_users};
    my @new_cc = map {$_->id} @{$self->cc_users};
    my ($removed_cc, $added_cc) = diff_arrays(\@old_cc, \@new_cc);
    
    if (scalar @$removed_cc) {
        $dbh->do('DELETE FROM cc WHERE bug_id = ? AND ' 
                 . $dbh->sql_in('who', $removed_cc), undef, $self->id);
    }
    foreach my $user_id (@$added_cc) {
        $dbh->do('INSERT INTO cc (bug_id, who) VALUES (?,?)',
                 undef, $self->id, $user_id);
    }
    # If any changes were found, record it in the activity log
    if (scalar @$removed_cc || scalar @$added_cc) {
        my $removed_users = Bugzilla::User->new_from_list($removed_cc);
        my $added_users   = Bugzilla::User->new_from_list($added_cc);
        my $removed_names = join(', ', (map {$_->login} @$removed_users));
        my $added_names   = join(', ', (map {$_->login} @$added_users));
        $changes->{cc} = [$removed_names, $added_names];
    }
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958

    # Aliases
    my $old_aliases = $old_bug->alias;
    my $new_aliases = $self->alias;
    my ($removed_aliases, $added_aliases) = diff_arrays($old_aliases, $new_aliases);

    foreach my $alias (@$removed_aliases) {
        $dbh->do('DELETE FROM bugs_aliases WHERE bug_id = ? AND alias = ?',
                 undef, $self->id, $alias);
    }
    foreach my $alias (@$added_aliases) {
        trick_taint($alias);
        $dbh->do('INSERT INTO bugs_aliases (bug_id, alias) VALUES (?,?)',
                 undef, $self->id, $alias);
    }
    # If any changes were found, record it in the activity log
    if (scalar @$removed_aliases || scalar @$added_aliases) {
        $changes->{alias} = [join(', ', @$removed_aliases), join(', ', @$added_aliases)];
    }

959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
    # Keywords
    my @old_kw_ids = map { $_->id } @{$old_bug->keyword_objects};
    my @new_kw_ids = map { $_->id } @{$self->keyword_objects};

    my ($removed_kw, $added_kw) = diff_arrays(\@old_kw_ids, \@new_kw_ids);

    if (scalar @$removed_kw) {
        $dbh->do('DELETE FROM keywords WHERE bug_id = ? AND ' 
                 . $dbh->sql_in('keywordid', $removed_kw), undef, $self->id);
    }
    foreach my $keyword_id (@$added_kw) {
        $dbh->do('INSERT INTO keywords (bug_id, keywordid) VALUES (?,?)',
                 undef, $self->id, $keyword_id);
    }
    # If any changes were found, record it in the activity log
    if (scalar @$removed_kw || scalar @$added_kw) {
        my $removed_keywords = Bugzilla::Keyword->new_from_list($removed_kw);
        my $added_keywords   = Bugzilla::Keyword->new_from_list($added_kw);
        my $removed_names = join(', ', (map {$_->name} @$removed_keywords));
        my $added_names   = join(', ', (map {$_->name} @$added_keywords));
        $changes->{keywords} = [$removed_names, $added_names];
    }

    # Dependencies
    foreach my $pair ([qw(dependson blocked)], [qw(blocked dependson)]) {
        my ($type, $other) = @$pair;
        my $old = $old_bug->$type;
        my $new = $self->$type;
        
        my ($removed, $added) = diff_arrays($old, $new);
        foreach my $removed_id (@$removed) {
            $dbh->do("DELETE FROM dependencies WHERE $type = ? AND $other = ?",
                     undef, $removed_id, $self->id);
            
            # Add an activity entry for the other bug.
            LogActivityEntry($removed_id, $other, $self->id, '',
995
                             $user->id, $delta_ts);
996 997 998 999 1000 1001 1002 1003 1004 1005
            # Update delta_ts on the other bug so that we trigger mid-airs.
            $dbh->do('UPDATE bugs SET delta_ts = ? WHERE bug_id = ?',
                     undef, $delta_ts, $removed_id);
        }
        foreach my $added_id (@$added) {
            $dbh->do("INSERT INTO dependencies ($type, $other) VALUES (?,?)",
                     undef, $added_id, $self->id);
            
            # Add an activity entry for the other bug.
            LogActivityEntry($added_id, $other, '', $self->id,
1006
                             $user->id, $delta_ts);
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
            # Update delta_ts on the other bug so that we trigger mid-airs.
            $dbh->do('UPDATE bugs SET delta_ts = ? WHERE bug_id = ?',
                     undef, $delta_ts, $added_id);
        }
        
        if (scalar(@$removed) || scalar(@$added)) {
            $changes->{$type} = [join(', ', @$removed), join(', ', @$added)];
        }
    }

    # Groups
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    my %old_groups = map {$_->id => $_} @{$old_bug->groups_in};
    my %new_groups = map {$_->id => $_} @{$self->groups_in};
    my ($removed_gr, $added_gr) = diff_arrays([keys %old_groups],
                                              [keys %new_groups]);
    if (scalar @$removed_gr || scalar @$added_gr) {
        if (@$removed_gr) {
            my $qmarks = join(',', ('?') x @$removed_gr);
            $dbh->do("DELETE FROM bug_group_map
                       WHERE bug_id = ? AND group_id IN ($qmarks)", undef,
                     $self->id, @$removed_gr);
        }
        my $sth_insert = $dbh->prepare(
            'INSERT INTO bug_group_map (bug_id, group_id) VALUES (?,?)');
        foreach my $gid (@$added_gr) {
            $sth_insert->execute($self->id, $gid);
        }
        my @removed_names = map { $old_groups{$_}->name } @$removed_gr;
        my @added_names   = map { $new_groups{$_}->name } @$added_gr;
        $changes->{'bug_group'} = [join(', ', @removed_names),
                                   join(', ', @added_names)];
    }
1039

1040
    # Comments
1041
    foreach my $comment (@{$self->{added_comments} || []}) {
1042 1043 1044
        # Override the Comment's timestamp to be identical to the update
        # timestamp.
        $comment->{bug_when} = $delta_ts;
1045
        $comment = Bugzilla::Comment->insert_create_data($comment);
1046 1047
        if ($comment->work_time) {
            LogActivityEntry($self->id, "work_time", "", $comment->work_time,
1048
                             $user->id, $delta_ts);
1049
        }
1050
    }
1051

1052
    # Comment Privacy 
1053 1054 1055
    foreach my $comment (@{$self->{comment_isprivate} || []}) {
        $comment->update();
        
1056
        my ($from, $to) 
1057
            = $comment->is_private ? (0, 1) : (1, 0);
1058
        LogActivityEntry($self->id, "longdescs.isprivate", $from, $to, 
1059
                         $user->id, $delta_ts, $comment->id);
1060
    }
1061

1062 1063 1064
    # Clear the cache of comments
    delete $self->{comments};

1065
    # Insert the values into the multiselect value tables
1066 1067
    my @multi_selects = grep {$_->type == FIELD_TYPE_MULTI_SELECT}
                             Bugzilla->active_custom_fields;
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
    foreach my $field (@multi_selects) {
        my $name = $field->name;
        my ($removed, $added) = diff_arrays($old_bug->$name, $self->$name);
        if (scalar @$removed || scalar @$added) {
            $changes->{$name} = [join(', ', @$removed), join(', ', @$added)];

            $dbh->do("DELETE FROM bug_$name where bug_id = ?",
                     undef, $self->id);
            foreach my $value (@{$self->$name}) {
                $dbh->do("INSERT INTO bug_$name (bug_id, value) VALUES (?,?)",
                         undef, $self->id, $value);
            }
        }
    }

1083
    # See Also
1084

1085 1086
    my ($removed_see, $added_see) =
        diff_arrays($old_bug->see_also, $self->see_also, 'name');
1087

1088 1089
    $_->remove_from_db foreach @$removed_see;
    $_->insert_create_data($_) foreach @$added_see;
1090

1091
    # If any changes were found, record it in the activity log
1092
    if (scalar @$removed_see || scalar @$added_see) {
1093 1094
        $changes->{see_also} = [join(', ', map { $_->name } @$removed_see),
                                join(', ', map { $_->name } @$added_see)];
1095 1096
    }

1097 1098 1099 1100 1101 1102
    # Flags
    my ($removed, $added) = Bugzilla::Flag->update_flags($self, $old_bug, $delta_ts);
    if ($removed || $added) {
        $changes->{'flagtypes.name'} = [$removed, $added];
    }

1103 1104 1105
    $_->update foreach @{ $self->{_update_ref_bugs} || [] };
    delete $self->{_update_ref_bugs};

1106 1107 1108 1109 1110
    # Log bugs_activity items
    # XXX Eventually, when bugs_activity is able to track the dupe_id,
    # this code should go below the duplicates-table-updating code below.
    foreach my $field (keys %$changes) {
        my $change = $changes->{$field};
1111 1112
        my $from = defined $change->[0] ? $change->[0] : '';
        my $to   = defined $change->[1] ? $change->[1] : '';
1113 1114
        LogActivityEntry($self->id, $field, $from, $to,
                         $user->id, $delta_ts);
1115 1116
    }

1117 1118 1119
    # Check if we have to update the duplicates table and the other bug.
    my ($old_dup, $cur_dup) = ($old_bug->dup_id || 0, $self->dup_id || 0);
    if ($old_dup != $cur_dup) {
1120
        $dbh->do("DELETE FROM duplicates WHERE dupe = ?", undef, $self->id);
1121 1122 1123 1124 1125 1126 1127
        if ($cur_dup) {
            $dbh->do('INSERT INTO duplicates (dupe, dupe_of) VALUES (?,?)',
                     undef, $self->id, $cur_dup);
            if (my $update_dup = delete $self->{_dup_for_update}) {
                $update_dup->update();
            }
        }
1128

1129
        $changes->{'dup_id'} = [$old_dup || undef, $cur_dup || undef];
1130 1131
    }

1132 1133 1134
    Bugzilla::Hook::process('bug_end_of_update', 
        { bug => $self, timestamp => $delta_ts, changes => $changes,
          old_bug => $old_bug });
1135

1136
    # If any change occurred, refresh the timestamp of the bug.
1137 1138 1139
    if (scalar(keys %$changes) || $self->{added_comments}
        || $self->{comment_isprivate})
    {
1140 1141
        $dbh->do('UPDATE bugs SET delta_ts = ? WHERE bug_id = ?',
                 undef, ($delta_ts, $self->id));
1142
        $self->{delta_ts} = $delta_ts;
1143 1144
    }

1145 1146 1147 1148 1149
    # Update last-visited
    if ($user->is_involved_in_bug($self)) {
        $self->update_user_last_visit($user, $delta_ts);
    }

1150 1151 1152 1153
    # If a user is no longer involved, remove their last visit entry
    my $last_visits =
      Bugzilla::BugUserLastVisit->match({ bug_id => $self->id });
    foreach my $lv (@$last_visits) {
1154
        $lv->remove_from_db() unless $lv->user->is_involved_in_bug($self);
1155 1156
    }

1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
    # Update bug ignore data if user wants to ignore mail for this bug
    if (exists $self->{'bug_ignored'}) {
        my $bug_ignored_changed;
        if ($self->{'bug_ignored'} && !$user->is_bug_ignored($self->id)) {
            $dbh->do('INSERT INTO email_bug_ignore
                      (user_id, bug_id) VALUES (?, ?)',
                     undef, $user->id, $self->id);
            $bug_ignored_changed = 1;

        }
        elsif (!$self->{'bug_ignored'} && $user->is_bug_ignored($self->id)) {
            $dbh->do('DELETE FROM email_bug_ignore
                      WHERE user_id = ? AND bug_id = ?',
                     undef, $user->id, $self->id);
            $bug_ignored_changed = 1;
        }
        delete $user->{bugs_ignored} if $bug_ignored_changed;
    }

1176 1177
    $dbh->bz_commit_transaction();

1178 1179 1180 1181
    # The only problem with this here is that update() is often called
    # in the middle of a transaction, and if that transaction is rolled
    # back, this change will *not* be rolled back. As we expect rollbacks
    # to be extremely rare, that is OK for us.
1182 1183 1184 1185
    $self->_sync_fulltext(
        update_short_desc => $changes->{short_desc},
        update_comments   => $self->{added_comments} || $self->{comment_isprivate}
    );
1186

1187 1188 1189 1190
    # Remove obsolete internal variables.
    delete $self->{'_old_assigned_to'};
    delete $self->{'_old_qa_contact'};

1191 1192
    # Also flush the visible_bugs cache for this bug as the user's
    # relationship with this bug may have changed.
1193
    delete $user->{_visible_bugs_cache}->{$self->id};
1194

1195 1196 1197
    return $changes;
}

1198 1199 1200 1201 1202 1203
# Used by create().
# We need to handle multi-select fields differently than normal fields,
# because they're arrays and don't go into the bugs table.
sub _extract_multi_selects {
    my ($invocant, $params) = @_;

1204 1205
    my @multi_selects = grep {$_->type == FIELD_TYPE_MULTI_SELECT}
                             Bugzilla->active_custom_fields;
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
    my %ms_values;
    foreach my $field (@multi_selects) {
        my $name = $field->name;
        if (exists $params->{$name}) {
            my $array = delete($params->{$name}) || [];
            $ms_values{$name} = $array;
        }
    }
    return \%ms_values;
}

1217 1218
# Should be called any time you update short_desc or change a comment.
sub _sync_fulltext {
1219
    my ($self, %options) = @_;
1220
    my $dbh = Bugzilla->dbh;
1221 1222 1223 1224 1225 1226 1227 1228 1229

    my($all_comments, $public_comments);
    if ($options{new_bug} || $options{update_comments}) {
        my $comments = $dbh->selectall_arrayref(
            'SELECT thetext, isprivate FROM longdescs WHERE bug_id = ?',
            undef, $self->id);
        $all_comments = join("\n", map { $_->[0] } @$comments);
        my @no_private = grep { !$_->[1] } @$comments;
        $public_comments = join("\n", map { $_->[0] } @no_private);
1230
    }
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254

    if ($options{new_bug}) {
        $dbh->do('INSERT INTO bugs_fulltext (bug_id, short_desc, comments,
                                             comments_noprivate)
                 VALUES (?, ?, ?, ?)',
                 undef,
                 $self->id, $self->short_desc, $all_comments, $public_comments);
    } else {
        my(@names, @values);
        if ($options{update_short_desc}) {
            push @names, 'short_desc';
            push @values, $self->short_desc;
        }
        if ($options{update_comments}) {
            push @names, ('comments', 'comments_noprivate');
            push @values, ($all_comments, $public_comments);
        }
        if (@names) {
            $dbh->do('UPDATE bugs_fulltext SET ' .
                     join(', ', map { "$_ = ?" } @names) .
                     ' WHERE bug_id = ?',
                     undef,
                     @values, $self->id);
        }
1255 1256 1257
    }
}

1258 1259 1260 1261
sub remove_from_db {
    my ($self) = @_;
    my $dbh = Bugzilla->dbh;

1262
    ThrowCodeError("bug_error", { bug => $self }) if $self->{'error'};
1263 1264

    my $bug_id = $self->{'bug_id'};
1265 1266
    $self->SUPER::remove_from_db();
    # The bugs_fulltext table doesn't support foreign keys.
1267
    $dbh->do("DELETE FROM bugs_fulltext WHERE bug_id = ?", undef, $bug_id);
1268
}
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286

#####################################################################
# Sending Email After Bug Update
#####################################################################

sub send_changes {
    my ($self, $changes, $vars) = @_;

    my $user = Bugzilla->user;

    my $old_qa  = $changes->{'qa_contact'}  
                  ? $changes->{'qa_contact'}->[0] : '';
    my $old_own = $changes->{'assigned_to'} 
                  ? $changes->{'assigned_to'}->[0] : '';
    my $old_cc  = $changes->{cc}
                  ? $changes->{cc}->[0] : '';

    my %forced = (
1287
        cc        => [split(/[,;]+/, $old_cc)],
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
        owner     => $old_own,
        qacontact => $old_qa,
        changer   => $user,
    );

    _send_bugmail({ id => $self->id, type => 'bug', forced => \%forced }, 
                  $vars);

    # If the bug was marked as a duplicate, we need to notify users on the
    # other bug of any changes to that bug.
    my $new_dup_id = $changes->{'dup_id'} ? $changes->{'dup_id'}->[1] : undef;
    if ($new_dup_id) {
        _send_bugmail({ forced => { changer => $user }, type => "dupe",
                        id => $new_dup_id }, $vars);
    }

    # If there were changes in dependencies, we need to notify those
    # dependencies.
    if ($changes->{'bug_status'}) {
        my ($old_status, $new_status) = @{ $changes->{'bug_status'} };

        # If this bug has changed from opened to closed or vice-versa,
        # then all of the bugs we block need to be notified.
        if (is_open_state($old_status) ne is_open_state($new_status)) {
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
            my $params = { forced   => { changer => $user },
                           type     => 'dep',
                           dep_only => 1,
                           blocker  => $self,
                           changes  => $changes };

            foreach my $id (@{ $self->blocked }) {
                $params->{id} = $id;
                _send_bugmail($params, $vars);
            }
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
        }
    }

    # To get a list of all changed dependencies, convert the "changes" arrays
    # into a long string, then collapse that string into unique numbers in
    # a hash.
    my $all_changed_deps = join(', ', @{ $changes->{'dependson'} || [] });
    $all_changed_deps = join(', ', @{ $changes->{'blocked'} || [] },
                                   $all_changed_deps);
    my %changed_deps = map { $_ => 1 } split(', ', $all_changed_deps);
    # When clearning one field (say, blocks) and filling in the other
    # (say, dependson), an empty string can get into the hash and cause
    # an error later.
    delete $changed_deps{''};

1337
    foreach my $id (sort { $a <=> $b } (keys %changed_deps)) {
1338 1339 1340
        _send_bugmail({ forced => { changer => $user }, type => "dep",
                         id => $id }, $vars);
    }
1341 1342

    # Sending emails for the referenced bugs.
1343
    foreach my $ref_bug_id (uniq @{ $self->{see_also_changes} || [] }) {
1344
        _send_bugmail({ forced => { changer => $user },
1345
                        id => $ref_bug_id }, $vars);
1346
    }
1347 1348 1349 1350 1351
}

sub _send_bugmail {
    my ($params, $vars) = @_;

1352 1353
    require Bugzilla::BugMail;

1354
    my $results = 
1355
        Bugzilla::BugMail::Send($params->{'id'}, $params->{'forced'}, $params);
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365

    if (Bugzilla->usage_mode == USAGE_MODE_BROWSER) {
        my $template = Bugzilla->template;
        $vars->{$_} = $params->{$_} foreach keys %$params;
        $vars->{'sent_bugmail'} = $results;
        $template->process("bug/process/results.html.tmpl", $vars)
            || ThrowTemplateError($template->error());
        $vars->{'header_done'} = 1;
    }
}
1366

1367 1368 1369 1370 1371
#####################################################################
# Validators
#####################################################################

sub _check_alias {
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
    my ($invocant, $aliases) = @_;
    $aliases = ref $aliases ? $aliases : [split(/[\s,]+/, $aliases)];

    # Remove empty aliases
    @$aliases = grep { $_ } @$aliases;

    foreach my $alias (@$aliases) {
        $alias = trim($alias);

        # Make sure the alias isn't too long.
        if (length($alias) > 40) {
            ThrowUserError("alias_too_long");
        }
        # Make sure the alias isn't just a number.
        if ($alias =~ /^\d+$/) {
            ThrowUserError("alias_is_numeric", { alias => $alias });
        }
        # Make sure the alias has no commas or spaces.
        if ($alias =~ /[, ]/) {
            ThrowUserError("alias_has_comma_or_space", { alias => $alias });
        }
        # Make sure the alias is unique, or that it's already our alias.
        my $other_bug = new Bugzilla::Bug($alias);
        if (!$other_bug->{error}
            && (!ref $invocant || $other_bug->id != $invocant->id))
        {
            ThrowUserError("alias_in_use", { alias => $alias,
                                             bug_id => $other_bug->id });
        }
1401 1402
    }

1403
    return $aliases;
1404 1405 1406
}

sub _check_assigned_to {
1407
    my ($invocant, $assignee, undef, $params) = @_;
1408
    my $user = Bugzilla->user;
1409 1410
    my $component = blessed($invocant) ? $invocant->component_obj
                                       : $params->{component};
1411 1412 1413

    # Default assignee is the component owner.
    my $id;
1414 1415 1416 1417 1418
    # If this is a new bug, you can only set the assignee if you have editbugs.
    # If you didn't specify the assignee, we use the default assignee.
    if (!ref $invocant
        && (!$user->in_group('editbugs', $component->product_id) || !$assignee))
    {
1419 1420
        $id = $component->default_assignee->id;
    } else {
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
        if (!ref $assignee) {
            $assignee = trim($assignee);
            # When updating a bug, assigned_to can't be empty.
            ThrowUserError("reassign_to_empty") if ref $invocant && !$assignee;
            $assignee = Bugzilla::User->check($assignee);
        }
        $id = $assignee->id;
        # create() checks this another way, so we don't have to run this
        # check during create().
        $invocant->_check_strict_isolation_for_user($assignee) if ref $invocant;
1431 1432 1433 1434 1435
    }
    return $id;
}

sub _check_bug_file_loc {
1436
    my ($invocant, $url) = @_;
1437
    $url = '' if !defined($url);
1438
    $url = trim($url);
1439 1440 1441 1442 1443 1444
    # On bug entry, if bug_file_loc is "http://", the default, use an 
    # empty value instead. However, on bug editing people can set that
    # back if they *really* want to.
    if (!ref $invocant && $url eq 'http://') {
        $url = '';
    }
1445 1446 1447
    return $url;
}

1448
sub _check_bug_status {
1449
    my ($invocant, $new_status, undef, $params) = @_;
1450
    my $user = Bugzilla->user;
1451
    my @valid_statuses;
1452
    my $old_status; # Note that this is undef for new bugs.
1453

1454
    my ($product, $comment);
1455
    if (ref $invocant) {
1456
        @valid_statuses = @{$invocant->statuses_available};
1457
        $product = $invocant->product_obj;
1458 1459 1460
        $old_status = $invocant->status;
        my $comments = $invocant->{added_comments} || [];
        $comment = $comments->[-1];
1461
    }
1462
    else {
1463 1464
        $product = $params->{product};
        $comment = $params->{comment};
1465
        @valid_statuses = @{ Bugzilla::Bug->statuses_available($product) };
1466 1467
    }

1468 1469
    # Check permissions for users filing new bugs.
    if (!ref $invocant) {
1470 1471
        if ($user->in_group('editbugs', $product->id)
            || $user->in_group('canconfirm', $product->id)) {
1472 1473
            # If the user with privs hasn't selected another status,
            # select the first one of the list.
1474 1475 1476 1477 1478 1479 1480 1481 1482
            unless ($new_status) {
                if (scalar(@valid_statuses) == 1) {
                    $new_status = $valid_statuses[0];
                }
                else {
                    $new_status = ($valid_statuses[0]->name ne 'UNCONFIRMED') ?
                                  $valid_statuses[0] : $valid_statuses[1];
                }
            }
1483 1484
        }
        else {
1485
            # A user with no privs cannot choose the initial status.
1486 1487
            # If UNCONFIRMED is valid for this product, use it; else
            # use the first bug status available.
1488 1489 1490 1491 1492 1493
            if (grep {$_->name eq 'UNCONFIRMED'} @valid_statuses) {
                $new_status = 'UNCONFIRMED';
            }
            else {
                $new_status = $valid_statuses[0];
            }
1494
        }
1495
    }
1496

1497 1498
    # Time to validate the bug status.
    $new_status = Bugzilla::Status->check($new_status) unless ref($new_status);
1499 1500 1501 1502
    # We skip this check if we are changing from a status to itself.
    if ( (!$old_status || $old_status->id != $new_status->id)
          && !grep {$_->name eq $new_status->name} @valid_statuses) 
    {
1503 1504
        ThrowUserError('illegal_bug_status_transition',
                       { old => $old_status, new => $new_status });
1505
    }
1506

1507
    # Check if a comment is required for this change.
1508 1509
    if ($new_status->comment_required_on_change_from($old_status)
        && !$comment->{'thetext'})
1510
    {
1511
        ThrowUserError('comment_required',
1512 1513
          { old => $old_status ? $old_status->name : undef,
            new => $new_status->name, field => 'bug_status' });
1514 1515
    }
    
1516 1517 1518 1519
    if (ref $invocant 
        && ($new_status->name eq 'IN_PROGRESS'
            # Backwards-compat for the old default workflow.
            or $new_status->name eq 'ASSIGNED')
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
        && Bugzilla->params->{"usetargetmilestone"}
        && Bugzilla->params->{"musthavemilestoneonaccept"}
        # musthavemilestoneonaccept applies only if at least two
        # target milestones are defined for the product.
        && scalar(@{ $product->milestones }) > 1
        && $invocant->target_milestone eq $product->default_milestone)
    {
        ThrowUserError("milestone_required", { bug => $invocant });
    }

1530 1531 1532 1533 1534
    if (!blessed $invocant) {
        $params->{everconfirmed} = $new_status->name eq 'UNCONFIRMED' ? 0 : 1;
    }

    return $new_status->name;
1535 1536
}

1537
sub _check_cc {
1538 1539 1540
    my ($invocant, $ccs, undef, $params) = @_;
    my $component = blessed($invocant) ? $invocant->component_obj
                                       : $params->{component};
1541
    return [map {$_->id} @{$component->initial_cc}] unless $ccs;
1542

1543
    # Allow comma-separated input as well as arrayrefs.
1544
    $ccs = [split(/[,;]+/, $ccs)] if !ref $ccs;
1545

1546 1547
    my %cc_ids;
    foreach my $person (@$ccs) {
1548
        $person = trim($person);
1549 1550 1551 1552
        next unless $person;
        my $id = login_to_id($person, THROW_ERROR);
        $cc_ids{$id} = 1;
    }
1553 1554 1555 1556

    # Enforce Default CC
    $cc_ids{$_->id} = 1 foreach (@{$component->initial_cc});

1557 1558 1559
    return [keys %cc_ids];
}

1560
sub _check_comment {
1561
    my ($invocant, $comment_txt, undef, $params) = @_;
1562

1563 1564 1565 1566
    # Comment can be empty. We should force it to be empty if the text is undef
    if (!defined $comment_txt) {
        $comment_txt = '';
    }
1567

1568
    # Load up some data
1569
    my $isprivate = delete $params->{comment_is_private};
1570
    my $timestamp = $params->{creation_ts};
1571

1572 1573 1574 1575 1576
    # Create the new comment so we can check it
    my $comment = {
        thetext  => $comment_txt,
        bug_when => $timestamp,
    };
1577

1578 1579 1580 1581
    # We don't include the "isprivate" column unless it was specified. 
    # This allows it to fall back to its database default.
    if (defined $isprivate) {
        $comment->{isprivate} = $isprivate;
1582
    }
1583

1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
    # Validate comment. We have to do this special as a comment normally
    # requires a bug to be already created. For a new bug, the first comment
    # obviously can't get the bug if the bug is created after this
    # (see bug 590334)
    Bugzilla::Comment->check_required_create_fields($comment);
    $comment = Bugzilla::Comment->run_create_validators($comment,
                                                        { skip => ['bug_id'] }
    );

    return $comment; 
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
}

sub _check_commenton {
    my ($invocant, $new_value, $field, $params) = @_;

    my $has_comment =
        ref($invocant) ? $invocant->{added_comments}
                       : (defined $params->{comment}
                          and $params->{comment}->{thetext} ne '');

    my $is_changing = ref($invocant) ? $invocant->$field ne $new_value
                                     : $new_value ne '';
1606

1607 1608 1609 1610 1611
    if ($is_changing && !$has_comment) {
        my $old_value = ref($invocant) ? $invocant->$field : undef;
        ThrowUserError('comment_required',
            { field => $field, old => $old_value, new => $new_value });
    }
1612 1613
}

1614
sub _check_component {
1615
    my ($invocant, $name, undef, $params) = @_;
1616 1617
    $name = trim($name);
    $name || ThrowUserError("require_component");
1618 1619
    my $product = blessed($invocant) ? $invocant->product_obj 
                                     : $params->{product};
1620
    my $old_comp = blessed($invocant) ? $invocant->component : '';
1621 1622 1623 1624 1625
    my $object = Bugzilla::Component->check({ product => $product, name => $name });
    if ($object->name ne $old_comp && !$object->is_active) {
        ThrowUserError('value_inactive', { class => ref($object), value => $name });
    }
    return $object;
1626 1627
}

1628 1629 1630 1631
sub _check_creation_ts {
    return Bugzilla->dbh->selectrow_array('SELECT LOCALTIMESTAMP(0)');
}

1632
sub _check_deadline {
1633
    my ($invocant, $date) = @_;
1634 1635 1636 1637 1638 1639 1640 1641

    # When filing bugs, we're forgiving and just return undef if
    # the user isn't a timetracker. When updating bugs, check_can_change_field
    # controls permissions, so we don't want to check them here.
    if (!ref $invocant and !Bugzilla->user->is_timetracker) {
        return undef;
    }

1642 1643 1644
    # Validate entered deadline
    $date = trim($date);
    return undef if !$date;
1645 1646 1647 1648 1649 1650
    validate_date($date)
        || ThrowUserError('illegal_date', { date   => $date,
                                            format => 'YYYY-MM-DD' });
    return $date;
}

1651 1652 1653
# Takes two comma/space-separated strings and returns arrayrefs
# of valid bug IDs.
sub _check_dependencies {
1654 1655 1656
    my ($invocant, $value, $field, $params) = @_;

    return $value if $params->{_dependencies_validated};
1657 1658 1659

    if (!ref $invocant) {
        # Only editbugs users can set dependencies on bug entry.
1660 1661
        return ([], []) unless Bugzilla->user->in_group(
            'editbugs', $params->{product}->id);
1662 1663
    }

1664 1665 1666 1667 1668 1669 1670
    # This is done this way so that dependson and blocked can be in
    # VALIDATORS, meaning that they can be in VALIDATOR_DEPENDENCIES,
    # which means that they can be checked in the right order during
    # bug creation.
    my $opposite = $field eq 'dependson' ? 'blocked' : 'dependson';
    my %deps_in = ($field => $value || '',
                   $opposite => $params->{$opposite} || '');
1671

1672
    foreach my $type (qw(dependson blocked)) {
1673 1674 1675
        my @bug_ids = ref($deps_in{$type}) 
            ? @{$deps_in{$type}} 
            : split(/[\s,]+/, $deps_in{$type});
1676 1677
        # Eliminate nulls.
        @bug_ids = grep {$_} @bug_ids;
1678

1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
        my @check_access = @bug_ids;
        # When we're updating a bug, only added or removed bug_ids are 
        # checked for whether or not we can see/edit those bugs.
        if (ref $invocant) {
            my $old = $invocant->$type;
            my ($removed, $added) = diff_arrays($old, \@bug_ids);
            @check_access = (@$added, @$removed);
            
            # Check field permissions if we've changed anything.
            if (@check_access) {
                my $privs;
                if (!$invocant->check_can_change_field($type, 0, 1, \$privs)) {
                    ThrowUserError('illegal_change', { field => $type,
                                                       privs => $privs });
                }
            }
        }

        my $user = Bugzilla->user;
        foreach my $modified_id (@check_access) {
1699
            my $delta_bug = $invocant->check($modified_id);
1700 1701 1702 1703 1704 1705 1706 1707
            # Under strict isolation, you can't modify a bug if you can't
            # edit it, even if you can see it.
            if (Bugzilla->params->{"strict_isolation"}) {
                if (!$user->can_edit_product($delta_bug->{'product_id'})) {
                    ThrowUserError("illegal_change_deps", {field => $type});
                }
            }
        }
1708 1709
        # Replace all aliases by their corresponding bug ID.
        @bug_ids = map { $_ =~ /^(\d+)$/ ? $1 : $invocant->check($_, $type)->id } @bug_ids;
1710 1711
        $deps_in{$type} = \@bug_ids;
    }
1712

1713
    # And finally, check for dependency loops.
1714
    my $bug_id = ref($invocant) ? $invocant->id : 0;
1715 1716
    my %deps = ValidateDependencies($deps_in{dependson}, $deps_in{blocked},
                                    $bug_id);
1717

1718 1719 1720
    $params->{$opposite} = $deps{$opposite};
    $params->{_dependencies_validated} = 1;
    return $deps{$field};
1721 1722
}

1723 1724 1725
sub _check_dup_id {
    my ($self, $dupe_of) = @_;
    my $dbh = Bugzilla->dbh;
1726 1727 1728

    # Store the bug ID/alias passed by the user for visibility checks.
    my $orig_dupe_of = $dupe_of = trim($dupe_of);
1729
    $dupe_of || ThrowCodeError('undefined_field', { field => 'dup_id' });
1730 1731 1732
    # Validate the bug ID. The second argument will force check() to only
    # make sure that the bug exists, and convert the alias to the bug ID
    # if a string is passed. Group restrictions are checked below.
1733
    my $dupe_of_bug = $self->check($dupe_of, 'dup_id');
1734
    $dupe_of = $dupe_of_bug->id;
1735 1736 1737 1738 1739 1740

    # If the dupe is unchanged, we have nothing more to check.
    return $dupe_of if ($self->dup_id && $self->dup_id == $dupe_of);

    # If we come here, then the duplicate is new. We have to make sure
    # that we can view/change it (issue A on bug 96085).
1741
    $dupe_of_bug->check_is_visible($orig_dupe_of);
1742

1743 1744
    # Make sure a loop isn't created when marking this bug
    # as duplicate.
1745
   _resolve_ultimate_dup_id($self->id, $dupe_of, 1);
1746 1747 1748 1749 1750 1751 1752 1753 1754

    my $cur_dup = $self->dup_id || 0;
    if ($cur_dup != $dupe_of && Bugzilla->params->{'commentonduplicate'}
        && !$self->{added_comments})
    {
        ThrowUserError('comment_required');
    }

    # Should we add the reporter to the CC list of the new bug?
1755
    # If they can see the bug...
1756
    if ($self->reporter->can_see_bug($dupe_of)) {
1757
        # We only add them if they're not the reporter of the other bug.
1758 1759 1760 1761 1762 1763
        $self->{_add_dup_cc} = 1
            if $dupe_of_bug->reporter->id != $self->reporter->id;
    }
    # What if the reporter currently can't see the new bug? In the browser 
    # interface, we prompt the user. In other interfaces, we default to 
    # not adding the user, as the safest option.
1764
    elsif (Bugzilla->usage_mode == USAGE_MODE_BROWSER) {
1765 1766 1767 1768 1769 1770 1771
        # If we've already confirmed whether the user should be added...
        my $cgi = Bugzilla->cgi;
        my $add_confirmed = $cgi->param('confirm_add_duplicate');
        if (defined $add_confirmed) {
            $self->{_add_dup_cc} = $add_confirmed;
        }
        else {
1772 1773
            # Note that here we don't check if the user is already the reporter
            # of the dupe_of bug, since we already checked if they can *see*
1774 1775
            # the bug, above. People might have reporter_accessible turned
            # off, but cclist_accessible turned on, so they might want to
1776
            # add the reporter even though they're already the reporter of the
1777 1778 1779 1780
            # dup_of bug.
            my $vars = {};
            my $template = Bugzilla->template;
            # Ask the user what they want to do about the reporter.
1781
            $vars->{'cclist_accessible'} = $dupe_of_bug->cclist_accessible;
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
            $vars->{'original_bug_id'} = $dupe_of;
            $vars->{'duplicate_bug_id'} = $self->id;
            print $cgi->header();
            $template->process("bug/process/confirm-duplicate.html.tmpl", $vars)
              || ThrowTemplateError($template->error());
            exit;
        }
    }

    return $dupe_of;
}

1794
sub _check_groups {
1795
    my ($invocant, $group_names, undef, $params) = @_;
1796 1797

    my $bug_id = blessed($invocant) ? $invocant->id : undef;
1798 1799
    my $product = blessed($invocant) ? $invocant->product_obj 
                                     : $params->{product};
1800 1801
    my %add_groups;

1802 1803 1804 1805 1806 1807 1808
    # In email or WebServices, when the "groups" item actually 
    # isn't specified, then just add the default groups.
    if (!defined $group_names) {
        my $available = $product->groups_available;
        foreach my $group (@$available) {
            $add_groups{$group->id} = $group if $group->{is_default};
        }
1809
    }
1810 1811 1812 1813 1814 1815
    else {
        # Allow a comma-separated list, for email_in.pl.
        $group_names = [map { trim($_) } split(',', $group_names)]
            if !ref $group_names;

        # First check all the groups they chose to set.
1816
        my %args = ( product => $product->name, bug_id => $bug_id, action => 'add' );
1817
        foreach my $name (@$group_names) {
1818
            my $group = Bugzilla::Group->check_no_disclose({ %args, name => $name });
1819 1820

            if (!$product->group_is_settable($group)) {
1821
                ThrowUserError('group_restriction_not_allowed', { %args, name => $name });
1822
            }
1823
            $add_groups{$group->id} = $group;
1824 1825 1826
        }
    }

1827 1828 1829 1830
    # Now enforce mandatory groups.
    $add_groups{$_->id} = $_ foreach @{ $product->groups_mandatory };

    my @add_groups = values %add_groups;
1831 1832 1833
    return \@add_groups;
}

1834
sub _check_keywords {
1835 1836 1837 1838 1839 1840 1841 1842 1843
    my ($invocant, $keywords_in, undef, $params) = @_;

    return [] if !defined $keywords_in;

    my $keyword_array = $keywords_in;
    if (!ref $keyword_array) {
        $keywords_in = trim($keywords_in);
        $keyword_array = [split(/[\s,]+/, $keywords_in)];
    }
1844
 
1845
    my %keywords;
1846
    foreach my $keyword (@$keyword_array) {
1847
        next unless $keyword;
1848
        my $obj = Bugzilla::Keyword->check($keyword);
1849
        $keywords{$obj->id} = $obj;
1850
    }
1851
    return [values %keywords];
1852 1853
}

1854
sub _check_product {
1855
    my ($invocant, $name) = @_;
1856 1857 1858 1859 1860
    $name = trim($name);
    # If we're updating the bug and they haven't changed the product,
    # always allow it.
    if (ref $invocant && lc($invocant->product_obj->name) eq lc($name)) {
        return $invocant->product_obj;
1861
    }
1862 1863
    # Check that the product exists and that the user
    # is allowed to enter bugs into this product.
1864 1865
    my $product = Bugzilla->user->can_enter_product($name, THROW_ERROR);
    return $product;
1866 1867
}

1868
sub _check_priority {
1869
    my ($invocant, $priority) = @_;
1870
    if (!ref $invocant && !Bugzilla->params->{'letsubmitterchoosepriority'}) {
1871 1872
        $priority = Bugzilla->params->{'defaultpriority'};
    }
1873
    return $invocant->_check_select_field($priority, 'priority');
1874 1875
}

1876
sub _check_qa_contact {
1877
    my ($invocant, $qa_contact, undef, $params) = @_;
1878
    $qa_contact = trim($qa_contact) if !ref $qa_contact;
1879 1880
    my $component = blessed($invocant) ? $invocant->component_obj
                                       : $params->{component};
1881 1882 1883 1884 1885 1886 1887 1888
    if (!ref $invocant) {
        # Bugs get no QA Contact on creation if useqacontact is off.
        return undef if !Bugzilla->params->{useqacontact};
        # Set the default QA Contact if one isn't specified or if the
        # user doesn't have editbugs.
        if (!Bugzilla->user->in_group('editbugs', $component->product_id)
            || !$qa_contact)
        {
1889
            return $component->default_qa_contact ? $component->default_qa_contact->id : undef;
1890 1891
        }
    }
1892

1893 1894
    # If a QA Contact was specified or if we're updating, check
    # the QA Contact for validity.
1895 1896
    my $id;
    if ($qa_contact) {
1897 1898 1899 1900
        $qa_contact = Bugzilla::User->check($qa_contact) if !ref $qa_contact;
        $id = $qa_contact->id;
        # create() checks this another way, so we don't have to run this
        # check during create().
1901
        # If there is no QA contact, this check is not required.
1902
        $invocant->_check_strict_isolation_for_user($qa_contact)
1903
            if (ref $invocant && $id);
1904 1905 1906 1907 1908 1909
    }

    # "0" always means "undef", for QA Contact.
    return $id || undef;
}

1910 1911 1912 1913 1914 1915 1916 1917 1918
sub _check_reporter {
    my $invocant = shift;
    my $reporter;
    if (ref $invocant) {
        # You cannot change the reporter of a bug.
        $reporter = $invocant->reporter->id;
    }
    else {
        # On bug creation, the reporter is the logged in user
1919
        # (meaning that they must be logged in first!).
1920
        Bugzilla->login(LOGIN_REQUIRED);
1921 1922 1923 1924 1925
        $reporter = Bugzilla->user->id;
    }
    return $reporter;
}

1926
sub _check_resolution {
1927
    my ($invocant, $resolution, undef, $params) = @_;
1928
    $resolution = trim($resolution);
1929 1930 1931 1932
    my $status = ref($invocant) ? $invocant->status->name 
                                : $params->{bug_status};
    my $is_open = ref($invocant) ? $invocant->status->is_open 
                                 : is_open_state($status);
1933 1934 1935 1936
    
    # Throw a special error for resolving bugs without a resolution
    # (or trying to change the resolution to '' on a closed bug without
    # using clear_resolution).
1937 1938
    ThrowUserError('missing_resolution', { status => $status })
        if !$resolution && !$is_open;
1939 1940
    
    # Make sure this is a valid resolution.
1941
    $resolution = $invocant->_check_select_field($resolution, 'resolution');
1942 1943

    # Don't allow open bugs to have resolutions.
1944
    ThrowUserError('resolution_not_allowed') if $is_open;
1945 1946
    
    # Check noresolveonopenblockers.
1947 1948
    my $dependson = ref($invocant) ? $invocant->dependson
                                   : ($params->{dependson} || []);
1949 1950
    if (Bugzilla->params->{"noresolveonopenblockers"}
        && $resolution eq 'FIXED'
1951 1952 1953
        && (!ref $invocant or !$invocant->resolution 
            or $resolution ne $invocant->resolution)
        && scalar @$dependson)
1954
    {
1955
        my $dep_bugs = Bugzilla::Bug->new_from_list($dependson);
1956 1957
        my $count_open = grep { $_->isopened } @$dep_bugs;
        if ($count_open) {
1958
            my $bug_id = ref($invocant) ? $invocant->id : undef;
1959
            ThrowUserError("still_unresolved_bugs",
1960
                           { bug_id => $bug_id, dep_count => $count_open });
1961 1962 1963 1964
        }
    }

    # Check if they're changing the resolution and need to comment.
1965 1966
    if (Bugzilla->params->{'commentonchange_resolution'}) {
        $invocant->_check_commenton($resolution, 'resolution', $params);
1967 1968
    }
    
1969 1970 1971
    return $resolution;
}

1972
sub _check_short_desc {
1973
    my ($invocant, $short_desc) = @_;
1974 1975 1976 1977 1978 1979
    # Set the parameter to itself, but cleaned up
    $short_desc = clean_text($short_desc) if $short_desc;

    if (!defined $short_desc || $short_desc eq '') {
        ThrowUserError("require_summary");
    }
1980 1981 1982 1983
    if (length($short_desc) > MAX_FREETEXT_LENGTH) {
        ThrowUserError('freetext_too_long', 
                       { field => 'short_desc', text => $short_desc });
    }
1984 1985 1986
    return $short_desc;
}

1987
sub _check_status_whiteboard { return defined $_[1] ? $_[1] : ''; }
1988

1989 1990
# Unlike other checkers, this one doesn't return anything.
sub _check_strict_isolation {
1991
    my ($invocant, $ccs, $assignee, $qa_contact, $product) = @_;
1992 1993
    return unless Bugzilla->params->{'strict_isolation'};

1994 1995 1996 1997 1998 1999 2000 2001 2002
    if (ref $invocant) {
        my $original = $invocant->new($invocant->id);

        # We only check people if they've been added. This way, if
        # strict_isolation is turned on when there are invalid users
        # on bugs, people can still add comments and so on.
        my @old_cc = map { $_->id } @{$original->cc_users};
        my @new_cc = map { $_->id } @{$invocant->cc_users};
        my ($removed, $added) = diff_arrays(\@old_cc, \@new_cc);
2003 2004
        $ccs = Bugzilla::User->new_from_list($added);

2005 2006
        $assignee = $invocant->assigned_to
            if $invocant->assigned_to->id != $original->assigned_to->id;
2007 2008 2009 2010 2011 2012
        if ($invocant->qa_contact
            && (!$original->qa_contact
                || $invocant->qa_contact->id != $original->qa_contact->id))
        {
            $qa_contact = $invocant->qa_contact;
        }
2013
        $product = $invocant->product_obj;
2014 2015 2016 2017
    }

    my @related_users = @$ccs;
    push(@related_users, $assignee) if $assignee;
2018

2019 2020
    if (Bugzilla->params->{'useqacontact'} && $qa_contact) {
        push(@related_users, $qa_contact);
2021 2022
    }

2023 2024 2025
    @related_users = @{Bugzilla::User->new_from_list(\@related_users)}
        if !ref $invocant;

2026 2027
    # For each unique user in @related_users...(assignee and qa_contact
    # could be duplicates of users in the CC list)
2028
    my %unique_users = map {$_->id => $_} @related_users;
2029
    my @blocked_users;
2030 2031
    foreach my $id (keys %unique_users) {
        my $related_user = $unique_users{$id};
2032
        if (!$related_user->can_edit_product($product->id) ||
2033
            !$related_user->can_see_product($product->name)) {
2034 2035 2036 2037
            push (@blocked_users, $related_user->login);
        }
    }
    if (scalar(@blocked_users)) {
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
        my %vars = ( users   => \@blocked_users,
                     product => $product->name );
        if (ref $invocant) {
            $vars{'bug_id'} = $invocant->id;
        }
        else {
            $vars{'new'} = 1;
        }
        ThrowUserError("invalid_user_group", \%vars);
    }
}

# This is used by various set_ checkers, to make their code simpler.
sub _check_strict_isolation_for_user {
    my ($self, $user) = @_;
    return unless Bugzilla->params->{"strict_isolation"};
    if (!$user->can_edit_product($self->{product_id})) {
        ThrowUserError('invalid_user_group',
                       { users   => $user->login,
                         product => $self->product,
                         bug_id  => $self->id });
2059 2060 2061
    }
}

2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
sub _check_tag_name {
    my ($invocant, $tag) = @_;

    $tag = clean_text($tag);
    $tag || ThrowUserError('no_tag_to_edit');
    ThrowUserError('tag_name_too_long') if length($tag) > MAX_LEN_QUERY_NAME;
    trick_taint($tag);
    # Tags are all lowercase.
    return lc($tag);
}

2073
sub _check_target_milestone {
2074 2075 2076
    my ($invocant, $target, undef, $params) = @_;
    my $product = blessed($invocant) ? $invocant->product_obj 
                                     : $params->{product};
2077
    my $old_target = blessed($invocant) ? $invocant->target_milestone : '';
2078 2079
    $target = trim($target);
    $target = $product->default_milestone if !defined $target;
2080 2081
    my $object = Bugzilla::Milestone->check(
        { product => $product, name => $target });
2082
    if ($old_target && $object->name ne $old_target && !$object->is_active) {
2083 2084
        ThrowUserError('value_inactive', { class => ref($object),  value => $target });
    }
2085
    return $object->name;
2086 2087
}

2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
sub _check_time_field {
    my ($invocant, $value, $field, $params) = @_;

    # When filing bugs, we're forgiving and just return 0 if
    # the user isn't a timetracker. When updating bugs, check_can_change_field
    # controls permissions, so we don't want to check them here.
    if (!ref $invocant and !Bugzilla->user->is_timetracker) {
        return 0;
    }

    # check_time is in Bugzilla::Object.
    return $invocant->check_time($value, $field, $params);
}

2102
sub _check_version {
2103
    my ($invocant, $version, undef, $params) = @_;
2104
    $version = trim($version);
2105 2106
    my $product = blessed($invocant) ? $invocant->product_obj 
                                     : $params->{product};
2107
    my $old_vers = blessed($invocant) ? $invocant->version : '';
2108 2109 2110 2111
    my $object = Bugzilla::Version->check({ product => $product, name => $version });
    if ($object->name ne $old_vers && !$object->is_active) {
        ThrowUserError('value_inactive', { class => ref($object), value => $version });
    }
2112
    return $object->name;
2113 2114
}

2115 2116
# Custom Field Validators

2117 2118 2119 2120
sub _check_field_is_mandatory {
    my ($invocant, $value, $field, $params) = @_;

    if (!blessed($field)) {
2121 2122
        $field = Bugzilla::Field->new({ name => $field });
        return if !$field;
2123 2124 2125 2126 2127 2128
    }

    return if !$field->is_mandatory;

    return if !$field->is_visible_on_bug($params || $invocant);

2129 2130 2131 2132 2133 2134
    return if ($field->type == FIELD_TYPE_SINGLE_SELECT
                 && scalar @{ get_legal_field_values($field->name) } == 1);

    return if ($field->type == FIELD_TYPE_MULTI_SELECT
                 && !scalar @{ get_legal_field_values($field->name) });

2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
    if (ref($value) eq 'ARRAY') {
        $value = join('', @$value);
    }

    $value = trim($value);
    if (!defined($value)
        or $value eq ""
        or ($value eq '---' and $field->type == FIELD_TYPE_SINGLE_SELECT)
        or ($value =~ EMPTY_DATETIME_REGEX
            and $field->type == FIELD_TYPE_DATETIME))
    {
        ThrowUserError('required_field', { field => $field });
    }
}

2150 2151
sub _check_date_field {
    my ($invocant, $date) = @_;
2152
    return $invocant->_check_datetime_field($date, undef, {date_only => 1});
2153 2154
}

2155
sub _check_datetime_field {
2156
    my ($invocant, $date_time, $field, $params) = @_;
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169

    # Empty datetimes are empty strings or strings only containing
    # 0's, whitespace, and punctuation.
    if ($date_time =~ /^[\s0[:punct:]]*$/) {
        return undef;
    }

    $date_time = trim($date_time);
    my ($date, $time) = split(' ', $date_time);
    if ($date && !validate_date($date)) {
        ThrowUserError('illegal_date', { date   => $date,
                                         format => 'YYYY-MM-DD' });
    }
2170
    if ($time && $params->{date_only}) {
2171 2172 2173
        ThrowUserError('illegal_date', { date   => $date_time,
                                         format => 'YYYY-MM-DD' });
    }
2174 2175 2176 2177 2178 2179 2180
    if ($time && !validate_time($time)) {
        ThrowUserError('illegal_time', { 'time' => $time,
                                         format => 'HH:MM:SS' });
    }
    return $date_time
}

2181 2182 2183
sub _check_default_field { return defined $_[1] ? trim($_[1]) : ''; }

sub _check_freetext_field {
2184
    my ($invocant, $text, $field) = @_;
2185 2186 2187

    $text = (defined $text) ? trim($text) : '';
    if (length($text) > MAX_FREETEXT_LENGTH) {
2188 2189
        ThrowUserError('freetext_too_long', 
                       { field => $field, text => $text });
2190 2191 2192 2193
    }
    return $text;
}

2194 2195
sub _check_multi_select_field {
    my ($invocant, $values, $field) = @_;
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206

    # Allow users (mostly email_in.pl) to specify multi-selects as
    # comma-separated values.
    if (defined $values and !ref $values) {
        # We don't split on spaces because multi-select values can and often
        # do have spaces in them. (Theoretically they can have commas in them
        # too, but that's much less common and people should be able to work
        # around it pretty cleanly, if they want to use email_in.pl.)
        $values = [split(',', $values)];
    }

2207
    return [] if !$values;
2208
    my @checked_values;
2209
    foreach my $value (@$values) {
2210
        push(@checked_values, $invocant->_check_select_field($value, $field));
2211
    }
2212
    return \@checked_values;
2213 2214
}

2215 2216
sub _check_select_field {
    my ($invocant, $value, $field) = @_;
2217 2218
    my $object = Bugzilla::Field::Choice->type($field)->check($value);
    return $object->name;
2219
}
2220

2221 2222 2223
sub _check_bugid_field {
    my ($invocant, $value, $field) = @_;
    return undef if !$value;
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
    
    # check that the value is a valid, visible bug id
    my $checked_id = $invocant->check($value, $field)->id;
    
    # check for loop (can't have a loop if this is a new bug)
    if (ref $invocant) {
        _check_relationship_loop($field, $invocant->bug_id, $checked_id);
    }

    return $checked_id;
}

2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
sub _check_textarea_field {
    my ($invocant, $text, $field) = @_;

    $text = (defined $text) ? trim($text) : '';

    # Web browsers submit newlines as \r\n.
    # Sanitize all input to match the web standard.
    # XMLRPC input could be either \n or \r\n
    $text =~ s/\r?\n/\r\n/g;

    return $text;
}

2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
sub _check_integer_field {
    my ($invocant, $value, $field) = @_;
    $value = defined($value) ? trim($value) : '';

    if ($value eq '') {
        return 0;
    }

    my $orig_value = $value;
    if (!detaint_signed($value)) {
        ThrowUserError("number_not_integer",
                       {field => $field, num => $orig_value});
    }
2262
    elsif (abs($value) > MAX_INT_32) {
2263 2264 2265 2266 2267 2268 2269
        ThrowUserError("number_too_large",
                       {field => $field, num => $orig_value, max_num => MAX_INT_32});
    }

    return $value;
}

2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293
sub _check_relationship_loop {
    # Generates a dependency tree for a given bug.  Calls itself recursively
    # to generate sub-trees for the bug's dependencies.
    my ($field, $bug_id, $dep_id, $ids) = @_;

    # Don't do anything if this bug doesn't have any dependencies.
    return unless defined($dep_id);

    # Check whether we have seen this bug yet
    $ids = {} unless defined $ids;
    $ids->{$bug_id} = 1;
    if ($ids->{$dep_id}) {
        ThrowUserError("relationship_loop_single", {
            'bug_id' => $bug_id,
            'dep_id' => $dep_id,
            'field_name' => $field});
    }
    
    # Get this dependency's record from the database
    my $dbh = Bugzilla->dbh;
    my $next_dep_id = $dbh->selectrow_array(
        "SELECT $field FROM bugs WHERE bug_id = ?", undef, $dep_id);

    _check_relationship_loop($field, $dep_id, $next_dep_id, $ids);
2294 2295
}

2296
#####################################################################
2297 2298 2299 2300 2301 2302
# Class Accessors
#####################################################################

sub fields {
    my $class = shift;

2303 2304
   my @fields =
   (
2305 2306 2307 2308 2309 2310
        # Standard Fields
        # Keep this ordering in sync with bugzilla.dtd.
        qw(bug_id alias creation_ts short_desc delta_ts
           reporter_accessible cclist_accessible
           classification_id classification
           product component version rep_platform op_sys
2311
           bug_status resolution dup_id see_also
2312 2313
           bug_file_loc status_whiteboard keywords
           priority bug_severity target_milestone
2314
           dependson blocked everconfirmed
2315 2316 2317
           reporter assigned_to cc estimated_time
           remaining_time actual_time deadline),

2318
        # Conditional Fields
2319
        Bugzilla->params->{'useqacontact'} ? "qa_contact" : (),
2320
        # Custom Fields
2321
        map { $_->name } Bugzilla->active_custom_fields
2322
    );
2323
    Bugzilla::Hook::process('bug_fields', {'fields' => \@fields} );
2324 2325
    
    return @fields;
2326 2327
}

2328 2329 2330 2331
#####################################################################
# Mutators 
#####################################################################

2332 2333 2334
# To run check_can_change_field.
sub _set_global_validator {
    my ($self, $value, $field) = @_;
2335
    my $current = $self->$field;
2336
    my $privs;
2337 2338 2339 2340 2341 2342 2343 2344 2345

    if (ref $current && ref($current) ne 'ARRAY'
        && $current->isa('Bugzilla::Object')) {
        $current = $current->id ;
    }
    if (ref $value && ref($value) ne 'ARRAY'
        && $value->isa('Bugzilla::Object')) {
        $value = $value->id ;
    }
2346 2347 2348
    my $can = $self->check_can_change_field($field, $current, $value, \$privs);
    if (!$can) {
        if ($field eq 'assigned_to' || $field eq 'qa_contact') {
2349 2350
            $value   = Bugzilla::User->new($value)->login;
            $current = Bugzilla::User->new($current)->login;
2351 2352 2353 2354 2355 2356
        }
        ThrowUserError('illegal_change', { field    => $field,
                                           oldvalue => $current,
                                           newvalue => $value,
                                           privs    => $privs });
    }
2357
    $self->_check_field_is_mandatory($value, $field);
2358 2359 2360
}


2361 2362 2363 2364
#################
# "Set" Methods #
#################

2365 2366
# Note that if you are changing multiple bugs at once, you must pass
# other_bugs to set_all in order for it to behave properly.
2367 2368
sub set_all {
    my $self = shift;
2369 2370 2371 2372 2373 2374 2375
    my ($input_params) = @_;
    
    # Clone the data as we are going to alter it, and this would affect
    # subsequent bugs when calling set_all() again, as some fields would
    # be modified or no longer defined.
    my $params = {};
    %$params = %$input_params;
2376

2377 2378 2379 2380 2381 2382 2383 2384 2385
    # You cannot mark bugs as duplicate when changing several bugs at once
    # (because currently there is no way to check for duplicate loops in that
    # situation). You also cannot set the alias of several bugs at once.
    if ($params->{other_bugs} and scalar @{ $params->{other_bugs} } > 1) {
        ThrowUserError('dupe_not_allowed') if exists $params->{dup_id};
        ThrowUserError('multiple_alias_not_allowed') 
            if defined $params->{alias};
    }

2386 2387 2388 2389 2390 2391 2392
    # For security purposes, and because lots of other checks depend on it,
    # we set the product first before anything else.
    my $product_changed; # Used only for strict_isolation checks.
    if (exists $params->{'product'}) {
        $product_changed = $self->_set_product($params->{'product'}, $params);
    }

2393 2394
    # strict_isolation checks mean that we should set the groups
    # immediately after changing the product.
2395
    $self->_add_remove($params, 'groups');
2396

2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426
    if (exists $params->{'dependson'} or exists $params->{'blocked'}) {
        my %set_deps;
        foreach my $name (qw(dependson blocked)) {
            my @dep_ids = @{ $self->$name };
            # If only one of the two fields was passed in, then we need to
            # retain the current value for the other one.
            if (!exists $params->{$name}) {
                $set_deps{$name} = \@dep_ids;
                next;
            }

            # Explicitly setting them to a particular value overrides
            # add/remove.
            if (exists $params->{$name}->{set}) {
                $set_deps{$name} = $params->{$name}->{set};
                next;
            }

            foreach my $add (@{ $params->{$name}->{add} || [] }) {
                push(@dep_ids, $add) if !grep($_ == $add, @dep_ids);
            }
            foreach my $remove (@{ $params->{$name}->{remove} || [] }) {
                @dep_ids = grep($_ != $remove, @dep_ids);
            }
            $set_deps{$name} = \@dep_ids;
        }

        $self->set_dependencies($set_deps{'dependson'}, $set_deps{'blocked'});
    }

2427
    if (exists $params->{'keywords'}) {
2428 2429 2430 2431 2432
        # Sorting makes the order "add, remove, set", just like for other
        # fields.
        foreach my $action (sort keys %{ $params->{'keywords'} }) {
            $self->modify_keywords($params->{'keywords'}->{$action}, $action);
        }
2433 2434
    }

2435 2436 2437 2438 2439
    if (exists $params->{'comment'} or exists $params->{'work_time'}) {
        # Add a comment as needed to each bug. This is done early because
        # there are lots of things that want to check if we added a comment.
        $self->add_comment($params->{'comment'}->{'body'},
            { isprivate => $params->{'comment'}->{'is_private'},
2440
              work_time => $params->{'work_time'} });
2441 2442
    }

2443
    if (exists $params->{alias} && $params->{alias}{set}) {
2444 2445
        my ($removed_aliases, $added_aliases) = diff_arrays(
            $self->alias, $params->{alias}{set});
2446
        $params->{alias} = {
2447 2448
            add    => $added_aliases,
            remove => $removed_aliases,
2449 2450 2451
        };
    }

2452 2453
    my %normal_set_all;
    foreach my $name (keys %$params) {
2454
        # These are handled separately below.
2455 2456 2457 2458 2459
        if ($self->can("set_$name")) {
            $normal_set_all{$name} = $params->{$name};
        }
    }
    $self->SUPER::set_all(\%normal_set_all);
2460 2461 2462 2463

    $self->reset_assigned_to if $params->{'reset_assigned_to'};
    $self->reset_qa_contact  if $params->{'reset_qa_contact'};

2464
    $self->_add_remove($params, 'see_also');
2465 2466 2467 2468 2469 2470 2471 2472 2473

    # And set custom fields.
    my @custom_fields = Bugzilla->active_custom_fields;
    foreach my $field (@custom_fields) {
        my $fname = $field->name;
        if (exists $params->{$fname}) {
            $self->set_custom_field($field, $params->{$fname});
        }
    }
2474 2475

    $self->_add_remove($params, 'cc');
2476
    $self->_add_remove($params, 'alias');
2477 2478 2479 2480 2481 2482

    # 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, because if they *did* change the assignee, qa, or CC,
2483
    # then we don't want to check the original ones, only the new ones.
2484
    $self->_check_strict_isolation() if $product_changed;
2485 2486 2487 2488 2489 2490 2491 2492
}

# Helper for set_all that helps with fields that have an "add/remove"
# pattern instead of a "set_" pattern.
sub _add_remove {
    my ($self, $params, $name) = @_;
    my @add    = @{ $params->{$name}->{add}    || [] };
    my @remove = @{ $params->{$name}->{remove} || [] };
2493
    $name =~ s/s$// if $name ne 'alias';
2494 2495 2496 2497
    my $add_method = "add_$name";
    my $remove_method = "remove_$name";
    $self->$add_method($_) foreach @add;
    $self->$remove_method($_) foreach @remove;
2498 2499
}

2500 2501 2502
sub set_assigned_to {
    my ($self, $value) = @_;
    $self->set('assigned_to', $value);
2503 2504
    # Store the old assignee. check_can_change_field() needs it.
    $self->{'_old_assigned_to'} = $self->{'assigned_to_obj'}->id;
2505 2506 2507 2508 2509 2510 2511
    delete $self->{'assigned_to_obj'};
}
sub reset_assigned_to {
    my $self = shift;
    my $comp = $self->component_obj;
    $self->set_assigned_to($comp->default_assignee);
}
2512
sub set_bug_ignored       { $_[0]->set('bug_ignored',       $_[1]); }
2513
sub set_cclist_accessible { $_[0]->set('cclist_accessible', $_[1]); }
2514

2515
sub set_comment_is_private {
2516 2517 2518 2519 2520
    my ($self, $comments, $isprivate) = @_;
    $self->{comment_isprivate} ||= [];
    my $is_insider = Bugzilla->user->is_insider;

    $comments = { $comments => $isprivate } unless ref $comments;
2521

2522 2523 2524 2525 2526 2527 2528 2529 2530
    foreach my $comment (@{$self->comments}) {
        # Skip unmodified comment privacy.
        next unless exists $comments->{$comment->id};

        my $isprivate = delete $comments->{$comment->id} ? 1 : 0;
        if ($isprivate != $comment->is_private) {
            ThrowUserError('user_not_insider') unless $is_insider;
            $comment->set_is_private($isprivate);
            push @{$self->{comment_isprivate}}, $comment;
2531 2532 2533
        }
    }

2534 2535 2536
    # If there are still entries in $comments, then they are illegal.
    ThrowUserError('comment_invalid_isprivate', { id => join(', ', keys %$comments) })
      if scalar keys %$comments;
2537

2538 2539
    # If no comment privacy has been modified, remove this key.
    delete $self->{comment_isprivate} unless scalar @{$self->{comment_isprivate}};
2540
}
2541

2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
sub set_component  {
    my ($self, $name) = @_;
    my $old_comp  = $self->component_obj;
    my $component = $self->_check_component($name);
    if ($old_comp->id != $component->id) {
        $self->{component_id}  = $component->id;
        $self->{component}     = $component->name;
        $self->{component_obj} = $component;
        # For update()
        $self->{_old_component_name} = $old_comp->name;
        # Add in the Default CC of the new Component;
        foreach my $cc (@{$component->initial_cc}) {
            $self->add_cc($cc);
        }
    }
}
2558 2559
sub set_custom_field {
    my ($self, $field, $value) = @_;
2560

2561
    if (ref $value eq 'ARRAY' && $field->type != FIELD_TYPE_MULTI_SELECT) {
2562 2563
        $value = $value->[0];
    }
2564 2565 2566
    ThrowCodeError('field_not_custom', { field => $field }) if !$field->custom;
    $self->set($field->name, $value);
}
2567
sub set_deadline { $_[0]->set('deadline', $_[1]); }
2568 2569
sub set_dependencies {
    my ($self, $dependson, $blocked) = @_;
2570 2571 2572
    my %extra = ( blocked => $blocked );
    $dependson = $self->_check_dependencies($dependson, 'dependson', \%extra);
    $blocked = $extra{blocked};
2573 2574 2575 2576 2577 2578
    # These may already be detainted, but all setters are supposed to
    # detaint their input if they've run a validator (just as though
    # we had used Bugzilla::Object::set), so we do that here.
    detaint_natural($_) foreach (@$dependson, @$blocked);
    $self->{'dependson'} = $dependson;
    $self->{'blocked'}   = $blocked;
2579 2580
    delete $self->{depends_on_obj};
    delete $self->{blocks_obj};
2581
}
2582 2583 2584 2585 2586
sub _clear_dup_id { $_[0]->{dup_id} = undef; }
sub set_dup_id {
    my ($self, $dup_id) = @_;
    my $old = $self->dup_id || 0;
    $self->set('dup_id', $dup_id);
2587
    my $new = $self->dup_id;
2588
    return if $old == $new;
2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603

    # Make sure that we have the DUPLICATE resolution. This is needed
    # if somebody calls set_dup_id without calling set_bug_status or
    # set_resolution.
    if ($self->resolution ne 'DUPLICATE') {
        # Even if the current status is VERIFIED, we change it back to
        # RESOLVED (or whatever the duplicate_or_move_bug_status is) here,
        # because that's the same thing the UI does when you click on the
        # "Mark as Duplicate" link. If people really want to retain their
        # current status, they can use set_bug_status and set the DUPLICATE
        # resolution before getting here.
        $self->set_bug_status(
            Bugzilla->params->{'duplicate_or_move_bug_status'},
            { resolution => 'DUPLICATE' });
    }
2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628
    
    # Update the other bug.
    my $dupe_of = new Bugzilla::Bug($self->dup_id);
    if (delete $self->{_add_dup_cc}) {
        $dupe_of->add_cc($self->reporter);
    }
    $dupe_of->add_comment("", { type       => CMT_HAS_DUPE,
                                extra_data => $self->id });
    $self->{_dup_for_update} = $dupe_of;
    
    # Now make sure that we add a duplicate comment on *this* bug.
    # (Change an existing comment into a dup comment, if there is one,
    # or add an empty dup comment.)
    if ($self->{added_comments}) {
        my @normal = grep { !defined $_->{type} || $_->{type} == CMT_NORMAL }
                          @{ $self->{added_comments} };
        # Turn the last one into a dup comment.
        $normal[-1]->{type} = CMT_DUPE_OF;
        $normal[-1]->{extra_data} = $self->dup_id;
    }
    else {
        $self->add_comment('', { type       => CMT_DUPE_OF,
                                 extra_data => $self->dup_id });
    }
}
2629
sub set_estimated_time { $_[0]->set('estimated_time', $_[1]); }
2630
sub _set_everconfirmed { $_[0]->set('everconfirmed', $_[1]); }
2631 2632 2633 2634 2635
sub set_flags {
    my ($self, $flags, $new_flags) = @_;

    Bugzilla::Flag->set_flag($self, $_) foreach (@$flags, @$new_flags);
}
2636 2637 2638
sub set_op_sys         { $_[0]->set('op_sys',        $_[1]); }
sub set_platform       { $_[0]->set('rep_platform',  $_[1]); }
sub set_priority       { $_[0]->set('priority',      $_[1]); }
2639 2640 2641
# For security reasons, you have to use set_all to change the product.
# See the strict_isolation check in set_all for an explanation.
sub _set_product {
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
    my ($self, $name, $params) = @_;
    my $old_product = $self->product_obj;
    my $product = $self->_check_product($name);
    
    my $product_changed = 0;
    if ($old_product->id != $product->id) {
        $self->{product_id}  = $product->id;
        $self->{product}     = $product->name;
        $self->{product_obj} = $product;
        # For update()
        $self->{_old_product_name} = $old_product->name;
        # Delete fields that depend upon the old Product value.
        delete $self->{choices};
        $product_changed = 1;
    }

    $params ||= {};
2659 2660 2661 2662
    # We delete these so that they're not set again later in set_all.
    my $comp_name = delete $params->{component} || $self->component;
    my $vers_name = delete $params->{version}   || $self->version;
    my $tm_name   = delete $params->{target_milestone};
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679
    # This way, if usetargetmilestone is off and we've changed products,
    # set_target_milestone will reset our target_milestone to
    # $product->default_milestone. But if we haven't changed products,
    # we don't reset anything.
    if (!defined $tm_name
        && (Bugzilla->params->{'usetargetmilestone'} || !$product_changed))
    {
        $tm_name = $self->target_milestone;
    }

    if ($product_changed && Bugzilla->usage_mode == USAGE_MODE_BROWSER) {
        # Try to set each value with the new product.
        # Have to set error_mode because Throw*Error calls exit() otherwise.
        my $old_error_mode = Bugzilla->error_mode;
        Bugzilla->error_mode(ERROR_MODE_DIE);
        my $component_ok = eval { $self->set_component($comp_name);      1; };
        my $version_ok   = eval { $self->set_version($vers_name);        1; };
2680 2681 2682 2683 2684 2685 2686 2687 2688
        my $milestone_ok = 1;
        # Reporters can move bugs between products but not set the TM.
        if ($self->check_can_change_field('target_milestone', 0, 1)) {
            $milestone_ok = eval { $self->set_target_milestone($tm_name); 1; };
        }
        else {
            # Have to set this directly to bypass the validators.
            $self->{target_milestone} = $product->default_milestone;
        }
2689 2690 2691 2692 2693
        # If there were any errors thrown, make sure we don't mess up any
        # other part of Bugzilla that checks $@.
        undef $@;
        Bugzilla->error_mode($old_error_mode);
        
2694
        my $verified = $params->{product_change_confirmed};
2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705
        my %vars;
        if (!$verified || !$component_ok || !$version_ok || !$milestone_ok) {
            $vars{defaults} = {
                # Note that because of the eval { set } above, these are
                # already set correctly if they're valid, otherwise they're
                # set to some invalid value which the template will ignore.
                component => $self->component,
                version   => $self->version,
                milestone => $milestone_ok ? $self->target_milestone
                                           : $product->default_milestone
            };
2706 2707 2708
            $vars{components} = [map { $_->name } grep($_->is_active, @{$product->components})];
            $vars{milestones} = [map { $_->name } grep($_->is_active, @{$product->milestones})];
            $vars{versions}   = [map { $_->name } grep($_->is_active, @{$product->versions})];
2709 2710 2711 2712 2713 2714 2715 2716
        }

        if (!$verified) {
            $vars{verify_bug_groups} = 1;
            my $dbh = Bugzilla->dbh;
            my @idlist = ($self->id);
            push(@idlist, map {$_->id} @{ $params->{other_bugs} })
                if $params->{other_bugs};
2717
            @idlist = uniq @idlist;
2718 2719 2720 2721
            # Get the ID of groups which are no longer valid in the new product.
            my $gids = $dbh->selectcol_arrayref(
                'SELECT bgm.group_id
                   FROM bug_group_map AS bgm
2722
                  WHERE bgm.bug_id IN (' . join(',', ('?') x @idlist) . ')
2723 2724 2725 2726 2727 2728 2729 2730 2731
                    AND bgm.group_id NOT IN
                        (SELECT gcm.group_id
                           FROM group_control_map AS gcm
                           WHERE gcm.product_id = ?
                                 AND ( (gcm.membercontrol != ?
                                        AND gcm.group_id IN ('
                                        . Bugzilla->user->groups_as_string . '))
                                       OR gcm.othercontrol != ?) )',
                undef, (@idlist, $product->id, CONTROLMAPNA, CONTROLMAPNA));
2732
            $vars{'old_groups'} = Bugzilla::Group->new_from_list($gids);
2733 2734 2735

            # Did we come here from editing multiple bugs? (affects how we
            # show optional group changes)
2736
            $vars{multiple_bugs} = (@idlist > 1) ? 1 : 0;
2737
        }
2738

2739 2740
        if (%vars) {
            $vars{product} = $product;
2741
            $vars{bug} = $self;
2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752
            my $template = Bugzilla->template;
            $template->process("bug/process/verify-new-product.html.tmpl",
                \%vars) || ThrowTemplateError($template->error());
            exit;
        }
    }
    else {
        # When we're not in the browser (or we didn't change the product), we
        # just die if any of these are invalid.
        $self->set_component($comp_name);
        $self->set_version($vers_name);
2753 2754 2755
        if ($product_changed 
            and !$self->check_can_change_field('target_milestone', 0, 1)) 
        {
2756 2757 2758
            # Have to set this directly to bypass the validators.
            $self->{target_milestone} = $product->default_milestone;
        }
2759 2760 2761
        else {
            $self->set_target_milestone($tm_name);
        }
2762
    }
2763

2764
    if ($product_changed) {
2765
        # Remove groups that can't be set in the new product.
2766 2767 2768 2769
        # We copy this array because the original array is modified while we're
        # working, and that confuses "foreach".
        my @current_groups = @{$self->groups_in};
        foreach my $group (@current_groups) {
2770
            if (!$product->group_is_valid($group)) {
2771 2772 2773
                $self->remove_group($group);
            }
        }
2774

2775
        # Make sure the bug is in all the mandatory groups for the new product.
2776
        foreach my $group (@{$product->groups_mandatory}) {
2777 2778 2779 2780
            $self->add_group($group);
        }
    }
    
2781 2782 2783
    return $product_changed;
}

2784 2785 2786
sub set_qa_contact {
    my ($self, $value) = @_;
    $self->set('qa_contact', $value);
2787 2788 2789 2790
    # Store the old QA contact. check_can_change_field() needs it.
    if ($self->{'qa_contact_obj'}) {
        $self->{'_old_qa_contact'} = $self->{'qa_contact_obj'}->id;
    }
2791 2792 2793 2794 2795 2796 2797
    delete $self->{'qa_contact_obj'};
}
sub reset_qa_contact {
    my $self = shift;
    my $comp = $self->component_obj;
    $self->set_qa_contact($comp->default_qa_contact);
}
2798 2799 2800
sub set_remaining_time { $_[0]->set('remaining_time', $_[1]); }
# Used only when closing a bug or moving between closed states.
sub _zero_remaining_time { $_[0]->{'remaining_time'} = 0; }
2801
sub set_reporter_accessible { $_[0]->set('reporter_accessible', $_[1]); }
2802
sub set_resolution {
2803
    my ($self, $value, $params) = @_;
2804 2805 2806
    
    my $old_res = $self->resolution;
    $self->set('resolution', $value);
2807
    delete $self->{choices};
2808
    my $new_res = $self->resolution;
2809

2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825
    if ($new_res ne $old_res) {
        # Clear the dup_id if we're leaving the dup resolution.
        if ($old_res eq 'DUPLICATE') {
            $self->_clear_dup_id();
        }
        # Duplicates should have no remaining time left.
        elsif ($new_res eq 'DUPLICATE' && $self->remaining_time != 0) {
            $self->_zero_remaining_time();
        }
    }
    
    # We don't check if we're entering or leaving the dup resolution here,
    # because we could be moving from being a dup of one bug to being a dup
    # of another, theoretically. Note that this code block will also run
    # when going between different closed states.
    if ($self->resolution eq 'DUPLICATE') {
2826 2827
        if (my $dup_id = $params->{dup_id}) {
            $self->set_dup_id($dup_id);
2828 2829 2830 2831 2832
        }
        elsif (!$self->dup_id) {
            ThrowUserError('dupe_id_required');
        }
    }
2833 2834 2835 2836

    # This method has handled dup_id, so set_all doesn't have to worry
    # about it now.
    delete $params->{dup_id};
2837 2838 2839 2840 2841 2842 2843 2844 2845
}
sub clear_resolution {
    my $self = shift;
    if (!$self->status->is_open) {
        ThrowUserError('resolution_cant_clear', { bug_id => $self->id });
    }
    $self->{'resolution'} = ''; 
    $self->_clear_dup_id; 
}
2846
sub set_severity       { $_[0]->set('bug_severity',  $_[1]); }
2847
sub set_bug_status {
2848
    my ($self, $status, $params) = @_;
2849
    my $old_status = $self->status;
2850
    $self->set('bug_status', $status);
2851
    delete $self->{'status'};
2852 2853
    delete $self->{'statuses_available'};
    delete $self->{'choices'};
2854
    my $new_status = $self->status;
2855
   
2856 2857
    if ($new_status->is_open) {
        # Check for the everconfirmed transition
2858
        $self->_set_everconfirmed($new_status->name eq 'UNCONFIRMED' ? 0 : 1);
2859
        $self->clear_resolution();
2860 2861 2862 2863
        # Calling clear_resolution handled the "resolution" and "dup_id"
        # setting, so set_all doesn't have to worry about them.
        delete $params->{resolution};
        delete $params->{dup_id};
2864 2865 2866 2867
    }
    else {
        # We do this here so that we can make sure closed statuses have
        # resolutions.
2868 2869 2870 2871 2872 2873 2874
        my $resolution = $self->resolution;
        # We need to check "defined" to prevent people from passing
        # a blank resolution in the WebService, which would otherwise fail
        # silently.
        if (defined $params->{resolution}) {
            $resolution = delete $params->{resolution};
        }
2875 2876
        $self->set_resolution($resolution, $params);

2877 2878 2879 2880 2881
        # Changing between closed statuses zeros the remaining time.
        if ($new_status->id != $old_status->id && $self->remaining_time != 0) {
            $self->_zero_remaining_time();
        }
    }
2882
}
2883
sub set_status_whiteboard { $_[0]->set('status_whiteboard', $_[1]); }
2884 2885 2886 2887
sub set_summary           { $_[0]->set('short_desc',        $_[1]); }
sub set_target_milestone  { $_[0]->set('target_milestone',  $_[1]); }
sub set_url               { $_[0]->set('bug_file_loc',      $_[1]); }
sub set_version           { $_[0]->set('version',           $_[1]); }
2888 2889 2890 2891 2892

########################
# "Add/Remove" Methods #
########################

2893 2894
# These are in alphabetical order by field name.

2895 2896 2897
# Accepts a User object or a username. Adds the user only if they
# don't already exist as a CC on the bug.
sub add_cc {
2898
    my ($self, $user_or_name) = @_;
2899 2900
    return if !$user_or_name;
    my $user = ref $user_or_name ? $user_or_name
2901
                                 : Bugzilla::User->check($user_or_name);
2902
    $self->_check_strict_isolation_for_user($user);
2903 2904 2905 2906 2907 2908 2909 2910 2911
    my $cc_users = $self->cc_users;
    push(@$cc_users, $user) if !grep($_->id == $user->id, @$cc_users);
}

# Accepts a User object or a username. Removes the User if they exist
# in the list, but doesn't throw an error if they don't exist.
sub remove_cc {
    my ($self, $user_or_name) = @_;
    my $user = ref $user_or_name ? $user_or_name
2912
                                 : Bugzilla::User->check($user_or_name);
2913 2914 2915 2916
    my $currentUser = Bugzilla->user;
    if (!$self->user->{'canedit'} && $user->id != $currentUser->id) {
        ThrowUserError('cc_remove_denied');
    }
2917 2918 2919 2920
    my $cc_users = $self->cc_users;
    @$cc_users = grep { $_->id != $user->id } @$cc_users;
}

2921 2922 2923 2924 2925
sub add_alias {
    my ($self, $alias) = @_;
    return if !$alias;
    my $aliases = $self->_check_alias($alias);
    $alias = $aliases->[0];
2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938
    my @new_aliases;
    my $found = 0;
    foreach my $old_alias (@{ $self->alias }) {
        if (lc($old_alias) eq lc($alias)) {
            push(@new_aliases, $alias);
            $found = 1;
        }
        else {
            push(@new_aliases, $old_alias);
        }
    }
    push(@new_aliases, $alias) if !$found;
    $self->{alias} = \@new_aliases;
2939 2940 2941 2942 2943 2944 2945 2946
}

sub remove_alias {
    my ($self, $alias) = @_;
    my $bug_aliases = $self->alias;
    @$bug_aliases = grep { $_ ne $alias } @$bug_aliases;
}

2947 2948 2949 2950 2951 2952 2953
# $bug->add_comment("comment", {isprivate => 1, work_time => 10.5,
#                               type => CMT_NORMAL, extra_data => $data});
sub add_comment {
    my ($self, $comment, $params) = @_;

    $params ||= {};

2954 2955
    # Fill out info that doesn't change and callers may not pass in
    $params->{'bug_id'}  = $self;
2956
    $params->{'thetext'} = defined($comment) ? $comment : '';
2957 2958 2959 2960 2961

    # Validate all the entered data
    Bugzilla::Comment->check_required_create_fields($params);
    $params = Bugzilla::Comment->run_create_validators($params);

2962 2963 2964 2965 2966 2967 2968 2969
    # This makes it so we won't create new comments when there is nothing
    # to add 
    if ($params->{'thetext'} eq ''
        && !($params->{type} || abs($params->{work_time} || 0)))
    {
        return;
    }

2970 2971 2972 2973
    # If the user has explicitly set remaining_time, this will be overridden
    # later in set_all. But if they haven't, this keeps remaining_time
    # up-to-date.
    if ($params->{work_time}) {
2974
        $self->set_remaining_time(max($self->remaining_time - $params->{work_time}, 0));
2975 2976
    }

2977 2978
    $self->{added_comments} ||= [];

2979
    push(@{$self->{added_comments}}, $params);
2980
}
2981

2982 2983
sub modify_keywords {
    my ($self, $keywords, $action) = @_;
2984 2985

    if (!$action || !grep { $action eq $_ } qw(add remove set)) {
2986
        $action = 'set';
2987
    }
2988

2989
    $keywords = $self->_check_keywords($keywords);
2990 2991
    my @old_keywords = @{ $self->keyword_objects };
    my @result;
2992

2993
    if ($action eq 'set') {
2994 2995 2996 2997
        @result = @$keywords;
    }
    else {
        # We're adding or deleting specific keywords.
2998
        my %keys = map { $_->id => $_ } @old_keywords;
2999 3000 3001 3002 3003 3004 3005 3006
        if ($action eq 'add') {
            $keys{$_->id} = $_ foreach @$keywords;
        }
        else {
            delete $keys{$_->id} foreach @$keywords;
        }
        @result = values %keys;
    }
3007 3008 3009 3010 3011 3012 3013

    # Check if anything was added or removed.
    my @old_ids = map { $_->id } @old_keywords;
    my @new_ids = map { $_->id } @result;
    my ($removed, $added) = diff_arrays(\@old_ids, \@new_ids);
    my $any_changes = scalar @$removed || scalar @$added;

3014 3015
    # Make sure we retain the sort order.
    @result = sort {lc($a->name) cmp lc($b->name)} @result;
3016

3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029
    if ($any_changes) {
        my $privs;
        my $new = join(', ', (map {$_->name} @result));
        my $check = $self->check_can_change_field('keywords', 0, 1, \$privs)
            || ThrowUserError('illegal_change', { field    => 'keywords',
                                                  oldvalue => $self->keywords,
                                                  newvalue => $new,
                                                  privs    => $privs });
    }

    $self->{'keyword_objects'} = \@result;
}

3030 3031 3032
sub add_group {
    my ($self, $group) = @_;

3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045
    # If the user enters "FoO" but the DB has "Foo", $group->name would
    # return "Foo" and thus revealing the existence of the group name.
    # So we have to store and pass the name as entered by the user to
    # the error message, if we have it.
    my $group_name = blessed($group) ? $group->name : $group;
    my $args = { name => $group_name, product => $self->product,
                 bug_id => $self->id, action => 'add' };

    $group = Bugzilla::Group->check_no_disclose($args) if !blessed $group;

    # If the bug is already in this group, then there is nothing to do.
    return if $self->in_group($group);

3046

3047
    # Make sure that bugs in this product can actually be restricted
3048 3049
    # to this group by the current user.
    $self->product_obj->group_is_settable($group)
3050
         || ThrowUserError('group_restriction_not_allowed', $args);
3051 3052 3053 3054 3055 3056 3057 3058

    # OtherControl people can add groups only during a product change,
    # and only when the group is not NA for them.
    if (!Bugzilla->user->in_group($group->name)) {
        my $controls = $self->product_obj->group_controls->{$group->id};
        if (!$self->{_old_product_name}
            || $controls->{othercontrol} == CONTROLMAPNA)
        {
3059
            ThrowUserError('group_restriction_not_allowed', $args);
3060 3061 3062 3063
        }
    }

    my $current_groups = $self->groups_in;
3064
    push(@$current_groups, $group);
3065 3066 3067 3068
}

sub remove_group {
    my ($self, $group) = @_;
3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085

    # See add_group() for the reason why we store the user input.
    my $group_name = blessed($group) ? $group->name : $group;
    my $args = { name => $group_name, product => $self->product,
                 bug_id => $self->id, action => 'remove' };

    $group = Bugzilla::Group->check_no_disclose($args) if !blessed $group;

    # If the bug isn't in this group, then either the name is misspelled,
    # or the group really doesn't exist. Let the user know about this problem.
    $self->in_group($group) || ThrowUserError('group_invalid_removal', $args);

    # Check if this is a valid group for this product. You can *always*
    # remove a group that is not valid for this product (set_product does this).
    # This particularly happens when we're moving a bug to a new product.
    # You still have to be a member of an inactive group to remove it.
    if ($self->product_obj->group_is_valid($group)) {
3086 3087
        my $controls = $self->product_obj->group_controls->{$group->id};

3088 3089 3090
        # Nobody can ever remove a Mandatory group, unless it became inactive.
        if ($controls->{membercontrol} == CONTROLMAPMANDATORY && $group->is_active) {
            ThrowUserError('group_invalid_removal', $args);
3091 3092 3093 3094 3095 3096 3097 3098 3099
        }

        # OtherControl people can remove groups only during a product change,
        # and only when they are non-Mandatory and non-NA.
        if (!Bugzilla->user->in_group($group->name)) {
            if (!$self->{_old_product_name}
                || $controls->{othercontrol} == CONTROLMAPMANDATORY
                || $controls->{othercontrol} == CONTROLMAPNA)
            {
3100
                ThrowUserError('group_invalid_removal', $args);
3101 3102 3103
            }
        }
    }
3104

3105 3106 3107 3108
    my $current_groups = $self->groups_in;
    @$current_groups = grep { $_->id != $group->id } @$current_groups;
}

3109
sub add_see_also {
3110
    my ($self, $input, $skip_recursion) = @_;
3111 3112 3113 3114

    # This is needed by xt/search.t.
    $input = $input->name if blessed($input);

3115
    $input = trim($input);
3116
    return if !$input;
3117

3118
    my ($class, $uri) = Bugzilla::BugUrl->class_for($input);
3119

3120
    my $params = { value => $uri, bug_id => $self, class => $class };
3121
    $class->check_required_create_fields($params);
3122

3123
    my $field_values = $class->run_create_validators($params);
3124 3125 3126
    my $value = $field_values->{value}->as_string;
    trick_taint($value);
    $field_values->{value} = $value;
3127 3128 3129 3130

    # We only add the new URI if it hasn't been added yet. URIs are
    # case-sensitive, but most of our DBs are case-insensitive, so we do
    # this check case-insensitively.
3131
    if (!grep { lc($_->name) eq lc($value) } @{ $self->see_also }) {
3132
        my $privs;
3133
        my $can = $self->check_can_change_field('see_also', '', $value, \$privs);
3134 3135
        if (!$can) {
            ThrowUserError('illegal_change', { field    => 'see_also',
3136
                                               newvalue => $value,
3137 3138
                                               privs    => $privs });
        }
3139 3140 3141 3142
        # If this is a link to a local bug then save the
        # ref bug id for sending changes email.
        my $ref_bug = delete $field_values->{ref_bug};
        if ($class->isa('Bugzilla::BugUrl::Bugzilla::Local')
3143 3144
            and !$skip_recursion
            and $ref_bug->check_can_change_field('see_also', '', $self->id, \$privs))
3145 3146 3147 3148 3149
        {
            $ref_bug->add_see_also($self->id, 'skip_recursion');
            push @{ $self->{_update_ref_bugs} }, $ref_bug;
            push @{ $self->{see_also_changes} }, $ref_bug->id;
        }
3150
        push @{ $self->{see_also} }, bless ($field_values, $class);
3151 3152 3153 3154
    }
}

sub remove_see_also {
3155
    my ($self, $url, $skip_recursion) = @_;
3156
    my $see_also = $self->see_also;
3157 3158 3159 3160 3161 3162 3163

    # This is needed by xt/search.t.
    $url = $url->name if blessed($url);

    my ($removed_bug_url, $new_see_also) =
        part { lc($_->name) ne lc($url) } @$see_also;

3164
    my $privs;
3165
    my $can = $self->check_can_change_field('see_also', $see_also, $new_see_also, \$privs);
3166 3167 3168 3169
    if (!$can) {
        ThrowUserError('illegal_change', { field    => 'see_also',
                                           oldvalue => $url,
                                           privs    => $privs });
3170 3171
    }

3172 3173 3174 3175
    # Since we remove also the url from the referenced bug,
    # we need to notify changes for that bug too.
    $removed_bug_url = $removed_bug_url->[0];
    if (!$skip_recursion and $removed_bug_url
3176 3177
        and $removed_bug_url->isa('Bugzilla::BugUrl::Bugzilla::Local')
        and $removed_bug_url->ref_bug_url)
3178 3179 3180 3181
    {
        my $ref_bug
            = Bugzilla::Bug->check($removed_bug_url->ref_bug_url->bug_id);

3182 3183 3184
        if (Bugzilla->user->can_edit_product($ref_bug->product_id)
            and $ref_bug->check_can_change_field('see_also', $self->id, '', \$privs))
        {
3185 3186 3187 3188 3189 3190 3191
            my $self_url = $removed_bug_url->local_uri($self->id);
            $ref_bug->remove_see_also($self_url, 'skip_recursion');
            push @{ $self->{_update_ref_bugs} }, $ref_bug;
            push @{ $self->{see_also_changes} }, $ref_bug->id;
        }
    }

3192
    $self->{see_also} = $new_see_also || [];
3193 3194
}

3195 3196 3197 3198 3199 3200 3201 3202 3203
sub add_tag {
    my ($self, $tag) = @_;
    my $dbh = Bugzilla->dbh;
    my $user = Bugzilla->user;
    $tag = $self->_check_tag_name($tag);

    my $tag_id = $user->tags->{$tag}->{id};
    # If this tag doesn't exist for this user yet, create it.
    if (!$tag_id) {
3204
        $dbh->do('INSERT INTO tag (user_id, name) VALUES (?, ?)',
3205 3206
                  undef, ($user->id, $tag));

3207
        $tag_id = $dbh->selectrow_array('SELECT id FROM tag
3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242
                                         WHERE name = ? AND user_id = ?',
                                         undef, ($tag, $user->id));
        # The list has changed.
        delete $user->{tags};
    }
    # Do nothing if this tag is already set for this bug.
    return if grep { $_ eq $tag } @{$self->tags};

    # Increment the counter. Do it before the SQL call below,
    # to not count the tag twice.
    $user->tags->{$tag}->{bug_count}++;

    $dbh->do('INSERT INTO bug_tag (bug_id, tag_id) VALUES (?, ?)',
              undef, ($self->id, $tag_id));

    push(@{$self->{tags}}, $tag);
}

sub remove_tag {
    my ($self, $tag) = @_;
    my $dbh = Bugzilla->dbh;
    my $user = Bugzilla->user;
    $tag = $self->_check_tag_name($tag);

    my $tag_id = exists $user->tags->{$tag} ? $user->tags->{$tag}->{id} : undef;
    # Do nothing if the user doesn't use this tag, or didn't set it for this bug.
    return unless ($tag_id && grep { $_ eq $tag } @{$self->tags});

    $dbh->do('DELETE FROM bug_tag WHERE bug_id = ? AND tag_id = ?',
              undef, ($self->id, $tag_id));

    $self->{tags} = [grep { $_ ne $tag } @{$self->tags}];

    # Decrement the counter, and delete the tag if no bugs are using it anymore.
    if (!--$user->tags->{$tag}->{bug_count}) {
3243
        $dbh->do('DELETE FROM tag WHERE name = ? AND user_id = ?',
3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259
                  undef, ($tag, $user->id));

        # The list has changed.
        delete $user->{tags};
    }
}

sub tags {
    my $self = shift;
    my $dbh = Bugzilla->dbh;
    my $user = Bugzilla->user;

    # This method doesn't support several users using the same bug object.
    if (!exists $self->{tags}) {
        $self->{tags} = $dbh->selectcol_arrayref(
            'SELECT name FROM bug_tag
3260
             INNER JOIN tag ON tag.id = bug_tag.tag_id
3261 3262 3263 3264 3265 3266
             WHERE bug_id = ? AND user_id = ?',
             undef, ($self->id, $user->id));
    }
    return $self->{tags};
}

3267
#####################################################################
3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300
# Simple Accessors
#####################################################################

# These are accessors that don't need to access the database.
# Keep them in alphabetical order.

sub bug_file_loc        { return $_[0]->{bug_file_loc}        }
sub bug_id              { return $_[0]->{bug_id}              }
sub bug_severity        { return $_[0]->{bug_severity}        }
sub bug_status          { return $_[0]->{bug_status}          }
sub cclist_accessible   { return $_[0]->{cclist_accessible}   }
sub component_id        { return $_[0]->{component_id}        }
sub creation_ts         { return $_[0]->{creation_ts}         }
sub estimated_time      { return $_[0]->{estimated_time}      }
sub deadline            { return $_[0]->{deadline}            }
sub delta_ts            { return $_[0]->{delta_ts}            }
sub error               { return $_[0]->{error}               }
sub everconfirmed       { return $_[0]->{everconfirmed}       }
sub lastdiffed          { return $_[0]->{lastdiffed}          }
sub op_sys              { return $_[0]->{op_sys}              }
sub priority            { return $_[0]->{priority}            }
sub product_id          { return $_[0]->{product_id}          }
sub remaining_time      { return $_[0]->{remaining_time}      }
sub reporter_accessible { return $_[0]->{reporter_accessible} }
sub rep_platform        { return $_[0]->{rep_platform}        }
sub resolution          { return $_[0]->{resolution}          }
sub short_desc          { return $_[0]->{short_desc}          }
sub status_whiteboard   { return $_[0]->{status_whiteboard}   }
sub target_milestone    { return $_[0]->{target_milestone}    }
sub version             { return $_[0]->{version}             }

#####################################################################
# Complex Accessors
3301 3302
#####################################################################

3303 3304 3305
# These are accessors that have to access the database for additional
# information about a bug.

3306 3307 3308 3309
# These subs are in alphabetical order, as much as possible.
# If you add a new sub, please try to keep it in alphabetical order
# with the other ones.

3310 3311 3312 3313 3314
# Note: If you add a new method, remember that you must check the error
# state of the bug before returning any data. If $self->{error} is
# defined, then return something empty. Otherwise you risk potential
# security holes.

3315 3316 3317 3318 3319
sub dup_id {
    my ($self) = @_;
    return $self->{'dup_id'} if exists $self->{'dup_id'};

    $self->{'dup_id'} = undef;
3320 3321
    return if $self->{'error'};

3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333
    if ($self->{'resolution'} eq 'DUPLICATE') { 
        my $dbh = Bugzilla->dbh;
        $self->{'dup_id'} =
          $dbh->selectrow_array(q{SELECT dupe_of 
                                  FROM duplicates
                                  WHERE dupe = ?},
                                undef,
                                $self->{'bug_id'});
    }
    return $self->{'dup_id'};
}

3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355
sub _resolve_ultimate_dup_id {
    my ($bug_id, $dupe_of, $loops_are_an_error) = @_;
    my $dbh = Bugzilla->dbh;
    my $sth = $dbh->prepare('SELECT dupe_of FROM duplicates WHERE dupe = ?');

    my $this_dup = $dupe_of || $dbh->selectrow_array($sth, undef, $bug_id);
    my $last_dup = $bug_id;

    my %dupes;
    while ($this_dup) {
        if ($this_dup == $bug_id) {
            if ($loops_are_an_error) {
                ThrowUserError('dupe_loop_detected', { bug_id  => $bug_id,
                                                       dupe_of => $dupe_of });
            }
            else {
                return $last_dup;
            }
        }
        # If $dupes{$this_dup} is already set to 1, then a loop
        # already exists which does not involve this bug.
        # As the user is not responsible for this loop, do not
3356
        # prevent them from marking this bug as a duplicate.
3357 3358 3359 3360 3361 3362 3363 3364 3365
        return $last_dup if exists $dupes{$this_dup};
        $dupes{$this_dup} = 1;
        $last_dup = $this_dup;
        $this_dup = $dbh->selectrow_array($sth, undef, $this_dup);
    }

    return $last_dup;
}

3366 3367 3368 3369
sub actual_time {
    my ($self) = @_;
    return $self->{'actual_time'} if exists $self->{'actual_time'};

3370
    if ( $self->{'error'} || !Bugzilla->user->is_timetracker ) {
3371 3372 3373
        $self->{'actual_time'} = undef;
        return $self->{'actual_time'};
    }
3374

3375 3376 3377 3378 3379
    my $sth = Bugzilla->dbh->prepare("SELECT SUM(work_time)
                                      FROM longdescs 
                                      WHERE longdescs.bug_id=?");
    $sth->execute($self->{bug_id});
    $self->{'actual_time'} = $sth->fetchrow_array();
3380 3381 3382
    return $self->{'actual_time'};
}

3383 3384 3385 3386 3387 3388 3389
sub alias {
    my ($self) = @_;
    return $self->{'alias'} if exists $self->{'alias'};
    return [] if $self->{'error'};

    my $dbh = Bugzilla->dbh;
    $self->{'alias'} = $dbh->selectcol_arrayref(
3390 3391
        q{SELECT alias FROM bugs_aliases WHERE bug_id = ? ORDER BY alias},
        undef, $self->bug_id);
3392 3393 3394 3395

    return $self->{'alias'};
}

3396
sub any_flags_requesteeble {
3397 3398 3399
    my ($self) = @_;
    return $self->{'any_flags_requesteeble'} 
        if exists $self->{'any_flags_requesteeble'};
3400
    return 0 if $self->{'error'};
3401

3402 3403 3404 3405 3406 3407
    my $any_flags_requesteeble =
      grep { $_->is_requestable && $_->is_requesteeble } @{$self->flag_types};
    # Useful in case a flagtype is no longer requestable but a requestee
    # has been set before we turned off that bit.
    $any_flags_requesteeble ||= grep { $_->requestee_id } @{$self->flags};
    $self->{'any_flags_requesteeble'} = $any_flags_requesteeble;
3408 3409 3410 3411

    return $self->{'any_flags_requesteeble'};
}

3412
sub attachments {
3413 3414
    my ($self) = @_;
    return $self->{'attachments'} if exists $self->{'attachments'};
3415
    return [] if $self->{'error'};
3416 3417

    $self->{'attachments'} =
3418
        Bugzilla::Attachment->get_attachments_by_bug($self, {preload => 1});
3419
    $_->object_cache_set() foreach @{ $self->{'attachments'} };
3420 3421 3422
    return $self->{'attachments'};
}

3423
sub assigned_to {
3424
    my ($self) = @_;
3425 3426
    return $self->{'assigned_to_obj'} if exists $self->{'assigned_to_obj'};
    $self->{'assigned_to'} = 0 if $self->{'error'};
3427
    $self->{'assigned_to_obj'} ||= new Bugzilla::User({ id => $self->{'assigned_to'}, cache => 1 });
3428
    return $self->{'assigned_to_obj'};
3429 3430
}

3431
sub blocked {
3432 3433
    my ($self) = @_;
    return $self->{'blocked'} if exists $self->{'blocked'};
3434
    return [] if $self->{'error'};
3435 3436 3437 3438
    $self->{'blocked'} = EmitDependList("dependson", "blocked", $self->bug_id);
    return $self->{'blocked'};
}

3439 3440 3441 3442 3443 3444
sub blocks_obj {
    my ($self) = @_;
    $self->{blocks_obj} ||= $self->_bugs_in_order($self->blocked);
    return $self->{blocks_obj};
}

3445 3446 3447 3448 3449
sub bug_group {
    my ($self) = @_;
    return join(', ', (map { $_->name } @{$self->groups_in}));
}

3450 3451 3452 3453 3454 3455 3456 3457 3458
sub related_bugs {
    my ($self, $relationship) = @_;
    return [] if $self->{'error'};

    my $field_name = $relationship->name;
    $self->{'related_bugs'}->{$field_name} ||= $self->match({$field_name => $self->id});
    return $self->{'related_bugs'}->{$field_name}; 
}

3459
sub cc {
3460 3461
    my ($self) = @_;
    return $self->{'cc'} if exists $self->{'cc'};
3462
    return [] if $self->{'error'};
3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474

    my $dbh = Bugzilla->dbh;
    $self->{'cc'} = $dbh->selectcol_arrayref(
        q{SELECT profiles.login_name FROM cc, profiles
           WHERE bug_id = ?
             AND cc.who = profiles.userid
        ORDER BY profiles.login_name},
      undef, $self->bug_id);

    return $self->{'cc'};
}

3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487
# XXX Eventually this will become the standard "cc" method used everywhere.
sub cc_users {
    my $self = shift;
    return $self->{'cc_users'} if exists $self->{'cc_users'};
    return [] if $self->{'error'};
    
    my $dbh = Bugzilla->dbh;
    my $cc_ids = $dbh->selectcol_arrayref(
        'SELECT who FROM cc WHERE bug_id = ?', undef, $self->id);
    $self->{'cc_users'} = Bugzilla::User->new_from_list($cc_ids);
    return $self->{'cc_users'};
}

3488 3489 3490
sub component {
    my ($self) = @_;
    return '' if $self->{error};
3491
    $self->{component} //= $self->component_obj->name;
3492 3493 3494
    return $self->{component};
}

3495 3496 3497 3498 3499
# XXX Eventually this will replace component()
sub component_obj {
    my ($self) = @_;
    return $self->{component_obj} if defined $self->{component_obj};
    return {} if $self->{error};
3500 3501
    $self->{component_obj} =
        new Bugzilla::Component({ id => $self->{component_id}, cache => 1 });
3502 3503 3504
    return $self->{component_obj};
}

3505 3506 3507
sub classification_id {
    my ($self) = @_;
    return 0 if $self->{error};
3508
    $self->{classification_id} //= $self->product_obj->classification_id;
3509 3510 3511 3512 3513 3514
    return $self->{classification_id};
}

sub classification {
    my ($self) = @_;
    return '' if $self->{error};
3515
    $self->{classification} //= $self->product_obj->classification->name;
3516 3517 3518
    return $self->{classification};
}

3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536
sub default_bug_status {
    my $class = shift;
    # XXX This should just call new_bug_statuses when the UI accepts closed
    # bug statuses instead of accepting them as a parameter.
    my @statuses = @_;

    my $status;
    if (scalar(@statuses) == 1) {
        $status = $statuses[0]->name;
    }
    else {
        $status = ($statuses[0]->name ne 'UNCONFIRMED')
                  ? $statuses[0]->name : $statuses[1]->name;
    }

    return $status;
}

3537
sub dependson {
3538 3539
    my ($self) = @_;
    return $self->{'dependson'} if exists $self->{'dependson'};
3540
    return [] if $self->{'error'};
3541 3542 3543 3544 3545
    $self->{'dependson'} = 
        EmitDependList("blocked", "dependson", $self->bug_id);
    return $self->{'dependson'};
}

3546 3547 3548 3549 3550 3551
sub depends_on_obj {
    my ($self) = @_;
    $self->{depends_on_obj} ||= $self->_bugs_in_order($self->dependson);
    return $self->{depends_on_obj};
}

3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571
sub duplicates {
    my $self = shift;
    return $self->{duplicates} if exists $self->{duplicates};
    return [] if $self->{error};
    $self->{duplicates} = Bugzilla::Bug->new_from_list($self->duplicate_ids);
    return $self->{duplicates};
}

sub duplicate_ids {
    my $self = shift;
    return $self->{duplicate_ids} if exists $self->{duplicate_ids};
    return [] if $self->{error};

    my $dbh = Bugzilla->dbh;
    $self->{duplicate_ids} =
      $dbh->selectcol_arrayref('SELECT dupe FROM duplicates WHERE dupe_of = ?',
                               undef, $self->id);
    return $self->{duplicate_ids};
}

3572
sub flag_types {
3573 3574
    my ($self) = @_;
    return $self->{'flag_types'} if exists $self->{'flag_types'};
3575
    return [] if $self->{'error'};
3576

3577 3578 3579 3580
    my $vars = { target_type  => 'bug',
                 product_id   => $self->{product_id},
                 component_id => $self->{component_id},
                 bug_id       => $self->bug_id };
3581

3582
    $self->{'flag_types'} = Bugzilla::Flag->_flag_types($vars);
3583 3584 3585
    return $self->{'flag_types'};
}

3586 3587 3588 3589 3590 3591 3592 3593
sub flags {
    my $self = shift;

    # Don't cache it as it must be in sync with ->flag_types.
    $self->{flags} = [map { @{$_->{flags}} } @{$self->flag_types}];
    return $self->{flags};
}

3594 3595
sub isopened {
    my $self = shift;
3596 3597 3598 3599
    unless (exists $self->{isopened}) {
        $self->{isopened} = is_open_state($self->{bug_status}) ? 1 : 0;
    }
    return $self->{isopened};
3600 3601
}

3602
sub keywords {
3603
    my ($self) = @_;
3604 3605
    return join(', ', (map { $_->name } @{$self->keyword_objects}));
}
3606

3607 3608 3609 3610 3611
# XXX At some point, this should probably replace the normal "keywords" sub.
sub keyword_objects {
    my $self = shift;
    return $self->{'keyword_objects'} if defined $self->{'keyword_objects'};
    return [] if $self->{'error'};
3612

3613 3614 3615 3616 3617
    my $dbh = Bugzilla->dbh;
    my $ids = $dbh->selectcol_arrayref(
         "SELECT keywordid FROM keywords WHERE bug_id = ?", undef, $self->id);
    $self->{'keyword_objects'} = Bugzilla::Keyword->new_from_list($ids);
    return $self->{'keyword_objects'};
3618 3619
}

3620 3621
sub comments {
    my ($self, $params) = @_;
3622
    return [] if $self->{'error'};
3623 3624 3625 3626 3627
    $params ||= {};

    if (!defined $self->{'comments'}) {
        $self->{'comments'} = Bugzilla::Comment->match({ bug_id => $self->id });
        my $count = 0;
3628
        state $is_mysql = Bugzilla->dbh->isa('Bugzilla::DB::Mysql') ? 1 : 0;
3629 3630
        foreach my $comment (@{ $self->{'comments'} }) {
            $comment->{count} = $count++;
3631
            $comment->{bug} = $self;
3632 3633 3634
            # XXX - hack for MySQL. Convert [U+....] back into its Unicode
            # equivalent for characters above U+FFFF as MySQL older than 5.5.3
            # cannot store them, see Bugzilla::Comment::_check_thetext().
3635 3636 3637 3638 3639
            if ($is_mysql) {
                # Perl 5.13.8 and older complain about non-characters.
                no warnings 'utf8';
                $comment->{thetext} =~ s/\x{FDD0}\[U\+((?:[1-9A-F]|10)[0-9A-F]{4})\]\x{FDD1}/chr(hex $1)/eg
            }
3640
        }
3641 3642
        # Some bugs may have no comments when upgrading old installations.
        Bugzilla::Comment->preload($self->{'comments'}) if $count;
3643 3644 3645 3646
    }
    my @comments = @{ $self->{'comments'} };

    my $order = $params->{order} 
3647
        || Bugzilla->user->setting('comment_sort_order');
3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663
    if ($order ne 'oldest_to_newest') {
        @comments = reverse @comments;
        if ($order eq 'newest_to_oldest_desc_first') {
            unshift(@comments, pop @comments);
        }
    }

    if ($params->{after}) {
        my $from = datetime_from($params->{after});
        @comments = grep { datetime_from($_->creation_ts) > $from } @comments;
    }
    if ($params->{to}) {
        my $to = datetime_from($params->{to});
        @comments = grep { datetime_from($_->creation_ts) <= $to } @comments;
    }
    return \@comments;
3664 3665
}

3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687
sub new_bug_statuses {
    my ($class, $product) = @_;
    my $user = Bugzilla->user;

    # Construct the list of allowable statuses.
    my @statuses = @{ Bugzilla::Bug->statuses_available($product) };

    # If the user has no privs...
    unless ($user->in_group('editbugs', $product->id)
            || $user->in_group('canconfirm', $product->id))
    {
        # ... use UNCONFIRMED if available, else use the first status of the list.
        my ($unconfirmed) = grep { $_->name eq 'UNCONFIRMED' } @statuses;
    
        # Because of an apparent Perl bug, "$unconfirmed || $statuses[0]" doesn't
        # work, so we're using an "?:" operator. See bug 603314 for details.
        @statuses = ($unconfirmed ? $unconfirmed : $statuses[0]);
    }

    return \@statuses;
}

3688 3689 3690 3691 3692 3693 3694 3695
# This is needed by xt/search.t.
sub percentage_complete {
    my $self = shift;
    return undef if $self->{'error'} || !Bugzilla->user->is_timetracker;
    my $remaining = $self->remaining_time;
    my $actual    = $self->actual_time;
    my $total = $remaining + $actual;
    return undef if $total == 0;
3696 3697 3698 3699
    # Search.pm truncates this value to an integer, so we want to as well,
    # since this is mostly used in a test where its value needs to be
    # identical to what the database will return.
    return int(100 * ($actual / $total));
3700 3701
}

3702 3703 3704
sub product {
    my ($self) = @_;
    return '' if $self->{error};
3705
    $self->{product} //= $self->product_obj->name;
3706 3707 3708
    return $self->{product};
}

3709 3710 3711 3712
# XXX This should eventually replace the "product" subroutine.
sub product_obj {
    my $self = shift;
    return {} if $self->{error};
3713 3714
    $self->{product_obj} ||=
        new Bugzilla::Product({ id => $self->{product_id}, cache => 1 });
3715
    return $self->{product_obj};
3716 3717
}

3718
sub qa_contact {
3719
    my ($self) = @_;
3720
    return $self->{'qa_contact_obj'} if exists $self->{'qa_contact_obj'};
3721
    return undef if $self->{'error'};
3722

3723
    if (Bugzilla->params->{'useqacontact'} && $self->{'qa_contact'}) {
3724
        $self->{'qa_contact_obj'} = new Bugzilla::User({ id => $self->{'qa_contact'}, cache => 1 });
3725
    } else {
3726
        $self->{'qa_contact_obj'} = undef;
3727
    }
3728
    return $self->{'qa_contact_obj'};
3729 3730
}

3731
sub reporter {
3732 3733
    my ($self) = @_;
    return $self->{'reporter'} if exists $self->{'reporter'};
3734
    $self->{'reporter_id'} = 0 if $self->{'error'};
3735
    $self->{'reporter'} = new Bugzilla::User({ id => $self->{'reporter_id'}, cache => 1 });
3736 3737 3738
    return $self->{'reporter'};
}

3739 3740 3741
sub see_also {
    my ($self) = @_;
    return [] if $self->{'error'};
3742
    if (!exists $self->{see_also}) {
3743 3744 3745 3746 3747 3748 3749 3750 3751
        my $ids = Bugzilla->dbh->selectcol_arrayref(
            'SELECT id FROM bug_see_also WHERE bug_id = ?',
            undef, $self->id);

        my $bug_urls = Bugzilla::BugUrl->new_from_list($ids);

        $self->{see_also} = $bug_urls;
    }
    return $self->{see_also};
3752 3753
}

3754 3755 3756 3757 3758 3759 3760
sub status {
    my $self = shift;
    return undef if $self->{'error'};

    $self->{'status'} ||= new Bugzilla::Status({name => $self->{'bug_status'}});
    return $self->{'status'};
}
3761

3762
sub statuses_available {
3763 3764 3765 3766 3767 3768
    my ($invocant, $product) = @_;

    my @statuses;

    if (ref $invocant) {
      return [] if $invocant->{'error'};
3769

3770 3771 3772 3773 3774 3775 3776 3777
      return $invocant->{'statuses_available'}
          if defined $invocant->{'statuses_available'};

        @statuses = @{ $invocant->status->can_change_to };
        $product = $invocant->product_obj;
    } else {
        @statuses = @{ Bugzilla::Status->can_change_to };
    }
3778 3779

    # UNCONFIRMED is only a valid status if it is enabled in this product.
3780
    if (!$product->allows_unconfirmed) {
3781 3782 3783
        @statuses = grep { $_->name ne 'UNCONFIRMED' } @statuses;
    }

3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796
    if (ref $invocant) {
        my $available = $invocant->_refine_available_statuses(@statuses);
        $invocant->{'statuses_available'} = $available;
        return $available;
    }

    return \@statuses;
}

sub _refine_available_statuses {
    my $self = shift;
    my @statuses = @_;

3797 3798 3799 3800 3801 3802 3803 3804
    my @available;
    foreach my $status (@statuses) {
        # Make sure this is a legal status transition
        next if !$self->check_can_change_field(
                     'bug_status', $self->status->name, $status->name);
        push(@available, $status);
    }

3805 3806 3807 3808
    # If this bug has an inactive status set, it should still be in the list.
    if (!grep($_->name eq $self->status->name, @available)) {
        unshift(@available, $self->status);
    }
3809 3810
    
    return \@available;
3811 3812
}

3813
sub show_attachment_flags {
3814 3815 3816
    my ($self) = @_;
    return $self->{'show_attachment_flags'} 
        if exists $self->{'show_attachment_flags'};
3817
    return 0 if $self->{'error'};
3818 3819 3820 3821 3822 3823 3824 3825 3826

    # The number of types of flags that can be set on attachments to this bug
    # and the number of flags on those attachments.  One of these counts must be
    # greater than zero in order for the "flags" column to appear in the table
    # of attachments.
    my $num_attachment_flag_types = Bugzilla::FlagType::count(
        { 'target_type'  => 'attachment',
          'product_id'   => $self->{'product_id'},
          'component_id' => $self->{'component_id'} });
3827
    my $num_attachment_flags = Bugzilla::Flag->count(
3828
        { 'target_type'  => 'attachment',
3829
          'bug_id'       => $self->bug_id });
3830 3831 3832 3833 3834 3835 3836

    $self->{'show_attachment_flags'} =
        ($num_attachment_flag_types || $num_attachment_flags);

    return $self->{'show_attachment_flags'};
}

3837 3838 3839
sub groups {
    my $self = shift;
    return $self->{'groups'} if exists $self->{'groups'};
3840
    return [] if $self->{'error'};
3841

3842
    my $dbh = Bugzilla->dbh;
3843 3844 3845 3846 3847 3848 3849 3850 3851
    my @groups;

    # Some of this stuff needs to go into Bugzilla::User

    # For every group, we need to know if there is ANY bug_group_map
    # record putting the current bug in that group and if there is ANY
    # user_group_map record putting the user in that group.
    # The LEFT JOINs are checking for record existence.
    #
3852
    my $grouplist = Bugzilla->user->groups_as_string;
3853 3854
    my $sth = $dbh->prepare(
             "SELECT DISTINCT groups.id, name, description," .
3855 3856
             " CASE WHEN bug_group_map.group_id IS NOT NULL" .
             " THEN 1 ELSE 0 END," .
3857
             " CASE WHEN groups.id IN($grouplist) THEN 1 ELSE 0 END," .
3858 3859 3860 3861
             " isactive, membercontrol, othercontrol" .
             " FROM groups" . 
             " LEFT JOIN bug_group_map" .
             " ON bug_group_map.group_id = groups.id" .
3862
             " AND bug_id = ?" .
3863 3864
             " LEFT JOIN group_control_map" .
             " ON group_control_map.group_id = groups.id" .
3865
             " AND group_control_map.product_id = ? " .
3866 3867
             " WHERE isbuggroup = 1" .
             " ORDER BY description");
3868
    $sth->execute($self->{'bug_id'},
3869
                  $self->{'product_id'});
3870

3871 3872
    while (my ($groupid, $name, $description, $ison, $ingroup, $isactive,
            $membercontrol, $othercontrol) = $sth->fetchrow_array()) {
3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889

        $membercontrol ||= 0;

        # For product groups, we only want to use the group if either
        # (1) The bit is set and not required, or
        # (2) The group is Shown or Default for members and
        #     the user is a member of the group.
        if ($ison ||
            ($isactive && $ingroup
                       && (($membercontrol == CONTROLMAPDEFAULT)
                           || ($membercontrol == CONTROLMAPSHOWN))
            ))
        {
            my $ismandatory = $isactive
              && ($membercontrol == CONTROLMAPMANDATORY);

            push (@groups, { "bit" => $groupid,
3890
                             "name" => $name,
3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902
                             "ison" => $ison,
                             "ingroup" => $ingroup,
                             "mandatory" => $ismandatory,
                             "description" => $description });
        }
    }

    $self->{'groups'} = \@groups;

    return $self->{'groups'};
}

3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913
sub groups_in {
    my $self = shift;
    return $self->{'groups_in'} if exists $self->{'groups_in'};
    return [] if $self->{'error'};
    my $group_ids = Bugzilla->dbh->selectcol_arrayref(
        'SELECT group_id FROM bug_group_map WHERE bug_id = ?',
        undef, $self->id);
    $self->{'groups_in'} = Bugzilla::Group->new_from_list($group_ids);
    return $self->{'groups_in'};
}

3914 3915 3916 3917 3918
sub in_group {
    my ($self, $group) = @_;
    return grep($_->id == $group->id, @{$self->groups_in}) ? 1 : 0;
}

3919 3920 3921
sub user {
    my $self = shift;
    return $self->{'user'} if exists $self->{'user'};
3922
    return {} if $self->{'error'};
3923

3924
    my $user = Bugzilla->user;
3925 3926
    my $prod_id = $self->{'product_id'};

3927 3928 3929 3930 3931 3932 3933 3934 3935 3936
    my $editbugs = $user->in_group('editbugs', $prod_id);
    my $is_reporter = $user->id == $self->{reporter_id} ? 1 : 0;
    my $is_assignee = $user->id == $self->{'assigned_to'} ? 1 : 0;
    my $is_qa_contact = Bugzilla->params->{'useqacontact'}
                        && $self->{'qa_contact'}
                        && $user->id == $self->{'qa_contact'} ? 1 : 0;

    my $canedit = $editbugs || $is_assignee || $is_qa_contact;
    my $canconfirm = $editbugs || $user->in_group('canconfirm', $prod_id);
    my $has_any_role = $is_reporter || $is_assignee || $is_qa_contact;
3937

3938
    $self->{'user'} = {canconfirm => $canconfirm,
3939
                       canedit    => $canedit,
3940 3941
                       isreporter => $is_reporter,
                       has_any_role => $has_any_role};
3942 3943 3944
    return $self->{'user'};
}

3945 3946
# This is intended to get values that can be selected by the user in the
# UI. It should not be used for security or validation purposes.
3947 3948 3949
sub choices {
    my $self = shift;
    return $self->{'choices'} if exists $self->{'choices'};
3950
    return {} if $self->{'error'};
3951
    my $user = Bugzilla->user;
3952

3953
    my @products = @{ $user->get_enterable_products };
3954 3955
    # The current product is part of the popup, even if new bugs are no longer
    # allowed for that product
3956 3957 3958
    if (!grep($_->name eq $self->product_obj->name, @products)) {
        unshift(@products, $self->product_obj);
    }
3959 3960 3961
    my %class_ids = map { $_->classification_id => 1 } @products;
    my $classifications = 
        Bugzilla::Classification->new_from_list([keys %class_ids]);
3962 3963

    my %choices = (
3964
        bug_status => $self->statuses_available,
3965
        classification => $classifications,
3966 3967 3968
        product    => \@products,
        component  => $self->product_obj->components,
        version    => $self->product_obj->versions,
3969 3970 3971 3972 3973 3974 3975
        target_milestone => $self->product_obj->milestones,
    );

    my $resolution_field = new Bugzilla::Field({ name => 'resolution' });
    # Don't include the empty resolution in drop-downs.
    my @resolutions = grep($_->name, @{ $resolution_field->legal_values });
    $choices{'resolution'} = \@resolutions;
3976

3977 3978 3979 3980 3981
    foreach my $key (keys %choices) {
        my $value = $self->$key;
        $choices{$key} = [grep { $_->is_active || $_->name eq $value } @{ $choices{$key} }];
    }

3982
    $self->{'choices'} = \%choices;
3983 3984
    return $self->{'choices'};
}
3985

3986 3987 3988 3989 3990
# Convenience Function. If you need speed, use this. If you need
# other Bug fields in addition to this, just create a new Bug with
# the alias.
# Queries the database for the bug with a given alias, and returns
# the ID of the bug if it exists or the undefined value if it doesn't.
3991
sub bug_alias_to_id {
3992 3993 3994 3995
    my ($alias) = @_;
    my $dbh = Bugzilla->dbh;
    trick_taint($alias);
    return $dbh->selectrow_array(
3996
        "SELECT bug_id FROM bugs_aliases WHERE alias = ?", undef, $alias);
3997 3998
}

3999 4000 4001 4002
#####################################################################
# Subroutines
#####################################################################

4003 4004
# Returns a list of currently active and editable bug fields,
# including multi-select fields.
4005 4006
sub editable_bug_fields {
    my @fields = Bugzilla->dbh->bz_table_columns('bugs');
4007 4008 4009
    # Add multi-select fields
    push(@fields, map { $_->name } @{Bugzilla->fields({obsolete => 0,
                                                       type => FIELD_TYPE_MULTI_SELECT})});
4010
    # Obsolete custom fields are not editable.
4011
    my @obsolete_fields = @{ Bugzilla->fields({obsolete => 1, custom => 1}) };
4012
    @obsolete_fields = map { $_->name } @obsolete_fields;
4013 4014 4015 4016
    foreach my $remove ("bug_id", "reporter", "creation_ts", "delta_ts", 
                        "lastdiffed", @obsolete_fields) 
    {
        my $location = firstidx { $_ eq $remove } @fields;
4017
        # Ensure field exists before attempting to remove it.
4018
        splice(@fields, $location, 1) if ($location > -1);
4019
    }
4020
    return @fields;
4021 4022
}

4023 4024
# XXX - When Bug::update() will be implemented, we should make this routine
#       a private method.
4025 4026
# Join with bug_status and bugs tables to show bugs with open statuses first,
# and then the others
4027
sub EmitDependList {
4028 4029 4030
    my ($my_field, $target_field, $bug_id, $exclude_resolved) = @_;
    my $cache = Bugzilla->request_cache->{bug_dependency_list} ||= {};

4031
    my $dbh = Bugzilla->dbh;
4032 4033 4034 4035 4036
    $exclude_resolved = $exclude_resolved ? 1 : 0;
    my $is_open_clause = $exclude_resolved ? 'AND is_open = 1' : '';

    $cache->{"${target_field}_sth_$exclude_resolved"} ||= $dbh->prepare(
          "SELECT $target_field
4037
             FROM dependencies
4038
                  INNER JOIN bugs ON dependencies.$target_field = bugs.bug_id
4039
                  INNER JOIN bug_status ON bugs.bug_status = bug_status.value
4040 4041 4042 4043 4044 4045
            WHERE $my_field = ? $is_open_clause
            ORDER BY is_open DESC, $target_field");

    return $dbh->selectcol_arrayref(
        $cache->{"${target_field}_sth_$exclude_resolved"},
        undef, $bug_id);
4046 4047
}

4048 4049 4050
# Creates a lot of bug objects in the same order as the input array.
sub _bugs_in_order {
    my ($self, $bug_ids) = @_;
4051 4052
    return [] unless @$bug_ids;

4053
    my %bug_map;
4054 4055
    my $dbh = Bugzilla->dbh;

4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066
    # there's no need to load bugs from the database if they are already in the
    # object-cache
    my @missing_ids;
    foreach my $bug_id (@$bug_ids) {
        if (my $bug = Bugzilla::Bug->object_cache_get($bug_id)) {
            $bug_map{$bug_id} = $bug;
        }
        else {
            push @missing_ids, $bug_id;
        }
    }
4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081
    if (@missing_ids) {
        my $bugs = Bugzilla::Bug->new_from_list(\@missing_ids);
        $bug_map{$_->id} = $_ foreach @$bugs;
    }

    # Dependencies are often displayed using their aliases instead of their
    # bug ID. Load them all at once.
    my $rows = $dbh->selectall_arrayref(
        'SELECT bug_id, alias FROM bugs_aliases WHERE ' .
        $dbh->sql_in('bug_id', $bug_ids) . ' ORDER BY alias');

    foreach my $row (@$rows) {
        my ($bug_id, $alias) = @$row;
        $bug_map{$bug_id}->{alias} ||= [];
        push @{ $bug_map{$bug_id}->{alias} }, $alias;
4082
    }
4083 4084 4085
    # Make sure all bugs have their alias attribute set.
    $bug_map{$_}->{alias} ||= [] foreach @$bug_ids;

4086
    return [ map { $bug_map{$_} } @$bug_ids ];
4087 4088
}

4089
# Get the activity of a bug, starting from $starttime (if given).
4090
# This routine assumes Bugzilla::Bug->check has been previously called.
4091
sub get_activity {
4092
    my ($self, $attach_id, $starttime, $include_comment_tags) = @_;
4093
    my $dbh = Bugzilla->dbh;
4094
    my $user = Bugzilla->user;
4095 4096

    # Arguments passed to the SQL query.
4097
    my @args = ($self->id);
4098 4099 4100 4101 4102 4103

    # Only consider changes since $starttime, if given.
    my $datepart = "";
    if (defined $starttime) {
        trick_taint($starttime);
        push (@args, $starttime);
4104
        $datepart = "AND bug_when > ?";
4105 4106
    }

4107 4108 4109 4110 4111 4112
    my $attachpart = "";
    if ($attach_id) {
        push(@args, $attach_id);
        $attachpart = "AND bugs_activity.attach_id = ?";
    }

4113 4114 4115
    # Only includes attachments the user is allowed to see.
    my $suppjoins = "";
    my $suppwhere = "";
4116
    if (!$user->is_insider) {
4117 4118 4119 4120 4121
        $suppjoins = "LEFT JOIN attachments 
                   ON attachments.attach_id = bugs_activity.attach_id";
        $suppwhere = "AND COALESCE(attachments.isprivate, 0) = 0";
    }

4122
    my $query = "SELECT fielddefs.name, bugs_activity.attach_id, " .
4123
        $dbh->sql_date_format('bugs_activity.bug_when', '%Y.%m.%d %H:%i:%s') .
4124
            " AS bug_when, bugs_activity.removed, bugs_activity.added, profiles.login_name,
4125
               bugs_activity.comment_id
4126 4127
          FROM bugs_activity
               $suppjoins
4128
    INNER JOIN fielddefs
4129
            ON bugs_activity.fieldid = fielddefs.id
4130 4131 4132 4133
    INNER JOIN profiles
            ON profiles.userid = bugs_activity.who
         WHERE bugs_activity.bug_id = ?
               $datepart
4134
               $attachpart
4135 4136 4137 4138 4139 4140
               $suppwhere ";

    if (Bugzilla->params->{'comment_taggers_group'}
        && $include_comment_tags
        && !$attach_id)
    {
4141 4142 4143 4144 4145 4146 4147 4148 4149
        # Only includes comment tag activity for comments the user is allowed to see.
        $suppjoins = "";
        $suppwhere = "";
        if (!Bugzilla->user->is_insider) {
            $suppjoins = "INNER JOIN longdescs
                          ON longdescs.comment_id = longdescs_tags_activity.comment_id";
            $suppwhere = "AND longdescs.isprivate = 0";
        }

4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160
        $query .= "
            UNION ALL
            SELECT 'comment_tag' AS name,
                   NULL AS attach_id," .
                   $dbh->sql_date_format('longdescs_tags_activity.bug_when', '%Y.%m.%d %H:%i:%s') . " AS bug_when,
                   longdescs_tags_activity.removed,
                   longdescs_tags_activity.added,
                   profiles.login_name,
                   longdescs_tags_activity.comment_id as comment_id
              FROM longdescs_tags_activity
                   INNER JOIN profiles ON profiles.userid = longdescs_tags_activity.who
4161
                   $suppjoins
4162 4163
             WHERE longdescs_tags_activity.bug_id = ?
                   $datepart
4164
                   $suppwhere
4165 4166 4167 4168 4169 4170
        ";
        push @args, $self->id;
        push @args, $starttime if defined $starttime;
    }

    $query .= "ORDER BY bug_when, comment_id";
4171 4172 4173 4174 4175 4176 4177 4178 4179

    my $list = $dbh->selectall_arrayref($query, undef, @args);

    my @operations;
    my $operation = {};
    my $changes = [];
    my $incomplete_data = 0;

    foreach my $entry (@$list) {
4180
        my ($fieldname, $attachid, $when, $removed, $added, $who, $comment_id) = @$entry;
4181 4182 4183 4184
        my %change;
        my $activity_visible = 1;

        # check if the user should see this field's activity
4185 4186
        if (grep { $fieldname eq $_ } TIMETRACKING_FIELDS) {
            $activity_visible = $user->is_timetracker;
4187 4188
        }
        elsif ($fieldname eq 'longdescs.isprivate'
4189
               && !$user->is_insider && $added)
4190 4191 4192 4193
        { 
            $activity_visible = 0;
        } 
        else {
4194 4195 4196 4197 4198
            $activity_visible = 1;
        }

        if ($activity_visible) {
            # Check for the results of an old Bugzilla data corruption bug
4199 4200 4201 4202
            if (($added eq '?' && $removed eq '?')
                || ($added =~ /^\? / || $removed =~ /^\? /)) {
                $incomplete_data = 1;
            }
4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219

            # An operation, done by 'who' at time 'when', has a number of
            # 'changes' associated with it.
            # If this is the start of a new operation, store the data from the
            # previous one, and set up the new one.
            if ($operation->{'who'}
                && ($who ne $operation->{'who'}
                    || $when ne $operation->{'when'}))
            {
                $operation->{'changes'} = $changes;
                push (@operations, $operation);

                # Create new empty anonymous data structures.
                $operation = {};
                $changes = [];
            }

4220 4221 4222 4223 4224
            # If this is the same field as the previous item, then concatenate
            # the data into the same change.
            if ($operation->{'who'} && $who eq $operation->{'who'}
                && $when eq $operation->{'when'}
                && $fieldname eq $operation->{'fieldname'}
4225
                && ($comment_id || 0) == ($operation->{'comment_id'} || 0)
4226 4227 4228
                && ($attachid || 0) == ($operation->{'attachid'} || 0))
            {
                my $old_change = pop @$changes;
4229 4230
                $removed = join_activity_entries($fieldname, $old_change->{'removed'}, $removed);
                $added = join_activity_entries($fieldname, $old_change->{'added'}, $added);
4231
            }
4232 4233
            $operation->{'who'} = $who;
            $operation->{'when'} = $when;
4234 4235
            $operation->{'fieldname'} = $change{'fieldname'} = $fieldname;
            $operation->{'attachid'} = $change{'attachid'} = $attachid;
4236 4237
            $change{'removed'} = $removed;
            $change{'added'} = $added;
4238

4239
            if ($comment_id) {
Frédéric Buclin's avatar
Frédéric Buclin committed
4240
                $operation->{comment_id} = $change{'comment'} = Bugzilla::Comment->new($comment_id);
4241 4242
            }

4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254
            push (@$changes, \%change);
        }
    }

    if ($operation->{'who'}) {
        $operation->{'changes'} = $changes;
        push (@operations, $operation);
    }

    return(\@operations, $incomplete_data);
}

4255 4256
# Update the bugs_activity table to reflect changes made in bugs.
sub LogActivityEntry {
4257 4258
    my ($bug_id, $field, $removed, $added, $user_id, $timestamp, $comment_id,
        $attach_id) = @_;
4259
    my $sth = Bugzilla->dbh->prepare_cached(
4260 4261 4262
        'INSERT INTO bugs_activity
        (bug_id, who, bug_when, fieldid, removed, added, comment_id, attach_id)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
4263

4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285
    # in the case of CCs, deps, and keywords, there's a possibility that someone
    # might try to add or remove a lot of them at once, which might take more
    # space than the activity table allows.  We'll solve this by splitting it
    # into multiple entries if it's too long.
    while ($removed || $added) {
        my ($removestr, $addstr) = ($removed, $added);
        if (length($removestr) > MAX_LINE_LENGTH) {
            my $commaposition = find_wrap_point($removed, MAX_LINE_LENGTH);
            $removestr = substr($removed, 0, $commaposition);
            $removed = substr($removed, $commaposition);
        } else {
            $removed = ""; # no more entries
        }
        if (length($addstr) > MAX_LINE_LENGTH) {
            my $commaposition = find_wrap_point($added, MAX_LINE_LENGTH);
            $addstr = substr($added, 0, $commaposition);
            $added = substr($added, $commaposition);
        } else {
            $added = ""; # no more entries
        }
        trick_taint($addstr);
        trick_taint($removestr);
4286 4287 4288
        my $fieldid = get_field_id($field);
        $sth->execute($bug_id, $user_id, $timestamp, $fieldid, $removestr,
            $addstr, $comment_id, $attach_id);
4289 4290 4291
    }
}

4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
# Update bug_user_last_visit table
sub update_user_last_visit {
    my ($self, $user, $last_visit_ts) = @_;
    my $lv = Bugzilla::BugUserLastVisit->match({ bug_id  => $self->id,
                                                 user_id => $user->id })->[0];

    if ($lv) {
        $lv->set(last_visit_ts => $last_visit_ts);
        $lv->update;
    }
    else {
        Bugzilla::BugUserLastVisit->create({ bug_id        => $self->id,
                                             user_id       => $user->id,
                                             last_visit_ts => $last_visit_ts });
    }
}

4309 4310 4311
# Convert WebService API and email_in.pl field names to internal DB field
# names.
sub map_fields {
4312
    my ($params, $except) = @_; 
4313 4314 4315

    my %field_values;
    foreach my $field (keys %$params) {
4316 4317
        # Don't allow setting private fields via email_in or the WebService.
        next if $field =~ /^_/;
4318 4319 4320 4321 4322 4323 4324
        my $field_name;
        if ($except->{$field}) {
           $field_name = $field;
        }
        else {
            $field_name = FIELD_MAP->{$field} || $field;
        }
4325 4326 4327 4328 4329
        $field_values{$field_name} = $params->{$field};
    }
    return \%field_values;
}

4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347
################################################################################
# check_can_change_field() defines what users are allowed to change. You
# can add code here for site-specific policy changes, according to the
# instructions given in the Bugzilla Guide and below. Note that you may also
# have to update the Bugzilla::Bug::user() function to give people access to the
# options that they are permitted to change.
#
# check_can_change_field() returns true if the user is allowed to change this
# field, and false if they are not.
#
# The parameters to this method are as follows:
# $field    - name of the field in the bugs table the user is trying to change
# $oldvalue - what they are changing it from
# $newvalue - what they are changing it to
# $PrivilegesRequired - return the reason of the failure, if any
################################################################################
sub check_can_change_field {
    my $self = shift;
4348
    my ($field, $oldvalue, $newvalue, $PrivilegesRequired) = (@_);
4349
    my $user = Bugzilla->user;
4350 4351 4352 4353 4354 4355 4356

    $oldvalue = defined($oldvalue) ? $oldvalue : '';
    $newvalue = defined($newvalue) ? $newvalue : '';

    # Return true if they haven't changed this field at all.
    if ($oldvalue eq $newvalue) {
        return 1;
4357 4358 4359
    } elsif (ref($newvalue) eq 'ARRAY' && ref($oldvalue) eq 'ARRAY') {
        my ($removed, $added) = diff_arrays($oldvalue, $newvalue);
        return 1 if !scalar(@$removed) && !scalar(@$added);
4360 4361 4362
    } elsif (trim($oldvalue) eq trim($newvalue)) {
        return 1;
    # numeric fields need to be compared using ==
4363 4364
    } elsif (($field eq 'estimated_time' || $field eq 'remaining_time' 
              || $field eq 'work_time')
4365 4366 4367 4368 4369
             && $oldvalue == $newvalue)
    {
        return 1;
    }

4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383
    my @priv_results;
    Bugzilla::Hook::process('bug_check_can_change_field',
        { bug => $self, field => $field, 
          new_value => $newvalue, old_value => $oldvalue, 
          priv_results => \@priv_results });
    if (my $priv_required = first { $_ > 0 } @priv_results) {
        $$PrivilegesRequired = $priv_required;
        return 0;
    }
    my $allow_found = first { $_ == 0 } @priv_results;
    if (defined $allow_found) {
        return 1;
    }

4384 4385
    # Allow anyone to change comments, or set flags
    if ($field =~ /^longdesc/ || $field eq 'flagtypes.name') {
4386 4387 4388
        return 1;
    }

4389
    # If the user isn't allowed to change a field, we must tell them who can.
4390 4391 4392
    # We store the required permission set into the $PrivilegesRequired
    # variable which gets passed to the error template.
    #
4393 4394 4395 4396
    # $PrivilegesRequired = PRIVILEGES_REQUIRED_NONE : no privileges required;
    # $PrivilegesRequired = PRIVILEGES_REQUIRED_REPORTER : the reporter, assignee or an empowered user;
    # $PrivilegesRequired = PRIVILEGES_REQUIRED_ASSIGNEE : the assignee or an empowered user;
    # $PrivilegesRequired = PRIVILEGES_REQUIRED_EMPOWERED : an empowered user.
4397 4398 4399 4400

    # Only users in the time-tracking group can change time-tracking fields,
    # including the deadline.
    if (grep { $_ eq $field } (TIMETRACKING_FIELDS, 'deadline')) {
4401
        if (!$user->is_timetracker) {
4402
            $$PrivilegesRequired = PRIVILEGES_REQUIRED_EMPOWERED;
4403 4404 4405
            return 0;
        }
    }
4406

4407 4408
    # Allow anyone with (product-specific) "editbugs" privs to change anything.
    if ($user->in_group('editbugs', $self->{'product_id'})) {
4409 4410 4411
        return 1;
    }

4412
    # *Only* users with (product-specific) "canconfirm" privs can confirm bugs.
4413
    if ($self->_changes_everconfirmed($field, $oldvalue, $newvalue)) {
4414
        $$PrivilegesRequired = PRIVILEGES_REQUIRED_EMPOWERED;
4415
        return $user->in_group('canconfirm', $self->{'product_id'});
4416 4417 4418 4419 4420
    }

    # Make sure that a valid bug ID has been given.
    if (!$self->{'error'}) {
        # Allow the assignee to change anything else.
4421 4422 4423
        if ($self->{'assigned_to'} == $user->id
            || $self->{'_old_assigned_to'} && $self->{'_old_assigned_to'} == $user->id)
        {
4424 4425 4426 4427 4428
            return 1;
        }

        # Allow the QA contact to change anything else.
        if (Bugzilla->params->{'useqacontact'}
4429 4430
            && (($self->{'qa_contact'} && $self->{'qa_contact'} == $user->id)
                || ($self->{'_old_qa_contact'} && $self->{'_old_qa_contact'} == $user->id)))
4431 4432 4433 4434 4435 4436 4437 4438 4439 4440
        {
            return 1;
        }
    }

    # At this point, the user is either the reporter or an
    # unprivileged user. We first check for fields the reporter
    # is not allowed to change.

    # The reporter may not:
4441
    # - reassign bugs, unless the bugs are assigned to them;
4442 4443 4444
    #   in that case we will have already returned 1 above
    #   when checking for the assignee of the bug.
    if ($field eq 'assigned_to') {
4445
        $$PrivilegesRequired = PRIVILEGES_REQUIRED_ASSIGNEE;
4446 4447 4448 4449
        return 0;
    }
    # - change the QA contact
    if ($field eq 'qa_contact') {
4450
        $$PrivilegesRequired = PRIVILEGES_REQUIRED_ASSIGNEE;
4451 4452 4453 4454
        return 0;
    }
    # - change the target milestone
    if ($field eq 'target_milestone') {
4455
        $$PrivilegesRequired = PRIVILEGES_REQUIRED_ASSIGNEE;
4456 4457
        return 0;
    }
4458
    # - change the priority (unless they could have set it originally)
4459
    if ($field eq 'priority'
4460
        && !Bugzilla->params->{'letsubmitterchoosepriority'})
4461
    {
4462
        $$PrivilegesRequired = PRIVILEGES_REQUIRED_ASSIGNEE;
4463 4464
        return 0;
    }
4465 4466
    # - unconfirm bugs (confirming them is handled above)
    if ($field eq 'everconfirmed') {
4467
        $$PrivilegesRequired = PRIVILEGES_REQUIRED_ASSIGNEE;
4468 4469 4470 4471 4472 4473
        return 0;
    }
    # - change the status from one open state to another
    if ($field eq 'bug_status'
        && is_open_state($oldvalue) && is_open_state($newvalue)) 
    {
4474
       $$PrivilegesRequired = PRIVILEGES_REQUIRED_ASSIGNEE;
4475 4476
       return 0;
    }
4477 4478 4479 4480 4481 4482 4483 4484

    # The reporter is allowed to change anything else.
    if (!$self->{'error'} && $self->{'reporter_id'} == $user->id) {
        return 1;
    }

    # If we haven't returned by this point, then the user doesn't
    # have the necessary permissions to change this field.
4485
    $$PrivilegesRequired = PRIVILEGES_REQUIRED_REPORTER;
4486 4487 4488
    return 0;
}

4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506
# A helper for check_can_change_field
sub _changes_everconfirmed {
    my ($self, $field, $old, $new) = @_;
    return 1 if $field eq 'everconfirmed';
    if ($field eq 'bug_status') {
        if ($self->everconfirmed) {
            # Moving a confirmed bug to UNCONFIRMED will change everconfirmed.
            return 1 if $new eq 'UNCONFIRMED';
        }
        else {
            # Moving an unconfirmed bug to an open state that isn't 
            # UNCONFIRMED will confirm the bug.
            return 1 if (is_open_state($new) and $new ne 'UNCONFIRMED');
        }
    }
    return 0;
}

4507 4508 4509 4510
#
# Field Validation
#

4511
# Validate and return a hash of dependencies
4512
sub ValidateDependencies {
4513
    my $fields = {};
4514
    # These can be arrayrefs or they can be strings.
4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527
    $fields->{'dependson'} = shift;
    $fields->{'blocked'} = shift;
    my $id = shift || 0;

    unless (defined($fields->{'dependson'})
            || defined($fields->{'blocked'}))
    {
        return;
    }

    my $dbh = Bugzilla->dbh;
    my %deps;
    my %deptree;
4528 4529 4530 4531
    my %sth;
    $sth{dependson} = $dbh->prepare('SELECT dependson FROM dependencies WHERE blocked   = ?');
    $sth{blocked}   = $dbh->prepare('SELECT blocked   FROM dependencies WHERE dependson = ?');

4532 4533 4534 4535 4536 4537 4538
    foreach my $pair (["blocked", "dependson"], ["dependson", "blocked"]) {
        my ($me, $target) = @{$pair};
        $deptree{$target} = [];
        $deps{$target} = [];
        next unless $fields->{$target};

        my %seen;
4539 4540 4541
        my $target_array = ref($fields->{$target}) ? $fields->{$target}
                           : [split(/[\s,]+/, $fields->{$target})];
        foreach my $i (@$target_array) {
4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555
            if ($id == $i) {
                ThrowUserError("dependency_loop_single");
            }
            if (!exists $seen{$i}) {
                push(@{$deptree{$target}}, $i);
                $seen{$i} = 1;
            }
        }
        # populate $deps{$target} as first-level deps only.
        # and find remainder of dependency tree in $deptree{$target}
        @{$deps{$target}} = @{$deptree{$target}};
        my @stack = @{$deps{$target}};
        while (@stack) {
            my $i = shift @stack;
4556
            my $dep_list = $dbh->selectcol_arrayref($sth{$target}, undef, $i);
4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573
            foreach my $t (@$dep_list) {
                # ignore any _current_ dependencies involving this bug,
                # as they will be overwritten with data from the form.
                if ($t != $id && !exists $seen{$t}) {
                    push(@{$deptree{$target}}, $t);
                    push @stack, $t;
                    $seen{$t} = 1;
                }
            }
        }
    }

    my @deps   = @{$deptree{'dependson'}};
    my @blocks = @{$deptree{'blocked'}};
    my %union = ();
    my %isect = ();
    foreach my $b (@deps, @blocks) { $union{$b}++ && $isect{$b}++ }
4574
    my @isect = keys %isect;
4575
    if (scalar(@isect) > 0) {
4576
        ThrowUserError("dependency_loop_multi", {'deps' => \@isect});
4577 4578 4579
    }
    return %deps;
}
4580

4581 4582

#####################################################################
4583
# Custom Field Accessors
4584 4585
#####################################################################

4586 4587 4588 4589
sub _create_cf_accessors {
    my ($invocant) = @_;
    my $class = ref($invocant) || $invocant;
    return if Bugzilla->request_cache->{"${class}_cf_accessors_created"};
4590

4591 4592 4593 4594 4595 4596 4597 4598 4599 4600
    my $fields = Bugzilla->fields({ custom => 1 });
    foreach my $field (@$fields) {
        my $accessor = $class->_accessor_for($field);
        my $name = "${class}::" . $field->name;
        {
            no strict 'refs';
            next if defined *{$name};
            *{$name} = $accessor;
        }
    }
4601

4602 4603
    Bugzilla->request_cache->{"${class}_cf_accessors_created"} = 1;
}
4604

4605 4606 4607 4608 4609 4610 4611
sub _accessor_for {
    my ($class, $field) = @_;
    if ($field->type == FIELD_TYPE_MULTI_SELECT) {
        return $class->_multi_select_accessor($field->name);
    }
    return $class->_cf_accessor($field->name);
}
4612

4613 4614 4615 4616 4617 4618 4619 4620
sub _cf_accessor {
    my ($class, $field) = @_;
    my $accessor = sub {
        my ($self) = @_;
        return $self->{$field};
    };
    return $accessor;
}
4621

4622 4623 4624 4625 4626 4627 4628 4629 4630 4631
sub _multi_select_accessor {
    my ($class, $field) = @_;
    my $accessor = sub {
        my ($self) = @_;
        $self->{$field} ||= Bugzilla->dbh->selectcol_arrayref(
            "SELECT value FROM bug_$field WHERE bug_id = ? ORDER BY value",
            undef, $self->id);
        return $self->{$field};
    };
    return $accessor;
4632 4633 4634
}

1;
4635

4636
__END__
4637 4638 4639 4640 4641 4642 4643 4644
=head1 B<Methods>

=over

=item C<initialize>

Ensures the accessors for custom fields are always created.

4645 4646 4647 4648 4649 4650 4651 4652 4653 4654
=item C<add_alias($alias)>

Adds an alias to the internal respresentation of the bug. You will need to
call L<update> to make the changes permanent.

=item C<remove_alias($alias)>

Removes an alias from the internal respresentation of the bug. You will need to
call L<update> to make the changes permanent.

4655 4656 4657 4658 4659
=item C<update_user_last_visit($user, $last_visit)>

Creates or updates a L<Bugzilla::BugUserLastVisit> for this bug and the supplied
$user, the timestamp given as $last_visit.

4660 4661
=back

4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737
=head1 B<Methods in need of POD>

=over

=item remove_cc

=item add_see_also

=item choices

=item keywords

=item blocked

=item qa_contact

=item add_comment

=item bug_severity

=item dup_id

=item set_priority

=item any_flags_requesteeble

=item set_bug_status

=item estimated_time

=item set_platform

=item statuses_available

=item set_custom_field

=item remove_see_also

=item remove_from_db

=item product_obj

=item reporter_accessible

=item set_summary

=item LogActivityEntry

=item set_assigned_to

=item add_group

=item bug_file_loc

=item DATE_COLUMNS

=item set_component

=item delta_ts

=item set_resolution

=item version

=item deadline

=item fields

=item dependson

=item check_can_change_field

=item update

=item set_op_sys

4738
=item object_cache_key
4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799

=item bug_group

=item comments

=item map_fields

=item assigned_to

=item user

=item ValidateDependencies

=item short_desc

=item duplicate_ids

=item isopened

=item remaining_time

=item set_deadline

=item preload

=item groups_in

=item clear_resolution

=item set_estimated_time

=item in_group

=item status

=item get_activity

=item reporter

=item rep_platform

=item DB_COLUMNS

=item flag_types

=item bug_status

=item attachments

=item flags

=item set_flags

=item actual_time

=item component

=item UPDATE_COLUMNS

=item set_cclist_accessible

4800 4801
=item set_bug_ignored

4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926
=item product

=item VALIDATORS

=item show_attachment_flags

=item set_comment_is_private

=item set_severity

=item send_changes

=item add_tag

=item bug_id

=item reset_qa_contact

=item remove_group

=item set_dup_id

=item set_target_milestone

=item cc_users

=item everconfirmed

=item check_is_visible

=item check_for_edit

=item match

=item VALIDATOR_DEPENDENCIES

=item possible_duplicates

=item set_url

=item add_cc

=item blocks_obj

=item set_status_whiteboard

=item product_id

=item error

=item reset_assigned_to

=item status_whiteboard

=item create

=item set_all

=item set_reporter_accessible

=item classification_id

=item tags

=item modify_keywords

=item priority

=item keyword_objects

=item set_dependencies

=item depends_on_obj

=item cclist_accessible

=item cc

=item duplicates

=item component_obj

=item see_also

=item groups

=item default_bug_status

=item related_bugs

=item editable_bug_fields

=item resolution

=item lastdiffed

=item classification

=item alias

=item op_sys

=item remove_tag

=item percentage_complete

=item EmitDependList

=item bug_alias_to_id

=item set_qa_contact

=item creation_ts

=item set_version

=item component_id

=item new_bug_statuses

=item set_remaining_time

=item target_milestone

=back