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