processmail 28.3 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
#                 Matthew Tuck <matty@chariot.net.au>
27

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

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

33 34
use RelationSet;

35 36 37 38

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

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

44 45
umask(0);

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

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

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

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

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

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

sub FormatTriple {
    my ($a, $b, $c) = (@_);
    $^A = "";
    my $temp = formline << 'END', $a, $b, $c;
69
^>>>>>>>>>>>>>>>>>>|^<<<<<<<<<<<<<<<<<<<<<<<<<<<|^<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
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;
}
    

87
sub ProcessOneBug {
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    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);
112
    # $start and $end are considered safe because users can't touch them
113 114
    trick_taint($start);
    trick_taint($end);
115

116 117 118
    my $ccSet = new RelationSet();
    $ccSet->mergeFromDB("SELECT who FROM cc WHERE bug_id = $id");
    $values{'cc'} = $ccSet->toString();
119
    
120
    my @voterList;
121 122 123
    SendSQL("SELECT profiles.login_name FROM votes, profiles " .
            "WHERE votes.bug_id = $id AND profiles.userid = votes.who");
    while (MoreSQLData()) {
124
        push(@voterList, FetchOneColumn());
125
    }
126 127 128 129 130 131 132 133 134 135 136

    $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, " .
137
            "       bug_when, removed, added, attach_id " .
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
            "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) {
155
        my ($who, $what, $when, $old, $new, $attachid) = (@$ref);
156 157
        if ($who ne $lastwho) {
            $lastwho = $who;
158
            $difftext .= "\n$who" . Param('emailsuffix') . " changed:\n\n";
159
            $difftext .= FormatTriple("What    ", "Removed", "Added");
160 161
            $difftext .= ('-' x 76) . "\n";
        }
162
        $what =~ s/^Attachment/Attachment #$attachid/ if $attachid;
163 164 165 166 167 168
        $difftext .= FormatTriple($what, $old, $new);
    }

    $difftext = trim($difftext);


169 170 171 172
    my $deptext = "";

    my $resid = 

173
    SendSQL("SELECT bugs_activity.bug_id, bugs.short_desc, fielddefs.name, " .
174
            "       removed, added " .
175
            "FROM bugs_activity, bugs, dependencies, fielddefs ".
176
            "WHERE bugs_activity.bug_id = dependencies.dependson " .
177
            "  AND bugs.bug_id = bugs_activity.bug_id ".
178 179 180 181 182 183 184 185 186 187 188
            "  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;
189 190
    my $depbug = 0;
    my @depbugs;
191
    while (MoreSQLData()) {
192 193 194
        my ($summary, $what, $old, $new);
        ($depbug, $summary, $what, $old, $new) = (FetchSQLData());
        if ($depbug ne $lastbug) {
195 196 197
            if ($interestingchange) {
                $deptext .= $thisdiff;
            }
198
            $lastbug = $depbug;
199
            my $urlbase = Param("urlbase");
200
            $thisdiff =
201 202 203
              "\nBug $id depends on bug $depbug, which changed state.\n\n" . 
              "Bug $depbug Summary: $summary\n" . 
              "${urlbase}show_bug.cgi?id=$depbug\n\n"; 
204 205 206 207 208 209 210 211
            $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;
        }
212 213
        
        push(@depbugs, $depbug);
214
    }
215
    
216 217 218 219 220 221 222 223 224 225 226
    if ($interestingchange) {
        $deptext .= $thisdiff;
    }

    $deptext = trim($deptext);

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


227
    my ($newcomments, $anyprivate) = GetLongDescriptionAsText($id, $start, $end);
228

229 230 231 232
    #
    # Start of email filtering code
    #
    my $count = 0;
233

234 235 236 237
    # Get a list of the reasons a user might receive email about the bug.
    my @currentEmailAttributes = 
      getEmailAttributes(\%values, \@diffs, $newcomments);
    
238
    my (@assigned_toList,@reporterList,@qa_contactList,@ccList) = ();
239

240 241 242
    #open(LOG, ">>/tmp/maillog");
    #print LOG "\nBug ID: $id   CurrentEmailAttributes:";
    #print LOG join(',', @currentEmailAttributes) . "\n";
243

244
    @excludedAddresses = (); # zero out global list 
245

246 247 248 249 250 251 252 253 254 255 256 257 258
    @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 = (); 
    }
259

260 261
    @ccList = filterEmailGroup('CClist', \@currentEmailAttributes,
                               $values{'cc'});
262

263 264
    @voterList = filterEmailGroup('Voter', \@currentEmailAttributes,
                                  join(',',@voterList));
265

266
    my @emailList = (@assigned_toList, @reporterList, 
267
                     @qa_contactList, @ccList, @voterList);
268

269 270 271
    # only need one entry per person
    my @allEmail = ();
    my %AlreadySeen = ();
272
    my $checkperson = "";
273
    foreach my $person (@emailList) {
274 275 276 277
        # don't modify the original so it sends out with the right case
        # based on who came first.
        $checkperson = lc($person);
        if ( !($AlreadySeen{$checkperson}) ) {
278
            push(@allEmail,$person);
279
            $AlreadySeen{$checkperson}++;
280
        }
281
    }
282

283 284 285 286
    #print LOG "\nbug $id email sent: " . join(',', @allEmail) . "\n";
        
    @excludedAddresses = filterExcludeList(\@excludedAddresses,
                                           \@allEmail);
287

288 289 290
    # print LOG "excluded: " . join(',',@excludedAddresses) . "\n\n";

    foreach my $person ( @allEmail ) {
291 292
        my @reasons;

293
        $count++;
294 295 296 297 298 299 300

        push(@reasons, 'AssignedTo') if lsearch(\@assigned_toList, $person) != -1;
        push(@reasons, 'Reporter') if lsearch(\@reporterList, $person) != -1;
        push(@reasons, 'QAContact') if lsearch(\@qa_contactList, $person) != -1;
        push(@reasons, 'CC') if lsearch(\@ccList, $person) != -1;
        push(@reasons, 'Voter') if lsearch(\@voterList, $person) != -1;

301
        if ( !defined(NewProcessOnePerson($person, $count, \@headerlist,
302 303
                                          \@reasons, \%values,
                                          \%defmailhead, 
304
                                          \%fielddescription, $difftext, 
305 306
                                          $newcomments, $anyprivate, 
                                          $start, $id, 
307 308
                                          \@depbugs))) 
        {
309 310 311 312 313 314

            # 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;
315 316

        }
317
    }
318

319

320 321
    SendSQL("UPDATE bugs SET lastdiffed = '$end', delta_ts = delta_ts " .
            "WHERE bug_id = $id");
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336

    # 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";
337
    print " <a href=\"userprefs.cgi?tab=email\">change your preferences</a></center>\n";
338

339
}
340

341 342 343 344 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
# 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
372
            if (lc($included) eq lc($excluded)) {
373
                pop(@result);
374
                last;
375 376 377 378 379
            }
        }
    }

    # only need one entry per person
380 381
    my $checkperson = "";

382
    foreach my $person (@result) {
383 384
        $checkperson = lc($person);
        if ( !($alreadySeen{$checkperson}) ) {
385
            push(@uniqueResult,$person);
386
            $alreadySeen{$checkperson}++;
387 388 389 390 391 392 393 394 395
        }
    }

    return @uniqueResult;
}

# if the Status was changed to Resolved or Verified
#       set the Resolved flag
#
396
# else if Severity, Status, Target Milestone OR Priority fields have any change
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
#       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
#
414
sub getEmailAttributes (\%\@$) {
415
    
416
    my ($bug, $fieldDiffs, $commentField) = @_;
417 418
    my (@flags,@uniqueFlags,%alreadySeen) = ();
    
419 420 421 422 423 424
    # Add a flag if the status of the bug is "unconfirmed".
    if ($bug->{'bug_status'} eq $::unconfirmedstate) {
        push (@flags, 'Unconfirmed')
    };
    
    foreach my $ref (@$fieldDiffs) {
425 426 427 428
        my ($who, $fieldName, $when, $old, $new) = (@$ref);
        
        #print qq{field: $fieldName $new<br>};
        
429
        # the STATUS will be flagged for Severity, Status, Target Milestone and 
430 431
        # Priority changes
        #
432 433
        if ( $fieldName eq 'Status' && ($new eq 'RESOLVED' || $new eq 'VERIFIED')) {
            push (@flags, 'Resolved');
434 435
        }
        elsif ( $fieldName eq 'Severity' || $fieldName eq 'Status' ||
436
                $fieldName eq 'Priority' || $fieldName eq 'Target Milestone') {
437 438 439 440 441 442
            push (@flags, 'Status');
        } elsif ( $fieldName eq 'Keywords') {
            push (@flags, 'Keywords');
        } elsif ( $fieldName eq 'CC') {
            push (@flags, 'CC');
        }
443 444 445 446 447 448 449 450 451 452

        # 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') {
453
            my @added = split (/[ ,]/, $new);
454 455
            push (@{$force{'CClist'}}, @added);
        }
456 457 458 459 460
    }
    
    if ( $commentField =~ /Created an attachment \(/ ) {
        push (@flags, 'Attachments');
    }
461
    elsif ( ($commentField ne '') && !(scalar(@flags) == 1 && $flags[0] eq 'Resolved')) {
462 463 464 465
        push (@flags, 'Comments');
    }
    
    # default fallthrough for any unflagged change is 'Other'
466
    if ( @flags == 0 && @$fieldDiffs != 0 ) {
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
        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 ($$$) {
488 489 490 491
    # This function figures out who should receive email about the bug
    # based on the user's role with regard to the bug (assignee, reporter 
    # etc.), the changes that occurred (new comments, attachment added, 
    # status changed etc.) and the user's email preferences.
492
    
493 494 495
    # Returns a filtered list of those users who would receive email
    # about these changes, and adds the names of those users who would
    # not receive email about them to the global @excludedAddresses list.
496
    
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
    my ($role, $reasons, $users) = @_;
    
    # Make a list of users to filter.
    my @users = split( /,/ , $users );
    
    # Treat users who are in the process of being removed from this role
    # as if they were still in it.
    push @users, @{$force{$role}};

    # If this installation supports user watching, add to the list those
    # users who are watching other users already on the list.  By doing
    # this here, we allow watchers to inherit the roles of the people 
    # they are watching while at the same time filtering email for watchers
    # based on their own preferences.
    if (Param("supportwatchers") && scalar(@users)) {
        # Convert the unfiltered list of users into an SQL-quoted, 
        # comma-separated string suitable for use in an SQL query.
        my $watched = join(",", map(SqlQuote($_), @users));
        SendSQL("SELECT watchers.login_name 
                   FROM watch, profiles AS watchers, profiles AS watched
                  WHERE watched.login_name IN ($watched)
                    AND watched.userid = watch.watched
                    AND watch.watcher = watchers.userid");
        push (@users, FetchOneColumn()) while MoreSQLData();
521 522
    }

523 524
    # Initialize the list of recipients.
    my @recipients = ();
525

526 527
    USER: foreach my $user (@users) {
        next unless $user;
528
        
529 530 531 532 533 534 535 536
        # Get the user's unique ID, and if the user is not registered
        # (no idea why unregistered users should even be on this list,
        # but the code that was here before I re-wrote it allows this),
        # then we do not have any preferences for them, so assume the
        # default preference to receive all mail for any reason.
        my $userid = DBname_to_id($user);
        if (!$userid) {
            push(@recipients, $user);
537 538 539
            next;
        }
        
540 541 542
        # Get the user's email preferences from the database.
        SendSQL("SELECT emailflags FROM profiles WHERE userid = $userid");
        my $prefs = FetchOneColumn();
543
        
544 545 546 547 548 549 550 551
        # If the user's preferences are empty, assume the default preference 
        # to receive all mail.  This happens when the installation upgraded
        # from a version of Bugzilla without email preferences to one with
        # them, but the user has not set their preferences yet.
        if (!defined($prefs) || $prefs !~ /email/) {
            push(@recipients, $user);
            next;
        }
552
        
553 554 555 556 557 558 559 560 561 562 563 564 565
        # Write the user's preferences into a Perl record indexed by 
        # preference name.  We pass the value "255" to the split function 
        # because otherwise split will trim trailing null fields, causing 
        # Perl to generate lots of warnings.  Any suitably large number 
        # would do.
        my %prefs = split(/~/, $prefs, 255);
        
        # If this user is the one who made the change in the first place,
        # and they prefer not to receive mail about their own changes,
        # filter them from the list.
        if (lc($user) eq $nametoexclude && $prefs{'ExcludeSelf'} eq 'on') {
            push(@excludedAddresses, $user);
            next;
566 567
        }
        
568 569 570 571 572 573 574 575 576 577 578 579
        # If the user doesn't want to receive email about unconfirmed
        # bugs, that setting overrides their other preferences, including
        # the preference to receive email when they are added to or removed
        # from a role, so remove them from the list before checking their
        # other preferences.
        if (grep(/Unconfirmed/, @$reasons)
            && exists($prefs{"email${role}Unconfirmed"})
            && $prefs{"email${role}Unconfirmed"} eq '')
        {
            push(@excludedAddresses, $user);
            next;
        }
580
        
581 582 583 584 585 586 587 588 589 590
        # If the user was added to or removed from this role, and they
        # prefer to receive email when that happens, send them mail.
        # Note: This was originally written to send email when users
        # were removed from roles and was later enhanced for additions,
        # but for simplicity's sake the name "Removeme" was retained.
        if (grep($_ eq $user, @{$force{$role}})
            && $prefs{"email${role}Removeme"} eq 'on')
        {
            push (@recipients, $user);
            next;
591
        }
592 593 594 595 596 597 598 599 600 601 602
        
        # If the user prefers to be included in mail about this change,
        # or they haven't specified a preference for it (because they
        # haven't visited the email preferences page since the preference
        # was added, in which case we include them by default), add them
        # to the list of recipients.
        foreach my $reason (@$reasons) {
            my $pref = "email$role$reason";
            if (!exists($prefs{$pref}) || $prefs{$pref} eq 'on') {
                push(@recipients, $user);
                next USER;
603
            }
604 605 606 607 608 609 610
        }
    
        # At this point there's no way the user wants to receive email
        # about this change, so exclude them from the list of recipients.
        push(@excludedAddresses, $user);
    
    } # for each user on the unfiltered list
611

612
    return @recipients;
613 614
}

615
sub NewProcessOnePerson ($$$$$$$$$$$$$) {
616
    my ($person, $count, $hlRef, $reasonsRef, $valueRef, $dmhRef, $fdRef, $difftext, 
617
        $newcomments, $anyprivate, $start, $id, $depbugsRef) = @_;
618

619 620
    my %values = %$valueRef;
    my @headerlist = @$hlRef;
621
    my @reasons = @$reasonsRef;
622 623
    my %defmailhead = %$dmhRef;
    my %fielddescription = %$fdRef;
624 625
    my @depbugs = @$depbugsRef;
    
626 627 628
    if ($seen{$person}) {
      return;
    }
629 630 631 632

    if ($nomail{$person}) {
      return;
    }
633

634
        
635
    SendSQL("SELECT userid, (refreshed_when > " . SqlQuote($::last_changed) . ") " .
636
            "FROM profiles WHERE login_name = " . SqlQuote($person));
637
    my ($userid, $current) = (FetchSQLData());
638

639
    $seen{$person} = 1;
640

641
    detaint_natural($userid);
642 643 644 645

    if (!$current) {
        DeriveGroup($userid);
    }
646

647 648 649
    # if this person doesn't have permission to see info on this bug, 
    # return.
    #
650
    # XXX - This currently means that if a bug is suddenly given
651 652 653 654
    # 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.
    #
655 656
    return unless CanSeeBug($id, $userid);
    
657 658

    #  Drop any non-insiders if the comment is private
659 660 661
     return if (Param("insidergroup") && 
               ($anyprivate != 0) && 
               (!UserInGroup(Param("insidergroup"), $userid)));
662

663 664 665 666 667 668
    # We shouldn't send changedmail if this is a dependency mail, and any of 
    # the depending bugs is not visible to the user.
    foreach my $dep_id (@depbugs) {
        my $save_id = $dep_id;
        detaint_natural($dep_id) || warn("Unexpected Error: \@depbugs contains a non-numeric value: '$save_id'")
                                 && return;
669
        return unless CanSeeBug($dep_id, $userid);
670 671
    }

672 673 674 675 676 677 678
    my %mailhead = %defmailhead;
    
    my $head = "";
    
    foreach my $f (@headerlist) {
      if ($mailhead{$f}) {
        my $value = $values{$f};
679 680
        # If there isn't anything to show, don't include this header
        if (! $value) {
681 682 683 684 685 686 687 688 689 690 691 692
          next;
        }
        my $desc = $fielddescription{$f};
        $head .= FormatDouble($desc, $value);
      }
    }
    
    if ($difftext eq "" && $newcomments eq "") {
      # Whoops, no differences!
      return;
    }
    
693
    my $reasonsbody = "------- You are receiving this mail because: -------\n";
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714

    if (scalar(@reasons) == 0) {
        $reasonsbody .= "Whoops!  I have no idea!\n";
    } else {
        foreach my $reason (@reasons) {
            if ($reason eq 'AssignedTo') {
                $reasonsbody .= "You are the assignee for the bug, or are watching the assignee.\n";
            } elsif ($reason eq 'Reporter') {
                $reasonsbody .= "You reported the bug, or are watching the reporter.\n";
            } elsif ($reason eq 'QAContact') {
                $reasonsbody .= "You are the QA contact for the bug, or are watching the QA contact.\n";
            } elsif ($reason eq 'CC') {
                $reasonsbody .= "You are on the CC list for the bug, or are watching someone who is.\n";
            } elsif ($reason eq 'Voter') {
                $reasonsbody .= "You are a voter for the bug, or are watching someone who is.\n";
            } else {
                $reasonsbody .= "Whoops!  There is an unknown reason!\n";
            }
        }
    }

715 716 717
    my $isnew = ($start !~ m/[1-9]/);
    
    my %substs;
718

719 720 721 722 723 724
    # If an attachment was created, then add an URL. (Note: the 'g'lobal
    # replace should work with comments with multiple attachments.)

    if ( $newcomments =~ /Created an attachment \(/ ) {

        my $showattachurlbase =
725
            Param('urlbase') . "attachment.cgi?id=";
726

727
        $newcomments =~ s/(Created an attachment \(id=([0-9]+)\))/$1\n --> \(${showattachurlbase}$2&action=view\)/g;
728 729
    }

730
    $person .= Param('emailsuffix');
731 732 733 734 735
# 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.
736
    $substs{"neworchanged"} = $isnew ? 'New: ' : '';
737 738 739 740 741 742 743 744 745
    $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'};
746 747
    $substs{"reasonsheader"} = join(" ", @reasons);
    $substs{"reasonsbody"} = $reasonsbody;
748 749 750 751
    
    my $template = Param("newchangedmail");
    
    my $msg = PerformSubsts($template, \%substs);
752 753 754

    my $sendmailparam = "-ODeliveryMode=deferred";
    if (Param("sendmailnow")) {
755
       $sendmailparam = "";
756
    }
757 758

    if ($enableSendMail == 1) {
759
    open(SENDMAIL, "|/usr/lib/sendmail $sendmailparam -t -i") ||
760 761 762 763
      die "Can't open sendmail";
    
    print SENDMAIL trim($msg) . "\n";
    close SENDMAIL;
764
    }
765
    push(@sentlist, $person);
766
    return 1;
767 768
}

769 770 771
# Code starts here

ConnectToDatabase();
772
GetVersionTable();
773 774 775

if (open(FID, "<data/nomail")) {
    while (<FID>) {
776
        $nomail{trim($_)} = 1;
777 778 779 780
    }
    close FID;
}

781 782 783 784 785 786 787 788
# Since any email recipients must be rederived if the user has not
# been rederived since the most recent group change, figure out when that
# is once and determine the need to rederive users using the same DB access
# that gets the user's email address each time a person is processed.
#
SendSQL("SELECT MAX(last_changed) FROM groups");
($::last_changed) = FetchSQLData();

789
if ($#ARGV >= 0 && $ARGV[0] eq "regenerate") {
790
    print "Regenerating is no longer required or supported\n";
791 792 793
    exit;
}

794
if ($#ARGV >= 0 && $ARGV[0] eq "-forcecc") {
795 796
    shift(@ARGV);
    foreach my $i (split(/,/, shift(@ARGV))) {
797
        push(@{$force{'CClist'}}, trim($i));
798 799 800
    }
}

801 802 803 804 805 806 807 808 809 810
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)));
}

811 812 813 814 815
if ($#ARGV >= 0 && $ARGV[0] eq "-forcereporter") {
    shift(@ARGV);
    @{$force{'Reporter'}} = trim(shift(@ARGV));
}

816
if (($#ARGV < 0) || ($#ARGV > 1)) {
817 818
    print "Usage:\n processmail {bugid} {nametoexclude} " . 
      "[-forcecc list,of,users]\n             [-forceowner name] " .
819
      "[-forceqacontact name]\n             [-forcereporter name]\nor\n" .
820
      " processmail rescanall\n";
821 822 823
    exit;
}

824
if ($#ARGV == 1) {
825
    $nametoexclude = lc($ARGV[1]);
826 827
}

828
if ($ARGV[0] eq "rescanall") {
829 830
    print "Collecting bug ids...\n";
    SendSQL("select bug_id, lastdiffed, delta_ts from bugs where lastdiffed < delta_ts AND delta_ts < date_sub(now(), INTERVAL 30 minute) order by bug_id");
831 832
    my @list;
    while (my @row = FetchSQLData()) {
833 834 835 836 837
        my $time = $row[2];
        if ($time =~ /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/) {
            $time = "$1-$2-$3 $4:$5:$6";
        }
        print STDERR "Bug $row[0] has unsent mail. lastdiffed is $row[1], delta_ts is $time.\n";
838 839
        push @list, $row[0];
    }
840 841 842 843 844 845
    if (scalar(@list) > 0) {
        print STDERR scalar(@list) . " bugs found with possibly unsent mail\n";
        print STDERR "Updating bugs, sending mail if required\n";
    } else {
        print "All appropriate mail appears to have been sent\n"
    }
846
    foreach my $id (@list) {
847 848 849
        if (detaint_natural($id)) {
            ProcessOneBug($id);
        }
850 851
    }
} else {
852 853 854 855 856 857 858 859
    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);
860
}
861

862
exit;