Bug.pm 131 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Dawn Endico    <endico@mozilla.org>
#                 Terry Weissman <terry@mozilla.org>
cyeh%bluemartini.com's avatar
cyeh%bluemartini.com committed
22
#                 Chris Yeh      <cyeh@bluemartini.com>
23 24
#                 Bradley Baetz  <bbaetz@acm.org>
#                 Dave Miller    <justdave@bugzilla.org>
25
#                 Max Kanat-Alexander <mkanat@bugzilla.org>
26
#                 Frédéric Buclin <LpSolit@gmail.com>
27
#                 Lance Larsh <lance.larsh@oracle.com>
28

29
package Bugzilla::Bug;
30

31 32
use strict;

33
use Bugzilla::Attachment;
34
use Bugzilla::Constants;
35
use Bugzilla::Field;
36 37
use Bugzilla::Flag;
use Bugzilla::FlagType;
38
use Bugzilla::Hook;
39
use Bugzilla::Keyword;
40
use Bugzilla::User;
41
use Bugzilla::Util;
42
use Bugzilla::Error;
43
use Bugzilla::Product;
44 45
use Bugzilla::Component;
use Bugzilla::Group;
46
use Bugzilla::Status;
47

48
use List::Util qw(min);
49
use Storable qw(dclone);
50 51
use URI;
use URI::QueryParam;
52

53
use base qw(Bugzilla::Object Exporter);
54
@Bugzilla::Bug::EXPORT = qw(
55
    bug_alias_to_id
56
    RemoveVotes CheckIfVotedConfirmed
57
    LogActivityEntry
58
    editable_bug_fields
59 60
);

61 62 63 64
#####################################################################
# Constants
#####################################################################

65 66 67 68 69 70 71 72
use constant DB_TABLE   => 'bugs';
use constant ID_FIELD   => 'bug_id';
use constant NAME_FIELD => 'alias';
use constant LIST_ORDER => ID_FIELD;

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

77
    my @columns = (qw(
78
        alias
79
        assigned_to
80 81 82 83 84 85 86 87 88 89 90 91
        bug_file_loc
        bug_id
        bug_severity
        bug_status
        cclist_accessible
        component_id
        delta_ts
        estimated_time
        everconfirmed
        op_sys
        priority
        product_id
92
        qa_contact
93 94 95 96 97 98 99 100 101 102 103 104
        remaining_time
        rep_platform
        reporter_accessible
        resolution
        short_desc
        status_whiteboard
        target_milestone
        version
    ),
    'reporter    AS reporter_id',
    $dbh->sql_date_format('creation_ts', '%Y.%m.%d %H:%i') . ' AS creation_ts',
    $dbh->sql_date_format('deadline', '%Y-%m-%d') . ' AS deadline',
105
    @custom_names);
106
    
107
    Bugzilla::Hook::process("bug-columns", { columns => \@columns });
108 109
    
    return @columns;
110 111
}

112 113 114 115 116 117 118 119 120
use constant REQUIRED_CREATE_FIELDS => qw(
    component
    product
    short_desc
    version
);

# There are also other, more complex validators that are called
# from run_create_validators.
121 122 123 124 125
sub VALIDATORS {
    my $validators = {
        alias          => \&_check_alias,
        bug_file_loc   => \&_check_bug_file_loc,
        bug_severity   => \&_check_bug_severity,
126 127
        comment        => \&_check_comment,
        commentprivacy => \&_check_commentprivacy,
128 129 130 131 132 133 134 135 136 137 138
        deadline       => \&_check_deadline,
        estimated_time => \&_check_estimated_time,
        op_sys         => \&_check_op_sys,
        priority       => \&_check_priority,
        product        => \&_check_product,
        remaining_time => \&_check_remaining_time,
        rep_platform   => \&_check_rep_platform,
        short_desc     => \&_check_short_desc,
        status_whiteboard => \&_check_status_whiteboard,
    };

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

163
    return $validators;
164 165
};

166
use constant UPDATE_VALIDATORS => {
167
    assigned_to         => \&_check_assigned_to,
168
    bug_status          => \&_check_bug_status,
169
    cclist_accessible   => \&Bugzilla::Object::check_boolean,
170
    dup_id              => \&_check_dup_id,
171
    everconfirmed       => \&Bugzilla::Object::check_boolean,
172
    qa_contact          => \&_check_qa_contact,
173
    reporter_accessible => \&Bugzilla::Object::check_boolean,
174 175 176
    resolution          => \&_check_resolution,
    target_milestone    => \&_check_target_milestone,
    version             => \&_check_version,
177 178
};

179
sub UPDATE_COLUMNS {
180 181
    my @custom = grep {$_->type != FIELD_TYPE_MULTI_SELECT}
                      Bugzilla->active_custom_fields;
182
    my @custom_names = map {$_->name} @custom;
183
    my @columns = qw(
184
        alias
185
        assigned_to
186 187 188
        bug_file_loc
        bug_severity
        bug_status
189
        cclist_accessible
190
        component_id
191 192
        deadline
        estimated_time
193 194 195
        everconfirmed
        op_sys
        priority
196
        product_id
197
        qa_contact
198
        remaining_time
199
        rep_platform
200
        reporter_accessible
201 202 203
        resolution
        short_desc
        status_whiteboard
204 205
        target_milestone
        version
206
    );
207
    push(@columns, @custom_names);
208 209
    return @columns;
};
210

211 212 213 214 215
use constant NUMERIC_COLUMNS => qw(
    estimated_time
    remaining_time
);

216 217 218 219 220 221
sub DATE_COLUMNS {
    my @fields = Bugzilla->get_fields(
        { custom => 1, type => FIELD_TYPE_DATETIME });
    return map { $_->name } @fields;
}

222 223 224 225 226 227 228 229 230 231
# This is used by add_comment to know what we validate before putting in
# the DB.
use constant UPDATE_COMMENT_COLUMNS => qw(
    thetext
    work_time
    type
    extra_data
    isprivate
);

232 233 234 235 236 237
# Used in LogActivityEntry(). Gives the max length of lines in the
# activity table.
use constant MAX_LINE_LENGTH => 254;

#####################################################################

238
sub new {
239 240 241 242
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
    my $param = shift;

243 244 245 246 247
    # Remove leading "#" mark if we've just been passed an id.
    if (!ref $param && $param =~ /^#(\d+)$/) {
        $param = $1;
    }

248 249
    # If we get something that looks like a word (not a number),
    # make it the "name" param.
250
    if (!defined $param || (!ref($param) && $param !~ /^\d+$/)) {
251
        # But only if aliases are enabled.
252
        if (Bugzilla->params->{'usebugaliases'} && $param) {
253 254 255 256 257 258 259 260 261 262
            $param = { name => $param };
        }
        else {
            # Aliases are off, and we got something that's not a number.
            my $error_self = {};
            bless $error_self, $class;
            $error_self->{'bug_id'} = $param;
            $error_self->{'error'}  = 'InvalidBugId';
            return $error_self;
        }
263 264
    }

265 266 267 268 269 270 271
    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 = {};
272 273 274 275 276 277 278 279
        if (ref $param) {
            $error_self->{bug_id} = $param->{name};
            $error_self->{error}  = 'InvalidBugId';
        }
        else {
            $error_self->{bug_id} = $param;
            $error_self->{error}  = 'NotFound';
        }
280 281
        bless $error_self, $class;
        return $error_self;
282
    }
283 284

    return $self;
285 286
}

287 288
sub check {
    my $class = shift;
289 290
    my ($id, $field) = @_;

291 292
    ThrowUserError('improper_bug_id_field_value', { field => $field }) unless defined $id;

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    # Bugzilla::Bug throws lots of special errors, so we don't call
    # SUPER::check, we just call our new and do our own checks.
    my $self = $class->new(trim($id));
    # For error messages, use the id that was returned by new(), because
    # it's cleaned up.
    $id = $self->id;

    if ($self->{error}) {
        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 });
        }
    }

311 312 313 314 315
    unless ($field && $field =~ /^(dependson|blocked|dup_id)$/) {
        $self->check_is_visible;
    }
    return $self;
}
316

317 318
sub check_is_visible {
    my $self = shift;
319
    my $user = Bugzilla->user;
320 321

    if (!$user->can_see_bug($self->id)) {
322 323 324
        # 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).
        if ($user->id) {
325
            ThrowUserError("bug_access_denied", { bug_id => $self->id });
326
        } else {
327
            ThrowUserError("bug_access_query", { bug_id => $self->id });
328 329
        }
    }
330 331
}

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
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(@_);
}

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
# 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.
#
# C<alias>        - An alias for this bug. Will be ignored if C<usebugaliases>
#                   is off.
# 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>.
430
sub create {
431
    my ($class, $params) = @_;
432 433
    my $dbh = Bugzilla->dbh;

434 435
    $dbh->bz_start_transaction();

436 437 438 439 440 441 442 443 444 445 446 447 448 449
    # 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);
450

451
    # These are not a fields in the bugs table, so we don't pass them to
452
    # insert_create_data.
453 454 455 456
    my $cc_ids     = delete $params->{cc};
    my $groups     = delete $params->{groups};
    my $depends_on = delete $params->{dependson};
    my $blocked    = delete $params->{blocked};
457 458 459
    my ($comment, $privacy) = ($params->{comment}, $params->{commentprivacy});
    delete $params->{comment};
    delete $params->{commentprivacy};
460

461 462 463 464 465
    # Set up the keyword cache for bug creation.
    my $keywords = $params->{keywords};
    $params->{keywords} = join(', ', sort {lc($a) cmp lc($b)} 
                                          map($_->name, @$keywords));

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

470
    my $ms_values = $class->_extract_multi_selects($params);
471 472
    my $bug = $class->insert_create_data($params);

473 474 475 476 477 478 479
    # Add the group restrictions
    my $sth_group = $dbh->prepare(
        'INSERT INTO bug_group_map (bug_id, group_id) VALUES (?, ?)');
    foreach my $group_id (@$groups) {
        $sth_group->execute($bug->bug_id, $group_id);
    }

480 481
    $dbh->do('UPDATE bugs SET creation_ts = ? WHERE bug_id = ?', undef,
             $timestamp, $bug->bug_id);
482 483
    # Update the bug instance as well
    $bug->{creation_ts} = $timestamp;
484

485
    # Add the CCs
486 487 488 489 490
    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);
    }

491 492 493 494 495 496 497
    # 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);
    }

498 499 500
    # Set up dependencies (blocked/dependson)
    my $sth_deps = $dbh->prepare(
        'INSERT INTO dependencies (blocked, dependson) VALUES (?, ?)');
501 502
    my $sth_bug_time = $dbh->prepare('UPDATE bugs SET delta_ts = ? WHERE bug_id = ?');

503 504 505 506
    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,
507
                         $bug->{reporter_id}, $timestamp);
508
        $sth_bug_time->execute($timestamp, $depends_on_id);
509 510 511 512 513
    }
    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,
514
                         $bug->{reporter_id}, $timestamp);
515
        $sth_bug_time->execute($timestamp, $blocked_id);
516 517
    }

518 519 520 521 522 523 524 525 526 527
    # 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);
        }
    }

528 529
    # And insert the comment. We always insert a comment on bug creation,
    # but sometimes it's blank.
530 531 532 533 534 535 536 537 538 539 540 541
    my @columns = qw(bug_id who bug_when thetext);
    my @values  = ($bug->bug_id, $bug->{reporter_id}, $timestamp, $comment);
    # We don't include the "isprivate" column unless it was specified. 
    # This allows it to fall back to its database default.
    if (defined $privacy) {
        push(@columns, 'isprivate');
        push(@values, $privacy);
    }
    my $qmarks = "?," x @columns;
    chop($qmarks);
    $dbh->do('INSERT INTO longdescs (' . join(',', @columns)  . ")
                   VALUES ($qmarks)", undef, @values);
542

543 544 545 546
    Bugzilla::Hook::process('bug-end_of_create', { bug => $bug,
                                                   timestamp => $timestamp,
                                                 });

547 548 549 550 551 552
    $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.
    $bug->_sync_fulltext('new bug');
553

554 555 556
    return $bug;
}

557 558 559

sub run_create_validators {
    my $class  = shift;
560
    my $params = $class->SUPER::run_create_validators(@_);
561

562
    my $product = $params->{product};
563 564 565 566
    $params->{product_id} = $product->id;
    delete $params->{product};

    ($params->{bug_status}, $params->{everconfirmed})
567 568
        = $class->_check_bug_status($params->{bug_status}, $product,
                                    $params->{comment});
569

570 571
    $params->{target_milestone} = $class->_check_target_milestone(
        $params->{target_milestone}, $product);
572

573
    $params->{version} = $class->_check_version($params->{version}, $product);
574

575
    $params->{keywords} = $class->_check_keywords($params->{keywords}, $product);
576

577 578 579
    $params->{groups} = $class->_check_groups($product,
        $params->{groups});

580
    my $component = $class->_check_component($params->{component}, $product);
581 582 583 584
    $params->{component_id} = $component->id;
    delete $params->{component};

    $params->{assigned_to} = 
585
        $class->_check_assigned_to($params->{assigned_to}, $component);
586
    $params->{qa_contact} =
587
        $class->_check_qa_contact($params->{qa_contact}, $component);
588 589
    $params->{cc} = $class->_check_cc($component, $params->{cc});

590
    # Callers cannot set Reporter, currently.
591
    $params->{reporter} = $class->_check_reporter();
592

593
    $params->{creation_ts} ||= Bugzilla->dbh->selectrow_array('SELECT NOW()');
594
    $params->{delta_ts} = $params->{creation_ts};
595 596 597 598

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

600 601
    $class->_check_strict_isolation($params->{cc}, $params->{assigned_to},
                                    $params->{qa_contact}, $product);
602

603
    ($params->{dependson}, $params->{blocked}) = 
604 605
        $class->_check_dependencies($params->{dependson}, $params->{blocked},
                                    $product);
606

607 608 609 610 611 612
    # You can't set these fields on bug creation (or sometimes ever).
    delete $params->{resolution};
    delete $params->{votes};
    delete $params->{lastdiffed};
    delete $params->{bug_id};

613
    return $params;
614 615
}

616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
sub set_all {
    my ($self, $args) = @_;

    # For security purposes, and because lots of other checks depend on it,
    # we set the product first before anything else.
    my $product_change = 0;
    if ($args->{product}) {
        my $changed = $self->set_product($args->{product},
                                        { component => $args->{component},
                                          version   => $args->{version},
                                          target_milestone => $args->{target_milestone},
                                          change_confirmed => $args->{confirm_product_change},
                                          other_bugs => $args->{other_bugs},
                                        });
        # that will be used later to check strict isolation
        $product_change = $changed;
    }

    # add/remove groups
    $self->remove_group($_) foreach @{$args->{remove_group}};
    $self->add_group($_) foreach @{$args->{add_group}};

    # this is temporary until all related code is moved from
    # process_bug.cgi to set_all
    return $product_change;
}

643 644 645
sub update {
    my $self = shift;

646
    my $dbh = Bugzilla->dbh;
647 648
    # XXX This is just a temporary hack until all updating happens
    # inside this function.
649 650
    my $delta_ts = shift || $dbh->selectrow_array("SELECT NOW()");

651
    my ($changes, $old_bug) = $self->SUPER::update(@_);
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672

    # 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];
        }
    }

673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
    # 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];
    }
    
    # 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);
    }
    $dbh->do('UPDATE bugs SET keywords = ? WHERE bug_id = ?', undef,
             $self->keywords, $self->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, '',
                             Bugzilla->user->id, $delta_ts);
            # 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,
                             Bugzilla->user->id, $delta_ts);
            # 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
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
    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)];
    }
    
778
    # Comments
779 780 781 782 783 784 785
    foreach my $comment (@{$self->{added_comments} || []}) {
        my $columns = join(',', keys %$comment);
        my @values  = values %$comment;
        my $qmarks  = join(',', ('?') x @values);
        $dbh->do("INSERT INTO longdescs (bug_id, who, bug_when, $columns)
                       VALUES (?,?,?,$qmarks)", undef,
                 $self->bug_id, Bugzilla->user->id, $delta_ts, @values);
786 787 788 789
        if ($comment->{work_time}) {
            LogActivityEntry($self->id, "work_time", "", $comment->{work_time},
                Bugzilla->user->id, $delta_ts);
        }
790
    }
791 792 793 794 795 796
    
    foreach my $comment_id (keys %{$self->{comment_isprivate} || {}}) {
        $dbh->do("UPDATE longdescs SET isprivate = ? WHERE comment_id = ?",
                 undef, $self->{comment_isprivate}->{$comment_id}, $comment_id);
        # XXX It'd be nice to track this in the bug activity.
    }
797

798
    # Insert the values into the multiselect value tables
799 800
    my @multi_selects = grep {$_->type == FIELD_TYPE_MULTI_SELECT}
                             Bugzilla->active_custom_fields;
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
    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);
            }
        }
    }

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
    # See Also
    my ($removed_see, $added_see) = 
        diff_arrays($old_bug->see_also, $self->see_also);

    if (scalar @$removed_see) {
        $dbh->do('DELETE FROM bug_see_also WHERE bug_id = ? AND '
                 . $dbh->sql_in('value', [('?') x @$removed_see]),
                  undef, $self->id, @$removed_see);
    }
    foreach my $url (@$added_see) {
        $dbh->do('INSERT INTO bug_see_also (bug_id, value) VALUES (?,?)',
                 undef, $self->id, $url);
    }
    # If any changes were found, record it in the activity log
    if (scalar @$removed_see || scalar @$added_see) {
        $changes->{see_also} = [join(', ', @$removed_see),
                                join(', ', @$added_see)];
    }

835 836 837 838 839
    # 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};
840 841 842 843
        my $from = defined $change->[0] ? $change->[0] : '';
        my $to   = defined $change->[1] ? $change->[1] : '';
        LogActivityEntry($self->id, $field, $from, $to, Bugzilla->user->id,
                         $delta_ts);
844 845
    }

846 847 848
    # 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) {
849
        $dbh->do("DELETE FROM duplicates WHERE dupe = ?", undef, $self->id);
850 851 852 853 854 855 856 857 858
        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();
            }
        }
        
        $changes->{'dup_id'} = [$old_dup || undef, $cur_dup || undef];
859 860
    }

861 862 863 864 865
    Bugzilla::Hook::process('bug-end_of_update', { bug       => $self,
                                                   timestamp => $delta_ts,
                                                   changes   => $changes,
                                                 });

866 867 868 869
    # If any change occurred, refresh the timestamp of the bug.
    if (scalar(keys %$changes) || $self->{added_comments}) {
        $dbh->do('UPDATE bugs SET delta_ts = ? WHERE bug_id = ?',
                 undef, ($delta_ts, $self->id));
870
        $self->{delta_ts} = $delta_ts;
871 872
    }

873 874 875 876 877 878 879
    # 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.
    $self->_sync_fulltext()
        if $self->{added_comments} || $changes->{short_desc};

880 881 882 883
    # Remove obsolete internal variables.
    delete $self->{'_old_assigned_to'};
    delete $self->{'_old_qa_contact'};

884 885 886 887
    # Also flush the visible_bugs cache for this bug as the user's
    # relationship with this bug may have changed.
    delete Bugzilla->user->{_visible_bugs_cache}->{$self->id};

888 889 890
    return $changes;
}

891 892 893 894 895 896
# 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) = @_;

897 898
    my @multi_selects = grep {$_->type == FIELD_TYPE_MULTI_SELECT}
                             Bugzilla->active_custom_fields;
899 900 901 902 903 904 905 906 907 908 909
    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;
}

910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
# Should be called any time you update short_desc or change a comment.
sub _sync_fulltext {
    my ($self, $new_bug) = @_;
    my $dbh = Bugzilla->dbh;
    if ($new_bug) {
        $dbh->do('INSERT INTO bugs_fulltext (bug_id, short_desc)
                  SELECT bug_id, short_desc FROM bugs WHERE bug_id = ?',
                 undef, $self->id);
    }
    else {
        $dbh->do('UPDATE bugs_fulltext SET short_desc = ? WHERE bug_id = ?',
                 undef, $self->short_desc, $self->id);
    }
    my $comments = $dbh->selectall_arrayref(
        'SELECT thetext, isprivate FROM longdescs WHERE bug_id = ?',
        undef, $self->id);
    my $all = join("\n", map { $_->[0] } @$comments);
    my @no_private = grep { !$_->[1] } @$comments;
    my $nopriv_string = join("\n", map { $_->[0] } @no_private);
    $dbh->do('UPDATE bugs_fulltext SET comments = ?, comments_noprivate = ?
               WHERE bug_id = ?', undef, $all, $nopriv_string, $self->id);
}


934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
# This is the correct way to delete bugs from the DB.
# No bug should be deleted from anywhere else except from here.
#
sub remove_from_db {
    my ($self) = @_;
    my $dbh = Bugzilla->dbh;

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

    my $bug_id = $self->{'bug_id'};

    # tables having 'bugs.bug_id' as a foreign key:
    # - attachments
    # - bug_group_map
    # - bugs
    # - bugs_activity
952
    # - bugs_fulltext
953 954 955 956 957 958 959 960
    # - cc
    # - dependencies
    # - duplicates
    # - flags
    # - keywords
    # - longdescs
    # - votes

961 962 963
    # Also, the attach_data table uses attachments.attach_id as a foreign
    # key, and so indirectly depends on a bug deletion too.

964
    $dbh->bz_start_transaction();
965 966 967 968 969 970 971 972 973 974 975

    $dbh->do("DELETE FROM bug_group_map WHERE bug_id = ?", undef, $bug_id);
    $dbh->do("DELETE FROM bugs_activity WHERE bug_id = ?", undef, $bug_id);
    $dbh->do("DELETE FROM cc WHERE bug_id = ?", undef, $bug_id);
    $dbh->do("DELETE FROM dependencies WHERE blocked = ? OR dependson = ?",
             undef, ($bug_id, $bug_id));
    $dbh->do("DELETE FROM duplicates WHERE dupe = ? OR dupe_of = ?",
             undef, ($bug_id, $bug_id));
    $dbh->do("DELETE FROM flags WHERE bug_id = ?", undef, $bug_id);
    $dbh->do("DELETE FROM keywords WHERE bug_id = ?", undef, $bug_id);
    $dbh->do("DELETE FROM votes WHERE bug_id = ?", undef, $bug_id);
976 977 978 979 980 981 982

    # The attach_data table doesn't depend on bugs.bug_id directly.
    my $attach_ids =
        $dbh->selectcol_arrayref("SELECT attach_id FROM attachments
                                  WHERE bug_id = ?", undef, $bug_id);

    if (scalar(@$attach_ids)) {
983 984
        $dbh->do("DELETE FROM attach_data WHERE " 
                 . $dbh->sql_in('id', $attach_ids));
985 986
    }

987 988 989
    # Several of the previous tables also depend on attach_id.
    $dbh->do("DELETE FROM attachments WHERE bug_id = ?", undef, $bug_id);
    $dbh->do("DELETE FROM bugs WHERE bug_id = ?", undef, $bug_id);
990
    $dbh->do("DELETE FROM longdescs WHERE bug_id = ?", undef, $bug_id);
991

992 993
    $dbh->bz_commit_transaction();

994 995 996
    # The bugs_fulltext table doesn't support transactions.
    $dbh->do("DELETE FROM bugs_fulltext WHERE bug_id = ?", undef, $bug_id);

997 998 999 1000 1001
    # Now this bug no longer exists
    $self->DESTROY;
    return $self;
}

1002 1003 1004 1005 1006
#####################################################################
# Validators
#####################################################################

sub _check_alias {
1007
   my ($invocant, $alias) = @_;
1008
   $alias = trim($alias);
1009
   return undef if (!Bugzilla->params->{'usebugaliases'} || !$alias);
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031

    # Make sure the alias isn't too long.
    if (length($alias) > 20) {
        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 });
    }

1032 1033 1034 1035
   return $alias;
}

sub _check_assigned_to {
1036
    my ($invocant, $assignee, $component) = @_;
1037 1038 1039 1040
    my $user = Bugzilla->user;

    # Default assignee is the component owner.
    my $id;
1041 1042 1043 1044 1045
    # 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))
    {
1046 1047
        $id = $component->default_assignee->id;
    } else {
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
        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;
1058 1059 1060 1061 1062
    }
    return $id;
}

sub _check_bug_file_loc {
1063
    my ($invocant, $url) = @_;
1064 1065 1066 1067 1068 1069 1070
    $url = '' if !defined($url);
    # 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 = '';
    }
1071 1072 1073
    return $url;
}

1074
sub _check_bug_severity {
1075
    my ($invocant, $severity) = @_;
1076 1077 1078 1079 1080
    $severity = trim($severity);
    check_field('bug_severity', $severity);
    return $severity;
}

1081
sub _check_bug_status {
1082
    my ($invocant, $new_status, $product, $comment) = @_;
1083
    my $user = Bugzilla->user;
1084
    my @valid_statuses;
1085
    my $old_status; # Note that this is undef for new bugs.
1086

1087
    if (ref $invocant) {
1088
        @valid_statuses = @{$invocant->status->can_change_to};
1089
        $product = $invocant->product_obj;
1090 1091 1092
        $old_status = $invocant->status;
        my $comments = $invocant->{added_comments} || [];
        $comment = $comments->[-1];
1093
    }
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
    else {
        @valid_statuses = @{Bugzilla::Status->can_change_to()};
    }

    if (!$product->votes_to_confirm) {
        # UNCONFIRMED becomes an invalid status if votes_to_confirm is 0,
        # even if you are in editbugs.
        @valid_statuses = grep {$_->name ne 'UNCONFIRMED'} @valid_statuses;
    }

1104 1105
    # Check permissions for users filing new bugs.
    if (!ref $invocant) {
1106 1107
        if ($user->in_group('editbugs', $product->id)
            || $user->in_group('canconfirm', $product->id)) {
1108 1109
            # If the user with privs hasn't selected another status,
            # select the first one of the list.
1110 1111 1112 1113 1114 1115 1116 1117 1118
            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];
                }
            }
1119 1120
        }
        else {
1121
            # A user with no privs cannot choose the initial status.
1122 1123
            # If UNCONFIRMED is valid for this product, use it; else
            # use the first bug status available.
1124 1125 1126 1127 1128 1129
            if (grep {$_->name eq 'UNCONFIRMED'} @valid_statuses) {
                $new_status = 'UNCONFIRMED';
            }
            else {
                $new_status = $valid_statuses[0];
            }
1130
        }
1131
    }
1132 1133 1134 1135 1136
    # Time to validate the bug status.
    $new_status = Bugzilla::Status->check($new_status) unless ref($new_status);
    if (!grep {$_->name eq $new_status->name} @valid_statuses) {
        ThrowUserError('illegal_bug_status_transition',
                       { old => $old_status, new => $new_status });
1137
    }
1138

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    # Check if a comment is required for this change.
    if ($new_status->comment_required_on_change_from($old_status) && !$comment)
    {
        ThrowUserError('comment_required', { old => $old_status,
                                             new => $new_status });
        
    }
    
    if (ref $invocant && $new_status->name eq 'ASSIGNED'
        && 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 });
    }

    return $new_status->name if ref $invocant;
1159
    return ($new_status->name, $new_status->name eq 'UNCONFIRMED' ? 0 : 1);
1160 1161
}

1162
sub _check_cc {
1163
    my ($invocant, $component, $ccs) = @_;
1164
    return [map {$_->id} @{$component->initial_cc}] unless $ccs;
1165 1166 1167 1168 1169 1170 1171

    my %cc_ids;
    foreach my $person (@$ccs) {
        next unless $person;
        my $id = login_to_id($person, THROW_ERROR);
        $cc_ids{$id} = 1;
    }
1172 1173 1174 1175

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

1176 1177 1178
    return [keys %cc_ids];
}

1179
sub _check_comment {
1180
    my ($invocant, $comment) = @_;
1181

1182
    $comment = '' unless defined $comment;
1183 1184 1185 1186 1187 1188

    # Remove any trailing whitespace. Leading whitespace could be
    # a valid part of the comment.
    $comment =~ s/\s*$//s;
    $comment =~ s/\r\n?/\n/g; # Get rid of \r.

1189
    ThrowUserError('comment_too_long') if length($comment) > MAX_COMMENT_LENGTH;
1190 1191 1192
    return $comment;
}

1193 1194
sub _check_commentprivacy {
    my ($invocant, $comment_privacy) = @_;
1195 1196 1197 1198
    if ($comment_privacy && !Bugzilla->user->is_insider) {
        ThrowUserError('user_not_insider');
    }
    return $comment_privacy ? 1 : 0;
1199 1200
}

1201 1202 1203 1204 1205 1206 1207 1208
sub _check_comment_type {
    my ($invocant, $type) = @_;
    detaint_natural($type)
      || ThrowCodeError('bad_arg', { argument => 'type', 
                                     function => caller });
    return $type;
}

1209
sub _check_component {
1210
    my ($invocant, $name, $product) = @_;
1211 1212
    $name = trim($name);
    $name || ThrowUserError("require_component");
1213
    ($product = $invocant->product_obj) if ref $invocant;
1214
    my $obj = Bugzilla::Component->check({ product => $product, name => $name });
1215 1216 1217
    return $obj;
}

1218
sub _check_deadline {
1219
    my ($invocant, $date) = @_;
1220 1221
    
    # Check time-tracking permissions.
1222
    my $tt_group = Bugzilla->params->{"timetrackinggroup"};
1223 1224
    # deadline() returns '' instead of undef if no deadline is set.
    my $current = ref $invocant ? ($invocant->deadline || undef) : undef;
1225 1226 1227 1228 1229
    return $current unless $tt_group && Bugzilla->user->in_group($tt_group);
    
    # Validate entered deadline
    $date = trim($date);
    return undef if !$date;
1230 1231 1232 1233 1234 1235
    validate_date($date)
        || ThrowUserError('illegal_date', { date   => $date,
                                            format => 'YYYY-MM-DD' });
    return $date;
}

1236 1237 1238
# Takes two comma/space-separated strings and returns arrayrefs
# of valid bug IDs.
sub _check_dependencies {
1239 1240 1241 1242 1243 1244
    my ($invocant, $depends_on, $blocks, $product) = @_;

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

1247 1248 1249
    my %deps_in = (dependson => $depends_on || '', blocked => $blocks || '');

    foreach my $type qw(dependson blocked) {
1250 1251 1252
        my @bug_ids = ref($deps_in{$type}) 
            ? @{$deps_in{$type}} 
            : split(/[\s,]+/, $deps_in{$type});
1253 1254
        # Eliminate nulls.
        @bug_ids = grep {$_} @bug_ids;
1255 1256
        # We do this up here to make sure all aliases are converted to IDs.
        @bug_ids = map { $invocant->check($_, $type)->id } @bug_ids;
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
       
        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) {
1278
            my $delta_bug = $invocant->check($modified_id);
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
            # 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});
                }
            }
        }
        
        $deps_in{$type} = \@bug_ids;
    }
1290

1291
    # And finally, check for dependency loops.
1292 1293
    my $bug_id = ref($invocant) ? $invocant->id : 0;
    my %deps = ValidateDependencies($deps_in{dependson}, $deps_in{blocked}, $bug_id);
1294 1295 1296 1297

    return ($deps{'dependson'}, $deps{'blocked'});
}

1298 1299 1300 1301 1302 1303
sub _check_dup_id {
    my ($self, $dupe_of) = @_;
    my $dbh = Bugzilla->dbh;
    
    $dupe_of = trim($dupe_of);
    $dupe_of || ThrowCodeError('undefined_field', { field => 'dup_id' });
1304 1305 1306
    # 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.
1307
    my $dupe_of_bug = $self->check($dupe_of, 'dup_id');
1308
    $dupe_of = $dupe_of_bug->id;
1309 1310 1311 1312 1313 1314 1315 1316

    # 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).
    $dupe_of_bug->check_is_visible;

1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
    # Make sure a loop isn't created when marking this bug
    # as duplicate.
    my %dupes;
    my $this_dup = $dupe_of;
    my $sth = $dbh->prepare('SELECT dupe_of FROM duplicates WHERE dupe = ?');

    while ($this_dup) {
        if ($this_dup == $self->id) {
            ThrowUserError('dupe_loop_detected', { bug_id  => $self->id,
                                                   dupe_of => $dupe_of });
        }
        # 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
        # prevent him from marking this bug as a duplicate.
        last if exists $dupes{$this_dup};
        $dupes{$this_dup} = 1;
        $this_dup = $dbh->selectrow_array($sth, undef, $this_dup);
    }

    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?
    # If he can see the bug...
    if ($self->reporter->can_see_bug($dupe_of)) {
        # We only add him if he's not the reporter of the other bug.
        $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.
1354
    elsif (Bugzilla->usage_mode == USAGE_MODE_BROWSER) {
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
        # 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 {
            # Note that here we don't check if he user is already the reporter
            # of the dupe_of bug, since we already checked if he can *see*
            # the bug, above. People might have reporter_accessible turned
            # off, but cclist_accessible turned on, so they might want to
            # add the reporter even though he's already the reporter of the
            # dup_of bug.
            my $vars = {};
            my $template = Bugzilla->template;
            # Ask the user what they want to do about the reporter.
1371
            $vars->{'cclist_accessible'} = $dupe_of_bug->cclist_accessible;
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
            $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;
}

1384
sub _check_estimated_time {
1385
    return $_[0]->_check_time($_[1], 'estimated_time');
1386 1387
}

1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
sub _check_groups {
    my ($invocant, $product, $group_ids) = @_;

    my $user = Bugzilla->user;

    my %add_groups;
    my $controls = $product->group_controls;

    foreach my $id (@$group_ids) {
        my $group = new Bugzilla::Group($id)
            || ThrowUserError("invalid_group_ID");

        # This can only happen if somebody hacked the enter_bug form.
        ThrowCodeError("inactive_group", { name => $group->name })
            unless $group->is_active;

        my $membercontrol = $controls->{$id}
                            && $controls->{$id}->{membercontrol};
        my $othercontrol  = $controls->{$id} 
                            && $controls->{$id}->{othercontrol};
        
        my $permit = ($membercontrol && $user->in_group($group->name))
                     || $othercontrol;

        $add_groups{$id} = 1 if $permit;
    }

    foreach my $id (keys %$controls) {
1416
        next unless $controls->{$id}->{'group'}->is_active;
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
        my $membercontrol = $controls->{$id}->{membercontrol} || 0;
        my $othercontrol  = $controls->{$id}->{othercontrol}  || 0;

        # Add groups required
        if ($membercontrol == CONTROLMAPMANDATORY
            || ($othercontrol == CONTROLMAPMANDATORY
                && !$user->in_group_id($id))) 
        {
            # User had no option, bug needs to be in this group.
            $add_groups{$id} = 1;
        }
    }

    my @add_groups = keys %add_groups;
    return \@add_groups;
}

1434
sub _check_keywords {
1435
    my ($invocant, $keyword_string, $product) = @_;
1436
    $keyword_string = trim($keyword_string);
1437 1438 1439 1440 1441 1442 1443
    return [] if !$keyword_string;
    
    # On creation, only editbugs users can set keywords.
    if (!ref $invocant) {
        return [] if !Bugzilla->user->in_group('editbugs', $product->id);
    }
    
1444
    my %keywords;
1445 1446 1447 1448
    foreach my $keyword (split(/[\s,]+/, $keyword_string)) {
        next unless $keyword;
        my $obj = new Bugzilla::Keyword({ name => $keyword });
        ThrowUserError("unknown_keyword", { keyword => $keyword }) if !$obj;
1449
        $keywords{$obj->id} = $obj;
1450
    }
1451
    return [values %keywords];
1452 1453
}

1454
sub _check_product {
1455
    my ($invocant, $name) = @_;
1456 1457 1458 1459 1460
    $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;
1461
    }
1462 1463 1464 1465 1466 1467
    # Check that the product exists and that the user
    # is allowed to enter bugs into this product.
    Bugzilla->user->can_enter_product($name, THROW_ERROR);
    # can_enter_product already does everything that check_product
    # would do for us, so we don't need to use it.
    return new Bugzilla::Product({ name => $name });
1468 1469
}

1470
sub _check_op_sys {
1471
    my ($invocant, $op_sys) = @_;
1472 1473 1474 1475 1476 1477
    $op_sys = trim($op_sys);
    check_field('op_sys', $op_sys);
    return $op_sys;
}

sub _check_priority {
1478
    my ($invocant, $priority) = @_;
1479
    if (!ref $invocant && !Bugzilla->params->{'letsubmitterchoosepriority'}) {
1480 1481 1482 1483 1484 1485 1486 1487
        $priority = Bugzilla->params->{'defaultpriority'};
    }
    $priority = trim($priority);
    check_field('priority', $priority);

    return $priority;
}

1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
sub _check_qa_contact {
    my ($invocant, $qa_contact, $component) = @_;
    $qa_contact = trim($qa_contact) if !ref $qa_contact;
    
    my $id;
    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)
        {
            $id = $component->default_qa_contact->id;
        }
    }
    
    # If a QA Contact was specified or if we're updating, check
    # the QA Contact for validity.
    if (!defined $id && $qa_contact) {
        $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().
1512
        # If there is no QA contact, this check is not required.
1513
        $invocant->_check_strict_isolation_for_user($qa_contact)
1514
            if (ref $invocant && $id);
1515 1516 1517 1518 1519 1520
    }

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

1521
sub _check_remaining_time {
1522
    return $_[0]->_check_time($_[1], 'remaining_time');
1523 1524
}

1525
sub _check_rep_platform {
1526
    my ($invocant, $platform) = @_;
1527 1528 1529 1530 1531
    $platform = trim($platform);
    check_field('rep_platform', $platform);
    return $platform;
}

1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
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
        # (meaning that he must be logged in first!).
        $reporter = Bugzilla->user->id;
        $reporter || ThrowCodeError('invalid_user');
    }
    return $reporter;
}

1548
sub _check_resolution {
1549
    my ($self, $resolution) = @_;
1550
    $resolution = trim($resolution);
1551 1552 1553 1554 1555 1556 1557 1558
    
    # 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).
    ThrowUserError('missing_resolution', { status => $self->status->name })
        if !$resolution && !$self->status->is_open;
    
    # Make sure this is a valid resolution.
1559
    check_field('resolution', $resolution);
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582

    # Don't allow open bugs to have resolutions.
    ThrowUserError('resolution_not_allowed') if $self->status->is_open;
    
    # Check noresolveonopenblockers.
    if (Bugzilla->params->{"noresolveonopenblockers"} && $resolution eq 'FIXED')
    {
        my @dependencies = CountOpenDependencies($self->id);
        if (@dependencies) {
            ThrowUserError("still_unresolved_bugs",
                           { dependencies     => \@dependencies,
                             dependency_count => scalar @dependencies });
        }
    }

    # Check if they're changing the resolution and need to comment.
    if (Bugzilla->params->{'commentonchange_resolution'} 
        && $self->resolution && $resolution ne $self->resolution 
        && !$self->{added_comments})
    {
        ThrowUserError('comment_required');
    }
    
1583 1584 1585
    return $resolution;
}

1586
sub _check_short_desc {
1587
    my ($invocant, $short_desc) = @_;
1588 1589 1590 1591 1592 1593 1594 1595 1596
    # 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");
    }
    return $short_desc;
}

1597
sub _check_status_whiteboard { return defined $_[1] ? $_[1] : ''; }
1598

1599 1600
# Unlike other checkers, this one doesn't return anything.
sub _check_strict_isolation {
1601
    my ($invocant, $ccs, $assignee, $qa_contact, $product) = @_;
1602 1603
    return unless Bugzilla->params->{'strict_isolation'};

1604 1605 1606 1607 1608 1609 1610 1611 1612
    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);
1613 1614
        $ccs = Bugzilla::User->new_from_list($added);

1615 1616
        $assignee = $invocant->assigned_to
            if $invocant->assigned_to->id != $original->assigned_to->id;
1617 1618 1619 1620 1621 1622
        if ($invocant->qa_contact
            && (!$original->qa_contact
                || $invocant->qa_contact->id != $original->qa_contact->id))
        {
            $qa_contact = $invocant->qa_contact;
        }
1623
        $product = $invocant->product_obj;
1624 1625 1626 1627
    }

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

1629 1630
    if (Bugzilla->params->{'useqacontact'} && $qa_contact) {
        push(@related_users, $qa_contact);
1631 1632
    }

1633 1634 1635
    @related_users = @{Bugzilla::User->new_from_list(\@related_users)}
        if !ref $invocant;

1636 1637
    # For each unique user in @related_users...(assignee and qa_contact
    # could be duplicates of users in the CC list)
1638
    my %unique_users = map {$_->id => $_} @related_users;
1639
    my @blocked_users;
1640 1641
    foreach my $id (keys %unique_users) {
        my $related_user = $unique_users{$id};
1642
        if (!$related_user->can_edit_product($product->id) ||
1643
            !$related_user->can_see_product($product->name)) {
1644 1645 1646 1647
            push (@blocked_users, $related_user->login);
        }
    }
    if (scalar(@blocked_users)) {
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
        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 });
1669 1670 1671
    }
}

1672
sub _check_target_milestone {
1673 1674 1675
    my ($invocant, $target, $product) = @_;
    $product = $invocant->product_obj if ref $invocant;

1676 1677 1678 1679 1680 1681 1682 1683
    $target = trim($target);
    $target = $product->default_milestone if !defined $target;
    check_field('target_milestone', $target,
            [map($_->name, @{$product->milestones})]);
    return $target;
}

sub _check_time {
1684
    my ($invocant, $time, $field) = @_;
1685 1686 1687 1688 1689

    my $current = 0;
    if (ref $invocant && $field ne 'work_time') {
        $current = $invocant->$field;
    }
1690
    my $tt_group = Bugzilla->params->{"timetrackinggroup"};
1691 1692
    return $current unless $tt_group && Bugzilla->user->in_group($tt_group);
    
1693 1694 1695 1696 1697 1698
    $time = trim($time) || 0;
    ValidateTime($time, $field);
    return $time;
}

sub _check_version {
1699
    my ($invocant, $version, $product) = @_;
1700
    $version = trim($version);
1701
    ($product = $invocant->product_obj) if ref $invocant;
1702 1703 1704 1705
    check_field('version', $version, [map($_->name, @{$product->versions})]);
    return $version;
}

1706 1707 1708 1709
sub _check_work_time {
    return $_[0]->_check_time($_[1], 'work_time');
}

1710 1711
# Custom Field Validators

1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
sub _check_datetime_field {
    my ($invocant, $date_time) = @_;

    # 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' });
    }
    if ($time && !validate_time($time)) {
        ThrowUserError('illegal_time', { 'time' => $time,
                                         format => 'HH:MM:SS' });
    }
    return $date_time
}

1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
sub _check_default_field { return defined $_[1] ? trim($_[1]) : ''; }

sub _check_freetext_field {
    my ($invocant, $text) = @_;

    $text = (defined $text) ? trim($text) : '';
    if (length($text) > MAX_FREETEXT_LENGTH) {
        ThrowUserError('freetext_too_long', { text => $text });
    }
    return $text;
}

1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
sub _check_multi_select_field {
    my ($invocant, $values, $field) = @_;
    return [] if !$values;
    foreach my $value (@$values) {
        $value = trim($value);
        check_field($field, $value);
        trick_taint($value);
    }
    return $values;
}

1757 1758 1759 1760 1761 1762
sub _check_select_field {
    my ($invocant, $value, $field) = @_;
    $value = trim($value);
    check_field($field, $value);
    return $value;
}
1763

1764 1765 1766 1767 1768 1769
sub _check_bugid_field {
    my ($invocant, $value, $field) = @_;
    return undef if !$value;
    return $invocant->check($value, $field)->id;
}

1770
#####################################################################
1771 1772 1773 1774 1775 1776
# Class Accessors
#####################################################################

sub fields {
    my $class = shift;

1777 1778
   my @fields =
   (
1779 1780 1781 1782 1783 1784
        # 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
1785
           bug_status resolution dup_id see_also
1786 1787
           bug_file_loc status_whiteboard keywords
           priority bug_severity target_milestone
1788
           dependson blocked votes everconfirmed
1789 1790 1791
           reporter assigned_to cc estimated_time
           remaining_time actual_time deadline),

1792
        # Conditional Fields
1793
        Bugzilla->params->{'useqacontact'} ? "qa_contact" : (),
1794
        # Custom Fields
1795
        map { $_->name } Bugzilla->active_custom_fields
1796
    );
1797 1798 1799
    Bugzilla::Hook::process("bug-fields", {'fields' => \@fields} );
    
    return @fields;
1800 1801
}

1802 1803 1804 1805
#####################################################################
# Mutators 
#####################################################################

1806 1807 1808
# To run check_can_change_field.
sub _set_global_validator {
    my ($self, $value, $field) = @_;
1809
    my $current = $self->$field;
1810
    my $privs;
1811 1812 1813 1814 1815 1816 1817 1818 1819

    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 ;
    }
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
    my $can = $self->check_can_change_field($field, $current, $value, \$privs);
    if (!$can) {
        if ($field eq 'assigned_to' || $field eq 'qa_contact') {
            $value   = user_id_to_login($value);
            $current = user_id_to_login($current);
        }
        ThrowUserError('illegal_change', { field    => $field,
                                           oldvalue => $current,
                                           newvalue => $value,
                                           privs    => $privs });
    }
1831 1832 1833
}


1834 1835 1836 1837
#################
# "Set" Methods #
#################

1838
sub set_alias { $_[0]->set('alias', $_[1]); }
1839 1840 1841
sub set_assigned_to {
    my ($self, $value) = @_;
    $self->set('assigned_to', $value);
1842 1843
    # Store the old assignee. check_can_change_field() needs it.
    $self->{'_old_assigned_to'} = $self->{'assigned_to_obj'}->id;
1844 1845 1846 1847 1848 1849 1850
    delete $self->{'assigned_to_obj'};
}
sub reset_assigned_to {
    my $self = shift;
    my $comp = $self->component_obj;
    $self->set_assigned_to($comp->default_assignee);
}
1851
sub set_cclist_accessible { $_[0]->set('cclist_accessible', $_[1]); }
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
sub set_comment_is_private {
    my ($self, $comment_id, $isprivate) = @_;
    return unless Bugzilla->user->is_insider;
    my ($comment) = grep($comment_id eq $_->{id}, @{$self->longdescs});
    ThrowUserError('comment_invalid_isprivate', { id => $comment_id }) 
        if !$comment;

    $isprivate = $isprivate ? 1 : 0;
    if ($isprivate != $comment->{isprivate}) {
        $self->{comment_isprivate} ||= {};
        $self->{comment_isprivate}->{$comment_id} = $isprivate;
    }
}
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
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);
        }
    }
}
1881 1882
sub set_custom_field {
    my ($self, $field, $value) = @_;
1883
    if (ref $value eq 'ARRAY' && $field->type != FIELD_TYPE_MULTI_SELECT) {
1884 1885
        $value = $value->[0];
    }
1886 1887 1888
    ThrowCodeError('field_not_custom', { field => $field }) if !$field->custom;
    $self->set($field->name, $value);
}
1889
sub set_deadline { $_[0]->set('deadline', $_[1]); }
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
sub set_dependencies {
    my ($self, $dependson, $blocked) = @_;
    ($dependson, $blocked) = $self->_check_dependencies($dependson, $blocked);
    # 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;
}
1900 1901 1902 1903 1904
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);
1905
    my $new = $self->dup_id;
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
    return if $old == $new;
    
    # 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 });
    }
}
1932
sub set_estimated_time { $_[0]->set('estimated_time', $_[1]); }
1933
sub _set_everconfirmed { $_[0]->set('everconfirmed', $_[1]); }
1934 1935 1936
sub set_op_sys         { $_[0]->set('op_sys',        $_[1]); }
sub set_platform       { $_[0]->set('rep_platform',  $_[1]); }
sub set_priority       { $_[0]->set('priority',      $_[1]); }
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
sub set_product {
    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};
        delete $self->{milestoneurl};
        $product_changed = 1;
    }

    $params ||= {};
    my $comp_name = $params->{component} || $self->component;
    my $vers_name = $params->{version}   || $self->version;
    my $tm_name   = $params->{target_milestone};
    # 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; };
1976 1977 1978 1979 1980 1981 1982 1983 1984
        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;
        }
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
        # 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);
        
        my $verified = $params->{change_confirmed};
        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
            };
            $vars{components} = [map { $_->name } @{$product->components}];
            $vars{milestones} = [map { $_->name } @{$product->milestones}];
            $vars{versions}   = [map { $_->name } @{$product->versions}];
        }

        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};
            # 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
2017
                  WHERE bgm.bug_id IN (' . join(',', ('?') x @idlist) . ')
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031
                    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));
            $vars{'old_groups'} = Bugzilla::Group->new_from_list($gids);            
        }
        
        if (%vars) {
            $vars{product} = $product;
2032
            $vars{bug} = $self;
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
            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);
2044
        if ($product_changed && !$self->check_can_change_field('target_milestone', 0, 1)) {
2045 2046 2047
            # Have to set this directly to bypass the validators.
            $self->{target_milestone} = $product->default_milestone;
        }
2048 2049 2050
        else {
            $self->set_target_milestone($tm_name);
        }
2051 2052
    }
    
2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
    if ($product_changed) {
        # Remove groups that aren't valid in the new product. This will also
        # have the side effect of removing the bug from groups that aren't
        # active anymore.
        #
        # 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) {
            if (!grep($group->id == $_->id, @{$product->groups_valid})) {
                $self->remove_group($group);
            }
        }
    
        # Make sure the bug is in all the mandatory groups for the new product.
        foreach my $group (@{$product->groups_mandatory_for(Bugzilla->user)}) {
            $self->add_group($group);
        }
    }
    
2073 2074 2075 2076
    # XXX This is temporary until all of process_bug uses update();
    return $product_changed;
}

2077 2078 2079
sub set_qa_contact {
    my ($self, $value) = @_;
    $self->set('qa_contact', $value);
2080 2081 2082 2083
    # 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;
    }
2084 2085 2086 2087 2088 2089 2090
    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);
}
2091 2092 2093
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; }
2094
sub set_reporter_accessible { $_[0]->set('reporter_accessible', $_[1]); }
2095
sub set_resolution {
2096
    my ($self, $value, $params) = @_;
2097 2098 2099 2100
    
    my $old_res = $self->resolution;
    $self->set('resolution', $value);
    my $new_res = $self->resolution;
2101

2102
    if ($new_res ne $old_res) {
2103 2104 2105 2106
        # MOVED has a special meaning and can only be used when
        # really moving bugs to another installation.
        ThrowCodeError('no_manual_moved') if ($new_res eq 'MOVED' && !$params->{moving});

2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
        # 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') {
2122 2123
        if ($params->{dupe_of}) {
            $self->set_dup_id($params->{dupe_of});
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137
        }
        elsif (!$self->dup_id) {
            ThrowUserError('dupe_id_required');
        }
    }
}
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; 
}
2138
sub set_severity       { $_[0]->set('bug_severity',  $_[1]); }
2139
sub set_status {
2140
    my ($self, $status, $params) = @_;
2141
    my $old_status = $self->status;
2142
    $self->set('bug_status', $status);
2143 2144 2145 2146 2147
    delete $self->{'status'};
    my $new_status = $self->status;
    
    if ($new_status->is_open) {
        # Check for the everconfirmed transition
2148
        $self->_set_everconfirmed($new_status->name eq 'UNCONFIRMED' ? 0 : 1);
2149 2150 2151 2152 2153
        $self->clear_resolution();
    }
    else {
        # We do this here so that we can make sure closed statuses have
        # resolutions.
2154 2155 2156
        my $resolution = delete $params->{resolution} || $self->resolution;
        $self->set_resolution($resolution, $params);

2157 2158 2159 2160 2161
        # Changing between closed statuses zeros the remaining time.
        if ($new_status->id != $old_status->id && $self->remaining_time != 0) {
            $self->_zero_remaining_time();
        }
    }
2162
}
2163
sub set_status_whiteboard { $_[0]->set('status_whiteboard', $_[1]); }
2164 2165 2166 2167
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]); }
2168 2169 2170 2171 2172

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

2173 2174
# These are in alphabetical order by field name.

2175 2176 2177
# 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 {
2178
    my ($self, $user_or_name) = @_;
2179 2180
    return if !$user_or_name;
    my $user = ref $user_or_name ? $user_or_name
2181
                                 : Bugzilla::User->check($user_or_name);
2182
    $self->_check_strict_isolation_for_user($user);
2183 2184 2185 2186 2187 2188 2189 2190 2191
    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
2192
                                 : Bugzilla::User->check($user_or_name);
2193 2194 2195 2196
    my $cc_users = $self->cc_users;
    @$cc_users = grep { $_->id != $user->id } @$cc_users;
}

2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
# $bug->add_comment("comment", {isprivate => 1, work_time => 10.5,
#                               type => CMT_NORMAL, extra_data => $data});
sub add_comment {
    my ($self, $comment, $params) = @_;

    $comment = $self->_check_comment($comment);

    $params ||= {};
    if (exists $params->{work_time}) {
        $params->{work_time} = $self->_check_work_time($params->{work_time});
2207 2208
        ThrowUserError('comment_required')
            if $comment eq '' && $params->{work_time} != 0;
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
    }
    if (exists $params->{type}) {
        $params->{type} = $self->_check_comment_type($params->{type});
    }
    if (exists $params->{isprivate}) {
        $params->{isprivate} = 
            $self->_check_commentprivacy($params->{isprivate});
    }
    # XXX We really should check extra_data, too.

    if ($comment eq '' && !($params->{type} || $params->{work_time})) {
        return;
    }

2223 2224 2225 2226 2227
    # So we really want to comment. Make sure we are allowed to do so.
    my $privs;
    $self->check_can_change_field('longdesc', 0, 1, \$privs)
        || ThrowUserError('illegal_change', { field => 'longdesc', privs => $privs });

2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
    $self->{added_comments} ||= [];
    my $add_comment = dclone($params);
    $add_comment->{thetext} = $comment;

    # We only want to trick_taint fields that we know about--we don't
    # want to accidentally let somebody set some field that's not OK
    # to set!
    foreach my $field (UPDATE_COMMENT_COLUMNS) {
        trick_taint($add_comment->{$field}) if defined $add_comment->{$field};
    }

    push(@{$self->{added_comments}}, $add_comment);
}
2241

2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
# There was a lot of duplicate code when I wrote this as three separate
# functions, so I just combined them all into one. This is also easier for
# process_bug to use.
sub modify_keywords {
    my ($self, $keywords, $action) = @_;
    
    $action ||= "makeexact";
    if (!grep($action eq $_, qw(add delete makeexact))) {
        $action = "makeexact";
    }
    
    $keywords = $self->_check_keywords($keywords);

    my (@result, $any_changes);
    if ($action eq 'makeexact') {
        @result = @$keywords;
        # Check if anything was added or removed.
        my @old_ids = map { $_->id } @{$self->keyword_objects};
        my @new_ids = map { $_->id } @result;
        my ($removed, $added) = diff_arrays(\@old_ids, \@new_ids);
        $any_changes = scalar @$removed || scalar @$added;
    }
    else {
        # We're adding or deleting specific keywords.
        my %keys = map {$_->id => $_} @{$self->keyword_objects};
        if ($action eq 'add') {
            $keys{$_->id} = $_ foreach @$keywords;
        }
        else {
            delete $keys{$_->id} foreach @$keywords;
        }
        @result = values %keys;
        $any_changes = scalar @$keywords;
    }
    # Make sure we retain the sort order.
    @result = sort {lc($a->name) cmp lc($b->name)} @result;
    
    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;
    return $any_changes;
}

2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361
sub add_group {
    my ($self, $group) = @_;
    # Invalid ids are silently ignored. (We can't tell people whether
    # or not a group exists.)
    $group = new Bugzilla::Group($group) unless ref $group;
    return unless $group;

    # Make sure that bugs in this product can actually be restricted
    # to this group.
    grep($group->id == $_->id, @{$self->product_obj->groups_valid})
         || ThrowUserError('group_invalid_restriction',
                { product => $self->product, group_id => $group->id });

    # 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)
        {
            ThrowUserError('group_change_denied',
                           { bug => $self, group_id => $group->id });
        }
    }

    my $current_groups = $self->groups_in;
    if (!grep($group->id == $_->id, @$current_groups)) {
        push(@$current_groups, $group);
    }
}

sub remove_group {
    my ($self, $group) = @_;
    $group = new Bugzilla::Group($group) unless ref $group;
    return unless $group;
    
    # First, check if this is a valid group for this product.
    # You can *always* remove a group that is not valid for this product, so
    # we don't do any other checks if that's the case. (set_product does this.)
    #
    # This particularly happens when isbuggroup is no longer 1, and we're
    # moving a bug to a new product.
    if (grep($_->id == $group->id, @{$self->product_obj->groups_valid})) {   
        my $controls = $self->product_obj->group_controls->{$group->id};

        # Nobody can ever remove a Mandatory group.
        if ($controls->{membercontrol} == CONTROLMAPMANDATORY) {
            ThrowUserError('group_invalid_removal',
                { product => $self->product, group_id => $group->id,
                  bug => $self });
        }

        # 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)
            {
                ThrowUserError('group_change_denied',
                               { bug => $self, group_id => $group->id });
            }
        }
    }
    
    my $current_groups = $self->groups_in;
    @$current_groups = grep { $_->id != $group->id } @$current_groups;
}

2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
sub add_see_also {
    my ($self, $input) = @_;
    $input = trim($input);

    # We assume that the URL is an HTTP URL if there is no (something):// 
    # in front.
    my $uri = new URI($input);
    if (!$uri->scheme) {
        # This works better than setting $uri->scheme('http'), because
        # that creates URLs like "http:domain.com" and doesn't properly
        # differentiate the path from the domain.
        $uri = new URI("http://$input");
    }
    elsif ($uri->scheme ne 'http' && $uri->scheme ne 'https') {
        ThrowUserError('bug_url_invalid', { url => $input, reason => 'http' });
    }

2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
    my $result;
    # Launchpad URLs
    if ($uri->authority =~ /launchpad.net$/) {
        # Launchpad bug URLs can look like various things:
        #   https://bugs.launchpad.net/ubuntu/+bug/1234
        #   https://launchpad.net/bugs/1234
        # All variations end with either "/bugs/1234" or "/+bug/1234"
        if ($uri->path =~ m|bugs?/(\d+)$|) {
            # This is the shortest standard URL form for Launchpad bugs,
            # and so we reduce all URLs to this.
            $result = "https://launchpad.net/bugs/$1";
        }
        else {
            ThrowUserError('bug_url_invalid',
                           { url => $input, reason => 'id' });
        }
    }
    # Bugzilla URLs
    else {
        if ($uri->path !~ /show_bug\.cgi$/) {
            ThrowUserError('bug_url_invalid', 
                           { url => $input, reason => 'show_bug' });
        }

        my $bug_id = $uri->query_param('id');
        # We don't currently allow aliases, because we can't check to see
        # if somebody's putting both an alias link and a numeric ID link.
        # When we start validating the URL by accessing the other Bugzilla,
        # we can allow aliases.
        detaint_natural($bug_id);
        if (!$bug_id) {
            ThrowUserError('bug_url_invalid', 
                           { url => $input, reason => 'id' });
        }

        # Make sure that "id" is the only query parameter.
        $uri->query("id=$bug_id");
        # And remove any # part if there is one.
        $uri->fragment(undef);
        $result = $uri->canonical->as_string;
    }
2420 2421 2422 2423 2424 2425 2426 2427 2428

    if (length($result) > MAX_BUG_URL_LENGTH) {
        ThrowUserError('bug_url_too_long', { url => $result });
    }

    # 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.
    if (!grep { lc($_) eq lc($result) } @{ $self->see_also }) {
2429 2430 2431 2432 2433 2434 2435 2436
        my $privs;
        my $can = $self->check_can_change_field('see_also', '', $result, \$privs);
        if (!$can) {
            ThrowUserError('illegal_change', { field    => 'see_also',
                                               newvalue => $result,
                                               privs    => $privs });
        }

2437 2438 2439 2440 2441 2442 2443
        push(@{ $self->see_also }, $result);
    }
}

sub remove_see_also {
    my ($self, $url) = @_;
    my $see_also = $self->see_also;
2444 2445 2446 2447 2448 2449 2450 2451 2452
    my @new_see_also = grep { lc($_) ne lc($url) } @$see_also;
    my $privs;
    my $can = $self->check_can_change_field('see_also', $see_also, \@new_see_also, \$privs);
    if (!$can) {
        ThrowUserError('illegal_change', { field    => 'see_also',
                                           oldvalue => $url,
                                           privs    => $privs });
        }
    $self->{see_also} = \@new_see_also;
2453 2454
}

2455 2456
#####################################################################
# Instance Accessors
2457 2458 2459 2460 2461 2462
#####################################################################

# 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.

2463 2464 2465 2466 2467
# 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.

2468 2469 2470 2471 2472
sub dup_id {
    my ($self) = @_;
    return $self->{'dup_id'} if exists $self->{'dup_id'};

    $self->{'dup_id'} = undef;
2473 2474
    return if $self->{'error'};

2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
    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'};
}

2487 2488 2489 2490
sub actual_time {
    my ($self) = @_;
    return $self->{'actual_time'} if exists $self->{'actual_time'};

2491
    if ( $self->{'error'} || 
2492
         !Bugzilla->user->in_group(Bugzilla->params->{"timetrackinggroup"}) ) {
2493 2494 2495
        $self->{'actual_time'} = undef;
        return $self->{'actual_time'};
    }
2496

2497 2498 2499 2500 2501
    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();
2502 2503 2504
    return $self->{'actual_time'};
}

2505
sub any_flags_requesteeble {
2506 2507 2508
    my ($self) = @_;
    return $self->{'any_flags_requesteeble'} 
        if exists $self->{'any_flags_requesteeble'};
2509
    return 0 if $self->{'error'};
2510 2511 2512 2513 2514 2515 2516

    $self->{'any_flags_requesteeble'} = 
        grep($_->{'is_requesteeble'}, @{$self->flag_types});

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

2517
sub attachments {
2518 2519
    my ($self) = @_;
    return $self->{'attachments'} if exists $self->{'attachments'};
2520
    return [] if $self->{'error'};
2521 2522

    $self->{'attachments'} =
2523
        Bugzilla::Attachment->get_attachments_by_bug($self->bug_id, {preload => 1});
2524 2525 2526
    return $self->{'attachments'};
}

2527
sub assigned_to {
2528
    my ($self) = @_;
2529 2530 2531 2532
    return $self->{'assigned_to_obj'} if exists $self->{'assigned_to_obj'};
    $self->{'assigned_to'} = 0 if $self->{'error'};
    $self->{'assigned_to_obj'} ||= new Bugzilla::User($self->{'assigned_to'});
    return $self->{'assigned_to_obj'};
2533 2534
}

2535
sub blocked {
2536 2537
    my ($self) = @_;
    return $self->{'blocked'} if exists $self->{'blocked'};
2538
    return [] if $self->{'error'};
2539 2540 2541 2542
    $self->{'blocked'} = EmitDependList("dependson", "blocked", $self->bug_id);
    return $self->{'blocked'};
}

2543
# Even bugs in an error state always have a bug_id.
2544 2545
sub bug_id { $_[0]->{'bug_id'}; }

2546
sub cc {
2547 2548
    my ($self) = @_;
    return $self->{'cc'} if exists $self->{'cc'};
2549
    return [] if $self->{'error'};
2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563

    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);

    $self->{'cc'} = undef if !scalar(@{$self->{'cc'}});

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

2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576
# 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'};
}

2577 2578 2579 2580 2581 2582 2583 2584 2585 2586
sub component {
    my ($self) = @_;
    return $self->{component} if exists $self->{component};
    return '' if $self->{error};
    ($self->{component}) = Bugzilla->dbh->selectrow_array(
        'SELECT name FROM components WHERE id = ?',
        undef, $self->{component_id});
    return $self->{component};
}

2587 2588 2589 2590 2591 2592 2593 2594 2595
# XXX Eventually this will replace component()
sub component_obj {
    my ($self) = @_;
    return $self->{component_obj} if defined $self->{component_obj};
    return {} if $self->{error};
    $self->{component_obj} = new Bugzilla::Component($self->{component_id});
    return $self->{component_obj};
}

2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
sub classification_id {
    my ($self) = @_;
    return $self->{classification_id} if exists $self->{classification_id};
    return 0 if $self->{error};
    ($self->{classification_id}) = Bugzilla->dbh->selectrow_array(
        'SELECT classification_id FROM products WHERE id = ?',
        undef, $self->{product_id});
    return $self->{classification_id};
}

sub classification {
    my ($self) = @_;
    return $self->{classification} if exists $self->{classification};
    return '' if $self->{error};
    ($self->{classification}) = Bugzilla->dbh->selectrow_array(
        'SELECT name FROM classifications WHERE id = ?',
        undef, $self->classification_id);
    return $self->{classification};
}

2616
sub dependson {
2617 2618
    my ($self) = @_;
    return $self->{'dependson'} if exists $self->{'dependson'};
2619
    return [] if $self->{'error'};
2620 2621 2622 2623 2624
    $self->{'dependson'} = 
        EmitDependList("blocked", "dependson", $self->bug_id);
    return $self->{'dependson'};
}

2625
sub flag_types {
2626 2627
    my ($self) = @_;
    return $self->{'flag_types'} if exists $self->{'flag_types'};
2628
    return [] if $self->{'error'};
2629

2630 2631 2632 2633
    my $vars = { target_type  => 'bug',
                 product_id   => $self->{product_id},
                 component_id => $self->{component_id},
                 bug_id       => $self->bug_id };
2634

2635
    $self->{'flag_types'} = Bugzilla::Flag::_flag_types($vars);
2636 2637 2638
    return $self->{'flag_types'};
}

2639 2640 2641 2642 2643 2644 2645 2646 2647 2648
sub isopened {
    my $self = shift;
    return is_open_state($self->{bug_status}) ? 1 : 0;
}

sub isunconfirmed {
    my $self = shift;
    return ($self->bug_status eq 'UNCONFIRMED') ? 1 : 0;
}

2649
sub keywords {
2650
    my ($self) = @_;
2651 2652
    return join(', ', (map { $_->name } @{$self->keyword_objects}));
}
2653

2654 2655 2656 2657 2658
# 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'};
2659

2660 2661 2662 2663 2664
    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'};
2665 2666
}

2667 2668 2669
sub longdescs {
    my ($self) = @_;
    return $self->{'longdescs'} if exists $self->{'longdescs'};
2670
    return [] if $self->{'error'};
2671
    $self->{'longdescs'} = GetComments($self->{bug_id});
2672 2673 2674
    return $self->{'longdescs'};
}

2675
sub milestoneurl {
2676 2677
    my ($self) = @_;
    return $self->{'milestoneurl'} if exists $self->{'milestoneurl'};
2678
    return '' if $self->{'error'};
2679

2680
    $self->{'milestoneurl'} = $self->product_obj->milestone_url;
2681 2682 2683
    return $self->{'milestoneurl'};
}

2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
sub product {
    my ($self) = @_;
    return $self->{product} if exists $self->{product};
    return '' if $self->{error};
    ($self->{product}) = Bugzilla->dbh->selectrow_array(
        'SELECT name FROM products WHERE id = ?',
        undef, $self->{product_id});
    return $self->{product};
}

2694 2695 2696 2697
# XXX This should eventually replace the "product" subroutine.
sub product_obj {
    my $self = shift;
    return {} if $self->{error};
2698 2699
    $self->{product_obj} ||= new Bugzilla::Product($self->{product_id});
    return $self->{product_obj};
2700 2701
}

2702
sub qa_contact {
2703
    my ($self) = @_;
2704
    return $self->{'qa_contact_obj'} if exists $self->{'qa_contact_obj'};
2705
    return undef if $self->{'error'};
2706

2707 2708
    if (Bugzilla->params->{'useqacontact'} && $self->{'qa_contact'}) {
        $self->{'qa_contact_obj'} = new Bugzilla::User($self->{'qa_contact'});
2709 2710 2711 2712
    } else {
        # XXX - This is somewhat inconsistent with the assignee/reporter 
        # methods, which will return an empty User if they get a 0. 
        # However, we're keeping it this way now, for backwards-compatibility.
2713
        $self->{'qa_contact_obj'} = undef;
2714
    }
2715
    return $self->{'qa_contact_obj'};
2716 2717
}

2718
sub reporter {
2719 2720
    my ($self) = @_;
    return $self->{'reporter'} if exists $self->{'reporter'};
2721
    $self->{'reporter_id'} = 0 if $self->{'error'};
2722 2723 2724 2725
    $self->{'reporter'} = new Bugzilla::User($self->{'reporter_id'});
    return $self->{'reporter'};
}

2726 2727 2728 2729 2730 2731 2732 2733
sub see_also {
    my ($self) = @_;
    return [] if $self->{'error'};
    $self->{'see_also'} ||= Bugzilla->dbh->selectcol_arrayref(
        'SELECT value FROM bug_see_also WHERE bug_id = ?', undef, $self->id);
    return $self->{'see_also'};
}

2734 2735 2736 2737 2738 2739 2740
sub status {
    my $self = shift;
    return undef if $self->{'error'};

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

2742
sub show_attachment_flags {
2743 2744 2745
    my ($self) = @_;
    return $self->{'show_attachment_flags'} 
        if exists $self->{'show_attachment_flags'};
2746
    return 0 if $self->{'error'};
2747 2748 2749 2750 2751 2752 2753 2754 2755

    # 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'} });
2756
    my $num_attachment_flags = Bugzilla::Flag->count(
2757
        { 'target_type'  => 'attachment',
2758
          'bug_id'       => $self->bug_id });
2759 2760 2761 2762 2763 2764 2765

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

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

2766 2767
sub use_votes {
    my ($self) = @_;
2768
    return 0 if $self->{'error'};
2769

2770
    return Bugzilla->params->{'usevotes'} 
2771
           && $self->product_obj->votes_per_user > 0;
2772 2773 2774 2775 2776
}

sub groups {
    my $self = shift;
    return $self->{'groups'} if exists $self->{'groups'};
2777
    return [] if $self->{'error'};
2778

2779
    my $dbh = Bugzilla->dbh;
2780 2781 2782 2783 2784 2785 2786 2787 2788
    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.
    #
2789
    my $grouplist = Bugzilla->user->groups_as_string;
2790 2791
    my $sth = $dbh->prepare(
             "SELECT DISTINCT groups.id, name, description," .
2792 2793
             " CASE WHEN bug_group_map.group_id IS NOT NULL" .
             " THEN 1 ELSE 0 END," .
2794
             " CASE WHEN groups.id IN($grouplist) THEN 1 ELSE 0 END," .
2795 2796 2797 2798
             " isactive, membercontrol, othercontrol" .
             " FROM groups" . 
             " LEFT JOIN bug_group_map" .
             " ON bug_group_map.group_id = groups.id" .
2799
             " AND bug_id = ?" .
2800 2801
             " LEFT JOIN group_control_map" .
             " ON group_control_map.group_id = groups.id" .
2802
             " AND group_control_map.product_id = ? " .
2803 2804
             " WHERE isbuggroup = 1" .
             " ORDER BY description");
2805
    $sth->execute($self->{'bug_id'},
2806
                  $self->{'product_id'});
2807

2808 2809
    while (my ($groupid, $name, $description, $ison, $ingroup, $isactive,
            $membercontrol, $othercontrol) = $sth->fetchrow_array()) {
2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826

        $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,
2827
                             "name" => $name,
2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839
                             "ison" => $ison,
                             "ingroup" => $ingroup,
                             "mandatory" => $ismandatory,
                             "description" => $description });
        }
    }

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

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

2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
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'};
}

2851 2852 2853
sub user {
    my $self = shift;
    return $self->{'user'} if exists $self->{'user'};
2854
    return {} if $self->{'error'};
2855

2856
    my $user = Bugzilla->user;
2857
    my $canmove = Bugzilla->params->{'move-enabled'} && $user->is_mover;
2858

2859 2860 2861
    my $prod_id = $self->{'product_id'};

    my $unknown_privileges = $user->in_group('editbugs', $prod_id);
2862
    my $canedit = $unknown_privileges
2863
                  || $user->id == $self->{'assigned_to'}
2864
                  || (Bugzilla->params->{'useqacontact'}
2865 2866
                      && $self->{'qa_contact'}
                      && $user->id == $self->{'qa_contact'});
2867
    my $canconfirm = $unknown_privileges
2868
                     || $user->in_group('canconfirm', $prod_id);
2869 2870
    my $isreporter = $user->id
                     && $user->id == $self->{reporter_id};
2871 2872 2873 2874 2875

    $self->{'user'} = {canmove    => $canmove,
                       canconfirm => $canconfirm,
                       canedit    => $canedit,
                       isreporter => $isreporter};
2876 2877 2878 2879 2880 2881
    return $self->{'user'};
}

sub choices {
    my $self = shift;
    return $self->{'choices'} if exists $self->{'choices'};
2882
    return {} if $self->{'error'};
2883 2884

    $self->{'choices'} = {};
2885

2886
    my @prodlist = map {$_->name} @{Bugzilla->user->get_enterable_products};
2887 2888
    # The current product is part of the popup, even if new bugs are no longer
    # allowed for that product
2889 2890
    if (lsearch(\@prodlist, $self->product) < 0) {
        push(@prodlist, $self->product);
2891 2892 2893 2894
        @prodlist = sort @prodlist;
    }

    # Hack - this array contains "". See bug 106589.
2895
    my @res = grep ($_, @{get_legal_field_values('resolution')});
2896 2897 2898 2899

    $self->{'choices'} =
      {
       'product' => \@prodlist,
2900 2901 2902 2903 2904 2905
       'rep_platform' => get_legal_field_values('rep_platform'),
       'priority'     => get_legal_field_values('priority'),
       'bug_severity' => get_legal_field_values('bug_severity'),
       'op_sys'       => get_legal_field_values('op_sys'),
       'bug_status'   => get_legal_field_values('bug_status'),
       'resolution'   => \@res,
2906 2907 2908
       'component'    => [map($_->name, @{$self->product_obj->components})],
       'version'      => [map($_->name, @{$self->product_obj->versions})],
       'target_milestone' => [map($_->name, @{$self->product_obj->milestones})],
2909 2910 2911 2912
      };

    return $self->{'choices'};
}
2913

2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927
sub votes {
    my ($self) = @_;
    return 0 if $self->{error};
    return $self->{votes} if defined $self->{votes};

    my $dbh = Bugzilla->dbh;
    $self->{votes} = $dbh->selectrow_array(
        'SELECT SUM(vote_count) FROM votes
          WHERE bug_id = ? ' . $dbh->sql_group_by('bug_id'),
        undef, $self->bug_id);
    $self->{votes} ||= 0;
    return $self->{votes};
}

2928 2929 2930 2931 2932
# 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.
2933
sub bug_alias_to_id {
2934
    my ($alias) = @_;
2935
    return undef unless Bugzilla->params->{"usebugaliases"};
2936 2937 2938 2939 2940 2941
    my $dbh = Bugzilla->dbh;
    trick_taint($alias);
    return $dbh->selectrow_array(
        "SELECT bug_id FROM bugs WHERE alias = ?", undef, $alias);
}

2942 2943 2944 2945
#####################################################################
# Subroutines
#####################################################################

2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967
sub update_comment {
    my ($self, $comment_id, $new_comment) = @_;

    # Some validation checks.
    if ($self->{'error'}) {
        ThrowCodeError("bug_error", { bug => $self });
    }
    detaint_natural($comment_id)
      || ThrowCodeError('bad_arg', {argument => 'comment_id', function => 'update_comment'});

    # The comment ID must belong to this bug.
    my @current_comment_obj = grep {$_->{'id'} == $comment_id} @{$self->longdescs};
    scalar(@current_comment_obj)
      || ThrowCodeError('bad_arg', {argument => 'comment_id', function => 'update_comment'});

    # If the new comment is undefined, then there is nothing to update.
    # To delete a comment, an empty string should be passed.
    return unless defined $new_comment;
    $new_comment =~ s/\s*$//s;    # Remove trailing whitespaces.
    $new_comment =~ s/\r\n?/\n/g; # Handle Windows and Mac-style line endings.
    trick_taint($new_comment);

2968
    # We assume _check_comment() has already been called earlier.
2969 2970
    Bugzilla->dbh->do('UPDATE longdescs SET thetext = ? WHERE comment_id = ?',
                       undef, ($new_comment, $comment_id));
2971
    $self->_sync_fulltext();
2972 2973 2974 2975 2976

    # Update the comment object with this new text.
    $current_comment_obj[0]->{'body'} = $new_comment;
}

2977 2978 2979
# Represents which fields from the bugs table are handled by process_bug.cgi.
sub editable_bug_fields {
    my @fields = Bugzilla->dbh->bz_table_columns('bugs');
2980 2981 2982
    # Obsolete custom fields are not editable.
    my @obsolete_fields = Bugzilla->get_fields({obsolete => 1, custom => 1});
    @obsolete_fields = map { $_->name } @obsolete_fields;
2983
    foreach my $remove ("bug_id", "reporter", "creation_ts", "delta_ts", "lastdiffed", @obsolete_fields) {
2984
        my $location = lsearch(\@fields, $remove);
2985 2986
        # Custom multi-select fields are not stored in the bugs table.
        splice(@fields, $location, 1) if ($location > -1);
2987 2988 2989 2990 2991 2992
    }
    # Sorted because the old @::log_columns variable, which this replaces,
    # was sorted.
    return sort(@fields);
}

2993 2994
# XXX - When Bug::update() will be implemented, we should make this routine
#       a private method.
2995 2996
# Join with bug_status and bugs tables to show bugs with open statuses first,
# and then the others
2997
sub EmitDependList {
2998 2999
    my ($myfield, $targetfield, $bug_id) = (@_);
    my $dbh = Bugzilla->dbh;
3000
    my $list_ref = $dbh->selectcol_arrayref(
3001 3002 3003 3004 3005 3006
          "SELECT $targetfield
             FROM dependencies
                  INNER JOIN bugs ON dependencies.$targetfield = bugs.bug_id
                  INNER JOIN bug_status ON bugs.bug_status = bug_status.value
            WHERE $myfield = ?
            ORDER BY is_open DESC, $targetfield",
3007
            undef, $bug_id);
3008
    return $list_ref;
3009 3010
}

3011
sub ValidateTime {
3012 3013 3014 3015 3016 3017 3018
    my ($time, $field) = @_;

    # regexp verifies one or more digits, optionally followed by a period and
    # zero or more digits, OR we have a period followed by one or more digits
    # (allow negatives, though, so people can back out errors in time reporting)
    if ($time !~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/) {
        ThrowUserError("number_not_numeric",
3019
                       {field => "$field", num => "$time"});
3020 3021 3022 3023 3024
    }

    # Only the "work_time" field is allowed to contain a negative value.
    if ( ($time < 0) && ($field ne "work_time") ) {
        ThrowUserError("number_too_small",
3025
                       {field => "$field", num => "$time", min_num => "0"});
3026 3027 3028 3029
    }

    if ($time > 99999.99) {
        ThrowUserError("number_too_large",
3030
                       {field => "$field", num => "$time", max_num => "99999.99"});
3031
    }
3032
}
3033

3034
sub GetComments {
3035
    my ($id, $comment_sort_order, $start, $end, $raw) = @_;
3036 3037
    my $dbh = Bugzilla->dbh;

3038 3039 3040 3041
    $comment_sort_order = $comment_sort_order ||
        Bugzilla->user->settings->{'comment_sort_order'}->{'value'};

    my $sort_order = ($comment_sort_order eq "oldest_to_newest") ? 'asc' : 'desc';
3042

3043
    my @comments;
3044 3045
    my @args = ($id);

3046
    my $query = 'SELECT longdescs.comment_id AS id, profiles.userid, ' .
3047 3048 3049 3050 3051 3052 3053
                        $dbh->sql_date_format('longdescs.bug_when', '%Y.%m.%d %H:%i:%s') .
                      ' AS time, longdescs.thetext AS body, longdescs.work_time,
                        isprivate, already_wrapped, type, extra_data
                   FROM longdescs
             INNER JOIN profiles
                     ON profiles.userid = longdescs.who
                  WHERE longdescs.bug_id = ?';
3054

3055
    if ($start) {
3056 3057 3058 3059 3060 3061
        $query .= ' AND longdescs.bug_when > ?';
        push(@args, $start);
    }
    if ($end) {
        $query .= ' AND longdescs.bug_when <= ?';
        push(@args, $end);
3062
    }
3063

3064 3065 3066
    $query .= " ORDER BY longdescs.bug_when $sort_order";
    my $sth = $dbh->prepare($query);
    $sth->execute(@args);
3067

3068 3069 3070
    # Cache the users we look up
    my %users;

3071 3072
    while (my $comment_ref = $sth->fetchrow_hashref()) {
        my %comment = %$comment_ref;
3073 3074
        $users{$comment{'userid'}} ||= new Bugzilla::User($comment{'userid'});
        $comment{'author'} = $users{$comment{'userid'}};
3075 3076 3077

        # If raw data is requested, do not format 'special' comments.
        $comment{'body'} = format_comment(\%comment) unless $raw;
3078 3079 3080

        push (@comments, \%comment);
    }
3081 3082 3083 3084
   
    if ($comment_sort_order eq "newest_to_oldest_desc_first") {
        unshift(@comments, pop @comments);
    }
3085 3086 3087 3088

    return \@comments;
}

3089
# Format language specific comments.
3090 3091
sub format_comment {
    my $comment = shift;
3092 3093
    my $template = Bugzilla->template_inner;
    my $vars = {comment => $comment};
3094 3095
    my $body;

3096 3097
    $template->process("bug/format_comment.txt.tmpl", $vars, \$body)
        || ThrowTemplateError($template->error());
3098 3099 3100
    return $body;
}

3101
# Get the activity of a bug, starting from $starttime (if given).
3102
# This routine assumes Bugzilla::Bug->check has been previously called.
3103
sub GetBugActivity {
3104
    my ($bug_id, $attach_id, $starttime) = @_;
3105 3106 3107
    my $dbh = Bugzilla->dbh;

    # Arguments passed to the SQL query.
3108
    my @args = ($bug_id);
3109 3110 3111 3112 3113 3114 3115 3116 3117

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

3118 3119 3120 3121 3122 3123
    my $attachpart = "";
    if ($attach_id) {
        push(@args, $attach_id);
        $attachpart = "AND bugs_activity.attach_id = ?";
    }

3124 3125 3126
    # Only includes attachments the user is allowed to see.
    my $suppjoins = "";
    my $suppwhere = "";
3127
    if (Bugzilla->params->{"insidergroup"} 
3128
        && !Bugzilla->user->in_group(Bugzilla->params->{'insidergroup'})) 
3129
    {
3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147
        $suppjoins = "LEFT JOIN attachments 
                   ON attachments.attach_id = bugs_activity.attach_id";
        $suppwhere = "AND COALESCE(attachments.isprivate, 0) = 0";
    }

    my $query = "
        SELECT COALESCE(fielddefs.description, " 
               # This is a hack - PostgreSQL requires both COALESCE
               # arguments to be of the same type, and this is the only
               # way supported by both MySQL 3 and PostgreSQL to convert
               # an integer to a string. MySQL 4 supports CAST.
               . $dbh->sql_string_concat('bugs_activity.fieldid', q{''}) .
               "), fielddefs.name, bugs_activity.attach_id, " .
        $dbh->sql_date_format('bugs_activity.bug_when', '%Y.%m.%d %H:%i:%s') .
            ", bugs_activity.removed, bugs_activity.added, profiles.login_name
          FROM bugs_activity
               $suppjoins
     LEFT JOIN fielddefs
3148
            ON bugs_activity.fieldid = fielddefs.id
3149 3150 3151 3152
    INNER JOIN profiles
            ON profiles.userid = bugs_activity.who
         WHERE bugs_activity.bug_id = ?
               $datepart
3153
               $attachpart
3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174
               $suppwhere
      ORDER BY bugs_activity.bug_when";

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

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

    foreach my $entry (@$list) {
        my ($field, $fieldname, $attachid, $when, $removed, $added, $who) = @$entry;
        my %change;
        my $activity_visible = 1;

        # check if the user should see this field's activity
        if ($fieldname eq 'remaining_time'
            || $fieldname eq 'estimated_time'
            || $fieldname eq 'work_time'
            || $fieldname eq 'deadline')
        {
3175
            $activity_visible = 
3176
                Bugzilla->user->in_group(Bugzilla->params->{'timetrackinggroup'}) ? 1 : 0;
3177 3178 3179 3180 3181 3182
        } else {
            $activity_visible = 1;
        }

        if ($activity_visible) {
            # This gets replaced with a hyperlink in the template.
3183
            $field =~ s/^Attachment\s*// if $attachid;
3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223

            # Check for the results of an old Bugzilla data corruption bug
            $incomplete_data = 1 if ($added =~ /^\?/ || $removed =~ /^\?/);

            # 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 = [];
            }

            $operation->{'who'} = $who;
            $operation->{'when'} = $when;

            $change{'field'} = $field;
            $change{'fieldname'} = $fieldname;
            $change{'attachid'} = $attachid;
            $change{'removed'} = $removed;
            $change{'added'} = $added;
            push (@$changes, \%change);
        }
    }

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

    return(\@operations, $incomplete_data);
}

3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251
# Update the bugs_activity table to reflect changes made in bugs.
sub LogActivityEntry {
    my ($i, $col, $removed, $added, $whoid, $timestamp) = @_;
    my $dbh = Bugzilla->dbh;
    # 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);
            $removed =~ s/^[,\s]+//; # remove any comma or space
        } 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);
            $added =~ s/^[,\s]+//; # remove any comma or space
        } else {
            $added = ""; # no more entries
        }
        trick_taint($addstr);
        trick_taint($removestr);
3252
        my $fieldid = get_field_id($col);
3253 3254 3255 3256 3257 3258 3259
        $dbh->do("INSERT INTO bugs_activity
                  (bug_id, who, bug_when, fieldid, removed, added)
                  VALUES (?, ?, ?, ?, ?, ?)",
                  undef, ($i, $whoid, $timestamp, $fieldid, $removestr, $addstr));
    }
}

3260 3261 3262 3263 3264 3265 3266 3267 3268 3269
# CountOpenDependencies counts the number of open dependent bugs for a
# list of bugs and returns a list of bug_id's and their dependency count
# It takes one parameter:
#  - A list of bug numbers whose dependencies are to be checked
sub CountOpenDependencies {
    my (@bug_list) = @_;
    my @dependencies;
    my $dbh = Bugzilla->dbh;

    my $sth = $dbh->prepare(
3270
          "SELECT blocked, COUNT(bug_status) " .
3271
            "FROM bugs, dependencies " .
3272
           "WHERE " . $dbh->sql_in('blocked', \@bug_list) .
3273
             "AND bug_id = dependson " .
3274
             "AND bug_status IN (" . join(', ', map {$dbh->quote($_)} BUG_STATE_OPEN)  . ") " .
3275
          $dbh->sql_group_by('blocked'));
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285
    $sth->execute();

    while (my ($bug_id, $dependencies) = $sth->fetchrow_array()) {
        push(@dependencies, { bug_id       => $bug_id,
                              dependencies => $dependencies });
    }

    return @dependencies;
}

3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
# If a bug is moved to a product which allows less votes per bug
# compared to the previous product, extra votes need to be removed.
sub RemoveVotes {
    my ($id, $who, $reason) = (@_);
    my $dbh = Bugzilla->dbh;

    my $whopart = ($who) ? " AND votes.who = $who" : "";

    my $sth = $dbh->prepare("SELECT profiles.login_name, " .
                            "profiles.userid, votes.vote_count, " .
                            "products.votesperuser, products.maxvotesperbug " .
                            "FROM profiles " . 
                            "LEFT JOIN votes ON profiles.userid = votes.who " .
3299
                            "LEFT JOIN bugs ON votes.bug_id = bugs.bug_id " .
3300 3301 3302 3303 3304 3305 3306
                            "LEFT JOIN products ON products.id = bugs.product_id " .
                            "WHERE votes.bug_id = ? " . $whopart);
    $sth->execute($id);
    my @list;
    while (my ($name, $userid, $oldvotes, $votesperuser, $maxvotesperbug) = $sth->fetchrow_array()) {
        push(@list, [$name, $userid, $oldvotes, $votesperuser, $maxvotesperbug]);
    }
3307 3308 3309 3310 3311

    # @messages stores all emails which have to be sent, if any.
    # This array is passed to the caller which will send these emails itself.
    my @messages = ();

3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343
    if (scalar(@list)) {
        foreach my $ref (@list) {
            my ($name, $userid, $oldvotes, $votesperuser, $maxvotesperbug) = (@$ref);

            $maxvotesperbug = min($votesperuser, $maxvotesperbug);

            # If this product allows voting and the user's votes are in
            # the acceptable range, then don't do anything.
            next if $votesperuser && $oldvotes <= $maxvotesperbug;

            # If the user has more votes on this bug than this product
            # allows, then reduce the number of votes so it fits
            my $newvotes = $maxvotesperbug;

            my $removedvotes = $oldvotes - $newvotes;

            if ($newvotes) {
                $dbh->do("UPDATE votes SET vote_count = ? " .
                         "WHERE bug_id = ? AND who = ?",
                         undef, ($newvotes, $id, $userid));
            } else {
                $dbh->do("DELETE FROM votes WHERE bug_id = ? AND who = ?",
                         undef, ($id, $userid));
            }

            # Notice that we did not make sure that the user fit within the $votesperuser
            # range.  This is considered to be an acceptable alternative to losing votes
            # during product moves.  Then next time the user attempts to change their votes,
            # they will be forced to fit within the $votesperuser limit.

            # Now lets send the e-mail to alert the user to the fact that their votes have
            # been reduced or removed.
3344
            my $vars = {
3345
                'to' => $name . Bugzilla->params->{'emailsuffix'},
3346 3347
                'bugid' => $id,
                'reason' => $reason,
3348

3349 3350 3351 3352
                'votesremoved' => $removedvotes,
                'votesold' => $oldvotes,
                'votesnew' => $newvotes,
            };
3353

3354 3355 3356
            my $voter = new Bugzilla::User($userid);
            my $template = Bugzilla->template_inner($voter->settings->{'lang'}->{'value'});

3357 3358
            my $msg;
            $template->process("email/votes-removed.txt.tmpl", $vars, \$msg);
3359
            push(@messages, $msg);
3360
        }
3361 3362
        Bugzilla->template_inner("");

3363 3364 3365 3366 3367 3368
        my $votes = $dbh->selectrow_array("SELECT SUM(vote_count) " .
                                          "FROM votes WHERE bug_id = ?",
                                          undef, $id) || 0;
        $dbh->do("UPDATE bugs SET votes = ? WHERE bug_id = ?",
                 undef, ($votes, $id));
    }
3369
    # Now return the array containing emails to be sent.
3370
    return @messages;
3371 3372
}

3373 3374 3375
# If a user votes for a bug, or the number of votes required to
# confirm a bug has been reduced, check if the bug is now confirmed.
sub CheckIfVotedConfirmed {
3376
    my $id = shift;
3377 3378
    my $bug = new Bugzilla::Bug($id);

3379
    my $ret = 0;
3380
    if (!$bug->everconfirmed && $bug->votes >= $bug->product_obj->votes_to_confirm) {
3381 3382
        $bug->add_comment('', { type => CMT_POPULAR_VOTES });

3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393
        if ($bug->bug_status eq 'UNCONFIRMED') {
            # Get a valid open state.
            my $new_status;
            foreach my $state (@{$bug->status->can_change_to}) {
                if ($state->is_open && $state->name ne 'UNCONFIRMED') {
                    $new_status = $state->name;
                    last;
                }
            }
            ThrowCodeError('no_open_bug_status') unless $new_status;

3394 3395 3396 3397 3398 3399
            # We cannot call $bug->set_status() here, because a user without
            # canconfirm privs should still be able to confirm a bug by
            # popular vote. We already know the new status is valid, so it's safe.
            $bug->{bug_status} = $new_status;
            $bug->{everconfirmed} = 1;
            delete $bug->{'status'}; # Contains the status object.
3400 3401
        }
        else {
3402
            # If the bug is in a closed state, only set everconfirmed to 1.
3403 3404
            # Do not call $bug->_set_everconfirmed(), for the same reason as above.
            $bug->{everconfirmed} = 1;
3405
        }
3406
        $bug->update();
3407 3408 3409 3410 3411 3412

        $ret = 1;
    }
    return $ret;
}

3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430
################################################################################
# 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;
3431
    my ($field, $oldvalue, $newvalue, $PrivilegesRequired) = (@_);
3432
    my $user = Bugzilla->user;
3433 3434 3435 3436 3437 3438 3439

    $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;
3440 3441 3442
    } elsif (ref($newvalue) eq 'ARRAY' && ref($oldvalue) eq 'ARRAY') {
        my ($removed, $added) = diff_arrays($oldvalue, $newvalue);
        return 1 if !scalar(@$removed) && !scalar(@$added);
3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464
    } elsif (trim($oldvalue) eq trim($newvalue)) {
        return 1;
    # numeric fields need to be compared using ==
    } elsif (($field eq 'estimated_time' || $field eq 'remaining_time')
             && $oldvalue == $newvalue)
    {
        return 1;
    }

    # Allow anyone to change comments.
    if ($field =~ /^longdesc/) {
        return 1;
    }

    # If the user isn't allowed to change a field, we must tell him who can.
    # We store the required permission set into the $PrivilegesRequired
    # variable which gets passed to the error template.
    #
    # $PrivilegesRequired = 0 : no privileges required;
    # $PrivilegesRequired = 1 : the reporter, assignee or an empowered user;
    # $PrivilegesRequired = 2 : the assignee or an empowered user;
    # $PrivilegesRequired = 3 : an empowered user.
3465 3466 3467 3468 3469 3470 3471 3472 3473
    
    # Only users in the time-tracking group can change time-tracking fields.
    if ( grep($_ eq $field, qw(deadline estimated_time remaining_time)) ) {
        my $tt_group = Bugzilla->params->{timetrackinggroup};
        if (!$tt_group || !$user->in_group($tt_group)) {
            $$PrivilegesRequired = 3;
            return 0;
        }
    }
3474

3475 3476
    # Allow anyone with (product-specific) "editbugs" privs to change anything.
    if ($user->in_group('editbugs', $self->{'product_id'})) {
3477 3478 3479
        return 1;
    }

3480
    # *Only* users with (product-specific) "canconfirm" privs can confirm bugs.
3481
    if ($field eq 'canconfirm'
3482
        || ($field eq 'everconfirmed' && $newvalue)
3483 3484 3485 3486
        || ($field eq 'bug_status'
            && $oldvalue eq 'UNCONFIRMED'
            && is_open_state($newvalue)))
    {
3487
        $$PrivilegesRequired = 3;
3488
        return $user->in_group('canconfirm', $self->{'product_id'});
3489 3490 3491 3492 3493
    }

    # Make sure that a valid bug ID has been given.
    if (!$self->{'error'}) {
        # Allow the assignee to change anything else.
3494 3495 3496
        if ($self->{'assigned_to'} == $user->id
            || $self->{'_old_assigned_to'} && $self->{'_old_assigned_to'} == $user->id)
        {
3497 3498 3499 3500 3501
            return 1;
        }

        # Allow the QA contact to change anything else.
        if (Bugzilla->params->{'useqacontact'}
3502 3503
            && (($self->{'qa_contact'} && $self->{'qa_contact'} == $user->id)
                || ($self->{'_old_qa_contact'} && $self->{'_old_qa_contact'} == $user->id)))
3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517
        {
            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:
    # - reassign bugs, unless the bugs are assigned to him;
    #   in that case we will have already returned 1 above
    #   when checking for the assignee of the bug.
    if ($field eq 'assigned_to') {
3518
        $$PrivilegesRequired = 2;
3519 3520 3521 3522
        return 0;
    }
    # - change the QA contact
    if ($field eq 'qa_contact') {
3523
        $$PrivilegesRequired = 2;
3524 3525 3526 3527
        return 0;
    }
    # - change the target milestone
    if ($field eq 'target_milestone') {
3528
        $$PrivilegesRequired = 2;
3529 3530 3531 3532
        return 0;
    }
    # - change the priority (unless he could have set it originally)
    if ($field eq 'priority'
3533
        && !Bugzilla->params->{'letsubmitterchoosepriority'})
3534
    {
3535
        $$PrivilegesRequired = 2;
3536 3537
        return 0;
    }
3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549
    # - unconfirm bugs (confirming them is handled above)
    if ($field eq 'everconfirmed') {
        $$PrivilegesRequired = 2;
        return 0;
    }
    # - change the status from one open state to another
    if ($field eq 'bug_status'
        && is_open_state($oldvalue) && is_open_state($newvalue)) 
    {
       $$PrivilegesRequired = 2;
       return 0;
    }
3550 3551 3552 3553 3554 3555 3556 3557

    # 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.
3558
    $$PrivilegesRequired = 1;
3559 3560 3561
    return 0;
}

3562 3563 3564 3565
#
# Field Validation
#

3566
# Validate and return a hash of dependencies
3567
sub ValidateDependencies {
3568
    my $fields = {};
3569
    # These can be arrayrefs or they can be strings.
3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589
    $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;
    foreach my $pair (["blocked", "dependson"], ["dependson", "blocked"]) {
        my ($me, $target) = @{$pair};
        $deptree{$target} = [];
        $deps{$target} = [];
        next unless $fields->{$target};

        my %seen;
3590 3591 3592
        my $target_array = ref($fields->{$target}) ? $fields->{$target}
                           : [split(/[\s,]+/, $fields->{$target})];
        foreach my $i (@$target_array) {
3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627
            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;
            my $dep_list =
                $dbh->selectcol_arrayref("SELECT $target
                                          FROM dependencies
                                          WHERE $me = ?", undef, $i);
            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}++ }
3628
    my @isect = keys %isect;
3629
    if (scalar(@isect) > 0) {
3630
        ThrowUserError("dependency_loop_multi", {'deps' => \@isect});
3631 3632 3633
    }
    return %deps;
}
3634

3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654

#####################################################################
# Autoloaded Accessors
#####################################################################

# Determines whether an attribute access trapped by the AUTOLOAD function
# is for a valid bug attribute.  Bug attributes are properties and methods
# predefined by this module as well as bug fields for which an accessor
# can be defined by AUTOLOAD at runtime when the accessor is first accessed.
#
# XXX Strangely, some predefined attributes are on the list, but others aren't,
# and the original code didn't specify why that is.  Presumably the only
# attributes that need to be on this list are those that aren't predefined;
# we should verify that and update the list accordingly.
#
sub _validate_attribute {
    my ($attribute) = @_;

    my @valid_attributes = (
        # Miscellaneous properties and methods.
3655
        qw(error groups product_id component_id
3656 3657 3658
           longdescs milestoneurl attachments
           isopened isunconfirmed
           flag_types num_attachment_flag_types
3659
           show_attachment_flags any_flags_requesteeble),
3660 3661 3662 3663 3664 3665 3666 3667

        # Bug fields.
        Bugzilla::Bug->fields
    );

    return grep($attribute eq $_, @valid_attributes) ? 1 : 0;
}

3668 3669 3670 3671 3672 3673
sub AUTOLOAD {
  use vars qw($AUTOLOAD);
  my $attr = $AUTOLOAD;

  $attr =~ s/.*:://;
  return unless $attr=~ /[^A-Z]/;
3674 3675 3676 3677
  if (!_validate_attribute($attr)) {
      require Carp;
      Carp::confess("invalid bug attribute $attr");
  }
3678 3679 3680 3681

  no strict 'refs';
  *$AUTOLOAD = sub {
      my $self = shift;
3682 3683 3684 3685 3686 3687 3688 3689 3690

      return $self->{$attr} if defined $self->{$attr};

      $self->{_multi_selects} ||= [Bugzilla->get_fields(
          {custom => 1, type => FIELD_TYPE_MULTI_SELECT })];
      if ( grep($_->name eq $attr, @{$self->{_multi_selects}}) ) {
          $self->{$attr} ||= Bugzilla->dbh->selectcol_arrayref(
              "SELECT value FROM bug_$attr WHERE bug_id = ? ORDER BY value",
              undef, $self->id);
3691 3692
          return $self->{$attr};
      }
3693 3694

      return '';
3695 3696 3697
  };

  goto &$AUTOLOAD;
3698 3699 3700
}

1;