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