bug_email.pl 37.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#!/usr/bin/perl -w
# -*- 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>
#                 Gregor Fischer <fischer@suse.de>
#                 Klaas Freitag  <freitag@suse.de>
#                 Seth Landsman  <seth@dworkin.net>
24
#                 Ludovic Dubost <ludovic@pobox.com>
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
###############################################################
# Bugzilla: Create a new bug via email
###############################################################
# The email needs to be feeded to this program on STDIN. 
# This is usually done by having an entry like this in your 
# .procmailrc:
# 
#     BUGZILLA_HOME=/usr/local/httpd/htdocs/bugzilla
#     :0 c
#     |(cd $BUGZILLA_HOME/contrib; ./bug_email.pl)
# 
#
# Installation note:
#
# You need to work with bug_email.pl the MIME::Parser installed.
# 
41
# $Id: bug_email.pl,v 1.35 2006/05/29 17:24:54 lpsolit%gmail.com Exp $
42 43 44 45 46 47 48
###############################################################

# 02/12/2000 (SML)
# - updates to work with most recent database changes to the bugs database
# - updated so that it works out of bugzilla/contrib
# - initial checkin into the mozilla CVS tree (yay)

49 50 51 52 53 54 55 56
# 02/13/2000 (SML)
# - email transformation code.  
#   EMAIL_TRANSFORM_NONE does exact email matches
#   EMAIL_TRANSFORM_NAME_ONLY matches on the username 
#   EMAIL_TRANSFORM_BASE_DOMAIN matches on the username and checks the domain of
#    to see that the one in the database is a subset of the one in the sender address
#    this is probably prone to false positives and probably needs more work.

57 58 59 60 61
# 03/07/2000 (SML)
# - added in $DEFAULT_PRODUCT and $DEFAULT_COMPONENT.  i.e., if $DEFAULT_PRODUCT = "PENDING",
#    any email submitted bug will be entered with a product of PENDING, if no other product is
#    specified in the email.

62 63 64 65 66 67 68 69 70 71
# 10/21/2003 (Ludovic)
# - added $DEFAULT_VERSION, similar to product and component above
# - added command line switches to override version, product, and component, so separate
#   email addresses can be used for different product/component/version combinations.
#   Example for procmail:
#    # Feed mail to stdin of bug_email.pl
#    :0 Ec
#    * !^Subject: .*[Bug .*]
#    RESULT=|(cd $BUGZILLA_HOME/contrib && ./bug_email.pl -p='Tier_3_Operations' -c='General' )

72 73 74 75 76 77
# Next round of revisions :
# - querying a bug over email
# - appending a bug over email
# - keywords over email
# - use the globals.pl parameters functionality to edit and save this script's parameters
# - integrate some setup in the checksetup.pl script
78
# - gpg signatures for security
79 80 81 82

use strict;
use MIME::Parser;

83 84 85 86 87
BEGIN {
    chdir '..';        # this script lives in contrib
    push @INC, "contrib/.";
    push @INC, ".";
}
88 89

require "globals.pl";
90
use Bugzilla;
91 92
use BugzillaEmail;
use Bugzilla::Config qw(:DEFAULT $datadir);
93

94 95 96 97
use lib ".";
use lib "../";
use Bugzilla::Constants;
use Bugzilla::BugMail;
98
use Bugzilla::User;
99 100
use Bugzilla::Product;
use Bugzilla::Component;
101

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
my @mailerrors = ();       # Buffer for Errors in the mail
my @mailwarnings = ();     # Buffer for Warnings found in the mail
my $critical_err = 0; # Counter for critical errors - must be zero for success
my %Control;
my $Header = "";
my @RequiredLabels = ();
my @AllowedLabels = ();
my $Body = "";
my @attachments = ();

my $product_valid = 0;
my $test = 0;
my $restricted = 0;
my $SenderShort;
my $Message_ID;

118 119
my $dbh = Bugzilla->dbh;

120
# change to use default product / component functionality
seth%cs.brandeis.edu's avatar
seth%cs.brandeis.edu committed
121 122
my $DEFAULT_PRODUCT = "PENDING";
my $DEFAULT_COMPONENT = "PENDING";
123
my $DEFAULT_VERSION = "unspecified";
124

125 126 127 128 129 130 131 132 133 134 135 136 137 138
###############################################################
# storeAttachments
# 
# in this sub, attachments found in the dump-sub will be written to 
# the database. The info, which attachments need saving is stored
# in the global @attachments-list.
# The sub returns the number of stored attachments.
sub storeAttachments( $$ )
{
    my ($bugid, $submitter_id ) = @_;
    my $maxsize = 0;
    my $data;
    my $listref  = \@attachments;
    my $att_count = 0;
139
    my $dbh = Bugzilla->dbh;
140 141 142
    
    $submitter_id ||= 0;

143 144 145 146 147 148 149 150
    my $timestamp = $dbh->selectrow_array("SELECT NOW()");
    my $sth_attach = $dbh->prepare(q{
            INSERT INTO attachments (bug_id, creation_ts, description, 
                                     mimetype, ispatch, filename, submitter_id) 
            VALUES (?, ?, ?, ?, 0, ?, ?) });

    my $sth_data = $dbh->prepare(q{INSERT INTO attach_data (id, thedata)
                                   VALUES (LAST_INSERT_ID(), ?)});
151
    foreach my $pairref ( @$listref ) {
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
        my ($decoded_file, $mime, $on_disk, $description) = @$pairref;


        # Size check - mysql has a maximum space for the data ?
        $maxsize = 1047552;  # should be queried by a system( "mysqld --help" );,
        # but this seems not to be supported by all current mysql-versions

        # Read data file binary
        if( $on_disk ) {
            if( open( FILE, "$decoded_file" )) {
                binmode FILE;
                read FILE, $data, $maxsize;
                close FILE;
                $att_count ++;
            } else { 
                print "Error while reading attachment $decoded_file!\n";
                next;
            }
            # print "unlinking $datadir/mimedump-tmp/$decoded_file";
            # unlink "$datadir/mimedump-tmp/$decoded_file";
        } else {
            # data is in the scalar 
            $data = $decoded_file;
        }
176
        my @values = ($bugid, $timestamp, $description, $mime, $decoded_file, $submitter_id);
177

178 179 180 181
        unless ($test) {
            $sth_attach->execute(@values);
            $sth_data->execute($data);
        }
182
    }
183

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    return( $att_count );
}



###############################################################
# Beautification
sub horLine( )
{
    return( "-----------------------------------------------------------------------\n" ); 
}


###############################################################
# Check if $Name is in $GroupName

sub CheckPermissions {
    my ($GroupName, $Name) = @_;
    
203
    return findUser($Name);
204 205 206 207 208 209 210
}

###############################################################
# Check if component is valid for product.
sub CheckVersion {
    my $Product = shift;
    my $Version = shift;
211
    my $dbh = Bugzilla->dbh;
212
    
213 214 215 216 217 218 219
    my $version_value = $dbh->selectrow_array(q{SELECT value 
                                                  FROM versions 
                                            INNER JOIN products 
                                                    ON versions.product_id = products.id 
                                                 WHERE products.name= ? 
                                                   AND value= ?}, undef, $Product, $Version);
    return $version_value || "";
220 221 222 223 224 225 226 227 228 229 230
}

###############################################################
# Reply to a mail.
sub Reply( $$$$ ) {
    my ($Sender, $MessageID, $Subject, $Text) = @_;
    
    
    die "Cannot find sender-email-address" unless defined( $Sender );
    
    if( $test ) {
231
        open( MAIL, '>>', "$datadir/bug_email_test.log" );
232 233
    }
    else {
234
        open( MAIL, "| /usr/sbin/sendmail -t" );
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    }

    print MAIL "To: $Sender\n";
    print MAIL "From: Bugzilla Mailinterface<yourmail\@here.com>\n";
    print MAIL "Subject: $Subject\n";
    print MAIL "In-Reply-To: $MessageID\n" if ( defined( $MessageID ));
    print MAIL "\n";
    print MAIL "$Text";
    close( MAIL );

}


###############################################################
# getEnumList
# Queries the Database for the table description and figures the
# enum-settings out - usefull for checking fields for enums like
# prios 
sub getEnumList( $ )
{
255
    my $dbh = Bugzilla->dbh;
256
    my ($fieldname) = @_;
257
    my $result = $dbh->selectcol_arrayref(qq{SELECT value FROM $fieldname});
258

259
    return($result);
260 261 262 263 264 265 266 267 268
}

###############################################################
# CheckPriority
# Checks, if the priority setting is one of the enums defined
# in the data base
# Uses the global var. $Control{ 'priority' }
sub CheckPriority
{
269
    my $prio = $Control{'priority'};
270
    my $all_prios = getEnumList( "priority" );
271

272
    if( $prio eq "" || (lsearch( $all_prios, $prio ) == -1)  ) {
273 274
        # OK, Prio was not defined - create Answer
        my $Text = "You sent wrong priority-setting, valid values are:" .
275
            join( "\n\t", @$all_prios ) . "\n\n";
276
        $Text .= "*  The priority is set to the default value ". 
277
            Param('defaultpriority') . "\n";
278

279
        BugMailError( 0, $Text );
280

281 282
        # set default value from param-file
        $Control{'priority'} = Param( 'defaultpriority' );
283
    } else {
284
        # Nothing to do
285 286 287 288 289 290 291 292 293
    }
}

###############################################################
# CheckSeverity
# checks the bug_severity
sub CheckSeverity
{
    my $sever = ($Control{'bug_severity'} ||= "" );
294
    my $all_sever = getEnumList( "bug_severity" );
295

296
    if( (lsearch($all_sever, $sever) == -1) || $sever eq "" ) {
297 298
        # OK, Prio was not defined - create Answer
        my $Text = "You sent wrong bug_severity-setting, valid values are:" .
299
            join( "\n\t", @$all_sever ) . "\n\n";
300
        $Text .= "*  The bug_severity is set to the default value 'normal' \n";
301

302
        BugMailError( 0, $Text );
303

304 305
        # set default value from param-file
        $Control{'bug_severity'} = "normal";
306 307 308 309 310 311 312 313 314
    } 
}

###############################################################
# CheckArea
# checks the area-field
sub CheckArea
{
    my $area = ($Control{'area'} ||= "" );
315
    my $all = getEnumList( "area" );
316

317
    if( (lsearch($all, $area) == -1) || $area eq "" ) {
318 319
        # OK, Area was not defined - create Answer
        my $Text = "You sent wrong area-setting, valid values are:" .
320
            join( "\n\t", @$all ) . "\n\n";
321
        $Text .= "*  The area is set to the default value 'BUILD' \n";
322

323
        BugMailError( 0, $Text );
324

325 326
        # set default value from param-file
        $Control{'area'} = "BUILD";
327 328 329 330 331 332 333 334 335
    } 
}

###############################################################
# CheckPlatform
# checks the given Platform and corrects it
sub CheckPlatform
{
    my $platform = ($Control{'rep_platform'} ||= "" );
336
    my $all = getEnumList( "rep_platform" );
337

338
    if( (lsearch($all, $platform) == -1) ||  $platform eq "" ) {
339 340
        # OK, Prio was not defined - create Answer
        my $Text = "You sent wrong platform-setting, valid values are:" .
341
            join( "\n\t", @$all ) . "\n\n";
342
        $Text .= "*  The rep_platform is set to the default value 'All' \n";
343

344
        BugMailError( 0, $Text );
345

346 347
        # set default value from param-file
        $Control{'rep_platform'} = "All";
348 349 350 351 352 353 354 355 356
    } 
}

###############################################################
# CheckSystem
# checks the given Op-Sys and corrects it
sub CheckSystem
{
    my $sys = ($Control{'op_sys'} ||= "" );
357
    my $all = getEnumList( "op_sys" );
358

359
    if(  (lsearch( $all, $sys ) == -1) || $sys eq "" ) {
360 361
        # OK, Prio was not defined - create Answer
        my $Text = "You sent wrong OS-setting, valid values are:" .
362
            join( "\n\t", @$all ) . "\n\n";
363
        $Text .= "*  The op_sys is set to the default value 'Linux' \n";
364

365
        BugMailError( 0, $Text );
366

367 368
        # set default value from param-file
        $Control{'op_sys'} = "Linux";
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    } 
}

###############################################################
# Error Handler for Errors in the mail
# 
# This function can be called multiple within processing one mail and
# stores the errors found in the Mail. Errors are for example empty
# required tags, missing required tags and so on.
# 
# The benefit is, that the mail users get a reply, where all mail errors
# are reported. The reply mail includes all messages what was wrong and
# the second mail the user sends can be ok, cause all his faults where
# reported.
# 
# BugMailError takes two arguments: The first one is a flag, how heavy
# the error is:
# 
387
# 0 - It's an error, but Bugzilla can process the bug. The user should
388 389
#     handle that as a warning.
# 
390
# 1 - It's a real bug. Bugzilla can't store the bug. The mail has to be
391 392 393 394 395
#     resent.
# 
# 2 - Permission error: The user does not have the permission to send
#     a bug.
# 
396
# The second argument is a Text which describes the bug.
397 398 399 400 401 402 403
# 
# 
# #
sub BugMailError($ $ )
{
    my ( $errflag, $text ) = @_;

404
    # On permission error, don't sent all other Errors back -> just quit !
405
    if( $errflag == 2 ) {            # Permission-Error
406 407 408
        Reply( $SenderShort, $Message_ID, "Bugzilla Error", "Permission denied.\n\n" .
               "You do not have the permissions to create a new bug. Sorry.\n" );
        exit;
409 410 411 412 413
    }


    # Warnings - store for the reply mail
    if( $errflag == 0 ) {
414
        push( @mailwarnings, $text );
415 416 417 418
    }

    # Critical Error
    if( $errflag == 1 ) {
419 420
        $critical_err += 1;
        push( @mailerrors, $text );
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    }
}

###############################################################
# getWarningText()
# 
# getWarningText() returns a reply-ready Textline of all the
# Warnings in the Mail
sub getWarningText()
{
    my $anz = @mailwarnings;

    my $ret = <<END
  
The Bugzilla Mail Interface found warnings (JFYI):

END
    ;

    # Handshake if no warnings at all
    return( "\n\n Your mail was processed without Warnings !\n" ) if( $anz == 0 );

    # build a text
    $ret .= join( "\n     ", @mailwarnings );
    return( horLine() . $ret );
}

sub getErrorText()
{
    my $anz = @mailerrors;

    my $ret = <<END

**************************  ERROR  **************************
 
Your request to the Bugzilla mail interface could not be met
due to errors in the mail. We will find it !


END
    ;
    return( "\n\n Your mail was processed without errors !\n") if( $anz == 0 );
    # build a text
    $ret .= join( "\n     ", @mailerrors );
    return( $ret );
}

###############################################################
# generateTemplate
# 
# This functiuon generates a mail-Template with the 
sub generateTemplate()
{
    my $w;
    my $ret;

    # Required Labels
    $ret =<<EOF


You may want to use this template to resend your mail. Please fill in the missing
keys.

_____ snip _______________________________________________________________________

EOF
    ;
    foreach ( @RequiredLabels ) {
489 490 491
        $w = "";
        $w = $Control{$_} if defined( $Control{ $_ } );
        $ret .= sprintf( "    \@%-15s:  %s\n", $_, $w );
492 493 494 495 496
    }

    $ret .= "\n";
    # Allowed Labels
    foreach( @AllowedLabels ) {
497 498 499 500 501
        next if( /reporter/    );  # Reporter is not a valid label
        next if( /assigned_to/ );  # Assigned to is just a number 
        if( defined( $Control{ $_ } ) && lsearch( \@RequiredLabels, $_ ) == -1 ) {
            $ret .=  sprintf( "    \@%-15s:  %s\n", $_,  $Control{ $_ } );
        }
502 503 504 505
    }

    if( $Body eq "" ) {
    $ret .= <<END
506
        
507 508 509 510 511 512
   < the bug-description follows here >

_____ snip _______________________________________________________________________

END
    ; } else {
513
        $ret .= "\n" . $Body;
514
    }
515
        
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
    return( $ret );

}
#------------------------------
#
# dump_entity ENTITY, NAME
#
# Recursive routine for parsing a mime coded mail.
# One mail may contain more than one mime blocks, which need to be
# handled. Therefore, this function is called recursively.
#
# It gets the for bugzilla important information from the mailbody and 
# stores them into the global attachment-list @attachments. The attachment-list
# is needed in storeAttachments.
#
sub dump_entity {
    my ($entity, $name) = @_;
    defined($name) or $name = "'anonymous'";
    my $IO;


    # Output the body:
    my @parts = $entity->parts;
    if (@parts) {                     # multipart...
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
        my $i;
        foreach $i (0 .. $#parts) {       # dump each part...
            dump_entity($parts[$i], ("$name, part ".(1+$i)));
        }
    } else {                            # single part...        

        # Get MIME type, and display accordingly...
        my $msg_part = $entity->head->get( 'Content-Disposition' );
        
        $msg_part ||= ""; 

        my ($type, $subtype) = split('/', $entity->head->mime_type);
        my $body = $entity->bodyhandle;
        my ($data, $on_disk );

        if(  $msg_part =~ /^attachment/ ) {
            # Attached File
            my $des = $entity->head->get('Content-Description');
            $des ||= $entity->head->recommended_filename;
            $des ||= "unnamed attachment";

            if( defined( $body->path )) { # Data is on disk
                $on_disk = 1;
                $data = $body->path;
                
            } else {                      # Data is in core
                $on_disk = 0;
                $data = $body->as_string;
            }
            push ( @attachments, [ $data, $entity->head->mime_type, $on_disk, $des ] );
        } else {
            # Real Message
            if ($type =~ /^(text|message)$/) {     # text: display it...
                if ($IO = $body->open("r")) {
                    $Body .=  $_ while (defined($_ = $IO->getline));
                    $IO->close;
                } else {       # d'oh!
                    print "$0: couldn't find/open '$name': $!";
                }
            } else { print "Oooops - no Body !\n"; }
        }
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
    }
}

###############################################################
# sub extractControls
###############################################################
# 
# This sub parses the message Body and filters the control-keys. 
# Attention: Global hash Controls affected
#
sub extractControls( $ )
{
    my ($body) = @_;
    my $backbody = "";

    my @lbody = split( /\n/, $body );
    
    # In restricted mode, all lines before the first keyword
    # are skipped.
    if( $restricted ) {
601
        while( $lbody[0] =~ /^\s*\@.*/ ){ shift( @lbody );} 
602 603 604 605
    }
    
    # Filtering for keys
    foreach( @lbody ) {
606 607 608 609 610 611 612 613
        if( /^\s*\@description/ ) {
            s/\s*\@description//;
            $backbody .= $_;
        } elsif( /^\s*\@(.*?)(?:\s*=\s*|\s*:\s*|\s+)(.*?)\s*$/ ) {
            $Control{lc($1)} = $2;
        } else {
            $backbody .= "$_" . "\n";
        }
614 615
    }

616
    # that's it.
617 618 619 620 621 622 623 624 625 626 627 628
    return( $backbody );
}

###############################################################
# Main starts here
###############################################################
# 
# Commandline switches:
# -t: test mode - no DB-Inserts
foreach( @ARGV ) {
    $restricted = 1 if ( /-r/ );
    $test = 1 if ( /-t/ );
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

    if ( /-p=['"]?(.+)['"]?/ )
    {
      $DEFAULT_PRODUCT = $1;
    }

    if ( /-c=['"]?(.+)["']?/ )
    {
      $DEFAULT_COMPONENT = $1;
    }

    if ( /-v=['"]?(.+)["']?/ )
    {
      $DEFAULT_VERSION = $1;
    }

645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
}

#
# Parsing a mime-message
#
if( -t STDIN ) {
print STDERR <<END
 Bugzilla Mail Interface

 This scripts reads a mail message through stdin and parses the message,
 for to insert a bug to bugzilla.

  Options
 -t: Testmode - No insert to the DB, but logfile
 -r: restricted mode - all lines before the keys in the mail are skipped

END
    ; 
exit;
}


# Create a new MIME parser:
my $parser = new MIME::Parser;

# Create and set the output directory:
# FIXME: There should be a $BUGZILLA_HOME variable (SML)
672 673
(-d "$datadir/mimedump-tmp") or mkdir "$datadir/mimedump-tmp",0755 or die "mkdir: $!";
(-w "$datadir/mimedump-tmp") or die "can't write to directory";
674

675
$parser->output_dir("$datadir/mimedump-tmp");
676 677 678 679 680 681 682 683 684 685
    
# Read the MIME message:
my $entity = $parser->read(\*STDIN) or die "couldn't parse MIME stream";
$entity->remove_sig(10);          # Removes the signature in the last 10 lines

# Getting values from parsed mail
my $Sender = $entity->get( 'From' );
$Sender ||=  $entity->get( 'Reply-To' );
$Message_ID = $entity->get( 'Message-Id' );

686
die (" *** Can't find Sender-address in sent mail ! ***\n" ) unless defined( $Sender );
687 688 689 690 691 692
chomp( $Sender );
chomp( $Message_ID );

$SenderShort = $Sender;
$SenderShort =~ s/^.*?([a-zA-Z0-9_.-]+?\@[a-zA-Z0-9_.-]+\.[a-zA-Z0-9_.-]+).*$/$1/;

693 694
$SenderShort = findUser($SenderShort);

695
if (!defined($SenderShort)) {
696 697 698
  $SenderShort = $Sender;
  $SenderShort =~ s/^.*?([a-zA-Z0-9_.-]+?\@[a-zA-Z0-9_.-]+\.[a-zA-Z0-9_.-]+).*$/$1/;
}
699 700 701 702 703 704 705 706 707 708 709 710

my $Subject = "";
$Subject = $entity->get( 'Subject' );
chomp( $Subject );

# Get all the attachments
dump_entity($entity);
# print $Body;
$Body = extractControls( $Body );  # fills the Control-Hash

if( $test ) {
    foreach (keys %Control ) {
711
        print "$_ => $Control{$_}\n";
712 713 714 715 716 717 718 719 720 721 722 723 724
    }
}

$Control{'short_desc'} ||= $Subject;
#
#  * Mailparsing finishes here *
#

######################################################################
# Now a lot of Checks of the given Labels start.
# Check Control-Labels
# not: reporter !
@AllowedLabels = ("product", "version", "rep_platform",
725 726 727 728
                  "bug_severity", "priority", "op_sys", "assigned_to",
                  "bug_status", "bug_file_loc", "short_desc", "component",
                  "status_whiteboard", "target_milestone", "groupset",
                  "qa_contact");
729 730 731
#my @AllowedLabels = qw{Summary priority platform assign};
foreach (keys %Control) {
    if ( lsearch( \@AllowedLabels, $_) < 0 ) {
732
        BugMailError( 0, "You sent a unknown label: " . $_ );
733 734 735 736 737 738 739 740 741 742 743 744
    }
}

push( @AllowedLabels, "reporter" );
$Control{'reporter'} = $SenderShort;

# Check required Labels - not all labels are required, because they could be generated
# from the given information
# Just send a warning- the error-Flag will be set later
@RequiredLabels = qw{product version component short_desc};
foreach my $Label (@RequiredLabels) {
    if ( ! defined $Control{$Label} ) {
745 746
        BugMailError( 0, "You were missing a required label: \@$Label\n" );
        next;
747 748 749
    }

    if( $Control{$Label} =~ /^\s*$/  ) {
750 751
        BugMailError( 0, "One of your required labels is empty: $Label" );
        next;
752 753 754 755 756 757 758 759 760 761 762 763 764
    }
}

if ( $Body =~ /^\s*$/s ) {
    BugMailError( 1, "You sent a completely empty body !" );
}


# umask 0;

# Check Permissions ...
if (! CheckPermissions("CreateBugs", $SenderShort ) ) {
    BugMailError( 2, "Permission denied.\n\n"  .
765
                  "You do not have the permissions to create a new bug. Sorry.\n" );
766 767 768
}

# Set QA
769
if (Param("useqacontact")) {
770 771 772 773
    if (defined($Control{'qa_contact'}) 
        && $Control{'qa_contact'} !~ /^\s*$/ ) {
        $Control{'qa_contact'} = DBname_to_id($Control{'qa_contact'});
    } else {
774 775 776 777 778 779 780 781
        $Control{'qa_contact'} = $dbh->selectrow_array(q{
                                    SELECT initialqacontact 
                                      FROM components 
                                INNER JOIN products 
                                        ON components.product_id = products.id 
                                     WHERE products.name = ? 
                                       AND components.name = ?}, 
                                       undef, $Control{'product'}, $Control{'component'});
782
    }
783 784 785 786 787 788
}

# Set Assigned - assigned_to depends on the product, cause initialowner 
#                depends on the product !
#                => first check product !
# Product
789
my $product;
790
my $all_products;
791 792
# set to the default product.  If the default product is empty, this has no effect
my $Product = $DEFAULT_PRODUCT;
793 794 795 796
if (defined($Control{ 'product'})) {
    $product = new Bugzilla::Product({'name' => $Control{'product'}});
    $Product = $product ? $product->name : "";
}
797 798

if ( $Product eq "" ) {
799
    my $Text = "You didn't send a value for the required key \@product !\n\n";
800 801

    $Text = "You sent the invalid product \"$Control{'product'}\"!\n\n"
802
        if( defined( $Control{ 'product'} ));
803 804

    $Text .= "Valid products are:\n\t";
805 806 807 808
    $all_products = $dbh->selectcol_arrayref(q{SELECT name 
                                                 FROM products 
                                                ORDER BY name});
    $Text .= join( "\n\t", @$all_products ) . "\n\n";
809 810 811 812 813
    $Text .= horLine();

    BugMailError( 1, $Text );
} else {
    # Fill list @all_products, which is needed in case of component-help
814
    @$all_products = ( $Product );
815 816 817 818 819 820 821
    $product_valid = 1;
}
$Control{'product'} = $Product;

#
# Check the Component:
#
822 823

# set to the default component.  If the default component is empty, this has no effect
824
my $component;
825
my $Component = $DEFAULT_COMPONENT;
826

827 828 829 830
if (defined($Control{'component'})) {
    $component = new Bugzilla::Component({'product_id' => $product->id,
                                          'name' => $Control{'component'}});
    $Component = $component ? $component->name : "";
831
}
832

833 834 835 836 837
if ( $Component eq "" ) {

    my $Text = "You did not send a value for the required key \@component!\n\n"; 

    if( defined( $Control{ 'component' } )) {
838
        $Text = "You sent the invalid component \"$Control{'component'}\" !\n";
839 840 841 842 843 844
    }

    #
    # Attention: If no product was sent, the user needs info for all components of all
    #            products -> big reply mail :)
    #            if a product was sent, only reply the components of the sent product
845 846 847 848 849 850 851
    my $val_components;
    my $sth_comp = $dbh->prepare(q{SELECT components.name 
                                     FROM components 
                               INNER JOIN products 
                                       ON components.product_id = products.id 
                                    WHERE products.name = ?});
    foreach my $prod ( @$all_products ) {
852
        $Text .= "\nValid components for product `$prod' are: \n\t";
853

854
        $val_components = $dbh->selectcol_arrayref($sth_comp, undef, $prod);
855

856
        $Text .= join( "\n\t", @$val_components ) . "\n";
857 858 859 860
    }
    
    # Special: if there is a valid product, maybe it has only one component -> use it !
    # 
861
    my $amount_of_comps = scalar(@$val_components);
862
    if( $product_valid  && $amount_of_comps == 1 ) {
863
        $Component = @$val_components[0];
864
        
865 866
        $Text .= " * You did not send a component, but a valid product $Product.\n";
        $Text .= " * This product only has one component $Component.\n" .
867 868
                " * This component was set by bugzilla for submitting the bug.\n\n";
        BugMailError( 0, $Text ); # No blocker
869 870

    } else { # The component is really buggy :(
871 872
        $Text  .= horLine();
        BugMailError( 1, $Text );
873 874 875 876 877 878 879
    }
}
$Control{'component'} = $Component;


#
# Check assigned_to
880 881 882 883
# If a value was given in the e-mail, convert it to an ID,
# otherwise, retrieve it from the database.
if ( defined($Control{'assigned_to'}) 
     && $Control{'assigned_to'} !~ /^\s*$/ ) {
884
    $Control{'assigned_to'} = login_to_id($Control{'assigned_to'});
885
} else {
886 887 888 889 890 891 892 893
    $Control{'assigned_to'} = $dbh->selectrow_array(q{
                                SELECT initialowner 
                                  FROM components
                            INNER JOIN products 
                                    ON components.product_id=products.id 
                                 WHERE products.name= ? 
                                   AND components.name= ?}, 
                                   undef, $Control{'product'}, $Control{'component'});
894 895 896 897
}

if ( $Control{'assigned_to'} == 0 ) {
    my $Text = "Could not resolve key \@assigned_to !\n" .
898 899
        "If you do NOT send a value for assigned_to, the bug will be assigned to\n" .
            "the qa-contact for the product and component.\n";
900
    $Text .= "This works only if product and component are OK. \n" 
901
        . horLine();
902 903 904 905 906

    BugMailError( 1, $Text );
}


907
$Control{'reporter'} = login_to_id($Control{'reporter'});
908 909 910 911 912 913 914 915 916 917 918 919 920
if ( ! $Control{'reporter'} ) {
    BugMailError( 1, "Could not resolve reporter !\n" );
}

### Set default values
CheckPriority( );
CheckSeverity( );
CheckPlatform( );
CheckSystem( );
# CheckArea();

### Check values ...
# Version
921
my $Version = "$DEFAULT_VERSION";
922 923 924 925 926
$Version = CheckVersion( $Control{'product'}, $Control{'version'} ) if( defined( $Control{'version'}));
if ( $Version eq "" ) {
    my $Text = "You did not send a value for the required key \@version!\n\n";

    if( defined( $Control{'version'})) {
927
        my $Text = "You sent the invalid version \"$Control{'version'}\"!\n";
928 929 930 931 932
    }

    my $anz_versions;
    my @all_versions;
    # Assemble help text
933 934 935 936 937 938 939 940
    my $sth_versions = $dbh->prepare(q{SELECT value 
                                         FROM versions
                                   INNER JOIN products 
                                           ON versions.product_id = products.id 
                                        WHERE products.name= ?});

    foreach my $prod ( @$all_products ) {
        $Text .= "Valid versions for product $prod are: \n\t";
941

942
        @all_versions = @{$dbh->selectcol_arrayref($sth_versions, undef, $prod)};
943 944
        $anz_versions = @all_versions;
        $Text .= join( "\n\t", @all_versions ) . "\n" ; 
945 946 947 948 949

    }

    # Check if we could use the only version
    if( $anz_versions == 1 && $product_valid ) {
950 951
        $Version = $all_versions[0];
        # Fine, there is only one version string
952 953
        $Text .= " * You did not send a version, but a valid product $Product.\n";
        $Text .= " * This product has has only the one version $Version.\n" .
954 955 956
            " * This version was set by bugzilla for submitting the bug.\n\n";
        $Text .= horLine();
        BugMailError( 0, $Text ); # No blocker
957
    } else {
958 959
        $Text .= horLine();
        BugMailError( 1, $Text );
960 961 962 963 964 965
    }

}

$Control{'version'} = $Version;

966
# GroupsSet: Protections for Bug info. This parameter controls the visiblility of the 
967 968
# given bug. An Error in the given Buggroup is not a blocker, a default is taken.
#
969
# The GroupSet is accepted only as literals linked with whitespaces, plus-signs or kommas
970 971
#
my $GroupSet = "";
972
my %GroupArr = ();
973 974 975
$GroupSet = $Control{'groupset'} if( defined( $Control{ 'groupset' }));
#
# Fetch the default value for groupsetting
976
my $DefaultGroup = 'ReadInternal';
977 978 979 980 981

my $default_group = $dbh->selectrow_array(q{
                                    SELECT id 
                                      FROM groups 
                                     WHERE name= ?}, undef, $DefaultGroup);
982 983

if( $GroupSet eq "" ) {
984 985
    # Too bad: Groupset does not contain anything -> set to default
    $GroupArr{$DefaultGroup} = $default_group if(defined( $default_group ));
986 987 988
    #
    # Give the user a hint
    my $Text = "You did not send a value for optional key \@groupset, which controls\n";
989 990
    $Text .= "the Permissions of the bug. It will be set to a default value 'Internal Bug'\n";
    $Text .= "if the group '$DefaultGroup' exists.  The QA may change that.\n";
991 992 993 994 995 996 997 998 999 1000
    
    BugMailError( 0, $Text );
} else {
    # literal  e.g. 'ReadInternal'
    my $gserr = 0;
    my $Text = "";

    #
    # Split literal Groupsettings either on Whitespaces, +-Signs or ,
    # Then search for every Literal in the DB - col name
1001 1002 1003
    my $sth_groups = $dbh->prepare(q{SELECT id, name 
                                       FROM groups 
                                      WHERE name= ?});
1004
    foreach ( split /\s+|\s*\+\s*|\s*,\s*/, $GroupSet ) {
1005
        my( $bval, $bname ) = $dbh->selectrow_array($sth_groups, undef, $_);
1006
        if( defined( $bname ) && $_ eq $bname ) {
1007
        $GroupArr{$bname} = $bval;
1008 1009 1010 1011
        } else {
            $Text .= "You sent the wrong GroupSet-String $_\n";
            $gserr = 1;
        }
1012
    }
1013

1014 1015 1016
    #
    # Give help if wrong GroupSet-String came
    if( $gserr > 0 ) {
1017 1018
        # There happend errors 
        $Text .= "Here are all valid literal Groupsetting-strings:\n\t";
1019 1020 1021 1022 1023 1024 1025 1026 1027
        my $groups = $dbh->selectcol_arrayref(q{
                                SELECT g.name 
                                  FROM groups g
                            INNER JOIN user_group_map u 
                                    ON g.id = u.group_id 
                                 WHERE u.user_id = ? 
                                   AND g.isbuggroup = 1 } .
                     $dbh->sql_group_by('g.name'), undef, $Control{'reporter'});
        $Text .= join( "\n\t", @$groups ) . "\n";
1028
        BugMailError( 0, $Text );
1029 1030
    }
} # End of checking groupsets
1031
delete $Control{'groupset'};
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064

# ###################################################################################
# Checking is finished
#

# Check used fields
my @used_fields;

foreach my $f (@AllowedLabels) {
    if ((exists $Control{$f}) && ($Control{$f} !~ /^\s*$/ )) {
        push (@used_fields, $f);
    }
}

#
# Creating the query for inserting the bug
# -> this should only be done, if there was no critical error before
if( $critical_err == 0 )
{
    
    my $reply = <<END
  
  +---------------------------------------------------------------------------+
           B U G Z I L L A -  M A I L -  I N T E R F A C E 
  +---------------------------------------------------------------------------+

  Your Bugzilla Mail Interface request was successfull.

END
;

    $reply .= "Your Bug-ID is ";
    my $reporter = "";
1065
        
1066
    
1067

1068 1069
    my $tmp_reply = "These values were stored by bugzilla:\n";
    my $val;
1070
    my @values = ();
1071
    foreach my $field (@used_fields) {
1072 1073 1074
        if( $field eq "groupset" ) {
            push (@values, $Control{$field});
        } elsif ( $field eq 'product' ) {
1075
            push (@values, $product->id);
1076
        } elsif ( $field eq 'component' ) {
1077
            push (@values, $component->id);
1078 1079 1080
        } else {
            push (@values, $Control{$field});
        }
1081
        
1082
        $val = $Control{ $field };
1083
      
1084
        $val = DBID_to_name( $val ) if( $field =~ /reporter|assigned_to|qa_contact/ );
1085
      
1086
        $tmp_reply .= sprintf( "     \@%-15s = %-15s\n", $field, $val );
1087

1088 1089 1090
        if ($field eq "reporter") {
            $reporter = $val;
        }
1091
    }
1092 1093 1094 1095
    #
    # Display GroupArr
    #
    $tmp_reply .= sprintf( "     \@%-15s = %-15s\n", 'groupset', join(',', keys %GroupArr) );
1096 1097 1098 1099 1100 1101 1102 1103
    
    $tmp_reply .= "      ... and your error-description !\n";

    my $comment = $Body;
    $comment =~ s/\r\n/\n/g;     # Get rid of windows-style line endings.
    $comment =~ s/\r/\n/g;       # Get rid of mac-style line endings.
    $comment = trim($comment);

1104
    my $bug_when = $dbh->selectrow_array("SELECT NOW()");
1105

1106
    my $ever_confirmed = 0;
1107 1108 1109 1110 1111 1112 1113 1114
    my $state = "UNCONFIRMED";

    my $v_confirm = $dbh->selectrow_array(q{SELECT votestoconfirm 
                                              FROM products 
                                             WHERE name = ?}, undef, $Control{'product'});
    if (!$v_confirm) {
        $ever_confirmed = 1;
        $state = "NEW";
1115
    }
1116 1117 1118 1119 1120 1121 1122
   
    my $sql_placeholders = "?, " x scalar(@values);
    my $sql_used_fields = join(", ", @used_fields);
    
    my $query = qq{INSERT INTO bugs ($sql_used_fields, bug_status, 
                                     creation_ts, delta_ts, everconfirmed) 
                   VALUES ($sql_placeholders ?, ?, ?, ? )};
1123

1124 1125
    $query =~ s/product/product_id/;
    $query =~ s/component/component_id/;
1126

1127
    push (@values, $state, $bug_when, $bug_when, $ever_confirmed);
1128

1129 1130 1131
    my $userid = $dbh->selectrow_array(q{SELECT userid FROM profiles WHERE } .
                                        $dbh->sql_istrcmp('login_name', '?'),
                                        undef, $reporter);
1132

1133
    my $id;
1134 1135
    if( ! $test ) {

1136 1137
        $dbh->do($query, undef, @values);
        $id = $dbh->bz_last_key('bugs', 'bug_id');
1138

1139 1140 1141
        $dbh->do(q{INSERT INTO longdescs 
                           SET bug_id= ?, who= ?, bug_when= ?, thetext= ?}, 
                 undef, $id, $userid, $bug_when, $comment);
1142

1143
        # Cool, the mail was successful
1144
        # system("./processmail", $id, $SenderShort);
1145
    } else {
1146
        $id = 0xFFFFFFFF;  # TEST !
1147 1148
        print "\n-------------------------------------------------------------------------\n";
        print "$query\n";
1149 1150
    }

1151 1152 1153
    #
    # Handle GroupArr
    #
1154
    my $sth_groups = $dbh->prepare(q{INSERT INTO bug_group_map SET bug_id= ?, group_id= ?});
1155
    foreach my $grp (keys %GroupArr) {
1156 1157 1158 1159 1160
        if( ! $test) {
            $sth_groups->execute($id, $GroupArr{$grp});
        } else {
            print "INSERT INTO bug_group_map SET bug_id=$id, group_id=$GroupArr{$grp}\n";
        }
1161 1162
    }

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
    #
    # handle Attachments 
    #
    my $attaches = storeAttachments( $id, $Control{'reporter'} );
    $tmp_reply .= "\n\tYou sent $attaches attachment(s). \n" if( $attaches > 0 );

    $reply .= $id . "\n\n" . $tmp_reply . "\n" . getWarningText();
    $entity->purge();  # Removes all temp files

    #
    # Send the 'you did it'-reply
    Reply( $SenderShort, $Message_ID,"Bugzilla success (ID $id)", $reply );
1175 1176

    Bugzilla::BugMail::Send($id) if( ! $test);
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
    
} else {
    # There were critical errors in the mail - the bug couldnt be inserted. !
my $errreply = <<END
  
  +---------------------------------------------------------------------------+
          B U G Z I L L A -  M A I L -  I N T E R F A C E             
  +---------------------------------------------------------------------------+

END
    ;
    
    $errreply .= getErrorText() . getWarningText() . generateTemplate();

    Reply( $SenderShort, $Message_ID, "Bugzilla Error", $errreply );

1193
    # print getErrorText();
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    # print getWarningText();
    # print generateTemplate();
}





exit;