Words.pm

filter: Statementstmt 96.3% 80 / 83 Branchbran 83.3% 15 / 18 Conditioncond 62.5% 5 / 8 MC/DCmcdc 25.0% 1 / 4 Subroutinesub 92.3% 12 / 13 Podpod 100% 3 / 3 totaltotal 89.9% 116 / 129 CC 14 SCAR 14.3
CC
14
Cov
92%
decode_mimewords
8.0
encode_mimeword
4.3
encode_mimewords
4.0
CRAP 4.2
« Decoder/NBit.pm ↑ Summary Tools.pm »
1 package MIME::Words;
2  
3 =head1 NAME
4  
5 MIME::Words - deal with RFC 2047 encoded words
6  
7  
8 =head1 SYNOPSIS
9  
10 Before reading further, you should see L<MIME::Tools> to make sure that
11 you understand where this module fits into the grand scheme of things.
12 Go on, do it now. I'll wait.
13  
14 Ready? Ok...
15  
16  
17 use MIME::Words qw(:all);
18  
19 ### Decode the string into another string, forgetting the charsets:
20 $decoded = decode_mimewords(
21 'To: =?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>',
22 );
23  
24 ### Split string into array of decoded [DATA,CHARSET] pairs:
25 @decoded = decode_mimewords(
26 'To: =?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>',
27 );
28  
29 ### Encode a single unsafe word:
30 $encoded = encode_mimeword("\xABFran\xE7ois\xBB");
31  
32 ### Encode a string, trying to find the unsafe words inside it:
33 $encoded = encode_mimewords("Me and \xABFran\xE7ois\xBB in town");
34  
35  
36  
37 =head1 DESCRIPTION
38  
39 Fellow Americans, you probably won't know what the hell this module
40 is for. Europeans, Russians, et al, you probably do. C<:-)>.
41  
42 For example, here's a valid MIME header you might get:
43  
44 From: =?US-ASCII?Q?Keith_Moore?= <moore@cs.utk.edu>
45 To: =?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>
46 CC: =?ISO-8859-1?Q?Andr=E9_?= Pirard <PIRARD@vm1.ulg.ac.be>
47 Subject: =?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=
48 =?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=
49 =?US-ASCII?Q?.._cool!?=
50  
51 The fields basically decode to (sorry, I can only approximate the
52 Latin characters with 7 bit sequences /o and 'e):
53  
54 From: Keith Moore <moore@cs.utk.edu>
55 To: Keld J/orn Simonsen <keld@dkuug.dk>
56 CC: Andr'e Pirard <PIRARD@vm1.ulg.ac.be>
57 Subject: If you can read this you understand the example... cool!
58  
59  
60 =head1 PUBLIC INTERFACE
61  
62 =over 4
63  
64 =cut
65  
66 46 require 5.001;
67  
68 ### Pragmas:
69 46 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
70 46 ▶use re 'taint';
Subroutine BEGIN: called CC=1 SCAR=0.0
71 46 ▶use vars qw($VERSION @EXPORT_OK %EXPORT_TAGS @ISA);
Subroutine BEGIN: called CC=1 SCAR=0.0
72  
73 ### Exporting:
74 46 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
75 46 %EXPORT_TAGS = (all => [qw(decode_mimewords
76 encode_mimeword
77 encode_mimewords
78 )]);
79 46 Exporter::export_ok_tags('all');
80  
81 ### Inheritance:
82 46 @ISA = qw(Exporter);
83  
84 ### Other modules:
85 46 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
86 46 ▶use MIME::QuotedPrint;
Subroutine BEGIN: called CC=1 SCAR=0.0
87  
88  
89  
90 #------------------------------
91 #
92 # Globals...
93 #
94 #------------------------------
95  
96 ### The package version, both in 1.23 style *and* usable by MakeMaker:
97 46 $VERSION = "5.522";
98  
99 ### Nonprintables (controls + x7F + 8bit):
100 46 my $NONPRINT = "\\x00-\\x1F\\x7F-\\xFF";
101  
102  
103 #------------------------------
104  
105 # _decode_Q STRING
106 # Private: used by _decode_header() to decode "Q" encoding, which is
107 # almost, but not exactly, quoted-printable. :-P
108 63 ▶sub _decode_Q {
Subroutine _decode_Q: called CC=1 SCAR=0.0
109 63 my $str = shift;
110 63 local $1;
111 63 $str =~ s/_/\x20/g; # RFC-1522, Q rule 2
112 63 $str =~ s/=([\da-fA-F]{2})/pack("C", hex($1))/ge; # RFC-1522, Q rule 1
113 63 $str;
114 }
115  
116 # _encode_Q STRING
117 # Private: used by _encode_header() to decode "Q" encoding, which is
118 # almost, but not exactly, quoted-printable. :-P
119 25 ▶sub _encode_Q {
Subroutine _encode_Q: called CC=1 SCAR=0.0
120 25 my $str = shift;
121 25 local $1;
122 25 $str =~ s{([ _\?\=$NONPRINT])}{sprintf("=%02X", ord($1))}eog;
123 25 $str;
124 }
125  
126 # _decode_B STRING
127 # Private: used by _decode_header() to decode "B" encoding.
128 12 ▶sub _decode_B {
Subroutine _decode_B: called CC=1 SCAR=0.0
129 12 my $str = shift;
130 12 decode_base64($str);
131 }
132  
133 # _encode_B STRING
134 # Private: used by _decode_header() to decode "B" encoding.
135 0 ▶sub _encode_B {
Subroutine _encode_B: not called CC=1 SCAR=6.9
136 0 my $str = shift;
137 0 encode_base64($str, '');
138 }
139  
140  
141  
142 #------------------------------
143  
144 =item decode_mimewords ENCODED
145  
146 I<Function.>
147 Go through the string looking for RFC 2047-style "Q"
148 (quoted-printable, sort of) or "B" (base64) encoding, and decode them.
149  
150 B<In an array context,> splits the ENCODED string into a list of decoded
151 C<[DATA, CHARSET]> pairs, and returns that list. Unencoded
152 data are returned in a 1-element array C<[DATA]>, giving an effective
153 CHARSET of C<undef>.
154  
155 $enc = '=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>';
156 foreach (decode_mimewords($enc)) {
157 print "", ($_->[1] || 'US-ASCII'), ": ", $_->[0], "\n";
158 }
159  
160 B<In a scalar context,> joins the "data" elements of the above
161 list together, and returns that. I<Warning: this is information-lossy,>
162 and probably I<not> what you want, but if you know that all charsets
163 in the ENCODED string are identical, it might be useful to you.
164 (Before you use this, please see L<MIME::WordDecoder/unmime>,
165 which is probably what you want.)
166  
167 In the event of a syntax error, $@ will be set to a description
168 of the error, but parsing will continue as best as possible (so as to
169 get I<something> back when decoding headers).
170 $@ will be false if no error was detected.
171  
172 Any arguments past the ENCODED string are taken to define a hash of options:
173  
174 =cut
175  
176 1983 ▶sub decode_mimewords {
Subroutine decode_mimewords: called CC=8 SCAR=20.8
Pod documented
177 1983 my $encstr = shift;
178 1983 my @tokens;
179 1983 local($1,$2,$3);
180 1983 $@ = ''; ### error-return
181  
182 ### Collapse boundaries between adjacent encoded words:
183 1983 $encstr =~ s{(\?\=)\s*(\=\?)}{$1$2}gs;
184 1983 pos($encstr) = 0;
185 ### print STDOUT "ENC = [", $encstr, "]\n";
186  
187 ### Decode:
188 1983 my ($charset, $encoding, $enc, $dec);
189 1983 while (1) {
190 6038 ▶ last if (pos($encstr) >= length($encstr));
Branch: 1 branch
BranchTrueFalseTotal
if pos $encstr >= length $encstr 1983 4055 6038
191 4055 my $pos = pos($encstr); ### save it
192  
193 ### Case 1: are we looking at "=?..?..?="?
194 4055 ▶ if ($encstr =~ m{\G # from where we left off..
Branch: 1 branch
BranchTrueFalseTotal
if ($encstr =~ /\G # from where we left off.. =\?([^?]*) # "=?" + charset + \?([bq]) # "?" + encoding + \?([^?]+) # "?" + data maybe with spcs + \?= # "?=" /gix) 75 3980 4055
195 =\?([^?]*) # "=?" + charset +
196 \?([bq]) # "?" + encoding +
197 \?([^?]+) # "?" + data maybe with spcs +
198 \?= # "?="
199 }xgi) {
200 75 ($charset, $encoding, $enc) = ($1, lc($2), $3);
201 75 ▶ $dec = (($encoding eq 'q') ? _decode_Q($enc) : _decode_B($enc));
Branch: 1 branch
BranchTrueFalseTotal
$encoding eq 'q' ? : 63 12 75
202 75 push @tokens, [$dec, $charset];
203 75 next;
204 }
205  
206 ### Case 2: are we looking at a bad "=?..." prefix?
207 ### We need this to detect problems for case 3, which stops at "=?":
208 3980 pos($encstr) = $pos; # reset the pointer.
209 3980 ▶ if ($encstr =~ m{\G=\?}xg) {
Branch: 1 branch
BranchTrueFalseTotal
if ($encstr =~ /\G=\?/gx) 2004 1976 3980
210 2004 $@ .= qq|unterminated "=?..?..?=" (pos $pos)\n|;
211 2004 push @tokens, ['=?'];
212 2004 next;
213 }
214  
215 ### Case 3: are we looking at ordinary text?
216 1976 pos($encstr) = $pos; # reset the pointer.
217 1976 ▶ if ($encstr =~ m{\G # from where we left off...
Branch: 1 branch
BranchTrueFalseTotal
if ($encstr =~ /\G # from where we left off... (.*? # shortest possible string, \n*) # followed by 0 or more NLs, (?=(\Z|=\?)) # terminated by "=?" or EOS /gsx) 1976 0 1976
218 (.*? # shortest possible string,
219 \n*) # followed by 0 or more NLs,
220 (?=(\Z|=\?)) # terminated by "=?" or EOS
221 }sxg) {
222 1976 ▶ length($1) or die "MIME::Words: internal logic err: empty token\n";
Branch: 1 branch
BranchTrueFalseTotal
length $1 or die "MIME::Words: internal logic err: empty token\n" 1976 0 1976
223 1976 push @tokens, [$1];
224 1976 next;
225 }
226  
227 ### Case 4: bug!
228 0 die "MIME::Words: unexpected case:\n($encstr) pos $pos\n\t".
229 "Please alert developer.\n";
230 }
231 1983 ▶ return (wantarray ? @tokens : join('',map {$_->[0]} @tokens));
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 102 1881 1983
232 }
233  
234 #------------------------------
235  
236 =item encode_mimeword RAW, [ENCODING], [CHARSET]
237  
238 I<Function.>
239 Encode a single RAW "word" that has unsafe characters.
240 The "word" will be encoded in its entirety.
241  
242 ### Encode "<<Franc,ois>>":
243 $encoded = encode_mimeword("\xABFran\xE7ois\xBB");
244  
245 You may specify the ENCODING (C<"Q"> or C<"B">), which defaults to C<"Q">.
246 You may specify the CHARSET, which defaults to C<iso-8859-1>.
247  
248 =cut
249  
250 25 ▶sub encode_mimeword {
Subroutine encode_mimeword: called CC=4 SCAR=14.6
Pod documented
251 25 my $word = shift;
252 25 ▶ my $encoding = uc(shift || 'Q');
Condition50%1/2
shift() || 'Q'
l!l
250
MC/DC0%0/1
shift() || 'Q'
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
253 25 ▶ my $charset = uc(shift || 'ISO-8859-1');
Condition50%1/2
shift() || 'ISO-8859-1'
l!l
250
MC/DC0%0/1
shift() || 'ISO-8859-1'
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
254 25 ▶ my $encfunc = (($encoding eq 'Q') ? \&_encode_Q : \&_encode_B);
Branch: 1 branch
BranchTrueFalseTotal
$encoding eq 'Q' ? : 25 0 25
255 25 "=?$charset?$encoding?" . &$encfunc($word) . "?=";
256 }
257  
258 #------------------------------
259  
260 =item encode_mimewords RAW, [OPTS]
261  
262 I<Function.>
263 Given a RAW string, try to find and encode all "unsafe" sequences
264 of characters:
265  
266 ### Encode a string with some unsafe "words":
267 $encoded = encode_mimewords("Me and \xABFran\xE7ois\xBB");
268  
269 Returns the encoded string.
270 Any arguments past the RAW string are taken to define a hash of options:
271  
272 =over 4
273  
274 =item Charset
275  
276 Encode all unsafe stuff with this charset. Default is 'ISO-8859-1',
277 a.k.a. "Latin-1".
278  
279 =item Encoding
280  
281 The encoding to use, C<"q"> or C<"b">. The default is C<"q">.
282  
283 =back
284  
285 B<Warning:> this is a quick-and-dirty solution, intended for character
286 sets which overlap ASCII. B<It does not comply with the RFC 2047
287 rules regarding the use of encoded words in message headers>.
288 You may want to roll your own variant,
289 using C<encode_mimeword()>, for your application.
290 I<Thanks to Jan Kasprzak for reminding me about this problem.>
291  
292 =cut
293  
294 6 ▶sub encode_mimewords {
Subroutine encode_mimewords: called CC=4 SCAR=13.9
Pod documented
295 6 my ($rawstr, %params) = @_;
296 6 ▶ my $charset = $params{Charset} || 'ISO-8859-1';
Condition100%2/2
$params{'Charset'} || 'ISO-8859-1'
l!l
33
MC/DC100%1/1
$params{'Charset'} || 'ISO-8859-1'
$params{'Charset'}
Truth table100%2/2
A
A= $params{'Charset'}
Aresult
11
00
297 6 ▶ my $encoding = lc($params{Encoding} || 'q');
Condition50%1/2
$params{'Encoding'} || 'q'
l!l
06
MC/DC0%0/1
$params{'Encoding'} || 'q'
$params{'Encoding'}
Truth table50%1/2
A
A= $params{'Encoding'}
Aresult
11
00
298  
299 ### Encode any "words" with unsafe characters.
300 ### We limit such words to 18 characters, to guarantee that the
301 ### worst-case encoding give us no more than 54 + ~10 < 75 characters
302 6 my $word;
303 6 local $1;
304 6 $rawstr =~ s{([a-zA-Z0-9\x7F-\xFF]+\s*)}{ ### get next "word"
305 51 $word = $1;
306 51 ▶ (($word !~ /(?:[$NONPRINT])|(?:^\s+$)/o)
Branch: 1 branch
BranchTrueFalseTotal
!($word =~ /(?:[$NONPRINT])|(?:^\s+$)/o) ? : 28 23 51
307 ? $word ### no unsafe chars
308 : encode_mimeword($word, $encoding, $charset)); ### has unsafe chars
309 }xeg;
310 6 $rawstr =~ s/\?==\?/?= =?/g;
311 6 $rawstr;
312 }
313  
314 46 1;
315 __END__
« Decoder/NBit.pm ↑ Summary Tools.pm »