]> git.donarmstrong.com Git - debbugs.git/blob - scripts/service
merge changes from don
[debbugs.git] / scripts / service
1 #!/usr/bin/perl
2 # $Id: service.in,v 1.118 2005/10/19 01:22:14 don Exp $
3 #
4 # Usage: service <code>.nn
5 # Temps:  incoming/P<code>.nn
6
7 use warnings;
8 use strict;
9
10
11 use Debbugs::Config qw(:globals :config);
12
13 use File::Copy;
14 use MIME::Parser;
15
16 use Params::Validate qw(:types validate_with);
17
18 use Debbugs::Common qw(:util :quit :misc :lock);
19
20 use Debbugs::Status qw(:read :status :write :versions);
21
22 use Debbugs::MIME qw(decode_rfc1522 encode_rfc1522);
23 use Debbugs::Mail qw(send_mail_message);
24 use Debbugs::User;
25 use Debbugs::Recipients qw(:all);
26 use HTML::Entities qw(encode_entities);
27 use Debbugs::Versions::Dpkg;
28
29 use Debbugs::Status qw(splitpackages);
30
31 use Debbugs::CGI qw(html_escape);
32 use Debbugs::Control qw(:all);
33 use Debbugs::Log qw(:misc);
34 use Debbugs::Text qw(:templates);
35
36 use Mail::RFC822::Address;
37
38 chdir($config{spool_dir}) or
39      die "Unable to chdir to spool_dir '$config{spool_dir}': $!";
40
41 my $debug = 0;
42 umask(002);
43
44 my ($nn,$control) = $ARGV[0] =~ m/^(([RC])\.\d+)$/;
45 if (not defined $control or not defined $nn) {
46      die "Bad argument to service.in";
47 }
48 if (!rename("incoming/G$nn","incoming/P$nn")) {
49     defined $! and $! =~ m/no such file or directory/i and exit 0;
50     die "Failed to rename incoming/G$nn to incoming/P$nn: $!";
51 }
52
53 my $log_fh = IO::File->new("incoming/P$nn",'r') or
54      die "Unable to open incoming/P$nn for reading: $!";
55 my @log=<$log_fh>;
56 my @msg=@log;
57 close($log_fh);
58
59 chomp @msg;
60
61 print "###\n",join("##\n",@msg),"\n###\n" if $debug;
62
63 # Bug numbers to send e-mail to, hash so that we don't send to the
64 # same bug twice.
65 my (%bug_affected);
66
67 my (@headerlines,@bodylines);
68
69 my $parse_output = Debbugs::MIME::parse(join('',@log));
70 @headerlines = @{$parse_output->{header}};
71 @bodylines = @{$parse_output->{body}};
72
73 my %header;
74 for (@headerlines) {
75     $_ = decode_rfc1522($_);
76     s/\n\s/ /g;
77     print ">$_<\n" if $debug;
78     if (s/^(\S+):\s*//) {
79         my $v = lc $1;
80         print ">$v=$_<\n" if $debug;
81         $header{$v} = $_;
82     } else {
83         print "!>$_<\n" if $debug;
84     }
85 }
86 $header{'message-id'} ||= '';
87
88 grep(s/\s+$//,@bodylines);
89
90 print "***\n",join("\n",@bodylines),"\n***\n" if $debug;
91
92 if (defined $header{'resent-from'} && !defined $header{'from'}) {
93     $header{'from'} = $header{'resent-from'};
94 }
95
96 defined($header{'from'}) || die "no From header";
97
98 delete $header{'reply-to'} 
99         if ( defined($header{'reply-to'}) && $header{'reply-to'} =~ m/^\s*$/ );
100
101 my $replyto;
102 if ( defined($header{'reply-to'}) && $header{'reply-to'} ne "" ) {
103     $replyto = $header{'reply-to'};
104 } else {
105     $replyto = $header{'from'};
106 }
107
108 # This is an error counter which should be incremented every time there is an error.
109 my $errors = 0;
110 my $controlrequestaddr= ($control ? 'control' : 'request').$config{email_domain};
111 my $transcript_scalar = '';
112 my $transcript = IO::Scalar->new(\$transcript_scalar) or
113      die "Unable to create new IO::Scalar";
114 print {$transcript} "Processing commands for $controlrequestaddr:\n\n";
115
116 # debug level
117 my $dl = 0;
118 my $state= 'idle';
119 my $lowstate= 'idle';
120 my $mergelowstate= 'idle';
121 my $midix=0;
122
123 my $user = $replyto;
124 $user =~ s/,.*//;
125 $user =~ s/^.*<(.*)>.*$/$1/;
126 $user =~ s/[(].*[)]//;
127 $user =~ s/^\s*(\S+)\s+.*$/$1/;
128 $user = "" unless (Debbugs::User::is_valid_user($user));
129 my $indicated_user = 0;
130
131 my $quickabort = 0;
132
133
134 if (@gExcludeFromControl and grep {$replyto =~ m/\Q$_\E/} @gExcludeFromControl) {
135         print {$transcript} fill_template('mail/excluded_from_control');
136         $quickabort = 1;
137 }
138
139 my %limit_pkgs = ();
140 my %clonebugs = ();
141 my %bcc = ();
142
143
144 my @bcc;
145 sub addbcc {
146     push @bcc, $_[0] unless grep { $_ eq $_[0] } @bcc;
147 }
148
149 our $data;
150 our $message;
151 our $extramessage;
152 our $ref;
153
154 our $mismatch;
155 our $action;
156
157
158 # recipients of mail
159 my %recipients;
160 # affected_packages
161 my %affected_packages;
162 my $ok = 0;
163 my $unknowns = 0;
164 my $procline=0;
165 for ($procline=0; $procline<=$#bodylines; $procline++) {
166     my $noriginator;
167     my $newsubmitter;
168     my $oldsubmitter;
169     my $newowner;
170     $state eq 'idle' || print "state: $state ?\n";
171     $lowstate eq 'idle' || print "lowstate: $lowstate ?\n";
172     $mergelowstate eq 'idle' || print "mergelowstate: $mergelowstate ?\n";
173     if ($quickabort) {
174          print {$transcript} "Stopping processing here.\n\n";
175          last;
176     }
177     $_= $bodylines[$procline]; s/\s+$//;
178     next unless m/\S/;
179     print {$transcript} "> $_\n";
180     next if m/^\s*\#/;
181     $action= '';
182     if (m/^stop\s*$/i || m/^quit\s*$/i || m/^--\s*$/ || m/^thank(?:s|\s*you)?\s*$/i || m/^kthxbye\s*$/i) {
183         print {$transcript} "Stopping processing here.\n\n";
184         last;
185     } elsif (m/^debug\s+(\d+)$/i && $1 >= 0 && $1 <= 1000) {
186         $dl= $1+0;
187         print {$transcript} "Debug level $dl.\n\n";
188     } elsif (m/^(send|get)\s+\#?(\d{2,})$/i) {
189         $ref= $2+0;
190         &sendlynxdoc("bugreport.cgi?bug=$ref","logs for $gBug#$ref");
191     } elsif (m/^send-detail\s+\#?(\d{2,})$/i) {
192         $ref= $1+0;
193         &sendlynxdoc("bugreport.cgi?bug=$ref&boring=yes",
194                      "detailed logs for $gBug#$ref");
195     } elsif (m/^index(\s+full)?$/i) {
196         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
197         $errors++;
198         $ok++; # well, it's not really ok, but it fixes #81224 :)
199     } elsif (m/^index-summary\s+by-package$/i) {
200         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
201         $errors++;
202         $ok++; # well, it's not really ok, but it fixes #81224 :)
203     } elsif (m/^index-summary(\s+by-number)?$/i) {
204         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
205         $errors++;
206         $ok++; # well, it's not really ok, but it fixes #81224 :)
207     } elsif (m/^index(\s+|-)pack(age)?s?$/i) {
208         &sendlynxdoc("pkgindex.cgi?indexon=pkg",'index of packages');
209     } elsif (m/^index(\s+|-)maints?$/i) {
210         &sendlynxdoc("pkgindex.cgi?indexon=maint",'index of maintainers');
211     } elsif (m/^index(\s+|-)maint\s+(\S+)$/i) {
212         my $maint = $2;
213         &sendlynxdoc("pkgreport.cgi?maint=" . urlsanit($maint),
214                      "$gBug list for maintainer \`$maint'");
215         $ok++;
216     } elsif (m/^index(\s+|-)pack(age)?s?\s+(\S.*\S)$/i) {
217         my $package = $+;
218         &sendlynxdoc("pkgreport.cgi?pkg=" . urlsanit($package),
219                      "$gBug list for package $package");
220         $ok++;
221     } elsif (m/^send-unmatched(\s+this|\s+-?0)?$/i) {
222         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
223         $errors++;
224         $ok++; # well, it's not really ok, but it fixes #81224 :)
225     } elsif (m/^send-unmatched\s+(last|-1)$/i) {
226         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
227         $errors++;
228         $ok++; # well, it's not really ok, but it fixes #81224 :)
229     } elsif (m/^send-unmatched\s+(old|-2)$/i) {
230         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
231         $errors++;
232         $ok++; # well, it's not really ok, but it fixes #81224 :)
233     } elsif (m/^getinfo\s+([\w.-]+)$/i) {
234         # the following is basically a Debian-specific kludge, but who cares
235         my $req = $1;
236         if ($req =~ /^maintainers$/i && -f "$gConfigDir/Maintainers") {
237             &sendinfo("local", "$gConfigDir/Maintainers", "Maintainers file");
238         } elsif ($req =~ /^override\.(\w+)\.([\w.-]+)$/i) {
239             $req =~ s/.gz$//;
240             &sendinfo("ftp.d.o", "$req", "override file for $2 part of $1 distribution");
241         } elsif ($req =~ /^pseudo-packages\.(description|maintainers)$/i && -f "$gConfigDir/$req") {
242             &sendinfo("local", "$gConfigDir/$req", "$req file");
243         } else {
244             print {$transcript} "Info file $req does not exist.\n\n";
245         }
246     } elsif (m/^help/i) {
247         &sendhelp;
248         print {$transcript} "\n";
249         $ok++;
250     } elsif (m/^refcard/i) {
251         &sendtxthelp("bug-mailserver-refcard.txt","mail servers' reference card");
252     } elsif (m/^subscribe/i) {
253         print {$transcript} <<END;
254 There is no $gProject $gBug mailing list.  If you wish to review bug reports
255 please do so via http://$gWebDomain/ or ask this mail server
256 to send them to you.
257 soon: MAILINGLISTS_TEXT
258 END
259     } elsif (m/^unsubscribe/i) {
260         print {$transcript} <<END;
261 soon: UNSUBSCRIBE_TEXT
262 soon: MAILINGLISTS_TEXT
263 END
264     } elsif (m/^user\s+(\S+)\s*$/i) {
265         my $newuser = $1;
266         if (Debbugs::User::is_valid_user($newuser)) {
267             my $olduser = ($user ne "" ? " (was $user)" : "");
268             print {$transcript} "Setting user to $newuser$olduser.\n";
269             $user = $newuser;
270             $indicated_user = 1;
271         } else {
272             print {$transcript} "Selected user id ($newuser) invalid, sorry\n";
273             $errors++;
274             $user = "";
275             $indicated_user = 1;
276         }
277     } elsif (m/^usercategory\s+(\S+)(\s+\[hidden\])?\s*$/i) {
278         $ok++;
279         my $catname = $1;
280         my $hidden = ($2 ne "");
281
282         my $prefix = "";
283         my @cats;
284         my $bad = 0;
285         my $catsec = 0;
286         if ($user eq "") {
287             print {$transcript} "No valid user selected\n";
288             $errors++;
289             next;
290         }
291         if (not $indicated_user and defined $user) {
292              print {$transcript} "User is $user\n";
293              $indicated_user = 1;
294         }
295         my @ords = ();
296         while (++$procline <= $#bodylines) {
297             unless ($bodylines[$procline] =~ m/^\s*([*+])\s*(\S.*)$/) {
298                 $procline--;
299                 last;
300             }
301             print {$transcript} "> $bodylines[$procline]\n";
302             next if $bad;
303             my ($o, $txt) = ($1, $2);
304             if ($#cats == -1 && $o eq "+") {
305                 print {$transcript} "User defined category specification must start with a category name. Skipping.\n\n";
306                 $errors++;
307                 $bad = 1;
308                 next;
309             }
310             if ($o eq "+") {
311                 unless (ref($cats[-1]) eq "HASH") {
312                     $cats[-1] = { "nam" => $cats[-1], 
313                                   "pri" => [], "ttl" => [] };
314                 }
315                 $catsec++;
316                 my ($desc, $ord, $op);
317                 if ($txt =~ m/^(.*\S)\s*\[((\d+):\s*)?\]\s*$/) {
318                     $desc = $1; $ord = $3; $op = "";
319                 } elsif ($txt =~ m/^(.*\S)\s*\[((\d+):\s*)?(\S+)\]\s*$/) {
320                     $desc = $1; $ord = $3; $op = $4;
321                 } elsif ($txt =~ m/^([^[\s]+)\s*$/) {
322                     $desc = ""; $op = $1;
323                 } else {
324                     print {$transcript} "Unrecognised syntax for category section. Skipping.\n\n";
325                     $errors++;
326                     $bad = 1;
327                     next;
328                 }
329                 $ord = 999 unless defined $ord;
330
331                 if ($op) {
332                     push @{$cats[-1]->{"pri"}}, $prefix . $op;
333                     push @{$cats[-1]->{"ttl"}}, $desc;
334                     push @ords, "$ord $catsec";
335                 } else {
336                     $cats[-1]->{"def"} = $desc;
337                     push @ords, "$ord DEF";
338                     $catsec--;
339                 }
340                 @ords = sort { my ($a1, $a2, $b1, $b2) = split / /, "$a $b";
341                                $a1 <=> $b1 || $a2 <=> $b2; } @ords;
342                 $cats[-1]->{"ord"} = [map { m/^.* (\S+)/; $1 eq "DEF" ? $catsec + 1 : $1 } @ords];
343             } elsif ($o eq "*") {
344                 $catsec = 0;
345                 my ($name);
346                 if ($txt =~ m/^(.*\S)(\s*\[(\S+)\])\s*$/) {
347                     $name = $1; $prefix = $3;
348                 } else {
349                     $name = $txt; $prefix = "";
350                 }
351                 push @cats, $name;
352             }
353         }
354         # XXX: got @cats, now do something with it
355         my $u = Debbugs::User::get_user($user);
356         if (@cats) {
357             print {$transcript} "Added usercategory $catname.\n\n";
358             $u->{"categories"}->{$catname} = [ @cats ];
359             if (not $hidden) {
360                  push @{$u->{visible_cats}},$catname;
361             }
362         } else {
363             print {$transcript} "Removed usercategory $catname.\n\n";
364             delete $u->{"categories"}->{$catname};
365             @{$u->{visible_cats}} = grep {$_ ne $catname} @{$u->{visible_cats}};
366         }
367         $u->write();
368     } elsif (m/^usertags?\s+\#?(-?\d+)\s+(([=+-])\s*)?(\S.*)?$/i) {
369         $ok++;
370         $ref = $1;
371         my $addsubcode = $3 || "+";
372         my $tags = $4;
373         if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
374              $ref = $clonebugs{$ref};
375         }
376         if ($user eq "") {
377             print {$transcript} "No valid user selected\n";
378             $errors++;
379             $indicated_user = 1;
380         } elsif (&setbug) {
381             if (not $indicated_user and defined $user) {
382                  print {$transcript} "User is $user\n";
383                  $indicated_user = 1;
384             }
385             &nochangebug;
386             my %ut;
387             Debbugs::User::read_usertags(\%ut, $user);
388             my @oldtags = (); my @newtags = (); my @badtags = ();
389             my %chtags;
390             for my $t (split /[,\s]+/, $tags) {
391                 if ($t =~ m/^[a-zA-Z0-9.+\@-]+$/) {
392                     $chtags{$t} = 1;
393                 } else {
394                     push @badtags, $t;
395                 }
396             }
397             if (@badtags) {
398                 print {$transcript} "Ignoring illegal tag/s: ".join(', ', @badtags).".\nPlease use only alphanumerics, at, dot, plus and dash.\n";
399                 $errors++;
400             }
401             for my $t (keys %chtags) {
402                 $ut{$t} = [] unless defined $ut{$t};
403             }
404             for my $t (keys %ut) {
405                 my %res = map { ($_, 1) } @{$ut{$t}};
406                 push @oldtags, $t if defined $res{$ref};
407                 my $addop = ($addsubcode eq "+" or $addsubcode eq "=");
408                 my $del = (defined $chtags{$t} ? $addsubcode eq "-" 
409                                                : $addsubcode eq "=");
410                 $res{$ref} = 1 if ($addop && defined $chtags{$t});
411                 delete $res{$ref} if ($del);
412                 push @newtags, $t if defined $res{$ref};
413                 $ut{$t} = [ sort { $a <=> $b } (keys %res) ];
414             }
415             if (@oldtags == 0) {
416                 print {$transcript} "There were no usertags set.\n";
417             } else {
418                 print {$transcript} "Usertags were: " . join(" ", @oldtags) . ".\n";
419             }
420             print {$transcript} "Usertags are now: " . join(" ", @newtags) . ".\n";
421             Debbugs::User::write_usertags(\%ut, $user);
422         }
423     } elsif (!$control) {
424         print {$transcript} <<END;
425 Unknown command or malformed arguments to command.
426 (Use control\@$gEmailDomain to manipulate reports.)
427
428 END
429         $errors++;
430         if (++$unknowns >= 3) {
431             print {$transcript} "Too many unknown commands, stopping here.\n\n";
432             last;
433         }
434 #### "developer only" ones start here
435     } elsif (m/^close\s+\#?(-?\d+)(?:\s+(\d.*))?$/i) {
436         $ok++;
437         $ref= $1;
438         $bug_affected{$ref}=1;
439         my $version= $2;
440         if (&setbug) {
441             print {$transcript} "'close' is deprecated; see http://$gWebDomain/Developer$gHTMLSuffix#closing.\n";
442             if (length($data->{done}) and not defined($version)) {
443                 print {$transcript} "$gBug is already closed, cannot re-close.\n\n";
444                 &nochangebug;
445             } else {
446                 $action= "$gBug " .
447                     (defined($version) ?
448                         "marked as fixed in version $version" :
449                         "closed") .
450                     ", send any further explanations to $data->{originator}";
451                 do {
452                    $affected_packages{$data->{package}} = 1;
453                    add_recipients(data => $data,
454                                    recipients => \%recipients,
455                                    actions_taken => {done => 1},
456                                   );
457                     $data->{done}= $replyto;
458                     my @keywords= split ' ', $data->{keywords};
459                     my $extramessage = '';
460                     if (grep $_ eq 'pending', @keywords) {
461                         $extramessage= "Removed pending tag.\n";
462                         $data->{keywords}= join ' ', grep $_ ne 'pending',
463                                                 @keywords;
464                     }
465                     addfixedversions($data, $data->{package}, $version, 'binary');
466
467                     my $message= <<END;
468 From: $gMaintainerEmail ($gProject $gBug Tracking System)
469 To: $data->{originator}
470 Subject: $gBug#$ref acknowledged by developer
471          ($header{'subject'})
472 References: $header{'message-id'} $data->{msgid}
473 In-Reply-To: $data->{msgid}
474 Message-ID: <handler.$ref.$nn.notifdonectrl.$midix\@$gEmailDomain>
475 Reply-To: $ref\@$gEmailDomain
476 X-$gProject-PR-Message: they-closed-control $ref
477
478 This is an automatic notification regarding your $gBug report
479 #$ref: $data->{subject},
480 which was filed against the $data->{package} package.
481
482 It has been marked as closed by one of the developers, namely
483 $replyto.
484
485 You should be hearing from them with a substantive response shortly,
486 in case you haven't already. If not, please contact them directly.
487
488 $gMaintainer
489 (administrator, $gProject $gBugs database)
490
491 END
492                     &sendmailmessage($message,$data->{originator});
493                 } while (&getnextbug);
494             }
495         }
496     } elsif (m/^reassign\s+\#?(-?\d+)\s+(\S+)(?:\s+(\d.*))?$/i) {
497         $ok++;
498         $ref= $1;
499         my $newpackage= $2;
500         $bug_affected{$ref}=1;
501         my $version= $3;
502         $newpackage =~ y/A-Z/a-z/;
503         if (&setbug) {
504             if (length($data->{package})) {
505                 $action= "$gBug reassigned from package \`$data->{package}'".
506                          " to \`$newpackage'.";
507             } else {
508                 $action= "$gBug assigned to package \`$newpackage'.";
509             }
510             do {
511                 $affected_packages{$data->{package}} = 1;
512                 add_recipients(data => $data, recipients => \%recipients);
513                 $data->{package}= $newpackage;
514                 $data->{found_versions}= [];
515                 $data->{fixed_versions}= [];
516                 # TODO: what if $newpackage is a source package?
517                 addfoundversions($data, $data->{package}, $version, 'binary');
518                 add_recipients(data => $data, recipients => \%recipients);
519             } while (&getnextbug);
520         }
521     } elsif (m/^reopen\s+\#?(-?\d+)$/i ? ($noriginator='', 1) :
522              m/^reopen\s+\#?(-?\d+)\s+\=$/i ? ($noriginator='', 1) :
523              m/^reopen\s+\#?(-?\d+)\s+\!$/i ? ($noriginator=$replyto, 1) :
524              m/^reopen\s+\#?(-?\d+)\s+(\S.*\S)$/i ? ($noriginator=$2, 1) : 0) {
525         $ok++;
526         $ref= $1;
527         $bug_affected{$ref}=1;
528         if (&setbug) {
529             if (@{$data->{fixed_versions}}) {
530                 print {$transcript} "'reopen' may be inappropriate when a bug has been closed with a version;\nyou may need to use 'found' to remove fixed versions.\n";
531             }
532             if (!length($data->{done})) {
533                 print {$transcript} "$gBug is already open, cannot reopen.\n\n";
534                 &nochangebug;
535             } else {
536                 $action=
537                     $noriginator eq '' ? "$gBug reopened, originator not changed." :
538                         "$gBug reopened, originator set to $noriginator.";
539                 do {
540                     $affected_packages{$data->{package}} = 1;
541                     add_recipients(data => $data, recipients => \%recipients);
542                     $data->{originator}= $noriginator eq '' ?  $data->{originator} : $noriginator;
543                     $data->{fixed_versions}= [];
544                     $data->{done}= '';
545                 } while (&getnextbug);
546             }
547         }
548     } elsif (m{^found\s+\#?(-?\d+)
549                (?:\s+((?:$config{package_name_re}\/)?
550                     $config{package_version_re}))?$}ix) {
551         $ok++;
552         $ref= $1;
553         my $version= $2;
554         if (&setbug) {
555             if (!length($data->{done}) and not defined($version)) {
556                 print {$transcript} "$gBug is already open, cannot reopen.\n\n";
557                 $errors++;
558                 &nochangebug;
559             } else {
560                 $action=
561                     defined($version) ?
562                         "$gBug marked as found in version $version." :
563                         "$gBug reopened.";
564                 do {
565                     $affected_packages{$data->{package}} = 1;
566                     add_recipients(data => $data, recipients => \%recipients);
567                     # The 'done' field gets a bit weird with version
568                     # tracking, because a bug may be closed by multiple
569                     # people in different branches. Until we have something
570                     # more flexible, we set it every time a bug is fixed,
571                     # and clear it when a bug is found in a version greater
572                     # than any version in which the bug is fixed or when
573                     # a bug is found and there is no fixed version
574                     if (defined $version) {
575                         my ($version_only) = $version =~ m{([^/]+)$};
576                         addfoundversions($data, $data->{package}, $version, 'binary');
577                         my @fixed_order = sort {Debbugs::Versions::Dpkg::vercmp($a,$b);}
578                              map {s{.+/}{}; $_;} @{$data->{fixed_versions}};
579                         if (not @fixed_order or (Debbugs::Versions::Dpkg::vercmp($version_only,$fixed_order[-1]) >= 0)) {
580                              $action = "$gBug marked as found in version $version and reopened."
581                                   if length $data->{done};
582                              $data->{done} = '';
583                         }
584                     } else {
585                         # Versionless found; assume old-style "not fixed at
586                         # all".
587                         $data->{fixed_versions} = [];
588                         $data->{done} = '';
589                     }
590                 } while (&getnextbug);
591             }
592         }
593     } elsif (m[^notfound\s+\#?(-?\d+)\s+
594                ((?:$config{package_name_re}\/)?
595                     \S+)\s*$]ix) {
596         $ok++;
597         $ref= $1;
598         my $version= $2;
599         if (&setbug) {
600             $action= "$gBug no longer marked as found in version $version.";
601             if (length($data->{done})) {
602                 $extramessage= "(By the way, this $gBug is currently marked as done.)\n";
603             }
604             do {
605                 $affected_packages{$data->{package}} = 1;
606                 add_recipients(data => $data, recipients => \%recipients);
607                 removefoundversions($data, $data->{package}, $version, 'binary');
608             } while (&getnextbug);
609        }
610    }
611     elsif (m[^fixed\s+\#?(-?\d+)\s+
612              ((?:$config{package_name_re}\/)?
613                   $config{package_version_re})\s*$]ix) {
614         $ok++;
615         $ref= $1;
616         my $version= $2;
617         if (&setbug) {
618              $action=
619                   defined($version) ?
620                        "$gBug marked as fixed in version $version." :
621                             "$gBug reopened.";
622                 do {
623                     $affected_packages{$data->{package}} = 1;
624                     add_recipients(data => $data, recipients => \%recipients);
625                     addfixedversions($data, $data->{package}, $version, 'binary');
626                } while (&getnextbug);
627         }
628    }
629     elsif (m[^notfixed\s+\#?(-?\d+)\s+
630              ((?:$config{package_name_re}\/)?
631                   \S+)\s*$]ix) {
632         $ok++;
633         $ref= $1;
634         my $version= $2;
635         if (&setbug) {
636              $action=
637                   defined($version) ?
638                        "$gBug no longer marked as fixed in version $version." :
639                             "$gBug reopened.";
640                 do {
641                     $affected_packages{$data->{package}} = 1;
642                     add_recipients(data => $data, recipients => \%recipients);
643                     removefixedversions($data, $data->{package}, $version, 'binary');
644                } while (&getnextbug);
645         }
646    }
647     elsif (m/^submitter\s+\#?(-?\d+)\s+\!$/i ? ($newsubmitter=$replyto, 1) :
648              m/^submitter\s+\#?(-?\d+)\s+(\S.*\S)$/i ? ($newsubmitter=$2, 1) : 0) {
649         $ok++;
650         $ref= $1;
651         $bug_affected{$ref}=1;
652         if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
653             $ref = $clonebugs{$ref};
654         }
655         if (not Mail::RFC822::Address::valid($newsubmitter)) {
656              transcript("$newsubmitter is not a valid e-mail address; not changing submitter\n");
657              $errors++;
658         }
659         elsif (&getbug) {
660             if (&checkpkglimit) {
661                 &foundbug;
662                 $affected_packages{$data->{package}} = 1;
663                 add_recipients(data => $data, recipients => \%recipients);
664                 $oldsubmitter= $data->{originator};
665                 $data->{originator}= $newsubmitter;
666                 $action= "Changed $gBug submitter from $oldsubmitter to $newsubmitter.";
667                 &savebug;
668                 print {$transcript} "$action\n";
669                 if (length($data->{done})) {
670                     print {$transcript} "(By the way, that $gBug is currently marked as done.)\n";
671                 }
672                 print {$transcript} "\n";
673                 $message= <<END;
674 From: $gMaintainerEmail ($gProject $gBug Tracking System)
675 To: $oldsubmitter
676 Subject: $gBug#$ref submitter address changed
677          ($header{'subject'})
678 References: $header{'message-id'} $data->{msgid}
679 In-Reply-To: $data->{msgid}
680 Message-ID: <handler.$ref.$nn.newsubmitter.$midix\@$gEmailDomain>
681 Reply-To: $ref\@$gEmailDomain
682 X-$gProject-PR-Message: submitter-changed $ref
683
684 The submitter address recorded for your $gBug report
685 #$ref: $data->{subject}
686 has been changed.
687
688 The old submitter address for this report was
689 $oldsubmitter.
690 The new submitter address is
691 $newsubmitter.
692
693 This change was made by
694 $replyto.
695 If it was incorrect, please contact them directly.
696
697 $gMaintainer
698 (administrator, $gProject $gBugs database)
699
700 END
701                 &sendmailmessage($message,$oldsubmitter);
702             } else {
703                 &cancelbug;
704             }
705         } else {
706             &notfoundbug;
707         }
708     } elsif (m/^forwarded\s+\#?(-?\d+)\s+(\S.*\S)$/i) {
709         $ok++;
710         $ref= $1;
711         my $whereto= $2;
712         $bug_affected{$ref}=1;
713         if (&setbug) {
714             if (length($data->{forwarded})) {
715     $action= "Forwarded-to-address changed from $data->{forwarded} to $whereto.";
716             } else {
717     $action= "Noted your statement that $gBug has been forwarded to $whereto.";
718             }
719             if (length($data->{done})) {
720                 $extramessage= "(By the way, this $gBug is currently marked as done.)\n";
721             }
722             do {
723                 $affected_packages{$data->{package}} = 1;
724                 add_recipients(data => $data,
725                                recipients => \%recipients,
726                                actions_taken => {forwarded => 1},
727                               );
728                 $data->{forwarded}= $whereto;
729             } while (&getnextbug);
730         }
731     } elsif (m/^notforwarded\s+\#?(-?\d+)$/i) {
732         $ok++;
733         $ref= $1;
734         $bug_affected{$ref}=1;
735         if (&setbug) {
736             if (!length($data->{forwarded})) {
737                 print {$transcript} "$gBug is not marked as having been forwarded.\n\n";
738                 &nochangebug;
739             } else {
740     $action= "Removed annotation that $gBug had been forwarded to $data->{forwarded}.";
741                 do {
742                     $affected_packages{$data->{package}} = 1;
743                     add_recipients(data => $data, recipients => \%recipients);
744                     $data->{forwarded}= '';
745                 } while (&getnextbug);
746             }
747         }
748     } elsif (m/^severity\s+\#?(-?\d+)\s+([-0-9a-z]+)$/i ||
749         m/^priority\s+\#?(-?\d+)\s+([-0-9a-z]+)$/i) {
750         $ok++;
751         $ref= $1;
752         $bug_affected{$ref}=1;
753         my $newseverity= $2;
754         if (!grep($_ eq $newseverity, @gSeverityList, "$gDefaultSeverity")) {
755              print {$transcript} "Severity level \`$newseverity' is not known.\n".
756                   "Recognized are: $gShowSeverities.\n\n";
757             $errors++;
758         } elsif (exists $gObsoleteSeverities{$newseverity}) {
759             print {$transcript} "Severity level \`$newseverity' is obsolete. " .
760                  "Use $gObsoleteSeverities{$newseverity} instead.\n\n";
761                 $errors++;
762         } elsif (&setbug) {
763             my $printseverity= $data->{severity};
764             $printseverity= "$gDefaultSeverity" if $printseverity eq '';
765             $action= "Severity set to \`$newseverity' from \`$printseverity'";
766             do {
767                 $affected_packages{$data->{package}} = 1;
768                 add_recipients(data => $data, recipients => \%recipients);
769                 if (defined $gStrongList and isstrongseverity($newseverity)) {
770                     addbcc("$gStrongList\@$gListDomain");
771                 }
772                 $data->{severity}= $newseverity;
773             } while (&getnextbug);
774         }
775     } elsif (m/^tags?\s+\#?(-?\d+)\s+(([=+-])\s*)?(\S.*)?$/i) {
776         $ok++;
777         $ref = $1;
778         my $addsubcode = $3;
779         my $tags = $4;
780         $bug_affected{$ref}=1;
781         my $addsub = "add";
782         if (defined $addsubcode) {
783             $addsub = "sub" if ($addsubcode eq "-");
784             $addsub = "add" if ($addsubcode eq "+");
785             $addsub = "set" if ($addsubcode eq "=");
786         }
787         my @okaytags = ();
788         my @badtags = ();
789         foreach my $t (split /[\s,]+/, $tags) {
790             if (!grep($_ eq $t, @gTags)) {
791                 push @badtags, $t;
792             } else {
793                 push @okaytags, $t;
794             }
795         }
796         if (@badtags) {
797             print {$transcript} "Unknown tag/s: ".join(', ', @badtags).".\n".
798                  "Recognized are: ".join(' ', @gTags).".\n\n";
799             $errors++;
800         }
801         if (&setbug) {
802             if ($data->{keywords} eq '') {
803                 print {$transcript} "There were no tags set.\n";
804             } else {
805                 print {$transcript} "Tags were: $data->{keywords}\n";
806             }
807             if ($addsub eq "set") {
808                 $action= "Tags set to: " . join(", ", @okaytags);
809             } elsif ($addsub eq "add") {
810                 $action= "Tags added: " . join(", ", @okaytags);
811             } elsif ($addsub eq "sub") {
812                 $action= "Tags removed: " . join(", ", @okaytags);
813             }
814             do {
815                 $affected_packages{$data->{package}} = 1;
816                 add_recipients(data => $data, recipients => \%recipients);
817                 $data->{keywords} = '' if ($addsub eq "set");
818                 # Allow removing obsolete tags.
819                 if ($addsub eq "sub") {
820                     foreach my $t (@badtags) {
821                         $data->{keywords} = join ' ', grep $_ ne $t, 
822                             split ' ', $data->{keywords};
823                     }
824                 }
825                 # Now process all other additions and subtractions.
826                 foreach my $t (@okaytags) {
827                     $data->{keywords} = join ' ', grep $_ ne $t, 
828                         split ' ', $data->{keywords};
829                     $data->{keywords} = "$t $data->{keywords}" unless($addsub eq "sub");
830                 }
831                 $data->{keywords} =~ s/\s*$//;
832             } while (&getnextbug);
833         }
834     } elsif (m/^(un)?block\s+\#?(-?\d+)\s+(by|with)\s+(\S.*)?$/i) {
835         $ok++;
836         my $bugnum = $2; my $blockers = $4;
837         my $addsub = "add";
838         $addsub = "sub" if ($1 eq "un");
839         if ($bugnum =~ m/^-\d+$/ && defined $clonebugs{$bugnum}) {
840              $bugnum = $clonebugs{$bugnum};
841         }
842
843         my @okayblockers;
844         my @badblockers;
845         foreach my $b (split /[\s,]+/, $blockers) {
846             $b=~s/^\#//;
847             if ($b=~/[0-9]+/) {
848                 $ref=$b;
849                 if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
850                      $ref = $clonebugs{$ref};
851                 }
852                 if (&getbug) {
853                     &foundbug;
854                     push @okayblockers, $ref;
855
856                     # add to the list all bugs that are merged with $b,
857                     # because all of their data must be kept in sync
858                     my @thisbugmergelist= split(/ /,$data->{mergedwith});
859                     &cancelbug;
860
861                     foreach $ref (@thisbugmergelist) {
862                         if (&getbug) {
863                            push @okayblockers, $ref;
864                            &cancelbug;
865                         }
866                     }
867                 }
868                 else {
869                     &notfoundbug;
870                     push @badblockers, $ref;
871                 }
872             }
873             else {
874                 push @badblockers, $b;
875             }
876         }
877         if (@badblockers) {
878             print {$transcript} "Unknown blocking bug/s: ".join(', ', @badblockers).".\n";
879             $errors++;
880         }
881         
882         $ref=$bugnum;
883         if (&setbug) {
884             if ($data->{blockedby} eq '') {
885                 print {$transcript} "Was not blocked by any bugs.\n";
886             } else {
887                 print {$transcript} "Was blocked by: $data->{blockedby}\n";
888             }
889             if ($addsub eq "set") {
890                 $action= "Blocking bugs of $bugnum set to: " . join(", ", @okayblockers);
891             } elsif ($addsub eq "add") {
892                 $action= "Blocking bugs of $bugnum added: " . join(", ", @okayblockers);
893             } elsif ($addsub eq "sub") {
894                 $action= "Blocking bugs of $bugnum removed: " . join(", ", @okayblockers);
895             }
896             my %removedblocks;
897             my %addedblocks;
898             do {
899                 $affected_packages{$data->{package}} = 1;
900                 add_recipients(data => $data, recipients => \%recipients);
901                 my @oldblockerlist = split ' ', $data->{blockedby};
902                 $data->{blockedby} = '' if ($addsub eq "set");
903                 foreach my $b (@okayblockers) {
904                         $data->{blockedby} = manipset($data->{blockedby}, $b,
905                                 ($addsub ne "sub"));
906                 }
907
908                 foreach my $b (@oldblockerlist) {
909                         if (! grep { $_ eq $b } split ' ', $data->{blockedby}) {
910                                 push @{$removedblocks{$b}}, $ref;
911                         }
912                 }
913                 foreach my $b (split ' ', $data->{blockedby}) {
914                         if (! grep { $_ eq $b } @oldblockerlist) {
915                                 push @{$addedblocks{$b}}, $ref;
916                         }
917                 }
918             } while (&getnextbug);
919
920             # Now that the blockedby data is updated, change blocks data
921             # to match the changes.
922             foreach $ref (keys %addedblocks) {
923                 if (&getbug) {
924                     foreach my $b (@{$addedblocks{$ref}}) {
925                         $data->{blocks} = manipset($data->{blocks}, $b, 1);
926                     }
927                     &savebug;
928                 }
929             }
930             foreach $ref (keys %removedblocks) {
931                 if (&getbug) {
932                     foreach my $b (@{$removedblocks{$ref}}) {
933                         $data->{blocks} = manipset($data->{blocks}, $b, 0);
934                     }
935                     &savebug;
936                 }
937             }
938         }
939     } elsif (m/^retitle\s+\#?(-?\d+)\s+(\S.*\S)\s*$/i) {
940         $ok++;
941         $ref= $1; my $newtitle= $2;
942         $bug_affected{$ref}=1;
943         if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
944             $ref = $clonebugs{$ref};
945         }
946         if (&getbug) {
947             if (&checkpkglimit) {
948                 &foundbug;
949                 $affected_packages{$data->{package}} = 1;
950                 add_recipients(data => $data, recipients => \%recipients);
951                 my $oldtitle = $data->{subject};
952                 $data->{subject}= $newtitle;
953                 $action= "Changed $gBug title to `$newtitle' from `$oldtitle'.";
954                 &savebug;
955                 print {$transcript} "$action\n";
956                 if (length($data->{done})) {
957                     print {$transcript} "(By the way, that $gBug is currently marked as done.)\n";
958                 }
959                 print {$transcript} "\n";
960             } else {
961                 &cancelbug;
962             }
963         } else {
964             &notfoundbug;
965         }
966     } elsif (m/^unmerge\s+\#?(-?\d+)$/i) {
967         $ok++;
968         $ref= $1;
969         $bug_affected{$ref} = 1;
970         if (&setbug) {
971             if (!length($data->{mergedwith})) {
972                 print {$transcript} "$gBug is not marked as being merged with any others.\n\n";
973                 &nochangebug;
974             } else {
975                 $mergelowstate eq 'locked' || die "$mergelowstate ?";
976                 $action= "Disconnected #$ref from all other report(s).";
977                 my @newmergelist= split(/ /,$data->{mergedwith});
978                 my $discref= $ref;
979                 @bug_affected{@newmergelist} = 1 x @newmergelist;
980                 do {
981                     $affected_packages{$data->{package}} = 1;
982                     add_recipients(data => $data, recipients => \%recipients);
983                     $data->{mergedwith}= ($ref == $discref) ? ''
984                         : join(' ',grep($_ ne $ref,@newmergelist));
985                 } while (&getnextbug);
986             }
987         }
988     } elsif (m/^merge\s+#?(-?\d+(\s+#?-?\d+)+)\s*$/i) {
989         $ok++;
990         my @tomerge= sort { $a <=> $b } split(/\s+#?/,$1);
991         my @newmergelist= ();
992         my %tags = ();
993         my %found = ();
994         my %fixed = ();
995         &getmerge;
996         while (defined($ref= shift(@tomerge))) {
997             print {$transcript} "D| checking merge $ref\n" if $dl;
998             $ref+= 0;
999             if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
1000                 $ref = $clonebugs{$ref};
1001             }
1002             next if grep($_ == $ref,@newmergelist);
1003             if (!&getbug) { &notfoundbug; @newmergelist=(); last }
1004             if (!&checkpkglimit) { &cancelbug; @newmergelist=(); last; }
1005             &foundbug;
1006             print {$transcript} "D| adding $ref ($data->{mergedwith})\n" if $dl;
1007             $mismatch= '';
1008             &checkmatch('package','m_package',$data->{package},@newmergelist);
1009             &checkmatch('forwarded addr','m_forwarded',$data->{forwarded},@newmergelist);
1010             $data->{severity} = '$gDefaultSeverity' if $data->{severity} eq '';
1011             &checkmatch('severity','m_severity',$data->{severity},@newmergelist);
1012             &checkmatch('blocks','m_blocks',$data->{blocks},@newmergelist);
1013             &checkmatch('blocked-by','m_blockedby',$data->{blockedby},@newmergelist);
1014             &checkmatch('done mark','m_done',length($data->{done}) ? 'done' : 'open',@newmergelist);
1015             &checkmatch('owner','m_owner',$data->{owner},@newmergelist);
1016             &checkmatch('summary','m_summary',$data->{summary},@newmergelist);
1017             &checkmatch('affects','m_affects',$data->{affects},@newmergelist);
1018             foreach my $t (split /\s+/, $data->{keywords}) { $tags{$t} = 1; }
1019             foreach my $f (@{$data->{found_versions}}) { $found{$f} = 1; }
1020             foreach my $f (@{$data->{fixed_versions}}) { $fixed{$f} = 1; }
1021             if (length($mismatch)) {
1022                 print {$transcript} "Mismatch - only $gBugs in same state can be merged:\n".
1023                      $mismatch."\n";
1024                 $errors++;
1025                 &cancelbug; @newmergelist=(); last;
1026             }
1027             push(@newmergelist,$ref);
1028             push(@tomerge,split(/ /,$data->{mergedwith}));
1029             &cancelbug;
1030         }
1031         if (@newmergelist) {
1032             @newmergelist= sort { $a <=> $b } @newmergelist;
1033             $action= "Merged @newmergelist.";
1034             delete @fixed{keys %found};
1035             for $ref (@newmergelist) {
1036                 &getbug || die "huh ?  $gBug $ref disappeared during merge";
1037                 $affected_packages{$data->{package}} = 1;
1038                 add_recipients(data => $data, recipients => \%recipients);
1039                 @bug_affected{@newmergelist} = 1 x @newmergelist;
1040                 $data->{mergedwith}= join(' ',grep($_ != $ref,@newmergelist));
1041                 $data->{keywords}= join(' ', keys %tags);
1042                 $data->{found_versions}= [sort keys %found];
1043                 $data->{fixed_versions}= [sort keys %fixed];
1044                 &savebug;
1045             }
1046             print {$transcript} "$action\n\n";
1047         }
1048         &endmerge;
1049     } elsif (m/^forcemerge\s+\#?(-?\d+(?:\s+\#?-?\d+)+)\s*$/i) {
1050         $ok++;
1051         my @temp = split /\s+\#?/,$1;
1052         my $master_bug = shift @temp;
1053         my $master_bug_data;
1054         my @tomerge = sort { $a <=> $b } @temp;
1055         unshift @tomerge,$master_bug;
1056         print {$transcript} "D| force merging ".join(',',@tomerge)."\n" if $dl;
1057         my @newmergelist= ();
1058         my %tags = ();
1059         my %found = ();
1060         my %fixed = ();
1061         # Here we try to do the right thing.
1062         # First, if the bugs are in the same package, we merge all of the found, fixed, and tags.
1063         # If not, we discard the found and fixed.
1064         # Everything else we set to the values of the first bug.
1065         &getmerge;
1066         while (defined($ref= shift(@tomerge))) {
1067             print {$transcript} "D| checking merge $ref\n" if $dl;
1068             $ref+= 0;
1069             if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
1070                 $ref = $clonebugs{$ref};
1071             }
1072             next if grep($_ == $ref,@newmergelist);
1073             if (!&getbug) { &notfoundbug; @newmergelist=(); last }
1074             if (!&checkpkglimit) { &cancelbug; @newmergelist=(); last; }
1075             &foundbug;
1076             print {$transcript} "D| adding $ref ($data->{mergedwith})\n" if $dl;
1077             $master_bug_data = $data if not defined $master_bug_data;
1078             if ($data->{package} ne $master_bug_data->{package}) {
1079                  print {$transcript} "Mismatch - only $gBugs in the same package can be forcibly merged:\n".
1080                      "$gBug $ref is not in the same package as $master_bug\n";
1081                 $errors++;
1082                 &cancelbug; @newmergelist=(); last;
1083             }
1084             for my $t (split /\s+/,$data->{keywords}) {
1085                  $tags{$t} = 1;
1086             }
1087             @found{@{$data->{found_versions}}} = (1) x @{$data->{found_versions}};
1088             @fixed{@{$data->{fixed_versions}}} = (1) x @{$data->{fixed_versions}};
1089             push(@newmergelist,$ref);
1090             push(@tomerge,split(/ /,$data->{mergedwith}));
1091             &cancelbug;
1092         }
1093         if (@newmergelist) {
1094             @newmergelist= sort { $a <=> $b } @newmergelist;
1095             $action= "Forcibly Merged @newmergelist.";
1096             delete @fixed{keys %found};
1097             for $ref (@newmergelist) {
1098                 &getbug || die "huh ?  $gBug $ref disappeared during merge";
1099                 $affected_packages{$data->{package}} = 1;
1100                 add_recipients(data => $data, recipients => \%recipients);
1101                 @bug_affected{@newmergelist} = 1 x @newmergelist;
1102                 $data->{mergedwith}= join(' ',grep($_ != $ref,@newmergelist));
1103                 $data->{keywords}= join(' ', keys %tags);
1104                 $data->{found_versions}= [sort keys %found];
1105                 $data->{fixed_versions}= [sort keys %fixed];
1106                 my @field_list = qw(forwarded package severity blocks blockedby owner done affects summary);
1107                 @{$data}{@field_list} = @{$master_bug_data}{@field_list};
1108                 &savebug;
1109             }
1110             print {$transcript} "$action\n\n";
1111         }
1112         &endmerge;
1113     } elsif (m/^clone\s+#?(\d+)\s+((-\d+\s+)*-\d+)\s*$/i) {
1114         $ok++;
1115
1116         my $origref = $1;
1117         my @newclonedids = split /\s+/, $2;
1118         my $newbugsneeded = scalar(@newclonedids);
1119
1120         $ref = $origref;
1121         $bug_affected{$ref} = 1;
1122         if (&setbug) {
1123             $affected_packages{$data->{package}} = 1;
1124             if (length($data->{mergedwith})) {
1125                 print {$transcript} "$gBug is marked as being merged with others. Use an existing clone.\n\n";
1126                 $errors++;
1127                 &nochangebug;
1128             } else {
1129                 &filelock("nextnumber.lock");
1130                 open(N,"nextnumber") || die "nextnumber: read: $!";
1131                 my $v=<N>; $v =~ s/\n$// || die "nextnumber bad format";
1132                 my $firstref= $v+0;  $v += $newbugsneeded;
1133                 open(NN,">nextnumber"); print NN "$v\n"; close(NN);
1134                 &unfilelock;
1135
1136                 my $lastref = $firstref + $newbugsneeded - 1;
1137
1138                 if ($newbugsneeded == 1) {
1139                     $action= "$gBug $origref cloned as bug $firstref.";
1140                 } else {
1141                     $action= "$gBug $origref cloned as bugs $firstref-$lastref.";
1142                 }
1143
1144                 my $blocks = $data->{blocks};
1145                 my $blockedby = $data->{blockedby};
1146                 
1147                 &getnextbug;
1148                 my $ohash = get_hashname($origref);
1149                 my $clone = $firstref;
1150                 @bug_affected{@newclonedids} = 1 x @newclonedids;
1151                 for my $newclonedid (@newclonedids) {
1152                     $clonebugs{$newclonedid} = $clone;
1153             
1154                     my $hash = get_hashname($clone);
1155                     copy("db-h/$ohash/$origref.log", "db-h/$hash/$clone.log");
1156                     copy("db-h/$ohash/$origref.status", "db-h/$hash/$clone.status");
1157                     copy("db-h/$ohash/$origref.summary", "db-h/$hash/$clone.summary");
1158                     copy("db-h/$ohash/$origref.report", "db-h/$hash/$clone.report");
1159                     &bughook('new', $clone, $data);
1160                 
1161                     # Update blocking info of bugs blocked by or blocking the
1162                     # cloned bug.
1163                     foreach $ref (split ' ', $blocks) {
1164                         &getbug;
1165                         $data->{blockedby} = manipset($data->{blockedby}, $clone, 1);
1166                         &savebug;
1167                     }
1168                     foreach $ref (split ' ', $blockedby) {
1169                         &getbug;
1170                         $data->{blocks} = manipset($data->{blocks}, $clone, 1);
1171                         &savebug;
1172                     }
1173
1174                     $clone++;
1175                 }
1176             }
1177         }
1178     } elsif (m/^package\:?\s+(\S.*\S)?\s*$/i) {
1179         $ok++;
1180         my @pkgs = split /\s+/, $1;
1181         if (scalar(@pkgs) > 0) {
1182                 %limit_pkgs = map { ($_, 1) } @pkgs;
1183                 print {$transcript} "Ignoring bugs not assigned to: " .
1184                         join(" ", keys(%limit_pkgs)) . "\n\n";
1185         } else {
1186                 %limit_pkgs = ();
1187                 print {$transcript} "Not ignoring any bugs.\n\n";
1188         }
1189     } elsif (m/^affects?\s+\#?(-?\d+)(?:\s+((?:[=+-])?)\s*(\S.*)?)?\s*$/i) {
1190         $ok++;
1191         $ref = $1;
1192         my $add_remove = $2 || '';
1193         my $packages = $3 || '';
1194         $ref = $clonebugs{$ref} if exists $clonebugs{$ref};
1195         $bug_affected{$ref} = 1;
1196         eval {
1197              affects(bug          => $ref,
1198                      transcript   => $transcript,
1199                      ($dl > 0 ? (debug => $transcript):()),
1200                      requester    => $header{from},
1201                      request_addr => $controlrequestaddr,
1202                      message      => \@log,
1203                      recipients   => \%recipients,
1204                      packages     => [splitpackages($3)],
1205                      ($add_remove eq '+'?(add => 1):()),
1206                      ($add_remove eq '-'?(remove => 1):()),
1207                     );
1208         };
1209         if ($@) {
1210             $errors++;
1211             print {$transcript} "Failed to give $ref a summary: $@";
1212         }
1213
1214     } elsif (m/^summary\s+\#?(-?\d+)\s*(\d+|)\s*$/i) {
1215         $ok++;
1216         $ref = $1;
1217         my $summary_msg = length($2)?$2:undef;
1218         $ref = $clonebugs{$ref} if exists $clonebugs{$ref};
1219         $bug_affected{$ref} = 1;
1220         eval {
1221             summary(bug          => $ref,
1222                     transcript   => $transcript,
1223                     ($dl > 0 ? (debug => $transcript):()),
1224                     requester    => $header{from},
1225                     request_addr => $controlrequestaddr,
1226                     message      => \@log,
1227                     recipients   => \%recipients,
1228                     summary      => $summary_msg,
1229                    );
1230         };
1231         if ($@) {
1232             $errors++;
1233             print {$transcript} "Failed to give $ref a summary: $@";
1234         }
1235
1236     } elsif (m/^owner\s+\#?(-?\d+)\s+((?:\S.*\S)|\!)\s*$/i) {
1237         $ok++;
1238         $ref = $1;
1239         $ref = $clonebugs{$ref} if exists $clonebugs{$ref};
1240         my $newowner = $2;
1241         if ($newowner eq '!') {
1242             $newowner = $replyto;
1243         }
1244         $bug_affected{$ref} = 1;
1245         eval {
1246             owner(bug          => $ref,
1247                   transcript   => $transcript,
1248                   ($dl > 0 ? (debug => $transcript):()),
1249                   requester    => $header{from},
1250                   request_addr => $controlrequestaddr,
1251                   message      => \@log,
1252                   recipients   => \%recipients,
1253                   owner        => $newowner,
1254                  );
1255         };
1256         if ($@) {
1257             $errors++;
1258             print {$transcript} "Failed to mark $ref as having an owner: $@";
1259         }
1260     } elsif (m/^noowner\s+\#?(-?\d+)\s*$/i) {
1261         $ok++;
1262         $ref = $1;
1263         $ref = $clonebugs{$ref} if exists $clonebugs{$ref};
1264         $bug_affected{$ref} = 1;
1265         eval {
1266             owner(bug          => $ref,
1267                   transcript   => $transcript,
1268                   ($dl > 0 ? (debug => $transcript):()),
1269                   requester    => $header{from},
1270                   request_addr => $controlrequestaddr,
1271                   message      => \@log,
1272                   recipients   => \%recipients,
1273                   owner        => undef,
1274                  );
1275         };
1276         if ($@) {
1277             $errors++;
1278             print {$transcript} "Failed to mark $ref as not having an owner: $@";
1279         }
1280     } elsif (m/^unarchive\s+#?(\d+)$/i) {
1281          $ok++;
1282          $ref = $1;
1283          $ref = $clonebugs{$ref} if exists $clonebugs{$ref};
1284          $bug_affected{$ref} = 1;
1285          eval {
1286               bug_unarchive(bug        => $ref,
1287                             transcript => $transcript,
1288                             ($dl > 0 ? (debug => $transcript):()),
1289                             affected_bugs => \%bug_affected,
1290                             requester => $header{from},
1291                             request_addr => $controlrequestaddr,
1292                             message => \@log,
1293                             recipients => \%recipients,
1294                            );
1295          };
1296          if ($@) {
1297               $errors++;
1298          }
1299     } elsif (m/^archive\s+#?(\d+)$/i) {
1300          $ok++;
1301          $ref = $1;
1302          $ref = $clonebugs{$ref} if exists $clonebugs{$ref};
1303          $bug_affected{$ref} = 1;
1304          eval {
1305               bug_archive(bug => $ref,
1306                           transcript => $transcript,
1307                           ($dl > 0 ? (debug => $transcript):()),
1308                           ignore_time => 1,
1309                           archive_unarchived => 0,
1310                           affected_bugs => \%bug_affected,
1311                           requester => $header{from},
1312                           request_addr => $controlrequestaddr,
1313                           message => \@log,
1314                           recipients => \%recipients,
1315                          );
1316          };
1317          if ($@) {
1318               $errors++;
1319          }
1320     } else {
1321         print {$transcript} "Unknown command or malformed arguments to command.\n\n";
1322         $errors++;
1323         if (++$unknowns >= 5) {
1324             print {$transcript} "Too many unknown commands, stopping here.\n\n";
1325             last;
1326         }
1327     }
1328 }
1329 if ($procline>$#bodylines) {
1330     print {$transcript} ">\nEnd of message, stopping processing here.\n\n";
1331 }
1332 if (!$ok && !$quickabort) {
1333     $errors++;
1334     print {$transcript} "No commands successfully parsed; sending the help text(s).\n";
1335     &sendhelp;
1336     print {$transcript} "\n";
1337 }
1338
1339 my @maintccs = determine_recipients(recipients => \%recipients,
1340                                     address_only => 1,
1341                                     cc => 1,
1342                                    );
1343 my $maintccs = 'Cc: '.join(",\n    ",
1344                     determine_recipients(recipients => \%recipients,
1345                                          cc => 1,
1346                                         )
1347                    )."\n";
1348
1349 my $packagepr = '';
1350 $packagepr = "X-${gProject}-PR-Package: " . join(keys %affected_packages) . "\n" if keys %affected_packages;
1351
1352 # Add Bcc's to subscribed bugs
1353 # now handled by Debbugs::Recipients
1354 #push @bcc, map {"bugs=$_\@$gListDomain"} keys %bug_affected;
1355
1356 if (!defined $header{'subject'} || $header{'subject'} eq "") {
1357   $header{'subject'} = "your mail";
1358 }
1359
1360 # Error text here advertises how many errors there were
1361 my $error_text = $errors > 0 ? " (with $errors errors)":'';
1362
1363 my $reply= <<END;
1364 From: $gMaintainerEmail ($gProject $gBug Tracking System)
1365 To: $replyto
1366 ${maintccs}Subject: Processed${error_text}: $header{'subject'}
1367 In-Reply-To: $header{'message-id'}
1368 END
1369 $reply .= <<END;
1370 References: $header{'message-id'}
1371 Message-ID: <handler.s.$nn.transcript\@$gEmailDomain>
1372 Precedence: bulk
1373 ${packagepr}X-$gProject-PR-Message: transcript
1374
1375 ${transcript_scalar}Please contact me if you need assistance.
1376
1377 $gMaintainer
1378 (administrator, $gProject $gBugs database)
1379 END
1380
1381 my $repliedshow= join(', ',$replyto,
1382                       determine_recipients(recipients => \%recipients,
1383                                            cc => 1,
1384                                            address_only => 1,
1385                                           )
1386                      );
1387 # -1 is the service.in log
1388 &filelock("lock/-1");
1389 open(AP,">>db-h/-1.log") || die "open db-h/-1.log: $!";
1390 print(AP
1391       "\2\n$repliedshow\n\5\n$reply\n\3\n".
1392       "\6\n".
1393       "<strong>Request received</strong> from <code>".
1394       html_escape($header{'from'})."</code>\n".
1395       "to <code>".html_escape($controlrequestaddr)."</code>\n".
1396       "\3\n".
1397       "\7\n",escape_log(@log),"\n\3\n") || die "writing db-h/-1.log: $!";
1398 close(AP) || die "open db-h/-1.log: $!";
1399 &unfilelock;
1400 utime(time,time,"db-h");
1401
1402 &sendmailmessage($reply,
1403                  exists $header{'x-debbugs-no-ack'}?():$replyto,
1404                  make_list(values %{{determine_recipients(recipients => \%recipients,
1405                                                           address_only => 1,
1406                                                          )}}
1407                           ),
1408                 );
1409
1410 unlink("incoming/P$nn") || die "unlinking incoming/P$nn: $!";
1411
1412 sub sendmailmessage {
1413     my ($message,@recips) = @_;
1414     $message = "X-Loop: $gMaintainerEmail\n" . $message;
1415     send_mail_message(message    => $message,
1416                       recipients => \@recips,
1417                      );
1418     $midix++;
1419 }
1420
1421 sub fill_template{
1422      my ($template,$extra_var) = @_;
1423      $extra_var ||={};
1424      my $variables = {config => \%config,
1425                       defined($ref)?(ref    => $ref):(),
1426                       defined($data)?(data  => $data):(),
1427                       %{$extra_var},
1428                      };
1429      my $hole_var = {'&bugurl' =>
1430                      sub{"$_[0]: ".
1431                               'http://'.$config{cgi_domain}.'/'.
1432                                    Debbugs::CGI::bug_url($_[0]);
1433                     }
1434                     };
1435      return fill_in_template(template => $template,
1436                              variables => $variables,
1437                              hole_var  => $hole_var,
1438                             );
1439 }
1440
1441 =head2 message_body_template
1442
1443      message_body_template('mail/ack',{ref=>'foo'});
1444
1445 Creates a message body using a template
1446
1447 =cut
1448
1449 sub message_body_template{
1450      my ($template,$extra_var) = @_;
1451      $extra_var ||={};
1452      my $body = fill_template($template,$extra_var);
1453      return fill_template('mail/message_body',
1454                           {%{$extra_var},
1455                            body => $body,
1456                           },
1457                          );
1458 }
1459
1460 sub sendhelp {
1461         &sendtxthelpraw("bug-log-mailserver.txt","instructions for request\@$gEmailDomain");
1462         &sendtxthelpraw("bug-maint-mailcontrol.txt","instructions for control\@$gEmailDomain")
1463             if $control;
1464 }
1465
1466 #sub unimplemented {
1467 #    print {$transcript} "Sorry, command $_[0] not yet implemented.\n\n";
1468 #}
1469 our %checkmatch_values;
1470 sub checkmatch {
1471     my ($string,$mvarname,$svarvalue,@newmergelist) = @_;
1472     my ($mvarvalue);
1473     if (@newmergelist) {
1474         $mvarvalue = $checkmatch_values{$mvarname};
1475         print {$transcript} "D| checkmatch \`$string' /$mvarname/$mvarvalue/$svarvalue/\n"
1476             if $dl;
1477         $mismatch .=
1478             "Values for \`$string' don't match:\n".
1479             " #$newmergelist[0] has \`$mvarvalue';\n".
1480             " #$ref has \`$svarvalue'\n"
1481             if $mvarvalue ne $svarvalue;
1482     } else {
1483          print {$transcript} "D| setupmatch \`$string' /$mvarname/$svarvalue/\n"
1484               if $dl;
1485          $checkmatch_values{$mvarname} = $svarvalue;
1486     }
1487 }
1488
1489 sub checkpkglimit {
1490     if (keys %limit_pkgs and not defined $limit_pkgs{$data->{package}}) {
1491         print {$transcript} "$gBug number $ref belongs to package $data->{package}, skipping.\n\n";
1492         $errors++;
1493         return 0;
1494     }
1495     return 1;
1496 }
1497
1498 sub manipset {
1499     my $list = shift;
1500     my $elt = shift;
1501     my $add = shift;
1502
1503     my %h = map { $_ => 1 } split ' ', $list;
1504     if ($add) {
1505         $h{$elt}=1;
1506     }
1507     else {
1508         delete $h{$elt};
1509     }
1510     return join ' ', sort keys %h;
1511 }
1512
1513 # High-level bug manipulation calls
1514 # Do announcements themselves
1515 #
1516 # Possible calling sequences:
1517 #    setbug (returns 0)
1518 #    
1519 #    setbug (returns 1)
1520 #    &transcript(something)
1521 #    nochangebug
1522 #
1523 #    setbug (returns 1)
1524 #    $action= (something)
1525 #    do {
1526 #      (modify s_* variables)
1527 #    } while (getnextbug);
1528
1529 our $manybugs;
1530
1531 sub nochangebug {
1532     &dlen("nochangebug");
1533     $state eq 'single' || $state eq 'multiple' || die "$state ?";
1534     &cancelbug;
1535     &endmerge if $manybugs;
1536     $state= 'idle';
1537     &dlex("nochangebug");
1538 }
1539
1540 our $sref;
1541 our @thisbugmergelist;
1542
1543 sub setbug {
1544     &dlen("setbug $ref");
1545     if ($ref =~ m/^-\d+/) {
1546         if (!defined $clonebugs{$ref}) {
1547             &notfoundbug;
1548             &dlex("setbug => noclone");
1549             return 0;
1550         }
1551         $ref = $clonebugs{$ref};
1552     }
1553     $state eq 'idle' || die "$state ?";
1554     if (!&getbug) {
1555         &notfoundbug;
1556         &dlex("setbug => 0s");
1557         return 0;
1558     }
1559
1560     if (!&checkpkglimit) {
1561         &cancelbug;
1562         return 0;
1563     }
1564
1565     @thisbugmergelist= split(/ /,$data->{mergedwith});
1566     if (!@thisbugmergelist) {
1567         &foundbug;
1568         $manybugs= 0;
1569         $state= 'single';
1570         $sref=$ref;
1571         &dlex("setbug => 1s");
1572         return 1;
1573     }
1574     &cancelbug;
1575     &getmerge;
1576     $manybugs= 1;
1577     if (!&getbug) {
1578         &notfoundbug;
1579         &endmerge;
1580         &dlex("setbug => 0mc");
1581         return 0;
1582     }
1583     &foundbug;
1584     $state= 'multiple'; $sref=$ref;
1585     &dlex("setbug => 1m");
1586     return 1;
1587 }
1588
1589 sub getnextbug {
1590     &dlen("getnextbug");
1591     $state eq 'single' || $state eq 'multiple' || die "$state ?";
1592     &savebug;
1593     if (!$manybugs || !@thisbugmergelist) {
1594         length($action) || die;
1595         print {$transcript} "$action\n$extramessage\n";
1596         &endmerge if $manybugs;
1597         $state= 'idle';
1598         &dlex("getnextbug => 0");
1599         return 0;
1600     }
1601     $ref= shift(@thisbugmergelist);
1602     &getbug || die "bug $ref disappeared";
1603     &foundbug;
1604     &dlex("getnextbug => 1");
1605     return 1;
1606 }
1607
1608 # Low-level bug-manipulation calls
1609 # Do no announcements
1610 #
1611 #    getbug (returns 0)
1612 #
1613 #    getbug (returns 1)
1614 #    cancelbug
1615 #
1616 #    getmerge
1617 #    $action= (something)
1618 #    getbug (returns 1)
1619 #    savebug/cancelbug
1620 #    getbug (returns 1)
1621 #    savebug/cancelbug
1622 #    [getbug (returns 0)]
1623 #    &transcript("$action\n\n")
1624 #    endmerge
1625
1626 sub notfoundbug { print {$transcript} "$gBug number $ref not found. (Is it archived?)\n\n"; }
1627 sub foundbug { print {$transcript} "$gBug#$ref: $data->{subject}\n"; }
1628
1629 sub getmerge {
1630     &dlen("getmerge");
1631     $mergelowstate eq 'idle' || die "$mergelowstate ?";
1632     &filelock('lock/merge');
1633     $mergelowstate='locked';
1634     &dlex("getmerge");
1635 }
1636
1637 sub endmerge {
1638     &dlen("endmerge");
1639     $mergelowstate eq 'locked' || die "$mergelowstate ?";
1640     &unfilelock;
1641     $mergelowstate='idle';
1642     &dlex("endmerge");
1643 }
1644
1645 sub getbug {
1646     &dlen("getbug $ref");
1647     $lowstate eq 'idle' || die "$state ?";
1648     # Only use unmerged bugs here
1649     if (($data = &lockreadbug($ref,'db-h'))) {
1650         $sref= $ref;
1651         $lowstate= "open";
1652         &dlex("getbug => 1");
1653         $extramessage='';
1654         return 1;
1655     }
1656     $lowstate= 'idle';
1657     &dlex("getbug => 0");
1658     return 0;
1659 }
1660
1661 sub cancelbug {
1662     &dlen("cancelbug");
1663     $lowstate eq 'open' || die "$state ?";
1664     &unfilelock;
1665     $lowstate= 'idle';
1666     &dlex("cancelbug");
1667 }
1668
1669 sub savebug {
1670     &dlen("savebug $ref");
1671     $lowstate eq 'open' || die "$lowstate ?";
1672     length($action) || die;
1673     $ref == $sref || die "read $sref but saving $ref ?";
1674     append_action_to_log(bug => $ref,
1675                          action => $action,
1676                          requester => $header{from},
1677                          request_addr => $controlrequestaddr,
1678                          message => \@log,
1679                          get_lock => 0,
1680                         );
1681     unlockwritebug($ref, $data);
1682     $lowstate= "idle";
1683     &dlex("savebug");
1684 }
1685
1686 sub dlen {
1687     return if !$dl;
1688     print {$transcript} "C> @_ ($state $lowstate $mergelowstate)\n";
1689 }
1690
1691 sub dlex {
1692     return if !$dl;
1693     print {$transcript} "R> @_ ($state $lowstate $mergelowstate)\n";
1694 }
1695
1696 sub urlsanit {
1697     my $url = shift;
1698     $url =~ s/%/%25/g;
1699     $url =~ s/\+/%2b/g;
1700     my %saniarray = ('<','lt', '>','gt', '&','amp', '"','quot');
1701     $url =~ s/([<>&"])/\&$saniarray{$1};/g;
1702     return $url;
1703 }
1704
1705 sub sendlynxdoc {
1706     &sendlynxdocraw;
1707     print {$transcript} "\n";
1708     $ok++;
1709 }
1710
1711 sub sendtxthelp {
1712     &sendtxthelpraw;
1713     print {$transcript} "\n";
1714     $ok++;
1715 }
1716
1717
1718 our $doc;
1719 sub sendtxthelpraw {
1720     my ($relpath,$description) = @_;
1721     $doc='';
1722     open(D,"$gDocDir/$relpath") || die "open doc file $relpath: $!";
1723     while(<D>) { $doc.=$_; }
1724     close(D);
1725     print {$transcript} "Sending $description in separate message.\n";
1726     &sendmailmessage(<<END.$doc,$replyto);
1727 From: $gMaintainerEmail ($gProject $gBug Tracking System)
1728 To: $replyto
1729 Subject: $gProject $gBug help: $description
1730 References: $header{'message-id'}
1731 In-Reply-To: $header{'message-id'}
1732 Message-ID: <handler.s.$nn.help.$midix\@$gEmailDomain>
1733 Precedence: bulk
1734 X-$gProject-PR-Message: doc-text $relpath
1735
1736 END
1737     $ok++;
1738 }
1739
1740 sub sendlynxdocraw {
1741     my ($relpath,$description) = @_;
1742     $doc='';
1743     open(L,"lynx -nolist -dump http://$gCGIDomain/\Q$relpath\E 2>&1 |") || die "fork for lynx: $!";
1744     while(<L>) { $doc.=$_; }
1745     $!=0; close(L);
1746     if ($? == 255 && $doc =~ m/^\n*lynx: Can\'t access start file/) {
1747         print {$transcript} "Information ($description) is not available -\n".
1748              "perhaps the $gBug does not exist or is not on the WWW yet.\n";
1749          $ok++;
1750     } elsif ($?) {
1751         print {$transcript} "Error getting $description (code $? $!):\n$doc\n";
1752     } else {
1753         print {$transcript} "Sending $description.\n";
1754         &sendmailmessage(<<END.$doc,$replyto);
1755 From: $gMaintainerEmail ($gProject $gBug Tracking System)
1756 To: $replyto
1757 Subject: $gProject $gBugs information: $description
1758 References: $header{'message-id'}
1759 In-Reply-To: $header{'message-id'}
1760 Message-ID: <handler.s.$nn.info.$midix\@$gEmailDomain>
1761 Precedence: bulk
1762 X-$gProject-PR-Message: doc-html $relpath
1763
1764 END
1765          $ok++;
1766     }
1767 }
1768
1769
1770 sub sendinfo {
1771     my ($wherefrom,$path,$description) = @_;
1772     if ($wherefrom eq "ftp.d.o") {
1773       $doc = `lynx -nolist -dump http://ftp.debian.org/debian/indices/$path.gz 2>&1 | gunzip -cf` or die "fork for lynx/gunzip: $!";
1774       $! = 0;
1775       if ($? == 255 && $doc =~ m/^\n*lynx: Can\'t access start file/) {
1776           print {$transcript} "$description is not available.\n";
1777           $ok++; return;
1778       } elsif ($?) {
1779           print {$transcript} "Error getting $description (code $? $!):\n$doc\n";
1780           return;
1781       }
1782     } elsif ($wherefrom eq "local") {
1783       open P, "$path";
1784       $doc = do { local $/; <P> };
1785       close P;
1786     } else {
1787       print {$transcript} "internal errror: info files location unknown.\n";
1788       $ok++; return;
1789     }
1790     print {$transcript} "Sending $description.\n";
1791     &sendmailmessage(<<END.$doc,$replyto);
1792 From: $gMaintainerEmail ($gProject $gBug Tracking System)
1793 To: $replyto
1794 Subject: $gProject $gBugs information: $description
1795 References: $header{'message-id'}
1796 In-Reply-To: $header{'message-id'}
1797 Message-ID: <handler.s.$nn.info.$midix\@$gEmailDomain>
1798 Precedence: bulk
1799 X-$gProject-PR-Message: getinfo
1800
1801 $description follows:
1802
1803 END
1804     $ok++;
1805     print {$transcript} "\n";
1806 }