home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / xampp / xampp-perl-addon-1.4.9-installer.exe / Words.pm < prev    next >
Encoding:
Perl POD Document  |  2002-06-14  |  11.4 KB  |  407 lines

  1. package MIME::Words;
  2.  
  3.  
  4. =head1 NAME
  5.  
  6. MIME::Words - deal with RFC-1522 encoded words
  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.  
  18.     use MIME::Words qw(:all);
  19.  
  20.     ### Decode the string into another string, forgetting the charsets:
  21.     $decoded = decode_mimewords(
  22.           'To: =?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>',
  23.           );
  24.  
  25.     ### Split string into array of decoded [DATA,CHARSET] pairs:
  26.     @decoded = decode_mimewords(
  27.           'To: =?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>',
  28.           );
  29.  
  30.     ### Encode a single unsafe word:
  31.     $encoded = encode_mimeword("\xABFran\xE7ois\xBB");
  32.  
  33.     ### Encode a string, trying to find the unsafe words inside it:
  34.     $encoded = encode_mimewords("Me and \xABFran\xE7ois\xBB in town");
  35.  
  36.  
  37.  
  38. =head1 DESCRIPTION
  39.  
  40. Fellow Americans, you probably won't know what the hell this module
  41. is for.  Europeans, Russians, et al, you probably do.  C<:-)>.
  42.  
  43. For example, here's a valid MIME header you might get:
  44.  
  45.       From: =?US-ASCII?Q?Keith_Moore?= <moore@cs.utk.edu>
  46.       To: =?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>
  47.       CC: =?ISO-8859-1?Q?Andr=E9_?= Pirard <PIRARD@vm1.ulg.ac.be>
  48.       Subject: =?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=
  49.        =?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=
  50.        =?US-ASCII?Q?.._cool!?=
  51.  
  52. The fields basically decode to (sorry, I can only approximate the
  53. Latin characters with 7 bit sequences /o and 'e):
  54.  
  55.       From: Keith Moore <moore@cs.utk.edu>
  56.       To: Keld J/orn Simonsen <keld@dkuug.dk>
  57.       CC: Andr'e  Pirard <PIRARD@vm1.ulg.ac.be>
  58.       Subject: If you can read this you understand the example... cool!
  59.  
  60.  
  61. =head1 PUBLIC INTERFACE
  62.  
  63. =over 4
  64.  
  65. =cut
  66.  
  67. require 5.001;
  68.  
  69. ### Pragmas:
  70. use strict;
  71. use vars qw($VERSION @EXPORT_OK %EXPORT_TAGS @ISA);
  72.  
  73. ### Exporting:
  74. use Exporter;
  75. %EXPORT_TAGS = (all => [qw(decode_mimewords
  76.                encode_mimeword
  77.                encode_mimewords
  78.                )]);
  79. Exporter::export_ok_tags('all');
  80.  
  81. ### Inheritance:
  82. @ISA = qw(Exporter);
  83.  
  84. ### Other modules:
  85. use MIME::Base64;
  86. use MIME::QuotedPrint;
  87.  
  88.  
  89.  
  90. #------------------------------
  91. #
  92. # Globals...
  93. #
  94. #------------------------------
  95.  
  96. ### The package version, both in 1.23 style *and* usable by MakeMaker:
  97. $VERSION = substr q$Revision: 5.404 $, 10;
  98.  
  99. ### Nonprintables (controls + x7F + 8bit):
  100. 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. sub _decode_Q {
  109.     my $str = shift;
  110.     $str =~ s/_/\x20/g;                                # RFC-1522, Q rule 2
  111.     $str =~ s/=([\da-fA-F]{2})/pack("C", hex($1))/ge;  # RFC-1522, Q rule 1
  112.     $str;
  113. }
  114.  
  115. # _encode_Q STRING
  116. #     Private: used by _encode_header() to decode "Q" encoding, which is
  117. #     almost, but not exactly, quoted-printable.  :-P
  118. sub _encode_Q {
  119.     my $str = shift;
  120.     $str =~ s{([_\?\=$NONPRINT])}{sprintf("=%02X", ord($1))}eog;
  121.     $str;
  122. }
  123.  
  124. # _decode_B STRING
  125. #     Private: used by _decode_header() to decode "B" encoding.
  126. sub _decode_B {
  127.     my $str = shift;
  128.     decode_base64($str);
  129. }
  130.  
  131. # _encode_B STRING
  132. #     Private: used by _decode_header() to decode "B" encoding.
  133. sub _encode_B {
  134.     my $str = shift;
  135.     encode_base64($str, '');
  136. }
  137.  
  138.  
  139.  
  140. #------------------------------
  141.  
  142. =item decode_mimewords ENCODED, [OPTS...]
  143.  
  144. I<Function.>
  145. Go through the string looking for RFC-1522-style "Q"
  146. (quoted-printable, sort of) or "B" (base64) encoding, and decode them.
  147.  
  148. B<In an array context,> splits the ENCODED string into a list of decoded
  149. C<[DATA, CHARSET]> pairs, and returns that list.  Unencoded
  150. data are returned in a 1-element array C<[DATA]>, giving an effective
  151. CHARSET of C<undef>.
  152.  
  153.     $enc = '=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>';
  154.     foreach (decode_mimewords($enc)) {
  155.         print "", ($_[1] || 'US-ASCII'), ": ", $_[0], "\n";
  156.     }
  157.  
  158. B<In a scalar context,> joins the "data" elements of the above
  159. list together, and returns that.  I<Warning: this is information-lossy,>
  160. and probably I<not> what you want, but if you know that all charsets
  161. in the ENCODED string are identical, it might be useful to you.
  162. (Before you use this, please see L<MIME::WordDecoder/unmime>,
  163. which is probably what you want.)
  164.  
  165. In the event of a syntax error, $@ will be set to a description
  166. of the error, but parsing will continue as best as possible (so as to
  167. get I<something> back when decoding headers).
  168. $@ will be false if no error was detected.
  169.  
  170. Any arguments past the ENCODED string are taken to define a hash of options:
  171.  
  172. =over 4
  173.  
  174. =item Field
  175.  
  176. Name of the mail field this string came from.  I<Currently ignored.>
  177.  
  178. =back
  179.  
  180. =cut
  181.  
  182. sub decode_mimewords {
  183.     my $encstr = shift;
  184.     my %params = @_;
  185.     my @tokens;
  186.     $@ = '';           ### error-return
  187.  
  188.     ### Collapse boundaries between adjacent encoded words:
  189.     $encstr =~ s{(\?\=)\r?\n[ \t](\=\?)}{$1$2}gs;
  190.     pos($encstr) = 0;
  191.     ### print STDOUT "ENC = [", $encstr, "]\n";
  192.  
  193.     ### Decode:
  194.     my ($charset, $encoding, $enc, $dec);
  195.     while (1) {
  196.     last if (pos($encstr) >= length($encstr));
  197.     my $pos = pos($encstr);               ### save it
  198.  
  199.     ### Case 1: are we looking at "=?..?..?="?
  200.     if ($encstr =~    m{\G             # from where we left off..
  201.                 =\?([^?]*)     # "=?" + charset +
  202.                  \?([bq])      #  "?" + encoding +
  203.                  \?([^?]+)     #  "?" + data maybe with spcs +
  204.                  \?=           #  "?="
  205.                 }xgi) {
  206.         ($charset, $encoding, $enc) = ($1, lc($2), $3);
  207.         $dec = (($encoding eq 'q') ? _decode_Q($enc) : _decode_B($enc));
  208.         push @tokens, [$dec, $charset];
  209.         next;
  210.     }
  211.  
  212.     ### Case 2: are we looking at a bad "=?..." prefix? 
  213.     ### We need this to detect problems for case 3, which stops at "=?":
  214.     pos($encstr) = $pos;               # reset the pointer.
  215.     if ($encstr =~ m{\G=\?}xg) {
  216.         $@ .= qq|unterminated "=?..?..?=" in "$encstr" (pos $pos)\n|;
  217.         push @tokens, ['=?'];
  218.         next;
  219.     }
  220.  
  221.     ### Case 3: are we looking at ordinary text?
  222.     pos($encstr) = $pos;               # reset the pointer.
  223.     if ($encstr =~ m{\G                # from where we left off...
  224.              ([\x00-\xFF]*?    #   shortest possible string,
  225.               \n*)             #   followed by 0 or more NLs,
  226.                  (?=(\Z|=\?))      # terminated by "=?" or EOS
  227.             }xg) {
  228.         length($1) or die "MIME::Words: internal logic err: empty token\n";
  229.         push @tokens, [$1];
  230.         next;
  231.     }
  232.  
  233.     ### Case 4: bug!
  234.     die "MIME::Words: unexpected case:\n($encstr) pos $pos\n\t".
  235.         "Please alert developer.\n";
  236.     }
  237.     return (wantarray ? @tokens : join('',map {$_->[0]} @tokens));
  238. }
  239.  
  240. #------------------------------
  241.  
  242. =item encode_mimeword RAW, [ENCODING], [CHARSET]
  243.  
  244. I<Function.>
  245. Encode a single RAW "word" that has unsafe characters.
  246. The "word" will be encoded in its entirety.
  247.  
  248.     ### Encode "<<Franc,ois>>":
  249.     $encoded = encode_mimeword("\xABFran\xE7ois\xBB");
  250.  
  251. You may specify the ENCODING (C<"Q"> or C<"B">), which defaults to C<"Q">.
  252. You may specify the CHARSET, which defaults to C<iso-8859-1>.
  253.  
  254. =cut
  255.  
  256. sub encode_mimeword {
  257.     my $word = shift;
  258.     my $encoding = uc(shift || 'Q');
  259.     my $charset  = uc(shift || 'ISO-8859-1');
  260.     my $encfunc  = (($encoding eq 'Q') ? \&_encode_Q : \&_encode_B);
  261.     "=?$charset?$encoding?" . &$encfunc($word) . "?=";
  262. }
  263.  
  264. #------------------------------
  265.  
  266. =item encode_mimewords RAW, [OPTS]
  267.  
  268. I<Function.>
  269. Given a RAW string, try to find and encode all "unsafe" sequences
  270. of characters:
  271.  
  272.     ### Encode a string with some unsafe "words":
  273.     $encoded = encode_mimewords("Me and \xABFran\xE7ois\xBB");
  274.  
  275. Returns the encoded string.
  276. Any arguments past the RAW string are taken to define a hash of options:
  277.  
  278. =over 4
  279.  
  280. =item Charset
  281.  
  282. Encode all unsafe stuff with this charset.  Default is 'ISO-8859-1',
  283. a.k.a. "Latin-1".
  284.  
  285. =item Encoding
  286.  
  287. The encoding to use, C<"q"> or C<"b">.  The default is C<"q">.
  288.  
  289. =item Field
  290.  
  291. Name of the mail field this string will be used in.  I<Currently ignored.>
  292.  
  293. =back
  294.  
  295. B<Warning:> this is a quick-and-dirty solution, intended for character
  296. sets which overlap ASCII.  B<It does not comply with the RFC-1522
  297. rules regarding the use of encoded words in message headers>.
  298. You may want to roll your own variant,
  299. using C<encoded_mimeword()>, for your application.
  300. I<Thanks to Jan Kasprzak for reminding me about this problem.>
  301.  
  302. =cut
  303.  
  304. sub encode_mimewords {
  305.     my ($rawstr, %params) = @_;
  306.     my $charset  = $params{Charset} || 'ISO-8859-1';
  307.     my $encoding = lc($params{Encoding} || 'q');
  308.  
  309.     ### Encode any "words" with unsafe characters.
  310.     ###    We limit such words to 18 characters, to guarantee that the 
  311.     ###    worst-case encoding give us no more than 54 + ~10 < 75 characters
  312.     my $word;
  313.     $rawstr =~ s{([a-zA-Z0-9\x7F-\xFF]{1,18})}{     ### get next "word"
  314.     $word = $1;
  315.     (($word !~ /[$NONPRINT]/o) 
  316.      ? $word                                          ### no unsafe chars
  317.      : encode_mimeword($word, $encoding, $charset));  ### has unsafe chars
  318.     }xeg;
  319.     $rawstr;
  320. }
  321.  
  322. 1;
  323. __END__
  324.  
  325.  
  326. =back
  327.  
  328. =head1 NOTES
  329.  
  330. Exports its principle functions by default, in keeping with
  331. MIME::Base64 and MIME::QuotedPrint.
  332.  
  333.  
  334. =head1 AUTHOR
  335.  
  336. Eryq (F<eryq@zeegee.com>), ZeeGee Software Inc (F<http://www.zeegee.com>).
  337.  
  338. All rights reserved.  This program is free software; you can redistribute
  339. it and/or modify it under the same terms as Perl itself.
  340.  
  341. Thanks also to...
  342.  
  343.       Kent Boortz        For providing the idea, and the baseline
  344.                          RFC-1522-decoding code!
  345.       KJJ at PrimeNet    For requesting that this be split into
  346.                          its own module.
  347.       Stephane Barizien  For reporting a nasty bug.
  348.  
  349.  
  350. =head1 VERSION
  351.  
  352. $Revision: 5.404 $ $Date: 2000/11/10 16:45:12 $
  353.  
  354. =cut
  355.  
  356.  
  357. #------------------------------
  358. # Execute simple test if run as a script.
  359. #------------------------------
  360.   package main; no strict;
  361.   eval join('',<main::DATA>) || die "$@ $main::DATA" unless caller();
  362. }
  363. 1;           # end the module
  364. __END__
  365.  
  366.  
  367. ### Pick up other MIME stuff, just in case...
  368. BEGIN { unshift @INC, ".", "./etc", "./lib" };
  369. import MIME::Words;
  370.  
  371. my @encs = (
  372.         '=?US-ASCII?Q?Keith_Moore?= <moore@cs.utk.edu>',
  373.         '=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>',
  374.         '=?ISO-8859-1?Q?Andr=E9_?= Pirard <PIRARD@vm1.ulg.ac.be>',
  375.         ('=?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?='.
  376.          '=?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?='.
  377.          '=?US-ASCII?Q?.._cool!?='));
  378. foreach $enc (@encs) {
  379.     $x = decode_mimewords($enc);
  380.     print "DEC: ", $x, "\n";
  381. }
  382.  
  383. ### Encode a single unsafe word:
  384. $encoded = encode_mimeword("\xABFran\xE7ois\xBB");
  385. print "ENC1: ", $encoded, "\n";
  386.     
  387. ### Encode a string, trying to find the unsafe words inside it: 
  388. $encoded = encode_mimewords("Me and \xABFran\xE7ois\xBB at the beach");
  389. print "ENC2: ", $encoded, "\n";
  390.  
  391. ### Encode "<<Franc,ois>>":
  392. my $unsafe = <<EOF;
  393. Me and \xABFran\xE7ois\xBB, down at the beach
  394. with Dave <dave\@ether.net>
  395. EOF
  396. $encoded = encode_mimewords($unsafe);
  397. print "ENC3: ", $encoded, "\n";
  398. print "DEC3: ", scalar(decode_mimewords($encoded)), "\n";
  399.  
  400. ### So we know everything went well...
  401. exit 0;
  402.  
  403. #------------------------------
  404.  
  405.  
  406.