]> git.donarmstrong.com Git - debbugs.git/blob - cgi/bugreport.cgi
[project @ 2005-08-11 08:48:09 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 ($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) {
82          my $header = $entity->head;
83          if ($trim_headers and not $terse) {
84               my @headers;
85               foreach (qw(From To Cc Subject Date)) {
86                    my $head_field = $head->get($_);
87                    next unless defined $head_field and $head_field ne '';
88                    push @headers, qq($_: ) . htmlsanit(decode_rfc1522($head_field));
89               }
90               $$this .= join(qq(), @headers) unless $terse;
91               $$this .= qq(\n);
92          }
93          elsif (not $terse) {
94               $$this .= htmlsanit(decode_rfc1522($entity->head->stringify));
95               $$this .= qq(\n);
96          }
97     }
98
99     unless (($top and $type =~ m[^text(?:/plain)?(?:;|$)]) or
100             ($type =~ m[^multipart/])) {
101         push @$attachments, $entity;
102         my @dlargs = ($ref, "msg=$xmessage", "att=$#$attachments");
103         push @dlargs, "filename=$filename" if $filename ne '';
104         my $printname = $filename;
105         $printname = 'Message part ' . ($#$attachments + 1) if $filename eq '';
106         $$this .= '[<a href="' . dlurl(@dlargs) . qq{">$printname</a> } .
107                   "($type, $disposition)]\n\n";
108
109         if ($msg and defined($att) and $att eq $#$attachments) {
110             my $head = $entity->head;
111             chomp(my $type = $entity->effective_type);
112             my $body = $entity->stringify_body;
113             print "Content-Type: $type\n";
114             if ($filename ne '') {
115                 my $qf = $filename;
116                 $qf =~ s/"/\\"/g;
117                 $qf =~ s[.*/][];
118                 print qq{Content-Disposition: attachment; filename="$qf"\n};
119             }
120             print "\n";
121             my $decoder = new MIME::Decoder($head->mime_encoding);
122             $decoder->decode(new IO::Scalar(\$body), \*STDOUT);
123             exit(0);
124         }
125     }
126
127     return if not $top and $disposition eq 'attachment' and not defined($att);
128     return unless ($type =~ m[^text/?] and
129                    $type !~ m[^text/(?:html|enriched)(?:;|$)]) or
130                   $type =~ m[^application/pgp(?:;|$)] or
131                   $entity->parts;
132
133     if ($entity->is_multipart) {
134         my @parts = $entity->parts;
135         foreach my $part (@parts) {
136             display_entity($part, $ref, 0, $xmessage,
137                            $$this, @$attachments);
138             $$this .= "\n";
139         }
140     } elsif ($entity->parts) {
141         # We must be dealing with a nested message.
142         $$this .= "<blockquote>\n";
143         my @parts = $entity->parts;
144         foreach my $part (@parts) {
145             display_entity($part, $ref, 1, $xmessage,
146                            $$this, @$attachments);
147             $$this .= "\n";
148         }
149         $$this .= "</blockquote>\n";
150     } else {
151          if (not $terse) {
152               my $content_type = $entity->head->get('Content-Type:');
153               my ($charset) = $content_type =~ m/charset\s*=\s*\"?([\w-]+)\"?/i;
154               my $body = $entity->bodyhandle->as_string;
155               $body = convert_to_utf8($body,$charset) if defined $charset;
156               $body = htmlsanit($body);
157               $body =~ s,((ftp|http|https)://[\S~-]+?/?)((\&gt\;)?[)]?[']?[:.\,]?(\s|$)),<a href=\"$1\">$1</a>$3,go;
158               $$this .= $body;
159          }
160     }
161 }
162
163 my %maintainer = %{getmaintainers()};
164 my %pkgsrc = %{getpkgsrc()};
165
166 my $indexentry;
167 my $descriptivehead;
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 = "<strong>Severity: $status{severity}</strong>;\n";
206 } else {
207         $showseverity = "Severity: <em>$status{severity}</em>;\n";
208 }
209
210 $indexentry .= "<p>$showseverity";
211 $indexentry .= htmlpackagelinks($status{package}, 0) . ";\n";
212
213 $indexentry .= htmladdresslinks("Reported by: ", \&submitterurl,
214                                 $status{originator}) . ";\n";
215
216 $indexentry .= "Owned by: " . htmlsanit($status{owner}) . ";\n"
217               if length $status{owner};
218
219 my $dummy = strftime "%a, %e %b %Y %T UTC", localtime($status{date});
220 $indexentry .= "Date: ".$dummy.";\n<br>";
221
222 my @descstates;
223
224 push @descstates, "Tags: <strong>"
225                 . htmlsanit(join(", ", sort(split(/\s+/, $status{tags}))))
226                 . "</strong>"
227                         if length($status{tags});
228
229 my @merged= split(/ /,$status{mergedwith});
230 if (@merged) {
231         my $descmerged = 'merged with ';
232         my $mseparator = '';
233         for my $m (@merged) {
234                 $descmerged .= $mseparator."<a href=\"" . bugurl($m) . "\">#$m</a>";
235                 $mseparator= ",\n";
236         }
237         push @descstates, $descmerged;
238 }
239
240 if (@{$status{found_versions}}) {
241     my $foundtext = 'Found in ';
242     $foundtext .= (@{$status{found_versions}} == 1) ? 'version ' : 'versions ';
243     $foundtext .= join ', ', map htmlsanit($_), @{$status{found_versions}};
244     push @descstates, $foundtext;
245 }
246
247 if (@{$status{fixed_versions}}) {
248     my $fixedtext = '<strong>Fixed</strong> in ';
249     $fixedtext .= (@{$status{fixed_versions}} == 1) ? 'version ' : 'versions ';
250     $fixedtext .= join ', ', map htmlsanit($_), @{$status{fixed_versions}};
251     if (length($status{done})) {
252         $fixedtext .= ' by ' . htmlsanit(decode_rfc1522($status{done}));
253     }
254     push @descstates, $fixedtext;
255 } elsif (length($status{done})) {
256         push @descstates, "<strong>Done:</strong> ".htmlsanit(decode_rfc1522($status{done}));
257 } elsif (length($status{forwarded})) {
258         push @descstates, "<strong>Forwarded</strong> to ".maybelink($status{forwarded});
259 }
260
261 $indexentry .= join(";\n", @descstates) . ";\n<br>" if @descstates;
262
263 $descriptivehead = $indexentry;
264 foreach my $pkg (@tpacks) {
265     my $tmaint = defined($maintainer{$pkg}) ? $maintainer{$pkg} : '(unknown)';
266     my $tsrc = defined($pkgsrc{$pkg}) ? $pkgsrc{$pkg} : '(unknown)';
267
268     $descriptivehead .=
269             htmlmaintlinks(sub { $_[0] == 1 ? "Maintainer for $pkg is\n"
270                                             : "Maintainers for $pkg are\n" },
271                            $tmaint);
272     $descriptivehead .= ";\nSource for $pkg is\n".
273             '<a href="'.srcurl($tsrc)."\">$tsrc</a>" if ($tsrc ne "(unknown)");
274     $descriptivehead .= ".\n<br>";
275 }
276
277 my $buglogfh;
278 if ($buglog =~ m/\.gz$/) {
279     my $oldpath = $ENV{'PATH'};
280     $ENV{'PATH'} = '/bin:/usr/bin';
281     $buglogfh = new IO::File "zcat $buglog |" or &quitcgi("open log for $ref: $!");
282     $ENV{'PATH'} = $oldpath;
283 } else {
284     $buglogfh = new IO::File "<$buglog" or &quitcgi("open log for $ref: $!");
285 }
286 if ($buglog !~ m#^\Q$gSpoolDir/db#) {
287     $descriptivehead .= "\n<p>Bug is <strong>archived</strong>. No further changes may be made.</p>";
288 }
289
290
291 my @records;
292 eval{
293      @records = read_log_records($buglogfh);
294 };
295 if ($@) {
296      quitcgi("Bad bug log for $debbugs::gBug $ref. Unable to read records: $@");
297 }
298 undef $buglogfh;
299
300 =head2 handle_email_message
301
302      handle_email_message($record->{text},
303                           ref        => $bug_number,
304                           msg_number => $msg_number,
305                          );
306
307 Returns a decoded e-mail message and displays entities/attachments as
308 appropriate.
309
310
311 =cut
312
313 sub handle_email_message{
314      my ($email,%options) = @_;
315
316      my $output = '';
317      my $parser = new MIME::Parser;
318      $parser->tmp_to_core(1);
319      $parser->output_to_core(1);
320      # $parser->output_under("/tmp");
321      my $entity = $parser->parse_data( $email);
322      # TODO: make local subdir, clean it ourselves
323      # the following does NOT delete the msg dirs in /tmp
324      END { if ( $entity ) { $entity->purge; } if ( $parser ) { $parser->filer->purge; } }
325      my @attachments = ();
326      display_entity($entity, $options{ref}, 1, $options{msg_number}, $output, @attachments);
327      return $output;
328
329 }
330
331 =head2 bug_links
332
333      bug_links($one_bug);
334      bug_links($starting_bug,$stoping_bugs,);
335
336 Creates a set of links to bugs, starting with bug number
337 $starting_bug, and finishing with $stoping_bug; if only one bug is
338 passed, makes a link to only a single bug.
339
340 The content of the link is the bug number.
341
342 =cut
343
344 sub bug_links{
345      my ($start,$stop,$query_arguments) = @_;
346      $stop = $stop || $start;
347      $query_arguments ||= '';
348      my @output;
349      for my $bug ($start..$stop) {
350           push @output,'<a href="'.bugurl($bug,'').qq(">$bug</a>);
351      }
352      return join(', ',@output);
353 }
354
355 =head2 handle_record
356
357      push @log, handle_record($record,$ref,$msg_num);
358
359 Deals with a record in a bug log as returned by
360 L<Debbugs::Log::read_log_records>; returns the log information that
361 should be output to the browser.
362
363 =cut
364
365 sub handle_record{
366      my ($record,$bug_number,$msg_number,$seen_msg_ids) = @_;
367
368      my $output = '';
369      local $_ = $record->{type};
370      if (/html/) {
371           $output .= decode_rfc1522($record->{text});
372           # Link to forwarded http:// urls in the midst of the report
373           # (even though these links already exist at the top)
374           $output =~ s,((?:ftp|http|https)://[\S~-]+?/?)([\)\'\:\.\,]?(?:\s|\.<|$)),<a href=\"$1\">$1</a>$2,go;
375           # Add links to the cloned bugs
376           $output =~ s{(Bug )(\d+)( cloned as bugs? )(\d+)(?:\-(\d+)|)}{$1.bug_links($2).$3.bug_links($4,$5)}eo;
377           $output .= '<a href="' . bugurl($ref, 'msg='.($msg_number+1)) . '">Full text</a> and <a href="' .
378                bugurl($ref, 'msg='.($msg_number+1)) . '&mbox=yes">rfc822 format</a> available.</em>';
379      }
380      elsif (/recips/) {
381           my ($msg_id) = $record->{text} =~ /^Message-Id:\s+<(.+)>/im;
382           if (defined $msg_id and exists $$seen_msg_ids{$msg_id}) {
383                return ();
384           }
385           elsif (defined $msg_id) {
386                $$seen_msg_ids{$msg_id} = 1;
387           }
388           $output .= 'View this message in <a href="' . bugurl($ref, "msg=$msg_number") . '&mbox=yes">rfc822 format</a></em>';
389           $output .= '<pre class="message">' .
390                handle_email_message($record->{text},
391                                     ref        => $bug_number,
392                                     msg_number => $msg_number,
393                                    ) . '</pre>';
394      }
395      elsif (/autocheck/) {
396           # Do nothing
397      }
398      elsif (/incoming-recv/) {
399           my ($msg_id) = $record->{text} =~ /^Message-Id:\s+<(.+)>/im;
400           if (defined $msg_id and exists $$seen_msg_ids{$msg_id}) {
401                return ();
402           }
403           elsif (defined $msg_id) {
404                $$seen_msg_ids{$msg_id} = 1;
405           }
406           # Incomming Mail Message
407           my ($received,$hostname) = $record->{text} =~ m/Received: \(at (\S+)\) by (\S+)\;/;
408           $output .= qq|<h2><a name="msg$msg_number">Message received at |.
409                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></h2>\n";
410           $output .= '<pre class="message">' .
411                handle_email_message($record->{text},
412                                     ref        => $bug_number,
413                                     msg_number => $msg_number,
414                                    ) . '</pre>';
415      }
416      else {
417           die "Unknown record type $_";
418      }
419      return $output;
420 }
421
422 my $log='';
423 my $msg_num = 0;
424 my $skip_next = 0;
425 if (looks_like_number($msg) and ($msg-1) <= $#records) {
426      @records = ($records[$msg-1]);
427      $msg_num = $msg - 1;
428 }
429 my @log;
430 if ( $mbox ) {
431      if (@records > 1) {
432           print qq(Content-Disposition: attachment; filename="bug_${ref}.mbox"\n);
433           print "Content-Type: text/plain\n\n";
434      }
435      else {
436           $msg_num++;
437           print qq(Content-Disposition: attachment; filename="bug_${ref}_message_${msg_num}.mbox"\n);
438           print "Content-Type: message/rfc822\n\n";
439      }
440      for my $record (@records) {
441           next if $record->{type} !~ /^(?:recips|incoming-recv)$/;
442           next if not $boring and $record->{type} eq 'recips' and @records > 1;
443           my @lines = split( "\n", $record->{text}, -1 );
444           if ( $lines[ 1 ] =~ m/^From / ) {
445                my $tmp = $lines[ 0 ];
446                $lines[ 0 ] = $lines[ 1 ];
447                $lines[ 1 ] = $tmp;
448           }
449           if ( !( $lines[ 0 ] =~ m/^From / ) ) {
450                my $date = strftime "%a %b %d %T %Y", localtime;
451                unshift @lines, "From unknown $date";
452           }
453           map { s/^(>*From )/>$1/ } @lines[ 1 .. $#lines ];
454           print join( "\n", @lines ) . "\n";
455      }
456      exit 0;
457 }
458
459 else {
460      my %seen_msg_ids;
461      for my $record (@records) {
462           $msg_num++;
463           if ($skip_next) {
464                $skip_next = 0;
465                next;
466           }
467           $skip_next = 1 if $record->{type} eq 'html' and not $boring;
468           push @log, handle_record($record,$ref,$msg_num,\%seen_msg_ids);
469      }
470 }
471
472 @log = reverse @log if $reverse;
473 $log = join('<hr>',@log);
474
475
476 print "Content-Type: text/html; charset=utf-8\n\n";
477
478 my $title = htmlsanit($status{subject});
479
480 print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n";
481 print "<HTML><HEAD>\n" . 
482     "<TITLE>$debbugs::gProject $debbugs::gBug report logs - $short - $title</TITLE>\n" .
483      '<meta http-equiv="Content-Type" content="text/html;charset=utf-8">'.
484 #    "<link rel=\"stylesheet\" href=\"$debbugs::gWebHostBugDir/bugs.css\" type=\"text/css\">" .
485     "</HEAD>\n" .
486     '<BODY>' .
487     "\n";
488 print "<H1>" . "$debbugs::gProject $debbugs::gBug report logs - <A HREF=\"mailto:$ref\@$gEmailDomain\">$short</A>" .
489       "<BR>" . $title . "</H1>\n";
490
491 print "$descriptivehead\n";
492 printf "<p>View this report as an <a href=\"%s\">mbox folder</a>.</p>\n", mboxurl($ref);
493 print "<HR>";
494 print "$log";
495 print "<HR>";
496 print "Report that <a href=\"/cgi-bin/bugspam.cgi?bug=$ref\">this bug log contains spam</a>.<HR>\n";
497 print $tail_html;
498
499 print "</BODY></HTML>\n";
500
501 exit 0;