]> git.donarmstrong.com Git - debbugs.git/blob - cgi/bugreport.cgi
[project @ 2005-08-22 14:31:23 by ajt]
[debbugs.git] / cgi / bugreport.cgi
1 #!/usr/bin/perl -wT
2
3 package debbugs;
4
5 use strict;
6 use POSIX qw(strftime tzset);
7 use MIME::Parser;
8 use MIME::Decoder;
9 use IO::Scalar;
10 use IO::File;
11
12 #require '/usr/lib/debbugs/errorlib';
13 require './common.pl';
14
15 require '/etc/debbugs/config';
16 require '/etc/debbugs/text';
17
18 use vars(qw($gEmailDomain $gHTMLTail $gSpoolDir $gWebDomain));
19
20 # for read_log_records
21 use Debbugs::Log;
22 use Debbugs::MIME qw(convert_to_utf8 decode_rfc1522);
23
24 use Scalar::Util qw(looks_like_number);
25
26 my %param = readparse();
27
28 my $tail_html;
29
30 my $ref = $param{'bug'} || quitcgi("No bug number");
31 $ref =~ /(\d+)/ or quitcgi("Invalid bug number");
32 $ref = $1;
33 my $short = "#$ref";
34 my $msg = $param{'msg'} || "";
35 my $att = $param{'att'};
36 my $boring = ($param{'boring'} || 'no') eq 'yes'; 
37 my $terse = ($param{'terse'} || 'no') eq 'yes';
38 my $reverse = ($param{'reverse'} || 'no') eq 'yes';
39 my $mbox = ($param{'mbox'} || 'no') eq 'yes'; 
40 my $mime = ($param{'mime'} || 'yes') eq 'yes';
41
42 my $trim_headers = ($param{trim} || ($msg?'no':'yes')) eq 'yes';
43
44 # Not used by this script directly, but fetch these so that pkgurl() and
45 # friends can propagate them correctly.
46 my $archive = ($param{'archive'} || 'no') eq 'yes';
47 my $repeatmerged = ($param{'repeatmerged'} || 'yes') eq 'yes';
48 set_option('archive', $archive);
49 set_option('repeatmerged', $repeatmerged);
50
51 my $buglog = buglog($ref);
52
53 if (defined $ENV{REQUEST_METHOD} and $ENV{REQUEST_METHOD} eq 'HEAD' and not defined($att) and not $mbox) {
54     print "Content-Type: text/html; charset=utf-8\n";
55     my @stat = stat $buglog;
56     if (@stat) {
57         my $mtime = strftime '%a, %d %b %Y %T GMT', gmtime($stat[9]);
58         print "Last-Modified: $mtime\n";
59     }
60     print "\n";
61     exit 0;
62 }
63
64 sub display_entity ($$$$\$\@);
65 sub display_entity ($$$$\$\@) {
66     my $entity = shift;
67     my $ref = shift;
68     my $top = shift;
69     my $xmessage = shift;
70     my $this = shift;
71     my $attachments = shift;
72
73     my $head = $entity->head;
74     my $disposition = $head->mime_attr('content-disposition');
75     $disposition = 'inline' if not defined $disposition or $disposition eq '';
76     my $type = $entity->effective_type;
77     my $filename = $entity->head->recommended_filename;
78     $filename = '' unless defined $filename;
79     $filename = decode_rfc1522($filename);
80
81     if ($top and not $terse) {
82          my $header = $entity->head;
83          $$this .= "<pre class=\"headers\">\n";
84          if ($trim_headers) {
85               my @headers;
86               foreach (qw(From To Cc Subject Date)) {
87                    my $head_field = $head->get($_);
88                    next unless defined $head_field and $head_field ne '';
89                    push @headers, qq(<b>$_:</b> ) . htmlsanit(decode_rfc1522($head_field));
90               }
91               $$this .= join(qq(), @headers) unless $terse;
92          } else {
93               $$this .= htmlsanit(decode_rfc1522($entity->head->stringify));
94          }
95          $$this .= "</pre>\n";
96     }
97
98     unless (($top and $type =~ m[^text(?:/plain)?(?:;|$)]) or
99             ($type =~ m[^multipart/])) {
100         push @$attachments, $entity;
101         my @dlargs = ($ref, "msg=$xmessage", "att=$#$attachments");
102         push @dlargs, "filename=$filename" if $filename ne '';
103         my $printname = $filename;
104         $printname = 'Message part ' . ($#$attachments + 1) if $filename eq '';
105         $$this .= '<pre class="mime">[<a href="' . bugurl(@dlargs) . qq{">$printname</a> } .
106                   "($type, $disposition)]</pre>\n";
107
108         if ($msg and defined($att) and $att eq $#$attachments) {
109             my $head = $entity->head;
110             chomp(my $type = $entity->effective_type);
111             my $body = $entity->stringify_body;
112             print "Content-Type: $type\n";
113             if ($filename ne '') {
114                 my $qf = $filename;
115                 $qf =~ s/"/\\"/g;
116                 $qf =~ s[.*/][];
117                 print qq{Content-Disposition: attachment; filename="$qf"\n};
118             }
119             print "\n";
120             my $decoder = new MIME::Decoder($head->mime_encoding);
121             $decoder->decode(new IO::Scalar(\$body), \*STDOUT);
122             exit(0);
123         }
124     }
125
126     return if not $top and $disposition eq 'attachment' and not defined($att);
127     return unless ($type =~ m[^text/?] and
128                    $type !~ m[^text/(?:html|enriched)(?:;|$)]) or
129                   $type =~ m[^application/pgp(?:;|$)] or
130                   $entity->parts;
131
132     if ($entity->is_multipart) {
133         my @parts = $entity->parts;
134         foreach my $part (@parts) {
135             display_entity($part, $ref, 0, $xmessage,
136                            $$this, @$attachments);
137             $$this .= "\n";
138         }
139     } elsif ($entity->parts) {
140         # We must be dealing with a nested message.
141         $$this .= "<blockquote>\n";
142         my @parts = $entity->parts;
143         foreach my $part (@parts) {
144             display_entity($part, $ref, 1, $xmessage,
145                            $$this, @$attachments);
146             $$this .= "\n";
147         }
148         $$this .= "</blockquote>\n";
149     } else {
150          if (not $terse) {
151               my $content_type = $entity->head->get('Content-Type:') || "text/html";
152               my ($charset) = $content_type =~ m/charset\s*=\s*\"?([\w-]+)\"?/i;
153               my $body = $entity->bodyhandle->as_string;
154               $body = convert_to_utf8($body,$charset) if defined $charset;
155               $body = htmlsanit($body);
156               $body =~ s,((ftp|http|https)://[\S~-]+?/?)((\&gt\;)?[)]?[']?[:.\,]?(\s|$)),<a href=\"$1\">$1</a>$3,go;
157               $$this .= "<pre class=\"message\">";
158               $$this .= $body;
159               $$this .= "</pre>\n";
160          }
161     }
162 }
163
164 my %maintainer = %{getmaintainers()};
165 my %pkgsrc = %{getpkgsrc()};
166
167 my $indexentry;
168 my $showseverity;
169
170 my $tpack;
171 my $tmain;
172
173 $ENV{"TZ"} = 'UTC';
174 tzset();
175
176 my $dtime = strftime "%a, %e %b %Y %T UTC", localtime;
177 $tail_html = $debbugs::gHTMLTail;
178 $tail_html =~ s/SUBSTITUTE_DTIME/$dtime/;
179
180 my %status = %{getbugstatus($ref)};
181 unless (%status) {
182     print <<EOF;
183 Content-Type: text/html; charset=utf-8
184
185 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
186 <html>
187 <head><title>$debbugs::gProject $debbugs::gBug report logs - $short</title></head>
188 <body>
189 <h1>$debbugs::gProject $debbugs::gBug report logs - $short</h1>
190 <p>There is no record of $debbugs::gBug $short.
191 Try the <a href="http://$gWebDomain/">search page</a> instead.</p>
192 $tail_html</body></html>
193 EOF
194     exit 0;
195 }
196
197 $|=1;
198
199 $tpack = lc $status{'package'};
200 my @tpacks = splitpackages($tpack);
201
202 if  ($status{severity} eq 'normal') {
203         $showseverity = '';
204 } elsif (isstrongseverity($status{severity})) {
205         $showseverity = "Severity: <em class=\"severity\">$status{severity}</em>;\n";
206 } else {
207         $showseverity = "Severity: $status{severity};\n";
208 }
209
210 $indexentry .= "<div class=\"msgreceived\">\n";
211 $indexentry .= htmlpackagelinks($status{package}, 0) . ";\n";
212
213 foreach my $pkg (@tpacks) {
214     my $tmaint = defined($maintainer{$pkg}) ? $maintainer{$pkg} : '(unknown)';
215     my $tsrc = defined($pkgsrc{$pkg}) ? $pkgsrc{$pkg} : '(unknown)';
216
217     $indexentry .=
218             htmlmaintlinks(sub { $_[0] == 1 ? "Maintainer for $pkg is\n"
219                                             : "Maintainers for $pkg are\n" },
220                            $tmaint);
221     $indexentry .= ";\nSource for $pkg is\n".
222             '<a href="'.srcurl($tsrc)."\">$tsrc</a>" if ($tsrc ne "(unknown)");
223     $indexentry .= ".\n";
224 }
225
226 $indexentry .= "<br>";
227 $indexentry .= htmladdresslinks("Reported by: ", \&submitterurl,
228                                 $status{originator}) . ";\n";
229 $indexentry .= sprintf "Date: %s.\n",
230                 (strftime "%a, %e %b %Y %T UTC", localtime($status{date}));
231
232 $indexentry .= "<br>Owned by: " . htmlsanit($status{owner}) . ".\n"
233               if length $status{owner};
234
235 $indexentry .= "</div>\n";
236
237 my @descstates;
238
239 $indexentry .= "<h3>$showseverity";
240 $indexentry .= sprintf "Tags: %s;\n", 
241                 htmlsanit(join(", ", sort(split(/\s+/, $status{tags}))))
242                         if length($status{tags});
243 $indexentry .= "<br>" if (length($showseverity) or length($status{tags}));
244
245 my @merged= split(/ /,$status{mergedwith});
246 if (@merged) {
247         my $descmerged = 'Merged with ';
248         my $mseparator = '';
249         for my $m (@merged) {
250                 $descmerged .= $mseparator."<a href=\"" . bugurl($m) . "\">#$m</a>";
251                 $mseparator= ",\n";
252         }
253         push @descstates, $descmerged;
254 }
255
256 if (@{$status{found_versions}}) {
257     my $foundtext = 'Found in ';
258     $foundtext .= (@{$status{found_versions}} == 1) ? 'version ' : 'versions ';
259     $foundtext .= join ', ', map htmlsanit($_), @{$status{found_versions}};
260     push @descstates, $foundtext;
261 }
262
263 if (@{$status{fixed_versions}}) {
264     my $fixedtext = '<strong>Fixed</strong> in ';
265     $fixedtext .= (@{$status{fixed_versions}} == 1) ? 'version ' : 'versions ';
266     $fixedtext .= join ', ', map htmlsanit($_), @{$status{fixed_versions}};
267     if (length($status{done})) {
268         $fixedtext .= ' by ' . htmlsanit(decode_rfc1522($status{done}));
269     }
270     push @descstates, $fixedtext;
271 } elsif (length($status{done})) {
272     push @descstates, "<strong>Done:</strong> ".htmlsanit(decode_rfc1522($status{done}));
273 } elsif (length($status{forwarded})) {
274     push @descstates, "<strong>Forwarded</strong> to ".maybelink($status{forwarded});
275 }
276
277
278 my @blockedby= split(/ /, $status{blockedby});
279 if (@blockedby && $status{"pending"} ne 'fixed' && ! length($status{done})) {
280     for my $b (@blockedby) {
281         my %s = %{getbugstatus($b)};
282         next if $s{"pending"} eq 'fixed' || length $s{done};
283         push @descstates, "Fix blocked by <a href=\"" . bugurl($b) . "\">#$b</a>: ".htmlsanit($s{subject});
284     }
285 }
286
287 my @blocks= split(/ /, $status{blocks});
288 if (@blocks && $status{"pending"} ne 'fixed' && ! length($status{done})) {
289     for my $b (@blocks) {
290         my %s = %{getbugstatus($b)};
291         next if $s{"pending"} eq 'fixed' || length $s{done};
292         push @descstates, "Blocking fix for <a href=\"" . bugurl($b) . "\">#$b</a>: ".htmlsanit($s{subject});
293     }
294 }
295
296 if ($buglog !~ m#^\Q$gSpoolDir/db#) {
297     push @descstates, "Bug is archived. No further changes may be made";
298 }
299
300 $indexentry .= join(";\n<br>", @descstates) . ".\n" if @descstates;
301 $indexentry .= "</h3>\n";
302
303 my $descriptivehead = $indexentry;
304
305 my $buglogfh;
306 if ($buglog =~ m/\.gz$/) {
307     my $oldpath = $ENV{'PATH'};
308     $ENV{'PATH'} = '/bin:/usr/bin';
309     $buglogfh = new IO::File "zcat $buglog |" or &quitcgi("open log for $ref: $!");
310     $ENV{'PATH'} = $oldpath;
311 } else {
312     $buglogfh = new IO::File "<$buglog" or &quitcgi("open log for $ref: $!");
313 }
314
315
316 my @records;
317 eval{
318      @records = read_log_records($buglogfh);
319 };
320 if ($@) {
321      quitcgi("Bad bug log for $debbugs::gBug $ref. Unable to read records: $@");
322 }
323 undef $buglogfh;
324
325 =head2 handle_email_message
326
327      handle_email_message($record->{text},
328                           ref        => $bug_number,
329                           msg_number => $msg_number,
330                          );
331
332 Returns a decoded e-mail message and displays entities/attachments as
333 appropriate.
334
335
336 =cut
337
338 sub handle_email_message{
339      my ($email,%options) = @_;
340
341      my $output = '';
342      my $parser = new MIME::Parser;
343      $parser->tmp_to_core(1);
344      $parser->output_to_core(1);
345      # $parser->output_under("/tmp");
346      my $entity = $parser->parse_data( $email);
347      # TODO: make local subdir, clean it ourselves
348      # the following does NOT delete the msg dirs in /tmp
349      END { if ( $entity ) { $entity->purge; } if ( $parser ) { $parser->filer->purge; } }
350      my @attachments = ();
351      display_entity($entity, $options{ref}, 1, $options{msg_number}, $output, @attachments);
352      return $output;
353
354 }
355
356 =head2 bug_links
357
358      bug_links($one_bug);
359      bug_links($starting_bug,$stoping_bugs,);
360
361 Creates a set of links to bugs, starting with bug number
362 $starting_bug, and finishing with $stoping_bug; if only one bug is
363 passed, makes a link to only a single bug.
364
365 The content of the link is the bug number.
366
367 =cut
368
369 sub bug_links{
370      my ($start,$stop,$query_arguments) = @_;
371      $stop = $stop || $start;
372      $query_arguments ||= '';
373      my @output;
374      for my $bug ($start..$stop) {
375           push @output,'<a href="'.bugurl($bug,'').qq(">$bug</a>);
376      }
377      return join(', ',@output);
378 }
379
380 =head2 handle_record
381
382      push @log, handle_record($record,$ref,$msg_num);
383
384 Deals with a record in a bug log as returned by
385 L<Debbugs::Log::read_log_records>; returns the log information that
386 should be output to the browser.
387
388 =cut
389
390 sub handle_record{
391      my ($record,$bug_number,$msg_number,$seen_msg_ids) = @_;
392
393      my $output = '';
394      local $_ = $record->{type};
395      if (/html/) {
396           $output .= decode_rfc1522($record->{text});
397           # Link to forwarded http:// urls in the midst of the report
398           # (even though these links already exist at the top)
399           $output =~ s,((?:ftp|http|https)://[\S~-]+?/?)([\)\'\:\.\,]?(?:\s|\.<|$)),<a href=\"$1\">$1</a>$2,go;
400           # Add links to the cloned bugs
401           $output =~ s{(Bug )(\d+)( cloned as bugs? )(\d+)(?:\-(\d+)|)}{$1.bug_links($2).$3.bug_links($4,$5)}eo;
402           $output .= '<a href="' . bugurl($ref, 'msg='.($msg_number+1)) . '">Full text</a> and <a href="' .
403                bugurl($ref, 'msg='.($msg_number+1), 'mbox') . '">rfc822 format</a> available.</em>';
404
405           $output = "<div class=\"msgreceived\">\n" . $output . "</div>\n";
406      }
407      elsif (/recips/) {
408           my ($msg_id) = $record->{text} =~ /^Message-Id:\s+<(.+)>/im;
409           if (defined $msg_id and exists $$seen_msg_ids{$msg_id}) {
410                return ();
411           }
412           elsif (defined $msg_id) {
413                $$seen_msg_ids{$msg_id} = 1;
414           }
415           $output .= 'View this message in <a href="' . bugurl($ref, "msg=$msg_number", "mbox") . '">rfc822 format</a></em>';
416           $output .= handle_email_message($record->{text},
417                                     ref        => $bug_number,
418                                     msg_number => $msg_number,
419                                    );
420      }
421      elsif (/autocheck/) {
422           # Do nothing
423      }
424      elsif (/incoming-recv/) {
425           my ($msg_id) = $record->{text} =~ /^Message-Id:\s+<(.+)>/im;
426           if (defined $msg_id and exists $$seen_msg_ids{$msg_id}) {
427                return ();
428           }
429           elsif (defined $msg_id) {
430                $$seen_msg_ids{$msg_id} = 1;
431           }
432           # Incomming Mail Message
433           my ($received,$hostname) = $record->{text} =~ m/Received: \(at (\S+)\) by (\S+)\;/;
434           $output .= qq|<p class="msgreceived"><a name="msg$msg_number">Message received at |.
435                htmlsanit("$received\@$hostname") . q| (<a href="| . bugurl($ref, "msg=$msg_number") . '">full text</a>'.q|, <a href="| . bugurl($ref, "msg=$msg_number") . '&mbox=yes">mbox</a>)'.":</a></p>\n";
436           $output .= handle_email_message($record->{text},
437                                     ref        => $bug_number,
438                                     msg_number => $msg_number,
439                                    );
440      }
441      else {
442           die "Unknown record type $_";
443      }
444      return $output;
445 }
446
447 my $log='';
448 my $msg_num = 0;
449 my $skip_next = 0;
450 if (looks_like_number($msg) and ($msg-1) <= $#records) {
451      @records = ($records[$msg-1]);
452      $msg_num = $msg - 1;
453 }
454 my @log;
455 if ( $mbox ) {
456      if (@records > 1) {
457           print qq(Content-Disposition: attachment; filename="bug_${ref}.mbox"\n);
458           print "Content-Type: text/plain\n\n";
459      }
460      else {
461           $msg_num++;
462           print qq(Content-Disposition: attachment; filename="bug_${ref}_message_${msg_num}.mbox"\n);
463           print "Content-Type: message/rfc822\n\n";
464      }
465      for my $record (@records) {
466           next if $record->{type} !~ /^(?:recips|incoming-recv)$/;
467           next if not $boring and $record->{type} eq 'recips' and @records > 1;
468           my @lines = split( "\n", $record->{text}, -1 );
469           if ( $lines[ 1 ] =~ m/^From / ) {
470                my $tmp = $lines[ 0 ];
471                $lines[ 0 ] = $lines[ 1 ];
472                $lines[ 1 ] = $tmp;
473           }
474           if ( !( $lines[ 0 ] =~ m/^From / ) ) {
475                my $date = strftime "%a %b %d %T %Y", localtime;
476                unshift @lines, "From unknown $date";
477           }
478           map { s/^(>*From )/>$1/ } @lines[ 1 .. $#lines ];
479           print join( "\n", @lines ) . "\n";
480      }
481      exit 0;
482 }
483
484 else {
485      my %seen_msg_ids;
486      for my $record (@records) {
487           $msg_num++;
488           if ($skip_next) {
489                $skip_next = 0;
490                next;
491           }
492           $skip_next = 1 if $record->{type} eq 'html' and not $boring;
493           push @log, handle_record($record,$ref,$msg_num,\%seen_msg_ids);
494      }
495 }
496
497 @log = reverse @log if $reverse;
498 $log = join('<hr>',@log);
499
500
501 print "Content-Type: text/html; charset=utf-8\n\n";
502
503 my $title = htmlsanit($status{subject});
504
505 my $dummy2 = $debbugs::gWebHostBugDir;
506
507 print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n";
508 print "<HTML><HEAD>\n" . 
509     "<TITLE>$title - $debbugs::gProject $debbugs::gBug report logs - $short</TITLE>\n" .
510      '<meta http-equiv="Content-Type" content="text/html;charset=utf-8">'.
511      "<link rel=\"stylesheet\" href=\"$debbugs::gWebHostBugDir/css/bugs.css\" type=\"text/css\">" .
512     "</HEAD>\n" .
513     '<BODY>' .
514     "\n";
515 print "<H1>" . "$debbugs::gProject $debbugs::gBug report logs - <A HREF=\"mailto:$ref\@$gEmailDomain\">$short</A>" .
516       "<BR>" . $title . "</H1>\n";
517
518 print "$descriptivehead\n";
519 printf "<div class=\"msgreceived\"><p>View this report as an <a href=\"%s\">mbox folder</a>.</p></div>\n", bugurl($ref, "mbox");
520 print "<HR>";
521 print "$log";
522 print "<HR>";
523 print "<p class=\"msgreceived\">Send a report that <a href=\"/cgi-bin/bugspam.cgi?bug=$ref\">this bug log contains spam</a>.</p>\n<HR>\n";
524 print $tail_html;
525
526 print "</BODY></HTML>\n";
527
528 exit 0;