Bug.pm 19.8 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

26
package Bugzilla::Bug;
27

28 29
use strict;

30
use vars qw($legal_keywords @legal_platform
31 32 33
            @legal_priority @legal_severity @legal_opsys @legal_bugs_status
            @settable_resolution %components %versions %target_milestone
            @enterable_products %milestoneurl %prodmaxvotes);
34

35 36
use CGI::Carp qw(fatalsToBrowser);

37
use Bugzilla;
38
use Bugzilla::Attachment;
39
use Bugzilla::Config;
40 41 42 43
use Bugzilla::Constants;
use Bugzilla::Flag;
use Bugzilla::FlagType;
use Bugzilla::User;
44
use Bugzilla::Util;
45
use Bugzilla::Error;
46

47 48 49 50
sub fields {
    # Keep this ordering in sync with bugzilla.dtd
    my @fields = qw(bug_id alias creation_ts short_desc delta_ts
                    reporter_accessible cclist_accessible
51
                    classification_id classification
52 53 54 55 56
                    product component version rep_platform op_sys
                    bug_status resolution
                    bug_file_loc status_whiteboard keywords
                    priority bug_severity target_milestone
                    dependson blocked votes
57
                    reporter assigned_to cc
58 59
                   );

60 61 62 63
    if (Param('useqacontact')) {
        push @fields, "qa_contact";
    }

64
    if (Param('timetrackinggroup')) {
65
        push @fields, qw(estimated_time remaining_time actual_time deadline);
66 67 68 69 70 71 72 73 74 75 76 77 78
    }

    return @fields;
}

my %ok_field;
foreach my $key (qw(error groups
                    longdescs milestoneurl attachments
                    isopened isunconfirmed
                    flag_types num_attachment_flag_types
                    show_attachment_flags use_keywords any_flags_requesteeble
                   ),
                 fields()) {
79
    $ok_field{$key}++;
80
}
81 82 83 84 85

# create a new empty bug
#
sub new {
  my $type = shift();
86
  my %bug;
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

  # 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) = (@_);
112
  my $dbh = Bugzilla->dbh;
113

114 115 116 117
  $bug_id = trim($bug_id);

  my $old_bug_id = $bug_id;

118
  # If the bug ID isn't numeric, it might be an alias, so try to convert it.
119
  $bug_id = &::BugAliasToID($bug_id) if $bug_id !~ /^0*[1-9][0-9]*$/;
120

121
  if ((! defined $bug_id) || (!$bug_id) || (!detaint_natural($bug_id))) {
122
      # no bug number given or the alias didn't match a bug
123 124 125
      $self->{'bug_id'} = $old_bug_id;
      $self->{'error'} = "InvalidBugId";
      return $self;
126 127
  }

cyeh%bluemartini.com's avatar
cyeh%bluemartini.com committed
128 129
# default userid 0, or get DBID if you used an email address
  unless (defined $user_id) {
130 131
    $user_id = 0;
  }
cyeh%bluemartini.com's avatar
cyeh%bluemartini.com committed
132 133
  else {
     if ($user_id =~ /^\@/) {
134
        $user_id = &::DBname_to_id($user_id); 
cyeh%bluemartini.com's avatar
cyeh%bluemartini.com committed
135 136
     }
  }
137

138
  $self->{'who'} = new Bugzilla::User($user_id);
139 140

  my $query = "
141
    SELECT
142 143
      bugs.bug_id, alias, products.classification_id, classifications.name,
      bugs.product_id, products.name, version,
144 145 146 147 148
      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,
      qa_contact, status_whiteboard,
      DATE_FORMAT(creation_ts,'%Y.%m.%d %H:%i'),
149
      delta_ts, COALESCE(SUM(votes.vote_count), 0),
150
      reporter_accessible, cclist_accessible,
151
      estimated_time, remaining_time, DATE_FORMAT(deadline,'%Y-%m-%d')
152
    from bugs left join votes using(bug_id),
153
      classifications, products, components
154
    WHERE bugs.bug_id = ?
155
      AND classifications.id = products.classification_id
156 157
      AND products.id = bugs.product_id
      AND components.id = bugs.component_id
158 159
    group by bugs.bug_id";

160 161 162
  my $bug_sth = $dbh->prepare($query);
  $bug_sth->execute($bug_id);
  my @row;
163

164 165
  if ((@row = $bug_sth->fetchrow_array()) 
      && $self->{'who'}->can_see_bug($bug_id)) {
166 167
    my $count = 0;
    my %fields;
168 169
    foreach my $field ("bug_id", "alias", "classification_id", "classification",
                       "product_id", "product", "version", 
170 171 172 173 174
                       "rep_platform", "op_sys", "bug_status", "resolution", 
                       "priority", "bug_severity", "component_id", "component",
                       "assigned_to", "reporter", "bug_file_loc", "short_desc",
                       "target_milestone", "qa_contact", "status_whiteboard", 
                       "creation_ts", "delta_ts", "votes",
175
                       "reporter_accessible", "cclist_accessible",
176
                       "estimated_time", "remaining_time", "deadline")
177
      {
178
        $fields{$field} = shift @row;
179
        if (defined $fields{$field}) {
180 181 182
            $self->{$field} = $fields{$field};
        }
        $count++;
183
    }
184
  } elsif (@row) {
185 186
      $self->{'bug_id'} = $bug_id;
      $self->{'error'} = "NotPermitted";
187
      return $self;
188
  } else {
189 190
      $self->{'bug_id'} = $bug_id;
      $self->{'error'} = "NotFound";
191 192 193
      return $self;
  }

194 195 196 197 198
  $self->{'assigned_to'} = new Bugzilla::User($self->{'assigned_to'});
  $self->{'reporter'} = new Bugzilla::User($self->{'reporter'});

  if (Param('useqacontact') && $self->{'qa_contact'} > 0) {
      $self->{'qa_contact'} = new Bugzilla::User($self->{'qa_contact'});
199 200
  } else {
      $self->{'qa_contact'} = undef;
201
  }
202

203 204 205 206 207 208 209 210
  my $cc_ref = $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, $bug_id);
  if (scalar(@$cc_ref)) {
    $self->{'cc'} = $cc_ref;
211 212 213
  }

  if (@::legal_keywords) {
214 215 216
    # Get all entries and make them an array.
    my $list_ref = $dbh->selectcol_arrayref(
           "SELECT keyworddefs.name
217
              FROM keyworddefs, keywords
218
             WHERE keywords.bug_id = ?
219
               AND keyworddefs.id = keywords.keywordid
220 221 222 223
          ORDER BY keyworddefs.name",
        undef, ($bug_id));
    if ($list_ref) {
      $self->{'keywords'} = join(', ', @$list_ref);
224 225 226
    }
  }

227
  $self->{'attachments'} = Bugzilla::Attachment::query($self->{bug_id});
228 229 230 231 232 233 234 235 236 237 238

  # 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'},
239 240
                                'target_type' => 'bug',
                                'is_active'   => 1 });
241 242
  }
  $self->{'flag_types'} = $flag_types;
243
  $self->{'any_flags_requesteeble'} = grep($_->{'is_requesteeble'}, @$flag_types);
244 245 246 247 248 249 250 251

  # 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'},
252
                                'component_id' => $self->{'component_id'} });
253 254
  my $num_attachment_flags =
    Bugzilla::Flag::count({ 'target_type'  => 'attachment',
255 256
                            'bug_id'       => $self->{bug_id},
                            'is_active'    => 1 });
257 258 259 260 261 262

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

  $self->{'milestoneurl'} = $::milestoneurl{$self->{product}};

263
  $self->{'isunconfirmed'} = ($self->{bug_status} eq 'UNCONFIRMED');
264
  $self->{'isopened'} = &::IsOpenedState($self->{bug_status});
265 266 267
  
  my @depends = EmitDependList("blocked", "dependson", $bug_id);
  if (@depends) {
268
      $self->{'dependson'} = \@depends;
269
  }
270 271 272
  my @blocked = EmitDependList("dependson", "blocked", $bug_id);
  if (@blocked) {
    $self->{'blocked'} = \@blocked;
273
  }
cyeh%bluemartini.com's avatar
cyeh%bluemartini.com committed
274

275 276 277
  return $self;
}

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
sub dup_id {
    my ($self) = @_;

    return $self->{'dup_id'} if exists $self->{'dup_id'};

    $self->{'dup_id'} = undef;
    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'};
}

296 297 298 299 300
sub actual_time {
    my ($self) = @_;

    return $self->{'actual_time'} if exists $self->{'actual_time'};

301
    return undef unless Bugzilla->user->in_group(Param("timetrackinggroup"));
302

303 304 305 306 307
    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();
308 309 310 311 312 313 314 315
    return $self->{'actual_time'};
}

sub longdescs {
    my ($self) = @_;

    return $self->{'longdescs'} if exists $self->{'longdescs'};

316
    $self->{'longdescs'} = GetComments($self->{bug_id});
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336

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

sub use_keywords {
    return @::legal_keywords;
}

sub use_votes {
    my ($self) = @_;

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

sub groups {
    my $self = shift;

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

337
    my $dbh = Bugzilla->dbh;
338 339 340 341 342 343 344 345 346
    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.
    #
347 348
    my $sth = $dbh->prepare(
             "SELECT DISTINCT groups.id, name, description," .
349 350 351 352 353 354
             " bug_group_map.group_id IS NOT NULL," .
             " user_group_map.group_id IS NOT NULL," .
             " isactive, membercontrol, othercontrol" .
             " FROM groups" . 
             " LEFT JOIN bug_group_map" .
             " ON bug_group_map.group_id = groups.id" .
355
             " AND bug_id = ?" .
356 357
             " LEFT JOIN user_group_map" .
             " ON user_group_map.group_id = groups.id" .
358
             " AND user_id = ?" .
359
             " AND isbless = 0" .
360 361
             " LEFT JOIN group_control_map" .
             " ON group_control_map.group_id = groups.id" .
362
             " AND group_control_map.product_id = ? " .
363
             " WHERE isbuggroup = 1");
364 365
    $sth->execute($self->{'bug_id'}, Bugzilla->user->id,
                  $self->{'product_id'});
366

367 368
    while (my ($groupid, $name, $description, $ison, $ingroup, $isactive,
            $membercontrol, $othercontrol) = $sth->fetchrow_array()) {
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385

        $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,
386
                             "name" => $name,
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
                             "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'};

403
    my @movers = map { trim $_ } split(",", Param("movers"));
404
    my $canmove = Param("move-enabled") && Bugzilla->user->id && 
405 406 407 408 409 410 411 412
                  (lsearch(\@movers, Bugzilla->user->login) != -1);

    # 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.
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    my $unknown_privileges = !Bugzilla->user->id
                             || Bugzilla->user->in_group("editbugs");
    my $canedit = $unknown_privileges
                  || Bugzilla->user->id == $self->{'assigned_to'}{'id'}
                  || (Param('useqacontact')
                      && $self->{'qa_contact'}
                      && Bugzilla->user->id == $self->{'qa_contact'}{'id'});
    my $canconfirm = $unknown_privileges
                     || Bugzilla->user->in_group("canconfirm");
    my $isreporter = Bugzilla->user->id
                     && Bugzilla->user->id == $self->{'reporter'}{'id'};

    $self->{'user'} = {canmove    => $canmove,
                       canconfirm => $canconfirm,
                       canedit    => $canedit,
                       isreporter => $isreporter};
429 430 431 432 433 434 435 436 437 438
    return $self->{'user'};
}

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

    &::GetVersionTable();

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

440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    # 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;
        }

        if (!&::CanEnterProduct($product)) {
            # 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,
       'bug_status' => \@::legal_bugs_status,
       'resolution' => \@res,
       'component' => $::components{$self->{product}},
       'version' => $::versions{$self->{product}},
       'target_milestone' => $::target_milestone{$self->{product}},
      };

    return $self->{'choices'};
}
490 491

sub EmitDependList {
492 493 494 495 496 497 498 499 500 501 502
    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));
    return @$list_ref;
503 504
}

505
sub ValidateTime {
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
    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",
                       {field => "$field", num => "$time"},
                       "abort");
    }

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

    if ($time > 99999.99) {
        ThrowUserError("number_too_large",
                       {field => "$field", num => "$time", max_num => "99999.99"},
                       "abort");
    }
529
}
530

531 532 533 534 535 536 537 538
sub GetComments {
    my ($id) = (@_);
    my $dbh = Bugzilla->dbh;
    my @comments;
    my $sth = $dbh->prepare(
            "SELECT  profiles.realname AS name, profiles.login_name AS email,
                     date_format(longdescs.bug_when,'%Y.%m.%d %H:%i') AS time,
                     longdescs.thetext AS body, longdescs.work_time,
539
                     isprivate, already_wrapped,
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
                     date_format(longdescs.bug_when,'%Y%m%d%H%i%s')
            FROM     longdescs, profiles
            WHERE    profiles.userid = longdescs.who
              AND    longdescs.bug_id = ?
            ORDER BY longdescs.bug_when");
    $sth->execute($id);

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

        # Can't use "when" as a field name in MySQL
        $comment{'when'} = $comment{'bug_when'};
        delete($comment{'bug_when'});

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

        push (@comments, \%comment);
    }

    return \@comments;
}

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
# 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(
          "SELECT blocked, count(bug_status) " .
            "FROM bugs, dependencies " .
           "WHERE blocked IN (" . (join "," , @bug_list) . ") " .
             "AND bug_id = dependson " .
             "AND bug_status IN ('" . (join "','", &::OpenStates())  . "') " .
        "GROUP BY blocked ");
    $sth->execute();

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

    return @dependencies;
}

589 590 591 592 593 594
sub AUTOLOAD {
  use vars qw($AUTOLOAD);
  my $attr = $AUTOLOAD;

  $attr =~ s/.*:://;
  return unless $attr=~ /[^A-Z]/;
595
  confess ("invalid bug attribute $attr") unless $ok_field{$attr};
596 597 598 599 600 601 602 603 604 605 606 607

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

  goto &$AUTOLOAD;
608 609 610
}

1;