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