]> git.donarmstrong.com Git - debbugs.git/blob - cgi/bugreport.cgi
[project @ 2005-07-31 04:43:01 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 = read_log_records($buglogfh);
293 undef $buglogfh;
294
295 =head2 handle_email_message
296
297      handle_email_message($record->{text},
298                           ref        => $bug_number,
299                           msg_number => $msg_number,
300                          );
301
302 Returns a decoded e-mail message and displays entities/attachments as
303 appropriate.
304
305
306 =cut
307
308 sub handle_email_message{
309      my ($email,%options) = @_;
310
311      my $output = '';
312      my $parser = new MIME::Parser;
313      $parser->tmp_to_core(1);
314      $parser->output_to_core(1);
315      # $parser->output_under("/tmp");
316      my $entity = $parser->parse_data( $email);
317      # TODO: make local subdir, clean it ourselves
318      # the following does NOT delete the msg dirs in /tmp
319      END { if ( $entity ) { $entity->purge; } if ( $parser ) { $parser->filer->purge; } }
320      my @attachments = ();
321      display_entity($entity, $options{ref}, 1, $options{msg_number}, $output, @attachments);
322      return $output;
323
324 }
325
326 =head2 bug_links
327
328      bug_links($one_bug);
329      bug_links($starting_bug,$stoping_bugs,);
330
331 Creates a set of links to bugs, starting with bug number
332 $starting_bug, and finishing with $stoping_bug; if only one bug is
333 passed, makes a link to only a single bug.
334
335 The content of the link is the bug number.
336
337 =cut
338
339 sub bug_links{
340      my ($start,$stop,$query_arguments) = @_;
341      $stop = $stop || $start;
342      $query_arguments ||= '';
343      my @output;
344      for my $bug ($start..$stop) {
345           push @output,'<a href="'.bugurl($bug,'').qq(">$bug</a>);
346      }
347      return join(', ',@output);
348 }
349
350 =head2 handle_record
351
352      push @log, handle_record($record,$ref,$msg_num);
353
354 Deals with a record in a bug log as returned by
355 L<Debbugs::Log::read_log_records>; returns the log information that
356 should be output to the browser.
357
358 =cut
359
360 sub handle_record{
361      my ($record,$bug_number,$msg_number,$seen_msg_ids) = @_;
362
363      my $output = '';
364      local $_ = $record->{type};
365      if (/html/) {
366           $output .= decode_rfc1522($record->{text});
367           # Link to forwarded http:// urls in the midst of the report
368           # (even though these links already exist at the top)
369           $output =~ s,((?:ftp|http|https)://[\S~-]+?/?)([\)\'\:\.\,]?(?:\s|\.<|$)),<a href=\"$1\">$1</a>$2,go;
370           # Add links to the cloned bugs
371           $output =~ s{(Bug )(\d+)( cloned as bugs? )(\d+)(?:\-(\d+)|)}{$1.bug_links($2).$3.bug_links($4,$5)}eo;
372           $output .= '<a href="' . bugurl($ref, 'msg='.($msg_number+1)) . '">Full text</a> and <a href="' .
373                bugurl($ref, 'msg='.($msg_number+1)) . '&mbox=yes">rfc822 format</a> available.</em>';
374      }
375      elsif (/recips/) {
376           my ($msg_id) = $record->{text} =~ /^Message-Id:\s+<(.+)>/im;
377           if (defined $msg_id and exists $$seen_msg_ids{$msg_id}) {
378                return ();
379           }
380           elsif (defined $msg_id) {
381                $$seen_msg_ids{$msg_id} = 1;
382           }
383           $output .= 'View this message in <a href="' . bugurl($ref, "msg=$msg_number") . '&mbox=yes">rfc822 format</a></em>';
384           $output .= '<pre class="message">' .
385                handle_email_message($record->{text},
386                                     ref        => $bug_number,
387                                     msg_number => $msg_number,
388                                    ) . '</pre>';
389      }
390      elsif (/autocheck/) {
391           # Do nothing
392      }
393      elsif (/incoming-recv/) {
394           my ($msg_id) = $record->{text} =~ /^Message-Id:\s+<(.+)>/im;
395           if (defined $msg_id and exists $$seen_msg_ids{$msg_id}) {
396                return ();
397           }
398           elsif (defined $msg_id) {
399                $$seen_msg_ids{$msg_id} = 1;
400           }
401           # Incomming Mail Message
402           my ($received,$hostname) = $record->{text} =~ m/Received: \(at (\S+)\) by (\S+)\;/;
403           $output .= qq|<h2><a name="msg$msg_number">Message received at |.
404                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";
405           $output .= '<pre class="message">' .
406                handle_email_message($record->{text},
407                                     ref        => $bug_number,
408                                     msg_number => $msg_number,
409                                    ) . '</pre>';
410      }
411      else {
412           die "Unknown record type $_";
413      }
414      return $output;
415 }
416
417 my $log='';
418 my $msg_num = 0;
419 my $skip_next = 0;
420 if (looks_like_number($msg) and ($msg-1) <= $#records) {
421      @records = ($records[$msg-1]);
422      $msg_num = $msg - 1;
423 }
424 my @log;
425 if ( $mbox ) {
426      if (@records > 1) {
427           print qq(Content-Disposition: attachment; filename="bug_${ref}.mbox"\n);
428           print "Content-Type: text/plain\n\n";
429      }
430      else {
431           print qq(Content-Disposition: attachment; filename="bug_${ref}_message_${msg_num}.mbox"\n);
432           print "Content-Type: message/rfc822\n\n";
433      }
434      for my $record (@records) {
435           next if $record->{type} !~ /^(?:recips|incoming-recv)$/;
436           next if not $boring and $record->{type} eq 'recips';
437           my @lines = split( "\n", $record->{text}, -1 );
438           if ( $lines[ 1 ] =~ m/^From / ) {
439                my $tmp = $lines[ 0 ];
440                $lines[ 0 ] = $lines[ 1 ];
441                $lines[ 1 ] = $tmp;
442           }
443           if ( !( $lines[ 0 ] =~ m/^From / ) ) {
444                my $date = strftime "%a %b %d %T %Y", localtime;
445                unshift @lines, "From unknown $date";
446           }
447           map { s/^(>*From )/>$1/ } @lines[ 1 .. $#lines ];
448           print join( "\n", @lines ) . "\n";
449      }
450      exit 0;
451 }
452
453 else {
454      my %seen_msg_ids;
455      for my $record (@records) {
456           $msg_num++;
457           if ($skip_next) {
458                $skip_next = 0;
459                next;
460           }
461           $skip_next = 1 if $record->{type} eq 'html' and not $boring;
462           push @log, handle_record($record,$ref,$msg_num,\%seen_msg_ids);
463      }
464 }
465
466 @log = reverse @log if $reverse;
467 $log = join('<hr>',@log);
468
469
470 print "Content-Type: text/html; charset=utf-8\n\n";
471
472 my $title = htmlsanit($status{subject});
473
474 print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n";
475 print "<HTML><HEAD>\n" . 
476     "<TITLE>$debbugs::gProject $debbugs::gBug report logs - $short - $title</TITLE>\n" .
477 #    "<link rel=\"stylesheet\" href=\"$debbugs::gWebHostBugDir/bugs.css\" type=\"text/css\">" .
478     "</HEAD>\n" .
479     '<BODY>' .
480     "\n";
481 print "<H1>" . "$debbugs::gProject $debbugs::gBug report logs - <A HREF=\"mailto:$ref\@$gEmailDomain\">$short</A>" .
482       "<BR>" . $title . "</H1>\n";
483
484 print "$descriptivehead\n";
485 printf "<p>View this report as an <a href=\"%s\">mbox folder</a>.</p>\n", mboxurl($ref);
486 print "<HR>";
487 print "$log";
488 print $tail_html;
489
490 print "</BODY></HTML>\n";
491
492 exit 0;