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