Attachment.pm 25.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Terry Weissman <terry@mozilla.org>
#                 Myk Melez <myk@mozilla.org>
22
#                 Marc Schumann <wurblzap@gmail.com>
23
#                 Frédéric Buclin <LpSolit@gmail.com>
24 25 26

use strict;

27
package Bugzilla::Attachment;
28

29 30
=head1 NAME

31
Bugzilla::Attachment - Bugzilla attachment class.
32 33 34 35 36 37

=head1 SYNOPSIS

  use Bugzilla::Attachment;

  # Get the attachment with the given ID.
38
  my $attachment = new Bugzilla::Attachment($attach_id);
39 40

  # Get the attachments with the given IDs.
41
  my $attachments = Bugzilla::Attachment->new_from_list($attach_ids);
42 43 44

=head1 DESCRIPTION

45 46 47 48 49 50
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.
51 52 53

=cut

54
use Bugzilla::Constants;
55
use Bugzilla::Error;
56
use Bugzilla::Flag;
57
use Bugzilla::User;
58 59
use Bugzilla::Util;
use Bugzilla::Field;
60
use Bugzilla::Hook;
61

62 63 64
use File::Copy;
use List::Util qw(max);

65
use base qw(Bugzilla::Object);
66

67 68 69
###############################
####    Initialization     ####
###############################
70

71 72 73
use constant DB_TABLE   => 'attachments';
use constant ID_FIELD   => 'attach_id';
use constant LIST_ORDER => ID_FIELD;
74

75 76
sub DB_COLUMNS {
    my $dbh = Bugzilla->dbh;
77

78 79 80 81 82 83 84 85 86 87 88 89
    return qw(
        attach_id
        bug_id
        description
        filename
        isobsolete
        ispatch
        isprivate
        mimetype
        modification_time
        submitter_id),
        $dbh->sql_date_format('attachments.creation_ts', '%Y.%m.%d %H:%i') . ' AS creation_ts';
90 91
}

92 93 94
use constant REQUIRED_FIELD_MAP => {
    bug_id => 'bug',
};
95
use constant EXTRA_REQUIRED_FIELDS => qw(data);
96 97 98 99 100 101 102 103 104 105 106 107 108

use constant UPDATE_COLUMNS => qw(
    description
    filename
    isobsolete
    ispatch
    isprivate
    mimetype
);

use constant VALIDATORS => {
    bug           => \&_check_bug,
    description   => \&_check_description,
109
    filename      => \&_check_filename,
110
    ispatch       => \&Bugzilla::Object::check_boolean,
111
    isprivate     => \&_check_is_private,
112
    mimetype      => \&_check_content_type,
113 114
};

115 116 117 118
use constant VALIDATOR_DEPENDENCIES => {
    mimetype => ['ispatch'],
};

119 120 121 122
use constant UPDATE_VALIDATORS => {
    isobsolete => \&Bugzilla::Object::check_boolean,
};

123 124 125
###############################
####      Accessors      ######
###############################
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

=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 {
    my $self = shift;
    return $self->{bug_id};
}

=over

148 149 150 151 152 153 154 155 156 157 158 159
=item C<bug>

the bug object to which the attachment is attached

=back

=cut

sub bug {
    my $self = shift;

    require Bugzilla::Bug;
160
    $self->{bug} ||= Bugzilla::Bug->new($self->bug_id);
161 162 163 164 165
    return $self->{bug};
}

=over

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
=item C<description>

user-provided text describing the attachment

=back

=cut

sub description {
    my $self = shift;
    return $self->{description};
}

=over

=item C<contenttype>

the attachment's MIME media type

=back

=cut

sub contenttype {
    my $self = shift;
191
    return $self->{mimetype};
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
}

=over

=item C<attacher>

the user who attached the attachment

=back

=cut

sub attacher {
    my $self = shift;
    return $self->{attacher} if exists $self->{attacher};
207
    $self->{attacher} = new Bugzilla::User($self->{submitter_id});
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    return $self->{attacher};
}

=over

=item C<attached>

the date and time on which the attacher attached the attachment

=back

=cut

sub attached {
    my $self = shift;
223
    return $self->{creation_ts};
224 225 226 227
}

=over

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
=item C<modification_time>

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

=back

=cut

sub modification_time {
    my $self = shift;
    return $self->{modification_time};
}

=over

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 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 299 300 301 302
=item C<filename>

the name of the file the attacher attached

=back

=cut

sub filename {
    my $self = shift;
    return $self->{filename};
}

=over

=item C<ispatch>

whether or not the attachment is a patch

=back

=cut

sub ispatch {
    my $self = shift;
    return $self->{ispatch};
}

=over

=item C<isobsolete>

whether or not the attachment is obsolete

=back

=cut

sub isobsolete {
    my $self = shift;
    return $self->{isobsolete};
}

=over

=item C<isprivate>

whether or not the attachment is private

=back

=cut

sub isprivate {
    my $self = shift;
    return $self->{isprivate};
}

=over

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
=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 {
    my $self = shift;
    my $contenttype = $self->contenttype;
    my $cgi = Bugzilla->cgi;

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

    # 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\//));

    # 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(,.*)?$/);

    return 0;
}

=over

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
=item C<data>

the content of the attachment

=back

=cut

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

    # First try to get the attachment data from the database.
    ($self->{data}) = Bugzilla->dbh->selectrow_array("SELECT thedata
                                                      FROM attach_data
                                                      WHERE id = ?",
                                                     undef,
354
                                                     $self->id);
355 356 357 358 359

    # 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())) {
360
            local $/;
361 362
            binmode AH;
            $self->{data} = <AH>;
363 364 365
            close(AH);
        }
    }
366

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
    return $self->{data};
}

=over

=item C<datasize>

the length (in characters) of the attachment content

=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 {
    my $self = shift;
    return $self->{datasize} if exists $self->{datasize};

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

395
    $self->{datasize} =
396 397 398
        Bugzilla->dbh->selectrow_array("SELECT LENGTH(thedata)
                                        FROM attach_data
                                        WHERE id = ?",
399
                                       undef, $self->id) || 0;
400

401 402 403 404
    # 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}) {
405 406 407 408 409 410 411 412 413 414
        if (open(AH, $self->_get_local_filename())) {
            binmode AH;
            $self->{datasize} = (stat(AH))[7];
            close(AH);
        }
    }

    return $self->{datasize};
}

415 416 417 418 419 420 421
sub _get_local_filename {
    my $self = shift;
    my $hash = ($self->id % 100) + 100;
    $hash =~ s/.*(\d\d)$/group.$1/;
    return bz_locations()->{'attachdir'} . "/$hash/attachment." . $self->id;
}

422 423 424 425 426 427 428 429 430 431 432 433 434
=over

=item C<flags>

flags that have been set on the attachment

=back

=cut

sub flags {
    my $self = shift;

435 436
    # Don't cache it as it must be in sync with ->flag_types.
    $self->{flags} = [map { @{$_->{flags}} } @{$self->flag_types}];
437 438 439
    return $self->{flags};
}

440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
=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 {
    my $self = shift;
    return $self->{flag_types} if exists $self->{flag_types};

    my $vars = { target_type  => 'attachment',
                 product_id   => $self->bug->product_id,
                 component_id => $self->bug->component_id,
                 attach_id    => $self->id };

460
    $self->{flag_types} = Bugzilla::Flag->_flag_types($vars);
461 462 463
    return $self->{flag_types};
}

464 465 466 467
###############################
####      Validators     ######
###############################

468 469 470 471 472
sub set_content_type { $_[0]->set('mimetype', $_[1]); }
sub set_description  { $_[0]->set('description', $_[1]); }
sub set_filename     { $_[0]->set('filename', $_[1]); }
sub set_is_patch     { $_[0]->set('ispatch', $_[1]); }
sub set_is_private   { $_[0]->set('isprivate', $_[1]); }
473

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
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}};
        }
    }
}

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

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

499 500 501 502 503
sub _check_bug {
    my ($invocant, $bug) = @_;
    my $user = Bugzilla->user;

    $bug = ref $invocant ? $invocant->bug : $bug;
504 505 506 507

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

508 509 510 511
    ($user->can_see_bug($bug->id) && $user->can_edit_product($bug->product_id))
      || ThrowUserError("illegal_attachment_edit_bug", { bug_id => $bug->id });

    return $bug;
512 513
}

514
sub _check_content_type {
515 516 517 518
    my ($invocant, $content_type, undef, $params) = @_;
 
    my $is_patch = ref($invocant) ? $invocant->ispatch : $params->{ispatch};
    $content_type = 'text/plain' if $is_patch;
519
    $content_type = trim($content_type);
520
    my $legal_types = join('|', LEGAL_CONTENT_TYPES);
521
    if (!$content_type or $content_type !~ /^($legal_types)\/.+$/) {
522 523 524 525 526 527 528 529 530 531
        ThrowUserError("invalid_content_type", { contenttype => $content_type });
    }
    trick_taint($content_type);

    return $content_type;
}

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

532
    my $data = $params->{data};
533
    $params->{filesize} = ref $data ? -s $data : length($data);
534

535
    Bugzilla::Hook::process('attachment_process_data', { data       => \$data,
536 537
                                                         attributes => $params });

538
    $params->{filesize} || ThrowUserError('zero_length_file');
539
    # Make sure the attachment does not exceed the maximum permitted size.
540 541 542 543 544 545
    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);
546 547 548 549 550 551 552 553 554 555 556 557 558
    }
    return $data;
}

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

    $description = trim($description);
    $description || ThrowUserError('missing_attachment_description');
    return $description;
}

sub _check_filename {
559
    my ($invocant, $filename) = @_;
560

561 562
    $filename = trim($filename);
    $filename || ThrowUserError('file_not_specified');
563 564 565 566 567 568 569 570 571 572 573

    # 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 100 characters, counting from the end of the
    # string to make sure we keep the filename extension.
    $filename = substr($filename, -100, 100);
574
    trick_taint($filename);
575 576 577 578

    return $filename;
}

579 580
sub _check_is_private {
    my ($invocant, $is_private) = @_;
581

582
    $is_private = $is_private ? 1 : 0;
583 584 585 586
    if (((!ref $invocant && $is_private)
         || (ref $invocant && $invocant->isprivate != $is_private))
        && !Bugzilla->user->is_insider) {
        ThrowUserError('user_not_insider');
587
    }
588
    return $is_private;
589
}
590

591 592 593 594 595 596 597 598
=pod

=head2 Class Methods

=over

=item C<get_attachments_by_bug($bug_id)>

599 600
Description: retrieves and returns the attachments the currently logged in
             user can view for the given bug.
601 602 603 604 605 606 607

Params:     C<$bug_id> - integer - the ID of the bug for which
            to retrieve and return attachments.

Returns:    a reference to an array of attachment objects.

=cut
608

609
sub get_attachments_by_bug {
610
    my ($class, $bug_id, $vars) = @_;
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
    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);
627 628

    my $attachments = Bugzilla::Attachment->new_from_list($attach_ids);
629 630 631 632 633 634 635 636 637 638 639

    # To avoid $attachment->flags to run SQL queries itself for each
    # attachment listed here, we collect all the data at once and
    # populate $attachment->{flags} ourselves.
    if ($vars->{preload}) {
        $_->{flags} = [] foreach @$attachments;
        my %att = map { $_->id => $_ } @$attachments;

        my $flags = Bugzilla::Flag->match({ bug_id      => $bug_id,
                                            target_type => 'attachment' });

640 641 642
        # Exclude flags for private attachments you cannot see.
        @$flags = grep {exists $att{$_->attach_id}} @$flags;

643 644 645
        push(@{$att{$_->attach_id}->{flags}}, $_) foreach @$flags;
        $attachments = [sort {$a->id <=> $b->id} values %att];
    }
646
    return $attachments;
647
}
648

649 650
=pod

651
=item C<validate_can_edit($attachment, $product_id)>
652

653
Description: validates if the user is allowed to view and edit the attachment.
654
             Only the submitter or someone with editbugs privs can edit it.
655 656
             Only the submitter and users in the insider group can view
             private attachments.
657

658 659 660
Params:      $attachment - the attachment object being edited.
             $product_id - the product ID the attachment belongs to.

661
Returns:     1 on success, 0 otherwise.
662 663 664 665

=cut

sub validate_can_edit {
666
    my ($attachment, $product_id) = @_;
667 668
    my $user = Bugzilla->user;

669
    # The submitter can edit their attachments.
670 671 672
    return ($attachment->attacher->id == $user->id
            || ((!$attachment->isprivate || $user->is_insider)
                 && $user->in_group('editbugs', $product_id))) ? 1 : 0;
673 674
}

675
=item C<validate_obsolete($bug, $attach_ids)>
676 677 678

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

682
Params:      $bug - The bug object obsolete attachments should belong to.
683
             $attach_ids - The list of attachments to mark as obsolete.
684

685 686
Returns:     The list of attachment objects to mark as obsolete.
             Else an error is thrown.
687 688 689 690

=cut

sub validate_obsolete {
691
    my ($class, $bug, $list) = @_;
692 693

    # Make sure the attachment id is valid and the user has permissions to view
694 695
    # the bug to which it is attached. Make sure also that the user can view
    # the attachment itself.
696
    my @obsolete_attachments;
697
    foreach my $attachid (@$list) {
698 699 700 701 702 703 704
        my $vars = {};
        $vars->{'attach_id'} = $attachid;

        detaint_natural($attachid)
          || ThrowCodeError('invalid_attach_id_to_obsolete', $vars);

        # Make sure the attachment exists in the database.
705 706
        my $attachment = new Bugzilla::Attachment($attachid)
          || ThrowUserError('invalid_attach_id', $vars);
707

708
        # Check that the user can view and edit this attachment.
709 710
        $attachment->validate_can_edit($bug->product_id)
          || ThrowUserError('illegal_attachment_edit', { attach_id => $attachment->id });
711

712 713
        $vars->{'description'} = $attachment->description;

714 715
        if ($attachment->bug_id != $bug->bug_id) {
            $vars->{'my_bug_id'} = $bug->bug_id;
716 717 718 719
            $vars->{'attach_bug_id'} = $attachment->bug_id;
            ThrowCodeError('mismatched_bug_ids_on_obsolete', $vars);
        }

720
        next if $attachment->isobsolete;
721 722 723 724 725 726

        push(@obsolete_attachments, $attachment);
    }
    return @obsolete_attachments;
}

727 728 729
###############################
####     Constructors     #####
###############################
730 731 732

=pod

733
=item C<create>
734

735
Description: inserts an attachment into the given bug.
736

737 738
Params:     takes a hashref with the following keys:
            C<bug> - Bugzilla::Bug object - the bug for which to insert
739
            the attachment.
740 741 742 743 744 745 746 747
            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
748
            as returned by SELECT LOCALTIMESTAMP(0).
749 750 751 752 753 754
            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.
755 756 757

=cut

758
sub create {
759
    my $class = shift;
760
    my $dbh = Bugzilla->dbh;
761

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

765 766 767
    # Extract everything which is not a valid column name.
    my $bug = delete $params->{bug};
    $params->{bug_id} = $bug->id;
768 769
    my $data = delete $params->{data};
    my $size = delete $params->{filesize};
770

771 772
    my $attachment = $class->insert_create_data($params);
    my $attachid = $attachment->id;
773

774 775
    # The file is too large to be stored in the DB, so we store it locally.
    if ($size > Bugzilla->params->{'maxattachmentsize'} * 1024) {
776
        my $attachdir = bz_locations()->{'attachdir'};
777 778 779 780
        my $hash = ($attachid % 100) + 100;
        $hash =~ s/.*(\d\d)$/group.$1/;
        mkdir "$attachdir/$hash", 0770;
        chmod 0770, "$attachdir/$hash";
781 782 783
        if (ref $data) {
            copy($data, "$attachdir/$hash/attachment.$attachid");
            close $data;
784 785
        }
        else {
786 787 788 789
            open(AH, '>', "$attachdir/$hash/attachment.$attachid");
            binmode AH;
            print AH $data;
            close AH;
790
        }
791 792 793 794 795 796
        $data = ''; # Will be stored in the DB.
    }
    # If we have a filehandle, we need its content to store it in the DB.
    elsif (ref $data) {
        local $/;
        $data = <$data>;
797
    }
798

799 800 801 802 803 804 805
    my $sth = $dbh->prepare("INSERT INTO attach_data
                             (id, thedata) VALUES ($attachid, ?)");

    trick_taint($data);
    $sth->bind_param(1, $data, $dbh->BLOB_TYPE);
    $sth->execute();

806 807
    $attachment->{bug} = $bug;

808 809 810 811 812
    # Return the new attachment object.
    return $attachment;
}

sub run_create_validators {
813
    my ($class, $params) = @_;
814

815 816
    # Let's validate the attachment content first as it may
    # alter some other attachment attributes.
817
    $params->{data} = $class->_check_data($params);
818 819
    $params = $class->SUPER::run_create_validators($params);

820
    $params->{creation_ts} ||= Bugzilla->dbh->selectrow_array('SELECT LOCALTIMESTAMP(0)');
821 822
    $params->{modification_time} = $params->{creation_ts};
    $params->{submitter_id} = Bugzilla->user->id || ThrowCodeError('invalid_user');
823

824 825 826 827 828 829 830
    return $params;
}

sub update {
    my $self = shift;
    my $dbh = Bugzilla->dbh;
    my $user = Bugzilla->user;
831
    my $timestamp = shift || $dbh->selectrow_array('SELECT LOCALTIMESTAMP(0)');
832

833
    my ($changes, $old_self) = $self->SUPER::update(@_);
834 835 836 837 838

    my ($removed, $added) = Bugzilla::Flag->update_flags($self, $old_self, $timestamp);
    if ($removed || $added) {
        $changes->{'flagtypes.name'} = [$removed, $added];
    }
839 840 841 842 843 844 845 846

    # Record changes in the activity table.
    my $sth = $dbh->prepare('INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when,
                                                        fieldid, removed, added)
                             VALUES (?, ?, ?, ?, ?, ?, ?)');

    foreach my $field (keys %$changes) {
        my $change = $changes->{$field};
847 848 849
        $field = "attachments.$field" unless $field eq "flagtypes.name";
        my $fieldid = get_field_id($field);
        $sth->execute($self->bug_id, $self->id, $user->id, $timestamp,
850
                      $fieldid, $change->[0], $change->[1]);
851 852
    }

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

860
    return $changes;
861 862
}

863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
=pod

=item C<remove_from_db()>

Description: removes an attachment from the DB.

Params:     none

Returns:    nothing

=back

=cut

sub remove_from_db {
    my $self = shift;
    my $dbh = Bugzilla->dbh;

    $dbh->bz_start_transaction();
    $dbh->do('DELETE FROM flags WHERE attach_id = ?', undef, $self->id);
    $dbh->do('DELETE FROM attach_data WHERE id = ?', undef, $self->id);
884 885
    $dbh->do('UPDATE attachments SET mimetype = ?, ispatch = ?, isobsolete = ?
              WHERE attach_id = ?', undef, ('text/plain', 0, 1, $self->id));
886 887 888
    $dbh->bz_commit_transaction();
}

889 890 891 892 893 894 895 896
###############################
####       Helpers        #####
###############################

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

897
    return 'text/plain' if ($cgi->param('ispatch') || $cgi->param('attach_text'));
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916

    my $content_type;
    if (!defined $cgi->param('contenttypemethod')) {
        ThrowUserError("missing_content_type_method");
    }
    elsif ($cgi->param('contenttypemethod') eq 'autodetect') {
        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");

        # Set the ispatch flag to 1 if the content type
        # is text/x-diff or text/x-patch
        if ($content_type =~ m{text/x-(?:diff|patch)}) {
            $cgi->param('ispatch', 1);
            $content_type = 'text/plain';
        }
917 918 919 920 921 922

        # 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';
        }
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
    }
    elsif ($cgi->param('contenttypemethod') eq 'list') {
        # The user selected a content type from the list, so use their
        # selection.
        $content_type = $cgi->param('contenttypeselection');
    }
    elsif ($cgi->param('contenttypemethod') eq 'manual') {
        # The user entered a content type manually, so use their entry.
        $content_type = $cgi->param('contenttypeentry');
    }
    else {
        ThrowCodeError("illegal_content_type_method",
                       { contenttypemethod => $cgi->param('contenttypemethod') });
    }
    return $content_type;
}


941
1;