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