]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/CGI/Bugreport.pm
Merge branch 'master' into don/processcleanup
[debbugs.git] / Debbugs / CGI / Bugreport.pm
1 # This module is part of debbugs, and is released
2 # under the terms of the GPL version 2, or any later version. See the
3 # file README and COPYING for more information.
4 #
5 # [Other people have contributed to this file; their copyrights should
6 # be listed here too.]
7 # Copyright 2008 by Don Armstrong <don@donarmstrong.com>.
8
9
10 package Debbugs::CGI::Bugreport;
11
12 =head1 NAME
13
14 Debbugs::CGI::Bugreport -- specific routines for the bugreport cgi script
15
16 =head1 SYNOPSIS
17
18
19 =head1 DESCRIPTION
20
21
22 =head1 BUGS
23
24 None known.
25
26 =cut
27
28 use warnings;
29 use strict;
30 use vars qw($VERSION $DEBUG %EXPORT_TAGS @EXPORT_OK @EXPORT);
31 use base qw(Exporter);
32
33 use IO::Scalar;
34 use Params::Validate qw(validate_with :types);
35 use Debbugs::MIME qw(convert_to_utf8 decode_rfc1522 create_mime_message);
36 use Debbugs::CGI qw(:url :html :util);
37 use Debbugs::Common qw(globify_scalar english_join);
38 use Debbugs::Config qw(:config);
39 use POSIX qw(strftime);
40 use Encode qw(decode_utf8);
41
42 BEGIN{
43      ($VERSION) = q$Revision: 494 $ =~ /^Revision:\s+([^\s+])/;
44      $DEBUG = 0 unless defined $DEBUG;
45
46      @EXPORT = ();
47      %EXPORT_TAGS = ();
48      @EXPORT_OK = (qw(display_entity handle_record handle_email_message));
49      Exporter::export_ok_tags(keys %EXPORT_TAGS);
50      $EXPORT_TAGS{all} = [@EXPORT_OK];
51 }
52
53
54
55 =head2 display_entity
56
57      display_entity(entity      => $entity,
58                     bug_num     => $ref,
59                     outer       => 1,
60                     msg_num     => $msg_num,
61                     attachments => \@attachments,
62                     output      => \$output);
63
64
65 =over
66
67 =item entity -- MIME::Parser entity
68
69 =item bug_num -- Bug number
70
71 =item outer -- Whether this is the outer entity; defaults to 1
72
73 =item msg_num -- message number in the log
74
75 =item attachments -- arrayref of attachments
76
77 =item output -- scalar reference for output
78
79 =back
80
81 =cut
82
83 sub display_entity {
84     my %param = validate_with(params => \@_,
85                               spec   => {entity      => {type => OBJECT,
86                                                         },
87                                          bug_num     => {type => SCALAR,
88                                                          regex => qr/^\d+$/,
89                                                         },
90                                          outer       => {type => BOOLEAN,
91                                                          default => 1,
92                                                         },
93                                          msg_num     => {type => SCALAR,
94                                                         },
95                                          attachments => {type => ARRAYREF,
96                                                          default => [],
97                                                         },
98                                          output      => {type => SCALARREF|HANDLE,
99                                                          default => \*STDOUT,
100                                                         },
101                                          terse       => {type => BOOLEAN,
102                                                          default => 0,
103                                                         },
104                                          msg         => {type => SCALAR,
105                                                          optional => 1,
106                                                         },
107                                          att         => {type => SCALAR,
108                                                          optional => 1,
109                                                         },
110                                          trim_headers => {type => BOOLEAN,
111                                                           default => 1,
112                                                          },
113                                         }
114                              );
115
116     $param{output} = globify_scalar($param{output});
117     my $entity = $param{entity};
118     my $ref = $param{bug_num};
119     my $top = $param{outer};
120     my $xmessage = $param{msg_num};
121     my $attachments = $param{attachments};
122
123     my $head = $entity->head;
124     my $disposition = $head->mime_attr('content-disposition');
125     $disposition = 'inline' if not defined $disposition or $disposition eq '';
126     my $type = $entity->effective_type;
127     my $filename = $entity->head->recommended_filename;
128     $filename = '' unless defined $filename;
129     $filename = decode_rfc1522($filename);
130
131     if ($param{outer} and
132         not $param{terse} and
133         not exists $param{att}) {
134          my $header = $entity->head;
135          print {$param{output}} "<pre class=\"headers\">\n";
136          if ($param{trim_headers}) {
137               my @headers;
138               foreach (qw(From To Cc Subject Date)) {
139                    my $head_field = $head->get($_);
140                    next unless defined $head_field and $head_field ne '';
141                    push @headers, qq(<b>$_:</b> ) . html_escape(decode_rfc1522($head_field));
142               }
143               print {$param{output}} join(qq(), @headers);
144          } else {
145               print {$param{output}} html_escape(decode_rfc1522($entity->head->stringify));
146          }
147          print {$param{output}} "</pre>\n";
148     }
149
150     if (not (($param{outer} and $type =~ m{^text(?:/plain)?(?:;|$)})
151              or $type =~ m{^multipart/}
152             )) {
153         push @$attachments, $param{entity};
154         # output this attachment
155         if (exists $param{att} and
156             $param{att} == $#$attachments) {
157             my $head = $entity->head;
158             chomp(my $type = $entity->effective_type);
159             my $body = $entity->stringify_body;
160             # this attachment has its own content type, so we must not
161             # try to convert it to UTF-8 or do anything funky.
162             my @layers = PerlIO::get_layers($param{output});
163             binmode($param{output},':raw');
164             print {$param{output}} "Content-Type: $type";
165             my ($charset) = $head->get('Content-Type:') =~ m/charset\s*=\s*\"?([\w-]+)\"?/i;
166             print {$param{output}} qq(; charset="$charset") if defined $charset;
167             print {$param{output}} "\n";
168             if ($filename ne '') {
169                 my $qf = $filename;
170                 $qf =~ s/"/\\"/g;
171                 $qf =~ s[.*/][];
172                 print {$param{output}} qq{Content-Disposition: inline; filename="$qf"\n};
173             }
174             print {$param{output}} "\n";
175             my $decoder = MIME::Decoder->new($head->mime_encoding);
176             $decoder->decode(IO::Scalar->new(\$body), $param{output});
177             if (grep {/utf8/} @layers) {
178                 binmode($param{output},':utf8');
179             }
180             return;
181         }
182         elsif (not exists $param{att}) {
183              my @dlargs = (msg=>$xmessage, att=>$#$attachments);
184              push @dlargs, (filename=>$filename) if $filename ne '';
185              my $printname = $filename;
186              $printname = 'Message part ' . ($#$attachments + 1) if $filename eq '';
187              print {$param{output}} '<pre class="mime">[<a href="' .
188                   html_escape(bug_links(bug => $ref,
189                                         links_only => 1,
190                                         options => {@dlargs})
191                              ) . qq{">$printname</a> } .
192                                   "($type, $disposition)]</pre>\n";
193         }
194     }
195
196     return if not $param{outer} and $disposition eq 'attachment' and not exists $param{att};
197     return unless ($type =~ m[^text/?] and
198                    $type !~ m[^text/(?:html|enriched)(?:;|$)]) or
199                   $type =~ m[^application/pgp(?:;|$)] or
200                   $entity->parts;
201
202     if ($entity->is_multipart) {
203         my @parts = $entity->parts;
204         foreach my $part (@parts) {
205             display_entity(entity => $part,
206                            bug_num => $ref,
207                            outer => 0,
208                            msg_num => $xmessage,
209                            output => $param{output},
210                            attachments => $attachments,
211                            terse => $param{terse},
212                            exists $param{msg}?(msg=>$param{msg}):(),
213                            exists $param{att}?(att=>$param{att}):(),
214                           );
215             # print {$param{output}} "\n";
216         }
217     } elsif ($entity->parts) {
218         # We must be dealing with a nested message.
219          if (not exists $param{att}) {
220               print {$param{output}} "<blockquote>\n";
221          }
222         my @parts = $entity->parts;
223         foreach my $part (@parts) {
224             display_entity(entity => $part,
225                            bug_num => $ref,
226                            outer => 1,
227                            msg_num => $xmessage,
228                            output => $param{output},
229                            attachments => $attachments,
230                            terse => $param{terse},
231                            exists $param{msg}?(msg=>$param{msg}):(),
232                            exists $param{att}?(att=>$param{att}):(),
233                           );
234             # print {$param{output}} "\n";
235         }
236          if (not exists $param{att}) {
237               print {$param{output}} "</blockquote>\n";
238          }
239     } elsif (not $param{terse}) {
240          my $content_type = $entity->head->get('Content-Type:') || "text/html";
241          my ($charset) = $content_type =~ m/charset\s*=\s*\"?([\w-]+)\"?/i;
242          my $body = $entity->bodyhandle->as_string;
243          $body = convert_to_utf8($body,$charset//'utf8');
244          $body = html_escape($body);
245          # Attempt to deal with format=flowed
246          if ($content_type =~ m/format\s*=\s*\"?flowed\"?/i) {
247               $body =~ s{^\ }{}mgo;
248               # we ignore the other things that you can do with
249               # flowed e-mails cause they don't really matter.
250          }
251          # Add links to URLs
252          # We don't html escape here because we escape above;
253          # wierd terminators are because of that
254          $body =~ s{((?:ftp|http|https|svn|ftps|rsync)://[\S~-]+?/?) # Url
255                     ((?:\&gt\;)?[)]?(?:'|\&\#39\;)?[:.\,]?(?:\s|$)) # terminators
256               }{<a href=\"$1\">$1</a>$2}gox;
257          # Add links to bug closures
258          $body =~ s[(closes:\s*(?:bug)?\#?\s?\d+(?:,?\s*(?:bug)?\#?\s?\d+)*)]
259                    [my $temp = $1;
260                     $temp =~ s{(\d+)}
261                               {bug_links(bug=>$1)}ge;
262                     $temp;]gxie;
263          if (defined $config{cve_tracker} and
264              length $config{cve_tracker}
265             ) {
266              # Add links to CVE vulnerabilities (closes #568464)
267              $body =~ s{(^|\s)(CVE-\d{4}-\d{4,})(\s|[,.-\[\]]|$)}
268                        {$1<a href="http://$config{cve_tracker}$2">$2</a>$3}gxm;
269          }
270          if (not exists $param{att}) {
271               print {$param{output}} qq(<pre class="message">$body</pre>\n);
272          }
273     }
274 }
275
276
277 =head2 handle_email_message
278
279      handle_email_message($record->{text},
280                           ref        => $bug_number,
281                           msg_num => $msg_number,
282                          );
283
284 Returns a decoded e-mail message and displays entities/attachments as
285 appropriate.
286
287
288 =cut
289
290 sub handle_email_message{
291      my ($email,%param) = @_;
292
293      # output needs to have the is_utf8 flag on to avoid double
294      # encoding
295      my $output = decode_utf8('');
296      my $parser = MIME::Parser->new();
297      # Because we are using memory, not tempfiles, there's no need to
298      # clean up here like in Debbugs::MIME
299      $parser->tmp_to_core(1);
300      $parser->output_to_core(1);
301      my $entity = $parser->parse_data( $email);
302      my @attachments = ();
303      display_entity(entity  => $entity,
304                     bug_num => $param{ref},
305                     outer   => 1,
306                     msg_num => $param{msg_num},
307                     output => \$output,
308                     attachments => \@attachments,
309                     terse       => $param{terse},
310                     exists $param{msg}?(msg=>$param{msg}):(),
311                     exists $param{att}?(att=>$param{att}):(),
312                     exists $param{trim_headers}?(trim_headers=>$param{trim_headers}):(),
313                    );
314      return $output;
315
316 }
317
318 =head2 handle_record
319
320      push @log, handle_record($record,$ref,$msg_num);
321
322 Deals with a record in a bug log as returned by
323 L<Debbugs::Log::read_log_records>; returns the log information that
324 should be output to the browser.
325
326 =cut
327
328 sub handle_record{
329      my ($record,$bug_number,$msg_number,$seen_msg_ids) = @_;
330
331      # output needs to have the is_utf8 flag on to avoid double
332      # encoding
333      my $output = decode_utf8('');
334      local $_ = $record->{type};
335      if (/html/) {
336          # $record->{text} is not in perl's internal encoding; convert it
337          my $text = decode_utf8($record->{text});
338           my ($time) = $text =~ /<!--\s+time:(\d+)\s+-->/;
339           my $class = $text =~ /^<strong>(?:Acknowledgement|Reply|Information|Report|Notification)/m ? 'infmessage':'msgreceived';
340           $output .= decode_rfc1522($text);
341           # Link to forwarded http:// urls in the midst of the report
342           # (even though these links already exist at the top)
343           $output =~ s,((?:ftp|http|https)://[\S~-]+?/?)((?:[\)\'\:\.\,]|\&\#39;)?(?:\s|\.<|$)),<a href=\"$1\">$1</a>$2,go;
344           # Add links to the cloned bugs
345           $output =~ s{(Bug )(\d+)( cloned as bugs? )(\d+)(?:\-(\d+)|)}{$1.bug_links(bug=>$2).$3.bug_links(bug=>(defined $5)?[$4..$5]:$4)}eo;
346           # Add links to merged bugs
347           $output =~ s{(?<=Merged )([\d\s]+)(?=\.)}{join(' ',map {bug_links(bug=>$_)} (split /\s+/, $1))}eo;
348           # Add links to blocked bugs
349           $output =~ s{(?<=Blocking bugs)(?:( of )(\d+))?( (?:added|set to|removed):\s+)([\d\s\,]+)}
350                       {(defined $2?$1.bug_links(bug=>$2):'').$3.
351                            english_join([map {bug_links(bug=>$_)} (split /\,?\s+/, $4)])}eo;
352           $output =~ s{((?:[Aa]dded|[Rr]emoved)\ blocking\ bug(?:\(s\))?)(?:(\ of\ )(\d+))?(:?\s+)
353                        (\d+(?:,\s+\d+)*(?:\,?\s+and\s+\d+)?)}
354                       {$1.(defined $3?$2.bug_links(bug=>$3):'').$4.
355                            english_join([map {bug_links(bug=>$_)} (split /\,?\s+(?:and\s+)?/, $5)])}xeo;
356           $output =~ s{([Aa]dded|[Rr]emoved)( indication that bug )(\d+)( blocks )([\d\s\,]+)}
357                       {$1.$2.(bug_links(bug=>$3)).$4.
358                            english_join([map {bug_links(bug=>$_)} (split /\,?\s+(?:and\s+)?/, $5)])}eo;
359           # Add links to reassigned packages
360           $output =~ s{(Bug reassigned from package \`)([^']+?)((?:'|\&\#39;) to \`)([^']+?)((?:'|\&\#39;))}
361           {$1.q(<a href=").html_escape(package_links(package=>$2)).qq(">$2</a>).$3.q(<a href=").html_escape(package_links(package=>$4)).qq(">$4</a>).$5}eo;
362           if (defined $time) {
363                $output .= ' ('.strftime('%a, %d %b %Y %T GMT',gmtime($time)).') ';
364           }
365           $output .= '<a href="' .
366                html_escape(bug_links(bug => $bug_number,
367                                      options => {msg => ($msg_number+1)},
368                                      links_only => 1,
369                                     )
370                           ) . '">Full text</a> and <a href="' .
371                                html_escape(bug_links(bug => $bug_number,
372                                                      options => {msg => ($msg_number+1),
373                                                                  mbox => 'yes'},
374                                                      links_only => 1)
375                                           ) . '">rfc822 format</a> available.';
376
377           $output = qq(<div class="$class"><hr>\n<a name="$msg_number"></a>\n) . $output . "</div>\n";
378      }
379      elsif (/recips/) {
380           my ($msg_id) = $record->{text} =~ /^Message-Id:\s+<(.+)>/im;
381           if (defined $msg_id and exists $$seen_msg_ids{$msg_id}) {
382                return ();
383           }
384           elsif (defined $msg_id) {
385                $$seen_msg_ids{$msg_id} = 1;
386           }
387           $output .= qq(<hr><p class="msgreceived"><a name="$msg_number"></a>\n);
388           $output .= 'View this message in <a href="' . html_escape(bug_links(bug=>$bug_number, links_only => 1, options=>{msg=>$msg_number, mbox=>'yes'})) . '">rfc822 format</a></p>';
389           $output .= handle_email_message($record->{text},
390                                           ref     => $bug_number,
391                                           msg_num => $msg_number,
392                                          );
393      }
394      elsif (/autocheck/) {
395           # Do nothing
396      }
397      elsif (/incoming-recv/) {
398           my ($msg_id) = $record->{text} =~ /^Message-Id:\s+<(.+)>/im;
399           if (defined $msg_id and exists $$seen_msg_ids{$msg_id}) {
400                return ();
401           }
402           elsif (defined $msg_id) {
403                $$seen_msg_ids{$msg_id} = 1;
404           }
405           # Incomming Mail Message
406           my ($received,$hostname) = $record->{text} =~ m/Received: \(at (\S+)\) by (\S+)\;/;
407           $output .= qq|<hr><p class="msgreceived"><a name="$msg_number"></a><a name="msg$msg_number"></a><a href="#$msg_number">Message #$msg_number</a> received at |.
408                html_escape("$received\@$hostname") .
409                     q| (<a href="| . html_escape(bug_links(bug => $bug_number, links_only => 1, options => {msg=>$msg_number})) . '">full text</a>'.
410                          q|, <a href="| . html_escape(bug_links(bug => $bug_number,
411                                                                 links_only => 1,
412                                                                 options => {msg=>$msg_number,
413                                                                             mbox=>'yes'}
414                                                                )
415                                                      ) .'">mbox</a>)'.":</p>\n";
416           $output .= handle_email_message($record->{text},
417                                           ref     => $bug_number,
418                                           msg_num => $msg_number,
419                                          );
420      }
421      else {
422           die "Unknown record type $_";
423      }
424      return $output;
425 }
426
427
428
429 1;
430
431
432 __END__
433
434
435
436
437
438