BugMail.pm 31.4 KB
Newer Older
1
# -*- Mode: perl; indent-tabs-mode: nil -*-
terry%netscape.com's avatar
terry%netscape.com committed
2
#
3 4 5 6 7 8 9 10 11 12
# 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
13
# The Original Code is the Bugzilla Bug Tracking System.
14
#
terry%netscape.com's avatar
terry%netscape.com committed
15
# The Initial Developer of the Original Code is Netscape Communications
16 17 18 19
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
20
# Contributor(s): Terry Weissman <terry@mozilla.org>,
21 22
#                 Bryce Nesbitt <bryce-mozilla@nextbus.com>
#                 Dan Mosedale <dmose@mozilla.org>
23
#                 Alan Raetz <al_raetz@yahoo.com>
24
#                 Jacob Steenhagen <jake@actex.net>
25
#                 Matthew Tuck <matty@chariot.net.au>
26 27
#                 Bradley Baetz <bbaetz@student.usyd.edu.au>
#                 J. Paul Reed <preed@sigkill.com>
28

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

31
package Bugzilla::BugMail;
terry%netscape.com's avatar
terry%netscape.com committed
32

33 34 35 36 37
use base qw(Exporter);
@Bugzilla::BugMail::EXPORT = qw(
    PerformSubsts
);

38
use Bugzilla::Config qw(:DEFAULT $datadir);
39
use Bugzilla::Util;
40

41 42 43
use Mail::Mailer;
use Mail::Header;

44 45 46 47
# This code is really ugly. It was a commandline interface, then it was moved
# There are package-global variables which we rely on ProcessOneBug to clean
# up each time, and other sorts of fun.
# This really needs to be cleaned at some point.
48

49
my $nametoexclude = "";
50
my %nomail;
51
my $last_changed;
52

53 54
my @excludedAddresses = ();

55 56 57 58 59 60 61
my $sitespec = '@'.Param('urlbase');
$sitespec =~ s/:\/\//\./; # Make the protocol look like part of the domain
$sitespec =~ s/^([^:\/]+):(\d+)/$1/; # Remove a port number, to relocate
if ($2) {
    $sitespec = "-$2$sitespec"; # Put the port number back in, before the '@'
}

62
my %force;
terry%netscape.com's avatar
terry%netscape.com committed
63

64
my %seen;
65 66
my @sentlist;

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
# I got sick of adding &:: to everything.
# However, 'Yuck!'
# I can't require, cause that pulls it in only once, so it won't then be
# in the global package, and these aren't modules, so I can't use globals.pl
# Remove this evilness once our stuff uses real packages.
sub AUTOLOAD {
    no strict 'refs';
    use vars qw($AUTOLOAD);
    my $subName = $AUTOLOAD;
    $subName =~ s/.*::/::/; # remove package name
    *$AUTOLOAD = \&$subName;
    goto &$AUTOLOAD;
}

# This is run when we load the package
82
if (open(NOMAIL, '<', "$datadir/nomail")) {
83 84 85 86 87 88 89
    while (<NOMAIL>) {
        $nomail{trim($_)} = 1;
    }
    close(NOMAIL);
}


90 91 92 93
sub FormatTriple {
    my ($a, $b, $c) = (@_);
    $^A = "";
    my $temp = formline << 'END', $a, $b, $c;
94
^>>>>>>>>>>>>>>>>>>|^<<<<<<<<<<<<<<<<<<<<<<<<<<<|^<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
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;
}

111 112 113 114 115 116 117 118 119 120 121 122
# This is a bit of a hack, basically keeping the old system()
# cmd line interface. Should clean this up at some point.
#
# args: bug_id, and an optional hash ref which may have keys for:
# changer, owner, qa, reporter, cc
# Optional hash contains values of people which will be forced to those
# roles when the email is sent.
# All the names are email addresses, not userids
# values are scalars, except for cc, which is a list
sub Send($;$) {
    my ($id, $recipients) = (@_);

123
    # This only works in a sub. Probably something to do with the
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    # require abuse we do.
    GetVersionTable();

    # Make sure to clean up _all_ package vars here. Yuck...
    $nametoexclude = $recipients->{'changer'} || "";
    @{$force{'CClist'}} = (exists $recipients->{'cc'} && 
     scalar($recipients->{'cc'}) > 0) ? map(trim($_), 
     @{$recipients->{'cc'}}) : ();
    @{$force{'Owner'}} = $recipients->{'owner'} ? 
     (trim($recipients->{'owner'})) : ();
    @{$force{'QAcontact'}} = $recipients->{'qacontact'} ? 
     (trim($recipients->{'qacontact'})) : ();
    @{$force{'Reporter'}} = $recipients->{'reporter'} ? 
     (trim($recipients->{'reporter'})) : ();
    @{$force{'Voter'}} = ();

    %seen = ();
    @excludedAddresses = ();
    @sentlist = ();

    return ProcessOneBug($id);
}

sub ProcessOneBug($) {
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    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);
    }
171 172 173
    $values{product} = get_product_name($values{product_id});
    $values{component} = get_component_name($values{component_id});

174
    my ($start, $end) = (@row);
175

176 177 178 179 180 181 182
    my $cc_ref = Bugzilla->dbh->selectcol_arrayref(
        q{SELECT profiles.login_name FROM cc, profiles
           WHERE bug_id = ?
             AND cc.who = profiles.userid
        ORDER BY profiles.login_name},
        undef, $id);
    $values{'cc'} = join(',', @$cc_ref); 
183
    
184
    my @voterList;
185 186 187
    SendSQL("SELECT profiles.login_name FROM votes, profiles " .
            "WHERE votes.bug_id = $id AND profiles.userid = votes.who");
    while (MoreSQLData()) {
188
        push(@voterList, FetchOneColumn());
189
    }
190 191 192 193 194 195

    $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'});
    }
196
    $values{'estimated_time'} = format_time_decimal($values{'estimated_time'});
197

198 199 200
    if ($values{'deadline'}) {
        $values{'deadline'} = time2str("%Y-%m-%d", str2time($values{'deadline'}));
    }
201

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    my @dependslist;
    SendSQL("SELECT dependson FROM dependencies WHERE 
             blocked = $id ORDER BY dependson");
    while (MoreSQLData()) {
        push(@dependslist, FetchOneColumn());
    }
    $values{'dependson'} = join(",", @dependslist);

    my @blockedlist;
    SendSQL("SELECT blocked FROM dependencies WHERE 
             dependson = $id ORDER BY blocked");
    while (MoreSQLData()) {
        push(@blockedlist, FetchOneColumn());
    }
    $values{'blocked'} = join(",", @blockedlist);

218 219
    my @diffs;

220 221 222
    # If lastdiffed is NULL, then we don't limit the search on time.
    my $when_restriction = $start ? 
        " AND bug_when > '$start' AND bug_when <= '$end'" : '';
223
    SendSQL("SELECT profiles.login_name, fielddefs.description, " .
224
            "       bug_when, removed, added, attach_id, fielddefs.name " .
225 226 227 228
            "FROM bugs_activity, fielddefs, profiles " .
            "WHERE bug_id = $id " .
            "  AND fielddefs.fieldid = bugs_activity.fieldid " .
            "  AND profiles.userid = who " .
229
            $when_restriction .
230 231 232 233 234 235 236 237 238
            "ORDER BY bug_when"
            );

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

    my $difftext = "";
239 240
    my $diffheader = "";
    my @diffparts;
241 242
    my $lastwho = "";
    foreach my $ref (@diffs) {
243
        my ($who, $what, $when, $old, $new, $attachid, $fieldname) = (@$ref);
244
        my $diffpart = {};
245 246
        if ($who ne $lastwho) {
            $lastwho = $who;
247 248 249
            $diffheader = "\n$who" . Param('emailsuffix') . " changed:\n\n";
            $diffheader .= FormatTriple("What    ", "Removed", "Added");
            $diffheader .= ('-' x 76) . "\n";
250
        }
251
        $what =~ s/^(Attachment )?/Attachment #$attachid / if $attachid;
252 253
        if( $fieldname eq 'estimated_time' ||
            $fieldname eq 'remaining_time' ) {
254 255
            $old = format_time_decimal($old);
            $new = format_time_decimal($new);
256
        }
257 258 259 260 261
        if ($attachid) {
            SendSQL("SELECT isprivate FROM attachments 
                     WHERE attach_id = $attachid");
            $diffpart->{'isprivate'} = FetchOneColumn();
        }
262 263 264 265 266
        $difftext = FormatTriple($what, $old, $new);
        $diffpart->{'header'} = $diffheader;
        $diffpart->{'fieldname'} = $fieldname;
        $diffpart->{'text'} = $difftext;
        push(@diffparts, $diffpart);
267 268 269
    }


270 271
    my $deptext = "";

272
    SendSQL("SELECT bugs_activity.bug_id, bugs.short_desc, fielddefs.name, " .
273
            "       removed, added " .
274
            "FROM bugs_activity, bugs, dependencies, fielddefs ".
275
            "WHERE bugs_activity.bug_id = dependencies.dependson " .
276
            "  AND bugs.bug_id = bugs_activity.bug_id ".
277 278 279 280
            "  AND dependencies.blocked = $id " .
            "  AND fielddefs.fieldid = bugs_activity.fieldid" .
            "  AND (fielddefs.name = 'bug_status' " .
            "    OR fielddefs.name = 'resolution') " .
281
            $when_restriction .
282 283 284 285 286
            "ORDER BY bug_when, bug_id");
    
    my $thisdiff = "";
    my $lastbug = "";
    my $interestingchange = 0;
287 288
    my $depbug = 0;
    my @depbugs;
289
    while (MoreSQLData()) {
290 291 292
        my ($summary, $what, $old, $new);
        ($depbug, $summary, $what, $old, $new) = (FetchSQLData());
        if ($depbug ne $lastbug) {
293 294 295
            if ($interestingchange) {
                $deptext .= $thisdiff;
            }
296
            $lastbug = $depbug;
297
            my $urlbase = Param("urlbase");
298
            $thisdiff =
299 300 301
              "\nBug $id depends on bug $depbug, which changed state.\n\n" . 
              "Bug $depbug Summary: $summary\n" . 
              "${urlbase}show_bug.cgi?id=$depbug\n\n"; 
302 303 304 305 306 307 308 309
            $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;
        }
310 311
        
        push(@depbugs, $depbug);
312
    }
313
    
314 315 316 317 318 319 320
    if ($interestingchange) {
        $deptext .= $thisdiff;
    }

    $deptext = trim($deptext);

    if ($deptext) {
321 322
        my $diffpart = {};
        $diffpart->{'text'} = "\n" . trim("\n\n" . $deptext);
323
        push(@diffparts, $diffpart);
324 325 326
    }


327
    my ($newcomments, $anyprivate) = GetLongDescriptionAsText($id, $start, $end);
328

329 330 331 332
    #
    # Start of email filtering code
    #
    my $count = 0;
333

334 335 336 337
    # Get a list of the reasons a user might receive email about the bug.
    my @currentEmailAttributes = 
      getEmailAttributes(\%values, \@diffs, $newcomments);
    
338
    my (@assigned_toList,@reporterList,@qa_contactList,@ccList) = ();
339

340 341 342
    #open(LOG, ">>/tmp/maillog");
    #print LOG "\nBug ID: $id   CurrentEmailAttributes:";
    #print LOG join(',', @currentEmailAttributes) . "\n";
343

344
    @excludedAddresses = (); # zero out global list 
345

346 347 348 349 350 351 352 353 354 355 356 357 358
    @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 = (); 
    }
359

360 361
    @ccList = filterEmailGroup('CClist', \@currentEmailAttributes,
                               $values{'cc'});
362

363 364
    @voterList = filterEmailGroup('Voter', \@currentEmailAttributes,
                                  join(',',@voterList));
365

366
    my @emailList = (@assigned_toList, @reporterList, 
367
                     @qa_contactList, @ccList, @voterList);
368

369 370 371
    # only need one entry per person
    my @allEmail = ();
    my %AlreadySeen = ();
372
    my $checkperson = "";
373
    foreach my $person (@emailList) {
374 375 376 377
        # don't modify the original so it sends out with the right case
        # based on who came first.
        $checkperson = lc($person);
        if ( !($AlreadySeen{$checkperson}) ) {
378
            push(@allEmail,$person);
379
            $AlreadySeen{$checkperson}++;
380
        }
381
    }
382

383 384 385 386
    #print LOG "\nbug $id email sent: " . join(',', @allEmail) . "\n";
        
    @excludedAddresses = filterExcludeList(\@excludedAddresses,
                                           \@allEmail);
387

388 389 390
    # print LOG "excluded: " . join(',',@excludedAddresses) . "\n\n";

    foreach my $person ( @allEmail ) {
391 392
        my @reasons;

393
        $count++;
394 395 396

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

401
        if ( !defined(NewProcessOnePerson($person, $count, \@headerlist,
402 403
                                          \@reasons, \%values,
                                          \%defmailhead, 
404 405 406
                                          \%fielddescription, \@diffparts,
                                          $newcomments, 
                                          $anyprivate, $start, $id, 
407 408
                                          \@depbugs))) 
        {
409 410 411 412 413 414

            # 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;
415 416

        }
417
    }
418

419

420
    SendSQL("UPDATE bugs SET lastdiffed = '$end' WHERE bug_id = $id");
421 422 423 424 425

    # Filter the exclude list for dupes one last time
    @excludedAddresses = filterExcludeList(\@excludedAddresses,
                                           \@sentlist);

426
    return { sent => \@sentlist, excluded => \@excludedAddresses };
427
}
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
# 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
460
            if (lc($included) eq lc($excluded)) {
461
                pop(@result);
462
                last;
463 464 465 466 467
            }
        }
    }

    # only need one entry per person
468 469
    my $checkperson = "";

470
    foreach my $person (@result) {
471 472
        $checkperson = lc($person);
        if ( !($alreadySeen{$checkperson}) ) {
473
            push(@uniqueResult,$person);
474
            $alreadySeen{$checkperson}++;
475 476 477 478 479 480 481 482 483
        }
    }

    return @uniqueResult;
}

# if the Status was changed to Resolved or Verified
#       set the Resolved flag
#
484
# else if Severity, Status, Target Milestone OR Priority fields have any change
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
#       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
#
502
sub getEmailAttributes (\%\@$) {
503
    
504
    my ($bug, $fieldDiffs, $commentField) = @_;
505 506
    my (@flags,@uniqueFlags,%alreadySeen) = ();
    
507
    # Add a flag if the status of the bug is "unconfirmed".
508
    if ($bug->{'bug_status'} eq 'UNCONFIRMED') {
509 510 511 512
        push (@flags, 'Unconfirmed')
    };
    
    foreach my $ref (@$fieldDiffs) {
513 514 515 516
        my ($who, $fieldName, $when, $old, $new) = (@$ref);
        
        #print qq{field: $fieldName $new<br>};
        
517
        # the STATUS will be flagged for Severity, Status, Target Milestone and 
518 519
        # Priority changes
        #
520 521
        if ( $fieldName eq 'Status' && ($new eq 'RESOLVED' || $new eq 'VERIFIED')) {
            push (@flags, 'Resolved');
522 523
        }
        elsif ( $fieldName eq 'Severity' || $fieldName eq 'Status' ||
524
                $fieldName eq 'Priority' || $fieldName eq 'Target Milestone') {
525 526 527 528 529 530
            push (@flags, 'Status');
        } elsif ( $fieldName eq 'Keywords') {
            push (@flags, 'Keywords');
        } elsif ( $fieldName eq 'CC') {
            push (@flags, 'CC');
        }
531

532 533 534 535
        # These next few lines find out who has been added
        # to the Owner, QA, CC, etc. fields.  They do not affect
        # the @flags array at all, but are run here because they
        # affect filtering later and we're already in the loop.
536
        if ($fieldName eq 'AssignedTo') {
537
            push (@{$force{'Owner'}}, $new);
538
        } elsif ($fieldName eq 'QAcontact') {
539
           push (@{$force{'QAcontact'}}, $new);
540
        } elsif ($fieldName eq 'CC') {
541
            my @added = split (/[ ,]/, $new);
542 543
            push (@{$force{'CClist'}}, @added);
        }
544 545 546 547 548
    }
    
    if ( $commentField =~ /Created an attachment \(/ ) {
        push (@flags, 'Attachments');
    }
549
    elsif ( ($commentField ne '') && !(scalar(@flags) == 1 && $flags[0] eq 'Resolved')) {
550 551 552 553
        push (@flags, 'Comments');
    }
    
    # default fallthrough for any unflagged change is 'Other'
554
    if ( @flags == 0 && @$fieldDiffs != 0 ) {
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
        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 ($$$) {
576
    # This function figures out who should receive email about the bug
577
    # based on the user's role with respect to the bug (assignee, reporter, 
578
    # etc.), the changes that occurred (new comments, attachment added, 
579
    # status changed, etc.) and the user's email preferences.
580
    
581 582 583
    # 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.
584
    
585 586 587 588 589 590
    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
591
    # as if they still have it.
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
    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();
609 610
    }

611 612
    # Initialize the list of recipients.
    my @recipients = ();
613

614 615
    USER: foreach my $user (@users) {
        next unless $user;
616
        
617 618 619 620
        # 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
621
        # default preference is to receive all mail.
622
        my $userid = login_to_id($user);
623 624
        if (!$userid) {
            push(@recipients, $user);
625 626 627
            next;
        }
        
628 629 630
        # Get the user's email preferences from the database.
        SendSQL("SELECT emailflags FROM profiles WHERE userid = $userid");
        my $prefs = FetchOneColumn();
631
        
632 633 634 635 636 637 638 639 640 641
        # 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.
642
        if (lc($user) eq lc($nametoexclude) && $prefs{'ExcludeSelf'} eq 'on') {
643 644
            push(@excludedAddresses, $user);
            next;
645 646
        }
        
647 648 649 650 651 652 653 654 655 656 657 658
        # 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;
        }
659
        
660 661 662 663 664 665 666 667 668 669
        # 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;
670
        }
671 672
        
        # If the user prefers to be included in mail about this change,
673
        # add them to the list of recipients.
674 675 676 677 678
        foreach my $reason (@$reasons) {
            my $pref = "email$role$reason";
            if (!exists($prefs{$pref}) || $prefs{$pref} eq 'on') {
                push(@recipients, $user);
                next USER;
679
            }
680 681 682 683 684 685 686
        }
    
        # 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
687

688
    return @recipients;
689 690
}

691
sub NewProcessOnePerson ($$$$$$$$$$$$$) {
692 693 694
    my ($person, $count, $hlRef, $reasonsRef, $valueRef, $dmhRef, $fdRef,  
        $diffRef, $newcomments, $anyprivate, $start, 
        $id, $depbugsRef) = @_;
695

696 697
    my %values = %$valueRef;
    my @headerlist = @$hlRef;
698
    my @reasons = @$reasonsRef;
699 700
    my %defmailhead = %$dmhRef;
    my %fielddescription = %$fdRef;
701
    my @diffparts = @$diffRef;
702 703
    my @depbugs = @$depbugsRef;
    
704 705 706
    if ($seen{$person}) {
      return;
    }
707 708 709 710

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

712 713 714
    # This routine should really get passed a userid
    # This rederives groups as a side effect
    my $user = Bugzilla::User->new_from_login($person);
715 716 717
    if (!$user) { # person doesn't exist, probably changed email
      return;
    }
718
    my $userid = $user->id;
719

720
    $seen{$person} = 1;
721

722 723 724
    # if this person doesn't have permission to see info on this bug, 
    # return.
    #
725
    # XXX - This currently means that if a bug is suddenly given
726 727 728 729
    # 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.
    #
730
    return unless $user->can_see_bug($id);
731 732

    #  Drop any non-insiders if the comment is private
733
    return if (Param("insidergroup") && 
734
               ($anyprivate != 0) && 
735
               (!$user->groups->{Param("insidergroup")}));
736

737
    # We shouldn't send changedmail if this is a dependency mail, and any of 
738
    # the depending bugs are not visible to the user.
739 740 741 742
    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;
743
        return unless $user->can_see_bug($dep_id);
744 745
    }

746 747 748 749 750 751 752
    my %mailhead = %defmailhead;
    
    my $head = "";
    
    foreach my $f (@headerlist) {
      if ($mailhead{$f}) {
        my $value = $values{$f};
753 754
        # If there isn't anything to show, don't include this header
        if (! $value) {
755 756
          next;
        }
757
        # Only send estimated_time if it is enabled and the user is in the group
758 759
        if (($f ne 'estimated_time' && $f ne 'deadline') ||
             $user->groups->{Param('timetrackinggroup')}) {
760

761 762 763
            my $desc = $fielddescription{$f};
            $head .= FormatDouble($desc, $value);
        }
764 765
      }
    }
766 767 768 769 770

    # Build difftext (the actions) by verifying the user should see them
    my $difftext = "";
    my $diffheader = "";
    my $add_diff;
771

772 773 774
    foreach my $diff (@diffparts) {
        $add_diff = 0;
        
775
        if (exists($diff->{'fieldname'}) && 
776 777
            ($diff->{'fieldname'} eq 'estimated_time' ||
             $diff->{'fieldname'} eq 'remaining_time' ||
778 779
             $diff->{'fieldname'} eq 'work_time' ||
             $diff->{'fieldname'} eq 'deadline')){
780
            if ($user->groups->{Param("timetrackinggroup")}) {
781 782
                $add_diff = 1;
            }
783 784 785 786 787
        } elsif (($diff->{'isprivate'}) 
                 && Param('insidergroup')
                 && !($user->groups->{Param('insidergroup')})
                ) {
            $add_diff = 0;
788 789 790
        } else {
            $add_diff = 1;
        }
791

792
        if ($add_diff) {
793 794
            if (exists($diff->{'header'}) && 
             ($diffheader ne $diff->{'header'})) {
795 796 797 798 799 800
                $diffheader = $diff->{'header'};
                $difftext .= $diffheader;
            }
            $difftext .= $diff->{'text'};
        }
    }
801
 
802 803 804 805 806
    if ($difftext eq "" && $newcomments eq "") {
      # Whoops, no differences!
      return;
    }
    
807
    my $reasonsbody = "------- You are receiving this mail because: -------\n";
808 809 810 811 812 813 814 815 816

    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";
817
            } elsif ($reason eq 'QAcontact') {
818 819 820 821 822 823 824 825 826 827 828
                $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";
            }
        }
    }

829
    my $isnew = !$start;
830 831
    
    my %substs;
832

833 834 835 836 837 838
    # 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 =
839
            Param('urlbase') . "attachment.cgi?id=";
840

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

844
    $person .= Param('emailsuffix');
845 846 847 848 849
# 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.
850
    $substs{"neworchanged"} = $isnew ? ' New: ' : '';
851 852 853 854 855 856 857 858
    $substs{"to"} = $person;
    $substs{"cc"} = '';
    $substs{"bugid"} = $id;
    if ($isnew) {
      $substs{"diffs"} = $head . "\n\n" . $newcomments;
    } else {
      $substs{"diffs"} = $difftext . "\n\n" . $newcomments;
    }
859 860
    $substs{"product"} = $values{'product'};
    $substs{"component"} = $values{'component'};
861
    $substs{"summary"} = $values{'short_desc'};
862 863
    $substs{"reasonsheader"} = join(" ", @reasons);
    $substs{"reasonsbody"} = $reasonsbody;
864
    $substs{"space"} = " ";
865 866 867 868 869
    if ($isnew) {
        $substs{'threadingmarker'} = "Message-ID: <bug-$id-$userid$sitespec>";
    } else {
        $substs{'threadingmarker'} = "In-Reply-To: <bug-$id-$userid$sitespec>";
    }
870 871 872 873
    
    my $template = Param("newchangedmail");
    
    my $msg = PerformSubsts($template, \%substs);
874

875 876 877 878 879 880 881
    MessageToMTA($msg);

    push(@sentlist, $person);
    return 1;
}

sub MessageToMTA ($) {
882
    my ($msg) = (@_);
883
    return if (Param('mail_delivery_method') eq "none");
884

885
    my @args;
886
    if (Param("mail_delivery_method") eq "sendmail" && !Param("sendmailnow")) {
887 888
        push @args, "-ODeliveryMode=deferred";
    }
889
    if (Param("mail_delivery_method") eq "smtp") {
890
        push @args, Server => Param("smtpserver");
891
    }
892 893
    my $mailer = new Mail::Mailer Param("mail_delivery_method"), @args;
    if (Param("mail_delivery_method") eq "testfile") {
894 895 896
        $Mail::Mailer::testfile::config{outfile} = "$datadir/mailer.testfile";
    }
    
897 898 899
    $msg =~ /(.*?)\n\n(.*)/ms;
    my @header_lines = split(/\n/, $1);
    my $body = $2;
900

901 902
    my $headers = new Mail::Header \@header_lines, Modify => 0;
    $mailer->open($headers->header_hashref);
903
    print $mailer $body;
904
    $mailer->close;
905 906
}

907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
# Performs substitutions for sending out email with variables in it,
# or for inserting a parameter into some other string.
#
# Takes a string and a reference to a hash containing substitution 
# variables and their values.
#
# If the hash is not specified, or if we need to substitute something
# that's not in the hash, then we will use parameters to do the 
# substitution instead.
#
# Substitutions are always enclosed with '%' symbols. So they look like:
# %some_variable_name%. If "some_variable_name" is a key in the hash, then
# its value will be placed into the string. If it's not a key in the hash,
# then the value of the parameter called "some_variable_name" will be placed
# into the string.
sub PerformSubsts ($;$) {
    my ($str, $substs) = (@_);
    $str =~ s/%([a-z]*)%/(defined $substs->{$1} ? $substs->{$1} : Param($1))/eg;
    return $str;
}

928
1;