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