attachment.cgi 24.7 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
#                 Frédéric Buclin <LpSolit@gmail.com>
29
#                 Marc Schumann <wurblzap@gmail.com>
30 31 32 33 34 35 36 37

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

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

38
use lib qw(. lib);
39

40
use Bugzilla;
41
use Bugzilla::Constants;
42
use Bugzilla::Error;
43 44
use Bugzilla::Flag; 
use Bugzilla::FlagType; 
45
use Bugzilla::User;
46
use Bugzilla::Util;
47
use Bugzilla::Bug;
48
use Bugzilla::Field;
49
use Bugzilla::Attachment;
50
use Bugzilla::Attachment::PatchReader;
51
use Bugzilla::Token;
52

53
Bugzilla->login();
54

55 56 57 58 59 60 61
# For most scripts we don't make $cgi and $template global variables. But
# when preparing Bugzilla for mod_perl, this script used these
# variables in so many subroutines that it was easier to just
# make them globals.
local our $cgi = Bugzilla->cgi;
local our $template = Bugzilla->template;
local our $vars = {};
62

63 64 65 66
################################################################################
# Main Body Execution
################################################################################

67 68 69 70
# 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'.
71 72

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

75 76 77 78 79 80
# Determine if PatchReader is installed
eval {
    require PatchReader;
    $vars->{'patchviewerinstalled'} = 1;
};

81
if ($action eq "view")  
82
{
83
    view();
84
}
85 86
elsif ($action eq "interdiff")
{
87
    interdiff();
88 89 90
}
elsif ($action eq "diff")
{
91
    diff();
92
}
93 94
elsif ($action eq "viewall") 
{ 
95
    viewall(); 
96
}
97 98
elsif ($action eq "enter") 
{ 
99 100
    Bugzilla->login(LOGIN_REQUIRED);
    enter(); 
101 102 103
}
elsif ($action eq "insert")
{
104 105
    Bugzilla->login(LOGIN_REQUIRED);
    insert();
106
}
107 108
elsif ($action eq "edit") 
{ 
109
    edit(); 
110 111 112
}
elsif ($action eq "update") 
{ 
113 114
    Bugzilla->login(LOGIN_REQUIRED);
    update();
115
}
116 117 118
elsif ($action eq "delete") {
    delete_attachment();
}
119 120
else 
{ 
121
  ThrowCodeError("unknown_action", { action => $action });
122 123 124 125 126 127 128 129
}

exit;

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

130 131 132 133 134 135 136 137
# 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.
#
138 139 140
# Returns an attachment object.

sub validateID {
141
    my $param = @_ ? $_[0] : 'id';
142 143
    my $user = Bugzilla->user;

144 145 146
    # 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
147
    if ($param eq 'id' && !$cgi->param('id')) {
148
        print $cgi->header();
149 150 151 152
        $template->process("attachment/choose.html.tmpl", $vars) ||
            ThrowTemplateError($template->error());
        exit;
    }
153
    
154 155 156 157 158 159 160
    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) });
161
  
162
    # Make sure the attachment exists in the database.
163 164
    my $attachment = Bugzilla::Attachment->get($attach_id)
      || ThrowUserError("invalid_attach_id", { attach_id => $attach_id });
165

166
    # Make sure the user is authorized to access this attachment's bug.
167 168
    ValidateBugID($attachment->bug_id);
    if ($attachment->isprivate && $user->id != $attachment->attacher->id && !$user->is_insider) {
169 170
        ThrowUserError('auth_failure', {action => 'access',
                                        object => 'attachment'});
171
    }
172
    return $attachment;
173 174
}

175 176 177
# 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.
178 179
sub validateFormat
{
180 181 182
  # receives a list of legal formats; first item is a default
  my $format = $cgi->param('format') || $_[0];
  if ( lsearch(\@_, $format) == -1)
183
  {
184
     ThrowUserError("invalid_format", { format  => $format, formats => \@_ });
185
  }
186

187
  return $format;
188 189
}

190 191
# Validates context of a diff/interdiff. Will throw an error if the context
# is not number, "file" or "patch". Returns the validated, detainted context.
192 193
sub validateContext
{
194 195 196 197
  my $context = $cgi->param('context') || "patch";
  if ($context ne "file" && $context ne "patch") {
    detaint_natural($context)
      || ThrowUserError("invalid_context", { context => $cgi->param('context') });
198
  }
199 200

  return $context;
201 202
}

203 204 205
sub validateCanChangeBug
{
    my ($bugid) = @_;
206 207 208
    my $dbh = Bugzilla->dbh;
    my ($productid) = $dbh->selectrow_array(
            "SELECT product_id
209
             FROM bugs 
210 211
             WHERE bug_id = ?", undef, $bugid);

212
    Bugzilla->user->can_edit_product($productid)
213 214
      || ThrowUserError("illegal_attachment_edit_bug",
                        { bug_id => $bugid });
215 216
}

217 218 219 220
################################################################################
# Functions
################################################################################

221
# Display an attachment.
222
sub view {
223
    # Retrieve and validate parameters
224 225 226 227
    my $attachment = validateID();
    my $contenttype = $attachment->contenttype;
    my $filename = $attachment->filename;

228 229 230
    # Bug 111522: allow overriding content-type manually in the posted form
    # params.
    if (defined $cgi->param('content_type'))
231
    {
232 233
        $cgi->param('contenttypemethod', 'manual');
        $cgi->param('contenttypeentry', $cgi->param('content_type'));
234
        Bugzilla::Attachment->validate_content_type(THROW_ERROR);
235
        $contenttype = $cgi->param('content_type');
236
    }
237

238
    # Return the appropriate HTTP response headers.
239
    $attachment->datasize || ThrowUserError("attachment_removed");
240

241
    $filename =~ s/^.*[\/\\]//;
242 243 244 245
    # escape quotes and backslashes in the filename, per RFCs 2045/822
    $filename =~ s/\\/\\\\/g; # escape backslashes
    $filename =~ s/"/\\"/g; # escape quotes

246 247
    print $cgi->header(-type=>"$contenttype; name=\"$filename\"",
                       -content_disposition=> "inline; filename=\"$filename\"",
248 249
                       -content_length => $attachment->datasize);
    print $attachment->data;
250 251
}

252 253
sub interdiff {
    # Retrieve and validate parameters
254 255
    my $old_attachment = validateID('oldid');
    my $new_attachment = validateID('newid');
256 257 258 259 260
    my $format = validateFormat('html', 'raw');
    my $context = validateContext();

    Bugzilla::Attachment::PatchReader::process_interdiff(
        $old_attachment, $new_attachment, $format, $context);
261 262
}

263 264
sub diff {
    # Retrieve and validate parameters
265
    my $attachment = validateID();
266 267
    my $format = validateFormat('html', 'raw');
    my $context = validateContext();
268

269 270 271 272
    # If it is not a patch, view normally.
    if (!$attachment->ispatch) {
        view();
        return;
273 274
    }

275
    Bugzilla::Attachment::PatchReader::process_diff($attachment, $format, $context);
276
}
277

278 279
# Display all attachments for a given bug in a series of IFRAMEs within one
# HTML page.
280
sub viewall {
281 282 283
    # Retrieve and validate parameters
    my $bugid = $cgi->param('bugid');
    ValidateBugID($bugid);
284
    my $bug = new Bugzilla::Bug($bugid);
285

286
    my $attachments = Bugzilla::Attachment->get_attachments_by_bug($bugid);
287

288 289 290
    # Define the variables and functions that will be passed to the UI template.
    $vars->{'bug'} = $bug;
    $vars->{'attachments'} = $attachments;
291

292
    print $cgi->header();
293

294 295 296
    # Generate and return the UI (HTML page) from the appropriate template.
    $template->process("attachment/show-multiple.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
297 298
}

299
# Display a form for entering a new attachment.
300
sub enter {
301 302 303 304
  # Retrieve and validate parameters
  my $bugid = $cgi->param('bugid');
  ValidateBugID($bugid);
  validateCanChangeBug($bugid);
305
  my $dbh = Bugzilla->dbh;
306 307 308
  my $user = Bugzilla->user;

  my $bug = new Bugzilla::Bug($bugid, $user->id);
309 310 311
  # 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 = "";
312 313
  if (!$user->in_group('editbugs', $bug->product_id)) {
      $canEdit = "AND submitter_id = " . $user->id;
314
  }
315 316 317
  my $attach_ids = $dbh->selectcol_arrayref("SELECT attach_id FROM attachments
                                             WHERE bug_id = ? AND isobsolete = 0 $canEdit
                                             ORDER BY attach_id", undef, $bugid);
318 319

  # Define the variables and functions that will be passed to the UI template.
320
  $vars->{'bug'} = $bug;
321
  $vars->{'attachments'} = Bugzilla::Attachment->get_list($attach_ids);
322

323
  my $flag_types = Bugzilla::FlagType::match({'target_type'  => 'attachment',
324 325
                                              'product_id'   => $bug->product_id,
                                              'component_id' => $bug->component_id});
326
  $vars->{'flag_types'} = $flag_types;
327
  $vars->{'any_flags_requesteeble'} = grep($_->is_requesteeble, @$flag_types);
328

329
  print $cgi->header();
330 331

  # Generate and return the UI (HTML page) from the appropriate template.
332 333
  $template->process("attachment/create.html.tmpl", $vars)
    || ThrowTemplateError($template->error());
334 335
}

336
# Insert a new attachment into the database.
337
sub insert {
338 339
    my $dbh = Bugzilla->dbh;
    my $user = Bugzilla->user;
340

341 342 343 344 345
    # Retrieve and validate parameters
    my $bugid = $cgi->param('bugid');
    ValidateBugID($bugid);
    validateCanChangeBug($bugid);
    ValidateComment(scalar $cgi->param('comment'));
346
    my ($timestamp) = Bugzilla->dbh->selectrow_array("SELECT NOW()"); 
347

348
    my $bug = new Bugzilla::Bug($bugid);
349
    my $attachment =
350
        Bugzilla::Attachment->insert_attachment_for_bug(THROW_ERROR, $bug, $user,
351
                                                        $timestamp, $vars);
352

353
  # Insert a comment about the new attachment into the database.
354 355
  my $comment = "Created an attachment (id=" . $attachment->id . ")\n" .
                $attachment->description . "\n";
356
  $comment .= ("\n" . $cgi->param('comment')) if defined $cgi->param('comment');
357

358
  AppendComment($bugid, $user->id, $comment, $attachment->isprivate, $timestamp);
359

360
  # Assign the bug to the user, if they are allowed to take it
361
  my $owner = "";
362
  if ($cgi->param('takebug') && $user->in_group('editbugs', $bug->product_id)) {
363 364 365 366 367 368 369 370 371 372 373
      # When taking a bug, we have to follow the workflow.
      my $bug_status = $cgi->param('bug_status') || '';
      ($bug_status) = grep {$_->name eq $bug_status} @{$bug->status->can_change_to};

      if ($bug_status && $bug_status->is_open
          && ($bug_status->name ne 'UNCONFIRMED' || $bug->product_obj->votes_to_confirm))
      {
          $bug->set_status($bug_status->name);
          $bug->clear_resolution();
          $bug->update($timestamp);
      }
374
      # Make sure the person we are taking the bug from gets mail.
375 376 377 378 379 380 381 382 383
      $owner = $bug->assigned_to->login;

      # Ideally, the code below should be replaced by $bug->set_assignee().
      $dbh->do('UPDATE bugs SET assigned_to = ?, delta_ts = ? WHERE bug_id = ?',
               undef, ($user->id, $timestamp, $bugid));

      LogActivityEntry($bugid, 'assigned_to', $owner, $user->login, $user->id, $timestamp);

  }
384

385
  # Define the variables and functions that will be passed to the UI template.
386
  $vars->{'mailrecipients'} =  { 'changer' => $user->login,
387
                                 'owner'   => $owner };
388
  $vars->{'attachment'} = $attachment;
389 390 391 392
  # We cannot reuse the $bug object as delta_ts has eventually been updated
  # since the object was created.
  $vars->{'bugs'} = [new Bugzilla::Bug($bugid)];
  $vars->{'header_done'} = 1;
393
  $vars->{'contenttypemethod'} = $cgi->param('contenttypemethod');
394

395
  print $cgi->header();
396
  # Generate and return the UI (HTML page) from the appropriate template.
397 398
  $template->process("attachment/created.html.tmpl", $vars)
    || ThrowTemplateError($template->error());
399 400
}

401 402 403 404
# 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.
405
sub edit {
406
  my $attachment = validateID();
407
  my $dbh = Bugzilla->dbh;
408 409 410

  # 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.
411
  my $bugattachments =
412 413 414
      Bugzilla::Attachment->get_attachments_by_bug($attachment->bug_id);
  # We only want attachment IDs.
  @$bugattachments = map { $_->id } @$bugattachments;
415 416 417 418 419 420

  my ($bugsummary, $product_id, $component_id) =
      $dbh->selectrow_array('SELECT short_desc, product_id, component_id
                               FROM bugs
                              WHERE bug_id = ?', undef, $attachment->bug_id);

421
  # Get a list of flag types that can be set for this attachment.
422 423
  my $flag_types = Bugzilla::FlagType::match({ 'target_type'  => 'attachment' ,
                                               'product_id'   => $product_id ,
424
                                               'component_id' => $component_id });
425
  foreach my $flag_type (@$flag_types) {
426
    $flag_type->{'flags'} = Bugzilla::Flag::match({ 'type_id'   => $flag_type->id,
427
                                                    'attach_id' => $attachment->id });
428 429
  }
  $vars->{'flag_types'} = $flag_types;
430
  $vars->{'any_flags_requesteeble'} = grep($_->is_requesteeble, @$flag_types);
431
  $vars->{'attachment'} = $attachment;
432
  $vars->{'bugsummary'} = $bugsummary; 
433
  $vars->{'attachments'} = $bugattachments;
434

435
  print $cgi->header();
436 437

  # Generate and return the UI (HTML page) from the appropriate template.
438 439
  $template->process("attachment/edit.html.tmpl", $vars)
    || ThrowTemplateError($template->error());
440 441
}

442 443 444 445 446
# 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.
447
sub update {
448 449
    my $user = Bugzilla->user;
    my $dbh = Bugzilla->dbh;
450 451 452

    # Retrieve and validate parameters
    ValidateComment(scalar $cgi->param('comment'));
453 454
    my $attachment = validateID();
    my $bug = new Bugzilla::Bug($attachment->bug_id);
455
    $attachment->validate_can_edit($bug->product_id);
456
    validateCanChangeBug($bug->id);
457 458 459
    Bugzilla::Attachment->validate_description(THROW_ERROR);
    Bugzilla::Attachment->validate_is_patch(THROW_ERROR);
    Bugzilla::Attachment->validate_content_type(THROW_ERROR) unless $cgi->param('ispatch');
460 461
    $cgi->param('isobsolete', $cgi->param('isobsolete') ? 1 : 0);
    $cgi->param('isprivate', $cgi->param('isprivate') ? 1 : 0);
462 463 464 465 466 467 468 469 470

    # If the submitter of the attachment is not in the insidergroup,
    # be sure that he cannot overwrite the private bit.
    # This check must be done before calling Bugzilla::Flag*::validate(),
    # because they will look at the private bit when checking permissions.
    # XXX - This is a ugly hack. Ideally, we shouldn't have to look at the
    # old private bit twice (first here, and then below again), but this is
    # the less risky change.
    unless ($user->is_insider) {
471
        $cgi->param('isprivate', $attachment->isprivate);
472
    }
473

474 475 476
    # The order of these function calls is important, as Flag::validate
    # assumes User::match_field has ensured that the values in the
    # requestee fields are legitimate user email addresses.
477
    Bugzilla::User::match_field($cgi, {
478
        '^requestee(_type)?-(\d+)$' => { 'type' => 'multi' }
479
    });
480
    Bugzilla::Flag::validate($cgi, $bug->id, $attachment->id);
481

482 483
    # Start a transaction in preparation for updating the attachment.
    $dbh->bz_start_transaction();
484

485
  # Quote the description and content type for use in the SQL UPDATE statement.
486 487 488 489 490 491 492
  my $description = $cgi->param('description');
  my $contenttype = $cgi->param('contenttype');
  my $filename = $cgi->param('filename');
  # we can detaint this way thanks to placeholders
  trick_taint($description);
  trick_taint($contenttype);
  trick_taint($filename);
493

494
  # Figure out when the changes were made.
495
  my ($timestamp) = $dbh->selectrow_array("SELECT NOW()");
496
    
497 498 499 500
  # 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.
501
  Bugzilla::Flag::process($bug, $attachment, $timestamp, $cgi, $vars);
502

503
  # Update the attachment record in the database.
504 505 506 507 508 509 510 511 512 513
  $dbh->do("UPDATE  attachments 
            SET     description = ?,
                    mimetype    = ?,
                    filename    = ?,
                    ispatch     = ?,
                    isobsolete  = ?,
                    isprivate   = ?
            WHERE   attach_id   = ?",
            undef, ($description, $contenttype, $filename,
            $cgi->param('ispatch'), $cgi->param('isobsolete'), 
514
            $cgi->param('isprivate'), $attachment->id));
515

516
  my $updated_attachment = Bugzilla::Attachment->get($attachment->id);
517
  # Record changes in the activity table.
518 519 520 521 522
  my $sth = $dbh->prepare('INSERT INTO bugs_activity (bug_id, attach_id, who, bug_when,
                                                      fieldid, removed, added)
                           VALUES (?, ?, ?, ?, ?, ?, ?)');

  if ($attachment->description ne $updated_attachment->description) {
523
    my $fieldid = get_field_id('attachments.description');
524 525
    $sth->execute($bug->id, $attachment->id, $user->id, $timestamp, $fieldid,
                  $attachment->description, $updated_attachment->description);
526
  }
527
  if ($attachment->contenttype ne $updated_attachment->contenttype) {
528
    my $fieldid = get_field_id('attachments.mimetype');
529 530
    $sth->execute($bug->id, $attachment->id, $user->id, $timestamp, $fieldid,
                  $attachment->contenttype, $updated_attachment->contenttype);
531
  }
532
  if ($attachment->filename ne $updated_attachment->filename) {
533
    my $fieldid = get_field_id('attachments.filename');
534 535
    $sth->execute($bug->id, $attachment->id, $user->id, $timestamp, $fieldid,
                  $attachment->filename, $updated_attachment->filename);
536
  }
537
  if ($attachment->ispatch != $updated_attachment->ispatch) {
538
    my $fieldid = get_field_id('attachments.ispatch');
539 540
    $sth->execute($bug->id, $attachment->id, $user->id, $timestamp, $fieldid,
                  $attachment->ispatch, $updated_attachment->ispatch);
541
  }
542
  if ($attachment->isobsolete != $updated_attachment->isobsolete) {
543
    my $fieldid = get_field_id('attachments.isobsolete');
544 545
    $sth->execute($bug->id, $attachment->id, $user->id, $timestamp, $fieldid,
                  $attachment->isobsolete, $updated_attachment->isobsolete);
546
  }
547
  if ($attachment->isprivate != $updated_attachment->isprivate) {
548
    my $fieldid = get_field_id('attachments.isprivate');
549 550
    $sth->execute($bug->id, $attachment->id, $user->id, $timestamp, $fieldid,
                  $attachment->isprivate, $updated_attachment->isprivate);
551
  }
552
  
553 554
  # Commit the transaction now that we are finished updating the database.
  $dbh->bz_commit_transaction();
555

556
  # If the user submitted a comment while editing the attachment,
557
  # add the comment to the bug.
558
  if ($cgi->param('comment'))
559
  {
560 561
    # Prepend a string to the comment to let users know that the comment came
    # from the "edit attachment" screen.
562
    my $comment = "(From update of attachment " . $attachment->id . ")\n" .
563
                  $cgi->param('comment');
564 565

    # Append the comment to the list of comments in the database.
566
    AppendComment($bug->id, $user->id, $comment, $updated_attachment->isprivate, $timestamp);
567
  }
568
  
569
  # Define the variables and functions that will be passed to the UI template.
570
  $vars->{'mailrecipients'} = { 'changer' => Bugzilla->user->login };
571
  $vars->{'attachment'} = $attachment;
572 573 574 575
  # We cannot reuse the $bug object as delta_ts has eventually been updated
  # since the object was created.
  $vars->{'bugs'} = [new Bugzilla::Bug($bug->id)];
  $vars->{'header_done'} = 1;
576

577
  print $cgi->header();
578 579

  # Generate and return the UI (HTML page) from the appropriate template.
580 581
  $template->process("attachment/updated.html.tmpl", $vars)
    || ThrowTemplateError($template->error());
582
}
583 584 585 586 587 588 589 590 591 592 593 594 595

# Only administrators can delete attachments.
sub delete_attachment {
    my $user = Bugzilla->login(LOGIN_REQUIRED);
    my $dbh = Bugzilla->dbh;

    print $cgi->header();

    $user->in_group('admin')
      || ThrowUserError('auth_failure', {group  => 'admin',
                                         action => 'delete',
                                         object => 'attachment'});

596
    Bugzilla->params->{'allow_attachment_deletion'}
597 598 599
      || ThrowUserError('attachment_deletion_disabled');

    # Make sure the administrator is allowed to edit this attachment.
600 601
    my $attachment = validateID();
    validateCanChangeBug($attachment->bug_id);
602 603 604 605 606 607 608 609 610

    $attachment->datasize || ThrowUserError('attachment_removed');

    # We don't want to let a malicious URL accidentally delete an attachment.
    my $token = trim($cgi->param('token'));
    if ($token) {
        my ($creator_id, $date, $event) = Bugzilla::Token::GetTokenData($token);
        unless ($creator_id
                  && ($creator_id == $user->id)
611
                  && ($event eq 'attachment' . $attachment->id))
612 613
        {
            # The token is invalid.
614
            ThrowUserError('token_does_not_exist');
615 616 617 618
        }

        # The token is valid. Delete the content of the attachment.
        my $msg;
619
        $vars->{'attachment'} = $attachment;
620 621 622 623 624 625 626
        $vars->{'date'} = $date;
        $vars->{'reason'} = clean_text($cgi->param('reason') || '');
        $vars->{'mailrecipients'} = { 'changer' => $user->login };

        $template->process("attachment/delete_reason.txt.tmpl", $vars, \$msg)
          || ThrowTemplateError($template->error());

627
        $dbh->bz_start_transaction();
628
        $dbh->do('DELETE FROM attach_data WHERE id = ?', undef, $attachment->id);
629 630 631
        $dbh->do('UPDATE attachments SET mimetype = ?, ispatch = ?, isurl = ?,
                         isobsolete = ?
                  WHERE attach_id = ?', undef,
632 633
                 ('text/plain', 0, 0, 1, $attachment->id));
        $dbh->do('DELETE FROM flags WHERE attach_id = ?', undef, $attachment->id);
634
        $dbh->bz_commit_transaction();
635 636 637 638 639 640 641

        # If the attachment is stored locally, remove it.
        if (-e $attachment->_get_local_filename) {
            unlink $attachment->_get_local_filename;
        }

        # Now delete the token.
642
        delete_token($token);
643 644

        # Paste the reason provided by the admin into a comment.
645
        AppendComment($attachment->bug_id, $user->id, $msg);
646

647 648 649 650
        # Required to display the bug the deleted attachment belongs to.
        $vars->{'bugs'} = [new Bugzilla::Bug($attachment->bug_id)];
        $vars->{'header_done'} = 1;

651 652 653 654 655
        $template->process("attachment/updated.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
    }
    else {
        # Create a token.
656
        $token = issue_session_token('attachment' . $attachment->id);
657 658 659 660 661 662 663 664

        $vars->{'a'} = $attachment;
        $vars->{'token'} = $token;

        $template->process("attachment/confirm-delete.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
    }
}