Attachment.pm 27 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

61
use base qw(Bugzilla::Object);
62

63 64 65
###############################
####    Initialization     ####
###############################
66

67 68 69
use constant DB_TABLE   => 'attachments';
use constant ID_FIELD   => 'attach_id';
use constant LIST_ORDER => ID_FIELD;
70

71 72
sub DB_COLUMNS {
    my $dbh = Bugzilla->dbh;
73

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

89 90 91
###############################
####      Accessors      ######
###############################
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

=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

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
=item C<bug>

the bug object to which the attachment is attached

=back

=cut

sub bug {
    my $self = shift;

    require Bugzilla::Bug;
    $self->{bug} = Bugzilla::Bug->new($self->bug_id);
    return $self->{bug};
}

=over

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
=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;
157
    return $self->{mimetype};
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
}

=over

=item C<attacher>

the user who attached the attachment

=back

=cut

sub attacher {
    my $self = shift;
    return $self->{attacher} if exists $self->{attacher};
173
    $self->{attacher} = new Bugzilla::User($self->{submitter_id});
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    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;
189
    return $self->{creation_ts};
190 191 192 193
}

=over

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
=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

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
=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

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
=item C<isurl>

whether or not the attachment is a URL

=back

=cut

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

=over

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
=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

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
=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

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
=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,
335
                                                     $self->id);
336 337 338 339 340

    # 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())) {
341
            local $/;
342 343
            binmode AH;
            $self->{data} = <AH>;
344 345 346
            close(AH);
        }
    }
347

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
    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};

376
    $self->{datasize} =
377 378 379
        Bugzilla->dbh->selectrow_array("SELECT LENGTH(thedata)
                                        FROM attach_data
                                        WHERE id = ?",
380
                                       undef, $self->id) || 0;
381

382 383 384 385
    # 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}) {
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
        if (open(AH, $self->_get_local_filename())) {
            binmode AH;
            $self->{datasize} = (stat(AH))[7];
            close(AH);
        }
    }

    return $self->{datasize};
}

=over

=item C<flags>

flags that have been set on the attachment

=back

=cut

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

410
    $self->{flags} = Bugzilla::Flag->match({ 'attach_id' => $self->id });
411 412 413
    return $self->{flags};
}

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
=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 };

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

438 439 440 441
###############################
####      Validators     ######
###############################

442 443
# Instance methods; no POD documentation here yet because the only ones so far
# are private.
444 445 446 447 448

sub _get_local_filename {
    my $self = shift;
    my $hash = ($self->id % 100) + 100;
    $hash =~ s/.*(\d\d)$/group.$1/;
449
    return bz_locations()->{'attachdir'} . "/$hash/attachment." . $self->id;
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
sub _validate_filename {
    my ($throw_error) = @_;
    my $cgi = Bugzilla->cgi;
    defined $cgi->upload('data')
        || ($throw_error ? ThrowUserError("file_not_specified") : return 0);

    my $filename = $cgi->upload('data');

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

    return $filename;
}

sub _validate_data {
    my ($throw_error, $hr_vars) = @_;
    my $cgi = Bugzilla->cgi;
477 478
    my $maxsize = $cgi->param('ispatch') ? Bugzilla->params->{'maxpatchsize'} 
                  : Bugzilla->params->{'maxattachmentsize'};
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
    $maxsize *= 1024; # Convert from K
    my $fh;
    # Skip uploading into a local variable if the user wants to upload huge
    # attachments into local files.
    if (!$cgi->param('bigfile')) {
        $fh = $cgi->upload('data');
    }
    my $data;

    # We could get away with reading only as much as required, except that then
    # we wouldn't have a size to print to the error handler below.
    if (!$cgi->param('bigfile')) {
        # enable 'slurp' mode
        local $/;
        $data = <$fh>;
    }

    $data
        || ($cgi->param('bigfile'))
        || ($throw_error ? ThrowUserError("zero_length_file") : return 0);

    # Windows screenshots are usually uncompressed BMP files which
    # makes for a quick way to eat up disk space. Let's compress them.
    # We do this before we check the size since the uncompressed version
    # could easily be greater than maxattachmentsize.
504
    if (Bugzilla->params->{'convert_uncompressed_images'}
505 506 507 508 509 510 511 512
        && $cgi->param('contenttype') eq 'image/bmp') {
        require Image::Magick;
        my $img = Image::Magick->new(magick=>'bmp');
        $img->BlobToImage($data);
        $img->set(magick=>'png');
        my $imgdata = $img->ImageToBlob();
        $data = $imgdata;
        $cgi->param('contenttype', 'image/png');
513
        $hr_vars->{'convertedbmp'} = 1;
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
    }

    # Make sure the attachment does not exceed the maximum permitted size
    my $len = $data ? length($data) : 0;
    if ($maxsize && $len > $maxsize) {
        my $vars = { filesize => sprintf("%.0f", $len/1024) };
        if ($cgi->param('ispatch')) {
            $throw_error ? ThrowUserError("patch_too_large", $vars) : return 0;
        }
        else {
            $throw_error ? ThrowUserError("file_too_large", $vars) : return 0;
        }
    }

    return $data || '';
}

531 532 533 534 535 536 537 538
=pod

=head2 Class Methods

=over

=item C<get_attachments_by_bug($bug_id)>

539 540
Description: retrieves and returns the attachments the currently logged in
             user can view for the given bug.
541 542 543 544 545 546 547

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
548

549
sub get_attachments_by_bug {
550
    my ($class, $bug_id, $vars) = @_;
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    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);
567 568

    my $attachments = Bugzilla::Attachment->new_from_list($attach_ids);
569 570 571 572 573 574 575 576 577 578 579

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

580 581 582
        # Exclude flags for private attachments you cannot see.
        @$flags = grep {exists $att{$_->attach_id}} @$flags;

583 584 585
        push(@{$att{$_->attach_id}->{flags}}, $_) foreach @$flags;
        $attachments = [sort {$a->id <=> $b->id} values %att];
    }
586
    return $attachments;
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 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 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 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
=pod

=item C<validate_is_patch()>

Description: validates the "patch" flag passed in by CGI.

Returns:    1 on success.

=cut

sub validate_is_patch {
    my ($class, $throw_error) = @_;
    my $cgi = Bugzilla->cgi;

    # Set the ispatch flag to zero if it is undefined, since the UI uses
    # an HTML checkbox to represent this flag, and unchecked HTML checkboxes
    # do not get sent in HTML requests.
    $cgi->param('ispatch', $cgi->param('ispatch') ? 1 : 0);

    # Set the content type to text/plain if the attachment is a patch.
    $cgi->param('contenttype', 'text/plain') if $cgi->param('ispatch');

    return 1;
}

=pod

=item C<validate_description()>

Description: validates the description passed in by CGI.

Returns:    1 on success.

=cut

sub validate_description {
    my ($class, $throw_error) = @_;
    my $cgi = Bugzilla->cgi;

    $cgi->param('description')
        || ($throw_error ? ThrowUserError("missing_attachment_description") : return 0);

    return 1;
}

=pod

=item C<validate_content_type()>

Description: validates the content type passed in by CGI.

Returns:    1 on success.

=cut

sub validate_content_type {
    my ($class, $throw_error) = @_;
    my $cgi = Bugzilla->cgi;

    if (!defined $cgi->param('contenttypemethod')) {
        $throw_error ? ThrowUserError("missing_content_type_method") : return 0;
    }
    elsif ($cgi->param('contenttypemethod') eq 'autodetect') {
        my $contenttype =
            $cgi->uploadInfo($cgi->param('data'))->{'Content-Type'};
        # The user asked us to auto-detect the content type, so use the type
        # specified in the HTTP request headers.
        if ( !$contenttype ) {
            $throw_error ? ThrowUserError("missing_content_type") : return 0;
        }
        $cgi->param('contenttype', $contenttype);
    }
    elsif ($cgi->param('contenttypemethod') eq 'list') {
        # The user selected a content type from the list, so use their
        # selection.
        $cgi->param('contenttype', $cgi->param('contenttypeselection'));
    }
    elsif ($cgi->param('contenttypemethod') eq 'manual') {
        # The user entered a content type manually, so use their entry.
        $cgi->param('contenttype', $cgi->param('contenttypeentry'));
    }
    else {
        $throw_error ?
            ThrowCodeError("illegal_content_type_method",
                           { contenttypemethod => $cgi->param('contenttypemethod') }) :
            return 0;
    }

    if ( $cgi->param('contenttype') !~
           /^(application|audio|image|message|model|multipart|text|video)\/.+$/ ) {
        $throw_error ?
            ThrowUserError("invalid_content_type",
                           { contenttype => $cgi->param('contenttype') }) :
            return 0;
    }

    return 1;
}

=pod

690
=item C<validate_can_edit($attachment, $product_id)>
691

692
Description: validates if the user is allowed to view and edit the attachment.
693
             Only the submitter or someone with editbugs privs can edit it.
694 695
             Only the submitter and users in the insider group can view
             private attachments.
696

697 698 699
Params:      $attachment - the attachment object being edited.
             $product_id - the product ID the attachment belongs to.

700 701 702 703 704
Returns:     1 on success. Else an error is thrown.

=cut

sub validate_can_edit {
705
    my ($attachment, $product_id) = @_;
706 707
    my $user = Bugzilla->user;

708 709 710 711
    # The submitter can edit their attachments.
    return 1 if ($attachment->attacher->id == $user->id
                 || ((!$attachment->isprivate || $user->is_insider)
                      && $user->in_group('editbugs', $product_id)));
712 713 714

    # If we come here, then this attachment cannot be seen by the user.
    ThrowUserError('illegal_attachment_edit', { attach_id => $attachment->id });
715 716
}

717
=item C<validate_obsolete($bug)>
718 719 720

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

724
Params:      $bug - The bug object obsolete attachments should belong to.
725 726 727 728 729 730

Returns:     1 on success. Else an error is thrown.

=cut

sub validate_obsolete {
731
    my ($class, $bug) = @_;
732 733 734
    my $cgi = Bugzilla->cgi;

    # Make sure the attachment id is valid and the user has permissions to view
735 736
    # the bug to which it is attached. Make sure also that the user can view
    # the attachment itself.
737 738 739 740 741 742 743 744 745
    my @obsolete_attachments;
    foreach my $attachid ($cgi->param('obsolete')) {
        my $vars = {};
        $vars->{'attach_id'} = $attachid;

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

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

749
        # Check that the user can view and edit this attachment.
750
        $attachment->validate_can_edit($bug->product_id);
751

752 753
        $vars->{'description'} = $attachment->description;

754 755
        if ($attachment->bug_id != $bug->bug_id) {
            $vars->{'my_bug_id'} = $bug->bug_id;
756 757 758 759 760 761 762 763 764 765 766 767 768
            $vars->{'attach_bug_id'} = $attachment->bug_id;
            ThrowCodeError('mismatched_bug_ids_on_obsolete', $vars);
        }

        if ($attachment->isobsolete) {
          ThrowCodeError('attachment_already_obsolete', $vars);
        }

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

769 770 771
###############################
####     Constructors     #####
###############################
772 773 774

=pod

775
=item C<create($throw_error, $bug, $user, $timestamp, $hr_vars)>
776 777 778

Description: inserts an attachment from CGI input for the given bug.

779 780
Params:     C<$bug> - Bugzilla::Bug object - the bug for which to insert
            the attachment.
781 782 783 784 785 786 787 788 789 790 791
            C<$user> - Bugzilla::User object - the user we're inserting an
            attachment for.
            C<$timestamp> - scalar - timestamp of the insert as returned
            by SELECT NOW().
            C<$hr_vars> - hash reference - reference to a hash of template
            variables.

Returns:    the ID of the new attachment.

=cut

792 793
# FIXME: needs to follow the way Object->create() works.
sub create {
794
    my ($class, $throw_error, $bug, $user, $timestamp, $hr_vars) = @_;
795 796 797 798 799 800 801 802

    my $cgi = Bugzilla->cgi;
    my $dbh = Bugzilla->dbh;
    my $attachurl = $cgi->param('attachurl') || '';
    my $data;
    my $filename;
    my $contenttype;
    my $isurl;
803 804
    $class->validate_is_patch($throw_error) || return;
    $class->validate_description($throw_error) || return;
805

806 807 808 809
    if (Bugzilla->params->{'allow_attach_url'}
        && ($attachurl =~ /^(http|https|ftp):\/\/\S+/)
        && !defined $cgi->upload('data'))
    {
810 811 812 813 814 815 816 817
        $filename = '';
        $data = $attachurl;
        $isurl = 1;
        $contenttype = 'text/plain';
        $cgi->param('ispatch', 0);
        $cgi->delete('bigfile');
    }
    else {
818
        $filename = _validate_filename($throw_error) || return;
819 820 821
        # need to validate content type before data as
        # we now check the content type for image/bmp in _validate_data()
        unless ($cgi->param('ispatch')) {
822
            $class->validate_content_type($throw_error) || return;
823 824 825 826 827 828 829 830 831

            # Set the ispatch flag to 1 if we're set to autodetect
            # and the content type is text/x-diff or text/x-patch
            if ($cgi->param('contenttypemethod') eq 'autodetect'
                && $cgi->param('contenttype') =~ m{text/x-(?:diff|patch)})
            {
                $cgi->param('ispatch', 1);
                $cgi->param('contenttype', 'text/plain');
            }
832
        }
833 834 835
        $data = _validate_data($throw_error, $hr_vars);
        # If the attachment is stored locally, $data eq ''.
        # If an error is thrown, $data eq '0'.
836
        ($data ne '0') || return;
837 838 839 840 841 842 843 844
        $contenttype = $cgi->param('contenttype');

        # These are inserted using placeholders so no need to panic
        trick_taint($filename);
        trick_taint($contenttype);
        $isurl = 0;
    }

845 846 847
    # Check attachments the user tries to mark as obsolete.
    my @obsolete_attachments;
    if ($cgi->param('obsolete')) {
848
        @obsolete_attachments = $class->validate_obsolete($bug);
849 850
    }

851 852
    # The order of these function calls is important, as Flag::validate
    # assumes User::match_field has ensured that the
853 854 855 856 857
    # values in the requestee fields are legitimate user email addresses.
    my $match_status = Bugzilla::User::match_field($cgi, {
        '^requestee(_type)?-(\d+)$' => { 'type' => 'multi' },
    }, MATCH_SKIP_CONFIRM);

858
    $hr_vars->{'match_field'} = 'requestee';
859
    if ($match_status == USER_MATCH_FAILED) {
860
        $hr_vars->{'message'} = 'user_match_failed';
861 862
    }
    elsif ($match_status == USER_MATCH_MULTIPLE) {
863
        $hr_vars->{'message'} = 'user_match_multiple';
864 865 866 867 868 869 870 871 872 873
    }

    # Escape characters in strings that will be used in SQL statements.
    my $description = $cgi->param('description');
    trick_taint($description);
    my $isprivate = $cgi->param('isprivate') ? 1 : 0;

    # Insert the attachment into the database.
    my $sth = $dbh->do(
        "INSERT INTO attachments
874
            (bug_id, creation_ts, modification_time, filename, description,
875
             mimetype, ispatch, isurl, isprivate, submitter_id)
876 877
         VALUES (?,?,?,?,?,?,?,?,?,?)", undef, ($bug->bug_id, $timestamp, $timestamp,
              $filename, $description, $contenttype, $cgi->param('ispatch'),
878 879 880 881 882 883 884 885 886 887 888 889
              $isurl, $isprivate, $user->id));
    # Retrieve the ID of the newly created attachment record.
    my $attachid = $dbh->bz_last_key('attachments', 'attach_id');

    # We only use $data here in this INSERT with a placeholder,
    # so it's safe.
    $sth = $dbh->prepare("INSERT INTO attach_data
                         (id, thedata) VALUES ($attachid, ?)");
    trick_taint($data);
    $sth->bind_param(1, $data, $dbh->BLOB_TYPE);
    $sth->execute();

890
    # If the file is to be stored locally, stream the file from the web server
891 892
    # to the local file without reading it into a local variable.
    if ($cgi->param('bigfile')) {
893
        my $attachdir = bz_locations()->{'attachdir'};
894 895 896 897 898 899 900 901
        my $fh = $cgi->upload('data');
        my $hash = ($attachid % 100) + 100;
        $hash =~ s/.*(\d\d)$/group.$1/;
        mkdir "$attachdir/$hash", 0770;
        chmod 0770, "$attachdir/$hash";
        open(AH, ">$attachdir/$hash/attachment.$attachid");
        binmode AH;
        my $sizecount = 0;
902
        my $limit = (Bugzilla->params->{"maxlocalattachment"} * 1048576);
903 904 905 906 907 908 909
        while (<$fh>) {
            print AH $_;
            $sizecount += length($_);
            if ($sizecount > $limit) {
                close AH;
                close $fh;
                unlink "$attachdir/$hash/attachment.$attachid";
910
                $throw_error ? ThrowUserError("local_file_too_large") : return;
911 912 913 914 915
            }
        }
        close AH;
        close $fh;
    }
916 917 918 919 920 921 922

    # Make existing attachments obsolete.
    my $fieldid = get_field_id('attachments.isobsolete');

    foreach my $obsolete_attachment (@obsolete_attachments) {
        # If the obsolete attachment has request flags, cancel them.
        # This call must be done before updating the 'attachments' table.
923
        Bugzilla::Flag->CancelRequests($bug, $obsolete_attachment, $timestamp);
924

925 926 927
        $dbh->do('UPDATE attachments SET isobsolete = 1, modification_time = ?
                  WHERE attach_id = ?',
                 undef, ($timestamp, $obsolete_attachment->id));
928 929 930 931 932 933 934 935

        $dbh->do('INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when,
                                             fieldid, removed, added)
                       VALUES (?,?,?,?,?,?,?)',
                  undef, ($bug->bug_id, $obsolete_attachment->id, $user->id,
                          $timestamp, $fieldid, 0, 1));
    }

936
    my $attachment = new Bugzilla::Attachment($attachid);
937 938 939 940 941 942 943 944 945 946 947 948 949

    # 1. Add flags, if any. To avoid dying if something goes wrong
    # while processing flags, we will eval() flag validation.
    # This requires errors to die().
    # XXX: this can go away as soon as flag validation is able to
    #      fail without dying.
    #
    # 2. Flag::validate() should not detect any reference to existing flags
    # when creating a new attachment. Setting the third param to -1 will
    # force this function to check this point.
    my $error_mode_cache = Bugzilla->error_mode;
    Bugzilla->error_mode(ERROR_MODE_DIE);
    eval {
950 951
        Bugzilla::Flag::validate($bug->bug_id, -1, SKIP_REQUESTEE_ON_ERROR);
        Bugzilla::Flag->process($bug, $attachment, $timestamp, $hr_vars);
952 953 954
    };
    Bugzilla->error_mode($error_mode_cache);
    if ($@) {
955 956
        $hr_vars->{'message'} = 'flag_creation_failed';
        $hr_vars->{'flag_creation_error'} = $@;
957
    }
958

959 960
    # Return the new attachment object.
    return $attachment;
961 962
}

963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
=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);
    $dbh->do('UPDATE attachments SET mimetype = ?, ispatch = ?, isurl = ?, isobsolete = ?
              WHERE attach_id = ?', undef, ('text/plain', 0, 0, 1, $self->id));
    $dbh->bz_commit_transaction();
}

989
1;