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 / Body.pm < prev    next >
Encoding:
Perl POD Document  |  2002-06-14  |  16.7 KB  |  681 lines

  1. package MIME::Body;
  2.  
  3.  
  4. =head1 NAME
  5.  
  6. MIME::Body - the body of a MIME message
  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. =head2 Obtaining bodies
  19.  
  20.    ### Get the bodyhandle of a MIME::Entity object:
  21.    $body = $entity->bodyhandle;
  22.  
  23.    ### Create a body which stores data in a disk file:
  24.    $body = new MIME::Body::File "/path/to/file";
  25.  
  26.    ### Create a body which stores data in an in-core array:
  27.    $body = new MIME::Body::InCore \@strings;
  28.  
  29.  
  30. =head2 Opening, closing, and using IO handles
  31.  
  32.    ### Write data to the body:
  33.    $IO = $body->open("w")      || die "open body: $!";
  34.    $IO->print($message);
  35.    $IO->close                  || die "close I/O handle: $!";
  36.  
  37.    ### Read data from the body (in this case, line by line):
  38.    $IO = $body->open("r")      || die "open body: $!";
  39.    while (defined($_ = $IO->getline)) {
  40.        ### do stuff
  41.    }
  42.    $IO->close                  || die "close I/O handle: $!";
  43.  
  44.  
  45. =head2 Other I/O
  46.  
  47.    ### Dump the ENCODED body data to a filehandle:
  48.    $body->print(\*STDOUT);
  49.  
  50.    ### Slurp all the UNENCODED data in, and put it in a scalar:
  51.    $string = $body->as_string;
  52.  
  53.    ### Slurp all the UNENCODED data in, and put it in an array of lines:
  54.    @lines = $body->as_lines;
  55.  
  56.  
  57. =head2 Working directly with paths to underlying files
  58.  
  59.    ### Where's the data?
  60.    if (defined($body->path)) {   ### data is on disk:
  61.        print "data is stored externally, in ", $body->path;
  62.    }
  63.    else {                        ### data is in core:
  64.        print "data is already in core, and is...\n", $body->as_string;
  65.    }
  66.  
  67.    ### Get rid of anything on disk:
  68.    $body->purge;
  69.  
  70.  
  71. =head1 DESCRIPTION
  72.  
  73. MIME messages can be very long (e.g., tar files, MPEGs, etc.) or very
  74. short (short textual notes, as in ordinary mail).  Long messages
  75. are best stored in files, while short ones are perhaps best stored
  76. in core.
  77.  
  78. This class is an attempt to define a common interface for objects
  79. which contain message data, regardless of how the data is
  80. physically stored.  The lifespan of a "body" object
  81. usually looks like this:
  82.  
  83. =over 4
  84.  
  85. =item 1.
  86.  
  87. B<Body object is created by a MIME::Parser during parsing.>
  88. It's at this point that the actual MIME::Body subclass is chosen,
  89. and new() is invoked.  (For example: if the body data is going to
  90. a file, then it is at this point that the class MIME::Body::File,
  91. and the filename, is chosen).
  92.  
  93. =item 2.
  94.  
  95. B<Data is written to the body> (usually by the MIME parser) like this:
  96. The body is opened for writing, via C<open("w")>.  This will trash any
  97. previous contents, and return an "I/O handle" opened for writing.
  98. Data is written to this I/O handle, via print().
  99. Then the I/O handle is closed, via close().
  100.  
  101. =item 3.
  102.  
  103. B<Data is read from the body> (usually by the user application) like this:
  104. The body is opened for reading by a user application, via C<open("r")>.
  105. This will return an "I/O handle" opened for reading.
  106. Data is read from the I/O handle, via read(), getline(), or getlines().
  107. Then the I/O handle is closed, via close().
  108.  
  109. =item 4.
  110.  
  111. B<Body object is destructed.>
  112.  
  113. =back
  114.  
  115. You can write your own subclasses, as long as they follow the
  116. interface described below.  Implementers of subclasses should assume
  117. that steps 2 and 3 may be repeated any number of times, and in
  118. different orders (e.g., 1-2-2-3-2-3-3-3-3-3-2-4).
  119.  
  120. In any case, once a MIME::Body has been created, you ask to open it
  121. for reading or writing, which gets you an "i/o handle": you then use
  122. the same mechanisms for reading from or writing to that handle, no matter
  123. what class it is.
  124.  
  125. Beware: unless you know for certain what kind of body you have, you
  126. should I<not> assume that the body has an underlying filehandle.
  127.  
  128.  
  129. =head1 PUBLIC INTERFACE
  130.  
  131. =over 4
  132.  
  133. =cut
  134.  
  135.  
  136. ### Pragmas:
  137. use strict;
  138. use vars qw($VERSION); 
  139.  
  140. ### System modules:
  141. use IO::Scalar;
  142. use Carp;
  143.  
  144. ### The package version, both in 1.23 style *and* usable by MakeMaker:
  145. $VERSION = substr q$Revision: 5.403 $, 10;
  146.  
  147.  
  148. #------------------------------
  149.  
  150. =item new ARGS...
  151.  
  152. I<Class method, constructor.>
  153. Create a new body.  Any ARGS are sent to init().
  154.  
  155. =cut
  156.  
  157. sub new {
  158.     my $self = bless {}, shift;
  159.     $self->init(@_);
  160.     $self;
  161. }
  162.  
  163. #------------------------------
  164.  
  165. =item init ARGS...
  166.  
  167. I<Instance method, abstract, initiallizer.>
  168. This is called automatically by C<new()>, with the arguments given
  169. to C<new()>.  The arguments are optional, and entirely up to the
  170. subclass.  The default method does nothing,
  171.  
  172. =cut
  173.  
  174. sub init { 1 }
  175.  
  176. #------------------------------
  177.  
  178. =item as_lines
  179.  
  180. I<Instance method.>
  181. Return the contents of the body as an array of lines (each terminated
  182. by a newline, with the possible exception of the final one).
  183. Returns empty on failure (NB: indistinguishable from an empty body!).
  184.  
  185. Note: the default method gets the data via
  186. repeated getline() calls; your subclass might wish to override this.
  187.  
  188. =cut
  189.  
  190. sub as_lines {
  191.     my $self = shift;
  192.     my @lines;
  193.     my $io = $self->open("r") || return ();
  194.     push @lines, $_ while (defined($_ = $io->getline()));
  195.     $io->close;
  196.     @lines;
  197. }
  198.  
  199. #------------------------------
  200.  
  201. =item as_string
  202.  
  203. I<Instance method.>
  204. Return the body data as a string (slurping it into core if necessary).
  205. Best not to do this unless you're I<sure> that the body is reasonably small!
  206. Returns empty string for an empty body, and undef on failure.
  207.  
  208. Note: the default method uses print(), which gets the data via
  209. repeated read() calls; your subclass might wish to override this.
  210.  
  211. =cut
  212.  
  213. sub as_string {
  214.     my $self = shift;
  215.     my $str = '';
  216.     my $out = new IO::Scalar \$str;
  217.     $self->print($out);
  218.     return $str;
  219. }
  220. *data = \&as_string;         ### silenty invoke preferred usage
  221.  
  222.  
  223. #------------------------------
  224.  
  225. =item binmode [ONOFF]
  226.  
  227. I<Instance method.>
  228. With argument, flags whether or not open() should return an I/O handle
  229. which has binmode() activated.  With no argument, just returns the
  230. current value.
  231.  
  232. =cut
  233.  
  234. sub binmode {
  235.     my ($self, $onoff) = @_;
  236.     $self->{MB_Binmode} = $onoff if (@_ > 1);
  237.     $self->{MB_Binmode};
  238. }
  239.  
  240. #------------------------------
  241.  
  242. =item dup
  243.  
  244. I<Instance method.>
  245. Duplicate the bodyhandle.
  246.  
  247. I<Beware:> external data in bodyhandles is I<not> copied to new files!
  248. Changing the data in one body's data file, or purging that body,
  249. I<will> affect its duplicate.  Bodies with in-core data probably need
  250. not worry.
  251.  
  252. =cut
  253.  
  254. sub dup {
  255.     my $self = shift;
  256.     bless { %$self }, ref($self);   ### shallow copy ok for ::File and ::Scalar
  257. }
  258.  
  259. #------------------------------
  260.  
  261. =item open READWRITE
  262.  
  263. I<Instance method, abstract.>
  264. This should do whatever is necessary to open the body for either
  265. writing (if READWRITE is "w") or reading (if mode is "r").
  266.  
  267. This method is expected to return an "I/O handle" object on success,
  268. and undef on error.  An I/O handle can be any object that supports a
  269. small set of standard methods for reading/writing data.
  270. See the IO::Handle class for an example.
  271.  
  272. =cut
  273.  
  274. sub open {
  275.     undef;
  276. }
  277.  
  278. #------------------------------
  279.  
  280. =item path [PATH]
  281.  
  282. I<Instance method.>
  283. If you're storing the body data externally (e.g., in a disk file), you'll
  284. want to give applications the ability to get at that data, for cleanup.
  285. This method should return the path to the data, or undef if there is none.
  286.  
  287. Where appropriate, the path I<should> be a simple string, like a filename.
  288. With argument, sets the PATH, which should be undef if there is none.
  289.  
  290. =cut
  291.  
  292. sub path {
  293.     my $self = shift;
  294.     $self->{MB_Path} = shift if @_;
  295.     $self->{MB_Path};
  296. }
  297.  
  298. #------------------------------
  299.  
  300. =item print FILEHANDLE
  301.  
  302. I<Instance method.>
  303. Output the body data to the given filehandle, or to the currently-selected
  304. one if none is given.
  305.  
  306. =cut
  307.  
  308. sub print {
  309.     my ($self, $fh) = @_;
  310.     my $nread;
  311.  
  312.     ### Get output filehandle, and ensure that it's a printable object:
  313.     $fh = IO::Wrap::wraphandle($fh || select);
  314.  
  315.     ### Write it:
  316.     my $buf = '';
  317.     my $io = $self->open("r") || return undef;
  318.     $fh->print($buf) while ($nread = $io->read($buf, 2048));
  319.     $io->close;
  320.     return defined($nread);    ### how'd we do?
  321. }
  322.  
  323. #------------------------------
  324.  
  325. =item purge
  326.  
  327. I<Instance method, abstract.>
  328. Remove any data which resides external to the program (e.g., in disk files).
  329. Immediately after a purge(), the path() should return undef to indicate
  330. that the external data is no longer available.
  331.  
  332. =cut
  333.  
  334. sub purge {
  335.     1;
  336. }
  337.  
  338.  
  339.  
  340. =back
  341.  
  342. =head1 SUBCLASSES
  343.  
  344. The following built-in classes are provided:
  345.  
  346.    Body                 Stores body     When open()ed,
  347.    class:               data in:        returns:
  348.    --------------------------------------------------------
  349.    MIME::Body::File     disk file       IO::Handle
  350.    MIME::Body::Scalar   scalar          IO::Scalar
  351.    MIME::Body::InCore   scalar array    IO::ScalarArray
  352.  
  353. =cut
  354.  
  355.  
  356. #------------------------------------------------------------
  357. package MIME::Body::File;
  358. #------------------------------------------------------------
  359.  
  360. =head2 MIME::Body::File
  361.  
  362. A body class that stores the data in a disk file.
  363. The I/O handle is a wrapped filehandle.  Invoke the constructor as:
  364.  
  365.     $body = new MIME::Body::File "/path/to/file";
  366.  
  367. In this case, the C<path()> method would return the given path,
  368. so you I<could> say:
  369.  
  370.     if (defined($body->path)) {
  371.     open BODY, $body->path or die "open: $!";
  372.     while (<BODY>) {
  373.         ### do stuff
  374.         }
  375.     close BODY;
  376.     }
  377.  
  378. But you're best off not doing this.
  379.  
  380. =cut
  381.  
  382.  
  383. ### Pragmas:
  384. use vars qw(@ISA);
  385. use strict;
  386.  
  387. ### System modules:
  388. require FileHandle;
  389.  
  390. ### Kit modules:
  391. use MIME::Tools qw(whine);
  392. use IO::Wrap;
  393.  
  394. @ISA = qw(MIME::Body);
  395.  
  396.  
  397. #------------------------------
  398. # init PATH
  399. #------------------------------
  400. sub init {
  401.     my ($self, $path) = @_;
  402.     $self->path($path);               ### use it as-is
  403.     $self;
  404. }
  405.  
  406. #------------------------------
  407. # open READWRITE
  408. #------------------------------
  409. sub open {
  410.     my ($self, $mode) = @_;
  411.     my $IO;
  412.     my $path = $self->path;
  413.     if ($mode eq 'w') {          ### writing
  414.     $IO = FileHandle->new(">$path") || die "write-open $path: $!";
  415.     }
  416.     elsif ($mode eq 'r') {       ### reading
  417.     $IO = FileHandle->new("<$path") || die "read-open $path: $!";
  418.     }
  419.     else {  
  420.     die "bad mode: '$mode'";
  421.     }
  422.     binmode($IO) if $self->binmode;        ### set binary read/write mode?
  423.     return (IO::Wrap::wraphandle($IO));    ### wrap if old FileHandle class
  424. }
  425.  
  426. #------------------------------
  427. # purge 
  428. #------------------------------
  429. # Unlink the path (and undefine it).
  430. #
  431. sub purge {
  432.     my $self = shift;
  433.     if (defined($self->path)) {
  434.     unlink $self->path or whine "couldn't unlink ".$self->path.": $!";
  435.     $self->path(undef);
  436.     }
  437.     1;
  438. }
  439.  
  440.  
  441.  
  442.  
  443. #------------------------------------------------------------
  444. package MIME::Body::Scalar;
  445. #------------------------------------------------------------
  446.  
  447. =head2 MIME::Body::Scalar
  448.  
  449. A body class that stores the data in-core, in a simple scalar.
  450. Invoke the constructor as:
  451.  
  452.     $body = new MIME::Body::Scalar \$string;
  453.  
  454. A single scalar argument sets the body to that value, exactly as though
  455. you'd opened for the body for writing, written the value,
  456. and closed the body again:
  457.  
  458.     $body = new MIME::Body::Scalar "Line 1\nLine 2\nLine 3";
  459.  
  460. A single array reference sets the body to the result of joining all the
  461. elements of that array together:
  462.  
  463.     $body = new MIME::Body::Scalar ["Line 1\n",
  464.                                     "Line 2\n",
  465.                                     "Line 3"];
  466.  
  467. Uses B<IO::Scalar> as the I/O handle.
  468.  
  469. =cut
  470.  
  471. use vars qw(@ISA);
  472. use strict;
  473.  
  474. require FileHandle;
  475.  
  476. use IO::Scalar;
  477. use Carp;
  478.  
  479. @ISA = qw(MIME::Body);
  480.  
  481.  
  482. #------------------------------
  483. # init DATA
  484. #------------------------------
  485. sub init {
  486.     my ($self, $data) = @_;
  487.     $data = join('', @$data)    if (ref($data) && (ref($data) eq 'ARRAY'));
  488.     $self->{MBS_Data} = (defined($data) ? $data : '');
  489.     $self;
  490. }
  491.  
  492. #------------------------------
  493. # as_string
  494. #------------------------------
  495. sub as_string {
  496.     shift->{MBS_Data};
  497. }
  498.  
  499. #------------------------------
  500. # open READWRITE
  501. #------------------------------
  502. sub open {
  503.     my ($self, $mode) = @_;
  504.     $self->{MBS_Data} = '' if ($mode eq 'w');        ### writing
  505.     return new IO::Scalar \($self->{MBS_Data});
  506. }
  507.  
  508.  
  509.  
  510.  
  511.  
  512. #------------------------------------------------------------
  513. package MIME::Body::InCore;
  514. #------------------------------------------------------------
  515.  
  516. =head2 MIME::Body::InCore
  517.  
  518. A body class that stores the data in-core.
  519. Invoke the constructor as:
  520.  
  521.     $body = new MIME::Body::InCore \$string;
  522.     $body = new MIME::Body::InCore  $string;
  523.     $body = new MIME::Body::InCore \@stringarray
  524.  
  525. A simple scalar argument sets the body to that value, exactly as though
  526. you'd opened for the body for writing, written the value,
  527. and closed the body again:
  528.  
  529.     $body = new MIME::Body::InCore "Line 1\nLine 2\nLine 3";
  530.  
  531. A single array reference sets the body to the concatenation of all
  532. scalars that it holds:
  533.  
  534.     $body = new MIME::Body::InCore ["Line 1\n",
  535.                                     "Line 2\n",
  536.                                     "Line 3"];
  537.  
  538. Uses B<IO::ScalarArray> as the I/O handle.
  539.  
  540. =cut
  541.  
  542. use vars qw(@ISA);
  543. use strict;
  544.  
  545. require FileHandle;
  546.  
  547. use IO::ScalarArray;
  548. use Carp;
  549.  
  550. @ISA = qw(MIME::Body);
  551.  
  552.  
  553. #------------------------------
  554. # init DATA
  555. #------------------------------
  556. sub init {
  557.     my ($self, $data) = @_;
  558.     if (!defined($data)) {  ### nothing
  559.     $self->{MBC_Data} = [];
  560.     }
  561.     elsif (!ref($data)) {   ### simple scalar
  562.     $self->{MBC_Data} = [ $data ];
  563.     }
  564.     elsif (ref($data) eq 'SCALAR') {
  565.     $self->{MBC_Data} = [ $$data ];
  566.     }
  567.     elsif (ref($data) eq 'ARRAY') {
  568.     $self->{MBC_Data} = $data;
  569.     }
  570.     else {
  571.     croak "I can't handle DATA which is a ".ref($data)."\n";
  572.     }
  573.     $self;
  574. }
  575.  
  576. #------------------------------
  577. # as_string
  578. #------------------------------
  579. sub as_string {
  580.     my $self = shift;
  581.     return join '', @{$self->{MBC_Data}};
  582. }
  583.  
  584. #------------------------------
  585. # open READWRITE
  586. #------------------------------
  587. sub open {
  588.     my ($self, $mode) = @_;
  589.     $self->{MBC_Data} = [] if ($mode eq 'w');        ### writing
  590.     return new IO::ScalarArray $self->{MBC_Data};
  591. }
  592.  
  593.  
  594. 1;
  595. __END__
  596.  
  597.  
  598. #------------------------------
  599.  
  600. =head2 Defining your own subclasses
  601.  
  602. So you're not happy with files and scalar-arrays?
  603. No problem: just define your own MIME::Body subclass, and make a subclass
  604. of MIME::Parser or MIME::ParserBase which returns an instance of your
  605. body class whenever appropriate in the C<new_body_for(head)> method.
  606.  
  607. Your "body" class must inherit from MIME::Body (or some subclass of it),
  608. and it must either provide (or inherit the default for) the following
  609. methods...
  610.  
  611. The default inherited method I<should suffice> for all these:
  612.  
  613.     new
  614.     binmode [ONOFF]
  615.     path
  616.  
  617. The default inherited method I<may suffice> for these, but perhaps
  618. there's a better implementation for your subclass.
  619.  
  620.     init ARGS...
  621.     as_lines
  622.     as_string
  623.     dup
  624.     print
  625.     purge
  626.  
  627. The default inherited method I<will probably not suffice> for these:
  628.  
  629.     open
  630.  
  631.  
  632.  
  633. =head1 NOTES
  634.  
  635. One reason I didn't just use FileHandle or IO::Handle objects for message
  636. bodies was that I wanted a "body" object to be a form of completely
  637. encapsulated program-persistent storage; that is, I wanted users
  638. to be able to write code like this...
  639.  
  640.    ### Get body handle from this MIME message, and read its data:
  641.    $body = $entity->bodyhandle;
  642.    $IO = $body->open("r");
  643.    while (defined($_ = $IO->getline)) {
  644.        print STDOUT $_;
  645.    }
  646.    $IO->close;
  647.  
  648. ...without requiring that they know anything more about how the
  649. $body object is actually storing its data (disk file, scalar variable,
  650. array variable, or whatever).
  651.  
  652. Storing the body of each MIME message in a persistently-open
  653. IO::Handle was a possibility, but it seemed like a bad idea,
  654. considering that a single multipart MIME message could easily suck up
  655. all the available file descriptors on some systems.  This risk increases
  656. if the user application is processing more than one MIME entity at a time.
  657.  
  658.  
  659.  
  660. =head1 AUTHOR
  661.  
  662. Eryq (F<eryq@zeegee.com>), ZeeGee Software Inc (F<http://www.zeegee.com>).
  663.  
  664. All rights reserved.  This program is free software; you can redistribute
  665. it and/or modify it under the same terms as Perl itself.
  666.  
  667. Thanks to Achim Bohnet for suggesting that MIME::Parser not be restricted
  668. to the use of FileHandles.
  669.  
  670.  
  671.  
  672. =head1 VERSION
  673.  
  674. $Revision: 5.403 $ $Date: 2000/11/04 19:54:46 $
  675.  
  676. =cut
  677.  
  678. #------------------------------
  679. 1;
  680.  
  681.