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

package Bugzilla::Comment;

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

14
use parent qw(Bugzilla::Object);
15

16
use Bugzilla::Attachment;
17
use Bugzilla::Comment::TagWeights;
18 19
use Bugzilla::Constants;
use Bugzilla::Error;
20
use Bugzilla::User;
21 22
use Bugzilla::Util;

23
use List::Util qw(first);
24 25
use Scalar::Util qw(blessed);

26 27 28 29
###############################
####    Initialization     ####
###############################

30 31 32
# Creation and updating of comments are audited in longdescs
# and bugs_activity respectively instead of audit_log.
use constant AUDIT_CREATES => 0;
33 34
use constant AUDIT_UPDATES => 0;

35
use constant DB_COLUMNS => qw(
36 37 38 39 40
  comment_id
  bug_id
  who
  bug_when
  work_time
41
  productive_time
42 43 44 45 46
  thetext
  isprivate
  already_wrapped
  type
  extra_data
47 48
);

49
use constant UPDATE_COLUMNS => qw(
50 51 52
  isprivate
  type
  extra_data
53 54
);

55 56
use constant DB_TABLE => 'longdescs';
use constant ID_FIELD => 'comment_id';
57

58 59 60 61
# In some rare cases, two comments can have identical timestamps. If
# this happens, we want to be sure that the comment added later shows up
# later in the sequence.
use constant LIST_ORDER => 'bug_when, comment_id';
62

63
use constant VALIDATORS => {
64 65 66 67
  bug_id     => \&_check_bug_id,
  who        => \&_check_who,
  bug_when   => \&_check_bug_when,
  work_time  => \&_check_work_time,
68
  productive_time => \&_check_work_time,
69 70 71 72
  thetext    => \&_check_thetext,
  isprivate  => \&_check_isprivate,
  extra_data => \&_check_extra_data,
  type       => \&_check_type,
73 74
};

75
use constant VALIDATOR_DEPENDENCIES => {
76 77 78 79
  extra_data => ['type'],
  bug_id     => ['who'],
  work_time  => ['who', 'bug_id'],
  isprivate  => ['who'],
80 81 82 83 84 85 86
};

#########################
# Database Manipulation #
#########################

sub update {
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  my $self = shift;
  my ($changes, $old_comment) = $self->SUPER::update(@_);

  if (exists $changes->{'thetext'} || exists $changes->{'isprivate'}) {
    $self->bug->_sync_fulltext(update_comments => 1);
  }

  my @old_tags = @{$old_comment->tags};
  my @new_tags = @{$self->tags};
  my ($removed_tags, $added_tags) = diff_arrays(\@old_tags, \@new_tags);

  if (@$removed_tags || @$added_tags) {
    my $dbh        = Bugzilla->dbh;
    my $when       = $dbh->selectrow_array("SELECT LOCALTIMESTAMP(0)");
    my $sth_delete = $dbh->prepare(
      "DELETE FROM longdescs_tags WHERE comment_id = ? AND tag = ?");
    my $sth_insert
      = $dbh->prepare("INSERT INTO longdescs_tags(comment_id, tag) VALUES (?, ?)");
    my $sth_activity = $dbh->prepare(
      "INSERT INTO longdescs_tags_activity
107 108
            (bug_id, comment_id, who, bug_when, added, removed)
            VALUES (?, ?, ?, ?, ?, ?)"
109
    );
110

111 112 113 114 115
    foreach my $tag (@$removed_tags) {
      my $weighted = Bugzilla::Comment::TagWeights->new({name => $tag});
      if ($weighted) {
        if ($weighted->weight == 1) {
          $weighted->remove_from_db();
116
        }
117 118 119 120 121 122 123 124 125
        else {
          $weighted->set_weight($weighted->weight - 1);
          $weighted->update();
        }
      }
      trick_taint($tag);
      $sth_delete->execute($self->id, $tag);
      $sth_activity->execute($self->bug_id, $self->id, Bugzilla->user->id, $when, '',
        $tag);
126 127
    }

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    foreach my $tag (@$added_tags) {
      my $weighted = Bugzilla::Comment::TagWeights->new({name => $tag});
      if ($weighted) {
        $weighted->set_weight($weighted->weight + 1);
        $weighted->update();
      }
      else {
        Bugzilla::Comment::TagWeights->create({tag => $tag, weight => 1});
      }
      trick_taint($tag);
      $sth_insert->execute($self->id, $tag);
      $sth_activity->execute($self->bug_id, $self->id, Bugzilla->user->id, $when,
        $tag, '');
    }
  }

  return $changes;
145 146
}

147 148
# Speeds up displays of comment lists by loading all author objects and tags at
# once for a whole list.
149
sub preload {
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
  my ($class, $comments) = @_;

  # Author
  my %user_ids = map { $_->{who} => 1 } @$comments;
  my $users    = Bugzilla::User->new_from_list([keys %user_ids]);
  my %user_map = map { $_->id => $_ } @$users;
  foreach my $comment (@$comments) {
    $comment->{author} = $user_map{$comment->{who}};
  }

  # Tags
  if (Bugzilla->params->{'comment_taggers_group'}) {
    my $dbh         = Bugzilla->dbh;
    my @comment_ids = map { $_->id } @$comments;
    my %comment_map = map { $_->id => $_ } @$comments;
    my $rows        = $dbh->selectall_arrayref(
      "SELECT comment_id, " . $dbh->sql_group_concat('tag', "','") . "
167
               FROM longdescs_tags
168 169 170 171 172 173
              WHERE "
        . $dbh->sql_in('comment_id', \@comment_ids) . ' '
        . $dbh->sql_group_by('comment_id')
    );
    foreach my $row (@$rows) {
      $comment_map{$row->[0]}->{tags} = [split(/,/, $row->[1])];
174
    }
175 176 177 178 179 180

    # Also sets the 'tags' attribute for comments which have no entry
    # in the longdescs_tags table, else calling $comment->tags will
    # trigger another SQL query again.
    $comment_map{$_}->{tags} ||= [] foreach @comment_ids;
  }
181 182
}

183 184 185 186 187
###############################
####      Accessors      ######
###############################

sub already_wrapped { return $_[0]->{'already_wrapped'}; }
188 189 190 191 192 193 194 195 196 197
sub body            { return $_[0]->{'thetext'}; }
sub bug_id          { return $_[0]->{'bug_id'}; }
sub creation_ts     { return $_[0]->{'bug_when'}; }
sub is_private      { return $_[0]->{'isprivate'}; }

sub work_time {

  # Work time is returned as a string (see bug 607909)
  return 0 if $_[0]->{'work_time'} + 0 == 0;
  return $_[0]->{'work_time'};
198
}
199 200 201 202 203 204 205 206

sub productive_time {
  # Work_time-like function

  return 0 if $_[0]->{'productive_time'} + 0 == 0;
  return $_[0]->{'productive_time'};
}

207 208
sub type       { return $_[0]->{'type'}; }
sub extra_data { return $_[0]->{'extra_data'} }
209

210
sub tags {
211 212 213 214 215
  my ($self) = @_;
  state $comment_taggers_group = Bugzilla->params->{'comment_taggers_group'};
  return [] unless $comment_taggers_group;
  $self->{'tags'} ||= Bugzilla->dbh->selectcol_arrayref(
    "SELECT tag
216 217
           FROM longdescs_tags
          WHERE comment_id = ?
218 219 220
          ORDER BY tag", undef, $self->id
  );
  return $self->{'tags'};
221 222 223
}

sub collapsed {
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
  my ($self) = @_;
  state $comment_taggers_group = Bugzilla->params->{'comment_taggers_group'};
  return 0 unless $comment_taggers_group;
  return $self->{collapsed} if exists $self->{collapsed};

  state $collapsed_comment_tags = Bugzilla->params->{'collapsed_comment_tags'};
  $self->{collapsed} = 0;
  Bugzilla->request_cache->{comment_tags_collapsed}
    ||= [split(/\s*,\s*/, $collapsed_comment_tags)];
  my @collapsed_tags = @{Bugzilla->request_cache->{comment_tags_collapsed}};
  foreach my $my_tag (@{$self->tags}) {
    $my_tag = lc($my_tag);
    foreach my $collapsed_tag (@collapsed_tags) {
      if ($my_tag eq lc($collapsed_tag)) {
        $self->{collapsed} = 1;
        last;
      }
241
    }
242 243 244
    last if $self->{collapsed};
  }
  return $self->{collapsed};
245 246
}

247
sub bug {
248 249 250 251
  my $self = shift;
  require Bugzilla::Bug;
  $self->{bug} ||= new Bugzilla::Bug($self->bug_id);
  return $self->{bug};
252 253 254
}

sub is_about_attachment {
255 256 257 258 259
  my ($self) = @_;
  return 1
    if ($self->type == CMT_ATTACHMENT_CREATED
    or $self->type == CMT_ATTACHMENT_UPDATED);
  return 0;
260 261 262
}

sub attachment {
263 264 265 266 267
  my ($self) = @_;
  return undef if not $self->is_about_attachment;
  $self->{attachment}
    ||= new Bugzilla::Attachment({id => $self->extra_data, cache => 1});
  return $self->{attachment};
268
}
269

270 271 272 273
sub author {
  my $self = shift;
  $self->{'author'} ||= new Bugzilla::User({id => $self->{'who'}, cache => 1});
  return $self->{'author'};
274 275 276
}

sub body_full {
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
  my ($self, $params) = @_;
  $params ||= {};
  my $template = Bugzilla->template_inner;
  my $body;
  if ($self->type) {
    $template->process("bug/format_comment.txt.tmpl", {comment => $self, %$params},
      \$body)
      || ThrowTemplateError($template->error());
    $body =~ s/^X//;
  }
  else {
    $body = $self->body;
  }
  if ($params->{wrap} and !$self->already_wrapped) {
    $body = wrap_comment($body);
  }
  return $body;
294 295
}

296 297 298 299
############
# Mutators #
############

300 301 302
sub set_is_private { $_[0]->set('isprivate',  $_[1]); }
sub set_type       { $_[0]->set('type',       $_[1]); }
sub set_extra_data { $_[0]->set('extra_data', $_[1]); }
303

304
sub add_tag {
305 306
  my ($self, $tag) = @_;
  $tag = $self->_check_tag($tag);
307

308 309 310 311
  my $tags = $self->tags;
  return if grep { lc($tag) eq lc($_) } @$tags;
  push @$tags, $tag;
  $self->{'tags'} = [sort @$tags];
312 313 314
}

sub remove_tag {
315 316
  my ($self, $tag) = @_;
  $tag = $self->_check_tag($tag);
317

318
  my $tags  = $self->tags;
319 320 321
  my $index = first { lc($tags->[$_]) eq lc($tag) } 0 .. scalar(@$tags) - 1;
  return unless defined $index;
  splice(@$tags, $index, 1);
322 323
}

324 325 326 327
##############
# Validators #
##############

328
sub run_create_validators {
329 330 331 332 333 334 335 336 337
  my $self   = shift;
  my $params = $self->SUPER::run_create_validators(@_);

  # Sometimes this run_create_validators is called with parameters that
  # skip bug_id validation, so it might not exist in the resulting hash.
  if (defined $params->{bug_id}) {
    $params->{bug_id} = $params->{bug_id}->id;
  }
  return $params;
338 339
}

340
sub _check_extra_data {
341 342
  my ($invocant, $extra_data, undef, $params) = @_;
  my $type = blessed($invocant) ? $invocant->type : $params->{type};
343

344 345 346 347 348 349 350 351 352 353 354 355 356
  if ($type == CMT_NORMAL) {
    if (defined $extra_data) {
      ThrowCodeError('comment_extra_data_not_allowed',
        {type => $type, extra_data => $extra_data});
    }
  }
  else {
    if (!defined $extra_data) {
      ThrowCodeError('comment_extra_data_required', {type => $type});
    }
    elsif ($type == CMT_ATTACHMENT_CREATED or $type == CMT_ATTACHMENT_UPDATED) {
      my $attachment = Bugzilla::Attachment->check({id => $extra_data});
      $extra_data = $attachment->id;
357 358
    }
    else {
359 360 361 362
      my $original = $extra_data;
      detaint_natural($extra_data)
        or ThrowCodeError('comment_extra_data_not_numeric',
        {type => $type, extra_data => $original});
363
    }
364
  }
365

366
  return $extra_data;
367 368 369
}

sub _check_type {
370 371 372 373 374 375
  my ($invocant, $type) = @_;
  $type ||= CMT_NORMAL;
  my $original = $type;
  detaint_natural($type)
    or ThrowCodeError('comment_type_invalid', {type => $original});
  return $type;
376 377
}

378
sub _check_bug_id {
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
  my ($invocant, $bug_id) = @_;

  ThrowCodeError('param_required',
    {function => 'Bugzilla::Comment->create', param => 'bug_id'})
    unless $bug_id;

  my $bug;
  if (blessed $bug_id) {

    # We got a bug object passed in, use it
    $bug = $bug_id;
    $bug->check_is_visible;
  }
  else {
    # We got a bug id passed in, check it and get the bug object
    $bug = Bugzilla::Bug->check({id => $bug_id});
  }

  # Make sure the user can edit the product
  Bugzilla->user->can_edit_product($bug->{product_id});

  # Make sure the user can comment
  my $privs;
  $bug->check_can_change_field('longdesc', 0, 1, \$privs)
    || ThrowUserError('illegal_change', {field => 'longdesc', privs => $privs});
  return $bug;
405 406 407
}

sub _check_who {
408 409 410
  my ($invocant, $who) = @_;
  Bugzilla->login(LOGIN_REQUIRED);
  return Bugzilla->user->id;
411 412 413
}

sub _check_bug_when {
414
  my ($invocant, $when) = @_;
415

416 417 418 419
  # Make sure the timestamp is defined, default to a timestamp from the db
  if (!defined $when) {
    $when = Bugzilla->dbh->selectrow_array('SELECT LOCALTIMESTAMP(0)');
  }
420

421 422 423 424
  # Make sure the timestamp parses
  if (!datetime_from($when)) {
    ThrowCodeError('invalid_timestamp', {timestamp => $when});
  }
425

426
  return $when;
427 428 429
}

sub _check_work_time {
430 431 432 433 434 435 436 437 438
  my ($invocant, $value_in, $field, $params) = @_;

  # Call down to Bugzilla::Object, letting it know negative
  # values are ok
  my $time = $invocant->check_time($value_in, $field, $params, 1);
  my $privs;
  $params->{bug_id}->check_can_change_field('work_time', 0, $time, \$privs)
    || ThrowUserError('illegal_change', {field => 'work_time', privs => $privs});
  return $time;
439 440 441
}

sub _check_thetext {
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
  my ($invocant, $thetext) = @_;

  ThrowCodeError('param_required',
    {function => 'Bugzilla::Comment->create', param => 'thetext'})
    unless defined $thetext;

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

  # Characters above U+FFFF cannot be stored by MySQL older than 5.5.3 as they
  # require the new utf8mb4 character set. Other DB servers are handling them
  # without any problem. So we need to replace these characters if we use MySQL,
  # else the comment is truncated.
  # XXX - Once we use utf8mb4 for comments, this hack for MySQL can go away.
  state $is_mysql = Bugzilla->dbh->isa('Bugzilla::DB::Mysql') ? 1 : 0;
  if ($is_mysql) {

    # Perl 5.13.8 and older complain about non-characters.
    no warnings 'utf8';
    $thetext
      =~ s/([\x{10000}-\x{10FFFF}])/"\x{FDD0}[" . uc(sprintf('U+%04x', ord($1))) . "]\x{FDD1}"/eg;
  }

  ThrowUserError('comment_too_long') if length($thetext) > MAX_COMMENT_LENGTH;
  return $thetext;
469 470 471
}

sub _check_isprivate {
472 473 474 475 476
  my ($invocant, $isprivate) = @_;
  if ($isprivate && !Bugzilla->user->is_insider) {
    ThrowUserError('user_not_insider');
  }
  return $isprivate ? 1 : 0;
477 478
}

479
sub _check_tag {
480 481 482 483 484 485 486
  my ($invocant, $tag) = @_;
  length($tag) < MIN_COMMENT_TAG_LENGTH
    and ThrowUserError('comment_tag_too_short', {tag => $tag});
  length($tag) > MAX_COMMENT_TAG_LENGTH
    and ThrowUserError('comment_tag_too_long', {tag => $tag});
  $tag =~ /^[\w\d\._-]+$/ or ThrowUserError('comment_tag_invalid', {tag => $tag});
  return $tag;
487 488
}

489
sub count {
490
  my ($self) = @_;
491

492
  return $self->{'count'} if defined $self->{'count'};
493

494 495 496
  my $dbh = Bugzilla->dbh;
  ($self->{'count'}) = $dbh->selectrow_array(
    "SELECT COUNT(*)
497 498
           FROM longdescs 
          WHERE bug_id = ? 
499 500
                AND bug_when <= ?", undef, $self->bug_id, $self->creation_ts
  );
501

502
  return --$self->{'count'};
503
}
504

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
1;

__END__

=head1 NAME

Bugzilla::Comment - A Comment for a given bug 

=head1 SYNOPSIS

 use Bugzilla::Comment;

 my $comment = Bugzilla::Comment->new($comment_id);
 my $comments = Bugzilla::Comment->new_from_list($comment_ids);

=head1 DESCRIPTION

Bugzilla::Comment represents a comment attached to a bug.

This implements all standard C<Bugzilla::Object> methods. See 
L<Bugzilla::Object> for more details.

=head2 Accessors

=over

=item C<bug_id>

C<int> The ID of the bug to which the comment belongs.

=item C<creation_ts>

C<string> The comment creation timestamp.

=item C<body>

C<string> The body without any special additional text.

=item C<work_time>

C<string> Time spent as related to this comment.

=item C<is_private>

549
C<boolean> Comment is marked as private.
550 551 552 553 554 555 556 557 558 559

=item C<already_wrapped>

If this comment is stored in the database word-wrapped, this will be C<1>.
C<0> otherwise.

=item C<author>

L<Bugzilla::User> who created the comment.

560 561 562 563
=item C<count>

C<int> The position this comment is located in the full list of comments for a bug starting from 0.

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 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
=item C<collapsed>

C<boolean> Comment should be displayed as collapsed by default.

=item C<tags>

C<array of strings> The tags attached to the comment.

=item C<add_tag>

=over

=item B<Description>

Attaches the specified tag to the comment.

=item B<Params>

=over

=item C<tag>

C<string> The tag to attach.

=back

=back

=item C<remove_tag>

=over

=item B<Description>

Detaches the specified tag from the comment.

=item B<Params>

=over

=item C<tag>

C<string> The tag to detach.

=back

=back

612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
=item C<body_full>

=over

=item B<Description>

C<string> Body of the comment, including any special text (such as
"this bug was marked as a duplicate of...").

=item B<Params>

=over

=item C<is_bugmail>

C<boolean>. C<1> if this comment should be formatted specifically for
bugmail.

=item C<wrap>

C<boolean>. C<1> if the comment should be returned word-wrapped.

=back

=item B<Returns>

A string, the full text of the comment as it would be displayed to an end-user.

=back

=back

=cut
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670

=head1 B<Methods in need of POD>

=over

=item set_type

=item bug

=item set_extra_data

=item set_is_private

=item attachment

=item is_about_attachment

=item extra_data

=item preload

=item type

=item update

=back