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