post_bug.cgi 20.4 KB
Newer Older
1
#!/usr/bin/perl -wT
2
# -*- Mode: perl; indent-tabs-mode: nil -*-
terry%netscape.com's avatar
terry%netscape.com committed
3
#
4 5 6 7 8 9 10 11 12 13
# 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.
#
terry%netscape.com's avatar
terry%netscape.com committed
14
# The Original Code is the Bugzilla Bug Tracking System.
15
#
terry%netscape.com's avatar
terry%netscape.com committed
16
# The Initial Developer of the Original Code is Netscape Communications
17 18 19 20
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
terry%netscape.com's avatar
terry%netscape.com committed
21
# Contributor(s): Terry Weissman <terry@mozilla.org>
22
#                 Dan Mosedale <dmose@mozilla.org>
23
#                 Joe Robins <jmrobins@tgix.com>
24
#                 Gervase Markham <gerv@gerv.net>
25
#                 Marc Schumann <wurblzap@gmail.com>
terry%netscape.com's avatar
terry%netscape.com committed
26

27
use strict;
28 29
use lib qw(.);

30
require "globals.pl";
31
use Bugzilla;
32
use Bugzilla::Attachment;
33
use Bugzilla::Constants;
34
use Bugzilla::Util;
35
use Bugzilla::Bug;
36
use Bugzilla::User;
37
use Bugzilla::Field;
38
use Bugzilla::Product;
39
use Bugzilla::Keyword;
40
use Bugzilla::Token;
41

42
my $user = Bugzilla->login(LOGIN_REQUIRED);
43

44
my $cgi = Bugzilla->cgi;
45
my $dbh = Bugzilla->dbh;
46 47
my $template = Bugzilla->template;
my $vars = {};
48

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
######################################################################
# Subroutines
######################################################################

# Determines whether or not a group is active by checking
# the "isactive" column for the group in the "groups" table.
# Note: This function selects groups by id rather than by name.
sub GroupIsActive {
    my ($group_id) = @_;
    $group_id ||= 0;
    detaint_natural($group_id);
    my ($is_active) = Bugzilla->dbh->selectrow_array(
        "SELECT isactive FROM groups WHERE id = ?", undef, $group_id);
    return $is_active;
}

######################################################################
# Main Script
######################################################################

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
# Detect if the user already used the same form to submit a bug
my $token = trim($cgi->param('token'));
if ($token) {
    my ($creator_id, $date, $old_bug_id) = Bugzilla::Token::GetTokenData($token);
    unless ($creator_id
              && ($creator_id == $user->id)
              && ($old_bug_id =~ "^createbug:"))
    {
        # The token is invalid.
        ThrowUserError('token_inexistent');
    }

    $old_bug_id =~ s/^createbug://;

    if ($old_bug_id && (!$cgi->param('ignore_token')
                        || ($cgi->param('ignore_token') != $old_bug_id)))
    {
        $vars->{'bugid'} = $old_bug_id;
        $vars->{'allow_override'} = defined $cgi->param('ignore_token') ? 0 : 1;

        print $cgi->header();
        $template->process("bug/create/confirm-create-dupe.html.tmpl", $vars)
           || ThrowTemplateError($template->error());
        exit;
    }
}    

96 97
# do a match on the fields if applicable

98
&Bugzilla::User::match_field ($cgi, {
99 100
    'cc'            => { 'type' => 'multi'  },
    'assigned_to'   => { 'type' => 'single' },
101
    'qa_contact'    => { 'type' => 'single' },
102
});
103 104 105 106 107

# The format of the initial comment can be structured by adding fields to the
# enter_bug template and then referencing them in the comment template.
my $comment;

108 109
my $format = $template->get_format("bug/create/comment",
                                   scalar($cgi->param('format')), "txt");
110

111
$template->process($format->{'template'}, $vars, \$comment)
112 113 114
  || ThrowTemplateError($template->error());

ValidateComment($comment);
115

116
# Check that the product exists and that the user
117
# is allowed to enter bugs into this product.
118
$user->can_enter_product(scalar $cgi->param('product'), 1);
119

120
my $product = Bugzilla::Product::check_product(scalar $cgi->param('product'));
dmose%mozilla.org's avatar
dmose%mozilla.org committed
121

122
# Set cookies
123 124
if (defined $cgi->param('product')) {
    if (defined $cgi->param('version')) {
125
        $cgi->send_cookie(-name => "VERSION-" . $product->name,
126 127
                          -value => $cgi->param('version'),
                          -expires => "Fri, 01-Jan-2038 00:00:00 GMT");
128 129
    }
}
terry%netscape.com's avatar
terry%netscape.com committed
130

131
if (defined $cgi->param('maketemplate')) {
132
    $vars->{'url'} = $cgi->query_string();
133
    $vars->{'short_desc'} = $cgi->param('short_desc');
terry%netscape.com's avatar
terry%netscape.com committed
134
    
135
    print $cgi->header();
136 137
    $template->process("bug/create/make-template.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
138
    exit;
terry%netscape.com's avatar
terry%netscape.com committed
139 140
}

141
umask 0;
terry%netscape.com's avatar
terry%netscape.com committed
142

143
# Some sanity checking
144 145
$cgi->param('component') || ThrowUserError("require_component");
my $component = Bugzilla::Component::check_component($product, scalar $cgi->param('component'));
terry%netscape.com's avatar
terry%netscape.com committed
146

147 148 149
# Set the parameter to itself, but cleaned up
$cgi->param('short_desc', clean_text($cgi->param('short_desc')));

150
if (!defined $cgi->param('short_desc')
151
    || $cgi->param('short_desc') eq "") {
152
    ThrowUserError("require_summary");
153 154
}

155 156 157
# Check that if required a description has been provided
# This has to go somewhere after 'maketemplate' 
#  or it breaks bookmarks with no comments.
158
if (Param("commentoncreate") && !trim($cgi->param('comment'))) {
159 160 161
    ThrowUserError("description_required");
}

162 163 164
# If bug_file_loc is "http://", the default, use an empty value instead.
$cgi->param('bug_file_loc', '') if $cgi->param('bug_file_loc') eq 'http://';

165 166

# Default assignee is the component owner.
167
if (!UserInGroup("editbugs") || $cgi->param('assigned_to') eq "") {
168 169 170
    my $initialowner = $dbh->selectrow_array(q{SELECT initialowner
                                                 FROM components
                                                WHERE id = ?},
171
                                               undef, $component->id);
172
    $cgi->param(-name => 'assigned_to', -value => $initialowner);
173
} else {
174
    $cgi->param(-name => 'assigned_to',
175
                -value => login_to_id(trim($cgi->param('assigned_to')), THROW_ERROR));
terry%netscape.com's avatar
terry%netscape.com committed
176 177
}

178
my @bug_fields = ("version", "rep_platform",
179
                  "bug_severity", "priority", "op_sys", "assigned_to",
180
                  "bug_status", "everconfirmed", "bug_file_loc", "short_desc",
181
                  "target_milestone", "status_whiteboard");
182

183 184 185 186 187 188 189 190 191
if (Param("usebugaliases")) {
   my $alias = trim($cgi->param('alias') || "");
   if ($alias ne "") {
       ValidateBugAlias($alias);
       $cgi->param('alias', $alias);
       push (@bug_fields,"alias");
   }
}

192
# Retrieve the default QA contact if the field is empty
193
if (Param("useqacontact")) {
194
    my $qa_contact;
195 196
    if (!UserInGroup("editbugs") || !defined $cgi->param('qa_contact')
        || trim($cgi->param('qa_contact')) eq "") {
197 198 199
        ($qa_contact) = $dbh->selectrow_array(q{SELECT initialqacontact 
                                                  FROM components 
                                                 WHERE id = ?},
200
                                                undef, $component->id);
201
    } else {
202
        $qa_contact = login_to_id(trim($cgi->param('qa_contact')), THROW_ERROR);
203 204
    }

205
    if ($qa_contact) {
206
        $cgi->param(-name => 'qa_contact', -value => $qa_contact);
207 208 209 210
        push(@bug_fields, "qa_contact");
    }
}

211
if (UserInGroup("editbugs") || UserInGroup("canconfirm")) {
212
    # Default to NEW if the user hasn't selected another status
213
    if (!defined $cgi->param('bug_status')) {
214 215
        $cgi->param(-name => 'bug_status', -value => "NEW");
    }
216 217
} else {
    # Default to UNCONFIRMED if we are using it, NEW otherwise
218
    $cgi->param(-name => 'bug_status', -value => 'UNCONFIRMED');
219 220 221
    my $votestoconfirm = $dbh->selectrow_array(q{SELECT votestoconfirm 
                                                   FROM products 
                                                  WHERE id = ?},
222
                                                 undef, $product->id);
223 224

    if (!$votestoconfirm) {
225
        $cgi->param(-name => 'bug_status', -value => "NEW");
226 227 228
    }
}

229
if (!defined $cgi->param('target_milestone')) {
230 231 232
    my $defaultmilestone = $dbh->selectrow_array(q{SELECT defaultmilestone
                                                     FROM products
                                                    WHERE name = ?},
233
                                                    undef, $product->name);
234
    $cgi->param(-name => 'target_milestone', -value => $defaultmilestone);
235 236
}

237
if (!Param('letsubmitterchoosepriority')) {
238
    $cgi->param(-name => 'priority', -value => Param('defaultpriority'));
239 240
}

241
# Some more sanity checking
242 243 244 245 246
check_field('rep_platform', scalar $cgi->param('rep_platform'));
check_field('bug_severity', scalar $cgi->param('bug_severity'));
check_field('priority',     scalar $cgi->param('priority'));
check_field('op_sys',       scalar $cgi->param('op_sys'));
check_field('bug_status',   scalar $cgi->param('bug_status'), ['UNCONFIRMED', 'NEW']);
247
check_field('version',      scalar $cgi->param('version'),
248
            [map($_->name, @{$product->versions})]);
249
check_field('target_milestone', scalar $cgi->param('target_milestone'),
250
            [map($_->name, @{$product->milestones})]);
251 252 253 254 255

foreach my $field_name ('assigned_to', 'bug_file_loc', 'comment') {
    defined($cgi->param($field_name))
      || ThrowCodeError('undefined_field', { field => $field_name });
}
256

257 258 259
my $everconfirmed = ($cgi->param('bug_status') eq 'UNCONFIRMED') ? 0 : 1;
$cgi->param(-name => 'everconfirmed', -value => $everconfirmed);

260
my @used_fields;
261
foreach my $field (@bug_fields) {
262
    if (defined $cgi->param($field)) {
263
        push (@used_fields, $field);
264 265
    }
}
266

267
$cgi->param(-name => 'product_id', -value => $product->id);
268
push(@used_fields, "product_id");
269
$cgi->param(-name => 'component_id', -value => $component->id);
270 271
push(@used_fields, "component_id");

272 273 274 275
my %ccids;

# Create the ccid hash for inserting into the db
# use a hash rather than a list to avoid adding users twice
276 277
if (defined $cgi->param('cc')) {
    foreach my $person ($cgi->param('cc')) {
278
        next unless $person;
279
        my $ccid = login_to_id($person, THROW_ERROR);
280 281
        if ($ccid && !$ccids{$ccid}) {
           $ccids{$ccid} = 1;
282 283 284
        }
    }
}
285 286 287 288 289
# Check for valid keywords and create list of keywords to be added to db
# (validity routine copied from process_bug.cgi)
my @keywordlist;
my %keywordseen;

290 291
if ($cgi->param('keywords') && UserInGroup("editbugs")) {
    foreach my $keyword (split(/[\s,]+/, $cgi->param('keywords'))) {
292 293 294
        if ($keyword eq '') {
           next;
        }
295 296
        my $keyword_obj = new Bugzilla::Keyword({name => $keyword});
        if (!$keyword_obj) {
297 298
            ThrowUserError("unknown_keyword",
                           { keyword => $keyword });
299
        }
300 301 302
        if (!$keywordseen{$keyword_obj->id}) {
            push(@keywordlist, $keyword_obj->id);
            $keywordseen{$keyword_obj->id} = 1;
303 304 305
        }
    }
}
306

307 308 309 310 311 312 313 314 315
if (Param("strict_isolation")) {
    my @blocked_users = ();
    my %related_users = %ccids;
    $related_users{$cgi->param('assigned_to')} = 1;
    if (Param('useqacontact') && $cgi->param('qa_contact')) {
        $related_users{$cgi->param('qa_contact')} = 1;
    }
    foreach my $pid (keys %related_users) {
        my $related_user = Bugzilla::User->new($pid);
316
        if (!$related_user->can_edit_product($product->id)) {
317 318 319 320 321 322 323
            push (@blocked_users, $related_user->login);
        }
    }
    if (scalar(@blocked_users)) {
        ThrowUserError("invalid_user_group", 
            {'users' => \@blocked_users,
             'new' => 1,
324
             'product' => $product->name
325 326 327 328
            });
    }
}

329 330
# Check for valid dependency info. 
foreach my $field ("dependson", "blocked") {
331
    if (UserInGroup("editbugs") && $cgi->param($field)) {
332
        my @validvalues;
333
        foreach my $id (split(/[\s,]+/, $cgi->param($field))) {
334
            next unless $id;
335
            # $field is not passed to ValidateBugID to prevent adding new 
336
            # dependencies on inaccessible bugs.
337
            ValidateBugID($id);
338 339
            push(@validvalues, $id);
        }
340
        $cgi->param(-name => $field, -value => join(",", @validvalues));
341 342
    }
}
343
# Gather the dependency list, and make sure there are no circular refs
344
my %deps;
345
if (UserInGroup("editbugs")) {
346 347
    %deps = Bugzilla::Bug::ValidateDependencies(scalar($cgi->param('dependson')),
                                                scalar($cgi->param('blocked')));
348 349
}

350
# get current time
351
my $timestamp = $dbh->selectrow_array(q{SELECT NOW()});
352

353
# Build up SQL string to add bug.
354
# creation_ts will only be set when all other fields are defined.
355 356

my @fields_values;
terry%netscape.com's avatar
terry%netscape.com committed
357

358
foreach my $field (@used_fields) {
359 360 361
    my $value = $cgi->param($field);
    trick_taint($value);
    push (@fields_values, $value);
terry%netscape.com's avatar
terry%netscape.com committed
362 363
}

364 365 366 367 368 369 370
my $sql_used_fields = join(", ", @used_fields);
my $sql_placeholders = "?, " x scalar(@used_fields);

my $query = qq{INSERT INTO bugs ($sql_used_fields, reporter, delta_ts,
                                 estimated_time, remaining_time, deadline)
               VALUES ($sql_placeholders ?, ?, ?, ?, ?)};

371
$comment =~ s/\r\n?/\n/g;     # Get rid of \r.
372
$comment = trim($comment);
373
# If comment is all whitespace, it'll be null at this point. That's
374 375
# OK except for the fact that it causes e-mail to be suppressed.
$comment = $comment ? $comment : " ";
376

377 378 379 380 381
push (@fields_values, $user->id);
push (@fields_values, $timestamp);

my $est_time = 0;
my $deadline;
382 383 384

# Time Tracking
if (UserInGroup(Param("timetrackinggroup")) &&
385
    defined $cgi->param('estimated_time')) {
386

387
    $est_time = $cgi->param('estimated_time');
388
    Bugzilla::Bug::ValidateTime($est_time, 'estimated_time');
389 390
    trick_taint($est_time);

391
}
392

393 394
push (@fields_values, $est_time, $est_time);

395
if ((UserInGroup(Param("timetrackinggroup"))) && ($cgi->param('deadline'))) {
396 397 398
    validate_date($cgi->param('deadline'))
      || ThrowUserError('illegal_date', {date => $cgi->param('deadline'),
                                         format => 'YYYY-MM-DD'});
399 400
    $deadline = $cgi->param('deadline');
    trick_taint($deadline);
401 402
}

403
push (@fields_values, $deadline);
404

405
# Groups
406
my @groupstoadd = ();
407 408 409 410 411
my $sth_othercontrol = $dbh->prepare(q{SELECT othercontrol
                                         FROM group_control_map
                                        WHERE group_id = ?
                                          AND product_id = ?});

412 413
foreach my $b (grep(/^bit-\d*$/, $cgi->param())) {
    if ($cgi->param($b)) {
414
        my $v = substr($b, 4);
415
        detaint_natural($v)
416
          || ThrowUserError("invalid_group_ID");
417 418 419 420 421
        if (!GroupIsActive($v)) {
            # Prevent the user from adding the bug to an inactive group.
            # Should only happen if there is a bug in Bugzilla or the user
            # hacked the "enter bug" form since otherwise the UI 
            # for adding the bug to the group won't appear on that form.
422
            $vars->{'bit'} = $v;
423
            ThrowCodeError("inactive_group");
424
        }
425
        my ($permit) = $user->in_group_id($v);
426
        if (!$permit) {
427
            my $othercontrol = $dbh->selectrow_array($sth_othercontrol, 
428
                                                     undef, ($v, $product->id));
429 430 431 432
            $permit = (($othercontrol == CONTROLMAPSHOWN)
                       || ($othercontrol == CONTROLMAPDEFAULT));
        }
        if ($permit) {
433 434
            push(@groupstoadd, $v)
        }
435 436 437
    }
}

438 439 440 441 442 443 444 445 446
my $groups = $dbh->selectall_arrayref(q{
                 SELECT DISTINCT groups.id, groups.name, membercontrol,
                                 othercontrol, description
                            FROM groups
                       LEFT JOIN group_control_map 
                              ON group_id = id
                             AND product_id = ?
                           WHERE isbuggroup != 0
                             AND isactive != 0
447
                        ORDER BY description}, undef, $product->id);
448 449 450

foreach my $group (@$groups) {
    my ($id, $groupname, $membercontrol, $othercontrol) = @$group;
451 452 453 454 455 456 457 458 459 460
    $membercontrol ||= 0;
    $othercontrol ||= 0;
    # Add groups required
    if (($membercontrol == CONTROLMAPMANDATORY)
       || (($othercontrol == CONTROLMAPMANDATORY) 
            && (!UserInGroup($groupname)))) {
        # User had no option, bug needs to be in this group.
        push(@groupstoadd, $id)
    }
}
461

462
# Add the bug report to the DB.
463 464
$dbh->bz_lock_tables('bugs WRITE', 'bug_group_map WRITE', 'longdescs WRITE',
                     'cc WRITE', 'keywords WRITE', 'dependencies WRITE',
465 466
                     'bugs_activity WRITE', 'groups READ',
                     'user_group_map READ', 'group_group_map READ',
467 468
                     'keyworddefs READ', 'fielddefs READ');

469
$dbh->do($query, undef, @fields_values);
470

471
# Get the bug ID back.
472
my $id = $dbh->bz_last_key('bugs', 'bug_id');
terry%netscape.com's avatar
terry%netscape.com committed
473

474
# Add the group restrictions
475 476
my $sth_addgroup = $dbh->prepare(q{
            INSERT INTO bug_group_map (bug_id, group_id) VALUES (?, ?)});
477
foreach my $grouptoadd (@groupstoadd) {
478
    $sth_addgroup->execute($id, $grouptoadd);
479 480
}

481 482 483
# Add the initial comment, allowing for the fact that it may be private
my $privacy = 0;
if (Param("insidergroup") && UserInGroup(Param("insidergroup"))) {
484
    $privacy = $cgi->param('commentprivacy') ? 1 : 0;
485 486
}

487 488 489 490
trick_taint($comment);
$dbh->do(q{INSERT INTO longdescs (bug_id, who, bug_when, thetext,isprivate)
           VALUES (?, ?, ?, ?, ?)}, undef, ($id, $user->id, $timestamp,
                                            $comment, $privacy));
terry%netscape.com's avatar
terry%netscape.com committed
491

492
# Insert the cclist into the database
493
my $sth_cclist = $dbh->prepare(q{INSERT INTO cc (bug_id, who) VALUES (?,?)});
494
foreach my $ccid (keys(%ccids)) {
495
    $sth_cclist->execute($id, $ccid);
terry%netscape.com's avatar
terry%netscape.com committed
496 497
}

498
my @all_deps;
499 500
my $sth_addkeyword = $dbh->prepare(q{
            INSERT INTO keywords (bug_id, keywordid) VALUES (?, ?)});
501 502
if (UserInGroup("editbugs")) {
    foreach my $keyword (@keywordlist) {
503
        $sth_addkeyword->execute($id, $keyword);
504
    }
505 506
    if (@keywordlist) {
        # Make sure that we have the correct case for the kw
507
        my $kw_ids = join(', ', @keywordlist);
508
        my $list = $dbh->selectcol_arrayref(qq{
509 510 511 512 513 514 515
                                    SELECT name 
                                      FROM keyworddefs 
                                     WHERE id IN ($kw_ids)});
        my $kw_list = join(', ', @$list);
        $dbh->do(q{UPDATE bugs 
                      SET delta_ts = ?, keywords = ? 
                    WHERE bug_id = ?}, undef, ($timestamp, $kw_list, $id));
516
    }
517 518 519
    if ($cgi->param('dependson') || $cgi->param('blocked')) {
        foreach my $pair (["blocked", "dependson"], ["dependson", "blocked"]) {
            my ($me, $target) = @{$pair};
520 521
            my $sth_dep = $dbh->prepare(qq{
                        INSERT INTO dependencies ($me, $target) VALUES (?, ?)});
522
            foreach my $i (@{$deps{$target}}) {
523
                $sth_dep->execute($id, $i);
524 525
                push(@all_deps, $i); # list for mailing dependent bugs
                # Log the activity for the other bug:
526
                LogActivityEntry($i, $me, "", $id, $user->id, $timestamp);
527 528 529
            }
        }
    }
530 531
}

532 533 534 535 536 537 538
# All fields related to the newly created bug are set.
# The bug can now be made accessible.
$dbh->do("UPDATE bugs SET creation_ts = ? WHERE bug_id = ?",
          undef, ($timestamp, $id));

$dbh->bz_unlock_tables();

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
# Add an attachment if requested.
if (defined($cgi->upload('data')) || $cgi->param('attachurl')) {
    $cgi->param('isprivate', $cgi->param('commentprivacy'));
    Bugzilla::Attachment->insert_attachment_for_bug(!THROW_ERROR,
                                                    $id, $user, $timestamp,
                                                    \$vars)
        || ($vars->{'message'} = 'attachment_creation_failed');

    # Determine if Patch Viewer is installed, for Diff link
    eval {
        require PatchReader;
        $vars->{'patchviewerinstalled'} = 1;
    };
}

554
# Email everyone the details of the new bug 
555
$vars->{'mailrecipients'} = {'changer' => $user->login};
556

557
$vars->{'id'} = $id;
558
my $bug = new Bugzilla::Bug($id, $user->id);
559
$vars->{'bug'} = $bug;
terry%netscape.com's avatar
terry%netscape.com committed
560

561
ThrowCodeError("bug_error", { bug => $bug }) if $bug->error;
562 563 564 565 566 567

$vars->{'sentmail'} = [];

push (@{$vars->{'sentmail'}}, { type => 'created',
                                id => $id,
                              });
568

569
foreach my $i (@all_deps) {
570
    push (@{$vars->{'sentmail'}}, { type => 'dep', id => $i, });
571
}
572

573
my @bug_list;
574 575
if ($cgi->cookie("BUGLIST")) {
    @bug_list = split(/:/, $cgi->cookie("BUGLIST"));
576
}
577
$vars->{'bug_list'} = \@bug_list;
578
$vars->{'use_keywords'} = 1 if Bugzilla::Keyword::keyword_count();
579

580 581 582 583 584 585
if ($token) {
    trick_taint($token);
    $dbh->do('UPDATE tokens SET eventdata = ? WHERE token = ?', undef, 
             ("createbug:$id", $token));
}

586
print $cgi->header();
587 588
$template->process("bug/create/created.html.tmpl", $vars)
  || ThrowTemplateError($template->error());
589

590