importxml.pl 47.9 KB
Newer Older
1
#!/usr/bin/perl -wT
2 3 4
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
#
6 7
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.
8

9
# This script reads in xml bug data from standard input and inserts
10 11 12 13 14
# a new bug into bugzilla. Everything before the beginning <?xml line
# is removed so you can pipe in email messages.

use strict;

15 16
#####################################################################
#
17 18 19 20
# This script is used to import bugs from another installation of bugzilla.
# It can be used in two ways.
# First using the move function of bugzilla
# on another system will send mail to an alias provided by
21
# the administrator of the target installation (you). Set up an alias
22
# similar to the one given below so this mail will be automatically
23 24
# run by this script and imported into your database.  Run 'newaliases'
# after adding this alias to your aliases file. Make sure your sendmail
25
# installation is configured to allow mail aliases to execute code.
26 27 28
#
# bugzilla-import: "|/usr/bin/perl /opt/bugzilla/importxml.pl"
#
29 30 31 32 33 34 35
# Second it can be run from the command line with any xml file from
# STDIN that conforms to the bugzilla DTD. In this case you can pass
# an argument to set whether you want to send the
# mail that will be sent to the exporter and maintainer normally.
#
# importxml.pl bugsfile.xml
#
36 37
#####################################################################

38 39 40
use File::Basename qw(dirname);
# MTAs may call this script from any directory, but it should always
# run from this one so that it can find its modules.
41
BEGIN {
42 43 44
    require File::Basename;
    my $dir = $0; $dir =~ /(.*)/; $dir = $1; # trick taint
    chdir(File::Basename::dirname($dir));
45
}
46

47
use lib qw(. lib);
48 49 50 51
# Data dumber is used for debugging, I got tired of copying it back in 
# and then removing it. 
#use Data::Dumper;

52

53
use Bugzilla;
54
use Bugzilla::Object;
55 56 57 58 59 60
use Bugzilla::Bug;
use Bugzilla::Product;
use Bugzilla::Version;
use Bugzilla::Component;
use Bugzilla::Milestone;
use Bugzilla::FlagType;
61
use Bugzilla::BugMail;
62
use Bugzilla::Mailer;
63
use Bugzilla::User;
64 65
use Bugzilla::Util;
use Bugzilla::Constants;
66
use Bugzilla::Keyword;
67
use Bugzilla::Field;
68
use Bugzilla::Status;
69 70 71 72 73 74

use MIME::Base64;
use MIME::Parser;
use Getopt::Long;
use Pod::Usage;
use XML::Twig;
75

76 77
my $debug = 0;
my $mail  = '';
78
my $attach_path = '';
79
my $help  = 0;
80 81 82
my $bug_page = 'show_bug.cgi?id=';
my $default_product_name = '';
my $default_component_name = '';
83 84 85 86

my $result = GetOptions(
    "verbose|debug+" => \$debug,
    "mail|sendmail!" => \$mail,
87
    "attach_path=s"  => \$attach_path,
88
    "help|?"         => \$help,
89
    "bug_page=s"     => \$bug_page,
90 91
    "product=s"      => \$default_product_name,
    "component=s"    => \$default_component_name,
92 93 94 95 96 97 98 99
);

pod2usage(0) if $help;

use constant OK_LEVEL    => 3;
use constant DEBUG_LEVEL => 2;
use constant ERR_LEVEL   => 1;

100
our @logs;
101 102 103 104
our @attachments;
our $bugtotal;
my $xml;
my $dbh = Bugzilla->dbh;
105
my $params = Bugzilla->params;
106 107 108 109 110
my ($timestamp) = $dbh->selectrow_array("SELECT NOW()");

###############################################################################
# Helper sub routines                                                         #
###############################################################################
111

112
sub MailMessage {
113 114 115 116
    return unless ($mail);
    my $subject    = shift;
    my $message    = shift;
    my @recipients = @_;
117
    my $from   = $params->{"mailfrom"};
118
    $from =~ s/@/\@/g;
119

120 121 122 123 124
    foreach my $to (@recipients){
        my $header = "To: $to\n";
        $header .= "From: Bugzilla <$from>\n";
        $header .= "Subject: $subject\n\n";
        my $sendmessage = $header . $message . "\n";
125
        MessageToMTA($sendmessage);
126
    }
127

128 129
}

130 131 132 133 134 135 136 137
sub Debug {
    return unless ($debug);
    my ( $message, $level ) = (@_);
    print STDERR "OK: $message \n" if ( $level == OK_LEVEL );
    print STDERR "ERR: $message \n" if ( $level == ERR_LEVEL );
    print STDERR "$message\n"
      if ( ( $debug == $level ) && ( $level == DEBUG_LEVEL ) );
}
138

139 140 141 142 143
sub Error {
    my ( $reason, $errtype, $exporter ) = @_;
    my $subject = "Bug import error: $reason";
    my $message = "Cannot import these bugs because $reason ";
    $message .= "\n\nPlease re-open the original bug.\n" if ($errtype);
144 145
    $message .= "For more info, contact " . $params->{"maintainer"} . ".\n";
    my @to = ( $params->{"maintainer"}, $exporter);
146 147 148
    Debug( $message, ERR_LEVEL );
    MailMessage( $subject, $message, @to );
    exit;
149 150
}

151 152 153 154 155 156
# This subroutine handles flags for process_bug. It is generic in that
# it can handle both attachment flags and bug flags.
sub flag_handler {
    my (
        $name,            $status,      $setter_login,
        $requestee_login, $exporterid,  $bugid,
157
        $componentid,     $productid,   $attachid
158 159 160 161 162
      )
      = @_;

    my $type         = ($attachid) ? "attachment" : "bug";
    my $err          = '';
163
    my $setter       = new Bugzilla::User({ name => $setter_login });
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    my $requestee;
    my $requestee_id;

    unless ($setter) {
        $err = "Invalid setter $setter_login on $type flag $name\n";
        $err .= "   Dropping flag $name\n";
        return $err;
    }
    if ( !$setter->can_see_bug($bugid) ) {
        $err .= "Setter is not a member of bug group\n";
        $err .= "   Dropping flag $name\n";
        return $err;
    }
    my $setter_id = $setter->id;
    if ( defined($requestee_login) ) {
179
        $requestee = new Bugzilla::User({ name => $requestee_login });
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
        if ( $requestee ) {
            if ( !$requestee->can_see_bug($bugid) ) {
                $err .= "Requestee is not a member of bug group\n";
                $err .= "   Requesting from the wind\n";
            }    
            else{
                $requestee_id = $requestee->id;
            }
        }
        else {
            $err = "Invalid requestee $requestee_login on $type flag $name\n";
            $err .= "   Requesting from the wind.\n";
        }
        
    }
    my $flag_types;

    # If this is an attachment flag we need to do some dirty work to look
    # up the flagtype ID
    if ($attachid) {
        $flag_types = Bugzilla::FlagType::match(
            {
                'target_type'  => 'attachment',
                'product_id'   => $productid,
                'component_id' => $componentid
            } );
    }
    else {
208
        my $bug = new Bugzilla::Bug($bugid);
209 210 211 212 213 214 215 216 217 218 219 220 221
        $flag_types = $bug->flag_types;
    }
    unless ($flag_types){
        $err  = "No flag types defined for this bug\n";
        $err .= "   Dropping flag $name\n";
        return $err;
    }

    # We need to see if the imported flag is in the list of known flags
    # It is possible for two flags on the same bug have the same name
    # If this is the case, we will only match the first one.
    my $ftype;
    foreach my $f ( @{$flag_types} ) {
222
        if ( $f->name eq $name) {
223 224 225 226 227 228
            $ftype = $f;
            last;
        }
    }

    if ($ftype) {    # We found the flag in the list
229
        my $grant_group = $ftype->grant_group;
230
        if (( $status eq '+' || $status eq '-' ) 
231
            && $grant_group && !$setter->in_group_id($grant_group->id)) {
232 233 234 235 236
            $err = "Setter $setter_login on $type flag $name ";
            $err .= "is not in the Grant Group\n";
            $err .= "   Dropping flag $name\n";
            return $err;
        }
237 238 239
        my $request_group = $ftype->request_group;
        if ($request_group
            && $status eq '?' && !$setter->in_group_id($request_group->id)) {
240 241 242 243 244
            $err = "Setter $setter_login on $type flag $name ";
            $err .= "is not in the Request Group\n";
            $err .= "   Dropping flag $name\n";
            return $err;
        }
245

246
        # Take the first flag_type that matches
247
        unless ($ftype->is_active) {
248 249 250 251 252 253
            $err = "Flag $name is not active in this database\n";
            $err .= "   Dropping flag $name\n";
            return $err;
        }

        $dbh->do("INSERT INTO flags 
254 255 256
                 (type_id, status, bug_id, attach_id, creation_date, 
                  setter_id, requestee_id)
                  VALUES (?, ?, ?, ?, ?, ?, ?)", undef,
257
            ($ftype->id, $status, $bugid, $attachid, $timestamp,
258
            $setter_id, $requestee_id));
259 260 261 262 263 264
    }
    else {
        $err = "Dropping unknown $type flag: $name\n";
        return $err;
    }
    return $err;
265 266
}

267 268 269 270 271 272 273 274
# Converts and returns the input data as an array.
sub _to_array {
    my $value = shift;

    $value = [$value] if !ref($value);
    return @$value;
}

275 276 277 278 279 280 281 282 283 284 285
###############################################################################
# XML Handlers                                                                #
###############################################################################

# This subroutine gets called only once - as soon as the <bugzilla> opening
# tag is parsed. It simply checks to see that the all important exporter
# maintainer and URL base are set.
#
#    exporter:   email address of the person moving the bugs
#    maintainer: the maintainer of the bugzilla installation
#                as set in the parameters file
286
#    urlbase:    The urlbase parameter of the installation
287 288 289 290 291 292 293 294 295 296
#                bugs are being moved from
#
sub init() {
    my ( $twig, $bugzilla ) = @_;
    my $root       = $twig->root;
    my $maintainer = $root->{'att'}->{'maintainer'};
    my $exporter   = $root->{'att'}->{'exporter'};
    my $urlbase    = $root->{'att'}->{'urlbase'};
    my $xmlversion = $root->{'att'}->{'version'};

297
    if ($xmlversion ne BUGZILLA_VERSION) {
298
            my $log = "Possible version conflict!\n";
299 300
            $log .= "   XML was exported from Bugzilla version $xmlversion\n";
            $log .= "   But this installation uses ";
301
            $log .= BUGZILLA_VERSION . "\n";
302 303
            Debug($log, OK_LEVEL);
            push(@logs, $log);
304 305 306 307 308
    }
    Error( "no maintainer", "REOPEN", $exporter ) unless ($maintainer);
    Error( "no exporter",   "REOPEN", $exporter ) unless ($exporter);
    Error( "invalid exporter: $exporter", "REOPEN", $exporter ) if ( !login_to_id($exporter) );
    Error( "no urlbase set", "REOPEN", $exporter ) unless ($urlbase);
309
}
310
    
311

312 313 314 315 316
# Parse attachments.
#
# This subroutine is called once for each attachment in the xml file.
# It is called as soon as the closing </attachment> tag is parsed.
# Since attachments have the potential to be very large, and
317
# since each attachment will be inside <bug>..</bug> tags we shove
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
# the attachment onto an array which will be processed by process_bug
# and then disposed of. The attachment array will then contain only
# one bugs' attachments at a time.
# The cycle will then repeat for the next <bug>
#
# The attach_id is ignored since mysql generates a new one for us.
# The submitter_id gets filled in with $exporterid.

sub process_attachment() {
    my ( $twig, $attach ) = @_;
    Debug( "Parsing attachments", DEBUG_LEVEL );
    my %attachment;

    $attachment{'date'} =
        format_time( $attach->field('date'), "%Y-%m-%d %R" ) || $timestamp;
    $attachment{'desc'}       = $attach->field('desc');
    $attachment{'ctype'}      = $attach->field('type') || "unknown/unknown";
    $attachment{'attachid'}   = $attach->field('attachid');
    $attachment{'ispatch'}    = $attach->{'att'}->{'ispatch'} || 0;
    $attachment{'isobsolete'} = $attach->{'att'}->{'isobsolete'} || 0;
    $attachment{'isprivate'}  = $attach->{'att'}->{'isprivate'} || 0;
    $attachment{'filename'}   = $attach->field('filename') || "file";
340
    $attachment{'attacher'}   = $attach->field('attacher');
341
    # Attachment data is not exported in versions 2.20 and older.
342 343 344 345 346 347 348 349 350 351 352 353
    if (defined $attach->first_child('data') &&
            defined $attach->first_child('data')->{'att'}->{'encoding'}) {
        my $encoding = $attach->first_child('data')->{'att'}->{'encoding'};
        if ($encoding =~ /base64/) {
            # decode the base64
            my $data   = $attach->field('data');
            my $output = decode_base64($data);
            $attachment{'data'} = $output;
        }
        elsif ($encoding =~ /filename/) {
            # read the attachment file
            Error("attach_path is required", undef) unless ($attach_path);
354 355 356 357 358 359 360
            
            my $filename = $attach->field('data');
            # Remove any leading path data from the filename
            $filename =~ s/(.*\/|.*\\)//gs;
            
            my $attach_filename = $attach_path . "/" . $filename;
            open(ATTACH_FH, "<", $attach_filename) or
361 362 363 364
                Error("cannot open $attach_filename", undef);
            $attachment{'data'} = do { local $/; <ATTACH_FH> };
            close ATTACH_FH;
        }
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
    }
    else {
        $attachment{'data'} = $attach->field('data');
    }

    # attachment flags
    my @aflags;
    foreach my $aflag ( $attach->children('flag') ) {
        my %aflag;
        $aflag{'name'}      = $aflag->{'att'}->{'name'};
        $aflag{'status'}    = $aflag->{'att'}->{'status'};
        $aflag{'setter'}    = $aflag->{'att'}->{'setter'};
        $aflag{'requestee'} = $aflag->{'att'}->{'requestee'};
        push @aflags, \%aflag;
    }
    $attachment{'flags'} = \@aflags if (@aflags);

    # free up the memory for use by the rest of the script
    $attach->delete;
    if ($attachment{'attachid'}) {
        push @attachments, \%attachment;
    }
    else {
        push @attachments, "err";
    }
390
}
391 392 393 394 395 396 397 398 399 400 401 402 403 404

# This subroutine will be called once for each <bug> in the xml file.
# It is called as soon as the closing </bug> tag is parsed.
# If this bug had any <attachment> tags, they will have been processed
# before we get to this point and their data will be in the @attachments
# array.
# As each bug is processed, it is inserted into the database and then
# purged from memory to free it up for later bugs.

sub process_bug {
    my ( $twig, $bug ) = @_;
    my $root             = $twig->root;
    my $maintainer       = $root->{'att'}->{'maintainer'};
    my $exporter_login   = $root->{'att'}->{'exporter'};
405
    my $exporter         = new Bugzilla::User({ name => $exporter_login });
406
    my $urlbase          = $root->{'att'}->{'urlbase'};
407 408
    my $url              = $urlbase . $bug_page;
    trick_taint($url);
409

410 411
    # We will store output information in this variable.
    my $log = "";
412 413 414 415 416 417 418 419 420 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
    if ( defined $bug->{'att'}->{'error'} ) {
        $log .= "\nError in bug " . $bug->field('bug_id') . "\@$urlbase: ";
        $log .= $bug->{'att'}->{'error'} . "\n";
        if ( $bug->{'att'}->{'error'} =~ /NotFound/ ) {
            $log .= "$exporter_login tried to move bug " . $bug->field('bug_id');
            $log .= " here, but $urlbase reports that this bug";
            $log .= " does not exist.\n";
        }
        elsif ( $bug->{'att'}->{'error'} =~ /NotPermitted/ ) {
            $log .= "$exporter_login tried to move bug " . $bug->field('bug_id');
            $log .= " here, but $urlbase reports that $exporter_login does ";
            $log .= " not have access to that bug.\n";
        }
        return;
    }
    $bugtotal++;

    # This list contains all other bug fields that we want to process.
    # If it is not in this list it will not be included.
    my %all_fields;
    foreach my $field ( 
        qw(long_desc attachment flag group), Bugzilla::Bug::fields() )
    {
        $all_fields{$field} = 1;
    }
    
    my %bug_fields;
    my $err = "";

   # Loop through all the xml tags inside a <bug> and compare them to the
   # lists of fields. If they match throw them into the hash. Otherwise
   # append it to the log, which will go into the comments when we are done.
    foreach my $bugchild ( $bug->children() ) {
        Debug( "Parsing field: " . $bugchild->name, DEBUG_LEVEL );
446 447 448 449 450

        # Skip the token if one is included. We don't want it included in
        # the comments, and it is not used by the importer.
        next if $bugchild->name eq 'token';

451
        if ( defined $all_fields{ $bugchild->name } ) {
452 453 454 455 456 457 458
            my @values = $bug->children_text($bugchild->name);
            if (scalar @values > 1) {
                $bug_fields{$bugchild->name} = \@values;
            }
            else {
                $bug_fields{$bugchild->name} = $values[0];
            }
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
        }
        else {
            $err .= "Unknown bug field \"" . $bugchild->name . "\"";
            $err .= " encountered while moving bug\n";
            $err .= "   <" . $bugchild->name . ">";
            if ( $bugchild->children_count > 1 ) {
                $err .= "\n";
                foreach my $subchild ( $bugchild->children() ) {
                    $err .= "     <" . $subchild->name . ">";
                    $err .= $subchild->field;
                    $err .= "</" . $subchild->name . ">\n";
                }
            }
            else {
                $err .= $bugchild->field;
            }
            $err .= "</" . $bugchild->name . ">\n";
        }
    }

    # Parse long descriptions
480
    my @long_descs;
481 482
    foreach my $comment ( $bug->children('long_desc') ) {
        Debug( "Parsing Long Description", DEBUG_LEVEL );
483 484 485 486 487 488 489
        my %long_desc = ( who       => $comment->field('who'),
                          bug_when  => $comment->field('bug_when'),
                          isprivate => $comment->{'att'}->{'isprivate'} || 0 );

        # If the exporter is not in the insidergroup, keep the comment public.
        $long_desc{isprivate} = 0 unless $exporter->is_insider;

490 491 492 493 494 495 496 497
        my $data = $comment->field('thetext');
        if ( defined $comment->first_child('thetext')->{'att'}->{'encoding'}
            && $comment->first_child('thetext')->{'att'}->{'encoding'} =~
            /base64/ )
        {
            $data = decode_base64($data);
        }

498 499
        # For backwards-compatibility with Bugzillas before 3.6:
        #
500 501
        # If we leave the attachment ID in the comment it will be made a link
        # to the wrong attachment. Since the new attachment ID is unknown yet
502 503 504 505 506 507 508 509 510
        # let's strip it out for now. We will make a comment with the right ID
        # later
        $data =~ s/Created an attachment \(id=\d+\)/Created an attachment/g;

        # Same goes for bug #'s Since we don't know if the referenced bug
        # is also being moved, lets make sure they know it means a different
        # bugzilla.
        $data =~ s/([Bb]ugs?\s*\#?\s*(\d+))/$url$2/g;

511 512 513
        # Keep the original commenter if possible, else we will fall back
        # to the exporter account.
        $long_desc{whoid} = login_to_id($long_desc{who});
514

515 516
        if (!$long_desc{whoid}) {
            $data = "The original author of this comment is $long_desc{who}.\n\n" . $data;
517
        }
518 519 520

        $long_desc{'thetext'} = $data;
        push @long_descs, \%long_desc;
521 522
    }

523
    my @sorted_descs = sort { $a->{'bug_when'} cmp $b->{'bug_when'} } @long_descs;
524

525
    my $comments = "\n\n--- Bug imported by $exporter_login ";
526
    $comments .= format_time(scalar localtime(time()), '%Y-%m-%d %R %Z') . " ";
527 528
    $comments .= " ---\n\n";
    $comments .= "This bug was previously known as _bug_ $bug_fields{'bug_id'} at ";
529
    $comments .= $url . $bug_fields{'bug_id'} . "\n";
530
    if ( defined $bug_fields{'dependson'} ) {
531
        $comments .= "This bug depended on bug(s) " .
532
                     join(' ', _to_array($bug_fields{'dependson'})) . ".\n";
533 534
    }
    if ( defined $bug_fields{'blocked'} ) {
535
        $comments .= "This bug blocked bug(s) " .
536
                     join(' ', _to_array($bug_fields{'blocked'})) . ".\n";
537 538 539 540 541 542 543 544 545 546 547
    }

    # Now we process each of the fields in turn and make sure they contain
    # valid data. We will create two parallel arrays, one for the query
    # and one for the values. For every field we need to push an entry onto
    # each array.
    my @query  = ();
    my @values = ();

    # Each of these fields we will check for newlines and shove onto the array
    foreach my $field (qw(status_whiteboard bug_file_loc short_desc)) {
548
        if ($bug_fields{$field}) {
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
            $bug_fields{$field} = clean_text( $bug_fields{$field} );
            push( @query,  $field );
            push( @values, $bug_fields{$field} );
        }
    }

    # Alias
    if ( $bug_fields{'alias'} ) {
        my ($alias) = $dbh->selectrow_array("SELECT COUNT(*) FROM bugs 
                                                WHERE alias = ?", undef,
                                                $bug_fields{'alias'} );
        if ($alias) {
            $err .= "Dropping conflicting bug alias ";
            $err .= $bug_fields{'alias'} . "\n";
        }
        else {
            $alias = $bug_fields{'alias'};
            push @query,  'alias';
            push @values, $alias;
        }
    }

    # Timestamps
    push( @query, "creation_ts" );
    push( @values,
574
        format_time( $bug_fields{'creation_ts'}, "%Y-%m-%d %T" )
575 576 577 578
          || $timestamp );

    push( @query, "delta_ts" );
    push( @values,
579
        format_time( $bug_fields{'delta_ts'}, "%Y-%m-%d %T" )
580 581 582 583
          || $timestamp );

    # Bug Access
    push( @query,  "cclist_accessible" );
584
    push( @values, $bug_fields{'cclist_accessible'} ? 1 : 0 );
585 586

    push( @query,  "reporter_accessible" );
587
    push( @values, $bug_fields{'reporter_accessible'} ? 1 : 0 );
588

589 590 591 592 593 594 595 596 597 598
    my $product = new Bugzilla::Product(
        { name => $bug_fields{'product'} || '' });
    if (!$product) {
        $err .= "Unknown Product " . $bug_fields{'product'} . "\n";
        $err .= "   Using default product set at the command line.\n";
        $product = new Bugzilla::Product({ name => $default_product_name })
            or Error("an invalid default product was defined for the target"
                     . " DB. " . $params->{"maintainer"} . " needs to specify "
                     . "--product when calling importxml.pl", "REOPEN", 
                     $exporter);
599
    }
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
    my $component = new Bugzilla::Component({
        product => $product, name => $bug_fields{'component'} || '' });
    if (!$component) {
        $err .= "Unknown Component " . $bug_fields{'component'} . "\n";
        $err .= "   Using default product and component set ";
        $err .= "at the command line.\n";

        $product = new Bugzilla::Product({ name => $default_product_name });
        $component = new Bugzilla::Component({
           name => $default_component_name, product => $product });
        if (!$component) {
            Error("an invalid default component was defined for the target" 
                  . " DB. ".  $params->{"maintainer"} . " needs to specify " 
                  . "--component when calling importxml.pl", "REOPEN", 
                  $exporter);
615 616 617 618 619 620 621 622 623 624 625 626 627 628
        }
    }

    my $prod_id = $product->id;
    my $comp_id = $component->id;

    push( @query,  "product_id" );
    push( @values, $prod_id );
    push( @query,  "component_id" );
    push( @values, $comp_id );

    # Since there is no default version for a product, we check that the one
    # coming over is valid. If not we will use the first one in @versions
    # and warn them.
629 630
    my $version = new Bugzilla::Version(
          { product => $product, name => $bug_fields{'version'} });
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648

    push( @query, "version" );
    if ($version) {
        push( @values, $version->name );
    }
    else {
        my @versions = @{ $product->versions };
        my $v        = $versions[0];
        push( @values, $v->name );
        $err .= "Unknown version \"";
        $err .= ( defined $bug_fields{'version'} )
            ? $bug_fields{'version'}
            : "unknown";
        $err .= " in product " . $product->name . ". \n";
        $err .= "   Setting version to \"" . $v->name . "\".\n";
    }

    # Milestone
649
    if ( $params->{"usetargetmilestone"} ) {
650 651 652 653 654 655 656
        my $milestone;
        if (defined $bug_fields{'target_milestone'}
            && $bug_fields{'target_milestone'} ne "") {

            $milestone = new Bugzilla::Milestone(
                { product => $product, name => $bug_fields{'target_milestone'} });
        }
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
        if ($milestone) {
            push( @values, $milestone->name );
        }
        else {
            push( @values, $product->default_milestone );
            $err .= "Unknown milestone \"";
            $err .= ( defined $bug_fields{'target_milestone'} )
                ? $bug_fields{'target_milestone'}
                : "unknown";
            $err .= " in product " . $product->name . ". \n";
            $err .= "   Setting to default milestone for this product, ";
            $err .= "\"" . $product->default_milestone . "\".\n";
        }
        push( @query, "target_milestone" );
    }

    # For priority, severity, opsys and platform we check that the one being
    # imported is valid. If it is not we use the defaults set in the parameters.
    if (defined( $bug_fields{'bug_severity'} )
        && check_field('bug_severity', scalar $bug_fields{'bug_severity'},
677
                       undef, ERR_LEVEL) )
678 679 680 681
    {
        push( @values, $bug_fields{'bug_severity'} );
    }
    else {
682
        push( @values, $params->{'defaultseverity'} );
683 684 685 686 687
        $err .= "Unknown severity ";
        $err .= ( defined $bug_fields{'bug_severity'} )
          ? $bug_fields{'bug_severity'}
          : "unknown";
        $err .= ". Setting to default severity \"";
688
        $err .= $params->{'defaultseverity'} . "\".\n";
689 690 691 692 693
    }
    push( @query, "bug_severity" );

    if (defined( $bug_fields{'priority'} )
        && check_field('priority', scalar $bug_fields{'priority'},
694
                       undef, ERR_LEVEL ) )
695 696 697 698
    {
        push( @values, $bug_fields{'priority'} );
    }
    else {
699
        push( @values, $params->{'defaultpriority'} );
700 701 702 703 704
        $err .= "Unknown priority ";
        $err .= ( defined $bug_fields{'priority'} )
          ? $bug_fields{'priority'}
          : "unknown";
        $err .= ". Setting to default priority \"";
705
        $err .= $params->{'defaultpriority'} . "\".\n";
706 707 708 709 710
    }
    push( @query, "priority" );

    if (defined( $bug_fields{'rep_platform'} )
        && check_field('rep_platform', scalar $bug_fields{'rep_platform'},
711
                       undef, ERR_LEVEL ) )
712 713 714 715
    {
        push( @values, $bug_fields{'rep_platform'} );
    }
    else {
716
        push( @values, $params->{'defaultplatform'} );
717 718 719 720 721
        $err .= "Unknown platform ";
        $err .= ( defined $bug_fields{'rep_platform'} )
          ? $bug_fields{'rep_platform'}
          : "unknown";
        $err .=". Setting to default platform \"";
722
        $err .= $params->{'defaultplatform'} . "\".\n";
723 724 725 726 727
    }
    push( @query, "rep_platform" );

    if (defined( $bug_fields{'op_sys'} )
        && check_field('op_sys',  scalar $bug_fields{'op_sys'},
728
                       undef, ERR_LEVEL ) )
729 730 731 732
    {
        push( @values, $bug_fields{'op_sys'} );
    }
    else {
733
        push( @values, $params->{'defaultopsys'} );
734 735 736 737
        $err .= "Unknown operating system ";
        $err .= ( defined $bug_fields{'op_sys'} )
          ? $bug_fields{'op_sys'}
          : "unknown";
738
        $err .= ". Setting to default OS \"" . $params->{'defaultopsys'} . "\".\n";
739 740 741 742
    }
    push( @query, "op_sys" );

    # Process time fields
743
    if ( $params->{"timetrackinggroup"} ) {
744
        my $date = validate_date( $bug_fields{'deadline'} ) ? $bug_fields{'deadline'} : undef;
745 746
        push( @values, $date );
        push( @query,  "deadline" );
747 748
        if ( defined $bug_fields{'estimated_time'} ) {
            eval {
749
                Bugzilla::Object::_validate_time($bug_fields{'estimated_time'}, "e");
750 751 752 753 754
            };
            if (!$@){
                push( @values, $bug_fields{'estimated_time'} );
                push( @query,  "estimated_time" );
            }
755
        }
756 757
        if ( defined $bug_fields{'remaining_time'} ) {
            eval {
758
                Bugzilla::Object::_validate_time($bug_fields{'remaining_time'}, "r");
759 760 761 762 763
            };
            if (!$@){
                push( @values, $bug_fields{'remaining_time'} );
                push( @query,  "remaining_time" );
            }
764
        }
765 766
        if ( defined $bug_fields{'actual_time'} ) {
            eval {
767
                Bugzilla::Object::_validate_time($bug_fields{'actual_time'}, "a");
768 769 770 771 772 773 774
            };
            if ($@){
                $bug_fields{'actual_time'} = 0.0;
                $err .= "Invalid Actual Time. Setting to 0.0\n";
            }
        }
        else {
775
            $bug_fields{'actual_time'} = 0.0;
776
            $err .= "Actual time not defined. Setting to 0.0\n";
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
        }
    }

    # Reporter Assignee QA Contact
    my $exporterid = $exporter->id;
    my $reporterid = login_to_id( $bug_fields{'reporter'} )
      if $bug_fields{'reporter'};
    push( @query, "reporter" );
    if ( ( $bug_fields{'reporter'} ) && ($reporterid) ) {
        push( @values, $reporterid );
    }
    else {
        push( @values, $exporterid );
        $err .= "The original reporter of this bug does not have\n";
        $err .= "   an account here. Reassigning to the person who moved\n";
        $err .= "   it here: $exporter_login.\n";
        if ( $bug_fields{'reporter'} ) {
            $err .= "   Previous reporter was $bug_fields{'reporter'}.\n";
        }
        else {
            $err .= "   Previous reporter is unknown.\n";
        }
    }

    my $changed_owner = 0;
    my $owner;
    push( @query, "assigned_to" );
    if ( ( $bug_fields{'assigned_to'} )
        && ( $owner = login_to_id( $bug_fields{'assigned_to'} )) ) {
        push( @values, $owner );
    }
    else {
        push( @values, $component->default_assignee->id );
        $changed_owner = 1;
        $err .= "The original assignee of this bug does not have\n";
        $err .= "   an account here. Reassigning to the default assignee\n";
        $err .= "   for the component, ". $component->default_assignee->login .".\n";
        if ( $bug_fields{'assigned_to'} ) {
            $err .= "   Previous assignee was $bug_fields{'assigned_to'}.\n";
        }
        else {
            $err .= "   Previous assignee is unknown.\n";
        }
    }

822
    if ( $params->{"useqacontact"} ) {
823 824 825 826 827 828 829
        my $qa_contact;
        push( @query, "qa_contact" );
        if ( ( defined $bug_fields{'qa_contact'})
            && ( $qa_contact = login_to_id( $bug_fields{'qa_contact'} ) ) ) {
            push( @values, $qa_contact );
        }
        else {
830 831 832 833
            push(@values, $component->default_qa_contact ?
                          $component->default_qa_contact->id : undef);

            if ($component->default_qa_contact) {
834 835 836 837 838 839 840 841 842
                $err .= "Setting qa contact to the default for this product.\n";
                $err .= "   This bug either had no qa contact or an invalid one.\n";
            }
        }
    }

    # Status & Resolution
    my $valid_res = check_field('resolution',  
                                  scalar $bug_fields{'resolution'}, 
843
                                  undef, ERR_LEVEL );
844 845
    my $valid_status = check_field('bug_status',  
                                  scalar $bug_fields{'bug_status'}, 
846
                                  undef, ERR_LEVEL );
847 848 849 850 851
    my $status = $bug_fields{'bug_status'} || undef;
    my $resolution = $bug_fields{'resolution'} || undef;
    
    # Check everconfirmed 
    my $everconfirmed;
852
    if ($product->allows_unconfirmed) {
853 854 855 856 857 858 859 860 861 862 863 864 865
        $everconfirmed = $bug_fields{'everconfirmed'} || 0;
    }
    else {
        $everconfirmed = 1;
    }
    push (@query,  "everconfirmed");
    push (@values, $everconfirmed);

    # Sanity check will complain about having bugs marked duplicate but no
    # entry in the dup table. Since we can't tell the bug ID of bugs
    # that might not yet be in the database we have no way of populating
    # this table. Change the resolution instead.
    if ( $valid_res  && ( $bug_fields{'resolution'} eq "DUPLICATE" ) ) {
866
        $resolution = "INVALID";
867
        $err .= "This bug was marked DUPLICATE in the database ";
868
        $err .= "it was moved from.\n    Changing resolution to \"INVALID\"\n";
869
    } 
870 871 872 873 874 875 876 877 878 879 880

    # If there is at least 1 initial bug status different from UNCO, use it,
    # else use the open bug status with the lowest sortkey (different from UNCO).
    my @bug_statuses = @{Bugzilla::Status->can_change_to()};
    @bug_statuses = grep { $_->name ne 'UNCONFIRMED' } @bug_statuses;

    my $initial_status;
    if (scalar(@bug_statuses)) {
        $initial_status = $bug_statuses[0]->name;
    }
    else {
881
        @bug_statuses = Bugzilla::Status->get_all();
882 883 884 885 886 887 888 889 890 891 892 893
        # Exclude UNCO and inactive bug statuses.
        @bug_statuses = grep { $_->is_active && $_->name ne 'UNCONFIRMED'} @bug_statuses;
        my @open_statuses = grep { $_->is_open } @bug_statuses;
        if (scalar(@open_statuses)) {
            $initial_status = $open_statuses[0]->name;
        }
        else {
            # There is NO other open bug statuses outside UNCO???
            Error("no open bug statuses available.");
        }
    }

894
    if ($status) {
895
        if($valid_status){
896
            if (is_open_state($status)) {
897
                if ($resolution) {
898 899 900 901 902 903
                    $err .= "Resolution set on an open status.\n";
                    $err .= "   Dropping resolution $resolution\n";
                    $resolution = undef;
                }
                if($changed_owner){
                    if($everconfirmed){  
904
                        $status = $initial_status;
905 906 907 908 909 910 911 912 913 914 915 916 917
                    }
                    else{
                        $status = "UNCONFIRMED";
                    }
                    if ($status ne $bug_fields{'bug_status'}){
                        $err .= "Bug reassigned, setting status to \"$status\".\n";
                        $err .= "   Previous status was \"";
                        $err .=  $bug_fields{'bug_status'} . "\".\n";
                    }
                }
                if($everconfirmed){
                    if($status eq "UNCONFIRMED"){
                        $err .= "Bug Status was UNCONFIRMED but everconfirmed was true\n";
918 919
                        $err .= "   Setting status to $initial_status\n";
                        $status = $initial_status;
920 921 922 923 924 925 926 927 928 929
                    }
                }
                else{ # $everconfirmed is false
                    if($status ne "UNCONFIRMED"){
                        $err .= "Bug Status was $status but everconfirmed was false\n";
                        $err .= "   Setting status to UNCONFIRMED\n";
                        $status = "UNCONFIRMED";
                    }
                }
            }
930
            else {
931
               if (!$resolution) {
932 933
                   $err .= "Missing Resolution. Setting status to ";
                   if($everconfirmed){
934 935
                       $status = $initial_status;
                       $err .= "$initial_status\n";
936 937 938 939 940 941
                   }
                   else{
                       $status = "UNCONFIRMED";
                       $err .= "UNCONFIRMED\n";
                   }
               }
942
               elsif (!$valid_res) {
943
                   $err .= "Unknown resolution \"$resolution\".\n";
944 945
                   $err .= "   Setting resolution to INVALID\n";
                   $resolution = "INVALID";
946 947 948 949 950
               }
            }   
        }
        else{ # $valid_status is false
            if($everconfirmed){  
951
                $status = $initial_status;
952 953 954 955 956 957 958 959 960 961
            }
            else{
                $status = "UNCONFIRMED";
            }        
            $err .= "Bug has invalid status, setting status to \"$status\".\n";
            $err .= "   Previous status was \"";
            $err .=  $bug_fields{'bug_status'} . "\".\n";
            $resolution = undef;
        }
    }
962
    else {
963
        if($everconfirmed){  
964
            $status = $initial_status;
965 966 967 968 969 970 971 972
        }
        else{
            $status = "UNCONFIRMED";
        }        
        $err .= "Bug has no status, setting status to \"$status\".\n";
        $err .= "   Previous status was unknown\n";
        $resolution = undef;
    }
973 974

    if ($resolution) {
975 976 977 978 979 980 981 982
        push( @query,  "resolution" );
        push( @values, $resolution );
    }
    
    # Bug status
    push( @query,  "bug_status" );
    push( @values, $status );

983 984
    # Custom fields - Multi-select fields have their own table.
    my %multi_select_fields;
985 986
    foreach my $field (Bugzilla->active_custom_fields) {
        my $custom_field = $field->name;
987 988
        my $value = $bug_fields{$custom_field};
        next unless defined $value;
989 990
        if ($field->type == FIELD_TYPE_FREETEXT) {
            push(@query, $custom_field);
991 992 993 994
            push(@values, clean_text($value));
        } elsif ($field->type == FIELD_TYPE_TEXTAREA) {
            push(@query, $custom_field);
            push(@values, $value);
995
        } elsif ($field->type == FIELD_TYPE_SINGLE_SELECT) {
996
            my $is_well_formed = check_field($custom_field, $value, undef, ERR_LEVEL);
997 998
            if ($is_well_formed) {
                push(@query, $custom_field);
999
                push(@values, $value);
1000
            } else {
1001 1002 1003 1004
                $err .= "Skipping illegal value \"$value\" in $custom_field.\n" ;
            }
        } elsif ($field->type == FIELD_TYPE_MULTI_SELECT) {
            my @legal_values;
1005
            foreach my $item (_to_array($value)) {
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
                my $is_well_formed = check_field($custom_field, $item, undef, ERR_LEVEL);
                if ($is_well_formed) {
                    push(@legal_values, $item);
                } else {
                    $err .= "Skipping illegal value \"$item\" in $custom_field.\n" ;
                }
            }
            if (scalar @legal_values) {
                $multi_select_fields{$custom_field} = \@legal_values;
            }
        } elsif ($field->type == FIELD_TYPE_DATETIME) {
            eval { $value = Bugzilla::Bug->_check_datetime_field($value); };
            if ($@) {
                $err .= "Skipping illegal value \"$value\" in $custom_field.\n" ;
            }
            else {
                push(@query, $custom_field);
                push(@values, $value);
1024 1025 1026 1027 1028 1029
            }
        } else {
            $err .= "Type of custom field $custom_field is an unhandled FIELD_TYPE: " .
                    $field->type . "\n";
        }
    }
1030 1031 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

    # For the sake of sanitycheck.cgi we do this.
    # Update lastdiffed if you do not want to have mail sent
    unless ($mail) {
        push @query,  "lastdiffed";
        push @values, $timestamp;
    }

    # INSERT the bug
    my $query = "INSERT INTO bugs (" . join( ", ", @query ) . ") VALUES (";
       $query .= '?,' foreach (@values);
    chop($query);    # Remove the last comma.
       $query .= ")";

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

    # We are almost certain to get some uninitialized warnings
    # Since this is just for debugging the query, let's shut them up
    eval {
        no warnings 'uninitialized';
        Debug(
            "Bug Query: INSERT INTO bugs (\n"
              . join( ",\n", @query )
              . "\n) VALUES (\n"
              . join( ",\n", @values ),
            DEBUG_LEVEL
        );
    };

    # Handle CC's
    if ( defined $bug_fields{'cc'} ) {
        my %ccseen;
        my $sth_cc = $dbh->prepare("INSERT INTO cc (bug_id, who) VALUES (?,?)");
1064
        foreach my $person (_to_array($bug_fields{'cc'})) {
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
            next unless $person;
            my $uid;
            if ($uid = login_to_id($person)) {
                if ( !$ccseen{$uid} ) {
                    $sth_cc->execute( $id, $uid );
                    $ccseen{$uid} = 1;
                }
            }
            else {
                $err .= "CC member $person does not have an account here\n";
            }
        }
    }

    # Handle keywords
    if ( defined( $bug_fields{'keywords'} ) ) {
        my %keywordseen;
        my $key_sth = $dbh->prepare(
            "INSERT INTO keywords 
                      (bug_id, keywordid) VALUES (?,?)"
        );
        foreach my $keyword ( split( /[\s,]+/, $bug_fields{'keywords'} )) {
            next unless $keyword;
1088 1089
            my $keyword_obj = new Bugzilla::Keyword({name => $keyword});
            if (!$keyword_obj) {
1090 1091 1092
                $err .= "Skipping unknown keyword: $keyword.\n";
                next;
            }
1093 1094 1095
            if (!$keywordseen{$keyword_obj->id}) {
                $key_sth->execute($id, $keyword_obj->id);
                $keywordseen{$keyword_obj->id} = 1;
1096 1097 1098 1099
            }
        }
    }

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
    # Insert values of custom multi-select fields. They have already
    # been validated.
    foreach my $custom_field (keys %multi_select_fields) {
        my $sth = $dbh->prepare("INSERT INTO bug_$custom_field
                                 (bug_id, value) VALUES (?, ?)");
        foreach my $value (@{$multi_select_fields{$custom_field}}) {
            $sth->execute($id, $value);
        }
    }

1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
    # Parse bug flags
    foreach my $bflag ( $bug->children('flag')) {
        next unless ( defined($bflag) );
        $err .= flag_handler(
            $bflag->{'att'}->{'name'},   $bflag->{'att'}->{'status'},
            $bflag->{'att'}->{'setter'}, $bflag->{'att'}->{'requestee'},
            $exporterid,                 $id,
            $comp_id,                    $prod_id,
            undef
        );
    }

    # Insert Attachments for the bug
    foreach my $att (@attachments) {
        if ($att eq "err"){
            $err .= "No attachment ID specified, dropping attachment\n";
            next;
        }
1128
        if (!$exporter->is_insider && $att->{'isprivate'}) {
1129 1130 1131 1132
            $err .= "Exporter not in insidergroup and attachment marked private.\n";
            $err .= "   Marking attachment public\n";
            $att->{'isprivate'} = 0;
        }
1133 1134 1135

        my $attacher_id = $att->{'attacher'} ? login_to_id($att->{'attacher'}) : undef;

1136
        $dbh->do("INSERT INTO attachments 
1137 1138 1139 1140
                 (bug_id, creation_ts, modification_time, filename, description,
                 mimetype, ispatch, isprivate, isobsolete, submitter_id) 
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            undef, $id, $att->{'date'}, $att->{'date'}, $att->{'filename'},
1141
            $att->{'desc'}, $att->{'ctype'}, $att->{'ispatch'},
1142
            $att->{'isprivate'}, $att->{'isobsolete'}, $attacher_id || $exporterid);
1143 1144 1145 1146 1147 1148 1149
        my $att_id   = $dbh->bz_last_key( 'attachments', 'attach_id' );
        my $att_data = $att->{'data'};
        my $sth = $dbh->prepare("INSERT INTO attach_data (id, thedata) 
                                 VALUES ($att_id, ?)" );
        trick_taint($att_data);
        $sth->bind_param( 1, $att_data, $dbh->BLOB_TYPE );
        $sth->execute();
1150

1151
        $comments .= "Imported an attachment (id=$att_id)\n";
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
        if (!$attacher_id) {
            if ($att->{'attacher'}) {
                $err .= "The original submitter of attachment $att_id was\n   ";
                $err .= $att->{'attacher'} . ", but he doesn't have an account here.\n";
            }
            else {
                $err .= "The original submitter of attachment $att_id is unknown.\n";
            }
            $err .= "   Reassigning to the person who moved it here: $exporter_login.\n";
        }
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178

        # Process attachment flags
        foreach my $aflag (@{ $att->{'flags'} }) {
            next unless defined($aflag) ;
            $err .= flag_handler(
                $aflag->{'name'},   $aflag->{'status'},
                $aflag->{'setter'}, $aflag->{'requestee'},
                $exporterid,        $id,
                $comp_id,           $prod_id,
                $att_id
            );
        }
    }

    # Clear the attachments array for the next bug
    @attachments = ();

1179
    # Insert comments and append any errors
1180
    my $worktime = $bug_fields{'actual_time'} || 0.0;
1181
    $worktime = 0.0 if (!$exporter->is_timetracker);
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
    $comments .= "\n$err\n" if $err;

    my $sth_comment =
      $dbh->prepare('INSERT INTO longdescs (bug_id, who, bug_when, isprivate,
                                            thetext, work_time)
                     VALUES (?, ?, ?, ?, ?, ?)');

    foreach my $c (@sorted_descs) {
        $sth_comment->execute($id, $c->{whoid} || $exporterid, $c->{bug_when},
                              $c->{isprivate}, $c->{thetext}, 0);
1192
    }
1193
    $sth_comment->execute($id, $exporterid, $timestamp, 0, $comments, $worktime);
1194
    Bugzilla::Bug->new($id)->_sync_fulltext('new_bug');
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205

    # Add this bug to each group of which its product is a member.
    my $sth_group = $dbh->prepare("INSERT INTO bug_group_map (bug_id, group_id) 
                         VALUES (?, ?)");
    foreach my $group_id ( keys %{ $product->group_controls } ) {
        if ($product->group_controls->{$group_id}->{'membercontrol'} != CONTROLMAPNA
            && $product->group_controls->{$group_id}->{'othercontrol'} != CONTROLMAPNA){
            $sth_group->execute( $id, $group_id );
        }
    }

1206
    $log .= "Bug ${url}$bug_fields{'bug_id'} ";
1207
    $log .= "imported as bug $id.\n";
1208
    $log .= $params->{"urlbase"} . "show_bug.cgi?id=$id\n\n";
1209 1210 1211 1212 1213 1214
    if ($err) {
        $log .= "The following problems were encountered while creating bug $id.\n";
        $log .= $err;
        $log .= "You may have to set certain fields in the new bug by hand.\n\n";
    }
    Debug( $log, OK_LEVEL );
1215
    push(@logs, $log);
1216
    Bugzilla::BugMail::Send( $id, { 'changer' => $exporter } ) if ($mail);
1217 1218 1219 1220

    # done with the xml data. Lets clear it from memory
    $twig->purge;

1221
}
1222

1223 1224 1225 1226 1227 1228
Debug( "Reading xml", DEBUG_LEVEL );

# Read STDIN in slurp mode. VERY dangerous, but we live on the wild side ;-)
local ($/);
$xml = <>;

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
# If there's anything except whitespace before <?xml then we guess it's a mail
# and MIME::Parser should parse it. Else don't.
if ($xml =~ m/\S.*<\?xml/s ) {

    # If the email was encoded (Mailer::MessageToMTA() does it when using UTF-8),
    # we have to decode it first, else the XML parsing will fail.
    my $parser = MIME::Parser->new;
    $parser->output_to_core(1);
    $parser->tmp_to_core(1);
    my $entity = $parser->parse_data($xml);
    my $bodyhandle = $entity->bodyhandle;
    $xml = $bodyhandle->as_string;

}

# remove everything in file before xml header
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
$xml =~ s/^.+(<\?xml version.+)$/$1/s;

Debug( "Parsing tree", DEBUG_LEVEL );
my $twig = XML::Twig->new(
    twig_handlers => {
        bug        => \&process_bug,
        attachment => \&process_attachment
    },
    start_tag_handlers => { bugzilla => \&init }
);
$twig->parse($xml);
my $root       = $twig->root;
my $maintainer = $root->{'att'}->{'maintainer'};
my $exporter   = $root->{'att'}->{'exporter'};
my $urlbase    = $root->{'att'}->{'urlbase'};
1260 1261 1262 1263

# It is time to email the result of the import.
my $log = join("\n\n", @logs);
$log .=  "\n\nImported $bugtotal bug(s) from $urlbase,\n  sent by $exporter.\n";
1264
my $subject =  "$bugtotal Bug(s) successfully moved from $urlbase to " 
1265
   . $params->{"urlbase"};
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
my @to = ($exporter, $maintainer);
MailMessage( $subject, $log, @to );

__END__

=head1 NAME

importxml - Import bugzilla bug data from xml.

=head1 SYNOPSIS

1277
 importxml.pl [options] [file ...]
1278 1279 1280

=head1 OPTIONS

1281
=over
1282 1283 1284

=item B<-?>

1285
Print a brief help message and exit.
1286 1287 1288

=item B<-v>

1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
Print error and debug information. Mulltiple -v increases verbosity

=item B<-m> B<--sendmail>

Send mail to exporter with a log of bugs imported and any errors.

=item B<--attach_path>

The path to the attachment files. (Required if encoding="filename"
is used for attachments.)

1300 1301 1302 1303 1304 1305 1306
=item B<--bug_page>

The page that links to the bug on top of urlbase. Its default value
is "show_bug.cgi?id=", which is what Bugzilla installations use.
You only need to pass this argument if you are importing bugs from
another bug tracking system.

1307 1308 1309 1310
=item B<--product=name>

The product to put the bug in if the product specified in the
XML doesn't exist.
1311

1312
=item B<--component=name>
1313

1314 1315
The component to put the bug in if the component specified in the
XML doesn't exist.
1316 1317 1318 1319

=back

=head1 DESCRIPTION
1320

1321 1322 1323 1324 1325 1326 1327 1328 1329
     This script is used to import bugs from another installation of bugzilla.
     It can be used in two ways.
     First using the move function of bugzilla
     on another system will send mail to an alias provided by
     the administrator of the target installation (you). Set up an alias
     similar to the one given below so this mail will be automatically 
     run by this script and imported into your database.  Run 'newaliases'
     after adding this alias to your aliases file. Make sure your sendmail
     installation is configured to allow mail aliases to execute code. 
1330

1331
     bugzilla-import: "|/usr/bin/perl /opt/bugzilla/importxml.pl --mail"
1332

1333 1334 1335 1336
     Second it can be run from the command line with any xml file from 
     STDIN that conforms to the bugzilla DTD. In this case you can pass 
     an argument to set whether you want to send the
     mail that will be sent to the exporter and maintainer normally.
1337

1338 1339 1340
     importxml.pl [options] bugsfile.xml

=cut