Bug.pm 46.5 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 vars qw($legal_keywords @legal_platform
34
            @legal_priority @legal_severity @legal_opsys @legal_bug_status
35 36
            @settable_resolution %components %versions %target_milestone
            @enterable_products %milestoneurl %prodmaxvotes);
37

38 39
use CGI::Carp qw(fatalsToBrowser);

40
use Bugzilla::Attachment;
41
use Bugzilla::Config;
42
use Bugzilla::Constants;
43
use Bugzilla::Field;
44 45 46
use Bugzilla::Flag;
use Bugzilla::FlagType;
use Bugzilla::User;
47
use Bugzilla::Util;
48
use Bugzilla::Error;
49

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

58 59 60 61 62 63 64 65 66
#####################################################################
# Constants
#####################################################################

# 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.
67 68
use constant MAX_COMMENT_LENGTH => 65535;

69 70
#####################################################################

71 72 73 74
# create a new empty bug
#
sub new {
  my $type = shift();
75
  my %bug;
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

  # create a ref to an empty hash and bless it
  #
  my $self = {%bug};
  bless $self, $type;

  # construct from a hash containing a bug's info
  #
  if ($#_ == 1) {
    $self->initBug(@_);
  } else {
    confess("invalid number of arguments \($#_\)($_)");
  }

  # bless as a Bug
  #
  return $self;
}

# dump info about bug into hash unless user doesn't have permission
# user_id 0 is used when person is not logged in.
#
sub initBug  {
  my $self = shift();
  my ($bug_id, $user_id) = (@_);
101
  my $dbh = Bugzilla->dbh;
102

103 104 105 106
  $bug_id = trim($bug_id);

  my $old_bug_id = $bug_id;

107
  # If the bug ID isn't numeric, it might be an alias, so try to convert it.
108
  $bug_id = bug_alias_to_id($bug_id) if $bug_id !~ /^0*[1-9][0-9]*$/;
109

110
  if ((! defined $bug_id) || (!$bug_id) || (!detaint_natural($bug_id))) {
111
      # no bug number given or the alias didn't match a bug
112 113 114
      $self->{'bug_id'} = $old_bug_id;
      $self->{'error'} = "InvalidBugId";
      return $self;
115 116
  }

117 118 119 120 121
  # If the user is not logged in, sets $user_id to 0.
  # Else gets $user_id from the user login name if this
  # argument is not numeric.
  my $stored_user_id = $user_id;
  if (!defined $user_id) {
122
    $user_id = 0;
123 124
  } elsif (!detaint_natural($user_id)) {
    $user_id = login_to_id($stored_user_id); 
cyeh%bluemartini.com's avatar
cyeh%bluemartini.com committed
125
  }
126

127
  $self->{'who'} = new Bugzilla::User($user_id);
128

129
    my $custom_fields = "";
130
    if (scalar(Bugzilla->custom_field_names) > 0) {
131 132 133
        $custom_fields = ", " . join(", ", Bugzilla->custom_field_names);
    }

134
  my $query = "
135
    SELECT
136 137
      bugs.bug_id, alias, products.classification_id, classifications.name,
      bugs.product_id, products.name, version,
138
      rep_platform, op_sys, bug_status, resolution, priority,
139 140 141 142
      bug_severity, bugs.component_id, components.name, 
      assigned_to AS assigned_to_id, reporter AS reporter_id,
      bug_file_loc, short_desc, target_milestone,
      qa_contact AS qa_contact_id, status_whiteboard, " .
143
      $dbh->sql_date_format('creation_ts', '%Y.%m.%d %H:%i') . ",
144
      delta_ts, COALESCE(SUM(votes.vote_count), 0), everconfirmed,
145
      reporter_accessible, cclist_accessible,
146
      estimated_time, remaining_time, " .
147 148
      $dbh->sql_date_format('deadline', '%Y-%m-%d') .
      $custom_fields . "
149 150
    FROM bugs
       LEFT JOIN votes
151
              ON bugs.bug_id = votes.bug_id
152 153 154 155 156 157 158
      INNER JOIN components
              ON components.id = bugs.component_id
      INNER JOIN products
              ON products.id = bugs.product_id
      INNER JOIN classifications
              ON classifications.id = products.classification_id
      WHERE bugs.bug_id = ? " .
159 160 161 162 163
    $dbh->sql_group_by('bugs.bug_id', 'alias, products.classification_id,
      classifications.name, bugs.product_id, products.name, version,
      rep_platform, op_sys, bug_status, resolution, priority,
      bug_severity, bugs.component_id, components.name, assigned_to,
      reporter, bug_file_loc, short_desc, target_milestone,
164
      qa_contact, status_whiteboard, everconfirmed, creation_ts, 
165 166
      delta_ts, reporter_accessible, cclist_accessible,
      estimated_time, remaining_time, deadline');
167

168 169 170
  my $bug_sth = $dbh->prepare($query);
  $bug_sth->execute($bug_id);
  my @row;
171

172 173
  if ((@row = $bug_sth->fetchrow_array()) 
      && $self->{'who'}->can_see_bug($bug_id)) {
174 175
    my $count = 0;
    my %fields;
176 177
    foreach my $field ("bug_id", "alias", "classification_id", "classification",
                       "product_id", "product", "version", 
178 179
                       "rep_platform", "op_sys", "bug_status", "resolution", 
                       "priority", "bug_severity", "component_id", "component",
180 181 182
                       "assigned_to_id", "reporter_id", 
                       "bug_file_loc", "short_desc",
                       "target_milestone", "qa_contact_id", "status_whiteboard",
183
                       "creation_ts", "delta_ts", "votes", "everconfirmed",
184
                       "reporter_accessible", "cclist_accessible",
185 186
                       "estimated_time", "remaining_time", "deadline",
                       Bugzilla->custom_field_names)
187
      {
188
        $fields{$field} = shift @row;
189
        if (defined $fields{$field}) {
190 191 192
            $self->{$field} = $fields{$field};
        }
        $count++;
193
    }
194
  } elsif (@row) {
195 196
      $self->{'bug_id'} = $bug_id;
      $self->{'error'} = "NotPermitted";
197
      return $self;
198
  } else {
199 200
      $self->{'bug_id'} = $bug_id;
      $self->{'error'} = "NotFound";
201 202 203
      return $self;
  }

204
  $self->{'isunconfirmed'} = ($self->{bug_status} eq 'UNCONFIRMED');
205
  $self->{'isopened'} = &::IsOpenedState($self->{bug_status});
206
  
207 208 209
  return $self;
}

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 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
# 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

    $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',
                         'longdescs WRITE', 'votes WRITE');

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

264

265
#####################################################################
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
# 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
           bug_status resolution
           bug_file_loc status_whiteboard keywords
           priority bug_severity target_milestone
           dependson blocked votes
           reporter assigned_to cc),
    
        # Conditional Fields
        Param('useqacontact') ? "qa_contact" : (),
        Param('timetrackinggroup') ? qw(estimated_time remaining_time
                                        actual_time deadline)
                                   : (),
    
        # Custom Fields
        Bugzilla->custom_field_names
    );
}


#####################################################################
# Instance Accessors
299 300 301 302 303 304
#####################################################################

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

305 306 307 308 309
# 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.

310 311 312 313 314
sub dup_id {
    my ($self) = @_;
    return $self->{'dup_id'} if exists $self->{'dup_id'};

    $self->{'dup_id'} = undef;
315 316
    return if $self->{'error'};

317 318 319 320 321 322 323 324 325 326 327 328
    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'};
}

329 330 331 332
sub actual_time {
    my ($self) = @_;
    return $self->{'actual_time'} if exists $self->{'actual_time'};

333 334 335 336 337
    if ( $self->{'error'} || 
         !Bugzilla->user->in_group(Param("timetrackinggroup")) ) {
        $self->{'actual_time'} = undef;
        return $self->{'actual_time'};
    }
338

339 340 341 342 343
    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();
344 345 346
    return $self->{'actual_time'};
}

347
sub any_flags_requesteeble {
348 349 350
    my ($self) = @_;
    return $self->{'any_flags_requesteeble'} 
        if exists $self->{'any_flags_requesteeble'};
351
    return 0 if $self->{'error'};
352 353 354 355 356 357 358

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

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

359
sub attachments {
360 361
    my ($self) = @_;
    return $self->{'attachments'} if exists $self->{'attachments'};
362
    return [] if $self->{'error'};
363 364 365

    $self->{'attachments'} =
        Bugzilla::Attachment->get_attachments_by_bug($self->bug_id);
366 367 368
    return $self->{'attachments'};
}

369
sub assigned_to {
370 371
    my ($self) = @_;
    return $self->{'assigned_to'} if exists $self->{'assigned_to'};
372
    $self->{'assigned_to_id'} = 0 if $self->{'error'};
373 374 375 376
    $self->{'assigned_to'} = new Bugzilla::User($self->{'assigned_to_id'});
    return $self->{'assigned_to'};
}

377
sub blocked {
378 379
    my ($self) = @_;
    return $self->{'blocked'} if exists $self->{'blocked'};
380
    return [] if $self->{'error'};
381 382 383 384
    $self->{'blocked'} = EmitDependList("dependson", "blocked", $self->bug_id);
    return $self->{'blocked'};
}

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

388
sub cc {
389 390
    my ($self) = @_;
    return $self->{'cc'} if exists $self->{'cc'};
391
    return [] if $self->{'error'};
392 393 394 395 396 397 398 399 400 401 402 403 404 405

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

406
sub dependson {
407 408
    my ($self) = @_;
    return $self->{'dependson'} if exists $self->{'dependson'};
409
    return [] if $self->{'error'};
410 411 412 413 414
    $self->{'dependson'} = 
        EmitDependList("blocked", "dependson", $self->bug_id);
    return $self->{'dependson'};
}

415
sub flag_types {
416 417
    my ($self) = @_;
    return $self->{'flag_types'} if exists $self->{'flag_types'};
418
    return [] if $self->{'error'};
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439

    # 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'},
              'target_type' => 'bug',
              'is_active'   => 1 });
    }

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

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

440
sub keywords {
441 442
    my ($self) = @_;
    return $self->{'keywords'} if exists $self->{'keywords'};
443
    return () if $self->{'error'};
444 445 446 447 448 449 450 451 452 453 454 455 456 457

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

458 459 460
sub longdescs {
    my ($self) = @_;
    return $self->{'longdescs'} if exists $self->{'longdescs'};
461
    return [] if $self->{'error'};
462
    $self->{'longdescs'} = GetComments($self->{bug_id});
463 464 465
    return $self->{'longdescs'};
}

466
sub milestoneurl {
467 468
    my ($self) = @_;
    return $self->{'milestoneurl'} if exists $self->{'milestoneurl'};
469
    return '' if $self->{'error'};
470 471 472 473
    $self->{'milestoneurl'} = $::milestoneurl{$self->{product}};
    return $self->{'milestoneurl'};
}

474
sub qa_contact {
475 476
    my ($self) = @_;
    return $self->{'qa_contact'} if exists $self->{'qa_contact'};
477
    return undef if $self->{'error'};
478

479
    if (Param('useqacontact') && $self->{'qa_contact_id'}) {
480
        $self->{'qa_contact'} = new Bugzilla::User($self->{'qa_contact_id'});
481 482 483 484 485 486 487 488 489
    } 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'};
}

490
sub reporter {
491 492
    my ($self) = @_;
    return $self->{'reporter'} if exists $self->{'reporter'};
493
    $self->{'reporter_id'} = 0 if $self->{'error'};
494 495 496 497 498
    $self->{'reporter'} = new Bugzilla::User($self->{'reporter_id'});
    return $self->{'reporter'};
}


499
sub show_attachment_flags {
500 501 502
    my ($self) = @_;
    return $self->{'show_attachment_flags'} 
        if exists $self->{'show_attachment_flags'};
503
    return 0 if $self->{'error'};
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524

    # 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',
          'bug_id'       => $self->bug_id,
          'is_active'    => 1 });

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

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


525 526 527 528 529 530
sub use_keywords {
    return @::legal_keywords;
}

sub use_votes {
    my ($self) = @_;
531
    return 0 if $self->{'error'};
532 533 534 535 536 537 538 539

    return Param('usevotes')
      && $::prodmaxvotes{$self->{product}} > 0;
}

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

542
    my $dbh = Bugzilla->dbh;
543 544 545 546 547 548 549 550 551
    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.
    #
552
    my $grouplist = Bugzilla->user->groups_as_string;
553 554
    my $sth = $dbh->prepare(
             "SELECT DISTINCT groups.id, name, description," .
555 556
             " CASE WHEN bug_group_map.group_id IS NOT NULL" .
             " THEN 1 ELSE 0 END," .
557
             " CASE WHEN groups.id IN($grouplist) THEN 1 ELSE 0 END," .
558 559 560 561
             " isactive, membercontrol, othercontrol" .
             " FROM groups" . 
             " LEFT JOIN bug_group_map" .
             " ON bug_group_map.group_id = groups.id" .
562
             " AND bug_id = ?" .
563 564
             " LEFT JOIN group_control_map" .
             " ON group_control_map.group_id = groups.id" .
565
             " AND group_control_map.product_id = ? " .
566 567
             " WHERE isbuggroup = 1" .
             " ORDER BY description");
568
    $sth->execute($self->{'bug_id'},
569
                  $self->{'product_id'});
570

571 572
    while (my ($groupid, $name, $description, $ison, $ingroup, $isactive,
            $membercontrol, $othercontrol) = $sth->fetchrow_array()) {
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589

        $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,
590
                             "name" => $name,
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
                             "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'};
606
    return {} if $self->{'error'};
607

608 609
    my $user = Bugzilla->user;
    my $canmove = Param('move-enabled') && $user->is_mover;
610 611 612 613 614 615 616

    # In the below, if the person hasn't logged in, then we treat them
    # as if they can do anything.  That's because we don't know why they
    # haven't logged in; it may just be because they don't use cookies.
    # Display everything as if they have all the permissions in the
    # world; their permissions will get checked when they log in and
    # actually try to make the change.
617 618
    my $unknown_privileges = !$user->id
                             || $user->in_group("editbugs");
619
    my $canedit = $unknown_privileges
620
                  || $user->id == $self->{assigned_to_id}
621
                  || (Param('useqacontact')
622
                      && $self->{'qa_contact_id'}
623
                      && $user->id == $self->{qa_contact_id});
624
    my $canconfirm = $unknown_privileges
625 626 627
                     || $user->in_group("canconfirm");
    my $isreporter = $user->id
                     && $user->id == $self->{reporter_id};
628 629 630 631 632

    $self->{'user'} = {canmove    => $canmove,
                       canconfirm => $canconfirm,
                       canedit    => $canedit,
                       isreporter => $isreporter};
633 634 635 636 637 638
    return $self->{'user'};
}

sub choices {
    my $self = shift;
    return $self->{'choices'} if exists $self->{'choices'};
639
    return {} if $self->{'error'};
640 641 642 643

    &::GetVersionTable();

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

645 646 647 648 649 650 651 652 653 654 655 656 657 658
    # Fiddle the product list.
    my $seen_curr_prod;
    my @prodlist;

    foreach my $product (@::enterable_products) {
        if ($product eq $self->{'product'}) {
            # if it's the product the bug is already in, it's ALWAYS in
            # the popup, period, whether the user can see it or not, and
            # regardless of the disallownew setting.
            $seen_curr_prod = 1;
            push(@prodlist, $product);
            next;
        }

659
        if (!Bugzilla->user->can_enter_product($product)) {
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
            # If we're using bug groups to restrict entry on products, and
            # this product has an entry group, and the user is not in that
            # group, we don't want to include that product in this list.
            next;
        }

        push(@prodlist, $product);
    }

    # The current product is part of the popup, even if new bugs are no longer
    # allowed for that product
    if (!$seen_curr_prod) {
        push (@prodlist, $self->{'product'});
        @prodlist = sort @prodlist;
    }

    # Hack - this array contains "". See bug 106589.
    my @res = grep ($_, @::settable_resolution);

    $self->{'choices'} =
      {
       'product' => \@prodlist,
       'rep_platform' => \@::legal_platform,
       'priority' => \@::legal_priority,
       'bug_severity' => \@::legal_severity,
       'op_sys' => \@::legal_opsys,
686
       'bug_status' => \@::legal_bug_status,
687 688 689 690 691 692 693 694
       'resolution' => \@res,
       'component' => $::components{$self->{product}},
       'version' => $::versions{$self->{product}},
       'target_milestone' => $::target_milestone{$self->{product}},
      };

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

696 697 698 699 700
# 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.
701
sub bug_alias_to_id {
702 703 704 705 706 707 708 709
    my ($alias) = @_;
    return undef unless Param("usebugaliases");
    my $dbh = Bugzilla->dbh;
    trick_taint($alias);
    return $dbh->selectrow_array(
        "SELECT bug_id FROM bugs WHERE alias = ?", undef, $alias);
}

710 711 712 713
#####################################################################
# Subroutines
#####################################################################

714
sub AppendComment {
715
    my ($bugid, $whoid, $comment, $isprivate, $timestamp, $work_time) = @_;
716 717 718 719 720 721 722 723
    $work_time ||= 0;
    my $dbh = Bugzilla->dbh;

    ValidateTime($work_time, "work_time") if $work_time;
    trick_taint($work_time);

    # Use the date/time we were given if possible (allowing calling code
    # to synchronize the comment's timestamp with those of other records).
724
    $timestamp ||= $dbh->selectrow_array('SELECT NOW()');
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

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

    if ($comment =~ /^\s*$/) {  # Nothin' but whitespace
        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
                      (bug_id, who, bug_when, thetext, isprivate, work_time)
               VALUES (?,?,?,?,?,?)}, undef,
             ($bugid, $whoid, $timestamp, $comment, $privacyval, $work_time));
    $dbh->do("UPDATE bugs SET delta_ts = ? WHERE bug_id = ?",
             undef, $timestamp, $bugid);
}
744
# This method is private and is not to be used outside of the Bug class.
745
sub EmitDependList {
746 747 748 749 750 751 752 753 754 755
    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));
756
    return $list_ref;
757 758
}

759
sub ValidateTime {
760 761 762 763 764 765 766
    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",
767
                       {field => "$field", num => "$time"});
768 769 770 771 772
    }

    # Only the "work_time" field is allowed to contain a negative value.
    if ( ($time < 0) && ($field ne "work_time") ) {
        ThrowUserError("number_too_small",
773
                       {field => "$field", num => "$time", min_num => "0"});
774 775 776 777
    }

    if ($time > 99999.99) {
        ThrowUserError("number_too_large",
778
                       {field => "$field", num => "$time", max_num => "99999.99"});
779
    }
780
}
781

782
sub GetComments {
783 784 785 786 787
    my ($id, $comment_sort_order) = (@_);
    $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';
788 789 790 791
    my $dbh = Bugzilla->dbh;
    my @comments;
    my $sth = $dbh->prepare(
            "SELECT  profiles.realname AS name, profiles.login_name AS email,
792
            " . $dbh->sql_date_format('longdescs.bug_when', '%Y.%m.%d %H:%i:%s') . "
793
               AS time, longdescs.thetext AS body, longdescs.work_time,
794
                     isprivate, already_wrapped
795
             FROM    longdescs, profiles
796 797
            WHERE    profiles.userid = longdescs.who
              AND    longdescs.bug_id = ?
798
            ORDER BY longdescs.bug_when $sort_order");
799 800 801 802 803 804 805 806 807 808
    $sth->execute($id);

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

        $comment{'email'} .= Param('emailsuffix');
        $comment{'name'} = $comment{'name'} || $comment{'email'};

        push (@comments, \%comment);
    }
809 810 811 812
   
    if ($comment_sort_order eq "newest_to_oldest_desc_first") {
        unshift(@comments, pop @comments);
    }
813 814 815 816

    return \@comments;
}

817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
# 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 = "";
    if (Param("insidergroup") && !UserInGroup(Param('insidergroup'))) {
        $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
            ON bugs_activity.fieldid = fielddefs.fieldid
    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')
        {
            $activity_visible = UserInGroup(Param('timetrackinggroup')) ? 1 : 0;
        } 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);
}

930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
# 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);
958
        my $fieldid = get_field_id($col);
959 960 961 962 963 964 965
        $dbh->do("INSERT INTO bugs_activity
                  (bug_id, who, bug_when, fieldid, removed, added)
                  VALUES (?, ?, ?, ?, ?, ?)",
                  undef, ($i, $whoid, $timestamp, $fieldid, $removestr, $addstr));
    }
}

966 967 968 969 970 971 972 973 974 975
# 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(
976
          "SELECT blocked, COUNT(bug_status) " .
977 978 979 980
            "FROM bugs, dependencies " .
           "WHERE blocked IN (" . (join "," , @bug_list) . ") " .
             "AND bug_id = dependson " .
             "AND bug_status IN ('" . (join "','", &::OpenStates())  . "') " .
981
          $dbh->sql_group_by('blocked'));
982 983 984 985 986 987 988 989 990 991
    $sth->execute();

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

    return @dependencies;
}

992
sub ValidateComment {
993 994 995 996 997 998 999
    my ($comment) = @_;

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

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
# 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 " .
1013
                            "LEFT JOIN bugs ON votes.bug_id = bugs.bug_id " .
1014 1015 1016 1017 1018 1019 1020
                            "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]);
    }
1021 1022 1023 1024 1025

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

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
    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.
            my %substs;

            $substs{"to"} = $name . Param('emailsuffix');
            $substs{"bugid"} = $id;
            $substs{"reason"} = $reason;

            $substs{"votesremoved"} = $removedvotes;
            $substs{"votesold"} = $oldvotes;
            $substs{"votesnew"} = $newvotes;

            $substs{"votesremovedtext"} = $removedvotestext;
            $substs{"votesoldtext"} = $oldvotestext;
            $substs{"votesnewtext"} = $newvotestext;

            $substs{"count"} = $removedvotes . "\n    " . $newvotestext;

1085
            my $msg = perform_substs(Param("voteremovedmail"), \%substs);
1086
            push(@messages, $msg);
1087 1088 1089 1090 1091 1092 1093
        }
        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));
    }
1094 1095
    # Now return the array containing emails to be sent.
    return \@messages;
1096 1097
}

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
# 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') {
1115
            my $fieldid = get_field_id("bug_status");
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
            $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));
        }

1129
        my $fieldid = get_field_id("everconfirmed");
1130 1131 1132 1133 1134
        $dbh->do("INSERT INTO bugs_activity " .
                 "(bug_id, who, bug_when, fieldid, removed, added) " .
                 "VALUES (?, ?, ?, ?, ?, ?)",
                 undef, ($id, $who, $timestamp, $fieldid, '0', '1'));

1135
        AppendComment($id, $who,
1136 1137 1138 1139 1140 1141 1142 1143
                      "*** This bug has been confirmed by popular vote. ***",
                      0, $timestamp);

        $ret = 1;
    }
    return $ret;
}

1144 1145 1146 1147
#
# Field Validation
#

1148 1149 1150 1151 1152 1153 1154 1155 1156
# 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;

1157 1158 1159
    # Get rid of leading '#' (number) mark, if present.
    $id =~ s/^\s*#//;
    # Remove whitespace
1160
    $id = trim($id);
1161

1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
    # 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});
    }
}

1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
# 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 = ?";
    if (detaint_natural($curr_id)) {
        $query .= " AND bug_id != $curr_id";
    }
    my $id = $dbh->selectrow_array($query, undef, $alias); 

    my $vars = {};
    $vars->{'alias'} = $alias;
    if ($id) {
1224
        $vars->{'bug_id'} = $id;
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
        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;
}

1241
# Validate and return a hash of dependencies
1242
sub ValidateDependencies {
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
    my $fields = {};
    $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;
        foreach my $i (split('[\s,]+', $fields->{$target})) {
            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}++ }
1300
    my @isect = keys %isect;
1301
    if (scalar(@isect) > 0) {
1302
        ThrowUserError("dependency_loop_multi", {'deps' => \@isect});
1303 1304 1305
    }
    return %deps;
}
1306

1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339

#####################################################################
# 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.
        qw(error groups
           longdescs milestoneurl attachments
           isopened isunconfirmed
           flag_types num_attachment_flag_types
           show_attachment_flags use_keywords any_flags_requesteeble),

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

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

1340 1341 1342 1343 1344 1345
sub AUTOLOAD {
  use vars qw($AUTOLOAD);
  my $attr = $AUTOLOAD;

  $attr =~ s/.*:://;
  return unless $attr=~ /[^A-Z]/;
1346
  confess("invalid bug attribute $attr") unless _validate_attribute($attr);
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358

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

  goto &$AUTOLOAD;
1359 1360 1361
}

1;