blib/lib/Catalyst/Controller/MIME.pm untested

filter: Statementstmt 0.0% 0 / 199 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 36 MC/DCmcdc 0.0% 0 / 23 Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 368 CC 31 SCAR 29.7
CC
31
Cov
0%
_resolve_path
56.0
_find_best_view_part
42.0
method
30.0
CRAP 19.6
1 package Catalyst::Controller::MIME;
2 use strict;
3 use warnings;
4  
5 our $VERSION = 0.02;
6  
7 use Moose;
8 use namespace::autoclean;
9  
10 BEGIN { extends 'Catalyst::Controller' }
11  
12 use Catalyst::Utils;
13 use HTML::TokeParser::Simple;
14 use HTML::Entities;
15 use Data::Dumper::Concise 'Dumper';
16  
17 # ---
18 # Supply code to obtain the MIME object via either coderef attr or
19 # extending get_mime() method
20 has 'get_mime_coderef', is => 'ro', isa => 'CodeRef', lazy => 1, default => sub {
21 sub { (shift)->get_mime(@_) }
22 };
23 sub get_mime { ... }
24 # ---
25  
26 has 'expose_methods', is => 'ro', isa => 'Bool', default => 0;
27  
28 # Render a MIME Object
29 sub content :Local {
30 my ($self, $c, $id, @path) = @_;
31 my $MIME = $self->_resolve_path($c, $id, @path);
32 return $self->_direct_render($c,$MIME);
33 }
34  
35 # View a MIME Object
36 sub view :Local {
37 my ($self, $c, $id, @path) = @_;
38 my $MIME = $self->_resolve_path($c, $id, @path);
39 return $self->_view_mime($c, $MIME, $id, @path);
40 }
41  
42 # View a MIME Object as RAW Text
43 sub raw_text :Local {
44 my ($self, $c, $id, @path) = @_;
45 my $MIME = $self->_resolve_path($c, $id, @path);
46
47 $c->response->header( 'Content-Type' => 'text/plain' );
48 $c->response->body( $MIME->as_string );
49 return $c->detach;
50 }
51  
52 sub _path_to_content_url {
53 my ($self, $c, @path) = @_;
54 return '/' . join('/',$self->action_namespace($c),'content',@path);
55 }
56  
57 sub _path_to_cid_path {
58 my ($self, $c, @path) = @_;
59 return '/' . join('/',$self->action_namespace($c),'content',@path,'cid');
60 }
61  
62  
63 # DEBUG action: Call a method on the Email::MIME object
64 sub method :Local {
65 my ($self, $c, $method, $id, @path) = @_;
66
67 $c->res->header( 'Content-Type' => 'text/plain' );
68
69 unless( $self->expose_methods ) {
70 $c->res->body('MIME Object Methods Disabled (see "expose_methods")');
71 return $c->detach;
72 }
73
74 my $MIME = $self->_resolve_path($c, $id, @path);
75
76 unless( $MIME->can($method) ) {
77 $c->res->body("No such method '$method'");
78 return $c->detach;
79 }
80
81 my @ret = $MIME->$method;
82 if(scalar @ret > 1) {
83 $c->res->body( Dumper(\@ret) );
84 }
85 else {
86 if(ref $ret[0]) {
87 $c->res->body( Dumper($ret[0]) );
88 }
89 else {
90 $c->res->body( $ret[0] );
91 }
92 }
93
94 return $c->detach;
95 }
96  
97  
98  
99 sub _resolve_path {
100 my ($self, $c, $MIME, $next, @path) = @_;
101
102 # $MIME is either a MIME object or the key/id of a MIME object:
103 unless (blessed $MIME) {
104 $MIME = $self->get_mime_coderef->($self,$c,$MIME)
105 # Idealy the derived class will throw its own exception
106 or Catalyst::Exception->throw("Content '$MIME' not found");
107
108 Catalyst::Exception->throw(
109 "get_mime/get_mime_coderef did not return an Email::MIME object"
110 ) unless (blessed $MIME && $MIME->isa('Email::MIME'));
111 }
112
113 return $MIME unless (defined $next);
114 $next = lc($next);
115
116 my $SubPart;
117
118 # Resolve by part index tree or cid
119 if($next eq 'cid' || $next eq 'content-id') {
120 my $cid = shift @path;
121 $SubPart = $self->_resolve_cid($MIME,$cid);
122 }
123 else {
124 # Assume 'part'
125 $next = shift @path if ($next eq 'part');
126  
127 my $idx = $next;
128 Catalyst::Exception->throw("Bad MIME Part Index '$idx' - must be an integer")
129 unless ($idx =~ /^\d+$/);
130
131 $SubPart = ($MIME->parts)[$idx]
132 or Catalyst::Exception->throw("MIME Part not found at index '$idx'");
133 }
134
135 # Continue recursively:
136 return $self->_resolve_path($c,$SubPart,@path);
137 }
138  
139  
140 sub _resolve_cid {
141 my ($self, $MIME, $cid) = @_;
142
143 my $FoundPart;
144
145 $MIME->walk_parts(sub {
146 my $Part = shift;
147 return if ($FoundPart);
148 $FoundPart = $Part if ( $Part->header('Content-ID') and (
149 $cid eq $Part->header('Content-ID') or
150 '<' . $cid . '>' eq $Part->header('Content-ID')
151 ));
152 });
153
154 Catalyst::Exception->throw('Content-ID ' . $cid . ' not found.')
155 unless ($FoundPart);
156
157 return $FoundPart;
158 }
159  
160 # Renders the MIME part directly, setting its headers/body as the response
161 sub _direct_render {
162 my ($self, $c, $MIME) = @_;
163
164 $self->_set_mime_headers($c,$MIME);
165
166 $c->res->body( $MIME->body );
167 return $c->detach;
168 }
169  
170  
171 sub _render_part {
172 my ($self, $c, $MIME, @path) = @_;
173
174 $self->_set_mime_headers($c,$MIME);
175
176 my $body = $MIME->body;
177 my $cid_path = $self->_path_to_cid_path($c,@path);
178 $self->_convert_cids(\$body,$cid_path)
179 if ($MIME->content_type =~ /^text/);
180
181 $c->res->body( $body );
182 return $c->detach;
183 }
184  
185  
186 sub _set_mime_headers {
187 my ($self, $c, $MIME,$exclude) = @_;
188
189 # TODO: find all the headers that will cause issues like the date/cookie
190 my @exclude_headers = qw(Date);
191 push @exclude_headers, @$exclude if (ref($exclude) eq 'ARRAY');
192 my %excl = map {lc($_)=>1} @exclude_headers;
193 my @header_names = grep { !$excl{lc($_)} } $MIME->header_names;
194 $c->res->header( $_ => $MIME->header($_) ) for (@header_names);
195  
196 }
197  
198 sub _view_part {
199 my ($self, $c, $MIME, @path) = @_;
200
201 my $ViewPart = $self->_find_best_view_part($MIME);
202
203 # Fall back to raw rendering unless the found View Part is text:
204 return $self->_render_part($c, $MIME, @path) unless (
205 $ViewPart->content_type =~ /^text/
206 );
207  
208 #$self->_set_mime_headers($c,$ViewPart,
209 # # must exclude these headers since we're decoding the message ourselves:
210 # # TODO: we probably don't need to be setting any headers
211 # ['Content-Type','Content-Transfer-Encoding']
212 #);
213
214 #my $body = $ViewPart->content_type =~ /^text\/html/ ?
215 # $self->_get_rich_html_body($ViewPart,$cid_path) :
216 # $self->_render_html_with_headers($ViewPart);
217
218 my $body = $self->_get_rich_html_body($c,$MIME,$ViewPart,@path);
219
220 $c->res->body( $body );
221 return $c->detach;
222 }
223  
224 # recurses into a multipart message and finds the best part to
225 # use to display the content
226 sub _find_best_view_part {
227 my ($self, $MIME) = @_;
228 # This only applies to multipart:
229 return $MIME unless ($MIME->content_type =~ /^multipart/);
230
231 my $CurBest;
232 my @parts = $MIME->parts;
233 for my $Part (@parts) {
234 # Recurse if the first part is another multipart
235 return $self->_find_best_view_part($Part) if (
236 ! $CurBest && $Part->content_type =~ /^multipart/
237 );
238
239 # Any text part:
240 $CurBest = $Part if (
241 ! $CurBest &&
242 $Part->content_type =~ /^text/
243 );
244
245 # text/html takes priority over text/plain:
246 $CurBest = $Part if (
247 ! ($CurBest->content_type =~ /^text\/html/) &&
248 $Part->content_type =~ /^text\/html/
249 );
250 }
251 return $CurBest ? $CurBest : $MIME;
252 }
253  
254  
255 sub _convert_cids {
256 my ($self, $htmlref, $cid_path) = @_;
257  
258 my $parser = HTML::TokeParser::Simple->new($htmlref);
259
260 my $substitutions = {};
261
262 # currently only doing img and a tags:
263
264 while (my $tag = $parser->get_tag) {
265
266 my $attr;
267 if($tag->is_tag('img')) {
268 $attr = 'src';
269 }
270 elsif($tag->is_tag('a')) {
271 $attr = 'href';
272 }
273 else {
274 next;
275 }
276
277 my $url = $tag->get_attr($attr) or next;
278 my ($prefix,$cid) = split(/\:/,$url,2);
279 next unless (lc($prefix) eq 'cid' && $cid);
280
281 # Replace the CID URL with a url back to this controller:
282 my $find = $tag->as_is;
283 $tag->set_attr($attr,"$cid_path/$cid");
284 $substitutions->{$find} = $tag->as_is;
285 }
286
287 foreach my $find (keys %$substitutions) {
288 my $replace = $substitutions->{$find};
289 $$htmlref =~ s/\Q$find\E/$replace/gm;
290 }
291 }
292  
293  
294  
295 ###### TODO: This needs to be moved into a View ######
296 sub _view_mime {
297 my ($self, $c, $MIME, @path) = @_;
298
299 return $self->_view_image($c, $MIME, @path)
300 if ( $MIME->content_type =~ /^image/ );
301
302
303 # Old view:
304
305 return $self->_view_part($c, $MIME, @path);
306 }
307  
308  
309 sub _view_image {
310 my ($self, $c, $MIME, @path) = @_;
311 my $src = $self->_path_to_content_url($c,@path);
312
313 return $self->_render_html_with_headers($c,$MIME,
314 "\n\n" . '<img src="' . $src . '">' . "\n\n"
315 );
316 }
317  
318  
319 sub _render_html_with_headers {
320 my ($self, $c, $MIME, $body) = @_;
321
322 my @inc_headers = qw(From Date To Subject);
323 @inc_headers = $MIME->header_names;
324
325 my $p = '<p style="margin-top:3px;margin-bottom:3px;">';
326 my $html = '<div style="font-size:90%;">';
327
328 $html .= $p . '<b>' . $_ . ':&nbsp;</b>' .
329 encode_entities(join(',',$MIME->header($_))) . '</p>' . "\n" for (@inc_headers);
330
331 $html .= '</div>';
332 $html .= '<hr><div style="padding-top:15px;"></div>';
333
334 $html .= $body;
335
336 $c->res->body( $html );
337 return $c->detach;
338 }
339  
340  
341 sub _get_rich_html_body {
342 my ($self, $c, $MIME, $ViewPart, @path) = @_;
343
344 my $body_str = $ViewPart->body_str;
345 if ($ViewPart->content_type =~ /^text\/html/) {
346 my $cid_path = $self->_path_to_cid_path($c,@path);
347 $self->_convert_cids(\$body_str,$cid_path);
348 }
349 else {
350 # Plain text:
351 $body_str = "\n\n" . '<pre style="white-space: pre-wrap; word-wrap: break-word;">' .
352 $body_str .
353 '</pre>' . "\n\n";
354 }
355
356 # E-Mail headers:
357 my @inc_headers = qw(From Date To Subject);
358
359 my @exist_headers = $MIME->header_names;
360 my %exist_hd = map {$_=>1} @exist_headers;
361 @inc_headers = grep { $exist_hd{$_} } @inc_headers;
362
363 # Unless there is more than 1 existing header from our list,
364 # just use all the headers:
365 @inc_headers = @exist_headers unless (scalar(@inc_headers) > 1);
366
367 my $p = '<p style="margin-top:3px;margin-bottom:3px;">';
368 my $html = '<div style="font-size:90%;">';
369
370 $html .= $p . '<b>' . $_ . ':&nbsp;</b>' .
371 encode_entities(join(',',$MIME->header($_))) . '</p>' . "\n" for (@inc_headers);
372
373 my @links = $self->_get_attachments_links($c,$MIME,@path);
374 $html .= $p .
375 '<b><i><span style="color:darkgreen;">Attachments:&nbsp;</span></i></b>' .
376 join(',&nbsp',@links) . '</p>' . "\n" if (scalar(@links) > 0);
377
378 $html .= '</div>' . "\n";
379 $html .= '<hr><div style="padding-top:15px;"></div>' . "\n\n";
380
381 return $html . $body_str;
382 }
383  
384  
385 # Gets a list of links (<a> tags) pointing to subparts (of multipart/mixed
386 # MIME objects) with a "name" or "filename" property within the content_type
387 # This I *think* is what E-Mail clients do when they add attachments
388 sub _get_attachments_links {
389 my ($self, $c, $MIME, @path) = @_;
390
391 # Displayed attachments in E-Mails are parts in multipart/mixed:
392 return () unless ($MIME->content_type =~ /multipart\/mixed/);
393
394 my @links = ();
395 my $count = 0;
396 foreach my $Part ($MIME->parts) {
397 my $idx = $count++;
398 my @sections = split(/\s*\;\s*/,$Part->content_type);
399 my %prop = ();
400 foreach my $sect (@sections) {
401 my ($k,$v) = split(/\s*\=\s*/,$sect,2);
402 next unless ($v);
403 $v =~ s/^\"//;
404 $v =~ s/\"$//;
405 $prop{lc($k)} = $v;
406 }
407
408 my $filename = ($prop{name} || $prop{filename}) or next;
409 push @links, '<a target="_blank" href="' .
410 $self->_path_to_content_url($c,@path,$idx) . '">' .
411 encode_entities($filename) . '</a>';
412 }
413  
414 return @links;
415 }
416  
417 1;
418  
419 __END__