]> git.donarmstrong.com Git - debbugs.git/blob - scripts/service
Remote obsolute @bcc code
[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 use Debbugs::Packages qw(binary_to_source);
22
23 use Debbugs::MIME qw(decode_rfc1522 encode_rfc1522 create_mime_message);
24 use Debbugs::Mail qw(send_mail_message);
25 use Debbugs::User;
26 use Debbugs::Recipients qw(:all);
27 use HTML::Entities qw(encode_entities);
28 use Debbugs::Versions::Dpkg;
29
30 use Debbugs::Status qw(splitpackages);
31
32 use Debbugs::CGI qw(html_escape);
33 use Debbugs::Control qw(:all);
34 use Debbugs::Control::Service qw(:all);
35 use Debbugs::Log qw(:misc);
36 use Debbugs::Text qw(:templates);
37
38 use Scalar::Util qw(looks_like_number);
39
40 use List::Util qw(first);
41
42 use Mail::RFC822::Address;
43 use Encode qw(decode encode);
44
45 chdir($config{spool_dir}) or
46      die "Unable to chdir to spool_dir '$config{spool_dir}': $!";
47
48 my $debug = 0;
49 umask(002);
50
51 my ($nn,$control) = $ARGV[0] =~ m/^(([RC])\.\d+)$/;
52 if (not defined $control or not defined $nn) {
53      die "Bad argument to service.in";
54 }
55 if (!rename("incoming/G$nn","incoming/P$nn")) {
56     defined $! and $! =~ m/no such file or directory/i and exit 0;
57     die "Failed to rename incoming/G$nn to incoming/P$nn: $!";
58 }
59
60 my $log_fh = IO::File->new("incoming/P$nn",'r') or
61      die "Unable to open incoming/P$nn for reading: $!";
62 my @log=<$log_fh>;
63 my @msg=@log;
64 close($log_fh);
65
66 chomp @msg;
67
68 print "###\n",join("##\n",@msg),"\n###\n" if $debug;
69
70 # Bug numbers to send e-mail to, hash so that we don't send to the
71 # same bug twice.
72 my (%bug_affected);
73
74 my (@headerlines,@bodylines);
75
76 my $parse_output = Debbugs::MIME::parse(join('',@log));
77 @headerlines = @{$parse_output->{header}};
78 @bodylines = @{$parse_output->{body}};
79
80 my %header;
81 for (@headerlines) {
82     $_ = decode_rfc1522($_);
83     s/\n\s/ /g;
84     print ">$_<\n" if $debug;
85     if (s/^(\S+):\s*//) {
86         my $v = lc $1;
87         print ">$v=$_<\n" if $debug;
88         $header{$v} = $_;
89     } else {
90         print "!>$_<\n" if $debug;
91     }
92 }
93 $header{'message-id'} ||= '';
94 $header{subject} ||= '';
95
96 grep(s/\s+$//,@bodylines);
97
98 print "***\n",join("\n",@bodylines),"\n***\n" if $debug;
99
100 if (defined $header{'resent-from'} && !defined $header{'from'}) {
101     $header{'from'} = $header{'resent-from'};
102 }
103
104 defined($header{'from'}) || die "no From header";
105
106 delete $header{'reply-to'} 
107         if ( defined($header{'reply-to'}) && $header{'reply-to'} =~ m/^\s*$/ );
108
109 my $replyto;
110 if ( defined($header{'reply-to'}) && $header{'reply-to'} ne "" ) {
111     $replyto = $header{'reply-to'};
112 } else {
113     $replyto = $header{'from'};
114 }
115
116 # This is an error counter which should be incremented every time there is an error.
117 my $errors = 0;
118 my $controlrequestaddr= ($control ? 'control' : 'request').'@'.$config{email_domain};
119 my $transcript_scalar = '';
120 open my $transcript, ">:scalar:utf8", \$transcript_scalar or
121      die "Unable to create transcript scalar: $!";
122 print {$transcript} "Processing commands for $controlrequestaddr:\n\n";
123
124
125 my $dl = 0;
126 my %affected_packages;
127 my %recipients;
128 # this is the hashref which is passed to all control calls
129 my %limit = ();
130
131
132 my @common_control_options =
133     (transcript        => $transcript,
134      requester         => $header{from},
135      request_addr      => $controlrequestaddr,
136      request_msgid     => $header{'message-id'},
137      request_subject   => $header{subject},
138      request_nn        => $nn,
139      request_replyto   => $replyto,
140      message           => \@log,
141      affected_bugs     => \%bug_affected,
142      affected_packages => \%affected_packages,
143      recipients        => \%recipients,
144      limit             => \%limit,
145     );
146
147 my $state= 'idle';
148 my $lowstate= 'idle';
149 my $mergelowstate= 'idle';
150 my $midix=0;
151
152 my $user = $replyto;
153 $user =~ s/,.*//;
154 $user =~ s/^.*<(.*)>.*$/$1/;
155 $user =~ s/[(].*[)]//;
156 $user =~ s/^\s*(\S+)\s+.*$/$1/;
157 $user = "" unless (Debbugs::User::is_valid_user($user));
158 my $indicated_user = 0;
159
160 my $quickabort = 0;
161
162
163 if (@gExcludeFromControl and grep {$replyto =~ m/\Q$_\E/} @gExcludeFromControl) {
164         print {$transcript} fill_template('mail/excluded_from_control');
165         $quickabort = 1;
166 }
167
168 my %limit_pkgs = ();
169 my %clonebugs = ();
170 my %bcc = ();
171
172
173 our $data;
174 our $message;
175 our $extramessage;
176 our $ref;
177
178 our $mismatch;
179 our $action;
180
181
182 my $ok = 0;
183 my $unknowns = 0;
184 my $procline=0;
185 for ($procline=0; $procline<=$#bodylines; $procline++) {
186     my $noriginator;
187     my $newsubmitter;
188     my $oldsubmitter;
189     my $newowner;
190     $state eq 'idle' || print "state: $state ?\n";
191     $lowstate eq 'idle' || print "lowstate: $lowstate ?\n";
192     $mergelowstate eq 'idle' || print "mergelowstate: $mergelowstate ?\n";
193     if ($quickabort) {
194          print {$transcript} "Stopping processing here.\n\n";
195          last;
196     }
197     $_= $bodylines[$procline]; s/\s+$//;
198     # Remove BOM markers from UTF-8 strings
199     # Fixes #488554
200     s/\xef\xbb\xbf//g;
201     next unless m/\S/;
202     eval {
203         my $temp = decode("utf8",$_,Encode::FB_CROAK);
204         $_ = $temp;
205     };
206     print {$transcript} "> $_\n";
207     next if m/^\s*\#/;
208     $action= '';
209     if (m/^(?:stop|quit|--|thank(?:s|\s*you)?|kthxbye)\.*\s*$/i) {
210         print {$transcript} "Stopping processing here.\n\n";
211         last;
212     } elsif (m/^debug\s+(\d+)$/i && $1 >= 0 && $1 <= 1000) {
213         $dl= $1+0;
214         if ($dl > 0 and not grep /debug/,@common_control_options) {
215             push @common_control_options,(debug => $transcript);
216         }
217         print {$transcript} "Debug level $dl.\n\n";
218     } elsif (m/^(send|get)\s+\#?(\d{2,})$/i) {
219         $ref= $2+0;
220         &sendlynxdoc("bugreport.cgi?bug=$ref","logs for $gBug#$ref");
221     } elsif (m/^send-detail\s+\#?(\d{2,})$/i) {
222         $ref= $1+0;
223         &sendlynxdoc("bugreport.cgi?bug=$ref&boring=yes",
224                      "detailed logs for $gBug#$ref");
225     } elsif (m/^index(\s+full)?$/i) {
226         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
227         $errors++;
228         $ok++; # well, it's not really ok, but it fixes #81224 :)
229     } elsif (m/^index-summary\s+by-package$/i) {
230         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
231         $errors++;
232         $ok++; # well, it's not really ok, but it fixes #81224 :)
233     } elsif (m/^index-summary(\s+by-number)?$/i) {
234         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
235         $errors++;
236         $ok++; # well, it's not really ok, but it fixes #81224 :)
237     } elsif (m/^index(\s+|-)pack(age)?s?$/i) {
238         &sendlynxdoc("pkgindex.cgi?indexon=pkg",'index of packages');
239     } elsif (m/^index(\s+|-)maints?$/i) {
240         &sendlynxdoc("pkgindex.cgi?indexon=maint",'index of maintainers');
241     } elsif (m/^index(\s+|-)maint\s+(\S+)$/i) {
242         my $maint = $2;
243         &sendlynxdoc("pkgreport.cgi?maint=" . urlsanit($maint),
244                      "$gBug list for maintainer \`$maint'");
245         $ok++;
246     } elsif (m/^index(\s+|-)pack(age)?s?\s+(\S.*\S)$/i) {
247         my $package = $+;
248         &sendlynxdoc("pkgreport.cgi?pkg=" . urlsanit($package),
249                      "$gBug list for package $package");
250         $ok++;
251     } elsif (m/^send-unmatched(\s+this|\s+-?0)?$/i) {
252         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
253         $errors++;
254         $ok++; # well, it's not really ok, but it fixes #81224 :)
255     } elsif (m/^send-unmatched\s+(last|-1)$/i) {
256         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
257         $errors++;
258         $ok++; # well, it's not really ok, but it fixes #81224 :)
259     } elsif (m/^send-unmatched\s+(old|-2)$/i) {
260         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
261         $errors++;
262         $ok++; # well, it's not really ok, but it fixes #81224 :)
263     } elsif (m/^getinfo\s+([\w.-]+)$/i) {
264         # the following is basically a Debian-specific kludge, but who cares
265         my $req = $1;
266         if ($req =~ /^maintainers$/i && -f "$gConfigDir/Maintainers") {
267             &sendinfo("local", "$gConfigDir/Maintainers", "Maintainers file");
268         } elsif ($req =~ /^override\.(\w+)\.([\w.-]+)$/i) {
269             $req =~ s/.gz$//;
270             &sendinfo("ftp.d.o", "$req", "override file for $2 part of $1 distribution");
271         } elsif ($req =~ /^pseudo-packages\.(description|maintainers)$/i && -f "$gConfigDir/$req") {
272             &sendinfo("local", "$gConfigDir/$req", "$req file");
273         } else {
274             print {$transcript} "Info file $req does not exist.\n\n";
275         }
276     } elsif (m/^help/i) {
277         &sendhelp;
278         print {$transcript} "\n";
279         $ok++;
280     } elsif (m/^refcard/i) {
281         &sendtxthelp("bug-mailserver-refcard.txt","mail servers' reference card");
282     } elsif (m/^subscribe/i) {
283         print {$transcript} <<END;
284 There is no $gProject $gBug mailing list.  If you wish to review bug reports
285 please do so via http://$gWebDomain/ or ask this mail server
286 to send them to you.
287 soon: MAILINGLISTS_TEXT
288 END
289     } elsif (m/^unsubscribe/i) {
290         print {$transcript} <<END;
291 soon: UNSUBSCRIBE_TEXT
292 soon: MAILINGLISTS_TEXT
293 END
294     } elsif (m/^user\s+(\S+)\s*$/i) {
295         my $newuser = $1;
296         if (Debbugs::User::is_valid_user($newuser)) {
297             my $olduser = ($user ne "" ? " (was $user)" : "");
298             print {$transcript} "Setting user to $newuser$olduser.\n";
299             $user = $newuser;
300             $indicated_user = 1;
301         } else {
302             print {$transcript} "Selected user id ($newuser) invalid, sorry\n";
303             $errors++;
304             $user = "";
305             $indicated_user = 1;
306         }
307     } elsif (m/^usercategory\s+(\S+)(\s+\[hidden\])?\s*$/i) {
308         $ok++;
309         my $catname = $1;
310         my $hidden = (defined $2 and $2 ne "");
311
312         my $prefix = "";
313         my @cats;
314         my $bad = 0;
315         my $catsec = 0;
316         if ($user eq "") {
317             print {$transcript} "No valid user selected\n";
318             $errors++;
319             next;
320         }
321         if (not $indicated_user and defined $user) {
322              print {$transcript} "User is $user\n";
323              $indicated_user = 1;
324         }
325         my @ords = ();
326         while (++$procline <= $#bodylines) {
327             unless ($bodylines[$procline] =~ m/^\s*([*+])\s*(\S.*)$/) {
328                 $procline--;
329                 last;
330             }
331             print {$transcript} "> $bodylines[$procline]\n";
332             next if $bad;
333             my ($o, $txt) = ($1, $2);
334             if ($#cats == -1 && $o eq "+") {
335                 print {$transcript} "User defined category specification must start with a category name. Skipping.\n\n";
336                 $errors++;
337                 $bad = 1;
338                 next;
339             }
340             if ($o eq "+") {
341                 unless (ref($cats[-1]) eq "HASH") {
342                     $cats[-1] = { "nam" => $cats[-1], 
343                                   "pri" => [], "ttl" => [] };
344                 }
345                 $catsec++;
346                 my ($desc, $ord, $op);
347                 if ($txt =~ m/^(.*\S)\s*\[((\d+):\s*)?\]\s*$/) {
348                     $desc = $1; $ord = $3; $op = "";
349                 } elsif ($txt =~ m/^(.*\S)\s*\[((\d+):\s*)?(\S+)\]\s*$/) {
350                     $desc = $1; $ord = $3; $op = $4;
351                 } elsif ($txt =~ m/^([^[\s]+)\s*$/) {
352                     $desc = ""; $op = $1;
353                 } else {
354                     print {$transcript} "Unrecognised syntax for category section. Skipping.\n\n";
355                     $errors++;
356                     $bad = 1;
357                     next;
358                 }
359                 $ord = 999 unless defined $ord;
360
361                 if ($op) {
362                     push @{$cats[-1]->{"pri"}}, $prefix . $op;
363                     push @{$cats[-1]->{"ttl"}}, $desc;
364                     push @ords, "$ord $catsec";
365                 } else {
366                     $cats[-1]->{"def"} = $desc;
367                     push @ords, "$ord DEF";
368                     $catsec--;
369                 }
370                 @ords = sort {
371                     my ($a1, $a2, $b1, $b2) = split / /, "$a $b";
372                     ((looks_like_number($a1) and looks_like_number($a2))?$a1 <=> $b1:$a1 cmp $b1) ||
373                     ((looks_like_number($a2) and looks_like_number($b2))?$a2 <=> $b2:$a2 cmp $b2);
374                 } @ords;
375                 $cats[-1]->{"ord"} = [map { m/^.* (\S+)/; $1 eq "DEF" ? $catsec + 1 : $1 } @ords];
376             } elsif ($o eq "*") {
377                 $catsec = 0;
378                 my ($name);
379                 if ($txt =~ m/^(.*\S)(\s*\[(\S+)\])\s*$/) {
380                     $name = $1; $prefix = $3;
381                 } else {
382                     $name = $txt; $prefix = "";
383                 }
384                 push @cats, $name;
385             }
386         }
387         # XXX: got @cats, now do something with it
388         my $u = Debbugs::User::get_user($user);
389         if (@cats) {
390             print {$transcript} "Added usercategory $catname.\n\n";
391             $u->{"categories"}->{$catname} = [ @cats ];
392             if (not $hidden) {
393                  push @{$u->{visible_cats}},$catname;
394             }
395         } else {
396             print {$transcript} "Removed usercategory $catname.\n\n";
397             delete $u->{"categories"}->{$catname};
398             @{$u->{visible_cats}} = grep {$_ ne $catname} @{$u->{visible_cats}};
399         }
400         $u->write();
401     } elsif (m/^usertags?\s+\#?(-?\d+)\s+(([=+-])\s*)?(\S.*)?$/i) {
402         $ok++;
403         $ref = $1;
404         my $addsubcode = $3 || "+";
405         my $tags = $4;
406         if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
407              $ref = $clonebugs{$ref};
408         }
409         if ($user eq "") {
410             print {$transcript} "No valid user selected\n";
411             $errors++;
412             $indicated_user = 1;
413         } elsif (check_limit(data => read_bug(bug => $ref),
414                              limit => \%limit,
415                              transcript => $transcript)) {
416             if (not $indicated_user and defined $user) {
417                  print {$transcript} "User is $user\n";
418                  $indicated_user = 1;
419             }
420             my %ut;
421             Debbugs::User::read_usertags(\%ut, $user);
422             my @oldtags = (); my @newtags = (); my @badtags = ();
423             my %chtags;
424             if (defined $tags and length $tags) {
425                  for my $t (split /[,\s]+/, $tags) {
426                       if ($t =~ m/^[a-zA-Z0-9.+\@-]+$/) {
427                            $chtags{$t} = 1;
428                       } else {
429                            push @badtags, $t;
430                       }
431                  }
432             }
433             if (@badtags) {
434                 print {$transcript} "Ignoring illegal tag/s: ".join(', ', @badtags).".\nPlease use only alphanumerics, at, dot, plus and dash.\n";
435                 $errors++;
436             }
437             for my $t (keys %chtags) {
438                 $ut{$t} = [] unless defined $ut{$t};
439             }
440             for my $t (keys %ut) {
441                 my %res = map { ($_, 1) } @{$ut{$t}};
442                 push @oldtags, $t if defined $res{$ref};
443                 my $addop = ($addsubcode eq "+" or $addsubcode eq "=");
444                 my $del = (defined $chtags{$t} ? $addsubcode eq "-" 
445                                                : $addsubcode eq "=");
446                 $res{$ref} = 1 if ($addop && defined $chtags{$t});
447                 delete $res{$ref} if ($del);
448                 push @newtags, $t if defined $res{$ref};
449                 $ut{$t} = [ sort { $a <=> $b } (keys %res) ];
450             }
451             if (@oldtags == 0) {
452                 print {$transcript} "There were no usertags set.\n";
453             } else {
454                 print {$transcript} "Usertags were: " . join(" ", @oldtags) . ".\n";
455             }
456             print {$transcript} "Usertags are now: " . join(" ", @newtags) . ".\n";
457             Debbugs::User::write_usertags(\%ut, $user);
458         }
459     } elsif (!$control) {
460         print {$transcript} <<END;
461 Unknown command or malformed arguments to command.
462 (Use control\@$gEmailDomain to manipulate reports.)
463
464 END
465         #### "developer only" ones start here
466     } elsif (defined valid_control($_)) {
467         my ($new_errors,$terminate_control) =
468             control_line(line => $_,
469                          clonebugs => \%clonebugs,
470                          limit => \%limit,
471                          common_control_options => \@common_control_options,
472                          errors => \$errors,
473                          transcript => $transcript,
474                          debug => $debug,
475                          ok => \$ok,
476                         );
477         if ($terminate_control) {
478             last;
479         }
480     } else {
481         $errors++;
482         if (++$unknowns >= 5) {
483             print {$transcript} "Too many unknown commands, stopping here.\n\n";
484             last;
485         }
486     }
487 }
488 if ($procline>$#bodylines) {
489     print {$transcript} ">\nEnd of message, stopping processing here.\n\n";
490 }
491 if (!$ok && !$quickabort) {
492     $errors++;
493     print {$transcript} "No commands successfully parsed; sending the help text(s).\n";
494     &sendhelp;
495     print {$transcript} "\n";
496 }
497
498 my @maintccs = determine_recipients(recipients => \%recipients,
499                                     address_only => 1,
500                                     cc => 1,
501                                    );
502 my $maintccs = 'Cc: '.join(",\n    ",
503                     determine_recipients(recipients => \%recipients,
504                                          cc => 1,
505                                         )
506                    )."\n";
507
508 my $packagepr = '';
509 $packagepr = "X-${gProject}-PR-Package: " . join(keys %affected_packages) . "\n" if keys %affected_packages;
510
511 # Add Bcc's to subscribed bugs
512 # now handled by Debbugs::Recipients
513 #push @bcc, map {"bugs=$_\@$gListDomain"} keys %bug_affected;
514
515 if (!defined $header{'subject'} || $header{'subject'} eq "") {
516   $header{'subject'} = "your mail";
517 }
518
519 # Error text here advertises how many errors there were
520 my $error_text = $errors > 0 ? " (with $errors errors)":'';
521
522 my @common_headers;
523 push @common_headers, 'X-Loop',$gMaintainerEmail;
524
525 my $temp_transcript = ${transcript_scalar};
526 eval{
527     $temp_transcript = decode("utf8",$temp_transcript,Encode::FB_CROAK);
528 };
529 my $reply =
530     create_mime_message([From          => "$gMaintainerEmail ($gProject $gBug Tracking System)",
531                          To            => $replyto,
532                          @maintccs ? (Cc => join(', ',@maintccs)):(),
533                          Subject       => "Processed${error_text}: $header{subject}",
534                          'Message-ID'  => "<handler.s.$nn.transcript\@$gEmailDomain>",
535                          'In-Reply-To' => $header{'message-id'},
536                          References    => join(' ',grep {defined $_} $header{'message-id'},$data->{msgid}),
537                          Precedence    => 'bulk',
538                          keys %affected_packages ?("X-${gProject}-PR-Package" => join(' ',keys %affected_packages)):(),
539                          keys %affected_packages ?("X-${gProject}-PR-Source" =>
540                                                    join(' ',
541                                                         map {defined $_ ?(ref($_)?@{$_}:$_):()}
542                                                         binary_to_source(binary => [keys %affected_packages],
543                                                                          source_only => 1))):(),
544                          "X-$gProject-PR-Message" => 'transcript',
545                          @common_headers,
546                         ],
547                         fill_template('mail/message_body',
548                                       {body => "${temp_transcript}Please contact me if you need assistance."},
549                                      ));
550
551 my $repliedshow= join(', ',$replyto,
552                       determine_recipients(recipients => \%recipients,
553                                            cc => 1,
554                                            address_only => 1,
555                                           )
556                      );
557
558 # -1 is the service.in log
559 &filelock("lock/-1");
560 open(AP,">>db-h/-1.log") || die "open db-h/-1.log: $!";
561 print(AP
562       "\2\n$repliedshow\n\5\n$reply\n\3\n".
563       "\6\n".
564       "<strong>Request received</strong> from <code>".
565       html_escape($header{'from'})."</code>\n".
566       "to <code>".html_escape($controlrequestaddr)."</code>\n".
567       "\3\n".
568       "\7\n",escape_log(@log),"\n\3\n") || die "writing db-h/-1.log: $!";
569 close(AP) || die "open db-h/-1.log: $!";
570 &unfilelock;
571 utime(time,time,"db-h");
572
573 &sendmailmessage($reply,
574                  exists $header{'x-debbugs-no-ack'}?():$replyto,
575                  make_list(values %{{determine_recipients(recipients => \%recipients,
576                                                           address_only => 1,
577                                                          )}}
578                           ),
579                 );
580
581 unlink("incoming/P$nn") || die "unlinking incoming/P$nn: $!";
582
583 sub sendmailmessage {
584     my ($message,@recips) = @_;
585     $message = "X-Loop: $gMaintainerEmail\n" . $message;
586     send_mail_message(message    => $message,
587                       recipients => \@recips,
588                      );
589     $midix++;
590 }
591
592 sub fill_template{
593      my ($template,$extra_var) = @_;
594      $extra_var ||={};
595      my $variables = {config => \%config,
596                       defined($ref)?(ref    => $ref):(),
597                       defined($data)?(data  => $data):(),
598                       refs => [map {exists $clonebugs{$_}?$clonebugs{$_}:$_} keys %bug_affected],
599                       %{$extra_var},
600                      };
601      my $hole_var = {'&bugurl' =>
602                      sub{"$_[0]: ".
603                               'http://'.$config{cgi_domain}.'/'.
604                                    Debbugs::CGI::bug_links(bug=>$_[0],
605                                                            links_only => 1,
606                                                           );
607                     }
608                     };
609      return fill_in_template(template => $template,
610                              variables => $variables,
611                              hole_var  => $hole_var,
612                             );
613 }
614
615 =head2 message_body_template
616
617      message_body_template('mail/ack',{ref=>'foo'});
618
619 Creates a message body using a template
620
621 =cut
622
623 sub message_body_template{
624      my ($template,$extra_var) = @_;
625      $extra_var ||={};
626      my $body = fill_template($template,$extra_var);
627      return fill_template('mail/message_body',
628                           {%{$extra_var},
629                            body => $body,
630                           },
631                          );
632 }
633
634 sub sendhelp {
635      if ($control) {
636           &sendtxthelpraw("bug-maint-mailcontrol.txt","instructions for control\@$gEmailDomain")
637      }
638      else {
639           &sendtxthelpraw("bug-log-mailserver.txt","instructions for request\@$gEmailDomain");
640      }
641 }
642
643 #sub unimplemented {
644 #    print {$transcript} "Sorry, command $_[0] not yet implemented.\n\n";
645 #}
646 our %checkmatch_values;
647 sub checkmatch {
648     my ($string,$mvarname,$svarvalue,@newmergelist) = @_;
649     my ($mvarvalue);
650     if (@newmergelist) {
651         $mvarvalue = $checkmatch_values{$mvarname};
652         print {$transcript} "D| checkmatch \`$string' /$mvarname/$mvarvalue/$svarvalue/\n"
653             if $dl;
654         $mismatch .=
655             "Values for \`$string' don't match:\n".
656             " #$newmergelist[0] has \`$mvarvalue';\n".
657             " #$ref has \`$svarvalue'\n"
658             if $mvarvalue ne $svarvalue;
659     } else {
660          print {$transcript} "D| setupmatch \`$string' /$mvarname/$svarvalue/\n"
661               if $dl;
662          $checkmatch_values{$mvarname} = $svarvalue;
663     }
664 }
665
666 sub checkpkglimit {
667     if (keys %limit_pkgs and not defined $limit_pkgs{$data->{package}}) {
668         print {$transcript} "$gBug number $ref belongs to package $data->{package}, skipping.\n\n";
669         $errors++;
670         return 0;
671     }
672     return 1;
673 }
674
675 sub manipset {
676     my $list = shift;
677     my $elt = shift;
678     my $add = shift;
679
680     my %h = map { $_ => 1 } split ' ', $list;
681     if ($add) {
682         $h{$elt}=1;
683     }
684     else {
685         delete $h{$elt};
686     }
687     return join ' ', sort keys %h;
688 }
689
690 # High-level bug manipulation calls
691 # Do announcements themselves
692 #
693 # Possible calling sequences:
694 #    setbug (returns 0)
695 #    
696 #    setbug (returns 1)
697 #    &transcript(something)
698 #    nochangebug
699 #
700 #    setbug (returns 1)
701 #    $action= (something)
702 #    do {
703 #      (modify s_* variables)
704 #    } while (getnextbug);
705
706 our $manybugs;
707
708 sub nochangebug {
709     &dlen("nochangebug");
710     $state eq 'single' || $state eq 'multiple' || die "$state ?";
711     &cancelbug;
712     &endmerge if $manybugs;
713     $state= 'idle';
714     &dlex("nochangebug");
715 }
716
717 our $sref;
718 our @thisbugmergelist;
719
720 sub setbug {
721     &dlen("setbug $ref");
722     if ($ref =~ m/^-\d+/) {
723         if (!defined $clonebugs{$ref}) {
724             &notfoundbug;
725             &dlex("setbug => noclone");
726             return 0;
727         }
728         $ref = $clonebugs{$ref};
729     }
730     $state eq 'idle' || die "$state ?";
731     if (!&getbug) {
732         &notfoundbug;
733         &dlex("setbug => 0s");
734         return 0;
735     }
736
737     if (!&checkpkglimit) {
738         &cancelbug;
739         return 0;
740     }
741
742     @thisbugmergelist= split(/ /,$data->{mergedwith});
743     if (!@thisbugmergelist) {
744         &foundbug;
745         $manybugs= 0;
746         $state= 'single';
747         $sref=$ref;
748         &dlex("setbug => 1s");
749         return 1;
750     }
751     &cancelbug;
752     &getmerge;
753     $manybugs= 1;
754     if (!&getbug) {
755         &notfoundbug;
756         &endmerge;
757         &dlex("setbug => 0mc");
758         return 0;
759     }
760     &foundbug;
761     $state= 'multiple'; $sref=$ref;
762     &dlex("setbug => 1m");
763     return 1;
764 }
765
766 sub getnextbug {
767     &dlen("getnextbug");
768     $state eq 'single' || $state eq 'multiple' || die "$state ?";
769     &savebug;
770     if (!$manybugs || !@thisbugmergelist) {
771         length($action) || die;
772         print {$transcript} "$action\n$extramessage\n";
773         &endmerge if $manybugs;
774         $state= 'idle';
775         &dlex("getnextbug => 0");
776         return 0;
777     }
778     $ref= shift(@thisbugmergelist);
779     &getbug || die "bug $ref disappeared";
780     &foundbug;
781     &dlex("getnextbug => 1");
782     return 1;
783 }
784
785 # Low-level bug-manipulation calls
786 # Do no announcements
787 #
788 #    getbug (returns 0)
789 #
790 #    getbug (returns 1)
791 #    cancelbug
792 #
793 #    getmerge
794 #    $action= (something)
795 #    getbug (returns 1)
796 #    savebug/cancelbug
797 #    getbug (returns 1)
798 #    savebug/cancelbug
799 #    [getbug (returns 0)]
800 #    &transcript("$action\n\n")
801 #    endmerge
802
803 sub notfoundbug { print {$transcript} "$gBug number $ref not found. (Is it archived?)\n\n"; }
804 sub foundbug { print {$transcript} "$gBug#$ref: $data->{subject}\n"; }
805
806 sub getmerge {
807     &dlen("getmerge");
808     $mergelowstate eq 'idle' || die "$mergelowstate ?";
809     &filelock('lock/merge');
810     $mergelowstate='locked';
811     &dlex("getmerge");
812 }
813
814 sub endmerge {
815     &dlen("endmerge");
816     $mergelowstate eq 'locked' || die "$mergelowstate ?";
817     &unfilelock;
818     $mergelowstate='idle';
819     &dlex("endmerge");
820 }
821
822 sub getbug {
823     &dlen("getbug $ref");
824     $lowstate eq 'idle' || die "$state ?";
825     # Only use unmerged bugs here
826     if (($data = &lockreadbug($ref,'db-h'))) {
827         $sref= $ref;
828         $lowstate= "open";
829         &dlex("getbug => 1");
830         $extramessage='';
831         return 1;
832     }
833     $lowstate= 'idle';
834     &dlex("getbug => 0");
835     return 0;
836 }
837
838 sub cancelbug {
839     &dlen("cancelbug");
840     $lowstate eq 'open' || die "$state ?";
841     &unfilelock;
842     $lowstate= 'idle';
843     &dlex("cancelbug");
844 }
845
846 sub savebug {
847     &dlen("savebug $ref");
848     $lowstate eq 'open' || die "$lowstate ?";
849     length($action) || die;
850     $ref == $sref || die "read $sref but saving $ref ?";
851     append_action_to_log(bug => $ref,
852                          action => $action,
853                          requester => $header{from},
854                          request_addr => $controlrequestaddr,
855                          message => \@log,
856                          get_lock => 0,
857                         );
858     unlockwritebug($ref, $data);
859     $lowstate= "idle";
860     &dlex("savebug");
861 }
862
863 sub dlen {
864     return if !$dl;
865     print {$transcript} "C> @_ ($state $lowstate $mergelowstate)\n";
866 }
867
868 sub dlex {
869     return if !$dl;
870     print {$transcript} "R> @_ ($state $lowstate $mergelowstate)\n";
871 }
872
873 sub urlsanit {
874     my $url = shift;
875     $url =~ s/%/%25/g;
876     $url =~ s/\+/%2b/g;
877     my %saniarray = ('<','lt', '>','gt', '&','amp', '"','quot');
878     $url =~ s/([<>&"])/\&$saniarray{$1};/g;
879     return $url;
880 }
881
882 sub sendlynxdoc {
883     &sendlynxdocraw;
884     print {$transcript} "\n";
885     $ok++;
886 }
887
888 sub sendtxthelp {
889     &sendtxthelpraw;
890     print {$transcript} "\n";
891     $ok++;
892 }
893
894
895 our $doc;
896 sub sendtxthelpraw {
897     my ($relpath,$description) = @_;
898     $doc='';
899     if (not -e "$gDocDir/$relpath") {
900         print {$transcript} "Unfortunatly, the help text doesn't exist, so it wasn't sent.\n";
901         warn "Help text $gDocDir/$relpath not found";
902         return;
903     }
904     open(D,"$gDocDir/$relpath") || die "open doc file $relpath: $!";
905     while(<D>) { $doc.=$_; }
906     close(D);
907     print {$transcript} "Sending $description in separate message.\n";
908     &sendmailmessage(<<END.$doc,$replyto);
909 From: $gMaintainerEmail ($gProject $gBug Tracking System)
910 To: $replyto
911 Subject: $gProject $gBug help: $description
912 References: $header{'message-id'}
913 In-Reply-To: $header{'message-id'}
914 Message-ID: <handler.s.$nn.help.$midix\@$gEmailDomain>
915 Precedence: bulk
916 X-$gProject-PR-Message: doc-text $relpath
917
918 END
919     $ok++;
920 }
921
922 sub sendlynxdocraw {
923     my ($relpath,$description) = @_;
924     $doc='';
925     open(L,"lynx -nolist -dump http://$gCGIDomain/\Q$relpath\E 2>&1 |") || die "fork for lynx: $!";
926     while(<L>) { $doc.=$_; }
927     $!=0; close(L);
928     if ($? == 255 && $doc =~ m/^\n*lynx: Can\'t access start file/) {
929         print {$transcript} "Information ($description) is not available -\n".
930              "perhaps the $gBug does not exist or is not on the WWW yet.\n";
931          $ok++;
932     } elsif ($?) {
933         print {$transcript} "Error getting $description (code $? $!):\n$doc\n";
934     } else {
935         print {$transcript} "Sending $description.\n";
936         &sendmailmessage(<<END.$doc,$replyto);
937 From: $gMaintainerEmail ($gProject $gBug Tracking System)
938 To: $replyto
939 Subject: $gProject $gBugs information: $description
940 References: $header{'message-id'}
941 In-Reply-To: $header{'message-id'}
942 Message-ID: <handler.s.$nn.info.$midix\@$gEmailDomain>
943 Precedence: bulk
944 X-$gProject-PR-Message: doc-html $relpath
945
946 END
947          $ok++;
948     }
949 }
950
951
952 sub sendinfo {
953     my ($wherefrom,$path,$description) = @_;
954     if ($wherefrom eq "ftp.d.o") {
955       $doc = `lynx -nolist -dump http://ftp.debian.org/debian/indices/$path.gz 2>&1 | gunzip -cf` or die "fork for lynx/gunzip: $!";
956       $! = 0;
957       if ($? == 255 && $doc =~ m/^\n*lynx: Can\'t access start file/) {
958           print {$transcript} "$description is not available.\n";
959           $ok++; return;
960       } elsif ($?) {
961           print {$transcript} "Error getting $description (code $? $!):\n$doc\n";
962           return;
963       }
964     } elsif ($wherefrom eq "local") {
965       open P, "$path";
966       $doc = do { local $/; <P> };
967       close P;
968     } else {
969       print {$transcript} "internal errror: info files location unknown.\n";
970       $ok++; return;
971     }
972     print {$transcript} "Sending $description.\n";
973     &sendmailmessage(<<END.$doc,$replyto);
974 From: $gMaintainerEmail ($gProject $gBug Tracking System)
975 To: $replyto
976 Subject: $gProject $gBugs information: $description
977 References: $header{'message-id'}
978 In-Reply-To: $header{'message-id'}
979 Message-ID: <handler.s.$nn.info.$midix\@$gEmailDomain>
980 Precedence: bulk
981 X-$gProject-PR-Message: getinfo
982
983 $description follows:
984
985 END
986     $ok++;
987     print {$transcript} "\n";
988 }