attachment.cgi 45.9 KB
Newer Older
1
#!/usr/bin/perl -wT
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# -*- 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>
23 24
#                 Daniel Raichle <draichle@gmx.net>
#                 Dave Miller <justdave@syndicomm.com>
25
#                 Alexander J. Vincent <ajvincent@juno.com>
26
#                 Max Kanat-Alexander <mkanat@bugzilla.org>
27
#                 Greg Hendricks <ghendricks@novell.com>
28 29 30 31 32 33 34 35

################################################################################
# Script Initialization
################################################################################

# Make it harder for us to do dangerous things in Perl.
use strict;

36 37
use lib qw(.);

38
# Include the Bugzilla CGI and general utility library.
39
require "globals.pl";
40
use Bugzilla::Config qw(:locations);
41

42
# Use these modules to handle flags.
43
use Bugzilla::Constants;
44 45
use Bugzilla::Flag; 
use Bugzilla::FlagType; 
46
use Bugzilla::User;
47
use Bugzilla::Util;
48
use Bugzilla::Bug;
49
use Bugzilla::Field;
50

51
Bugzilla->login();
52

53
my $cgi = Bugzilla->cgi;
54 55
my $template = Bugzilla->template;
my $vars = {};
56

57 58 59 60
################################################################################
# Main Body Execution
################################################################################

61 62 63 64
# All calls to this script should contain an "action" variable whose
# value determines what the user wants to do.  The code below checks
# the value of that variable and runs the appropriate code. If none is
# supplied, we default to 'view'.
65 66

# Determine whether to use the action specified by the user or the default.
67
my $action = $cgi->param('action') || 'view';
68 69

if ($action eq "view")  
70
{
71
    view();
72
}
73 74
elsif ($action eq "interdiff")
{
75
    interdiff();
76 77 78
}
elsif ($action eq "diff")
{
79
    diff();
80
}
81 82
elsif ($action eq "viewall") 
{ 
83
    viewall(); 
84
}
85 86
elsif ($action eq "enter") 
{ 
87 88
    Bugzilla->login(LOGIN_REQUIRED);
    enter(); 
89 90 91
}
elsif ($action eq "insert")
{
92 93
    Bugzilla->login(LOGIN_REQUIRED);
    insert();
94
}
95 96
elsif ($action eq "edit") 
{ 
97
    edit(); 
98 99 100
}
elsif ($action eq "update") 
{ 
101 102
    Bugzilla->login(LOGIN_REQUIRED);
    update();
103 104 105
}
else 
{ 
106
  ThrowCodeError("unknown_action", { action => $action });
107 108 109 110 111 112 113 114
}

exit;

################################################################################
# Data Validation / Security Authorization
################################################################################

115 116 117 118 119 120 121 122 123 124 125 126
# Validates an attachment ID. Optionally takes a parameter of a form
# variable name that contains the ID to be validated. If not specified,
# uses 'id'.
# 
# Will throw an error if 1) attachment ID is not a valid number,
# 2) attachment does not exist, or 3) user isn't allowed to access the
# attachment.
#
# Returns a list, where the first item is the validated, detainted
# attachment id, and the 2nd item is the bug id corresponding to the
# attachment.
# 
127 128
sub validateID
{
129 130
    my $param = @_ ? $_[0] : 'id';

131 132 133
    # If we're not doing interdiffs, check if id wasn't specified and
    # prompt them with a page that allows them to choose an attachment.
    # Happens when calling plain attachment.cgi from the urlbar directly
134 135
    if ($param eq 'id' && !$cgi->param('id')) {

136
        print $cgi->header();
137 138 139 140
        $template->process("attachment/choose.html.tmpl", $vars) ||
            ThrowTemplateError($template->error());
        exit;
    }
141
    
142 143 144 145 146 147 148
    my $attach_id = $cgi->param($param);

    # Validate the specified attachment id. detaint kills $attach_id if
    # non-natural, so use the original value from $cgi in our exception
    # message here.
    detaint_natural($attach_id)
     || ThrowUserError("invalid_attach_id", { attach_id => $cgi->param($param) });
149
  
150
    # Make sure the attachment exists in the database.
151
    SendSQL("SELECT bug_id, isprivate FROM attachments WHERE attach_id = $attach_id");
152
    MoreSQLData()
153
      || ThrowUserError("invalid_attach_id", { attach_id => $attach_id });
154

155
    # Make sure the user is authorized to access this attachment's bug.
156 157
    (my $bugid, my $isprivate) = FetchSQLData();

158
    ValidateBugID($bugid);
159 160 161 162
    if ($isprivate && Param("insidergroup")) {
        UserInGroup(Param("insidergroup"))
          || ThrowUserError("auth_failure", {action => "access",
                                             object => "attachment"});
163
    }
164

165
    return ($attach_id,$bugid);
166 167
}

168 169 170
# Validates format of a diff/interdiff. Takes a list as an parameter, which
# defines the valid format values. Will throw an error if the format is not
# in the list. Returns either the user selected or default format.
171 172
sub validateFormat
{
173 174 175
  # receives a list of legal formats; first item is a default
  my $format = $cgi->param('format') || $_[0];
  if ( lsearch(\@_, $format) == -1)
176
  {
177
     ThrowUserError("invalid_format", { format  => $format, formats => \@_ });
178
  }
179

180
  return $format;
181 182
}

183 184
# Validates context of a diff/interdiff. Will throw an error if the context
# is not number, "file" or "patch". Returns the validated, detainted context.
185 186
sub validateContext
{
187 188 189 190
  my $context = $cgi->param('context') || "patch";
  if ($context ne "file" && $context ne "patch") {
    detaint_natural($context)
      || ThrowUserError("invalid_context", { context => $cgi->param('context') });
191
  }
192 193

  return $context;
194 195
}

196 197 198 199 200 201 202 203 204
sub validateCanEdit
{
    my ($attach_id) = (@_);

    # People in editbugs can edit all attachments
    return if UserInGroup("editbugs");

    # Bug 97729 - the submitter can edit their attachments
    SendSQL("SELECT attach_id FROM attachments WHERE " .
205
            "attach_id = $attach_id AND submitter_id = " . Bugzilla->user->id);
206 207

    FetchSQLData()
208 209
      || ThrowUserError("illegal_attachment_edit",
                        { attach_id => $attach_id });
210 211
}

212 213 214 215
sub validateCanChangeAttachment 
{
    my ($attachid) = @_;
    SendSQL("SELECT product_id
216 217 218 219
             FROM attachments
             INNER JOIN bugs
             ON bugs.bug_id = attachments.bug_id
             WHERE attach_id = $attachid");
220
    my $productid = FetchOneColumn();
221
    Bugzilla->user->can_edit_product($productid)
222 223
      || ThrowUserError("illegal_attachment_edit",
                        { attach_id => $attachid });
224 225 226 227 228 229 230 231 232
}

sub validateCanChangeBug
{
    my ($bugid) = @_;
    SendSQL("SELECT product_id
             FROM bugs 
             WHERE bug_id = $bugid");
    my $productid = FetchOneColumn();
233
    Bugzilla->user->can_edit_product($productid)
234 235
      || ThrowUserError("illegal_attachment_edit_bug",
                        { bug_id => $bugid });
236 237
}

238 239
sub validateDescription
{
240 241
    $cgi->param('description')
      || ThrowUserError("missing_attachment_description");
242 243 244 245
}

sub validateIsPatch
{
246 247 248 249
    # 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);
250

251 252
    # Set the content type to text/plain if the attachment is a patch.
    $cgi->param('contenttype', 'text/plain') if $cgi->param('ispatch');
253 254 255 256
}

sub validateContentType
{
257
  if (!defined $cgi->param('contenttypemethod'))
258
  {
259
    ThrowUserError("missing_content_type_method");
260
  }
261
  elsif ($cgi->param('contenttypemethod') eq 'autodetect')
262
  {
263
    my $contenttype = $cgi->uploadInfo($cgi->param('data'))->{'Content-Type'};
264 265
    # The user asked us to auto-detect the content type, so use the type
    # specified in the HTTP request headers.
266
    if ( !$contenttype )
267
    {
268
      ThrowUserError("missing_content_type");
269
    }
270
    $cgi->param('contenttype', $contenttype);
271
  }
272
  elsif ($cgi->param('contenttypemethod') eq 'list')
273 274
  {
    # The user selected a content type from the list, so use their selection.
275
    $cgi->param('contenttype', $cgi->param('contenttypeselection'));
276
  }
277
  elsif ($cgi->param('contenttypemethod') eq 'manual')
278 279
  {
    # The user entered a content type manually, so use their entry.
280
    $cgi->param('contenttype', $cgi->param('contenttypeentry'));
281 282 283
  }
  else
  {
284
    ThrowCodeError("illegal_content_type_method",
285
                   { contenttypemethod => $cgi->param('contenttypemethod') });
286 287
  }

288 289
  if ( $cgi->param('contenttype') !~
         /^(application|audio|image|message|model|multipart|text|video)\/.+$/ )
290
  {
291
    ThrowUserError("invalid_content_type",
292
                   { contenttype => $cgi->param('contenttype') });
293
  }
294 295 296 297
}

sub validateIsObsolete
{
298 299 300 301
    # Set the isobsolete 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('isobsolete', $cgi->param('isobsolete') ? 1 : 0);
302 303
}

304 305 306 307 308
sub validatePrivate
{
    # Set the isprivate 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.
309
    $cgi->param('isprivate', $cgi->param('isprivate') ? 1 : 0);
310 311
}

312 313
sub validateData
{
314
  my $maxsize = $cgi->param('ispatch') ? Param('maxpatchsize') : Param('maxattachmentsize');
315
  $maxsize *= 1024; # Convert from K
316 317 318
  my $fh;
  # Skip uploading into a local variable if the user wants to upload huge
  # attachments into local files.
319
  if (!$cgi->param('bigfile'))
320 321 322
  {
    $fh = $cgi->upload('data');
  }
323
  my $data;
324

325 326
  # 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.
327
  if (!$cgi->param('bigfile'))
328
  {
329 330 331
      # enable 'slurp' mode
      local $/;
      $data = <$fh>;
332
  }
333 334

  $data
335
    || ($cgi->param('bigfile'))
336
    || ThrowUserError("zero_length_file");
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    
    # 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.
    if (Param('convert_uncompressed_images') && $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');
      $vars->{'convertedbmp'} = 1;
    }
    
353
  # Make sure the attachment does not exceed the maximum permitted size
354
  my $len = $data ? length($data) : 0;
355
  if ($maxsize && $len > $maxsize) {
356
      my $vars = { filesize => sprintf("%.0f", $len/1024) };
357
      if ($cgi->param('ispatch')) {
358
          ThrowUserError("patch_too_large", $vars);
359
      } else {
360
          ThrowUserError("file_too_large", $vars);
361 362 363
      }
  }

364
  return $data || '';
365 366 367 368
}

sub validateFilename
{
369
  defined $cgi->upload('data')
370
    || ThrowUserError("file_not_specified");
371

372
  my $filename = $cgi->upload('data');
373 374 375 376 377 378 379 380 381 382 383
  
  # 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);
384 385

  return $filename;
386 387 388 389
}

sub validateObsolete
{
390 391
  my @obsolete_ids = ();

392 393
  # Make sure the attachment id is valid and the user has permissions to view
  # the bug to which it is attached.
394
  foreach my $attachid ($cgi->param('obsolete')) {
395
    my $vars = {};
396 397
    $vars->{'attach_id'} = $attachid;
    
398
    detaint_natural($attachid)
399
      || ThrowCodeError("invalid_attach_id_to_obsolete", $vars);
400 401 402 403 404 405
  
    SendSQL("SELECT bug_id, isobsolete, description 
             FROM attachments WHERE attach_id = $attachid");

    # Make sure the attachment exists in the database.
    MoreSQLData()
406
      || ThrowUserError("invalid_attach_id", $vars);
407 408 409

    my ($bugid, $isobsolete, $description) = FetchSQLData();

410 411
    $vars->{'description'} = $description;
    
412
    if ($bugid != $cgi->param('bugid'))
413
    {
414
      $vars->{'my_bug_id'} = $cgi->param('bugid');
415
      $vars->{'attach_bug_id'} = $bugid;
416
      ThrowCodeError("mismatched_bug_ids_on_obsolete", $vars);
417 418 419 420
    }

    if ( $isobsolete )
    {
421
      ThrowCodeError("attachment_already_obsolete", $vars);
422
    }
423 424 425

    # Check that the user can modify this attachment
    validateCanEdit($attachid);
426
    push(@obsolete_ids, $attachid);
427
  }
428 429

  return @obsolete_ids;
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
}

# Returns 1 if the parameter is 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.
sub isViewable
{
  my $contenttype = trim(shift);
    
  # We assume we can view all text and image types  
  if ($contenttype =~ /^(text|image)\//) {
    return 1;
  }
  
  # Mozilla can view XUL. Note the trailing slash on the Gecko detection to
  # avoid sending XUL to Safari.
  if (($contenttype =~ /^application\/vnd\.mozilla\./) &&
      ($cgi->user_agent() =~ /Gecko\//))
  {
    return 1;
  }
452

453 454 455 456 457 458 459 460 461
  # If it's not one of the above types, we check the Accept: header for any 
  # types mentioned explicitly.
  my $accept = join(",", $cgi->Accept());
  
  if ($accept =~ /^(.*,)?\Q$contenttype\E(,.*)?$/) {
    return 1;
  }
  
  return 0;
462 463
}

464 465 466 467
################################################################################
# Functions
################################################################################

468
# Display an attachment.
469 470
sub view
{
471 472
    # Retrieve and validate parameters
    my ($attach_id) = validateID();
473

474
    # Retrieve the attachment content and its content type from the database.
475
    SendSQL("SELECT mimetype, filename, thedata FROM attachments " .
476
            "INNER JOIN attach_data ON id = attach_id " .
477
            "WHERE attach_id = $attach_id");
478
    my ($contenttype, $filename, $thedata) = FetchSQLData();
479
   
480 481 482
    # Bug 111522: allow overriding content-type manually in the posted form
    # params.
    if (defined $cgi->param('content_type'))
483
    {
484 485
        $cgi->param('contenttypemethod', 'manual');
        $cgi->param('contenttypeentry', $cgi->param('content_type'));
486
        validateContentType();
487
        $contenttype = $cgi->param('content_type');
488
    }
489

490
    # Return the appropriate HTTP response headers.
491 492
    $filename =~ s/^.*[\/\\]//;
    my $filesize = length($thedata);
493 494 495 496
    # A zero length attachment in the database means the attachment is 
    # stored in a local file
    if ($filesize == 0)
    {
497
        my $hash = ($attach_id % 100) + 100;
498
        $hash =~ s/.*(\d\d)$/group.$1/;
499
        if (open(AH, "$attachdir/$hash/attachment.$attach_id")) {
500 501 502 503 504 505 506 507 508
            binmode AH;
            $filesize = (stat(AH))[7];
        }
    }
    if ($filesize == 0)
    {
        ThrowUserError("attachment_removed");
    }

509

510 511 512 513
    # escape quotes and backslashes in the filename, per RFCs 2045/822
    $filename =~ s/\\/\\\\/g; # escape backslashes
    $filename =~ s/"/\\"/g; # escape quotes

514 515 516
    print $cgi->header(-type=>"$contenttype; name=\"$filename\"",
                       -content_disposition=> "inline; filename=\"$filename\"",
                       -content_length => $filesize);
517

518 519 520 521 522 523 524 525 526
    if ($thedata) {
        print $thedata;
    } else {
        while (<AH>) {
            print $_;
        }
        close(AH);
    }

527 528
}

529 530
sub interdiff
{
531 532 533 534 535 536
  # Retrieve and validate parameters
  my ($old_id) = validateID('oldid');
  my ($new_id) = validateID('newid');
  my $format = validateFormat('html', 'raw');
  my $context = validateContext();

537 538
  # Get old patch data
  my ($old_bugid, $old_description, $old_filename, $old_file_list) =
539
      get_unified_diff($old_id);
540 541 542

  # Get new patch data
  my ($new_bugid, $new_description, $new_filename, $new_file_list) =
543
      get_unified_diff($new_id);
544 545 546 547 548 549 550 551 552 553 554

  my $warning = warn_if_interdiff_might_fail($old_file_list, $new_file_list);

  #
  # send through interdiff, send output directly to template
  #
  # Must hack path so that interdiff will work.
  #
  $ENV{'PATH'} = $::diffpath;
  open my $interdiff_fh, "$::interdiffbin $old_filename $new_filename|";
  binmode $interdiff_fh;
555 556
    my ($reader, $last_reader) = setup_patch_readers("", $context);
    if ($format eq 'raw')
557
  {
558 559
    require PatchReader::DiffPrinter::raw;
    $last_reader->sends_data_to(new PatchReader::DiffPrinter::raw());
560 561 562 563 564 565 566 567
    # Actually print out the patch
    print $cgi->header(-type => 'text/plain',
                       -expires => '+3M');
  }
  else
  {
    $vars->{warning} = $warning if $warning;
    $vars->{bugid} = $new_bugid;
568
    $vars->{oldid} = $old_id;
569
    $vars->{old_desc} = $old_description;
570
    $vars->{newid} = $new_id;
571 572 573 574
    $vars->{new_desc} = $new_description;
    delete $vars->{attachid};
    delete $vars->{do_context};
    delete $vars->{context};
575
    setup_template_patch_reader($last_reader, $format, $context);
576
  }
577
  $reader->iterate_fh($interdiff_fh, "interdiff #$old_id #$new_id");
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
  close $interdiff_fh;
  $ENV{'PATH'} = '';

  #
  # Delete temporary files
  #
  unlink($old_filename) or warn "Could not unlink $old_filename: $!";
  unlink($new_filename) or warn "Could not unlink $new_filename: $!";
}

sub get_unified_diff
{
  my ($id) = @_;

  # Bring in the modules we need
593 594 595 596
  require PatchReader::Raw;
  require PatchReader::FixPatchRoot;
  require PatchReader::DiffPrinter::raw;
  require PatchReader::PatchInfoGrabber;
597 598 599
  require File::Temp;

  # Get the patch
600 601 602 603 604
  SendSQL("SELECT bug_id, description, ispatch, thedata " . 
          "FROM attachments " .
          "INNER JOIN attach_data " .
          "ON id = attach_id " .
          "WHERE attach_id = $id");
605 606 607 608 609 610 611
  my ($bugid, $description, $ispatch, $thedata) = FetchSQLData();
  if (!$ispatch) {
    $vars->{'attach_id'} = $id;
    ThrowCodeError("must_be_patch");
  }

  # Reads in the patch, converting to unified diff in a temp file
612 613 614
  my $reader = new PatchReader::Raw;
  my $last_reader = $reader;

615
  # fixes patch root (makes canonical if possible)
616 617 618 619 620 621
  if (Param('cvsroot')) {
    my $fix_patch_root = new PatchReader::FixPatchRoot(Param('cvsroot'));
    $last_reader->sends_data_to($fix_patch_root);
    $last_reader = $fix_patch_root;
  }

622
  # Grabs the patch file info
623 624 625 626
  my $patch_info_grabber = new PatchReader::PatchInfoGrabber();
  $last_reader->sends_data_to($patch_info_grabber);
  $last_reader = $patch_info_grabber;

627 628
  # Prints out to temporary file
  my ($fh, $filename) = File::Temp::tempfile();
629 630 631 632
  my $raw_printer = new PatchReader::DiffPrinter::raw($fh);
  $last_reader->sends_data_to($raw_printer);
  $last_reader = $raw_printer;

633
  # Iterate!
634
  $reader->iterate_string($id, $thedata);
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

  return ($bugid, $description, $filename, $patch_info_grabber->patch_info()->{files});
}

sub warn_if_interdiff_might_fail {
  my ($old_file_list, $new_file_list) = @_;
  # Verify that the list of files diffed is the same
  my @old_files = sort keys %{$old_file_list};
  my @new_files = sort keys %{$new_file_list};
  if (@old_files != @new_files ||
      join(' ', @old_files) ne join(' ', @new_files)) {
    return "interdiff1";
  }

  # Verify that the revisions in the files are the same
  foreach my $file (keys %{$old_file_list}) {
    if ($old_file_list->{$file}{old_revision} ne
        $new_file_list->{$file}{old_revision}) {
      return "interdiff2";
    }
  }

  return undef;
}

660
sub setup_patch_readers {
661
  my ($diff_root, $context) = @_;
662 663 664 665 666 667 668 669 670

  #
  # Parameters:
  # format=raw|html
  # context=patch|file|0-n
  # collapsed=0|1
  # headers=0|1
  #

671 672 673 674 675
  # Define the patch readers
  # The reader that reads the patch in (whatever its format)
  require PatchReader::Raw;
  my $reader = new PatchReader::Raw;
  my $last_reader = $reader;
676 677 678
  # Fix the patch root if we have a cvs root
  if (Param('cvsroot'))
  {
679 680 681 682
    require PatchReader::FixPatchRoot;
    $last_reader->sends_data_to(new PatchReader::FixPatchRoot(Param('cvsroot')));
    $last_reader->sends_data_to->diff_root($diff_root) if defined($diff_root);
    $last_reader = $last_reader->sends_data_to;
683 684
  }
  # Add in cvs context if we have the necessary info to do it
685
  if ($context ne "patch" && $::cvsbin && Param('cvsroot_get'))
686
  {
687 688
    require PatchReader::AddCVSContext;
    $last_reader->sends_data_to(
689
          new PatchReader::AddCVSContext($context,
690
                                         Param('cvsroot_get')));
691
    $last_reader = $last_reader->sends_data_to;
692
  }
693
  return ($reader, $last_reader);
694 695
}

696
sub setup_template_patch_reader
697
{
698
  my ($last_reader, $format, $context) = @_;
699

700
  require PatchReader::DiffPrinter::template;
701 702

  # Define the vars for templates
703 704
  if (defined $cgi->param('headers')) {
    $vars->{headers} = $cgi->param('headers');
705
  } else {
706
    $vars->{headers} = 1 if !defined $cgi->param('headers');
707
  }
708 709
  $vars->{collapsed} = $cgi->param('collapsed');
  $vars->{context} = $context;
710 711 712 713 714
  $vars->{do_context} = $::cvsbin && Param('cvsroot_get') && !$vars->{'newid'};

  # Print everything out
  print $cgi->header(-type => 'text/html',
                     -expires => '+3M');
715
  $last_reader->sends_data_to(new PatchReader::DiffPrinter::template($template,
716 717 718 719 720 721 722 723 724 725 726 727
                             "attachment/diff-header.$format.tmpl",
                             "attachment/diff-file.$format.tmpl",
                             "attachment/diff-footer.$format.tmpl",
                             { %{$vars},
                               bonsai_url => Param('bonsai_url'),
                               lxr_url => Param('lxr_url'),
                               lxr_root => Param('lxr_root'),
                             }));
}

sub diff
{
728 729 730 731 732
  # Retrieve and validate parameters
  my ($attach_id) = validateID();
  my $format = validateFormat('html', 'raw');
  my $context = validateContext();

733
  # Get patch data
734
  SendSQL("SELECT bug_id, description, ispatch, thedata FROM attachments " .
735
          "INNER JOIN attach_data ON id = attach_id " .
736
          "WHERE attach_id = $attach_id");
737 738 739 740 741 742 743 744 745
  my ($bugid, $description, $ispatch, $thedata) = FetchSQLData();

  # If it is not a patch, view normally
  if (!$ispatch)
  {
    view();
    return;
  }

746
  my ($reader, $last_reader) = setup_patch_readers(undef,$context);
747

748
  if ($format eq 'raw')
749
  {
750 751
    require PatchReader::DiffPrinter::raw;
    $last_reader->sends_data_to(new PatchReader::DiffPrinter::raw());
752 753 754
    # Actually print out the patch
    print $cgi->header(-type => 'text/plain',
                       -expires => '+3M');
755
    $reader->iterate_string("Attachment $attach_id", $thedata);
756 757 758 759 760 761 762 763 764 765 766
  }
  else
  {
    $vars->{other_patches} = [];
    if ($::interdiffbin && $::diffpath) {
      # Get list of attachments on this bug.
      # Ignore the current patch, but select the one right before it
      # chronologically.
      SendSQL("SELECT attach_id, description FROM attachments WHERE bug_id = $bugid AND ispatch = 1 ORDER BY creation_ts DESC");
      my $select_next_patch = 0;
      while (my ($other_id, $other_desc) = FetchSQLData()) {
767
        if ($other_id eq $attach_id) {
768 769 770 771 772 773 774 775 776 777 778
          $select_next_patch = 1;
        } else {
          push @{$vars->{other_patches}}, { id => $other_id, desc => $other_desc, selected => $select_next_patch };
          if ($select_next_patch) {
            $select_next_patch = 0;
          }
        }
      }
    }

    $vars->{bugid} = $bugid;
779
    $vars->{attachid} = $attach_id;
780
    $vars->{description} = $description;
781
    setup_template_patch_reader($last_reader, $format, $context);
782
    # Actually print out the patch
783
    $reader->iterate_string("Attachment $attach_id", $thedata);
784 785
  }
}
786

787 788
# Display all attachments for a given bug in a series of IFRAMEs within one
# HTML page.
789 790
sub viewall
{
791 792 793
    # Retrieve and validate parameters
    my $bugid = $cgi->param('bugid');
    ValidateBugID($bugid);
794

795 796
    # Retrieve the attachments from the database and write them into an array
    # of hashes where each hash represents one attachment.
797
    my $privacy = "";
798 799
    my $dbh = Bugzilla->dbh;

800 801 802
    if (Param("insidergroup") && !(UserInGroup(Param("insidergroup")))) {
        $privacy = "AND isprivate < 1 ";
    }
803 804 805
    SendSQL("SELECT attach_id, " .
            $dbh->sql_date_format('creation_ts', '%Y.%m.%d %H:%i') . ",
            mimetype, description, ispatch, isobsolete, isprivate, 
806
            LENGTH(thedata)
807 808 809 810
            FROM attachments 
            INNER JOIN attach_data
            ON attach_id = id
            WHERE bug_id = $bugid $privacy 
811
            ORDER BY attach_id");
812
  my @attachments; # the attachments array
813 814
  while (MoreSQLData())
  {
815
    my %a; # the attachment hash
816
    ($a{'attachid'}, $a{'date'}, $a{'contenttype'},
817 818
     $a{'description'}, $a{'ispatch'}, $a{'isobsolete'}, $a{'isprivate'},
     $a{'datasize'}) = FetchSQLData();
819
    $a{'isviewable'} = isViewable($a{'contenttype'});
820 821
    $a{'flags'} = Bugzilla::Flag::match({ 'attach_id' => $a{'attachid'},
                                          'is_active' => 1 });
822 823 824 825 826

    # Add the hash representing the attachment to the array of attachments.
    push @attachments, \%a;
  }

827 828
  # Retrieve the bug summary (for displaying on screen) and assignee.
  SendSQL("SELECT short_desc, assigned_to FROM bugs " .
829
          "WHERE bug_id = $bugid");
830
  my ($bugsummary, $assignee_id) = FetchSQLData();
831 832

  # Define the variables and functions that will be passed to the UI template.
833
  $vars->{'bugid'} = $bugid;
834
  $vars->{'attachments'} = \@attachments;
835 836
  $vars->{'bugassignee_id'} = $assignee_id;
  $vars->{'bugsummary'} = $bugsummary;
837
  $vars->{'GetBugLink'} = \&GetBugLink;
838

839
  print $cgi->header();
840 841

  # Generate and return the UI (HTML page) from the appropriate template.
842 843
  $template->process("attachment/show-multiple.html.tmpl", $vars)
    || ThrowTemplateError($template->error());
844 845
}

846
# Display a form for entering a new attachment.
847 848
sub enter
{
849 850 851 852
  # Retrieve and validate parameters
  my $bugid = $cgi->param('bugid');
  ValidateBugID($bugid);
  validateCanChangeBug($bugid);
853

854 855 856 857
  # Retrieve the attachments the user can edit from the database and write
  # them into an array of hashes where each hash represents one attachment.
  my $canEdit = "";
  if (!UserInGroup("editbugs")) {
858
      $canEdit = "AND submitter_id = " . Bugzilla->user->id;
859
  }
860
  SendSQL("SELECT attach_id, description, isprivate
861
           FROM attachments
862
           WHERE bug_id = $bugid 
863
           AND isobsolete = 0 $canEdit
864 865 866 867
           ORDER BY attach_id");
  my @attachments; # the attachments array
  while ( MoreSQLData() ) {
    my %a; # the attachment hash
868
    ($a{'id'}, $a{'description'}, $a{'isprivate'}) = FetchSQLData();
869 870 871 872 873

    # Add the hash representing the attachment to the array of attachments.
    push @attachments, \%a;
  }

874 875
  # Retrieve the bug summary (for displaying on screen) and assignee.
  SendSQL("SELECT short_desc, assigned_to FROM bugs 
876
           WHERE bug_id = $bugid");
877
  my ($bugsummary, $assignee_id) = FetchSQLData();
878 879

  # Define the variables and functions that will be passed to the UI template.
880
  $vars->{'bugid'} = $bugid;
881
  $vars->{'attachments'} = \@attachments;
882 883
  $vars->{'bugassignee_id'} = $assignee_id;
  $vars->{'bugsummary'} = $bugsummary;
884
  $vars->{'GetBugLink'} = \&GetBugLink;
885

886
  SendSQL("SELECT product_id, component_id FROM bugs
887
           WHERE bug_id = $bugid");
888 889 890 891 892 893 894 895
  my ($product_id, $component_id) = FetchSQLData();
  my $flag_types = Bugzilla::FlagType::match({'target_type'  => 'attachment',
                                              'product_id'   => $product_id,
                                              'component_id' => $component_id});
  $vars->{'flag_types'} = $flag_types;
  $vars->{'any_flags_requesteeble'} = grep($_->{'is_requesteeble'},
                                           @$flag_types);

896
  print $cgi->header();
897 898

  # Generate and return the UI (HTML page) from the appropriate template.
899 900
  $template->process("attachment/create.html.tmpl", $vars)
    || ThrowTemplateError($template->error());
901 902
}

903
# Insert a new attachment into the database.
904 905
sub insert
{
906 907
    my $dbh = Bugzilla->dbh;
    my $userid = Bugzilla->user->id;
908

909 910 911 912 913
    # Retrieve and validate parameters
    my $bugid = $cgi->param('bugid');
    ValidateBugID($bugid);
    validateCanChangeBug($bugid);
    ValidateComment(scalar $cgi->param('comment'));
914 915 916 917 918
    my $attachurl = $cgi->param('attachurl') || '';
    my $data;
    my $filename;
    my $contenttype;
    my $isurl;
919 920
    validateIsPatch();
    validateDescription();
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
  
    if (($attachurl =~ /^(http|https|ftp):\/\/\S+/) 
         && !(defined $cgi->upload('data'))) {
        $filename = '';
        $data = $attachurl;
        $isurl = 1;
        $contenttype = SqlQuote('text/plain');
        $cgi->param('ispatch', 0);
        $cgi->delete('bigfile');
    } else {
        $filename = validateFilename();
        # need to validate content type before data as
        # we now check the content type for image/bmp in validateData()
        validateContentType() unless $cgi->param('ispatch');
        $data = validateData();
        $contenttype = SqlQuote($cgi->param('contenttype'));
        $isurl = 0;
    }
939 940 941 942 943 944 945

    my @obsolete_ids = ();
    @obsolete_ids = validateObsolete() if $cgi->param('obsolete');

    # The order of these function calls is important, as both Flag::validate
    # and FlagType::validate assume User::match_field has ensured that the
    # values in the requestee fields are legitimate user email addresses.
946
    my $match_status = Bugzilla::User::match_field($cgi, {
947
        '^requestee(_type)?-(\d+)$' => { 'type' => 'multi' },
948 949 950 951 952 953 954 955 956 957
    }, MATCH_SKIP_CONFIRM);

    $vars->{'match_field'} = 'requestee';
    if ($match_status == USER_MATCH_FAILED) {
        $vars->{'message'} = 'user_match_failed';
    }
    elsif ($match_status == USER_MATCH_MULTIPLE) {
        $vars->{'message'} = 'user_match_multiple';
    }

958 959 960
    # FlagType::validate() and 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.
961
    Bugzilla::Flag::validate($cgi, $bugid, -1);
962
    Bugzilla::FlagType::validate($cgi, $bugid, -1);
963 964 965 966 967

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

969 970 971 972
  # Figure out when the changes were made.
  my ($timestamp) = Bugzilla->dbh->selectrow_array("SELECT NOW()"); 
  my $sql_timestamp = SqlQuote($timestamp); 

973
  # Insert the attachment into the database.
974
  my $sth = $dbh->prepare("INSERT INTO attachments
975
      (bug_id, creation_ts, filename, description,
976
       mimetype, ispatch, isurl, isprivate, submitter_id) 
977
      VALUES ($bugid, $sql_timestamp, $sql_filename,
978
              $description, $contenttype, " . $cgi->param('ispatch') . ",
979
              $isurl, $isprivate, $userid)");
980 981 982 983
  $sth->execute();
  # Retrieve the ID of the newly created attachment record.
  my $attachid = $dbh->bz_last_key('attachments', 'attach_id');

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


993 994
  # If the file is to be stored locally, stream the file from the webserver
  # to the local file without reading it into a local variable.
995
  if ($cgi->param('bigfile'))
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
  {
    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;
    my $limit = (Param("maxlocalattachment") * 1048576);
    while (<$fh>) {
        print AH $_;
        $sizecount += length($_);
        if ($sizecount > $limit) {
            close AH;
            close $fh;
            unlink "$attachdir/$hash/attachment.$attachid";
            ThrowUserError("local_file_too_large");
        }
    }
    close AH;
    close $fh;
  }


1021
  # Insert a comment about the new attachment into the database.
1022 1023 1024
  my $comment = "Created an attachment (id=$attachid)\n" .
                $cgi->param('description') . "\n";
  $comment .= ("\n" . $cgi->param('comment')) if defined $cgi->param('comment');
1025

1026
  AppendComment($bugid, $userid, $comment, $isprivate, $timestamp);
1027 1028

  # Make existing attachments obsolete.
1029
  my $fieldid = get_field_id('attachments.isobsolete');
1030
  foreach my $obsolete_id (@obsolete_ids) {
1031 1032
      # If the obsolete attachment has request flags, cancel them.
      # This call must be done before updating the 'attachments' table.
1033 1034 1035 1036 1037 1038 1039 1040
      Bugzilla::Flag::CancelRequests($bugid, $obsolete_id, $sql_timestamp);

      SendSQL("UPDATE attachments SET isobsolete = 1 " . 
              "WHERE attach_id = $obsolete_id");
      SendSQL("INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when,
                                          fieldid, removed, added) 
              VALUES ($bugid, $obsolete_id, $userid, $sql_timestamp, $fieldid,
                      '0', '1')");
1041 1042
  }

1043
  # Assign the bug to the user, if they are allowed to take it
1044
  my $owner = "";
1045
  
1046
  if ($cgi->param('takebug') && UserInGroup("editbugs")) {
1047 1048 1049 1050
      
      my @fields = ("assigned_to", "bug_status", "resolution", "login_name");
      
      # Get the old values, for the bugs_activity table
1051 1052 1053 1054
      SendSQL("SELECT " . join(", ", @fields) . " " .
              "FROM bugs " .
              "INNER JOIN profiles " .
              "ON profiles.userid = bugs.assigned_to " .
1055
              "WHERE bugs.bug_id = $bugid");
1056 1057
      
      my @oldvalues = FetchSQLData();
1058
      my @newvalues = ($userid, "ASSIGNED", "", Bugzilla->user->login);
1059 1060
      
      # Make sure the person we are taking the bug from gets mail.
1061
      $owner = $oldvalues[3];  
1062 1063 1064 1065 1066
                  
      @oldvalues = map(SqlQuote($_), @oldvalues);
      @newvalues = map(SqlQuote($_), @newvalues);
               
      # Update the bug record. Note that this doesn't involve login_name.
1067
      SendSQL("UPDATE bugs SET delta_ts = $sql_timestamp, " . 
1068
              join(", ", map("$fields[$_] = $newvalues[$_]", (0..2))) . 
1069
              " WHERE bug_id = $bugid");
1070 1071 1072 1073 1074 1075 1076 1077
      
      # We store email addresses in the bugs_activity table rather than IDs.
      $oldvalues[0] = $oldvalues[3];
      $newvalues[0] = $newvalues[3];
      
      # Add the changes to the bugs_activity table
      for (my $i = 0; $i < 3; $i++) {
          if ($oldvalues[$i] ne $newvalues[$i]) {
1078
              my $fieldid = get_field_id($fields[$i]);
1079 1080
              SendSQL("INSERT INTO bugs_activity " .
                      "(bug_id, who, bug_when, fieldid, removed, added) " .
1081 1082
                      "VALUES ($bugid, $userid, $sql_timestamp, " .
                      "$fieldid, $oldvalues[$i], $newvalues[$i])");
1083 1084 1085 1086
          }
      }      
  }   
  
1087
  # Create flags.
1088
  Bugzilla::Flag::process($bugid, $attachid, $timestamp, $cgi);
1089
   
1090
  # Define the variables and functions that will be passed to the UI template.
1091
  $vars->{'mailrecipients'} =  { 'changer' => Bugzilla->user->login,
1092
                                 'owner'   => $owner };
1093
  $vars->{'bugid'} = $bugid;
1094 1095
  $vars->{'attachid'} = $attachid;
  $vars->{'description'} = $description;
1096 1097
  $vars->{'contenttypemethod'} = $cgi->param('contenttypemethod');
  $vars->{'contenttype'} = $cgi->param('contenttype');
1098

1099
  print $cgi->header();
1100 1101

  # Generate and return the UI (HTML page) from the appropriate template.
1102 1103
  $template->process("attachment/created.html.tmpl", $vars)
    || ThrowTemplateError($template->error());
1104 1105
}

1106 1107 1108 1109
# Displays a form for editing attachment properties.
# Any user is allowed to access this page, unless the attachment
# is private and the user does not belong to the insider group.
# Validations are done later when the user submits changes.
1110 1111
sub edit
{
1112 1113
  # Retrieve and validate parameters
  my ($attach_id) = validateID();
1114 1115

  # Retrieve the attachment from the database.
1116 1117
  SendSQL("SELECT description, mimetype, filename, bug_id, ispatch, isurl,
                  isobsolete, isprivate, LENGTH(thedata)
1118 1119 1120 1121
           FROM attachments
           INNER JOIN attach_data
           ON id = attach_id
           WHERE attach_id = $attach_id");
1122
  my ($description, $contenttype, $filename, $bugid, $ispatch, $isurl, $isobsolete, $isprivate, $datasize) = FetchSQLData();
1123

1124 1125 1126 1127 1128 1129
  my $isviewable = !$isurl && isViewable($contenttype);
  my $thedata;
  if ($isurl) {
      SendSQL("SELECT thedata FROM attach_data WHERE id = $attach_id");
      ($thedata) = FetchSQLData();
  }
1130 1131 1132 1133 1134 1135 1136 1137

  # Retrieve a list of attachments for this bug as well as a summary of the bug
  # to use in a navigation bar across the top of the screen.
  SendSQL("SELECT attach_id FROM attachments WHERE bug_id = $bugid ORDER BY attach_id");
  my @bugattachments;
  push(@bugattachments, FetchSQLData()) while (MoreSQLData());
  SendSQL("SELECT short_desc FROM bugs WHERE bug_id = $bugid");
  my ($bugsummary) = FetchSQLData();
1138 1139 1140 1141
  
  # Get a list of flag types that can be set for this attachment.
  SendSQL("SELECT product_id, component_id FROM bugs WHERE bug_id = $bugid");
  my ($product_id, $component_id) = FetchSQLData();
1142 1143
  my $flag_types = Bugzilla::FlagType::match({ 'target_type'  => 'attachment' ,
                                               'product_id'   => $product_id ,
1144
                                               'component_id' => $component_id });
1145
  foreach my $flag_type (@$flag_types) {
1146
    $flag_type->{'flags'} = Bugzilla::Flag::match({ 'type_id'   => $flag_type->{'id'},
1147
                                                    'attach_id' => $attach_id,
1148
                                                    'is_active' => 1 });
1149 1150
  }
  $vars->{'flag_types'} = $flag_types;
1151
  $vars->{'any_flags_requesteeble'} = grep($_->{'is_requesteeble'}, @$flag_types);
1152
  
1153
  # Define the variables and functions that will be passed to the UI template.
1154
  $vars->{'attachid'} = $attach_id; 
1155
  $vars->{'description'} = $description; 
1156
  $vars->{'contenttype'} = $contenttype; 
1157
  $vars->{'filename'} = $filename;
1158 1159 1160
  $vars->{'bugid'} = $bugid; 
  $vars->{'bugsummary'} = $bugsummary; 
  $vars->{'ispatch'} = $ispatch; 
1161
  $vars->{'isurl'} = $isurl; 
1162
  $vars->{'isobsolete'} = $isobsolete; 
1163
  $vars->{'isprivate'} = $isprivate; 
1164
  $vars->{'datasize'} = $datasize;
1165
  $vars->{'thedata'} = $thedata;
1166 1167
  $vars->{'isviewable'} = $isviewable; 
  $vars->{'attachments'} = \@bugattachments; 
1168
  $vars->{'GetBugLink'} = \&GetBugLink;
1169

1170 1171 1172 1173 1174
  # Determine if PatchReader is installed
  eval {
    require PatchReader;
    $vars->{'patchviewerinstalled'} = 1;
  };
1175
  print $cgi->header();
1176 1177

  # Generate and return the UI (HTML page) from the appropriate template.
1178 1179
  $template->process("attachment/edit.html.tmpl", $vars)
    || ThrowTemplateError($template->error());
1180 1181
}

1182 1183 1184 1185 1186
# Updates an attachment record. Users with "editbugs" privileges, (or the
# original attachment's submitter) can edit the attachment's description,
# content type, ispatch and isobsolete flags, and statuses, and they can
# also submit a comment that appears in the bug.
# Users cannot edit the content of the attachment itself.
1187 1188
sub update
{
1189
  my $dbh = Bugzilla->dbh;
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
  my $userid = Bugzilla->user->id;

    # Retrieve and validate parameters
    ValidateComment(scalar $cgi->param('comment'));
    my ($attach_id, $bugid) = validateID();
    validateCanEdit($attach_id);
    validateCanChangeAttachment($attach_id);
    validateDescription();
    validateIsPatch();
    validateContentType() unless $cgi->param('ispatch');
    validateIsObsolete();
    validatePrivate();

    # The order of these function calls is important, as both Flag::validate
    # and FlagType::validate assume User::match_field has ensured that the
    # values in the requestee fields are legitimate user email addresses.
    Bugzilla::User::match_field($cgi, {
1207
        '^requestee(_type)?-(\d+)$' => { 'type' => 'multi' }
1208
    });
1209
    Bugzilla::Flag::validate($cgi, $bugid, $attach_id);
1210
    Bugzilla::FlagType::validate($cgi, $bugid, $attach_id);
1211

1212
  # Lock database tables in preparation for updating the attachment.
1213 1214 1215
  $dbh->bz_lock_tables('attachments WRITE', 'flags WRITE' ,
          'flagtypes READ', 'fielddefs READ', 'bugs_activity WRITE',
          'flaginclusions AS i READ', 'flagexclusions AS e READ',
1216 1217
          # cc, bug_group_map, user_group_map, and groups are in here so we
          # can check the permissions of flag requestees and email addresses
1218
          # on the flag type cc: lists via the CanSeeBug
1219 1220 1221 1222
          # function call in Flag::notify. group_group_map is in here si
          # Bugzilla::User can flatten groups.
          'bugs WRITE', 'profiles READ', 'email_setting READ',
          'cc READ', 'bug_group_map READ', 'user_group_map READ',
1223 1224
          'group_group_map READ', 'groups READ');

1225 1226
  # Get a copy of the attachment record before we make changes
  # so we can record those changes in the activity table.
1227
  SendSQL("SELECT description, mimetype, filename, ispatch, isobsolete, isprivate
1228
           FROM attachments WHERE attach_id = $attach_id");
1229 1230
  my ($olddescription, $oldcontenttype, $oldfilename, $oldispatch,
      $oldisobsolete, $oldisprivate) = FetchSQLData();
1231

1232
  # Quote the description and content type for use in the SQL UPDATE statement.
1233 1234 1235
  my $quoteddescription = SqlQuote($cgi->param('description'));
  my $quotedcontenttype = SqlQuote($cgi->param('contenttype'));
  my $quotedfilename = SqlQuote($cgi->param('filename'));
1236

1237 1238 1239 1240
  # Figure out when the changes were made.
  SendSQL("SELECT NOW()");
  my $timestamp = FetchOneColumn();
    
1241 1242 1243 1244
  # Update flags.  We have to do this before committing changes
  # to attachments so that we can delete pending requests if the user
  # is obsoleting this attachment without deleting any requests
  # the user submits at the same time.
1245
  Bugzilla::Flag::process($bugid, $attach_id, $timestamp, $cgi);
1246

1247 1248
  # Update the attachment record in the database.
  SendSQL("UPDATE  attachments 
1249 1250
           SET     description = $quoteddescription ,
                   mimetype = $quotedcontenttype ,
1251
                   filename = $quotedfilename ,
1252 1253 1254 1255
                   ispatch = " . $cgi->param('ispatch') . ",
                   isobsolete = " . $cgi->param('isobsolete') . ",
                   isprivate = " . $cgi->param('isprivate') . "
           WHERE   attach_id = $attach_id
1256 1257 1258
         ");

  # Record changes in the activity table.
1259
  my $sql_timestamp = SqlQuote($timestamp);
1260
  if ($olddescription ne $cgi->param('description')) {
1261
    my $quotedolddescription = SqlQuote($olddescription);
1262
    my $fieldid = get_field_id('attachments.description');
1263 1264 1265 1266
    SendSQL("INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when,
                                        fieldid, removed, added)
             VALUES ($bugid, $attach_id, $userid, $sql_timestamp, $fieldid,
                     $quotedolddescription, $quoteddescription)");
1267
  }
1268
  if ($oldcontenttype ne $cgi->param('contenttype')) {
1269
    my $quotedoldcontenttype = SqlQuote($oldcontenttype);
1270
    my $fieldid = get_field_id('attachments.mimetype');
1271 1272 1273 1274
    SendSQL("INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when,
                                        fieldid, removed, added)
             VALUES ($bugid, $attach_id, $userid, $sql_timestamp, $fieldid,
                     $quotedoldcontenttype, $quotedcontenttype)");
1275
  }
1276
  if ($oldfilename ne $cgi->param('filename')) {
1277
    my $quotedoldfilename = SqlQuote($oldfilename);
1278
    my $fieldid = get_field_id('attachments.filename');
1279 1280 1281 1282
    SendSQL("INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when,
                                        fieldid, removed, added)
             VALUES ($bugid, $attach_id, $userid, $sql_timestamp, $fieldid,
                     $quotedoldfilename, $quotedfilename)");
1283
  }
1284
  if ($oldispatch ne $cgi->param('ispatch')) {
1285
    my $fieldid = get_field_id('attachments.ispatch');
1286 1287 1288 1289
    SendSQL("INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when,
                                        fieldid, removed, added)
             VALUES ($bugid, $attach_id, $userid, $sql_timestamp, $fieldid,
                     $oldispatch, " . $cgi->param('ispatch') . ")");
1290
  }
1291
  if ($oldisobsolete ne $cgi->param('isobsolete')) {
1292
    my $fieldid = get_field_id('attachments.isobsolete');
1293 1294 1295 1296
    SendSQL("INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when,
                                        fieldid, removed, added)
             VALUES ($bugid, $attach_id, $userid, $sql_timestamp, $fieldid,
                     $oldisobsolete, " . $cgi->param('isobsolete') . ")");
1297
  }
1298
  if ($oldisprivate ne $cgi->param('isprivate')) {
1299
    my $fieldid = get_field_id('attachments.isprivate');
1300 1301 1302 1303
    SendSQL("INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when,
                                        fieldid, removed, added)
             VALUES ($bugid, $attach_id, $userid, $sql_timestamp, $fieldid,
                     $oldisprivate, " . $cgi->param('isprivate') . ")");
1304
  }
1305
  
1306
  # Unlock all database tables now that we are finished updating the database.
1307
  $dbh->bz_unlock_tables();
1308

1309
  # If the user submitted a comment while editing the attachment,
1310
  # add the comment to the bug.
1311
  if ($cgi->param('comment'))
1312
  {
1313 1314 1315 1316
    # Prepend a string to the comment to let users know that the comment came
    # from the "edit attachment" screen.
    my $comment = qq|(From update of attachment $attach_id)\n| .
                  $cgi->param('comment');
1317 1318

    # Append the comment to the list of comments in the database.
1319
    AppendComment($bugid, $userid, $comment, $cgi->param('isprivate'), $timestamp);
1320
  }
1321
  
1322
  # Define the variables and functions that will be passed to the UI template.
1323
  $vars->{'mailrecipients'} = { 'changer' => Bugzilla->user->login };
1324
  $vars->{'attachid'} = $attach_id; 
1325 1326
  $vars->{'bugid'} = $bugid; 

1327
  print $cgi->header();
1328 1329

  # Generate and return the UI (HTML page) from the appropriate template.
1330 1331
  $template->process("attachment/updated.html.tmpl", $vars)
    || ThrowTemplateError($template->error());
1332
}