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 / WordDecoder.pm < prev    next >
Encoding:
Perl POD Document  |  2002-06-14  |  15.4 KB  |  619 lines

  1. package MIME::WordDecoder;
  2.  
  3.  
  4. =head1 NAME
  5.  
  6. MIME::WordDecoder - decode RFC-1522 encoded words to a local representation
  7.  
  8.  
  9. =head1 SYNOPSIS
  10.  
  11. See L<MIME::Words> for the basics of encoded words.
  12. See L<"DESCRIPTION"> for how this class works.
  13.  
  14.     use MIME::WordDecoder;
  15.  
  16.  
  17.     ### Get the default word-decoder (used by unmime()):
  18.     $wd = default MIME::WordDecoder;
  19.  
  20.     ### Get a word-decoder which maps to ISO-8859-1 (Latin1):
  21.     $wd = supported MIME::WordDecoder "ISO-8859-1";
  22.  
  23.  
  24.     ### Decode a MIME string (e.g., into Latin1) via the default decoder:
  25.     $str = $wd->decode('To: =?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld>');
  26.  
  27.     ### Decode a string using the default decoder, non-OO style:
  28.     $str = unmime('To: =?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld>');
  29.  
  30.  
  31. =head1 DESCRIPTION
  32.  
  33. A MIME::WordDecoder consists, fundamentally, of a hash which maps
  34. a character set name (US-ASCII, ISO-8859-1, etc.) to a subroutine which
  35. knows how to take bytes in that character set and turn them into
  36. the target string representation.  Ideally, this target representation
  37. would be Unicode, but we don't want to overspecify the translation
  38. that takes place: if you want to convert MIME strings directly to Big5,
  39. that's your own decision.
  40.  
  41. The subroutine will be invoked with two arguments: DATA (the data in
  42. the given character set), and CHARSET (the upcased character set name).
  43.  
  44. For example:
  45.  
  46.     ### Keep 7-bit characters as-is, convert 8-bit characters to '#':
  47.     sub keep7bit {
  48.     local $_ = shift;
  49.     tr/\x00-\x7F/#/c;
  50.     $_;
  51.     }
  52.  
  53. Here's a decoder which uses that:
  54.  
  55.    ### Construct a decoder:
  56.    $wd = MIME::WordDecoder->new({'US-ASCII'   => "KEEP",   ### sub { $_[0] }
  57.                                  'ISO-8859-1' => \&keep7bit,
  58.                                  'ISO-8859-2' => \&keep7bit,
  59.                                  'Big5'       => "WARN",
  60.                                  '*'          => "DIE"});
  61.  
  62.    ### Convert some MIME text to a pure ASCII string...
  63.    $ascii = $wd->decode('To: =?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld>');
  64.  
  65.    ### ...which will now hold: "To: Keld J#rn Simonsen <keld>"
  66.  
  67.  
  68.  
  69. =head1 PUBLIC INTERFACE
  70.  
  71. =over
  72.  
  73. =cut
  74.  
  75. use strict;
  76. use Carp qw( carp croak );
  77. use MIME::Words qw(decode_mimewords);
  78. use Exporter;
  79. use vars qw(@ISA @EXPORT);
  80.  
  81. @ISA = qw(Exporter);
  82. @EXPORT = qw( unmime );
  83.  
  84.  
  85.  
  86. #------------------------------
  87. #
  88. # Globals
  89. #------------------------------
  90.  
  91. ### Decoders.
  92. my %DecoderFor = ();
  93.  
  94. ### Standard handlers.
  95. my %Handler = 
  96. (
  97.  KEEP   => sub {$_[0]},
  98.  IGNORE => sub {''},
  99.  WARN   => sub { carp "ignoring text in character set `$_[1]'\n" },
  100.  DIE    => sub { croak "can't handle text in character set `$_[1]'\n" },
  101.  );
  102.  
  103. ### Global default decoder.  We init it below.
  104. my $Default;
  105.  
  106.  
  107. #------------------------------
  108.  
  109. =item default [DECODER]
  110.  
  111. I<Class method.>
  112. Get/set the default DECODER object.
  113.  
  114. =cut
  115.  
  116. sub default {
  117.     my $class = shift;
  118.     if (@_) {
  119.     $Default = shift;
  120.     }
  121.     $Default;
  122. }
  123.  
  124. #------------------------------
  125.  
  126. =item supported CHARSET, [DECODER]
  127.  
  128. I<Class method.>
  129. If just CHARSET is given, returns a decoder object which maps
  130. data into that character set (the character set is forced to
  131. all-uppercase).
  132.  
  133.     $wd = supported MIME::WordDecoder "ISO-8859-1";
  134.  
  135. If DECODER is given, installs such an object:
  136.  
  137.     MIME::WordDecoder->supported("ISO-8859-1" =>
  138.                  (new MIME::WordDecoder::ISO_8859 "1"));
  139.  
  140. You should not override this method.
  141.  
  142. =cut
  143.  
  144. sub supported {
  145.     my ($class, $charset, $decoder) = @_;
  146.     $DecoderFor{uc($charset)} = $decoder if (@_ > 2);
  147.     $DecoderFor{uc($charset)};
  148. }
  149.  
  150. #------------------------------
  151.  
  152. =item new [\@HANDLERS]
  153.  
  154. I<Class method, constructor.>
  155. If \@HANDLERS is given, then @HANDLERS is passed to handler()
  156. to initiallize the internal map.
  157.  
  158. =cut
  159.  
  160. sub new {
  161.     my ($class, $h) = @_;
  162.     my $self = bless { MWD_Map=>{} }, $class;   
  163.  
  164.     ### Init the map:
  165.     $self->handler(@$h);
  166.     
  167.     ### Add fallbacks:
  168.     $self->{MWD_Map}{'*'}   ||= $Handler{WARN};
  169.     $self->{MWD_Map}{'raw'} ||= $self->{MWD_Map}{'US-ASCII'};
  170.     $self;
  171. }
  172.  
  173. #------------------------------
  174.  
  175. =item handler CHARSET=>\&SUBREF, ...
  176.  
  177. I<Instance method.>
  178. Set the handler SUBREF for a given CHARSET, for as many pairs
  179. as you care to supply.
  180.  
  181. When performing the translation of a MIME-encoded string, a
  182. given SUBREF will be invoked when translating a block of text
  183. in character set CHARSET.  The subroutine will be invoked with
  184. the following arguments:
  185.  
  186.     DATA    - the data in the given character set.
  187.     CHARSET - the upcased character set name, which may prove useful
  188.               if you are using the same SUBREF for multiple CHARSETs.
  189.     DECODER - the decoder itself, if it contains configuration information
  190.               that your handler function needs.
  191.  
  192. For example:
  193.  
  194.     $wd = new MIME::WordDecoder;
  195.     $wd->handler('US-ASCII'   => "KEEP");
  196.     $wd->handler('ISO-8859-1' => \&handle_latin1,
  197.          'ISO-8859-2' => \&handle_latin1,
  198.          '*'          => "DIE");
  199.  
  200. Notice that, much as with %SIG, the SUBREF can also be taken from
  201. a set of special keywords:
  202.  
  203.    KEEP     Pass data through unchanged.
  204.    IGNORE   Ignore data in this character set, without warning.
  205.    WARN     Ignore data in this character set, with warning.
  206.    DIE      Fatal exception with "can't handle character set" message.
  207.  
  208. The subroutine for the special CHARSET of 'raw' is used for raw
  209. (non-MIME-encoded) text, which is supposed to be US-ASCII.
  210. The handler for 'raw' defaults to whatever was specified for 'US-ASCII'
  211. at the time of construction.
  212.  
  213. The subroutine for the special CHARSET of '*' is used for any
  214. unrecognized character set.  The default action for '*' is WARN.
  215.  
  216. =cut
  217.  
  218. sub handler {
  219.     my $self = shift;
  220.     
  221.     ### Copy the hash, and edit it:
  222.     while (@_) {
  223.     my $c   = shift; 
  224.     my $sub = shift;
  225.     $self->{MWD_Map}{$c} = $self->real_handler($sub);
  226.     }
  227.     $self;
  228. }
  229.  
  230. #------------------------------
  231.  
  232. =item decode STRING
  233.  
  234. I<Instance method.>
  235. Decode a STRING which might contain MIME-encoded components into a
  236. local representation (e.g., UTF-8, etc.).
  237.  
  238. =cut
  239.  
  240. sub decode {
  241.     my ($self, $str) = @_;
  242.     defined($str) or return undef;
  243.     join('', map {
  244.     ### Get the data and (upcased) charset:
  245.     my $data    = $_->[0];
  246.     my $charset = (defined($_->[1]) ? uc($_->[1]) : 'raw');
  247.     $charset =~ s/\*\w+\Z//;   ### RFC2184 language suffix
  248.  
  249.     ### Get the handler; guess if never seen before:
  250.     defined($self->{MWD_Map}{$charset}) or
  251.         $self->{MWD_Map}{$charset} = 
  252.         ($self->real_handler($self->guess_handler($charset)) || 0);
  253.     my $subr = $self->{MWD_Map}{$charset} || $self->{MWD_Map}{'*'}; 
  254.  
  255.     ### Map this chunk:
  256.     &$subr($data, $charset, $self);
  257.     } decode_mimewords($str));
  258. }
  259.  
  260. #------------------------------
  261. #
  262. # guess_handler CHARSET    
  263. #
  264. # Instance method.  
  265. # An unrecognized charset has been seen.  Guess a handler subref 
  266. # for the given charset, returning false if there is none.
  267. # Successful mappings will be cached in the main map.
  268. #
  269. sub guess_handler {
  270.     undef;
  271. }
  272.  
  273. #------------------------------
  274. #
  275. # real_handler HANDLER
  276. #
  277. # Instance method.  
  278. # Translate the given handler, which might be a subref or a string.
  279. #
  280. sub real_handler {
  281.     my ($self, $sub) = @_;
  282.     (!$sub) or 
  283.     (ref($sub) eq 'CODE') or 
  284.         $sub = ($Handler{$sub} || croak "bad named handler: $sub\n");
  285.     $sub;
  286. }
  287.  
  288. #------------------------------
  289.  
  290. =item unmime STRING
  291.  
  292. I<Function, exported.>
  293. Decode the given STRING using the default() decoder.
  294. See L<default()|/default>.
  295.  
  296. =cut
  297.  
  298. sub unmime($) {
  299.     my $str = shift;
  300.     $Default->decode($str);
  301. }
  302.  
  303.  
  304. =back
  305.  
  306. =cut
  307.  
  308.  
  309.  
  310.  
  311.  
  312. =head1 SUBCLASSES
  313.  
  314. =over
  315.  
  316. =cut
  317.  
  318. #------------------------------------------------------------
  319. #------------------------------------------------------------
  320.  
  321. =item MIME::WordDecoder::ISO_8859
  322.  
  323. A simple decoder which keeps US-ASCII and the 7-bit characters
  324. of ISO-8859 character sets and UTF8, and also keeps 8-bit
  325. characters from the indicated character set.
  326.  
  327.     ### Construct:
  328.     $wd = new MIME::WordDecoder::ISO_8859 2;    ### ISO-8859-2
  329.  
  330.     ### What to translate unknown characters to (can also use empty):
  331.     ### Default is "?".
  332.     $wd->unknown("?");
  333.  
  334.     ### Collapse runs of unknown characters to a single unknown()?
  335.     ### Default is false.
  336.     $wd->collapse(1);
  337.  
  338.  
  339. According to B<http://czyborra.com/charsets/iso8859.html>
  340. (ca. November 2000):
  341.  
  342. ISO 8859 is a full series of 10 (and soon even more) standardized
  343. multilingual single-byte coded (8bit) graphic character sets for
  344. writing in alphabetic languages:
  345.  
  346.     1. Latin1 (West European)
  347.     2. Latin2 (East European)
  348.     3. Latin3 (South European)
  349.     4. Latin4 (North European)
  350.     5. Cyrillic
  351.     6. Arabic
  352.     7. Greek
  353.     8. Hebrew
  354.     9. Latin5 (Turkish)
  355.    10. Latin6 (Nordic)
  356.  
  357. The ISO 8859 charsets are not even remotely as complete as the truly
  358. great Unicode but they have been around and usable for quite a while
  359. (first registered Internet charsets for use with MIME) and have
  360. already offered a major improvement over the plain 7bit US-ASCII.
  361.  
  362. Characters 0 to 127 are always identical with US-ASCII and the
  363. positions 128 to 159 hold some less used control characters: the
  364. so-called C1 set from ISO 6429.
  365.  
  366. =cut
  367.  
  368. package MIME::WordDecoder::ISO_8859;
  369.  
  370. use strict;
  371. use vars qw(@ISA);
  372. @ISA = qw( MIME::WordDecoder );
  373.  
  374.  
  375. #------------------------------
  376. #
  377. # HANDLERS
  378. #
  379. #------------------------------
  380.  
  381. ### Keep 7bit characters.
  382. ### Turn all else to the special \x00.
  383. sub h_keep7bit {  
  384.     local $_    = $_[0];
  385. #   my $unknown = $_[2]->{MWDI_Unknown};
  386.  
  387.     s{[\x80-\xFF]}{\x00}g;
  388.     $_;
  389. }
  390.  
  391. ### Note: should use Unicode::String, converting/manipulating 
  392. ### everything into full Unicode form.
  393.  
  394. ### Keep 7bit UTF8 characters (ASCII).
  395. ### Keep ISO-8859-1 if this decoder is for Latin-1.
  396. ### Turn all else to the special \x00.
  397. sub h_utf8 {  
  398.     local $_    = $_[0];
  399. #   my $unknown = $_[2]->{MWDI_Unknown};
  400.     my $latin1 = ($_[2]->{MWDI_Num} == 1);
  401.     print STDERR "UTF8 in:  <$_>\n"; 
  402.  
  403.     my $tgt = '';
  404.     while (m{\G(
  405.           ([\x00-\x7F])                | # 0xxxxxxx
  406.       ([\xC0-\xDF] [\x80-\xBF])    | # 110yyyyy 10xxxxxx
  407.       ([\xE0-\xEF] [\x80-\xBF]{2}) | # 1110zzzz 10yyyyyy 10xxxxxx
  408.       ([\xF0-\xF7] [\x80-\xBF]{3}) | # 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx
  409.       .                              # error; synch
  410.       )}gcsx and ($1 ne '')) {   
  411.  
  412.     if    (defined($2))            { $tgt .= $2 }
  413.     elsif (defined($3) && $latin1) { $tgt .= "\x00" }
  414.         else                           { $tgt .= "\x00" }
  415.     }
  416.  
  417.     print STDERR "UTF8 out: <$tgt>\n"; 
  418.     $tgt;
  419. }
  420.  
  421. ### Keep characters which are 7bit in UTF8 (ASCII).
  422. ### Keep ISO-8859-1 if this decoder is for Latin-1.
  423. ### Turn all else to the special \x00.
  424. sub h_utf16 {  
  425.     local $_    = $_[0];
  426. #   my $unknown = $_[2]->{MWDI_Unknown};
  427.     my $latin1 = ($_[2]->{MWDI_Num} == 1);
  428.     print STDERR "UTF16 in:  <$_>\n"; 
  429.  
  430.     my $tgt = '';
  431.     while (m{\G(
  432.         (  \x00  ([\x00-\x7F])) |  # 00000000 0xxxxxxx
  433.         (  \x00  ([\x80-\xFF])) |  # 00000000 1xxxxxxx
  434.         ( [^\x00] [\x00-\xFF])  |  # etc
  435.         )
  436.          }gcsx and ($1 ne '')) {
  437.  
  438.     if    (defined($2))            { $tgt .= $3 }
  439.     elsif (defined($4) && $latin1) { $tgt .= $5 }
  440.         else                           { $tgt .= "\x00" }
  441.     }
  442.  
  443.     print STDERR "UTF16 out: <$tgt>\n"; 
  444.     $tgt;
  445. }
  446.  
  447.  
  448. #------------------------------
  449. #
  450. # PUBLIC INTERFACE
  451. #
  452. #------------------------------
  453.  
  454. #------------------------------
  455. #
  456. # new NUMBER
  457. #
  458. sub new {
  459.     my ($class, $num) = @_;
  460.  
  461.     my $self = $class->SUPER::new();
  462.     $self->handler('raw'      => 'KEEP',
  463.            'US-ASCII' => 'KEEP');
  464.  
  465.     $self->{MWDI_Num} = $num;
  466.     $self->{MWDI_Unknown} = "?";
  467.     $self->{MWDI_Collapse} = 0;
  468.     $self;
  469. }
  470.  
  471. #------------------------------
  472. #
  473. # guess_handler CHARSET
  474. #
  475. sub guess_handler {
  476.     my ($self, $charset) = @_;
  477.     return 'KEEP'              if (($charset =~ /^ISO[-_]?8859[-_](\d+)$/) && 
  478.                    ($1 eq $self->{MWDI_Num}));
  479.     return \&h_keep7bit        if ($charset =~ /^ISO[-_]?8859/);
  480.     return \&h_utf8            if ($charset =~ /^UTF[-_]?8$/);
  481.     return \&h_utf16           if ($charset =~ /^UTF[-_]?16$/);
  482.     undef;
  483. }
  484.  
  485. #------------------------------
  486. #
  487. # unknown [REPLACEMENT]
  488. #
  489. sub unknown {
  490.     my $self = shift;
  491.     $self->{MWDI_Unknown} = shift if @_;
  492.     $self->{MWDI_Unknown};
  493. }
  494.  
  495. #------------------------------
  496. #
  497. # collapse [YESNO]
  498. #
  499. sub collapse {
  500.     my $self = shift;
  501.     $self->{MWDI_Collapse} = shift if @_;
  502.     $self->{MWDI_Collapse};
  503. }
  504.  
  505. #------------------------------
  506. #
  507. # decode STRING
  508. #
  509. sub decode {
  510.     my $self = shift;
  511.  
  512.     ### Do inherited action:
  513.     my $basic = $self->SUPER::decode(@_);
  514.     defined($basic) or return undef;
  515.  
  516.     ### Translate/consolidate illegal characters:
  517.     $basic =~ tr{\x00}{\x00}c     if $self->{MWDI_Collapse};
  518.     $basic =~ s{\x00}{$self->{MWDI_Unknown}}g;
  519.     $basic;
  520. }
  521.  
  522. #------------------------------------------------------------
  523. #------------------------------------------------------------
  524.  
  525. =item MIME::WordDecoder::US_ASCII
  526.  
  527. A subclass of the ISO-8859-1 decoder which discards 8-bit characters.
  528. You're probably better off using ISO-8859-1.
  529.  
  530. =cut
  531.  
  532. package MIME::WordDecoder::US_ASCII;
  533.  
  534. use strict;
  535. use vars qw(@ISA);
  536. @ISA = qw( MIME::WordDecoder::ISO_8859 );
  537.  
  538. sub new {
  539.     my ($class) = @_;
  540.     return $class->SUPER::new("1");
  541. }
  542.  
  543. sub decode {
  544.     my $self = shift;
  545.  
  546.     ### Do inherited action:
  547.     my $basic = $self->SUPER::decode(@_);
  548.     defined($basic) or return undef;
  549.  
  550.     ### Translate/consolidate 8-bit characters:
  551.     $basic =~ tr{\x80-\xFF}{}c     if $self->{MWDI_Collapse};
  552.     $basic =~ s{[\x80-\xFF]}{$self->{MWDI_Unknown}}g;
  553.     $basic;
  554. }
  555.  
  556. =back
  557.  
  558. =cut
  559.  
  560. #------------------------------------------------------------
  561. #------------------------------------------------------------
  562.  
  563. package MIME::WordDecoder;
  564.  
  565. ### Now we can init the default handler.
  566. $Default = (MIME::WordDecoder::ISO_8859->new('1'));
  567.  
  568. ### Add US-ASCII handler:
  569. $DecoderFor{"US-ASCII"} = MIME::WordDecoder::US_ASCII->new;
  570.  
  571. ### Add ISO-8859-{1..15} handlers:
  572. for (1..15) { 
  573.     $DecoderFor{"ISO-8859-$_"} = MIME::WordDecoder::ISO_8859->new($_);
  574. }
  575.  
  576.   package main; no strict; local $^W = 0;
  577.   my @x = <::DATA>;
  578.   eval join('',<::DATA>) || die $@ unless caller();
  579. }
  580. 1;           # end the module
  581. __END__
  582.  
  583.  
  584. =head1 AUTHOR
  585.  
  586. Eryq (F<eryq@zeegee.com>), ZeeGee Software Inc (F<http://www.zeegee.com>).
  587.  
  588.  
  589. =head1 VERSION
  590.  
  591. $Revision: 5.403 $ $Date: 2000/11/23 05:04:03 $
  592.  
  593. =cut
  594.  
  595.  
  596. BEGIN { unshift @INC, ".", "./etc", "./lib" };
  597. import MIME::WordDecoder;
  598.  
  599. ### Decode a MIME string (e.g., into Latin1) via the default decoder:
  600. my $charset = $ARGV[0] || 'ISO-8859-1';
  601. my $wd = MIME::WordDecoder->supported($charset) || die "unsupported charset: $charset\n";
  602.  
  603. $wd->unknown('#');
  604. my @encs = (
  605.         'ASCII:  =?US-ASCII?Q?Keith_Moore?= <moore@cs.utk.edu>',
  606.         'Latin1: =?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>',
  607.         'Latin1: =?ISO-8859-1?Q?Andr=E9_?= Pirard <PIRARD@vm1.ulg.ac.be>',
  608.         'Latin1: =?ISO-8859-1?Q?Andr=E9_?=Pirard <PIRARD@vm1.ulg.ac.be>',
  609.         ' UTF-8: =?UTF-8?Q?Andr=E9_?=Pirard <PIRARD@vm1.ulg.ac.be>',
  610.         'UTF-16: =?UTF-16?Q?=00A=00n=00d=00r=00=E9?= Pirard <PIRARD@vm1.ulg.ac.be>',
  611.         ('=?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?='.
  612.          '=?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?='.
  613.          '=?US-ASCII?Q?.._cool!?='));
  614. $str = $wd->decode(join "\n", @encs);
  615. print "$str\n";
  616. 1;
  617.