Head.pm

filter: Statementstmt 89.5% 129 / 144 Branchbran 80.0% 32 / 40 Conditioncond 75.0% 21 / 28 MC/DCmcdc 53.3% 8 / 15 Subroutinesub 82.3% 28 / 34 Podpod 71.4% 15 / 21 totaltotal 82.6% 233 / 282 CC 36 SCAR 13.5
CC
36
Cov
86%
ambiguous_content
8.0
mime_type
6.8
decode
6.2
CRAP 3.9
« Tools.pm ↑ Summary Decoder/QuotedPrint.pm »
1 package MIME::Head;
2  
3 36 ▶use MIME::WordDecoder;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 =head1 NAME
5  
6 MIME::Head - MIME message header (a subclass of Mail::Header)
7  
8  
9 =head1 SYNOPSIS
10  
11 Before reading further, you should see L<MIME::Tools> to make sure that
12 you understand where this module fits into the grand scheme of things.
13 Go on, do it now. I'll wait.
14  
15 Ready? Ok...
16  
17 =head2 Construction
18  
19 ### Create a new, empty header, and populate it manually:
20 $head = MIME::Head->new;
21 $head->replace('content-type', 'text/plain; charset=US-ASCII');
22 $head->replace('content-length', $len);
23  
24 ### Parse a new header from a filehandle:
25 $head = MIME::Head->read(\*STDIN);
26  
27 ### Parse a new header from a file, or a readable pipe:
28 $testhead = MIME::Head->from_file("/tmp/test.hdr");
29 $a_b_head = MIME::Head->from_file("cat a.hdr b.hdr |");
30  
31  
32 =head2 Output
33  
34 ### Output to filehandle:
35 $head->print(\*STDOUT);
36  
37 ### Output as string:
38 print STDOUT $head->as_string;
39 print STDOUT $head->stringify;
40  
41  
42 =head2 Getting field contents
43  
44 ### Is this a reply?
45 $is_reply = 1 if ($head->get('Subject') =~ /^Re: /);
46  
47 ### Get receipt information:
48 print "Last received from: ", $head->get('Received', 0);
49 @all_received = $head->get('Received');
50  
51 ### Print the subject, or the empty string if none:
52 print "Subject: ", $head->get('Subject',0);
53  
54 ### Too many hops? Count 'em and see!
55 if ($head->count('Received') > 5) { ...
56  
57 ### Test whether a given field exists
58 warn "missing subject!" if (! $head->count('subject'));
59  
60  
61 =head2 Setting field contents
62  
63 ### Declare this to be an HTML header:
64 $head->replace('Content-type', 'text/html');
65  
66  
67 =head2 Manipulating field contents
68  
69 ### Get rid of internal newlines in fields:
70 $head->unfold;
71  
72 ### Decode any Q- or B-encoded-text in fields (DEPRECATED):
73 $head->decode;
74  
75  
76 =head2 Getting high-level MIME information
77  
78 ### Get/set a given MIME attribute:
79 unless ($charset = $head->mime_attr('content-type.charset')) {
80 $head->mime_attr("content-type.charset" => "US-ASCII");
81 }
82  
83 ### The content type (e.g., "text/html"):
84 $mime_type = $head->mime_type;
85  
86 ### The content transfer encoding (e.g., "quoted-printable"):
87 $mime_encoding = $head->mime_encoding;
88  
89 ### The recommended name when extracted:
90 $file_name = $head->recommended_filename;
91  
92 ### The boundary text, for multipart messages:
93 $boundary = $head->multipart_boundary;
94  
95  
96 =head1 DESCRIPTION
97  
98 A class for parsing in and manipulating RFC-822 message headers, with
99 some methods geared towards standard (and not so standard) MIME fields
100 as specified in the various I<Multipurpose Internet Mail Extensions>
101 RFCs (starting with RFC 2045)
102  
103  
104 =head1 PUBLIC INTERFACE
105  
106 =cut
107  
108 #------------------------------
109  
110 36 require 5.002;
111  
112 ### Pragmas:
113 36 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
114 36 ▶use vars qw($VERSION @ISA @EXPORT_OK);
Subroutine BEGIN: called CC=1 SCAR=0.0
115  
116 ### System modules:
117 36 ▶use IO::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
118  
119 ### Other modules:
120 36 ▶use Mail::Header 1.09 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
121 36 ▶use Mail::Field 1.05 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
122  
123 ### Kit modules:
124 36 ▶use MIME::Words qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
125 36 ▶use MIME::Tools qw(:config :msgs);
Subroutine BEGIN: called CC=1 SCAR=0.0
126 36 ▶use MIME::Field::ParamVal;
Subroutine BEGIN: called CC=1 SCAR=0.0
127 36 ▶use MIME::Field::ConTraEnc;
Subroutine BEGIN: called CC=1 SCAR=0.0
128 36 ▶use MIME::Field::ContDisp;
Subroutine BEGIN: called CC=1 SCAR=0.0
129 36 ▶use MIME::Field::ContType;
Subroutine BEGIN: called CC=1 SCAR=0.0
130  
131 36 @ISA = qw(Mail::Header);
132  
133 # The presence of more than one of the following headers
134 # in a given MIME entity could indicate an ambiguous parse
135 # and hence a security risk
136  
137 36 my $singleton_headers =
138 [
139 'content-type',
140 'content-disposition',
141 'content-transfer-encoding',
142 'content-id',
143 ];
144  
145 # The presence of a duplicated or empty parameters in one of the following
146 # headers in a given MIME entity could indicate an ambiguous parse and
147 # hence a security risk
148 36 my $singleton_parameter_headers =
149 [
150 'content-type',
151 'content-disposition',
152 ];
153  
154  
155 #------------------------------
156 #
157 # Public globals...
158 #
159 #------------------------------
160  
161 ### The package version, both in 1.23 style *and* usable by MakeMaker:
162 36 $VERSION = "5.522";
163  
164 ### Sanity (we put this test after our own version, for CPAN::):
165 36 ▶use Mail::Header 1.06 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
166  
167  
168 #------------------------------
169  
170 =head2 Creation, input, and output
171  
172 =over 4
173  
174 =cut
175  
176 #------------------------------
177  
178  
179 #------------------------------
180  
181 =item new [ARG],[OPTIONS]
182  
183 I<Class method, inherited.>
184 Creates a new header object. Arguments are the same as those in the
185 superclass.
186  
187 =cut
188  
189 8088 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
190 8088 my $class = shift;
191 8088 bless Mail::Header->new(@_), $class;
192 }
193  
194 =item ambiguous_content
195  
196 I<Instance method.>
197  
198 Returns true if this header has any the following properties:
199  
200 =over 4
201  
202 More than one Content-Type, Content-ID, Content-Transfer-Encoding or
203 Content-Disposition header.
204  
205 A Content-Type or Content-Disposition header contains a repeated
206 parameter, or a parameter list that cannot be parsed unambiguously
207 (see C<@unparsed_parameters> under mime_attr).
208  
209 A Content-Type header contains a boundary that is ambiguous.
210  
211 =back
212  
213 Messages with ambiguous content should be treated as a security risk.
214 In particular, if MIME-tools is used in an email security tool,
215 ambiguous messages should not be delivered to end-users.
216  
217 =cut
218 4021 ▶sub ambiguous_content {
Subroutine ambiguous_content: called CC=8 SCAR=20.8
Pod documented
219 4021 my ($self) = @_;
220  
221 4021 foreach my $hdr (@$singleton_headers) {
222 16070 ▶ if ($self->count($hdr) > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->count($hdr) > 1) 9 16061 16070
223 9 return 1;
224 }
225 }
226  
227 4012 foreach my $hdr (@$singleton_parameter_headers) {
228 7991 ▶ if ($self->mime_attr($hdr . '.@duplicate_parameters')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->mime_attr($hdr . '.@duplicate_parameters')) 14 7977 7991
229 14 return 1;
230 }
231 7977 ▶ if ($self->mime_attr($hdr . '.@empty_parameters')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->mime_attr($hdr . '.@empty_parameters')) 5 7972 7977
232 5 return 1;
233 }
234 7972 ▶ if ($self->mime_attr($hdr . '.@unparsed_parameters')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->mime_attr($hdr . '.@unparsed_parameters')) 19 7953 7972
235 19 return 1;
236 }
237 }
238  
239 3974 ▶ if ($self->mime_attr('content-type.@boundary_ambiguous')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->mime_attr("content-type.\@boundary_ambiguous")) 11 3963 3974
240 11 return 1;
241 }
242  
243 3963 return 0;
244 }
245 #------------------------------
246  
247 =item from_file EXPR,OPTIONS
248  
249 I<Class or instance method>.
250 For convenience, you can use this to parse a header object in from EXPR,
251 which may actually be any expression that can be sent to open() so as to
252 return a readable filehandle. The "file" will be opened, read, and then
253 closed:
254  
255 ### Create a new header by parsing in a file:
256 my $head = MIME::Head->from_file("/tmp/test.hdr");
257  
258 Since this method can function as either a class constructor I<or>
259 an instance initializer, the above is exactly equivalent to:
260  
261 ### Create a new header by parsing in a file:
262 my $head = MIME::Head->new->from_file("/tmp/test.hdr");
263  
264 On success, the object will be returned; on failure, the undefined value.
265  
266 The OPTIONS are the same as in new(), and are passed into new()
267 if this is invoked as a class method.
268  
269 B<Note:> This is really just a convenience front-end onto C<read()>,
270 provided mostly for backwards-compatibility with MIME-parser 1.0.
271  
272 =cut
273  
274 6 ▶sub from_file {
Subroutine from_file: called CC=5 SCAR=16.2
Pod documented
275 6 my ($self, $file, @opts) = @_; ### at this point, $self is inst. or class!
276 6 ▶ my $class = ref($self) ? ref($self) : $self;
Branch: 1 branch
BranchTrueFalseTotal
ref $self ? : 2 4 6
277  
278 ### Parse:
279 6 ▶ my $fh = IO::File->new($file, '<') or return error("open $file: $!");
Branch: 1 branch
BranchTrueFalseTotal
my $fh = "IO::File"->new($file, "<") or return error("open ${file}: $!") 5 1 6
280 5 ▶ $fh->binmode() or return error("binmode $file: $!"); # we expect to have \r\n at line ends, and want to keep 'em.
Branch: 1 branch
BranchTrueFalseTotal
$fh->binmode or return error("binmode ${file}: $!") 5 0 5
281 5 $self = $class->new($fh, @opts); ### now, $self is instance or undef
282 5 ▶ $fh->close or return error("close $file: $!");
Branch: 1 branch
BranchTrueFalseTotal
$fh->close or return error("close ${file}: $!") 5 0 5
283 5 $self;
284 }
285  
286 #------------------------------
287  
288 =item read FILEHANDLE
289  
290 I<Instance (or class) method.>
291 This initializes a header object by reading it in from a FILEHANDLE,
292 until the terminating blank line is encountered.
293 A syntax error or end-of-stream will also halt processing.
294  
295 Supply this routine with a reference to a filehandle glob; e.g., C<\*STDIN>:
296  
297 ### Create a new header by parsing in STDIN:
298 $head->read(\*STDIN);
299  
300 On success, the self object will be returned; on failure, a false value.
301  
302 B<Note:> in the MIME world, it is perfectly legal for a header to be
303 empty, consisting of nothing but the terminating blank line. Thus,
304 we can't just use the formula that "no tags equals error".
305  
306 B<Warning:> as of the time of this writing, Mail::Header::read did not flag
307 either syntax errors or unexpected end-of-file conditions (an EOF
308 before the terminating blank line). MIME::ParserBase takes this
309 into account.
310  
311 =cut
312  
313 3973 ▶sub read {
Subroutine read: called CC=2 SCAR=7.1
Pod documented
314 3973 my $self = shift; ### either instance or class!
315 3973 ▶ ref($self) or $self = $self->new; ### if used as class method, make new
Branch: 1 branch
BranchTrueFalseTotal
ref $self or $self = $self->new 3973 0 3973
316 3973 $self->SUPER::read(@_);
317 }
318  
319  
320  
321 #------------------------------
322  
323 =back
324  
325 =head2 Getting/setting fields
326  
327 The following are methods related to retrieving and modifying the header
328 fields. Some are inherited from Mail::Header, but I've kept the
329 documentation around for convenience.
330  
331 =over 4
332  
333 =cut
334  
335 #------------------------------
336  
337  
338 #------------------------------
339  
340 =item add TAG,TEXT,[INDEX]
341  
342 I<Instance method, inherited.>
343 Add a new occurrence of the field named TAG, given by TEXT:
344  
345 ### Add the trace information:
346 $head->add('Received',
347 'from eryq.pr.mcs.net by gonzo.net with smtp');
348  
349 Normally, the new occurrence will be I<appended> to the existing
350 occurrences. However, if the optional INDEX argument is 0, then the
351 new occurrence will be I<prepended>. If you want to be I<explicit>
352 about appending, specify an INDEX of -1.
353  
354 B<Warning>: this method always adds new occurrences; it doesn't overwrite
355 any existing occurrences... so if you just want to I<change> the value
356 of a field (creating it if necessary), then you probably B<don't> want to use
357 this method: consider using C<replace()> instead.
358  
359 =cut
360  
361 ### Inherited.
362  
363 #------------------------------
364 #
365 # copy
366 #
367 # Instance method, DEPRECATED.
368 # Duplicate the object.
369 #
370 0 ▶sub copy {
Subroutine copy: not called CC=1 SCAR=6.9
Pod undocumented
371 0 usage "deprecated: use dup() instead.";
372 0 shift->dup(@_);
373 }
374  
375 #------------------------------
376  
377 =item count TAG
378  
379 I<Instance method, inherited.>
380 Returns the number of occurrences of a field; in a boolean context, this
381 tells you whether a given field exists:
382  
383 ### Was a "Subject:" field given?
384 $subject_was_given = $head->count('subject');
385  
386 The TAG is treated in a case-insensitive manner.
387 This method returns some false value if the field doesn't exist,
388 and some true value if it does.
389  
390 =cut
391  
392 ### Inherited.
393  
394  
395 #------------------------------
396  
397 =item decode [FORCE]
398  
399 I<Instance method, DEPRECATED.>
400 Go through all the header fields, looking for RFC 1522 / RFC 2047 style
401 "Q" (quoted-printable, sort of) or "B" (base64) encoding, and decode
402 them in-place. Fellow Americans, you probably don't know what the hell
403 I'm talking about. Europeans, Russians, et al, you probably do.
404 C<:-)>.
405  
406 B<This method has been deprecated.>
407 See L<MIME::Parser/decode_headers> for the full reasons.
408 If you absolutely must use it and don't like the warning, then
409 provide a FORCE:
410  
411 "I_NEED_TO_FIX_THIS"
412 Just shut up and do it. Not recommended.
413 Provided only for those who need to keep old scripts functioning.
414  
415 "I_KNOW_WHAT_I_AM_DOING"
416 Just shut up and do it. Not recommended.
417 Provided for those who REALLY know what they are doing.
418  
419 B<What this method does.>
420 For an example, let's consider a valid email header you might get:
421  
422 From: =?US-ASCII?Q?Keith_Moore?= <moore@cs.utk.edu>
423 To: =?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>
424 CC: =?ISO-8859-1?Q?Andr=E9_?= Pirard <PIRARD@vm1.ulg.ac.be>
425 Subject: =?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=
426 =?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=
427 =?US-ASCII?Q?.._cool!?=
428  
429 That basically decodes to (sorry, I can only approximate the
430 Latin characters with 7 bit sequences /o and 'e):
431  
432 From: Keith Moore <moore@cs.utk.edu>
433 To: Keld J/orn Simonsen <keld@dkuug.dk>
434 CC: Andr'e Pirard <PIRARD@vm1.ulg.ac.be>
435 Subject: If you can read this you understand the example... cool!
436  
437 B<Note:> currently, the decodings are done without regard to the
438 character set: thus, the Q-encoding C<=F8> is simply translated to the
439 octet (hexadecimal C<F8>), period. For piece-by-piece decoding
440 of a given field, you want the array context of
441 C<MIME::Words::decode_mimewords()>.
442  
443 B<Warning:> the CRLF+SPACE separator that splits up long encoded words
444 into shorter sequences (see the Subject: example above) gets lost
445 when the field is unfolded, and so decoding after unfolding causes
446 a spurious space to be left in the field.
447 I<THEREFORE: if you're going to decode, do so BEFORE unfolding!>
448  
449 This method returns the self object.
450  
451 I<Thanks to Kent Boortz for providing the idea, and the baseline
452 RFC-1522-decoding code.>
453  
454 =cut
455  
456 2 ▶sub decode {
Subroutine decode: called CC=6 SCAR=18.3
Pod documented
457 2 my $self = shift;
458  
459 ### Warn if necessary:
460 2 ▶ my $force = shift || 0;
Condition50%1/2
shift() || 0
l!l
02
MC/DC0%0/1
shift() || 0
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
461 2 ▶ unless (($force eq "I_NEED_TO_FIX_THIS") ||
Branch: 1 branch
BranchTrueFalseTotal
unless ($force eq "I_NEED_TO_FIX_THIS" or $force eq "I_KNOW_WHAT_I_AM_DOING") 2 0 2
Condition33%1/3
$force eq "I_NEED_TO_FIX_THIS" or $force eq "I_KNOW_WHAT_I_AM_DOING"
l!l&&r!l&&!r
002
MC/DC0%0/2
$force eq "I_NEED_TO_FIX_THIS" or $force eq "I_KNOW_WHAT_I_AM_DOING"
$force eq "I_NEED_TO_FIX_THIS" $force eq "I_KNOW_WHAT_I_AM_DOING"
Truth table33%1/3
A or B
A= $force eq "I_NEED_TO_FIX_THIS"B= $force eq "I_KNOW_WHAT_I_AM_DOING"
ABresult
1X1
011
000
462 ($force eq "I_KNOW_WHAT_I_AM_DOING")) {
463 2 usage "decode is deprecated for safety";
464 }
465  
466 2 my ($tag, $i, @decoded);
467 2 foreach $tag ($self->tags) {
468 20 @decoded = map { scalar(decode_mimewords($_, Field=>$tag))
469 } $self->get_all($tag);
470 20 ▶ for ($i = 0; $i < @decoded; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @decoded) 20 20 40
471 20 $self->replace($tag, $decoded[$i], $i);
472 }
473 }
474 2 $self->{MH_Decoded} = 1;
475 2 $self;
476 }
477  
478 #------------------------------
479  
480 =item delete TAG,[INDEX]
481  
482 I<Instance method, inherited.>
483 Delete all occurrences of the field named TAG.
484  
485 ### Remove some MIME information:
486 $head->delete('MIME-Version');
487 $head->delete('Content-type');
488  
489 =cut
490  
491 ### Inherited
492  
493  
494 #------------------------------
495 #
496 # exists
497 #
498 0 ▶sub exists {
Subroutine exists: not called CC=1 SCAR=6.9
Pod undocumented
499 0 usage "deprecated; use count() instead";
500 0 shift->count(@_);
501 }
502  
503 #------------------------------
504 #
505 # fields
506 #
507 0 ▶sub fields {
Subroutine fields: not called CC=1 SCAR=6.9
Pod documented
508 0 usage "deprecated: use tags() instead",
509 shift->tags(@_);
510 }
511  
512 #------------------------------
513  
514 =item get TAG,[INDEX]
515  
516 I<Instance method, inherited.>
517 Get the contents of field TAG.
518  
519 If a B<numeric INDEX> is given, returns the occurrence at that index,
520 or undef if not present:
521  
522 ### Print the first and last 'Received:' entries (explicitly):
523 print "First, or most recent: ", $head->get('received', 0);
524 print "Last, or least recent: ", $head->get('received',-1);
525  
526 If B<no INDEX> is given, but invoked in a B<scalar> context, then
527 INDEX simply defaults to 0:
528  
529 ### Get the first 'Received:' entry (implicitly):
530 my $most_recent = $head->get('received');
531  
532 If B<no INDEX> is given, and invoked in an B<array> context, then
533 I<all> occurrences of the field are returned:
534  
535 ### Get all 'Received:' entries:
536 my @all_received = $head->get('received');
537  
538 B<NOTE>: The header(s) returned may end with a newline. If you don't
539 want this, then B<chomp> the return value.
540  
541 =cut
542  
543 ### Inherited.
544  
545  
546 #------------------------------
547  
548 =item get_all FIELD
549  
550 I<Instance method.>
551 Returns the list of I<all> occurrences of the field, or the
552 empty list if the field is not present:
553  
554 ### How did it get here?
555 @history = $head->get_all('Received');
556  
557 B<Note:> I had originally experimented with having C<get()> return all
558 occurrences when invoked in an array context... but that causes a lot of
559 accidents when you get careless and do stuff like this:
560  
561 print "\u$field: ", $head->get($field);
562  
563 It also made the intuitive behaviour unclear if the INDEX argument
564 was given in an array context. So I opted for an explicit approach
565 to asking for all occurrences.
566  
567 =cut
568  
569 21 ▶sub get_all {
Subroutine get_all: called CC=2 SCAR=7.1
Pod documented
570 21 my ($self, $tag) = @_;
571 21 ▶ $self->count($tag) or return (); ### empty if doesn't exist
Branch: 1 branch
BranchTrueFalseTotal
$self->count($tag) or return () 21 0 21
572 21 ($self->get($tag));
573 }
574  
575 #------------------------------
576 #
577 # original_text
578 #
579 # Instance method, DEPRECATED.
580 # Return an approximation of the original text.
581 #
582 0 ▶sub original_text {
Subroutine original_text: not called CC=1 SCAR=6.9
Pod undocumented
583 0 usage "deprecated: use stringify() instead";
584 0 shift->stringify(@_);
585 }
586  
587 #------------------------------
588  
589 =item print [OUTSTREAM]
590  
591 I<Instance method, override.>
592 Print the header out to the given OUTSTREAM, or the currently-selected
593 filehandle if none. The OUTSTREAM may be a filehandle, or any object
594 that responds to a print() message.
595  
596 The override actually lets you print to any object that responds to
597 a print() method. This is vital for outputting MIME entities to scalars.
598  
599 Also, it defaults to the I<currently-selected> filehandle if none is given
600 (not STDOUT!), so I<please> supply a filehandle to prevent confusion.
601  
602 =cut
603  
604 81 ▶sub print {
Subroutine print: called CC=2 SCAR=7.6
Pod documented
605 81 my ($self, $fh) = @_;
606 81 ▶ $fh ||= select;
Condition33%1/3
$fh ||= select
l!l&&r!l&&!r
8100
MC/DC0%0/2
$fh ||= select
$fh select
Truth table33%1/3
A ||= B
A= $fhB= select
ABresult
1X1
011
000
607 81 $fh->print($self->as_string);
608 }
609  
610 #------------------------------
611 #
612 # set TAG,TEXT
613 #
614 # Instance method, DEPRECATED.
615 # Set the field named TAG to [the single occurrence given by the TEXT.
616 #
617 0 ▶sub set {
Subroutine set: not called CC=1 SCAR=6.9
Pod undocumented
618 0 my $self = shift;
619 0 usage "deprecated: use the replace() method instead.";
620 0 $self->replace(@_);
621 }
622  
623 #------------------------------
624  
625 =item stringify
626  
627 I<Instance method.>
628 Return the header as a string. You can also invoke it as C<as_string>.
629  
630 If you set the variable $MIME::Entity::BOUNDARY_DELIMITER to a string,
631 that string will be used as line-end delimiter. If it is not set,
632 the line ending will be a newline character (\n)
633  
634 =cut
635  
636 84 ▶sub stringify {
Subroutine stringify: called CC=4 SCAR=14.0
Pod documented
637 84 my $self = shift; ### build clean header, and output...
638 84 ▶ my @header = grep {defined($_) ? $_ : ()} @{$self->header};
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 424 0 424
639 84 ▶ my $header_delimiter = $MIME::Entity::BOUNDARY_DELIMITER || "\n";
Condition100%2/2
$MIME::Entity::BOUNDARY_DELIMITER || "\n"
l!l
777
MC/DC100%1/1
$MIME::Entity::BOUNDARY_DELIMITER || "\n"
$MIME::Entity::BOUNDARY_DELIMITER
Truth table100%2/2
A
A= $MIME::Entity::BOUNDARY_DELIMITER
Aresult
11
00
640 84 ▶ join "", map { /\n$/ ? substr($_, 0, -1) . $header_delimiter : $_ . $header_delimiter } @header;
Branch: 1 branch
BranchTrueFalseTotal
/\n$/ ? : 424 0 424
641 }
642 81 ▶sub as_string { shift->stringify(@_) }
Subroutine as_string: called CC=1 SCAR=0.0
Pod documented
643  
644 #------------------------------
645  
646 =item unfold [FIELD]
647  
648 I<Instance method, inherited.>
649 Unfold (remove newlines in) the text of all occurrences of the given FIELD.
650 If the FIELD is omitted, I<all> fields are unfolded.
651 Returns the "self" object.
652  
653 =cut
654  
655 ### Inherited
656  
657  
658 #------------------------------
659  
660 =back
661  
662 =head2 MIME-specific methods
663  
664 All of the following methods extract information from the following fields:
665  
666 Content-type
667 Content-transfer-encoding
668 Content-disposition
669  
670 Be aware that they do not just return the raw contents of those fields,
671 and in some cases they will fill in sensible (I hope) default values.
672 Use C<get()> or C<mime_attr()> if you need to grab and process the
673 raw field text.
674  
675 B<Note:> some of these methods are provided both as a convenience and
676 for backwards-compatibility only, while others (like
677 recommended_filename()) I<really do have to be in MIME::Head to work
678 properly,> since they look for their value in more than one field.
679 However, if you know that a value is restricted to a single
680 field, you should really use the Mail::Field interface to get it.
681  
682 =over 4
683  
684 =cut
685  
686 #------------------------------
687  
688  
689 #------------------------------
690 #
691 # params TAG
692 #
693 # Instance method, DEPRECATED.
694 # Extract parameter info from a structured field, and return
695 # it as a hash reference. Provided for 1.0 compatibility only!
696 # Use the new MIME::Field interface classes (subclasses of Mail::Field).
697  
698 1 ▶sub params {
Subroutine params: called CC=1 SCAR=0.0
Pod undocumented
699 1 my ($self, $tag) = @_;
700 1 usage "deprecated: use the MIME::Field interface classes from now on!";
701 1 return MIME::Field::ParamVal->parse_params($self->get($tag,0));
702 }
703  
704 #------------------------------
705  
706 =item mime_attr ATTR,[VALUE]
707  
708 A quick-and-easy interface to set/get the attributes in structured
709 MIME fields:
710  
711 $head->mime_attr("content-type" => "text/html");
712 $head->mime_attr("content-type.charset" => "US-ASCII");
713 $head->mime_attr("content-type.name" => "homepage.html");
714  
715 This would cause the final output to look something like this:
716  
717 Content-type: text/html; charset=US-ASCII; name="homepage.html"
718  
719 Note that the special empty sub-field tag indicates the anonymous
720 first sub-field.
721  
722 B<Giving VALUE as undefined> will cause the contents of the named subfield
723 to be deleted:
724  
725 $head->mime_attr("content-type.charset" => undef);
726  
727 B<Supplying no VALUE argument> just returns the attribute's value,
728 or undefined if it isn't there:
729  
730 $type = $head->mime_attr("content-type"); ### text/html
731 $name = $head->mime_attr("content-type.name"); ### homepage.html
732  
733 In all cases, the new/current value is returned.
734  
735 The special sub-field tag C<@duplicate_parameters> (which can never be
736 a real tag) returns an arrayref of tags that were duplicated in the header,
737 or C<undef> if no such tags were found. For example, given the header:
738  
739 Content-Type: multipart/mixed; boundary="foo"; boundary="bar"
740  
741 Then:
742  
743 $head->mime_attr('content-type.@duplicate_parameters')
744  
745 would return:
746  
747 [ 'boundary' ]
748  
749 Similarly he special sub-field tag C<@empty_parameters> (which can
750 never be a real tag) returns an arrayref of tags that had an empty
751 parameter value in the header, or C<undef> if no such tags were
752 found. (This does not include C<name> or C<filename> paramaneters,
753 which I<are> allowed to be empty without triggering an ambiguous parse
754 signal.) For example, given the header:
755  
756 Content-Type: multipart/mixed; boundary=;
757  
758 Then:
759  
760 $head->mime_attr('content-type.@emtpy_parameters')
761  
762 would return:
763  
764 [ 'boundary' ]
765  
766 The special sub-field tag C<@unparsed_parameters> is true if parsing
767 stopped at a parameter it could not read and the rest of the field
768 contains "=", as in:
769  
770 Content-Type: multipart/mixed; x:y=1; boundary="foo"
771  
772 Any parameters after that point are lost. It is also true if text
773 skipped between parameters holds an odd number of '"' or a comment
774 still open at a ";", or a quoted value ends in a backslash, any of
775 which makes other parsers split the field at different semicolons.
776  
777 A duplicate or empty "boundary" tag should be treated as a security risk, as
778 should duplicate Content-Type headers in a message. Since such messages
779 cannot be parsed unambiguously, we strongly recommend that they never be
780 delivered to end-users.
781  
782 Note also that a parameter explicitly set to blank via something like:
783  
784 Content-Type: application/octet-stream; boundary=""
785  
786 I<will> populate C<@empty_parameters>
787  
788 =cut
789  
790 43109 ▶sub mime_attr {
Subroutine mime_attr: called CC=3 SCAR=11.0
Pod documented
791 43109 my ($self, $attr, $value) = @_;
792  
793 ### Break attribute name up:
794 43109 my ($tag, $subtag) = split /\./, $attr;
795 43109 ▶ $subtag ||= '_';
Condition100%2/2
$subtag ||= "_"
l!l
3015112958
MC/DC100%1/1
$subtag ||= "_"
$subtag
Truth table100%2/2
A
A= $subtag
Aresult
11
00
796  
797 ### Set or get?
798 43109 my $field = MIME::Field::ParamVal->parse($self->get($tag, 0));
799 43109 ▶ if (@_ > 2) { ### set it:
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 2) { } 12 43097 43109
800 12 $field->param($subtag, $value); ### set subfield
801 12 $self->replace($tag, $field->stringify); ### replace!
802 12 return $value;
803 }
804 else { ### get it:
805 43097 return $field->param($subtag);
806 }
807 }
808  
809 #------------------------------
810  
811 =item mime_encoding
812  
813 I<Instance method.>
814 Try I<real hard> to determine the content transfer encoding
815 (e.g., C<"base64">, C<"binary">), which is returned in all-lowercase.
816  
817 If no encoding could be found, the default of C<"7bit"> is returned
818 I quote from RFC 2045 section 6.1:
819  
820 This is the default value -- that is, "Content-Transfer-Encoding: 7BIT"
821 is assumed if the Content-Transfer-Encoding header field is not present.
822  
823 I do one other form of fixup: "7_bit", "7-bit", and "7 bit" are
824 corrected to "7bit"; likewise for "8bit".
825  
826 =cut
827  
828 2344 ▶sub mime_encoding {
Subroutine mime_encoding: called CC=2 SCAR=6.9
Pod documented
829 2344 my $self = shift;
830 2344 ▶ my $enc = lc($self->mime_attr('content-transfer-encoding') || '7bit');
Condition100%2/2
$self->mime_attr('content-transfer-encoding') || '7bit'
l!l
1762168
MC/DC100%1/1
$self->mime_attr('content-transfer-encoding') || '7bit'
$self->mime_attr('content-transfer-encoding')
Truth table100%2/2
A
A= $self->mime_attr('content-transfer-encoding')
Aresult
11
00
831 2344 $enc =~ s{^([78])[ _-]bit\Z}{$1bit};
832 2344 $enc;
833 }
834  
835 #------------------------------
836  
837 =item mime_type [DEFAULT]
838  
839 I<Instance method.>
840 Try C<real hard> to determine the content type (e.g., C<"text/plain">,
841 C<"image/gif">, C<"x-weird-type">, which is returned in all-lowercase.
842 "Real hard" means that if no content type could be found, the default
843 (usually C<"text/plain">) is returned. From RFC 2045 section 5.2:
844  
845 Default RFC 822 messages without a MIME Content-Type header are
846 taken by this protocol to be plain text in the US-ASCII character
847 set, which can be explicitly specified as:
848  
849 Content-type: text/plain; charset=us-ascii
850  
851 This default is assumed if no Content-Type header field is specified.
852  
853 Unless this is a part of a "multipart/digest", in which case
854 "message/rfc822" is the default. Note that you can also I<set> the
855 default, but you shouldn't: normally only the MIME parser uses this
856 feature.
857  
858 =cut
859  
860 10579 ▶sub mime_type {
Subroutine mime_type: called CC=6 SCAR=19.1
Pod documented
861 10579 my ($self, $default) = @_;
862 10579 ▶ $self->{MIH_DefaultType} = $default if @_ > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 4 10575 10579
863 my $s = $self->mime_attr('content-type') ||
864 $self->{MIH_DefaultType} ||
865 10579 ▶ 'text/plain';
Condition100%5/5
$self->mime_attr('content-type') || $self->{'MIH_DefaultType'} || 'text/plain'
l!l
10425154
$self->mime_attr("content-type") or $self->{"MIH_DefaultType"}
l!l&&r!l&&!r
104169154
MC/DC100%2/2
$self->mime_attr('content-type') || $self->{'MIH_DefaultType'} || 'text/plain'
$self->mime_attr("content-type") $self->{"MIH_DefaultType"}
Truth table100%3/3
A or B
A= $self->mime_attr("content-type")B= $self->{"MIH_DefaultType"}
ABresult
1X1
011
000
866 # avoid [perl #87336] bug, lc laundering tainted data
867 10579 ▶ return lc($s) if $] <= 5.008 || $] >= 5.014;
Branch: 1 branch
BranchTrueFalseTotal
if $] <= "5.008" or $] >= "5.014" 10579 0 10579
Condition33%1/3
$] <= "5.008" or $] >= "5.014"
l!l&&r!l&&!r
0105790
MC/DC0%0/2
$] <= "5.008" or $] >= "5.014"
$] <= "5.008" $] >= "5.014"
Truth table33%1/3
A or B
A= $] <= "5.008"B= $] >= "5.014"
ABresult
1X1
011
000
868 0 $s =~ tr/A-Z/a-z/;
869 0 $s;
870 }
871  
872 #------------------------------
873  
874 =item multipart_boundary
875  
876 I<Instance method.>
877 If this is a header for a multipart message, return the
878 "encapsulation boundary" used to separate the parts. The boundary
879 is returned exactly as given in the C<Content-type:> field; that
880 is, the leading double-hyphen (C<-->) is I<not> prepended.
881  
882 Well, I<almost> exactly... this passage from RFC 2046 dictates
883 that we remove any trailing spaces:
884  
885 If a boundary appears to end with white space, the white space
886 must be presumed to have been added by a gateway, and must be deleted.
887  
888 Returns undef (B<not> the empty string) if either the message is not
889 multipart or if there is no specified boundary.
890  
891 =cut
892  
893 1842 ▶sub multipart_boundary {
Subroutine multipart_boundary: called CC=2 SCAR=6.9
Pod documented
894 1842 my $self = shift;
895 1842 my $value = $self->mime_attr('content-type.boundary');
896 1842 ▶ return undef unless defined($value);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 3 1839 1842
897 1839 $value = decode_mimewords($value);
898 1839 $value =~ s/\s+$//; # kill trailing whitespace, per RFC 2046
899 1839 return $value;
900 }
901  
902 #------------------------------
903  
904 =item recommended_filename
905  
906 I<Instance method.>
907 Return the recommended external filename. This is used when
908 extracting the data from the MIME stream. The filename is always
909 returned as a string in Perl's internal format (the UTF8 flag may be on!)
910  
911 Returns undef if no filename could be suggested.
912  
913 =cut
914  
915 sub recommended_filename
916 197 ▶{
Subroutine recommended_filename: called CC=5 SCAR=16.1
Pod documented
917 197 my $self = shift;
918  
919 # Try these headers in order, taking the first defined,
920 # non-blank one we find.
921 197 my $wd = supported MIME::WordDecoder 'UTF-8';
922 197 foreach my $attr_name ( qw( content-disposition.filename content-type.name ) ) {
923 335 my $value = $self->mime_attr( $attr_name );
924 335 ▶ if ( defined $value
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value and $value ne "" and $value =~ /\S/) 83 252 335
Condition100%6/6
defined $value and $value ne "" and $value =~ /\S/
!ll&&!rl&&r
249383
defined $value and $value ne ""
!ll&&!rl&&r
248186
MC/DC100%3/3
defined $value and $value ne "" and $value =~ /\S/
defined $value $value ne "" $value =~ /\S/
Truth table100%4/4
A and B and C
A= defined $valueB= $value ne ""C= $value =~ /\S/
ABCresult
0XX0
10X0
1100
1111
925 && $value ne ''
926 && $value =~ /\S/ ) {
927 83 return $wd->decode($value);
928 }
929 }
930  
931 114 return undef;
932 }
933  
934 #------------------------------
935  
936 =back
937  
938 =cut
939  
940  
941 #------------------------------
942 #
943 # tweak_FROM_parsing
944 #
945 # DEPRECATED. Use the inherited mail_from() class method now.
946  
947 0 ▶sub tweak_FROM_parsing {
Subroutine tweak_FROM_parsing: not called CC=1 SCAR=6.9
Pod undocumented
948 0 my $self = shift;
949 0 usage "deprecated. Use mail_from() instead.";
950 0 $self->mail_from(@_);
951 }
952  
953  
954 __END__
« Tools.pm ↑ Summary Decoder/QuotedPrint.pm »