Bug.pm 72.1 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::Keyword;
39
use Bugzilla::User;
40
use Bugzilla::Util;
41
use Bugzilla::Error;
42
use Bugzilla::Product;
43 44
use Bugzilla::Component;
use Bugzilla::Group;
45

46 47
use List::Util qw(min);

48
use base qw(Bugzilla::Object Exporter);
49
@Bugzilla::Bug::EXPORT = qw(
50
    AppendComment ValidateComment
51
    bug_alias_to_id ValidateBugAlias ValidateBugID
52
    RemoveVotes CheckIfVotedConfirmed
53
    LogActivityEntry
54
    is_open_state
55
    editable_bug_fields
56 57
);

58 59 60 61
#####################################################################
# Constants
#####################################################################

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
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;
    return qw(
        alias
        bug_file_loc
        bug_id
        bug_severity
        bug_status
        cclist_accessible
        component_id
        delta_ts
        estimated_time
        everconfirmed
        op_sys
        priority
        product_id
        remaining_time
        rep_platform
        reporter_accessible
        resolution
        short_desc
        status_whiteboard
        target_milestone
        version
    ),
    'assigned_to AS assigned_to_id',
    'reporter    AS reporter_id',
    'qa_contact  AS qa_contact_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',
    Bugzilla->custom_field_names;
}

101 102
use constant REQUIRED_CREATE_FIELDS => qw(
    bug_severity
103
    comment
104 105 106 107 108 109 110 111 112 113 114
    component
    op_sys
    priority
    product
    rep_platform
    short_desc
    version
);

# There are also other, more complex validators that are called
# from run_create_validators.
115 116 117 118 119
sub VALIDATORS {
    my $validators = {
        alias          => \&_check_alias,
        bug_file_loc   => \&_check_bug_file_loc,
        bug_severity   => \&_check_bug_severity,
120 121
        comment        => \&_check_comment,
        commentprivacy => \&_check_commentprivacy,
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
        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,
    };

    my @select_fields = Bugzilla->get_fields({custom => 1, obsolete => 0,
                                              type => FIELD_TYPE_SINGLE_SELECT});

    foreach my $field (@select_fields) {
        $validators->{$field->name} = \&_check_select_field;
    }
    return $validators;
140 141
};

142 143 144 145 146
# Used in LogActivityEntry(). Gives the max length of lines in the
# activity table.
use constant MAX_LINE_LENGTH => 254;

# Used in ValidateComment(). Gives the max length allowed for a comment.
147 148
use constant MAX_COMMENT_LENGTH => 65535;

149 150 151 152 153 154 155 156
# The statuses that are valid on enter_bug.cgi and post_bug.cgi.
# The order is important--see _check_bug_status
use constant VALID_ENTRY_STATUS => qw(
    UNCONFIRMED
    NEW
    ASSIGNED
);

157 158
#####################################################################

159
sub new {
160 161 162 163 164 165
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
    my $param = shift;

    # If we get something that looks like a word (not a number),
    # make it the "name" param.
166
    if (!defined $param || (!ref($param) && $param !~ /^\d+$/)) {
167
        # But only if aliases are enabled.
168
        if (Bugzilla->params->{'usebugaliases'} && $param) {
169 170 171 172 173 174 175 176 177 178
            $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;
        }
179 180
    }

181 182 183 184 185 186 187 188 189 190 191
    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 = {};
        bless $error_self, $class;
        $error_self->{'bug_id'} = ref($param) ? $param->{name} : $param;
        $error_self->{'error'}  = 'NotFound';
        return $error_self;
192
    }
193 194 195 196 197 198 199 200

    # XXX At some point these should be moved into accessors.
    # They only are here because this is how Bugzilla::Bug
    # originally did things, before it was a Bugzilla::Object.
    $self->{'isunconfirmed'} = ($self->{bug_status} eq 'UNCONFIRMED');
    $self->{'isopened'}      = is_open_state($self->{bug_status});

    return $self;
201 202
}

203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
# 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>.
241 242 243 244 245 246 247
sub create {
    my $class  = shift;
    my $dbh = Bugzilla->dbh;

    $class->check_required_create_fields(@_);
    my $params = $class->run_create_validators(@_);

248
    # These are not a fields in the bugs table, so we don't pass them to
249 250 251
    # insert_create_data.
    my $cc_ids = $params->{cc};
    delete $params->{cc};
252 253
    my $groups = $params->{groups};
    delete $params->{groups};
254 255 256 257
    my $depends_on = $params->{dependson};
    delete $params->{dependson};
    my $blocked = $params->{blocked};
    delete $params->{blocked};
258 259 260
    my ($comment, $privacy) = ($params->{comment}, $params->{commentprivacy});
    delete $params->{comment};
    delete $params->{commentprivacy};
261

262 263 264 265 266
    # Set up the keyword cache for bug creation.
    my $keywords = $params->{keywords};
    $params->{keywords} = join(', ', sort {lc($a) cmp lc($b)} 
                                          map($_->name, @$keywords));

267 268 269 270 271
    # We don't want the bug to appear in the system until it's correctly
    # protected by groups.
    my $timestamp = $params->{creation_ts}; 
    delete $params->{creation_ts};

272 273 274 275
    $dbh->bz_lock_tables('bugs WRITE', 'bug_group_map WRITE', 
        'longdescs WRITE', 'cc WRITE', 'keywords WRITE', 'dependencies WRITE',
        'bugs_activity WRITE', 'fielddefs READ');

276 277
    my $bug = $class->insert_create_data($params);

278 279 280 281 282 283 284
    # 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);
    }

285 286
    $dbh->do('UPDATE bugs SET creation_ts = ? WHERE bug_id = ?', undef,
             $timestamp, $bug->bug_id);
287 288
    # Update the bug instance as well
    $bug->{creation_ts} = $timestamp;
289

290
    # Add the CCs
291 292 293 294 295
    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);
    }

296 297 298 299 300 301 302
    # 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);
    }

303 304 305 306 307 308 309
    # Set up dependencies (blocked/dependson)
    my $sth_deps = $dbh->prepare(
        'INSERT INTO dependencies (blocked, dependson) VALUES (?, ?)');
    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,
310
                         $bug->{reporter_id}, $timestamp);
311 312 313 314 315
    }
    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,
316
                         $bug->{reporter_id}, $timestamp);
317 318
    }

319 320
    # And insert the comment. We always insert a comment on bug creation,
    # but sometimes it's blank.
321 322 323 324 325 326 327 328 329 330 331 332
    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);
333 334 335

    $dbh->bz_unlock_tables();

336 337 338
    return $bug;
}

339 340 341

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

344
    my $product = $params->{product};
345 346 347 348
    $params->{product_id} = $product->id;
    delete $params->{product};

    ($params->{bug_status}, $params->{everconfirmed})
349
        = $class->_check_bug_status($product, $params->{bug_status});
350

351
    $params->{target_milestone} = $class->_check_target_milestone($product,
352 353
        $params->{target_milestone});

354
    $params->{version} = $class->_check_version($product, $params->{version});
355

356 357
    $params->{keywords} = $class->_check_keywords($product, $params->{keywords});

358 359 360
    $params->{groups} = $class->_check_groups($product,
        $params->{groups});

361
    my $component = $class->_check_component($product, $params->{component});
362 363 364 365
    $params->{component_id} = $component->id;
    delete $params->{component};

    $params->{assigned_to} = 
366
        $class->_check_assigned_to($component, $params->{assigned_to});
367
    $params->{qa_contact} =
368
        $class->_check_qa_contact($component, $params->{qa_contact});
369 370
    $params->{cc} = $class->_check_cc($component, $params->{cc});

371 372 373
    # Callers cannot set Reporter, currently.
    $params->{reporter} = Bugzilla->user->id;

374
    $params->{creation_ts} ||= Bugzilla->dbh->selectrow_array('SELECT NOW()');
375
    $params->{delta_ts} = $params->{creation_ts};
376 377 378 379

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

381
    $class->_check_strict_isolation($product, $params->{cc},
382
                                    $params->{assigned_to}, $params->{qa_contact});
383

384
    ($params->{dependson}, $params->{blocked}) = 
385
        $class->_check_dependencies($product, $params->{dependson}, $params->{blocked});
386

387 388 389 390 391 392
    # 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};

393
    return $params;
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
# 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
    # - cc
    # - dependencies
    # - duplicates
    # - flags
    # - keywords
    # - longdescs
    # - votes

422 423 424
    # Also, the attach_data table uses attachments.attach_id as a foreign
    # key, and so indirectly depends on a bug deletion too.

425 426 427 428
    $dbh->bz_lock_tables('attachments WRITE', 'bug_group_map WRITE',
                         'bugs WRITE', 'bugs_activity WRITE', 'cc WRITE',
                         'dependencies WRITE', 'duplicates WRITE',
                         'flags WRITE', 'keywords WRITE',
429 430
                         'longdescs WRITE', 'votes WRITE',
                         'attach_data WRITE');
431 432 433 434 435 436 437 438 439 440 441 442

    $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 longdescs WHERE bug_id = ?", undef, $bug_id);
    $dbh->do("DELETE FROM votes WHERE bug_id = ?", undef, $bug_id);
443 444 445 446 447 448 449 450 451 452 453

    # 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)) {
        $dbh->do("DELETE FROM attach_data WHERE id IN (" .
                 join(",", @$attach_ids) . ")");
    }

454 455 456 457 458 459 460 461 462 463 464
    # 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);

    $dbh->bz_unlock_tables();

    # Now this bug no longer exists
    $self->DESTROY;
    return $self;
}

465 466 467 468 469
#####################################################################
# Validators
#####################################################################

sub _check_alias {
470
   my ($invocant, $alias) = @_;
471
   $alias = trim($alias);
472 473
   return undef if (!Bugzilla->params->{'usebugaliases'} || !$alias);
   ValidateBugAlias($alias);
474 475 476 477
   return $alias;
}

sub _check_assigned_to {
478
    my ($invocant, $component, $name) = @_;
479 480 481 482 483
    my $user = Bugzilla->user;

    $name = trim($name);
    # Default assignee is the component owner.
    my $id;
484
    if (!$user->in_group('editbugs', $component->product_id) || !$name) {
485 486 487 488 489 490 491 492
        $id = $component->default_assignee->id;
    } else {
        $id = login_to_id($name, THROW_ERROR);
    }
    return $id;
}

sub _check_bug_file_loc {
493
    my ($invocant, $url) = @_;
494
    # If bug_file_loc is "http://", the default, use an empty value instead.
495
    $url = '' if (!defined($url) || $url eq 'http://');
496 497 498
    return $url;
}

499
sub _check_bug_severity {
500
    my ($invocant, $severity) = @_;
501 502 503 504 505
    $severity = trim($severity);
    check_field('bug_severity', $severity);
    return $severity;
}

506
sub _check_bug_status {
507
    my ($invocant, $product, $status) = @_;
508 509 510 511
    my $user = Bugzilla->user;

    my @valid_statuses = VALID_ENTRY_STATUS;

512 513
    if ($user->in_group('editbugs', $product->id)
        || $user->in_group('canconfirm', $product->id)) {
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
       # Default to NEW if the user with privs hasn't selected another status.
       $status ||= 'NEW';
    }
    elsif (!$product->votes_to_confirm) {
        # Without privs, products that don't support UNCONFIRMED default to
        # NEW.
        $status = 'NEW';
    }
    else {
        $status = 'UNCONFIRMED';
    }

    # UNCONFIRMED becomes an invalid status if votes_to_confirm is 0,
    # even if you are in editbugs.
    shift @valid_statuses if !$product->votes_to_confirm;

    check_field('bug_status', $status, \@valid_statuses);
531
    return ($status, $status eq 'UNCONFIRMED' ? 0 : 1);
532 533
}

534
sub _check_cc {
535
    my ($invocant, $component, $ccs) = @_;
536 537 538 539 540 541 542 543
    return [] unless $ccs;

    my %cc_ids;
    foreach my $person (@$ccs) {
        next unless $person;
        my $id = login_to_id($person, THROW_ERROR);
        $cc_ids{$id} = 1;
    }
544 545 546 547

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

548 549 550
    return [keys %cc_ids];
}

551
sub _check_comment {
552
    my ($invocant, $comment) = @_;
553

554
    $comment = '' unless defined $comment;
555 556 557 558 559 560 561 562 563 564 565 566

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

    ValidateComment($comment);

    if (Bugzilla->params->{"commentoncreate"} && !$comment) {
        ThrowUserError("description_required");
    }

567 568 569 570
    # On creation only, there must be a single-space comment, or
    # email will be supressed.
    $comment = ' ' if $comment eq '' && !ref($invocant);

571 572 573
    return $comment;
}

574 575 576 577 578 579 580
sub _check_commentprivacy {
    my ($invocant, $comment_privacy) = @_;
    my $insider_group = Bugzilla->params->{"insidergroup"};
    return ($insider_group && Bugzilla->user->in_group($insider_group) 
            && $comment_privacy) ? 1 : 0;
}

581
sub _check_component {
582
    my ($invocant, $product, $name) = @_;
583 584 585 586 587 588
    $name = trim($name);
    $name || ThrowUserError("require_component");
    my $obj = Bugzilla::Component::check_component($product, $name);
    return $obj;
}

589
sub _check_deadline {
590
    my ($invocant, $date) = @_;
591 592 593 594 595 596 597 598 599 600
    $date = trim($date);
    my $tt_group = Bugzilla->params->{"timetrackinggroup"};
    return undef unless $date && $tt_group 
                        && Bugzilla->user->in_group($tt_group);
    validate_date($date)
        || ThrowUserError('illegal_date', { date   => $date,
                                            format => 'YYYY-MM-DD' });
    return $date;
}

601 602 603
# Takes two comma/space-separated strings and returns arrayrefs
# of valid bug IDs.
sub _check_dependencies {
604
    my ($invocant, $product, $depends_on, $blocks) = @_;
605 606

    # Only editbugs users can set dependencies on bug entry.
607
    return ([], []) unless Bugzilla->user->in_group('editbugs', $product->id);
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629

    $depends_on ||= '';
    $blocks     ||= '';

    # Make sure all the bug_ids are valid.
    my @results;
    foreach my $string ($depends_on, $blocks) {
        my @array = split(/[\s,]+/, $string);
        # Eliminate nulls
        @array = grep($_, @array);
        # $field is not passed to ValidateBugID to prevent adding new
        # dependencies on inaccessible bugs.
        ValidateBugID($_) foreach (@array);
        push(@results, \@array);
    }

    #                               dependson    blocks
    my %deps = ValidateDependencies($results[0], $results[1]);

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

630
sub _check_estimated_time {
631
    return $_[0]->_check_time($_[1], 'estimated_time');
632 633
}

634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
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) {
662
        next unless $controls->{$id}->{'group'}->is_active;
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
        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;
}

680
sub _check_keywords {
681
    my ($invocant, $product, $keyword_string) = @_;
682
    $keyword_string = trim($keyword_string);
683 684
    return [] if (!$keyword_string
                  || !Bugzilla->user->in_group('editbugs', $product->id));
685

686
    my %keywords;
687 688 689 690
    foreach my $keyword (split(/[\s,]+/, $keyword_string)) {
        next unless $keyword;
        my $obj = new Bugzilla::Keyword({ name => $keyword });
        ThrowUserError("unknown_keyword", { keyword => $keyword }) if !$obj;
691
        $keywords{$obj->id} = $obj;
692
    }
693
    return [values %keywords];
694 695
}

696
sub _check_product {
697
    my ($invocant, $name) = @_;
698 699 700 701 702 703 704 705 706
    # 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.
    my $obj = new Bugzilla::Product({ name => $name });
    return $obj;
}

707
sub _check_op_sys {
708
    my ($invocant, $op_sys) = @_;
709 710 711 712 713 714
    $op_sys = trim($op_sys);
    check_field('op_sys', $op_sys);
    return $op_sys;
}

sub _check_priority {
715
    my ($invocant, $priority) = @_;
716 717 718 719 720 721 722 723 724
    if (!Bugzilla->params->{'letsubmitterchoosepriority'}) {
        $priority = Bugzilla->params->{'defaultpriority'};
    }
    $priority = trim($priority);
    check_field('priority', $priority);

    return $priority;
}

725
sub _check_remaining_time {
726
    return $_[0]->_check_time($_[1], 'remaining_time');
727 728
}

729
sub _check_rep_platform {
730
    my ($invocant, $platform) = @_;
731 732 733 734 735
    $platform = trim($platform);
    check_field('rep_platform', $platform);
    return $platform;
}

736
sub _check_short_desc {
737
    my ($invocant, $short_desc) = @_;
738 739 740 741 742 743 744 745 746
    # 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;
}

747
sub _check_status_whiteboard { return defined $_[1] ? $_[1] : ''; }
748

749 750
# Unlike other checkers, this one doesn't return anything.
sub _check_strict_isolation {
751
    my ($invocant, $product, $cc_ids, $assignee_id, $qa_contact_id) = @_;
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779

    return unless Bugzilla->params->{'strict_isolation'};

    my @related_users = @$cc_ids;
    push(@related_users, $assignee_id);

    if (Bugzilla->params->{'useqacontact'} && $qa_contact_id) {
        push(@related_users, $qa_contact_id);
    }

    # For each unique user in @related_users...(assignee and qa_contact
    # could be duplicates of users in the CC list)
    my %unique_users = map {$_ => 1} @related_users;
    my @blocked_users;
    foreach my $pid (keys %unique_users) {
        my $related_user = Bugzilla::User->new($pid);
        if (!$related_user->can_edit_product($product->id)) {
            push (@blocked_users, $related_user->login);
        }
    }
    if (scalar(@blocked_users)) {
        ThrowUserError("invalid_user_group",
            {'users' => \@blocked_users,
             'new' => 1,
             'product' => $product->name});
    }
}

780
sub _check_target_milestone {
781
    my ($invocant, $product, $target) = @_;
782 783 784 785 786 787 788 789
    $target = trim($target);
    $target = $product->default_milestone if !defined $target;
    check_field('target_milestone', $target,
            [map($_->name, @{$product->milestones})]);
    return $target;
}

sub _check_time {
790
    my ($invocant, $time, $field) = @_;
791 792 793 794 795 796 797
    my $tt_group = Bugzilla->params->{"timetrackinggroup"};
    return 0 unless $tt_group && Bugzilla->user->in_group($tt_group);
    $time = trim($time) || 0;
    ValidateTime($time, $field);
    return $time;
}

798
sub _check_qa_contact {
799
    my ($invocant, $component, $name) = @_;
800 801
    my $user = Bugzilla->user;

802 803
    return undef unless Bugzilla->params->{'useqacontact'};

804 805 806
    $name = trim($name);

    my $id;
807
    if (!$user->in_group('editbugs', $component->product_id) || !$name) {
808 809 810 811 812 813 814 815 816
        # We want to insert NULL into the database if we get a 0.
        $id = $component->default_qa_contact->id || undef;
    } else {
        $id = login_to_id($name, THROW_ERROR);
    }

    return $id;
}

817
sub _check_version {
818
    my ($invocant, $product, $version) = @_;
819 820 821 822 823
    $version = trim($version);
    check_field('version', $version, [map($_->name, @{$product->versions})]);
    return $version;
}

824 825 826 827 828 829
sub _check_select_field {
    my ($invocant, $value, $field) = @_;
    $value = trim($value);
    check_field($field, $value);
    return $value;
}
830

831
#####################################################################
832 833 834 835 836 837 838 839 840 841 842 843 844
# Class Accessors
#####################################################################

sub fields {
    my $class = shift;

    return (
        # 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
845
           bug_status resolution dup_id
846 847 848 849 850 851
           bug_file_loc status_whiteboard keywords
           priority bug_severity target_milestone
           dependson blocked votes
           reporter assigned_to cc),
    
        # Conditional Fields
852 853 854
        Bugzilla->params->{'useqacontact'} ? "qa_contact" : (),
        Bugzilla->params->{'timetrackinggroup'} ? 
            qw(estimated_time remaining_time actual_time deadline) : (),
855 856 857 858 859 860 861 862 863
    
        # Custom Fields
        Bugzilla->custom_field_names
    );
}


#####################################################################
# Instance Accessors
864 865 866 867 868 869
#####################################################################

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

870 871 872 873 874
# 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.

875 876 877 878 879
sub dup_id {
    my ($self) = @_;
    return $self->{'dup_id'} if exists $self->{'dup_id'};

    $self->{'dup_id'} = undef;
880 881
    return if $self->{'error'};

882 883 884 885 886 887 888 889 890 891 892 893
    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'};
}

894 895 896 897
sub actual_time {
    my ($self) = @_;
    return $self->{'actual_time'} if exists $self->{'actual_time'};

898
    if ( $self->{'error'} || 
899
         !Bugzilla->user->in_group(Bugzilla->params->{"timetrackinggroup"}) ) {
900 901 902
        $self->{'actual_time'} = undef;
        return $self->{'actual_time'};
    }
903

904 905 906 907 908
    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();
909 910 911
    return $self->{'actual_time'};
}

912
sub any_flags_requesteeble {
913 914 915
    my ($self) = @_;
    return $self->{'any_flags_requesteeble'} 
        if exists $self->{'any_flags_requesteeble'};
916
    return 0 if $self->{'error'};
917 918 919 920 921 922 923

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

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

924
sub attachments {
925 926
    my ($self) = @_;
    return $self->{'attachments'} if exists $self->{'attachments'};
927
    return [] if $self->{'error'};
928 929 930

    $self->{'attachments'} =
        Bugzilla::Attachment->get_attachments_by_bug($self->bug_id);
931 932 933
    return $self->{'attachments'};
}

934
sub assigned_to {
935 936
    my ($self) = @_;
    return $self->{'assigned_to'} if exists $self->{'assigned_to'};
937
    $self->{'assigned_to_id'} = 0 if $self->{'error'};
938 939 940 941
    $self->{'assigned_to'} = new Bugzilla::User($self->{'assigned_to_id'});
    return $self->{'assigned_to'};
}

942
sub blocked {
943 944
    my ($self) = @_;
    return $self->{'blocked'} if exists $self->{'blocked'};
945
    return [] if $self->{'error'};
946 947 948 949
    $self->{'blocked'} = EmitDependList("dependson", "blocked", $self->bug_id);
    return $self->{'blocked'};
}

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

953
sub cc {
954 955
    my ($self) = @_;
    return $self->{'cc'} if exists $self->{'cc'};
956
    return [] if $self->{'error'};
957 958 959 960 961 962 963 964 965 966 967 968 969 970

    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'};
}

971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
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};
}

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

1001
sub dependson {
1002 1003
    my ($self) = @_;
    return $self->{'dependson'} if exists $self->{'dependson'};
1004
    return [] if $self->{'error'};
1005 1006 1007 1008 1009
    $self->{'dependson'} = 
        EmitDependList("blocked", "dependson", $self->bug_id);
    return $self->{'dependson'};
}

1010
sub flag_types {
1011 1012
    my ($self) = @_;
    return $self->{'flag_types'} if exists $self->{'flag_types'};
1013
    return [] if $self->{'error'};
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

    # The types of flags that can be set on this bug.
    # If none, no UI for setting flags will be displayed.
    my $flag_types = Bugzilla::FlagType::match(
        {'target_type'  => 'bug',
         'product_id'   => $self->{'product_id'}, 
         'component_id' => $self->{'component_id'} });

    foreach my $flag_type (@$flag_types) {
        $flag_type->{'flags'} = Bugzilla::Flag::match(
            { 'bug_id'      => $self->bug_id,
              'type_id'     => $flag_type->{'id'},
1026
              'target_type' => 'bug' });
1027 1028 1029 1030 1031 1032 1033
    }

    $self->{'flag_types'} = $flag_types;

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

1034
sub keywords {
1035 1036
    my ($self) = @_;
    return $self->{'keywords'} if exists $self->{'keywords'};
1037
    return () if $self->{'error'};
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

    my $dbh = Bugzilla->dbh;
    my $list_ref = $dbh->selectcol_arrayref(
         "SELECT keyworddefs.name
            FROM keyworddefs, keywords
           WHERE keywords.bug_id = ?
             AND keyworddefs.id = keywords.keywordid
        ORDER BY keyworddefs.name",
        undef, ($self->bug_id));

    $self->{'keywords'} = join(', ', @$list_ref);
    return $self->{'keywords'};
}

1052 1053 1054
sub longdescs {
    my ($self) = @_;
    return $self->{'longdescs'} if exists $self->{'longdescs'};
1055
    return [] if $self->{'error'};
1056
    $self->{'longdescs'} = GetComments($self->{bug_id});
1057 1058 1059
    return $self->{'longdescs'};
}

1060
sub milestoneurl {
1061 1062
    my ($self) = @_;
    return $self->{'milestoneurl'} if exists $self->{'milestoneurl'};
1063
    return '' if $self->{'error'};
1064

1065
    $self->{'prod_obj'} ||= new Bugzilla::Product({name => $self->product});
1066
    $self->{'milestoneurl'} = $self->{'prod_obj'}->milestone_url;
1067 1068 1069
    return $self->{'milestoneurl'};
}

1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
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};
}

1080
sub qa_contact {
1081 1082
    my ($self) = @_;
    return $self->{'qa_contact'} if exists $self->{'qa_contact'};
1083
    return undef if $self->{'error'};
1084

1085
    if (Bugzilla->params->{'useqacontact'} && $self->{'qa_contact_id'}) {
1086
        $self->{'qa_contact'} = new Bugzilla::User($self->{'qa_contact_id'});
1087 1088 1089 1090 1091 1092 1093 1094 1095
    } 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.
        $self->{'qa_contact'} = undef;
    }
    return $self->{'qa_contact'};
}

1096
sub reporter {
1097 1098
    my ($self) = @_;
    return $self->{'reporter'} if exists $self->{'reporter'};
1099
    $self->{'reporter_id'} = 0 if $self->{'error'};
1100 1101 1102 1103 1104
    $self->{'reporter'} = new Bugzilla::User($self->{'reporter_id'});
    return $self->{'reporter'};
}


1105
sub show_attachment_flags {
1106 1107 1108
    my ($self) = @_;
    return $self->{'show_attachment_flags'} 
        if exists $self->{'show_attachment_flags'};
1109
    return 0 if $self->{'error'};
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120

    # 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'} });
    my $num_attachment_flags = Bugzilla::Flag::count(
        { 'target_type'  => 'attachment',
1121
          'bug_id'       => $self->bug_id });
1122 1123 1124 1125 1126 1127 1128

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

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

1129 1130
sub use_votes {
    my ($self) = @_;
1131
    return 0 if $self->{'error'};
1132

1133
    $self->{'prod_obj'} ||= new Bugzilla::Product({name => $self->product});
1134

1135 1136
    return Bugzilla->params->{'usevotes'} 
           && $self->{'prod_obj'}->votes_per_user > 0;
1137 1138 1139 1140 1141
}

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

1144
    my $dbh = Bugzilla->dbh;
1145 1146 1147 1148 1149 1150 1151 1152 1153
    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.
    #
1154
    my $grouplist = Bugzilla->user->groups_as_string;
1155 1156
    my $sth = $dbh->prepare(
             "SELECT DISTINCT groups.id, name, description," .
1157 1158
             " CASE WHEN bug_group_map.group_id IS NOT NULL" .
             " THEN 1 ELSE 0 END," .
1159
             " CASE WHEN groups.id IN($grouplist) THEN 1 ELSE 0 END," .
1160 1161 1162 1163
             " isactive, membercontrol, othercontrol" .
             " FROM groups" . 
             " LEFT JOIN bug_group_map" .
             " ON bug_group_map.group_id = groups.id" .
1164
             " AND bug_id = ?" .
1165 1166
             " LEFT JOIN group_control_map" .
             " ON group_control_map.group_id = groups.id" .
1167
             " AND group_control_map.product_id = ? " .
1168 1169
             " WHERE isbuggroup = 1" .
             " ORDER BY description");
1170
    $sth->execute($self->{'bug_id'},
1171
                  $self->{'product_id'});
1172

1173 1174
    while (my ($groupid, $name, $description, $ison, $ingroup, $isactive,
            $membercontrol, $othercontrol) = $sth->fetchrow_array()) {
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191

        $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,
1192
                             "name" => $name,
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
                             "ison" => $ison,
                             "ingroup" => $ingroup,
                             "mandatory" => $ismandatory,
                             "description" => $description });
        }
    }

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

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

sub user {
    my $self = shift;
    return $self->{'user'} if exists $self->{'user'};
1208
    return {} if $self->{'error'};
1209

1210
    my $user = Bugzilla->user;
1211
    my $canmove = Bugzilla->params->{'move-enabled'} && $user->is_mover;
1212

1213 1214 1215
    my $prod_id = $self->{'product_id'};

    my $unknown_privileges = $user->in_group('editbugs', $prod_id);
1216
    my $canedit = $unknown_privileges
1217
                  || $user->id == $self->{assigned_to_id}
1218
                  || (Bugzilla->params->{'useqacontact'}
1219
                      && $self->{'qa_contact_id'}
1220
                      && $user->id == $self->{qa_contact_id});
1221
    my $canconfirm = $unknown_privileges
1222
                     || $user->in_group('canconfirm', $prod_id);
1223 1224
    my $isreporter = $user->id
                     && $user->id == $self->{reporter_id};
1225 1226 1227 1228 1229

    $self->{'user'} = {canmove    => $canmove,
                       canconfirm => $canconfirm,
                       canedit    => $canedit,
                       isreporter => $isreporter};
1230 1231 1232 1233 1234 1235
    return $self->{'user'};
}

sub choices {
    my $self = shift;
    return $self->{'choices'} if exists $self->{'choices'};
1236
    return {} if $self->{'error'};
1237 1238

    $self->{'choices'} = {};
1239
    $self->{prod_obj} ||= new Bugzilla::Product({name => $self->product});
1240

1241
    my @prodlist = map {$_->name} @{Bugzilla->user->get_enterable_products};
1242 1243
    # The current product is part of the popup, even if new bugs are no longer
    # allowed for that product
1244 1245
    if (lsearch(\@prodlist, $self->product) < 0) {
        push(@prodlist, $self->product);
1246 1247 1248 1249
        @prodlist = sort @prodlist;
    }

    # Hack - this array contains "". See bug 106589.
1250
    my @res = grep ($_, @{settable_resolutions()});
1251 1252 1253 1254

    $self->{'choices'} =
      {
       'product' => \@prodlist,
1255 1256 1257 1258 1259 1260 1261 1262
       '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,
       'component'    => [map($_->name, @{$self->{prod_obj}->components})],
       'version'      => [map($_->name, @{$self->{prod_obj}->versions})],
1263
       'target_milestone' => [map($_->name, @{$self->{prod_obj}->milestones})],
1264 1265 1266 1267
      };

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

1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
# List of resolutions that may be set directly by hand in the bug form.
# 'MOVED' and 'DUPLICATE' are excluded from the list because setting
# bugs to those resolutions requires a special process.
sub settable_resolutions {
    my $resolutions = get_legal_field_values('resolution');
    my $pos = lsearch($resolutions, 'DUPLICATE');
    if ($pos >= 0) {
        splice(@$resolutions, $pos, 1);
    }
    $pos = lsearch($resolutions, 'MOVED');
    if ($pos >= 0) {
        splice(@$resolutions, $pos, 1);
    }
    return $resolutions;
}

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
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};
}

1299 1300 1301 1302 1303
# 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.
1304
sub bug_alias_to_id {
1305
    my ($alias) = @_;
1306
    return undef unless Bugzilla->params->{"usebugaliases"};
1307 1308 1309 1310 1311 1312
    my $dbh = Bugzilla->dbh;
    trick_taint($alias);
    return $dbh->selectrow_array(
        "SELECT bug_id FROM bugs WHERE alias = ?", undef, $alias);
}

1313 1314 1315 1316
#####################################################################
# Subroutines
#####################################################################

1317
sub AppendComment {
1318 1319
    my ($bugid, $whoid, $comment, $isprivate, $timestamp, $work_time,
        $type, $extra_data) = @_;
1320
    $work_time ||= 0;
1321
    $type ||= CMT_NORMAL;
1322 1323 1324 1325
    my $dbh = Bugzilla->dbh;

    ValidateTime($work_time, "work_time") if $work_time;
    trick_taint($work_time);
1326 1327
    detaint_natural($type)
      || ThrowCodeError('bad_arg', {argument => 'type', function => 'AppendComment'});
1328 1329 1330

    # Use the date/time we were given if possible (allowing calling code
    # to synchronize the comment's timestamp with those of other records).
1331
    $timestamp ||= $dbh->selectrow_array('SELECT NOW()');
1332 1333 1334 1335

    $comment =~ s/\r\n/\n/g;     # Handle Windows-style line endings.
    $comment =~ s/\r/\n/g;       # Handle Mac-style line endings.

1336
    if ($comment =~ /^\s*$/ && !$type) {  # Nothin' but whitespace
1337 1338 1339 1340 1341 1342 1343 1344
        return;
    }

    # Comments are always safe, because we always display their raw contents,
    # and we use them in a placeholder below.
    trick_taint($comment); 
    my $privacyval = $isprivate ? 1 : 0 ;
    $dbh->do(q{INSERT INTO longdescs
1345 1346 1347 1348 1349
                      (bug_id, who, bug_when, thetext, isprivate, work_time,
                       type, extra_data)
               VALUES (?, ?, ?, ?, ?, ?, ?, ?)}, undef,
             ($bugid, $whoid, $timestamp, $comment, $privacyval, $work_time,
              $type, $extra_data));
1350 1351 1352
    $dbh->do("UPDATE bugs SET delta_ts = ? WHERE bug_id = ?",
             undef, $timestamp, $bugid);
}
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365

# 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');
    foreach my $remove ("bug_id", "creation_ts", "delta_ts", "lastdiffed") {
        my $location = lsearch(\@fields, $remove);
        splice(@fields, $location, 1);
    }
    # Sorted because the old @::log_columns variable, which this replaces,
    # was sorted.
    return sort(@fields);
}

1366
# This method is private and is not to be used outside of the Bug class.
1367
sub EmitDependList {
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
    my ($myfield, $targetfield, $bug_id) = (@_);
    my $dbh = Bugzilla->dbh;
    my $list_ref =
        $dbh->selectcol_arrayref(
          "SELECT dependencies.$targetfield
             FROM dependencies, bugs
            WHERE dependencies.$myfield = ?
              AND bugs.bug_id = dependencies.$targetfield
         ORDER BY dependencies.$targetfield",
         undef, ($bug_id));
1378
    return $list_ref;
1379 1380
}

1381 1382 1383 1384 1385 1386
# Tells you whether or not the argument is a valid "open" state.
sub is_open_state {
    my ($state) = @_;
    return (grep($_ eq $state, BUG_STATE_OPEN) ? 1 : 0);
}

1387
sub ValidateTime {
1388 1389 1390 1391 1392 1393 1394
    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",
1395
                       {field => "$field", num => "$time"});
1396 1397 1398 1399 1400
    }

    # Only the "work_time" field is allowed to contain a negative value.
    if ( ($time < 0) && ($field ne "work_time") ) {
        ThrowUserError("number_too_small",
1401
                       {field => "$field", num => "$time", min_num => "0"});
1402 1403 1404 1405
    }

    if ($time > 99999.99) {
        ThrowUserError("number_too_large",
1406
                       {field => "$field", num => "$time", max_num => "99999.99"});
1407
    }
1408
}
1409

1410
sub GetComments {
1411 1412 1413
    my ($id, $comment_sort_order, $start, $end) = @_;
    my $dbh = Bugzilla->dbh;

1414 1415 1416 1417
    $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';
1418

1419
    my @comments;
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
    my @args = ($id);

    my $query = 'SELECT profiles.realname AS name, profiles.login_name AS email, ' .
                        $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 = ?';
    if ($start) {
        $query .= ' AND longdescs.bug_when > ?
                    AND longdescs.bug_when <= ?';
        push(@args, ($start, $end));
    }
    $query .= " ORDER BY longdescs.bug_when $sort_order";
    my $sth = $dbh->prepare($query);
    $sth->execute(@args);
1438 1439 1440 1441

    while (my $comment_ref = $sth->fetchrow_hashref()) {
        my %comment = %$comment_ref;

1442
        $comment{'email'} .= Bugzilla->params->{'emailsuffix'};
1443
        $comment{'name'} = $comment{'name'} || $comment{'email'};
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
        if ($comment{'type'} == CMT_DUPE_OF) {
            $comment{'body'} .= "\n\n" . get_text('bug_duplicate_of',
                                                  { dupe_of => $comment{'extra_data'} });
        }
        elsif ($comment{'type'} == CMT_HAS_DUPE) {
            $comment{'body'} = get_text('bug_has_duplicate',
                                        { dupe => $comment{'extra_data'} });
        }
        elsif ($comment{'type'} == CMT_POPULAR_VOTES) {
            $comment{'body'} = get_text('bug_confirmed_by_votes');
        }
        elsif ($comment{'type'} == CMT_MOVED_TO) {
            $comment{'body'} .= "\n\n" . get_text('bug_moved_to',
                                                  { login => $comment{'extra_data'} });
        }
1459 1460 1461

        push (@comments, \%comment);
    }
1462 1463 1464 1465
   
    if ($comment_sort_order eq "newest_to_oldest_desc_first") {
        unshift(@comments, pop @comments);
    }
1466 1467 1468 1469

    return \@comments;
}

1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
# Get the activity of a bug, starting from $starttime (if given).
# This routine assumes ValidateBugID has been previously called.
sub GetBugActivity {
    my ($id, $starttime) = @_;
    my $dbh = Bugzilla->dbh;

    # Arguments passed to the SQL query.
    my @args = ($id);

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

    # Only includes attachments the user is allowed to see.
    my $suppjoins = "";
    my $suppwhere = "";
1490
    if (Bugzilla->params->{"insidergroup"} 
1491
        && !Bugzilla->user->in_group(Bugzilla->params->{'insidergroup'})) 
1492
    {
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
        $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
1511
            ON bugs_activity.fieldid = fielddefs.id
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
    INNER JOIN profiles
            ON profiles.userid = bugs_activity.who
         WHERE bugs_activity.bug_id = ?
               $datepart
               $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')
        {
1537
            $activity_visible = 
1538
                Bugzilla->user->in_group(Bugzilla->params->{'timetrackinggroup'}) ? 1 : 0;
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
        } else {
            $activity_visible = 1;
        }

        if ($activity_visible) {
            # This gets replaced with a hyperlink in the template.
            $field =~ s/^Attachment// if $attachid;

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

1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
# 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);
1614
        my $fieldid = get_field_id($col);
1615 1616 1617 1618 1619 1620 1621
        $dbh->do("INSERT INTO bugs_activity
                  (bug_id, who, bug_when, fieldid, removed, added)
                  VALUES (?, ?, ?, ?, ?, ?)",
                  undef, ($i, $whoid, $timestamp, $fieldid, $removestr, $addstr));
    }
}

1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
# 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(
1632
          "SELECT blocked, COUNT(bug_status) " .
1633 1634 1635
            "FROM bugs, dependencies " .
           "WHERE blocked IN (" . (join "," , @bug_list) . ") " .
             "AND bug_id = dependson " .
1636
             "AND bug_status IN ('" . (join "','", BUG_STATE_OPEN)  . "') " .
1637
          $dbh->sql_group_by('blocked'));
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
    $sth->execute();

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

    return @dependencies;
}

1648
sub ValidateComment {
1649 1650 1651 1652 1653 1654 1655
    my ($comment) = @_;

    if (defined($comment) && length($comment) > MAX_COMMENT_LENGTH) {
        ThrowUserError("comment_too_long");
    }
}

1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
# 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 " .
1669
                            "LEFT JOIN bugs ON votes.bug_id = bugs.bug_id " .
1670 1671 1672 1673 1674 1675 1676
                            "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]);
    }
1677 1678 1679 1680 1681

    # @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 = ();

1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
    if (scalar(@list)) {
        foreach my $ref (@list) {
            my ($name, $userid, $oldvotes, $votesperuser, $maxvotesperbug) = (@$ref);
            my $s;

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

            $s = ($oldvotes == 1) ? "" : "s";
            my $oldvotestext = "You had $oldvotes vote$s on this bug.";

            $s = ($removedvotes == 1) ? "" : "s";
            my $removedvotestext = "You had $removedvotes vote$s removed from this bug.";

            my $newvotestext;
            if ($newvotes) {
                $dbh->do("UPDATE votes SET vote_count = ? " .
                         "WHERE bug_id = ? AND who = ?",
                         undef, ($newvotes, $id, $userid));
                $s = $newvotes == 1 ? "" : "s";
                $newvotestext = "You still have $newvotes vote$s on this bug."
            } else {
                $dbh->do("DELETE FROM votes WHERE bug_id = ? AND who = ?",
                         undef, ($id, $userid));
                $newvotestext = "You have no more votes remaining on this bug.";
            }

            # 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.
1725
            my $vars = {
1726

1727
                'to' => $name . Bugzilla->params->{'emailsuffix'},
1728 1729
                'bugid' => $id,
                'reason' => $reason,
1730

1731 1732 1733
                'votesremoved' => $removedvotes,
                'votesold' => $oldvotes,
                'votesnew' => $newvotes,
1734

1735 1736 1737
                'votesremovedtext' => $removedvotestext,
                'votesoldtext' => $oldvotestext,
                'votesnewtext' => $newvotestext,
1738

1739 1740
                'count' => $removedvotes . "\n    " . $newvotestext
            };
1741

1742 1743 1744
            my $msg;
            my $template = Bugzilla->template;
            $template->process("email/votes-removed.txt.tmpl", $vars, \$msg);
1745
            push(@messages, $msg);
1746 1747 1748 1749 1750 1751 1752
        }
        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));
    }
1753 1754
    # Now return the array containing emails to be sent.
    return \@messages;
1755 1756
}

1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
# 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 {
    my ($id, $who) = (@_);
    my $dbh = Bugzilla->dbh;

    my ($votes, $status, $everconfirmed, $votestoconfirm, $timestamp) =
        $dbh->selectrow_array("SELECT votes, bug_status, everconfirmed, " .
                              "       votestoconfirm, NOW() " .
                              "FROM bugs INNER JOIN products " .
                              "                  ON products.id = bugs.product_id " .
                              "WHERE bugs.bug_id = ?",
                              undef, $id);

    my $ret = 0;
    if ($votes >= $votestoconfirm && !$everconfirmed) {
        if ($status eq 'UNCONFIRMED') {
1774
            my $fieldid = get_field_id("bug_status");
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
            $dbh->do("UPDATE bugs SET bug_status = 'NEW', everconfirmed = 1, " .
                     "delta_ts = ? WHERE bug_id = ?",
                     undef, ($timestamp, $id));
            $dbh->do("INSERT INTO bugs_activity " .
                     "(bug_id, who, bug_when, fieldid, removed, added) " .
                     "VALUES (?, ?, ?, ?, ?, ?)",
                     undef, ($id, $who, $timestamp, $fieldid, 'UNCONFIRMED', 'NEW'));
        }
        else {
            $dbh->do("UPDATE bugs SET everconfirmed = 1, delta_ts = ? " .
                     "WHERE bug_id = ?", undef, ($timestamp, $id));
        }

1788
        my $fieldid = get_field_id("everconfirmed");
1789 1790 1791 1792 1793
        $dbh->do("INSERT INTO bugs_activity " .
                 "(bug_id, who, bug_when, fieldid, removed, added) " .
                 "VALUES (?, ?, ?, ?, ?, ?)",
                 undef, ($id, $who, $timestamp, $fieldid, '0', '1'));

1794
        AppendComment($id, $who, "", 0, $timestamp, 0, CMT_POPULAR_VOTES);
1795 1796 1797 1798 1799 1800

        $ret = 1;
    }
    return $ret;
}

1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
################################################################################
# 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
# $data     - hash containing relevant parameters, e.g. from the CGI object
################################################################################
sub check_can_change_field {
    my $self = shift;
    my ($field, $oldvalue, $newvalue, $PrivilegesRequired, $data) = (@_);
1821
    my $user = Bugzilla->user;
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860

    $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;
    } elsif (trim($oldvalue) eq trim($newvalue)) {
        return 1;
    # numeric fields need to be compared using ==
    } elsif (($field eq 'estimated_time' || $field eq 'remaining_time')
             && $newvalue ne $data->{'dontchange'}
             && $oldvalue == $newvalue)
    {
        return 1;
    }

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

    # Ignore the assigned_to field if the bug is not being reassigned
    if ($field eq 'assigned_to'
        && $data->{'knob'} ne 'reassignbycomponent'
        && $data->{'knob'} ne 'reassign')
    {
        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.

1861 1862
    # Allow anyone with (product-specific) "editbugs" privs to change anything.
    if ($user->in_group('editbugs', $self->{'product_id'})) {
1863 1864 1865
        return 1;
    }

1866
    # *Only* users with (product-specific) "canconfirm" privs can confirm bugs.
1867 1868 1869 1870 1871
    if ($field eq 'canconfirm'
        || ($field eq 'bug_status'
            && $oldvalue eq 'UNCONFIRMED'
            && is_open_state($newvalue)))
    {
1872
        $$PrivilegesRequired = 3;
1873
        return $user->in_group('canconfirm', $self->{'product_id'});
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
    }

    # Make sure that a valid bug ID has been given.
    if (!$self->{'error'}) {
        # Allow the assignee to change anything else.
        if ($self->{'assigned_to_id'} == $user->id) {
            return 1;
        }

        # Allow the QA contact to change anything else.
        if (Bugzilla->params->{'useqacontact'}
            && $self->{'qa_contact_id'}
            && ($self->{'qa_contact_id'} == $user->id))
        {
            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') {
1901
        $$PrivilegesRequired = 2;
1902 1903 1904 1905
        return 0;
    }
    # - change the QA contact
    if ($field eq 'qa_contact') {
1906
        $$PrivilegesRequired = 2;
1907 1908 1909 1910
        return 0;
    }
    # - change the target milestone
    if ($field eq 'target_milestone') {
1911
        $$PrivilegesRequired = 2;
1912 1913 1914 1915
        return 0;
    }
    # - change the priority (unless he could have set it originally)
    if ($field eq 'priority'
1916
        && !Bugzilla->params->{'letsubmitterchoosepriority'})
1917
    {
1918
        $$PrivilegesRequired = 2;
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
        return 0;
    }

    # 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.
1929
    $$PrivilegesRequired = 1;
1930 1931 1932
    return 0;
}

1933 1934 1935 1936
#
# Field Validation
#

1937 1938 1939 1940 1941 1942 1943 1944 1945
# Validates and verifies a bug ID, making sure the number is a 
# positive integer, that it represents an existing bug in the
# database, and that the user is authorized to access that bug.
# We detaint the number here, too.
sub ValidateBugID {
    my ($id, $field) = @_;
    my $dbh = Bugzilla->dbh;
    my $user = Bugzilla->user;

1946 1947 1948
    # Get rid of leading '#' (number) mark, if present.
    $id =~ s/^\s*#//;
    # Remove whitespace
1949
    $id = trim($id);
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 1976 1977 1978 1979 1980 1981 1982
    # If the ID isn't a number, it might be an alias, so try to convert it.
    my $alias = $id;
    if (!detaint_natural($id)) {
        $id = bug_alias_to_id($alias);
        $id || ThrowUserError("invalid_bug_id_or_alias",
                              {'bug_id' => $alias,
                               'field'  => $field });
    }
    
    # Modify the calling code's original variable to contain the trimmed,
    # converted-from-alias ID.
    $_[0] = $id;
    
    # First check that the bug exists
    $dbh->selectrow_array("SELECT bug_id FROM bugs WHERE bug_id = ?", undef, $id)
      || ThrowUserError("invalid_bug_id_non_existent", {'bug_id' => $id});

    return if (defined $field && ($field eq "dependson" || $field eq "blocked"));
    
    return if $user->can_see_bug($id);

    # The user did not pass any of the authorization tests, which means they
    # are not authorized to see the bug.  Display an error and stop execution.
    # 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) {
        ThrowUserError("bug_access_denied", {'bug_id' => $id});
    } else {
        ThrowUserError("bug_access_query", {'bug_id' => $id});
    }
}

1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
# ValidateBugAlias:
#   Check that the bug alias is valid and not used by another bug.  If 
#   curr_id is specified, verify the alias is not used for any other
#   bug id.  
sub ValidateBugAlias {
    my ($alias, $curr_id) = @_;
    my $dbh = Bugzilla->dbh;

    $alias = trim($alias || "");
    trick_taint($alias);

    if ($alias eq "") {
        ThrowUserError("alias_not_defined");
    }

    # Make sure the alias isn't too long.
    if (length($alias) > 20) {
        ThrowUserError("alias_too_long");
    }

    # Make sure the alias is unique.
    my $query = "SELECT bug_id FROM bugs WHERE alias = ?";
2005
    if ($curr_id && detaint_natural($curr_id)) {
2006 2007 2008 2009 2010 2011 2012
        $query .= " AND bug_id != $curr_id";
    }
    my $id = $dbh->selectrow_array($query, undef, $alias); 

    my $vars = {};
    $vars->{'alias'} = $alias;
    if ($id) {
2013
        $vars->{'bug_id'} = $id;
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
        ThrowUserError("alias_in_use", $vars);
    }

    # Make sure the alias isn't just a number.
    if ($alias =~ /^\d+$/) {
        ThrowUserError("alias_is_numeric", $vars);
    }

    # Make sure the alias has no commas or spaces.
    if ($alias =~ /[, ]/) {
        ThrowUserError("alias_has_comma_or_space", $vars);
    }

    $_[0] = $alias;
}

2030
# Validate and return a hash of dependencies
2031
sub ValidateDependencies {
2032
    my $fields = {};
2033
    # These can be arrayrefs or they can be strings.
2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
    $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;
2054 2055 2056
        my $target_array = ref($fields->{$target}) ? $fields->{$target}
                           : [split(/[\s,]+/, $fields->{$target})];
        foreach my $i (@$target_array) {
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
            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}++ }
2092
    my @isect = keys %isect;
2093
    if (scalar(@isect) > 0) {
2094
        ThrowUserError("dependency_loop_multi", {'deps' => \@isect});
2095 2096 2097
    }
    return %deps;
}
2098

2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118

#####################################################################
# 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.
2119
        qw(error groups product_id component_id
2120 2121 2122
           longdescs milestoneurl attachments
           isopened isunconfirmed
           flag_types num_attachment_flag_types
2123
           show_attachment_flags any_flags_requesteeble),
2124 2125 2126 2127 2128 2129 2130 2131

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

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

2132 2133 2134 2135 2136 2137
sub AUTOLOAD {
  use vars qw($AUTOLOAD);
  my $attr = $AUTOLOAD;

  $attr =~ s/.*:://;
  return unless $attr=~ /[^A-Z]/;
2138 2139 2140 2141
  if (!_validate_attribute($attr)) {
      require Carp;
      Carp::confess("invalid bug attribute $attr");
  }
2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153

  no strict 'refs';
  *$AUTOLOAD = sub {
      my $self = shift;
      if (defined $self->{$attr}) {
          return $self->{$attr};
      } else {
          return '';
      }
  };

  goto &$AUTOLOAD;
2154 2155 2156
}

1;