You need to sign in or sign up before continuing.
Attachment.pm 26.2 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
package Bugzilla::Attachment;
9 10 11

use 5.10.1;
use strict;
12
use warnings;
13

14 15
=head1 NAME

16
Bugzilla::Attachment - Bugzilla attachment class.
17 18 19 20 21 22

=head1 SYNOPSIS

  use Bugzilla::Attachment;

  # Get the attachment with the given ID.
23
  my $attachment = new Bugzilla::Attachment($attach_id);
24 25

  # Get the attachments with the given IDs.
26
  my $attachments = Bugzilla::Attachment->new_from_list($attach_ids);
27 28 29

=head1 DESCRIPTION

30 31 32 33 34 35
Attachment.pm represents an attachment object. It is an implementation
of L<Bugzilla::Object>, and thus provides all methods that
L<Bugzilla::Object> provides.

The methods that are specific to C<Bugzilla::Attachment> are listed
below.
36 37 38

=cut

39
use Bugzilla::Constants;
40
use Bugzilla::Error;
41
use Bugzilla::Flag;
42
use Bugzilla::User;
43 44
use Bugzilla::Util;
use Bugzilla::Field;
45
use Bugzilla::Hook;
46

47 48
use File::Copy;
use List::Util qw(max);
49
use Storable qw(dclone);
50

51
use base qw(Bugzilla::Object);
52

53 54 55
###############################
####    Initialization     ####
###############################
56

57 58 59
use constant DB_TABLE   => 'attachments';
use constant ID_FIELD   => 'attach_id';
use constant LIST_ORDER => ID_FIELD;
60

61
# Attachments are tracked in bugs_activity.
62
use constant AUDIT_CREATES => 0;
63
use constant AUDIT_UPDATES => 0;
64

65
use constant DB_COLUMNS => qw(
66 67 68 69 70 71 72 73 74 75 76
  attach_id
  bug_id
  creation_ts
  description
  filename
  isobsolete
  ispatch
  isprivate
  mimetype
  modification_time
  submitter_id
77
);
78

79
use constant REQUIRED_FIELD_MAP    => {bug_id => 'bug',};
80
use constant EXTRA_REQUIRED_FIELDS => qw(data);
81 82

use constant UPDATE_COLUMNS => qw(
83 84 85 86 87 88
  description
  filename
  isobsolete
  ispatch
  isprivate
  mimetype
89 90 91
);

use constant VALIDATORS => {
92 93 94 95 96 97
  bug         => \&_check_bug,
  description => \&_check_description,
  filename    => \&_check_filename,
  ispatch     => \&Bugzilla::Object::check_boolean,
  isprivate   => \&_check_is_private,
  mimetype    => \&_check_content_type,
98 99
};

100 101
use constant VALIDATOR_DEPENDENCIES =>
  {content_type => ['ispatch'], mimetype => ['ispatch'],};
102

103 104
use constant UPDATE_VALIDATORS =>
  {isobsolete => \&Bugzilla::Object::check_boolean,};
105

106 107 108
###############################
####      Accessors      ######
###############################
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

=pod

=head2 Instance Properties

=over

=item C<bug_id>

the ID of the bug to which the attachment is attached

=back

=cut

sub bug_id {
125
  return $_[0]->{bug_id};
126 127 128 129
}

=over

130 131 132 133 134 135 136 137 138
=item C<bug>

the bug object to which the attachment is attached

=back

=cut

sub bug {
139 140
  require Bugzilla::Bug;
  return $_[0]->{bug} //= Bugzilla::Bug->new({id => $_[0]->bug_id, cache => 1});
141 142 143 144
}

=over

145 146 147 148 149 150 151 152 153
=item C<description>

user-provided text describing the attachment

=back

=cut

sub description {
154
  return $_[0]->{description};
155 156 157 158 159 160 161 162 163 164 165 166 167
}

=over

=item C<contenttype>

the attachment's MIME media type

=back

=cut

sub contenttype {
168
  return $_[0]->{mimetype};
169 170 171 172 173 174 175 176 177 178 179 180 181
}

=over

=item C<attacher>

the user who attached the attachment

=back

=cut

sub attacher {
182 183
  return $_[0]->{attacher}
    //= new Bugzilla::User({id => $_[0]->{submitter_id}, cache => 1});
184 185 186 187 188 189 190 191 192 193 194 195 196
}

=over

=item C<attached>

the date and time on which the attacher attached the attachment

=back

=cut

sub attached {
197
  return $_[0]->{creation_ts};
198 199 200 201
}

=over

202 203 204 205 206 207 208 209 210
=item C<modification_time>

the date and time on which the attachment was last modified.

=back

=cut

sub modification_time {
211
  return $_[0]->{modification_time};
212 213 214 215
}

=over

216 217 218 219 220 221 222 223 224
=item C<filename>

the name of the file the attacher attached

=back

=cut

sub filename {
225
  return $_[0]->{filename};
226 227 228 229 230 231 232 233 234 235 236 237 238
}

=over

=item C<ispatch>

whether or not the attachment is a patch

=back

=cut

sub ispatch {
239
  return $_[0]->{ispatch};
240 241 242 243 244 245 246 247 248 249 250 251 252
}

=over

=item C<isobsolete>

whether or not the attachment is obsolete

=back

=cut

sub isobsolete {
253
  return $_[0]->{isobsolete};
254 255 256 257 258 259 260 261 262 263 264 265 266
}

=over

=item C<isprivate>

whether or not the attachment is private

=back

=cut

sub isprivate {
267
  return $_[0]->{isprivate};
268 269 270 271
}

=over

272 273 274 275 276 277 278 279 280 281 282 283
=item C<is_viewable>

Returns 1 if the attachment has a content-type viewable in this browser.
Note that we don't use $cgi->Accept()'s ability to check if a content-type
matches, because this will return a value even if it's matched by the generic
*/* which most browsers add to the end of their Accept: headers.

=back

=cut

sub is_viewable {
284 285
  my $contenttype = $_[0]->contenttype;
  my $cgi         = Bugzilla->cgi;
286

287 288
  # We assume we can view all text and image types.
  return 1 if ($contenttype =~ /^(text|image)\//);
289

290 291 292 293 294
  # Mozilla can view XUL. Note the trailing slash on the Gecko detection to
  # avoid sending XUL to Safari.
  return 1
    if (($contenttype =~ /^application\/vnd\.mozilla\./)
    && ($cgi->user_agent() =~ /Gecko\//));
295

296 297 298 299
  # If it's not one of the above types, we check the Accept: header for any
  # types mentioned explicitly.
  my $accept = join(",", $cgi->Accept());
  return 1 if ($accept =~ /^(.*,)?\Q$contenttype\E(,.*)?$/);
300

301
  return 0;
302 303 304 305
}

=over

306 307
=item C<data>

308
the content of the attachment
309 310 311 312 313 314

=back

=cut

sub data {
315 316
  my $self = shift;
  return $self->{data} if exists $self->{data};
317

318 319 320
  # First try to get the attachment data from the database.
  ($self->{data}) = Bugzilla->dbh->selectrow_array(
    "SELECT thedata
321
                                                      FROM attach_data
322 323 324 325 326 327 328 329 330 331 332 333
                                                      WHERE id = ?", undef,
    $self->id
  );

  # If there's no attachment data in the database, the attachment is stored
  # in a local file, so retrieve it from there.
  if (length($self->{data}) == 0) {
    if (open(AH, '<', $self->_get_local_filename())) {
      local $/;
      binmode AH;
      $self->{data} = <AH>;
      close(AH);
334
    }
335
  }
336

337
  return $self->{data};
338 339 340 341 342 343
}

=over

=item C<datasize>

344
the length (in bytes) of the attachment content
345 346 347 348 349 350 351 352 353 354 355 356 357 358

=back

=cut

# datasize is a property of the data itself, and it's unclear whether we should
# expose it at all, since you can easily derive it from the data itself: in TT,
# attachment.data.size; in Perl, length($attachment->{data}).  But perhaps
# it makes sense for performance reasons, since accessing the data forces it
# to get retrieved from the database/filesystem and loaded into memory,
# while datasize avoids loading the attachment into memory, calling SQL's
# LENGTH() function or stat()ing the file instead.  I've left it in for now.

sub datasize {
359 360
  my $self = shift;
  return $self->{datasize} if defined $self->{datasize};
361

362 363
  # If we have already retrieved the data, return its size.
  return length($self->{data}) if exists $self->{data};
364

365 366
  $self->{datasize} = Bugzilla->dbh->selectrow_array(
    "SELECT LENGTH(thedata)
367
                                        FROM attach_data
368 369 370 371 372 373 374 375 376 377 378
                                        WHERE id = ?", undef, $self->id
  ) || 0;

  # If there's no attachment data in the database, either the attachment
  # is stored in a local file, and so retrieve its size from the file,
  # or the attachment has been deleted.
  unless ($self->{datasize}) {
    if (open(AH, '<', $self->_get_local_filename())) {
      binmode AH;
      $self->{datasize} = (stat(AH))[7];
      close(AH);
379
    }
380
  }
381

382
  return $self->{datasize};
383 384
}

385
sub _get_local_filename {
386 387 388 389
  my $self = shift;
  my $hash = ($self->id % 100) + 100;
  $hash =~ s/.*(\d\d)$/group.$1/;
  return bz_locations()->{'attachdir'} . "/$hash/attachment." . $self->id;
390 391
}

392 393 394 395 396 397 398 399 400 401 402
=over

=item C<flags>

flags that have been set on the attachment

=back

=cut

sub flags {
403 404 405

  # Don't cache it as it must be in sync with ->flag_types.
  return $_[0]->{flags} = [map { @{$_->{flags}} } @{$_[0]->flag_types}];
406 407
}

408 409 410 411 412 413 414 415 416 417 418 419
=over

=item C<flag_types>

Return all flag types available for this attachment as well as flags
already set, grouped by flag type.

=back

=cut

sub flag_types {
420 421
  my $self = shift;
  return $self->{flag_types} if exists $self->{flag_types};
422

423 424 425 426 427 428
  my $vars = {
    target_type  => 'attachment',
    product_id   => $self->bug->product_id,
    component_id => $self->bug->component_id,
    attach_id    => $self->id
  };
429

430
  return $self->{flag_types} = Bugzilla::Flag->_flag_types($vars);
431 432
}

433 434 435 436
###############################
####      Validators     ######
###############################

437
sub set_content_type { $_[0]->set('mimetype',    $_[1]); }
438
sub set_description  { $_[0]->set('description', $_[1]); }
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
sub set_filename     { $_[0]->set('filename',    $_[1]); }
sub set_is_patch     { $_[0]->set('ispatch',     $_[1]); }
sub set_is_private   { $_[0]->set('isprivate',   $_[1]); }

sub set_is_obsolete {
  my ($self, $obsolete) = @_;

  my $old = $self->isobsolete;
  $self->set('isobsolete', $obsolete);
  my $new = $self->isobsolete;

  # If the attachment is being marked as obsolete, cancel pending requests.
  if ($new && $old != $new) {
    my @requests = grep { $_->status eq '?' } @{$self->flags};
    return unless scalar @requests;

    my %flag_ids = map { $_->id => 1 } @requests;
    foreach my $flagtype (@{$self->flag_types}) {
      @{$flagtype->{flags}} = grep { !$flag_ids{$_->id} } @{$flagtype->{flags}};
458
    }
459
  }
460 461 462
}

sub set_flags {
463
  my ($self, $flags, $new_flags) = @_;
464

465
  Bugzilla::Flag->set_flag($self, $_) foreach (@$flags, @$new_flags);
466 467
}

468
sub _check_bug {
469 470
  my ($invocant, $bug) = @_;
  my $user = Bugzilla->user;
471

472
  $bug = ref $invocant ? $invocant->bug : $bug;
473

474 475 476
  $bug
    || ThrowCodeError('param_required',
    {function => "$invocant->create", param => 'bug'});
477

478 479
  ($user->can_see_bug($bug->id) && $user->can_edit_product($bug->product_id))
    || ThrowUserError("illegal_attachment_edit_bug", {bug_id => $bug->id});
480

481
  return $bug;
482 483
}

484
sub _check_content_type {
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
  my ($invocant, $content_type, undef, $params) = @_;

  my $is_patch = ref($invocant) ? $invocant->ispatch : $params->{ispatch};
  $content_type = 'text/plain' if $is_patch;
  $content_type = clean_text($content_type);

# The subsets below cover all existing MIME types and charsets registered by IANA.
# (MIME type: RFC 2045 section 5.1; charset: RFC 2278 section 3.3)
  my $legal_types = join('|', LEGAL_CONTENT_TYPES);
  if (!$content_type
    || $content_type
    !~ /^($legal_types)\/[a-z0-9_\-\+\.]+(;\s*charset=[a-z0-9_\-\+]+)?$/i)
  {
    ThrowUserError("invalid_content_type", {contenttype => $content_type});
  }
  trick_taint($content_type);

  # $ENV{HOME} must be defined when using File::MimeInfo::Magic,
  # see https://rt.cpan.org/Public/Bug/Display.html?id=41744.
  local $ENV{HOME} = $ENV{HOME} || File::Spec->rootdir();

  # If we have autodetected application/octet-stream from the Content-Type
  # header, let's have a better go using a sniffer if available.
  if ( defined Bugzilla->input_params->{contenttypemethod}
    && Bugzilla->input_params->{contenttypemethod} eq 'autodetect'
    && $content_type eq 'application/octet-stream'
    && Bugzilla->feature('typesniffer'))
  {
    import File::MimeInfo::Magic qw(mimetype);
    require IO::Scalar;

    # data is either a filehandle, or the data itself.
    my $fh = $params->{data};
    if (!ref($fh)) {
      $fh = new IO::Scalar \$fh;
520
    }
521 522 523 524 525 526 527 528 529 530 531 532 533
    elsif (!$fh->isa('IO::Handle')) {

      # CGI.pm sends us an Fh that isn't actually an IO::Handle, but
      # has a method for getting an actual handle out of it.
      $fh = $fh->handle;

      # ->handle returns an literal IO::Handle, even though the
      # underlying object is a file. So we rebless it to be a proper
      # IO::File object so that we can call ->seek on it and so on.
      # Just in case CGI.pm fixes this some day, we check ->isa first.
      if (!$fh->isa('IO::File')) {
        bless $fh, 'IO::File';
      }
534 535
    }

536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
    my $mimetype = mimetype($fh);
    $fh->seek(0, 0);
    $content_type = $mimetype if $mimetype;
  }

  # Make sure patches are viewable in the browser
  if (!ref($invocant)
    && defined Bugzilla->input_params->{contenttypemethod}
    && Bugzilla->input_params->{contenttypemethod} eq 'autodetect'
    && $content_type =~ m{text/x-(?:diff|patch)})
  {
    $params->{ispatch} = 1;
    $content_type = 'text/plain';
  }

  return $content_type;
552 553 554
}

sub _check_data {
555
  my ($invocant, $params) = @_;
556

557 558
  my $data = $params->{data};
  $params->{filesize} = ref $data ? -s $data : length($data);
559

560 561
  Bugzilla::Hook::process('attachment_process_data',
    {data => \$data, attributes => $params});
562

563
  $params->{filesize} || ThrowUserError('zero_length_file');
564

565 566 567 568 569 570 571 572 573 574 575
  # Make sure the attachment does not exceed the maximum permitted size.
  my $max_size = max(
    Bugzilla->params->{'maxlocalattachment'} * 1048576,
    Bugzilla->params->{'maxattachmentsize'} * 1024
  );

  if ($params->{filesize} > $max_size) {
    my $vars = {filesize => sprintf("%.0f", $params->{filesize} / 1024)};
    ThrowUserError('file_too_large', $vars);
  }
  return $data;
576 577 578
}

sub _check_description {
579
  my ($invocant, $description) = @_;
580

581 582 583
  $description = trim($description);
  $description || ThrowUserError('missing_attachment_description');
  return $description;
584 585 586
}

sub _check_filename {
587
  my ($invocant, $filename) = @_;
588

589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
  $filename = clean_text($filename);
  if (!$filename) {
    if (ref $invocant) {
      ThrowUserError('filename_not_specified');
    }
    else {
      ThrowUserError('file_not_specified');
    }
  }

  # Remove path info (if any) from the file name.  The browser should do this
  # for us, but some are buggy.  This may not work on Mac file names and could
  # mess up file names with slashes in them, but them's the breaks.  We only
  # use this as a hint to users downloading attachments anyway, so it's not
  # a big deal if it munges incorrectly occasionally.
  $filename =~ s/^.*[\/\\]//;

  # Truncate the filename to MAX_ATTACH_FILENAME_LENGTH characters, counting
  # from the end of the string to make sure we keep the filename extension.
  $filename
    = substr($filename, -&MAX_ATTACH_FILENAME_LENGTH, MAX_ATTACH_FILENAME_LENGTH);
  trick_taint($filename);

  return $filename;
613 614
}

615
sub _check_is_private {
616 617 618 619 620 621
  my ($invocant, $is_private) = @_;

  $is_private = $is_private ? 1 : 0;
  if (
    (
         (!ref $invocant && $is_private)
622
      || (ref $invocant  && $invocant->isprivate != $is_private)
623 624 625 626 627 628 629
    )
    && !Bugzilla->user->is_insider
    )
  {
    ThrowUserError('user_not_insider');
  }
  return $is_private;
630
}
631

632 633 634 635 636 637
=pod

=head2 Class Methods

=over

638
=item C<get_attachments_by_bug($bug)>
639

640 641
Description: retrieves and returns the attachments the currently logged in
             user can view for the given bug.
642

643
Params:     C<$bug> - Bugzilla::Bug object - the bug for which
644 645 646 647 648
            to retrieve and return attachments.

Returns:    a reference to an array of attachment objects.

=cut
649

650
sub get_attachments_by_bug {
651 652 653 654 655 656 657 658 659 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 686 687 688 689 690 691 692 693 694 695 696
  my ($class, $bug, $vars) = @_;
  my $user = Bugzilla->user;
  my $dbh  = Bugzilla->dbh;

  # By default, private attachments are not accessible, unless the user
  # is in the insider group or submitted the attachment.
  my $and_restriction = '';
  my @values          = ($bug->id);

  unless ($user->is_insider) {
    $and_restriction = 'AND (isprivate = 0 OR submitter_id = ?)';
    push(@values, $user->id);
  }

  my $attach_ids = $dbh->selectcol_arrayref(
    "SELECT attach_id FROM attachments
                                               WHERE bug_id = ? $and_restriction",
    undef, @values
  );

  my $attachments = Bugzilla::Attachment->new_from_list($attach_ids);
  $_->{bug} = $bug foreach @$attachments;

 # To avoid $attachment->flags and $attachment->flag_types running SQL queries
 # themselves for each attachment listed here, we collect all the data at once and
 # populate $attachment->{flag_types} ourselves. We also load all attachers and
 # datasizes at once for the same reason.
  if ($vars->{preload}) {

    # Preload flag types and flags
    my $vars = {
      target_type  => 'attachment',
      product_id   => $bug->product_id,
      component_id => $bug->component_id,
      attach_id    => $attach_ids
    };
    my $flag_types = Bugzilla::Flag->_flag_types($vars);

    foreach my $attachment (@$attachments) {
      $attachment->{flag_types} = [];
      my $new_types = dclone($flag_types);
      foreach my $new_type (@$new_types) {
        $new_type->{flags}
          = [grep($_->attach_id == $attachment->id, @{$new_type->{flags}})];
        push(@{$attachment->{flag_types}}, $new_type);
      }
697 698
    }

699 700 701 702 703 704 705 706 707 708 709
    # Preload attachers.
    my %user_ids = map { $_->{submitter_id} => 1 } @$attachments;
    my $users    = Bugzilla::User->new_from_list([keys %user_ids]);
    my %user_map = map { $_->id => $_ } @$users;
    foreach my $attachment (@$attachments) {
      $attachment->{attacher} = $user_map{$attachment->{submitter_id}};
    }

    # Preload datasizes.
    my $sizes = $dbh->selectall_hashref(
      'SELECT attach_id, LENGTH(thedata) AS datasize
710
                                   FROM attachments LEFT JOIN attach_data ON attach_id = id
711 712
                                   WHERE bug_id = ?', 'attach_id', undef, $bug->id
    );
713

714 715 716
    # Force the size of attachments not in the DB to be recalculated.
    $_->{datasize} = $sizes->{$_->id}->{datasize} || undef foreach @$attachments;
  }
717

718
  return $attachments;
719
}
720

721 722
=pod

723
=item C<validate_can_edit>
724

725
Description: validates if the user is allowed to view and edit the attachment.
726
             Only the submitter or someone with editbugs privs can edit it.
727 728
             Only the submitter and users in the insider group can view
             private attachments.
729

730
Params:      none
731

732
Returns:     1 on success, 0 otherwise.
733 734 735 736

=cut

sub validate_can_edit {
737 738 739 740 741 742 743 744 745
  my $attachment = shift;
  my $user       = Bugzilla->user;

  # The submitter can edit their attachments.
  return (
    $attachment->attacher->id == $user->id
      || ((!$attachment->isprivate || $user->is_insider)
      && $user->in_group('editbugs', $attachment->bug->product_id))
  ) ? 1 : 0;
746 747
}

748
=item C<validate_obsolete($bug, $attach_ids)>
749 750 751

Description: validates if attachments the user wants to mark as obsolete
             really belong to the given bug and are not already obsolete.
752
             Moreover, a user cannot mark an attachment as obsolete if
753
             they cannot view it (due to restrictions on it).
754

755
Params:      $bug - The bug object obsolete attachments should belong to.
756
             $attach_ids - The list of attachments to mark as obsolete.
757

758 759
Returns:     The list of attachment objects to mark as obsolete.
             Else an error is thrown.
760 761 762 763

=cut

sub validate_obsolete {
764
  my ($class, $bug, $list) = @_;
765

766 767 768 769 770 771 772
  # Make sure the attachment id is valid and the user has permissions to view
  # the bug to which it is attached. Make sure also that the user can view
  # the attachment itself.
  my @obsolete_attachments;
  foreach my $attachid (@$list) {
    my $vars = {};
    $vars->{'attach_id'} = $attachid;
773

774
    detaint_natural($attachid) || ThrowUserError('invalid_attach_id', $vars);
775

776 777 778
    # Make sure the attachment exists in the database.
    my $attachment = new Bugzilla::Attachment($attachid)
      || ThrowUserError('invalid_attach_id', $vars);
779

780 781 782
    # Check that the user can view and edit this attachment.
    $attachment->validate_can_edit
      || ThrowUserError('illegal_attachment_edit', {attach_id => $attachment->id});
783

784 785 786 787
    if ($attachment->bug_id != $bug->bug_id) {
      $vars->{'my_bug_id'} = $bug->bug_id;
      ThrowUserError('mismatched_bug_ids_on_obsolete', $vars);
    }
788

789
    next if $attachment->isobsolete;
790

791 792 793
    push(@obsolete_attachments, $attachment);
  }
  return @obsolete_attachments;
794 795
}

796 797 798
###############################
####     Constructors     #####
###############################
799 800 801

=pod

802
=item C<create>
803

804
Description: inserts an attachment into the given bug.
805

806 807
Params:     takes a hashref with the following keys:
            C<bug> - Bugzilla::Bug object - the bug for which to insert
808
            the attachment.
809 810 811 812 813 814 815 816
            C<data> - Either a filehandle pointing to the content of the
            attachment, or the content of the attachment itself.
            C<description> - string - describe what the attachment is about.
            C<filename> - string - the name of the attachment (used by the
            browser when downloading it). If the attachment is a URL, this
            parameter has no effect.
            C<mimetype> - string - a valid MIME type.
            C<creation_ts> - string (optional) - timestamp of the insert
817
            as returned by SELECT LOCALTIMESTAMP(0).
818 819 820 821 822 823
            C<ispatch> - boolean (optional, default false) - true if the
            attachment is a patch.
            C<isprivate> - boolean (optional, default false) - true if
            the attachment is private.

Returns:    The new attachment object.
824 825 826

=cut

827
sub create {
828 829
  my $class = shift;
  my $dbh   = Bugzilla->dbh;
830

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

834 835 836 837 838
  # Extract everything which is not a valid column name.
  my $bug = delete $params->{bug};
  $params->{bug_id} = $bug->id;
  my $data = delete $params->{data};
  my $size = delete $params->{filesize};
839

840 841
  my $attachment = $class->insert_create_data($params);
  my $attachid   = $attachment->id;
842

843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
  # The file is too large to be stored in the DB, so we store it locally.
  if ($size > Bugzilla->params->{'maxattachmentsize'} * 1024) {
    my $attachdir = bz_locations()->{'attachdir'};
    my $hash      = ($attachid % 100) + 100;
    $hash =~ s/.*(\d\d)$/group.$1/;
    mkdir "$attachdir/$hash", 0770;
    chmod 0770, "$attachdir/$hash";
    if (ref $data) {
      copy($data, "$attachdir/$hash/attachment.$attachid");
      close $data;
    }
    else {
      open(AH, '>', "$attachdir/$hash/attachment.$attachid");
      binmode AH;
      print AH $data;
      close AH;
    }
    $data = '';    # Will be stored in the DB.
  }
862

863 864 865 866 867 868 869 870 871
  # If we have a filehandle, we need its content to store it in the DB.
  elsif (ref $data) {
    local $/;

    # Store the content in a temp variable while we close the FH.
    my $tmp = <$data>;
    close $data;
    $data = $tmp;
  }
872

873 874 875 876
  my $sth = $dbh->prepare(
    "INSERT INTO attach_data
                             (id, thedata) VALUES ($attachid, ?)"
  );
877

878 879 880
  trick_taint($data);
  $sth->bind_param(1, $data, $dbh->BLOB_TYPE);
  $sth->execute();
881

882
  $attachment->{bug} = $bug;
883

884 885
  # Return the new attachment object.
  return $attachment;
886 887
}

888 889
sub run_create_validators {
  my ($class, $params) = @_;
890

891
  $params->{submitter_id} = Bugzilla->user->id || ThrowUserError('invalid_user');
892

893 894 895 896
  # Let's validate the attachment content first as it may
  # alter some other attachment attributes.
  $params->{data} = $class->_check_data($params);
  $params = $class->SUPER::run_create_validators($params);
897

898 899 900
  $params->{creation_ts}
    ||= Bugzilla->dbh->selectrow_array('SELECT LOCALTIMESTAMP(0)');
  $params->{modification_time} = $params->{creation_ts};
901

902 903
  return $params;
}
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 930 931 932 933 934 935 936 937 938 939 940
sub update {
  my $self      = shift;
  my $dbh       = Bugzilla->dbh;
  my $user      = Bugzilla->user;
  my $timestamp = shift || $dbh->selectrow_array('SELECT LOCALTIMESTAMP(0)');

  my ($changes, $old_self) = $self->SUPER::update(@_);

  my ($removed, $added)
    = Bugzilla::Flag->update_flags($self, $old_self, $timestamp);
  if ($removed || $added) {
    $changes->{'flagtypes.name'} = [$removed, $added];
  }

  # Record changes in the activity table.
  require Bugzilla::Bug;
  foreach my $field (keys %$changes) {
    my $change = $changes->{$field};
    $field = "attachments.$field" unless $field eq "flagtypes.name";
    Bugzilla::Bug::LogActivityEntry($self->bug_id, $field, $change->[0],
      $change->[1], $user->id, $timestamp, undef, $self->id);
  }

  if (scalar(keys %$changes)) {
    $dbh->do('UPDATE attachments SET modification_time = ? WHERE attach_id = ?',
      undef, ($timestamp, $self->id));
    $dbh->do('UPDATE bugs SET delta_ts = ? WHERE bug_id = ?',
      undef, ($timestamp, $self->bug_id));
    $self->{modification_time} = $timestamp;

    # because we updated the attachments table after SUPER::update(), we
    # need to ensure the cache is flushed.
    Bugzilla->memcached->clear({table => 'attachments', id => $self->id});
  }

  return $changes;
941 942
}

943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
=pod

=item C<remove_from_db()>

Description: removes an attachment from the DB.

Params:     none

Returns:    nothing

=back

=cut

sub remove_from_db {
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
  my $self = shift;
  my $dbh  = Bugzilla->dbh;

  $dbh->bz_start_transaction();
  my $flag_ids
    = $dbh->selectcol_arrayref('SELECT id FROM flags WHERE attach_id = ?',
    undef, $self->id);
  $dbh->do('DELETE FROM flags WHERE ' . $dbh->sql_in('id', $flag_ids))
    if @$flag_ids;
  $dbh->do('DELETE FROM attach_data WHERE id = ?', undef, $self->id);
  $dbh->do(
    'UPDATE attachments SET mimetype = ?, ispatch = ?, isobsolete = ?
              WHERE attach_id = ?', undef, ('text/plain', 0, 1, $self->id)
  );
  $dbh->bz_commit_transaction();

  my $filename = $self->_get_local_filename;
  if (-e $filename) {
    unlink $filename or warn "Couldn't unlink $filename: $!";
  }

  # As we don't call SUPER->remove_from_db we need to manually clear
  # memcached here.
  Bugzilla->memcached->clear({table => 'attachments', id => $self->id});
  foreach my $flag_id (@$flag_ids) {
    Bugzilla->memcached->clear({table => 'flags', id => $flag_id});
  }
985 986
}

987 988 989 990 991 992
###############################
####       Helpers        #####
###############################

# Extract the content type from the attachment form.
sub get_content_type {
993
  my $cgi = Bugzilla->cgi;
994

995
  return 'text/plain' if ($cgi->param('ispatch') || $cgi->param('attach_text'));
996

997 998
  my $content_type;
  my $method = $cgi->param('contenttypemethod') || '';
999

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
  if ($method eq 'list') {

    # The user selected a content type from the list, so use their
    # selection.
    $content_type = $cgi->param('contenttypeselection');
  }
  elsif ($method eq 'manual') {

    # The user entered a content type manually, so use their entry.
    $content_type = $cgi->param('contenttypeentry');
  }
  else {
    defined $cgi->upload('data') || ThrowUserError('file_not_specified');

    # The user asked us to auto-detect the content type, so use the type
    # specified in the HTTP request headers.
    $content_type = $cgi->uploadInfo($cgi->param('data'))->{'Content-Type'};
    $content_type || ThrowUserError("missing_content_type");

    # Internet Explorer sends image/x-png for PNG images,
    # so convert that to image/png to match other browsers.
    if ($content_type eq 'image/x-png') {
      $content_type = 'image/png';
1023
    }
1024 1025
  }
  return $content_type;
1026 1027 1028
}


1029
1;
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

=head1 B<Methods in need of POD>

=over

=item set_filename

=item set_is_obsolete

=item DB_COLUMNS

=item set_is_private

=item set_content_type

=item set_description

=item get_content_type

=item set_flags

=item set_is_patch

=item update

=back