]> git.donarmstrong.com Git - debbugs.git/blob - cgi/bugreport.cgi
merge fixes for silly jidanni bugs
[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";
113             my ($charset) = $head->get('Content-Type:') =~ m/charset\s*=\s*\"?([\w-]+)\"?/i;
114             print qq(; charset="$charset") if defined $charset;
115             print "\n";
116             if ($filename ne '') {
117                 my $qf = $filename;
118                 $qf =~ s/"/\\"/g;
119                 $qf =~ s[.*/][];
120                 print qq{Content-Disposition: inline; filename="$qf"\n};
121             }
122             print "\n";
123             my $decoder = new MIME::Decoder($head->mime_encoding);
124             $decoder->decode(new IO::Scalar(\$body), \*STDOUT);
125             exit(0);
126         }
127     }
128
129     return if not $top and $disposition eq 'attachment' and not defined($att);
130     return unless ($type =~ m[^text/?] and
131                    $type !~ m[^text/(?:html|enriched)(?:;|$)]) or
132                   $type =~ m[^application/pgp(?:;|$)] or
133                   $entity->parts;
134
135     if ($entity->is_multipart) {
136         my @parts = $entity->parts;
137         foreach my $part (@parts) {
138             display_entity($part, $ref, 0, $xmessage,
139                            $$this, @$attachments);
140             $$this .= "\n";
141         }
142     } elsif ($entity->parts) {
143         # We must be dealing with a nested message.
144         $$this .= "<blockquote>\n";
145         my @parts = $entity->parts;
146         foreach my $part (@parts) {
147             display_entity($part, $ref, 1, $xmessage,
148                            $$this, @$attachments);
149             $$this .= "\n";
150         }
151         $$this .= "</blockquote>\n";
152     } else {
153          if (not $terse) {
154               my $content_type = $entity->head->get('Content-Type:') || "text/html";
155               my ($charset) = $content_type =~ m/charset\s*=\s*\"?([\w-]+)\"?/i;
156               my $body = $entity->bodyhandle->as_string;
157               $body = convert_to_utf8($body,$charset) if defined $charset;
158               $body = htmlsanit($body);
159               # Add links to URLs
160               $body =~ s,((ftp|http|https)://[\S~-]+?/?)((\&gt\;)?[)]?[']?[:.\,]?(\s|$)),<a href=\"$1\">$1</a>$3,go;
161               # Add links to bug closures
162               $body =~ s[(closes:\s*(?:bug)?\#?\s?\d+(?:,?\s*(?:bug)?\#?\s?\d+)*)
163                         ][my $temp = $1; $temp =~ s{(\d+)}{qq(<a href=").bugurl($1).qq(">$1</a>)}ge; $temp;]gxie;
164               $$this .= qq(<pre class="message">$body</pre>\n);
165          }
166     }
167 }
168
169 my %maintainer = %{getmaintainers()};
170 my %pkgsrc = %{getpkgsrc()};
171
172 my $indexentry;
173 my $showseverity;
174
175 my $tpack;
176 my $tmain;
177
178 $ENV{"TZ"} = 'UTC';
179 tzset();
180
181 my $dtime = strftime "%a, %e %b %Y %T UTC", localtime;
182 $tail_html = $debbugs::gHTMLTail;
183 $tail_html =~ s/SUBSTITUTE_DTIME/$dtime/;
184
185 my %status = %{getbugstatus($ref)};
186 unless (%status) {
187     print <<EOF;
188 Content-Type: text/html; charset=utf-8
189
190 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
191 <html>
192 <head><title>$short - $debbugs::gProject $debbugs::gBug report logs</title></head>
193 <body>
194 <h1>$debbugs::gProject $debbugs::gBug report logs - $short</h1>
195 <p>There is no record of $debbugs::gBug $short.
196 Try the <a href="http://$gWebDomain/">search page</a> instead.</p>
197 $tail_html</body></html>
198 EOF
199     exit 0;
200 }
201
202 $|=1;
203
204 $tpack = lc $status{'package'};
205 my @tpacks = splitpackages($tpack);
206
207 if  ($status{severity} eq 'normal') {
208         $showseverity = '';
209 } elsif (isstrongseverity($status{severity})) {
210         $showseverity = "Severity: <em class=\"severity\">$status{severity}</em>;\n";
211 } else {
212         $showseverity = "Severity: $status{severity};\n";
213 }
214
215 $indexentry .= "<div class=\"msgreceived\">\n";
216 $indexentry .= htmlpackagelinks($status{package}, 0) . ";\n";
217
218 foreach my $pkg (@tpacks) {
219     my $tmaint = defined($maintainer{$pkg}) ? $maintainer{$pkg} : '(unknown)';
220     my $tsrc = defined($pkgsrc{$pkg}) ? $pkgsrc{$pkg} : '(unknown)';
221
222     $indexentry .=
223             htmlmaintlinks(sub { $_[0] == 1 ? "Maintainer for $pkg is\n"
224                                             : "Maintainers for $pkg are\n" },
225                            $tmaint);
226     $indexentry .= ";\nSource for $pkg is\n".
227             '<a href="'.srcurl($tsrc)."\">$tsrc</a>" if ($tsrc ne "(unknown)");
228     $indexentry .= ".\n";
229 }
230
231 $indexentry .= "<br>";
232 $indexentry .= htmladdresslinks("Reported by: ", \&submitterurl,
233                                 $status{originator}) . ";\n";
234 $indexentry .= sprintf "Date: %s.\n",
235                 (strftime "%a, %e %b %Y %T UTC", localtime($status{date}));
236
237 $indexentry .= "<br>Owned by: " . htmlsanit($status{owner}) . ".\n"
238               if length $status{owner};
239
240 $indexentry .= "</div>\n";
241
242 my @descstates;
243
244 $indexentry .= "<h3>$showseverity";
245 $indexentry .= sprintf "Tags: %s;\n", 
246                 htmlsanit(join(", ", sort(split(/\s+/, $status{tags}))))
247                         if length($status{tags});
248 $indexentry .= "<br>" if (length($showseverity) or length($status{tags}));
249
250 my @merged= split(/ /,$status{mergedwith});
251 if (@merged) {
252         my $descmerged = 'Merged with ';
253         my $mseparator = '';
254         for my $m (@merged) {
255                 $descmerged .= $mseparator."<a href=\"" . bugurl($m) . "\">#$m</a>";
256                 $mseparator= ",\n";
257         }
258         push @descstates, $descmerged;
259 }
260
261 if (@{$status{found_versions}}) {
262     my $foundtext = 'Found in ';
263     $foundtext .= (@{$status{found_versions}} == 1) ? 'version ' : 'versions ';
264     $foundtext .= join ', ', map htmlsanit($_), @{$status{found_versions}};
265     push @descstates, $foundtext;
266 }
267
268 if (@{$status{fixed_versions}}) {
269     my $fixedtext = '<strong>Fixed</strong> in ';
270     $fixedtext .= (@{$status{fixed_versions}} == 1) ? 'version ' : 'versions ';
271     $fixedtext .= join ', ', map htmlsanit($_), @{$status{fixed_versions}};
272     if (length($status{done})) {
273         $fixedtext .= ' by ' . htmlsanit(decode_rfc1522($status{done}));
274     }
275     push @descstates, $fixedtext;
276 } elsif (length($status{done})) {
277     push @descstates, "<strong>Done:</strong> ".htmlsanit(decode_rfc1522($status{done}));
278 } elsif (length($status{forwarded})) {
279     push @descstates, "<strong>Forwarded</strong> to ".maybelink($status{forwarded});
280 }
281
282
283 my @blockedby= split(/ /, $status{blockedby});
284 if (@blockedby && $status{"pending"} ne 'fixed' && ! length($status{done})) {
285     for my $b (@blockedby) {
286         my %s = %{getbugstatus($b)};
287         next if $s{"pending"} eq 'fixed' || length $s{done};
288         push @descstates, "Fix blocked by <a href=\"" . bugurl($b) . "\">#$b</a>: ".htmlsanit($s{subject});
289     }
290 }
291
292 my @blocks= split(/ /, $status{blocks});
293 if (@blocks && $status{"pending"} ne 'fixed' && ! length($status{done})) {
294     for my $b (@blocks) {
295         my %s = %{getbugstatus($b)};
296         next if $s{"pending"} eq 'fixed' || length $s{done};
297         push @descstates, "Blocking fix for <a href=\"" . bugurl($b) . "\">#$b</a>: ".htmlsanit($s{subject});
298     }
299 }
300
301 if ($buglog !~ m#^\Q$gSpoolDir/db#) {
302     push @descstates, "Bug is archived. No further changes may be made";
303 }
304
305 $indexentry .= join(";\n<br>", @descstates) . ".\n" if @descstates;
306 $indexentry .= "</h3>\n";
307
308 my $descriptivehead = $indexentry;
309
310 my $buglogfh;
311 if ($buglog =~ m/\.gz$/) {
312     my $oldpath = $ENV{'PATH'};
313     $ENV{'PATH'} = '/bin:/usr/bin';
314     $buglogfh = new IO::File "zcat $buglog |" or &quitcgi("open log for $ref: $!");
315     $ENV{'PATH'} = $oldpath;
316 } else {
317     $buglogfh = new IO::File "<$buglog" or &quitcgi("open log for $ref: $!");
318 }
319
320
321 my @records;
322 eval{
323      @records = read_log_records($buglogfh);
324 };
325 if ($@) {
326      quitcgi("Bad bug log for $debbugs::gBug $ref. Unable to read records: $@");
327 }
328 undef $buglogfh;
329
330 =head2 handle_email_message
331
332      handle_email_message($record->{text},
333                           ref        => $bug_number,
334                           msg_number => $msg_number,
335                          );
336
337 Returns a decoded e-mail message and displays entities/attachments as
338 appropriate.
339
340
341 =cut
342
343 sub handle_email_message{
344      my ($email,%options) = @_;
345
346      my $output = '';
347      my $parser = new MIME::Parser;
348      # Because we are using memory, not tempfiles, there's no need to
349      # clean up here like in Debbugs::MIME
350      $parser->tmp_to_core(1);
351      $parser->output_to_core(1);
352      my $entity = $parser->parse_data( $email);
353      my @attachments = ();
354      display_entity($entity, $options{ref}, 1, $options{msg_number}, $output, @attachments);
355      return $output;
356
357 }
358
359 =head2 bug_links
360
361      bug_links($one_bug);
362      bug_links($starting_bug,$stoping_bugs,);
363
364 Creates a set of links to bugs, starting with bug number
365 $starting_bug, and finishing with $stoping_bug; if only one bug is
366 passed, makes a link to only a single bug.
367
368 The content of the link is the bug number.
369
370 =cut
371
372 sub bug_links{
373      my ($start,$stop,$query_arguments) = @_;
374      $stop = $stop || $start;
375      $query_arguments ||= '';
376      my @output;
377      for my $bug ($start..$stop) {
378           push @output,'<a href="'.bugurl($bug,'').qq(">$bug</a>);
379      }
380      return join(', ',@output);
381 }
382
383 =head2 handle_record
384
385      push @log, handle_record($record,$ref,$msg_num);
386
387 Deals with a record in a bug log as returned by
388 L<Debbugs::Log::read_log_records>; returns the log information that
389 should be output to the browser.
390
391 =cut
392
393 sub handle_record{
394      my ($record,$bug_number,$msg_number,$seen_msg_ids) = @_;
395
396      my $output = '';
397      local $_ = $record->{type};
398      if (/html/) {
399           my $class = $record->{text} =~ /^<strong>(?:Acknowledgement|Reply|Information|Report|Notification)/ ? 'infmessage':'msgreceived';
400           $output .= decode_rfc1522($record->{text});
401           # Link to forwarded http:// urls in the midst of the report
402           # (even though these links already exist at the top)
403           $output =~ s,((?:ftp|http|https)://[\S~-]+?/?)([\)\'\:\.\,]?(?:\s|\.<|$)),<a href=\"$1\">$1</a>$2,go;
404           # Add links to the cloned bugs
405           $output =~ s{(Bug )(\d+)( cloned as bugs? )(\d+)(?:\-(\d+)|)}{$1.bug_links($2).$3.bug_links($4,$5)}eo;
406           # Add links to merged bugs
407           $output =~ s{(?<=Merged )([\d\s]+)(?=\.)}{join(' ',map {bug_links($_)} (split /\s+/, $1))}eo;
408           # Add links to blocked bugs
409           $output =~ s{(?<=Blocking bugs)(?:(of )(\d+))?( (?:added|set to|removed):\s+)([\d\s\,]+)}
410                       {(defined $2?$1.bug_links($2):'').$3.
411                             join(' ',map {bug_links($_)} (split /\,?\s+/, $4))}eo;
412           # Add links to reassigned packages
413           $output =~ s{(Bug reassigned from package \`)([^\']+)(' to \`)([^\']+)(')}
414           {$1.q(<a href=").pkgurl($2).qq(">$2</a>).$3.q(<a href=").pkgurl($4).qq(">$4</a>).$5}eo;
415           $output .= '<a href="' . bugurl($ref, 'msg='.($msg_number+1)) . '">Full text</a> and <a href="' .
416                bugurl($ref, 'msg='.($msg_number+1), 'mbox') . '">rfc822 format</a> available.';
417
418           $output = qq(<div class="$class"><hr>\n<a name="$msg_number"></a>\n) . $output . "</div>\n";
419      }
420      elsif (/recips/) {
421           my ($msg_id) = $record->{text} =~ /^Message-Id:\s+<(.+)>/im;
422           if (defined $msg_id and exists $$seen_msg_ids{$msg_id}) {
423                return ();
424           }
425           elsif (defined $msg_id) {
426                $$seen_msg_ids{$msg_id} = 1;
427           }
428           $output .= qq(<hr><a name="$msg_number"></a>\n);
429           $output .= 'View this message in <a href="' . bugurl($ref, "msg=$msg_number", "mbox") . '">rfc822 format</a>';
430           $output .= handle_email_message($record->{text},
431                                     ref        => $bug_number,
432                                     msg_number => $msg_number,
433                                    );
434      }
435      elsif (/autocheck/) {
436           # Do nothing
437      }
438      elsif (/incoming-recv/) {
439           my ($msg_id) = $record->{text} =~ /^Message-Id:\s+<(.+)>/im;
440           if (defined $msg_id and exists $$seen_msg_ids{$msg_id}) {
441                return ();
442           }
443           elsif (defined $msg_id) {
444                $$seen_msg_ids{$msg_id} = 1;
445           }
446           # Incomming Mail Message
447           my ($received,$hostname) = $record->{text} =~ m/Received: \(at (\S+)\) by (\S+)\;/;
448           $output .= qq|<hr><p class="msgreceived"><a name="$msg_number"><a name="msg$msg_number">Message received</a> at |.
449                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>)'.":</p>\n";
450           $output .= handle_email_message($record->{text},
451                                     ref        => $bug_number,
452                                     msg_number => $msg_number,
453                                    );
454      }
455      else {
456           die "Unknown record type $_";
457      }
458      return $output;
459 }
460
461 my $log='';
462 my $msg_num = 0;
463 my $skip_next = 0;
464 if (looks_like_number($msg) and ($msg-1) <= $#records) {
465      @records = ($records[$msg-1]);
466      $msg_num = $msg - 1;
467 }
468 my @log;
469 if ( $mbox ) {
470      if (@records > 1) {
471           print qq(Content-Disposition: attachment; filename="bug_${ref}.mbox"\n);
472           print "Content-Type: text/plain\n\n";
473      }
474      else {
475           $msg_num++;
476           print qq(Content-Disposition: attachment; filename="bug_${ref}_message_${msg_num}.mbox"\n);
477           print "Content-Type: message/rfc822\n\n";
478      }
479      for my $record (@records) {
480           next if $record->{type} !~ /^(?:recips|incoming-recv)$/;
481           next if not $boring and $record->{type} eq 'recips' and @records > 1;
482           my @lines = split( "\n", $record->{text}, -1 );
483           if ( $lines[ 1 ] =~ m/^From / ) {
484                my $tmp = $lines[ 0 ];
485                $lines[ 0 ] = $lines[ 1 ];
486                $lines[ 1 ] = $tmp;
487           }
488           if ( !( $lines[ 0 ] =~ m/^From / ) ) {
489                my $date = strftime "%a %b %d %T %Y", localtime;
490                unshift @lines, "From unknown $date";
491           }
492           map { s/^(>*From )/>$1/ } @lines[ 1 .. $#lines ];
493           print join( "\n", @lines ) . "\n";
494      }
495      exit 0;
496 }
497
498 else {
499      my %seen_msg_ids;
500      for my $record (@records) {
501           $msg_num++;
502           if ($skip_next) {
503                $skip_next = 0;
504                next;
505           }
506           $skip_next = 1 if $record->{type} eq 'html' and not $boring;
507           push @log, handle_record($record,$ref,$msg_num,\%seen_msg_ids);
508      }
509 }
510
511 @log = reverse @log if $reverse;
512 $log = join("\n",@log);
513
514
515 print "Content-Type: text/html; charset=utf-8\n\n";
516
517 my $title = htmlsanit($status{subject});
518
519 my $dummy2 = $debbugs::gWebHostBugDir;
520
521 print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n";
522 print <<END;
523 <HTML><HEAD>
524 <TITLE>$short - $title - $debbugs::gProject $debbugs::gBug report logs</TITLE>
525 <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
526 <link rel="stylesheet" href="$debbugs::gWebHostBugDir/css/bugs.css" type="text/css">
527 <script type="text/javascript">
528 <!--
529 function toggle_infmessages(){
530        var styles = document.styleSheets;
531        var deleted = 0
532        for (var i = 0; i < styles.length; i++) {
533           for (var j = 0; j < styles[i].cssRules.length; j++) {
534             if (styles[i].cssRules[j].cssText == ".infmessage { display: none; }") {
535                  styles[i].deleteRule(j);
536                  deleted = 1;
537             }
538           }
539        }
540        if (!deleted) {
541             styles[0].insertRule(".infmessage { display: none; }",0);
542        }
543 }
544 -->
545 </script>
546 </HEAD>
547 <BODY>
548 END
549 print "<H1>" . "$debbugs::gProject $debbugs::gBug report logs - <A HREF=\"mailto:$ref\@$gEmailDomain\">$short</A>" .
550       "<BR>" . $title . "</H1>\n";
551
552 print "$descriptivehead\n";
553 print qq(<p><a href="mailto:$ref\@$debbugs::gEmailDomain">Reply</a> ),
554      qq(or <a href="mailto:$ref-subscribe\@$debbugs::gEmailDomain">subscribe</a> ),
555      qq(to this bug.</p>\n);
556 print qq(<p><a href="javascript:toggle_infmessages();">Toggle useless messages</a></p>);
557 printf "<div class=\"msgreceived\"><p>View this report as an <a href=\"%s\">mbox folder</a>.</p></div>\n", bugurl($ref, "mbox");
558 print "$log";
559 print "<HR>";
560 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";
561 print $tail_html;
562
563 print "</BODY></HTML>\n";
564
565 exit 0;