processmail 23.6 KB
Newer Older
1
#!/usr/bonsaitools/bin/perl -wT
2
# -*- Mode: perl; indent-tabs-mode: nil -*-
terry%netscape.com's avatar
terry%netscape.com committed
3
#
4 5 6 7 8 9 10 11 12 13
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
terry%netscape.com's avatar
terry%netscape.com committed
14
# The Original Code is the Bugzilla Bug Tracking System.
15
#
terry%netscape.com's avatar
terry%netscape.com committed
16
# The Initial Developer of the Original Code is Netscape Communications
17 18 19 20
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
21
# Contributor(s): Terry Weissman <terry@mozilla.org>,
22 23
#                 Bryce Nesbitt <bryce-mozilla@nextbus.com>
#                 Dan Mosedale <dmose@mozilla.org>
24
#                 Alan Raetz <al_raetz@yahoo.com>
25
#                 Jacob Steenhagen <jake@actex.net>
26
#
27

28 29
use diagnostics;
use strict;
30
use lib ".";
terry%netscape.com's avatar
terry%netscape.com committed
31

32
require "globals.pl";
terry%netscape.com's avatar
terry%netscape.com committed
33

34 35
use RelationSet;

36 37 38 39 40 41 42

# Shut up misguided -w warnings about "used only once".
sub processmail_sillyness {
    my $zz;
    $zz = $::db;
}

43
$| = 1;
terry%netscape.com's avatar
terry%netscape.com committed
44

45 46
umask(0);

47
my $nametoexclude = "";
48
my %nomail;
49

50 51 52 53 54
my @excludedAddresses = ();

# disable email flag for offline debugging work
my $enableSendMail = 1;

55 56 57 58 59
my %force;
@{$force{'QAcontact'}} = ();
@{$force{'Owner'}} = ();
@{$force{'Reporter'}} = ();
@{$force{'CClist'}} = ();
60
@{$force{'Voter'}} = ();
61

terry%netscape.com's avatar
terry%netscape.com committed
62

63
my %seen;
64 65 66 67 68 69
my @sentlist;

sub FormatTriple {
    my ($a, $b, $c) = (@_);
    $^A = "";
    my $temp = formline << 'END', $a, $b, $c;
70
^>>>>>>>>>>>>>>>>>>|^<<<<<<<<<<<<<<<<<<<<<<<<<<<|^<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
END
    ; # This semicolon appeases my emacs editor macros. :-)
    return $^A;
}
    
sub FormatDouble {
    my ($a, $b) = (@_);
    $a .= ":";
    $^A = "";
    my $temp = formline << 'END', $a, $b;
^>>>>>>>>>>>>>>>>>> ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
END
    ; # This semicolon appeases my emacs editor macros. :-)
    return $^A;
}
    

88
sub ProcessOneBug {
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    my ($id) = (@_);

    my @headerlist;
    my %values;
    my %defmailhead;
    my %fielddescription;

    my $msg = "";

    SendSQL("SELECT name, description, mailhead FROM fielddefs " .
            "ORDER BY sortkey");
    while (MoreSQLData()) {
        my ($field, $description, $mailhead) = (FetchSQLData());
        push(@headerlist, $field);
        $defmailhead{$field} = $mailhead;
        $fielddescription{$field} = $description;
    }
    SendSQL("SELECT " . join(',', @::log_columns) . ", lastdiffed, now() " .
            "FROM bugs WHERE bug_id = $id");
    my @row = FetchSQLData();
    foreach my $i (@::log_columns) {
        $values{$i} = shift(@row);
    }
    my ($start, $end) = (@row);
113 114 115 116
    # $start and $end are considered safe because users can't touch them
    $start = detaint_string($start);
    $end = detaint_string($end);

117 118 119
    my $ccSet = new RelationSet();
    $ccSet->mergeFromDB("SELECT who FROM cc WHERE bug_id = $id");
    $values{'cc'} = $ccSet->toString();
120 121 122 123 124 125 126
    
    my @voterlist;
    SendSQL("SELECT profiles.login_name FROM votes, profiles " .
            "WHERE votes.bug_id = $id AND profiles.userid = votes.who");
    while (MoreSQLData()) {
        push(@voterlist, FetchOneColumn());
    }
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

    $values{'assigned_to'} = DBID_to_name($values{'assigned_to'});
    $values{'reporter'} = DBID_to_name($values{'reporter'});
    if ($values{'qa_contact'}) {
        $values{'qa_contact'} = DBID_to_name($values{'qa_contact'});
    }

    my @diffs;


    SendSQL("SELECT profiles.login_name, fielddefs.description, " .
            "       bug_when, oldvalue, newvalue " .
            "FROM bugs_activity, fielddefs, profiles " .
            "WHERE bug_id = $id " .
            "  AND fielddefs.fieldid = bugs_activity.fieldid " .
            "  AND profiles.userid = who " .
            "  AND bug_when > '$start' " .
            "  AND bug_when <= '$end' " .
            "ORDER BY bug_when"
            );

    while (MoreSQLData()) {
        my @row = FetchSQLData();
        push(@diffs, \@row);
    }

    my $difftext = "";
    my $lastwho = "";
    foreach my $ref (@diffs) {
        my ($who, $what, $when, $old, $new) = (@$ref);
        if ($who ne $lastwho) {
            $lastwho = $who;
159
            $difftext .= "\n$who" . Param('emailsuffix') . " changed:\n\n";
160 161 162 163 164 165 166 167 168
            $difftext .= FormatTriple("What    ", "Old Value", "New Value");
            $difftext .= ('-' x 76) . "\n";
        }
        $difftext .= FormatTriple($what, $old, $new);
    }

    $difftext = trim($difftext);


169 170 171 172 173 174 175 176 177 178 179 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 208 209 210 211 212 213 214 215 216
    my $deptext = "";

    my $resid = 

    SendSQL("SELECT bugs_activity.bug_id, fielddefs.name, " .
            "       oldvalue, newvalue " .
            "FROM bugs_activity, dependencies, fielddefs ".
            "WHERE bugs_activity.bug_id = dependencies.dependson " .
            "  AND dependencies.blocked = $id " .
            "  AND fielddefs.fieldid = bugs_activity.fieldid" .
            "  AND (fielddefs.name = 'bug_status' " .
            "    OR fielddefs.name = 'resolution') " .
            "  AND bug_when > '$start' " .
            "  AND bug_when <= '$end' " .
            "ORDER BY bug_when, bug_id");
    
    my $thisdiff = "";
    my $lastbug = "";
    my $interestingchange = 0;
    while (MoreSQLData()) {
        my ($bug, $what, $old, $new) = (FetchSQLData());
        if ($bug ne $lastbug) {
            if ($interestingchange) {
                $deptext .= $thisdiff;
            }
            $lastbug = $bug;
            $thisdiff =
                "\nThis bug depends on bug $bug, which changed state:\n\n";
            $thisdiff .= FormatTriple("What    ", "Old Value", "New Value");
            $thisdiff .= ('-' x 76) . "\n";
            $interestingchange = 0;
        }
        $thisdiff .= FormatTriple($fielddescription{$what}, $old, $new);
        if ($what eq 'bug_status' && IsOpenedState($old) ne IsOpenedState($new)) {
            $interestingchange = 1;
        }
    }
    if ($interestingchange) {
        $deptext .= $thisdiff;
    }

    $deptext = trim($deptext);

    if ($deptext) {
        $difftext = trim($difftext . "\n\n" . $deptext);
    }


217
    my $newcomments = GetLongDescriptionAsText($id, $start, $end);
218

219 220 221 222
    #
    # Start of email filtering code
    #
    my $count = 0;
223

224 225
    my @currentEmailAttributes = getEmailAttributes($newcomments, @diffs);
    my (@assigned_toList,@reporterList,@qa_contactList,@ccList) = ();
226

227 228 229
    #open(LOG, ">>/tmp/maillog");
    #print LOG "\nBug ID: $id   CurrentEmailAttributes:";
    #print LOG join(',', @currentEmailAttributes) . "\n";
230

231
    @excludedAddresses = (); # zero out global list 
232

233 234 235 236 237 238 239 240 241 242 243 244 245
    @assigned_toList = filterEmailGroup('Owner',
                                        \@currentEmailAttributes,
                                        $values{'assigned_to'});
    @reporterList = filterEmailGroup('Reporter', 
                                     \@currentEmailAttributes,
                                     $values{'reporter'});
    if (Param('useqacontact') && $values{'qa_contact'}) {
        @qa_contactList = filterEmailGroup('QAcontact',
                                           \@currentEmailAttributes,
                                           $values{'qa_contact'});
    } else { 
        @qa_contactList = (); 
    }
246

247 248
    @ccList = filterEmailGroup('CClist', \@currentEmailAttributes,
                               $values{'cc'});
249

250 251
    @voterlist = filterEmailGroup('Voter', \@currentEmailAttributes,
                                  join(',',@voterlist));
252

253 254
    my @emailList = (@assigned_toList, @reporterList, 
                     @qa_contactList, @ccList, @voterlist);
255

256 257 258 259 260 261 262
    # only need one entry per person
    my @allEmail = ();
    my %AlreadySeen = ();
    foreach my $person (@emailList) {
        if ( !($AlreadySeen{$person}) ) {
            push(@allEmail,$person);
            $AlreadySeen{$person}++;
263
        }
264
    }
265

266 267 268 269
    #print LOG "\nbug $id email sent: " . join(',', @allEmail) . "\n";
        
    @excludedAddresses = filterExcludeList(\@excludedAddresses,
                                           \@allEmail);
270

271 272 273 274 275 276 277 278 279 280 281 282 283 284
    # print LOG "excluded: " . join(',',@excludedAddresses) . "\n\n";

    foreach my $person ( @allEmail ) {
        $count++;
        if ( !defined(NewProcessOnePerson($person, $count, \@headerlist,
                                          \%values, \%defmailhead, 
                                          \%fielddescription, $difftext, 
                                          $newcomments, $start, $id))) {

            # if a value is not returned, this means that the person
            # was not sent mail.  add them to the excludedAddresses list.
            # it will be filtered later for dups.
            #
            push @excludedAddresses, $person;
285 286

        }
287
    }
288

289

290 291
    SendSQL("UPDATE bugs SET lastdiffed = '$end', delta_ts = delta_ts " .
            "WHERE bug_id = $id");
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

    # Filter the exclude list for dupes one last time
    @excludedAddresses = filterExcludeList(\@excludedAddresses,
                                           \@sentlist);
    if (@sentlist) {
        print "<b>Email sent to:</b> " . join(", ", @sentlist) ."<br>\n";
    } else {
        print "<b>Email sent to:</b> no one<br>\n";
    }

    if (@excludedAddresses) {
        print "<b>Excluding:</b> " . join(", ", @excludedAddresses) . "\n";
    }

    print "<br><center>If you wish to tweak the kinds of mail Bugzilla sends you, you can";
    print " <a href=\"userprefs.cgi?bank=diffs\">change your preferences</a></center>\n";

309
}
310

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
# When one person is in different fields on one bug, they may be
# excluded from email because of one relationship to the bug (eg
# they're the QA contact) but included because of another (eg they
# also reported the bug).  Inclusion takes precedence, so this
# function looks for and removes any users from the exclude list who
# are also on the include list.  Additionally, it removes duplicate
# entries from the exclude list.  
#
# Arguments are the exclude list and the include list; the cleaned up
# exclude list is returned.
#
sub filterExcludeList ($$) {

    if ($#_ != 1) {
        die ("filterExcludeList called with wrong number of args");
    }

    my ($refExcluded, $refAll) = @_;

    my @excludedAddrs = @$refExcluded;
    my @allEmail = @$refAll;
    my @tmpList = @excludedAddrs;
    my (@result,@uniqueResult) = ();
    my %alreadySeen;

    foreach my $excluded (@tmpList) {

        push (@result,$excluded);
        foreach my $included (@allEmail) {

            # match found, so we remove the entry
            if ($included eq $excluded) {
                pop(@result);
344
                last;
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
            }
        }
    }

    # only need one entry per person
    foreach my $person (@result) {
        if ( !($alreadySeen{$person}) ) {
            push(@uniqueResult,$person);
            $alreadySeen{$person}++;
        }
    }

    return @uniqueResult;
}

# if the Status was changed to Resolved or Verified
#       set the Resolved flag
#
# else if Severity, Status OR Priority fields have any change
#       set the Status flag
#
# else if Keywords has changed
#       set the Keywords flag
#
# else if CC has changed
#       set the CC flag
#
# if the Comments field shows an attachment
#       set the Attachment flag
#
# else if Comments exist
#       set the Comments flag
#
# if no flags are set and there was some other field change
#       set the Status flag
#
sub getEmailAttributes ($@) {
    
    my ($commentField,@fieldDiffs) = @_;
    my (@flags,@uniqueFlags,%alreadySeen) = ();
    
    foreach my $ref (@fieldDiffs) {
        my ($who, $fieldName, $when, $old, $new) = (@$ref);
        
        #print qq{field: $fieldName $new<br>};
        
        # the STATUS will be flagged for Severity, Status and 
        # Priority changes
        #
        if ( $fieldName eq 'Status') {
            if ($new eq 'RESOLVED' || $new eq 'VERIFIED') {
                push (@flags, 'Resolved');
            }
        }
        elsif ( $fieldName eq 'Severity' || $fieldName eq 'Status' ||
                $fieldName eq 'Priority' ) {
            push (@flags, 'Status');
        } elsif ( $fieldName eq 'Keywords') {
            push (@flags, 'Keywords');
        } elsif ( $fieldName eq 'CC') {
            push (@flags, 'CC');
        }
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

        # These next few lines are for finding out who's been added
        # to the Owner, QA, CC, etc. fields.  It does not effect
        # the @flags array at all, but is run here because it does
        # effect filtering later and we're already in the loop.
        if ($fieldName eq 'Owner') {
            push (@{$force{'Owner'}}, $new);
        } elsif ($fieldName eq 'QAContact') {
           push (@{$force{'QAContact'}}, $new);
        } elsif ($fieldName eq 'CC') {
            my @oldVal = split (/,/, $old);
            my @newVal = split (/,/, $new);
            my @added = filterExcludeList(\@newVal, \@oldVal);
            push (@{$force{'CClist'}}, @added);
        }
422 423 424 425 426
    }
    
    if ( $commentField =~ /Created an attachment \(/ ) {
        push (@flags, 'Attachments');
    }
427
    elsif ( ($commentField ne '') && !(scalar(@flags) == 1 && $flags[0] eq 'Resolved')) {
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
        push (@flags, 'Comments');
    }
    
    # default fallthrough for any unflagged change is 'Other'
    if ( @flags == 0 && @fieldDiffs != 0 ) {
        push (@flags, 'Other');
    }
    
    # only need one flag per attribute type
    foreach my $flag (@flags) {
        if ( !($alreadySeen{$flag}) ) {
            push(@uniqueFlags,$flag);
            $alreadySeen{$flag}++;
        }
    }
    #print "\nEmail Attributes: ", join(' ,',@uniqueFlags), "<br>\n";
    
    # catch-all default, just in case the above logic is faulty
    if ( @uniqueFlags == 0) {
        push (@uniqueFlags, 'Comments');
    }
    
    return @uniqueFlags;
}

sub filterEmailGroup ($$$) {
    
    my ($emailGroup,$refAttributes,$emailList) = @_;
    my @emailAttributes = @$refAttributes;
    my @emailList = split(/,/,$emailList);
    my @filteredList = ();
    
460 461 462 463 464

    # the force list for this email group needs to be checked as well
    #
    push @emailList, @{$force{$emailGroup}};

465 466 467 468 469 470 471 472
    # Check this user for any watchers... doing this here allows them to inhert the
    # relationship to the bug of the person they are watching (if the person they
    # are watching is an owner, their mail is filtered as if they were the owner).
    if (Param("supportwatchers")) {
	my @watchers;
	foreach my $person(@emailList) {
	    my $personId = DBname_to_id($person);
	    SendSQL("SELECT watcher FROM watch WHERE watched = $personId");
473 474 475 476 477
	    while(MoreSQLData()) {
	        my ($watcher) = FetchSQLData();
	        if ($watcher) {
	            push (@watchers, DBID_to_name($watcher));
	        }
478 479 480 481 482 483
	    }
	}
	push(@emailList, @watchers);
    }


484 485 486 487 488 489
    foreach my $person (@emailList) {
        
        my $lastCount = @filteredList;

        if ( $person eq '' ) { next; }

490
        my $userid = DBname_to_id($person);
491

492
        if ( ! $userid ) {
493 494 495 496
            push(@filteredList,$person);
            next;
        }
        
497
        SendSQL("SELECT emailflags FROM profiles WHERE " .
498
                "userid = $userid" );
499

500
        my ($userFlagString) = FetchSQLData();
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
        
        # If the sender doesn't want email, exclude them from list
        
        if (lc($person) eq $nametoexclude) {
            
            if ( defined ($userFlagString) && 
                 $userFlagString =~ /ExcludeSelf\~on/ ) {
                
                push (@excludedAddresses,$person);
                next;
            }
        }
        
        # if the users database entry is empty, send them all email
        # by default (they have not accessed userprefs.cgi recently).
        
        if ( !defined($userFlagString) || !($userFlagString =~ /email/) ) {
            push(@filteredList,$person);
        }
        else {
521 522 523 524 525 526 527 528

            # the 255 param is here, because without a third param, 
            # split will trim any trailing null fields, which causes perl 
            # to eject lots of warnings.  any suitably large number would 
            # do.
                
            my %userFlags = split(/~/, $userFlagString, 255);

529 530 531
            # The default condition is to send each person email.
            # If we match the email attribute with the user flag, and
            # they do not want email, then remove them from the list.
532 533 534

            push(@filteredList,$person);            

535 536
            my $detectedOn = 0;
            
537 538 539 540
            foreach my $attribute (@emailAttributes) {

                my $matchName = 'email' . $emailGroup . $attribute;
                
541 542 543 544 545 546 547 548 549 550
                # **** Kludge... quick and dirty fix for 2.12
                #      http://bugzilla.mozilla.org/show_bug.cgi?id=73665
                # If this pref is new (it's been added since this user
                # last updated their filtering prefs, $userFlags{$matchName}
                # will be undefined.  This should be considered a match
                # so that new prefs will default to 'on'
                if (!defined($userFlags{$matchName})) {
                    $detectedOn = 1;
                }

551 552
                while ((my $flagName, my $flagValue) = each %userFlags) {
                    
553 554 555
                    if ($flagName !~ /$emailGroup/) { 
                        next; 
                    }
556

557 558 559 560
                    if ($flagName eq $matchName){
                        if ($flagValue eq 'on') {
                            $detectedOn = 1;
                        }
561
                    }
562 563 564 565 566

                } # for each userFlag

            } # for each email attribute

567 568 569 570 571 572 573
            # if the current flag hasn't been detected on at least once, 
            # this person gets filtered from this group.
            #
            if (! $detectedOn) {
                pop(@filteredList);
            }

574 575 576 577 578 579
            # check to see if the person was added to or removed from  
            # this email group.
            # Note: This was originally written as only removed from
            # and was rewritten to be Added/Removed, but for simplicity
            # sake, the name "Removeme" wasn't changed.
            # http://bugzilla.mozilla.org/show_bug.cgi?id=71912 
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601

            if ( grep ($_ eq $person, @{$force{$emailGroup}} ) ) {

                # if so, see if they want mail about that
                #
                if ( $userFlags{'email' . $emailGroup . 'Removeme'} eq 'on' ) {

                    # we definitely want mail sent to this person, since
                    # inclusion on a mail takes precedence over the previous
                    # exclusion

                    # have they been filtered for some other reason?
                    #
                    if (@filteredList == $lastCount) {
                        
                        # if so, put them back
                        #
                        push (@filteredList, $person);
                    }
                }
            }

602 603
        } # if $userFlagString is valid

604 605 606
        # has the person been moved off the filtered list?
        #
        if (@filteredList == $lastCount ) {
607

608 609
            # mark them as excluded
            #
610
            push (@excludedAddresses,$person);
611 612
        } 
            
613 614 615 616 617
    } # for each person

    return @filteredList;
}

618
sub NewProcessOnePerson ($$$$$$$$$$) {
619
    my ($person, $count, $hlRef, $valueRef, $dmhRef, $fdRef, $difftext, 
620
        $newcomments, $start, $id) = @_;
621

622 623 624 625
    my %values = %$valueRef;
    my @headerlist = @$hlRef;
    my %defmailhead = %$dmhRef;
    my %fielddescription = %$fdRef;
626

627 628 629
    if ($seen{$person}) {
      return;
    }
630 631 632 633

    if ($nomail{$person}) {
      return;
    }
634
        
635 636 637 638 639 640
    # Sanitize $values{'groupset'}
    if ($values{'groupset'} =~ m/(\d+)/) {
        $values{'groupset'} = $1;
    } else {
        $values{'groupset'} = 0;
    }
641
    SendSQL("SELECT userid, groupset & $values{'groupset'} " .
642
            "FROM profiles WHERE login_name = " . SqlQuote($person));
643
    my ($userid, $groupset) =  (FetchSQLData());
644 645
    
    $seen{$person} = 1;
646 647


648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    # if this person doesn't have permission to see info on this bug, 
    # return.
    #
    # XXX - I _think_ this currently means that if a bug is suddenly given
    # more restrictive permissions, people without those permissions won't
    # see the action of restricting the bug itself; the bug will just 
    # quietly disappear from their radar.
    #
    if ($groupset ne $values{'groupset'}) {
      return;
    }
    
    my %mailhead = %defmailhead;
    
    my $head = "";
    
    foreach my $f (@headerlist) {
      if ($mailhead{$f}) {
        my $value = $values{$f};
667 668
        # If there isn't anything to show, don't include this header
        if (! $value) {
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
          next;
        }
        my $desc = $fielddescription{$f};
        $head .= FormatDouble($desc, $value);
      }
    }
    
    if ($difftext eq "" && $newcomments eq "") {
      # Whoops, no differences!
      return;
    }
    
    my $isnew = ($start !~ m/[1-9]/);
    
    my %substs;
684 685

    $person .= Param('emailsuffix');
686 687 688 689 690
# 09/13/2000 cyeh@bluemartini.com
# If a bug is changed, don't put the word "Changed" in the subject mail
# since if the bug didn't change, you wouldn't be getting mail
# in the first place! see http://bugzilla.mozilla.org/show_bug.cgi?id=29820 
# for details.
691
    $substs{"neworchanged"} = $isnew ? 'New: ' : '';
692 693 694 695 696 697 698 699 700 701 702 703 704
    $substs{"to"} = $person;
    $substs{"cc"} = '';
    $substs{"bugid"} = $id;
    if ($isnew) {
      $substs{"diffs"} = $head . "\n\n" . $newcomments;
    } else {
      $substs{"diffs"} = $difftext . "\n\n" . $newcomments;
    }
    $substs{"summary"} = $values{'short_desc'};
    
    my $template = Param("newchangedmail");
    
    my $msg = PerformSubsts($template, \%substs);
705 706 707

    my $sendmailparam = "-ODeliveryMode=deferred";
    if (Param("sendmailnow")) {
708
       $sendmailparam = "";
709
    }
710 711

    if ($enableSendMail == 1) {
712
    open(SENDMAIL, "|/usr/lib/sendmail $sendmailparam -t") ||
713 714 715 716
      die "Can't open sendmail";
    
    print SENDMAIL trim($msg) . "\n";
    close SENDMAIL;
717
    }
718
    push(@sentlist, $person);
719
    return 1;
720 721
}

722 723 724
# Code starts here

ConnectToDatabase();
725 726 727
# Set Taint mode for the SQL
$::db->{Taint} = 1;
# ^^^ Taint mode is still a work in progress...
728
GetVersionTable();
729 730 731

if (open(FID, "<data/nomail")) {
    while (<FID>) {
732
        $nomail{trim($_)} = 1;
733 734 735 736
    }
    close FID;
}

737
if ($#ARGV >= 0 && $ARGV[0] eq "regenerate") {
738
    print "Regenerating is no longer required or supported\n";
739 740 741
    exit;
}

742
if ($#ARGV >= 0 && $ARGV[0] eq "-forcecc") {
743 744
    shift(@ARGV);
    foreach my $i (split(/,/, shift(@ARGV))) {
745
        push(@{$force{'CClist'}}, trim($i));
746 747 748
    }
}

749 750 751 752 753 754 755 756 757 758
if ($#ARGV >= 0 && $ARGV[0] eq "-forceowner") {
    shift(@ARGV);
    @{$force{'Owner'}} = (trim(shift(@ARGV)));
}

if ($#ARGV >= 0 && $ARGV[0] eq "-forceqacontact") {
    shift(@ARGV);
    @{$force{'QAcontact'}} = (trim(shift(@ARGV)));
}

759
if (($#ARGV < 0) || ($#ARGV > 1)) {
760 761
    print "Usage:\n processmail {bugid} {nametoexclude} " . 
      "[-forcecc list,of,users]\n             [-forceowner name] " .
762
      "[-forceqacontact name]\nor\n" .
763
      " processmail rescanall\n";
764 765 766
    exit;
}

767
if ($#ARGV == 1) {
768
    $nametoexclude = lc($ARGV[1]);
769 770
}

771 772
if ($ARGV[0] eq "rescanall") {
    print "<br> Collecting bug ids...\n";
773
    SendSQL("select bug_id from bugs where to_days(now()) - to_days(delta_ts) <= 2 order by bug_id");
774 775 776 777 778 779 780 781 782 783
    my @list;
    while (my @row = FetchSQLData()) {
        push @list, $row[0];
    }
    foreach my $id (@list) {
        $ARGV[0] = $id;
        print "<br> Doing bug $id\n";
        ProcessOneBug($ARGV[0]);
    }
} else {
784 785 786 787 788 789 790 791
    my $bugnum;
    if ($ARGV[0] =~ m/^([1-9][0-9]*)$/) {
        $bugnum = $1;
    } else {
        print "Error calling processmail (bug id is not an integer)<br>\n";
        exit;
    }
    ProcessOneBug($bugnum);
792
}
793

794
exit;