Debian lenny version packages
[pkg-perl] / deb-src / libarchive-zip-perl / libarchive-zip-perl-1.18 / lib / Archive / Zip.pm
1 package Archive::Zip;
2
3 # Copyright 2000 - 2002 Ned Konz. All rights reserved. This program is free
4 # software; you can redistribute it and/or modify it under the same terms as
5 # Perl itself.
6
7 # ----------------------------------------------------------------------
8 # class Archive::Zip
9 # Note that the package Archive::Zip exists only for exporting and
10 # sharing constants. Everything else is in another package
11 # in this file.
12 # Creation of a new Archive::Zip object actually creates a new object
13 # of class Archive::Zip::Archive.
14 # ----------------------------------------------------------------------
15
16 BEGIN {
17         require 5.003_96;
18 }
19 use strict;
20 use UNIVERSAL      ();
21 use Carp           ();
22 use IO::File       ();
23 use IO::Seekable   ();
24 use Compress::Zlib ();
25 use File::Spec     ();
26 use File::Temp     ();
27
28 use vars qw( $VERSION @ISA );
29 BEGIN {
30         $VERSION = '1.18';
31         $VERSION = eval $VERSION;
32
33         require Exporter;
34         @ISA = qw( Exporter );
35 }
36
37 use vars qw( $ChunkSize $ErrorHandler );
38
39 # This is the size we'll try to read, write, and (de)compress.
40 # You could set it to something different if you had lots of memory
41 # and needed more speed.
42 $ChunkSize = 32768;
43
44 $ErrorHandler = \&Carp::carp;
45
46 # BEGIN block is necessary here so that other modules can use the constants.
47 use vars qw( @EXPORT_OK %EXPORT_TAGS );
48 BEGIN {
49         @EXPORT_OK   = ('computeCRC32');
50         %EXPORT_TAGS = (
51                 CONSTANTS => [ qw(
52                         FA_MSDOS
53                         FA_UNIX
54                         GPBF_ENCRYPTED_MASK
55                         GPBF_DEFLATING_COMPRESSION_MASK
56                         GPBF_HAS_DATA_DESCRIPTOR_MASK
57                         COMPRESSION_STORED
58                         COMPRESSION_DEFLATED
59                         COMPRESSION_LEVEL_NONE
60                         COMPRESSION_LEVEL_DEFAULT
61                         COMPRESSION_LEVEL_FASTEST
62                         COMPRESSION_LEVEL_BEST_COMPRESSION
63                         IFA_TEXT_FILE_MASK
64                         IFA_TEXT_FILE
65                         IFA_BINARY_FILE
66                         ) ],
67
68                 MISC_CONSTANTS => [ qw(
69                         FA_AMIGA
70                         FA_VAX_VMS
71                         FA_VM_CMS
72                         FA_ATARI_ST
73                         FA_OS2_HPFS
74                         FA_MACINTOSH
75                         FA_Z_SYSTEM
76                         FA_CPM
77                         FA_TOPS20
78                         FA_WINDOWS_NTFS
79                         FA_QDOS
80                         FA_ACORN
81                         FA_VFAT
82                         FA_MVS
83                         FA_BEOS
84                         FA_TANDEM
85                         FA_THEOS
86                         GPBF_IMPLODING_8K_SLIDING_DICTIONARY_MASK
87                         GPBF_IMPLODING_3_SHANNON_FANO_TREES_MASK
88                         GPBF_IS_COMPRESSED_PATCHED_DATA_MASK
89                         COMPRESSION_SHRUNK
90                         DEFLATING_COMPRESSION_NORMAL
91                         DEFLATING_COMPRESSION_MAXIMUM
92                         DEFLATING_COMPRESSION_FAST
93                         DEFLATING_COMPRESSION_SUPER_FAST
94                         COMPRESSION_REDUCED_1
95                         COMPRESSION_REDUCED_2
96                         COMPRESSION_REDUCED_3
97                         COMPRESSION_REDUCED_4
98                         COMPRESSION_IMPLODED
99                         COMPRESSION_TOKENIZED
100                         COMPRESSION_DEFLATED_ENHANCED
101                         COMPRESSION_PKWARE_DATA_COMPRESSION_LIBRARY_IMPLODED
102                         ) ],
103
104                 ERROR_CODES => [ qw(
105                         AZ_OK
106                         AZ_STREAM_END
107                         AZ_ERROR
108                         AZ_FORMAT_ERROR
109                         AZ_IO_ERROR
110                         ) ],
111
112                 # For Internal Use Only
113                 PKZIP_CONSTANTS => [ qw(
114                         SIGNATURE_FORMAT
115                         SIGNATURE_LENGTH
116                         LOCAL_FILE_HEADER_SIGNATURE
117                         LOCAL_FILE_HEADER_FORMAT
118                         LOCAL_FILE_HEADER_LENGTH
119                         CENTRAL_DIRECTORY_FILE_HEADER_SIGNATURE
120                         DATA_DESCRIPTOR_FORMAT
121                         DATA_DESCRIPTOR_LENGTH
122                         DATA_DESCRIPTOR_SIGNATURE
123                         DATA_DESCRIPTOR_FORMAT_NO_SIG
124                         DATA_DESCRIPTOR_LENGTH_NO_SIG
125                         CENTRAL_DIRECTORY_FILE_HEADER_FORMAT
126                         CENTRAL_DIRECTORY_FILE_HEADER_LENGTH
127                         END_OF_CENTRAL_DIRECTORY_SIGNATURE
128                         END_OF_CENTRAL_DIRECTORY_SIGNATURE_STRING
129                         END_OF_CENTRAL_DIRECTORY_FORMAT
130                         END_OF_CENTRAL_DIRECTORY_LENGTH
131                         ) ],
132
133                 # For Internal Use Only
134                 UTILITY_METHODS => [ qw(
135                         _error
136                         _printError
137                         _ioError
138                         _formatError
139                         _subclassResponsibility
140                         _binmode
141                         _isSeekable
142                         _newFileHandle
143                         _readSignature
144                         _asZipDirName
145                         ) ],
146         );
147
148         # Add all the constant names and error code names to @EXPORT_OK
149         Exporter::export_ok_tags( qw(
150                 CONSTANTS
151                 ERROR_CODES
152                 PKZIP_CONSTANTS
153                 UTILITY_METHODS
154                 MISC_CONSTANTS
155                 ) );
156
157 }
158
159 # Error codes
160 use constant AZ_OK           => 0;
161 use constant AZ_STREAM_END   => 1;
162 use constant AZ_ERROR        => 2;
163 use constant AZ_FORMAT_ERROR => 3;
164 use constant AZ_IO_ERROR     => 4;
165
166 # File types
167 # Values of Archive::Zip::Member->fileAttributeFormat()
168
169 use constant FA_MSDOS        => 0;
170 use constant FA_AMIGA        => 1;
171 use constant FA_VAX_VMS      => 2;
172 use constant FA_UNIX         => 3;
173 use constant FA_VM_CMS       => 4;
174 use constant FA_ATARI_ST     => 5;
175 use constant FA_OS2_HPFS     => 6;
176 use constant FA_MACINTOSH    => 7;
177 use constant FA_Z_SYSTEM     => 8;
178 use constant FA_CPM          => 9;
179 use constant FA_TOPS20       => 10;
180 use constant FA_WINDOWS_NTFS => 11;
181 use constant FA_QDOS         => 12;
182 use constant FA_ACORN        => 13;
183 use constant FA_VFAT         => 14;
184 use constant FA_MVS          => 15;
185 use constant FA_BEOS         => 16;
186 use constant FA_TANDEM       => 17;
187 use constant FA_THEOS        => 18;
188
189 # general-purpose bit flag masks
190 # Found in Archive::Zip::Member->bitFlag()
191
192 use constant GPBF_ENCRYPTED_MASK             => 1 << 0;
193 use constant GPBF_DEFLATING_COMPRESSION_MASK => 3 << 1;
194 use constant GPBF_HAS_DATA_DESCRIPTOR_MASK   => 1 << 3;
195
196 # deflating compression types, if compressionMethod == COMPRESSION_DEFLATED
197 # ( Archive::Zip::Member->bitFlag() & GPBF_DEFLATING_COMPRESSION_MASK )
198
199 use constant DEFLATING_COMPRESSION_NORMAL     => 0 << 1;
200 use constant DEFLATING_COMPRESSION_MAXIMUM    => 1 << 1;
201 use constant DEFLATING_COMPRESSION_FAST       => 2 << 1;
202 use constant DEFLATING_COMPRESSION_SUPER_FAST => 3 << 1;
203
204 # compression method
205
206 # these two are the only ones supported in this module
207 use constant COMPRESSION_STORED                 => 0; # file is stored (no compression)
208 use constant COMPRESSION_DEFLATED               => 8; # file is Deflated
209 use constant COMPRESSION_LEVEL_NONE             => 0;
210 use constant COMPRESSION_LEVEL_DEFAULT          => -1;
211 use constant COMPRESSION_LEVEL_FASTEST          => 1;
212 use constant COMPRESSION_LEVEL_BEST_COMPRESSION => 9;
213
214 # internal file attribute bits
215 # Found in Archive::Zip::Member::internalFileAttributes()
216
217 use constant IFA_TEXT_FILE_MASK => 1;
218 use constant IFA_TEXT_FILE      => 1;
219 use constant IFA_BINARY_FILE    => 0;
220
221 # PKZIP file format miscellaneous constants (for internal use only)
222 use constant SIGNATURE_FORMAT   => "V";
223 use constant SIGNATURE_LENGTH   => 4;
224
225 # these lengths are without the signature.
226 use constant LOCAL_FILE_HEADER_SIGNATURE   => 0x04034b50;
227 use constant LOCAL_FILE_HEADER_FORMAT      => "v3 V4 v2";
228 use constant LOCAL_FILE_HEADER_LENGTH      => 26;
229
230 # PKZIP docs don't mention the signature, but Info-Zip writes it.
231 use constant DATA_DESCRIPTOR_SIGNATURE     => 0x08074b50;
232 use constant DATA_DESCRIPTOR_FORMAT        => "V3";
233 use constant DATA_DESCRIPTOR_LENGTH        => 12;
234
235 # but the signature is apparently optional.
236 use constant DATA_DESCRIPTOR_FORMAT_NO_SIG => "V2";
237 use constant DATA_DESCRIPTOR_LENGTH_NO_SIG => 8;
238
239 use constant CENTRAL_DIRECTORY_FILE_HEADER_SIGNATURE  => 0x02014b50;
240 use constant CENTRAL_DIRECTORY_FILE_HEADER_FORMAT     => "C2 v3 V4 v5 V2";
241 use constant CENTRAL_DIRECTORY_FILE_HEADER_LENGTH     => 42;
242
243 use constant END_OF_CENTRAL_DIRECTORY_SIGNATURE        => 0x06054b50;
244 use constant END_OF_CENTRAL_DIRECTORY_SIGNATURE_STRING =>
245         pack( "V", END_OF_CENTRAL_DIRECTORY_SIGNATURE );
246 use constant END_OF_CENTRAL_DIRECTORY_FORMAT           => "v4 V2 v";
247 use constant END_OF_CENTRAL_DIRECTORY_LENGTH           => 18;
248
249 use constant GPBF_IMPLODING_8K_SLIDING_DICTIONARY_MASK => 1 << 1;
250 use constant GPBF_IMPLODING_3_SHANNON_FANO_TREES_MASK  => 1 << 2;
251 use constant GPBF_IS_COMPRESSED_PATCHED_DATA_MASK      => 1 << 5;
252
253 # the rest of these are not supported in this module
254 use constant COMPRESSION_SHRUNK    => 1;    # file is Shrunk
255 use constant COMPRESSION_REDUCED_1 => 2;    # file is Reduced CF=1
256 use constant COMPRESSION_REDUCED_2 => 3;    # file is Reduced CF=2
257 use constant COMPRESSION_REDUCED_3 => 4;    # file is Reduced CF=3
258 use constant COMPRESSION_REDUCED_4 => 5;    # file is Reduced CF=4
259 use constant COMPRESSION_IMPLODED  => 6;    # file is Imploded
260 use constant COMPRESSION_TOKENIZED => 7;    # reserved for Tokenizing compr.
261 use constant COMPRESSION_DEFLATED_ENHANCED => 9;   # reserved for enh. Deflating
262 use constant COMPRESSION_PKWARE_DATA_COMPRESSION_LIBRARY_IMPLODED => 10;
263
264 # Load the various required classes
265 require Archive::Zip::Archive;
266 require Archive::Zip::Member;
267 require Archive::Zip::FileMember;
268 require Archive::Zip::DirectoryMember;
269 require Archive::Zip::ZipFileMember;
270 require Archive::Zip::NewFileMember;
271 require Archive::Zip::StringMember;
272
273 use constant ZIPARCHIVECLASS => 'Archive::Zip::Archive';
274 use constant ZIPMEMBERCLASS  => 'Archive::Zip::Member';
275
276 sub new    
277 {
278         my $class = shift;
279         return $class->ZIPARCHIVECLASS->new(@_);
280 }
281
282 sub computeCRC32    
283 {
284         my $data = shift;
285         $data = shift if ref($data);    # allow calling as an obj method
286         my $crc = shift;
287         return Compress::Zlib::crc32( $data, $crc );
288 }
289
290 # Report or change chunk size used for reading and writing.
291 # Also sets Zlib's default buffer size (eventually).
292 sub setChunkSize    
293 {
294         my $chunkSize = shift;
295         $chunkSize = shift if ref($chunkSize);    # object method on zip?
296         my $oldChunkSize = $Archive::Zip::ChunkSize;
297         $Archive::Zip::ChunkSize = $chunkSize if ($chunkSize);
298         return $oldChunkSize;
299 }
300
301 sub chunkSize    
302 {
303         return $Archive::Zip::ChunkSize;
304 }
305
306 sub setErrorHandler (&)    
307 {
308         my $errorHandler = shift;
309         $errorHandler = \&Carp::carp unless defined($errorHandler);
310         my $oldErrorHandler = $Archive::Zip::ErrorHandler;
311         $Archive::Zip::ErrorHandler = $errorHandler;
312         return $oldErrorHandler;
313 }
314
315 # ----------------------------------------------------------------------
316 # Private utility functions (not methods).
317 # ----------------------------------------------------------------------
318
319 sub _printError    
320 {
321         my $string = join ( ' ', @_, "\n" );
322         my $oldCarpLevel = $Carp::CarpLevel;
323         $Carp::CarpLevel += 2;
324         &{$ErrorHandler} ($string);
325         $Carp::CarpLevel = $oldCarpLevel;
326 }
327
328 # This is called on format errors.
329 sub _formatError    
330 {
331         shift if ref( $_[0] );
332         _printError( 'format error:', @_ );
333         return AZ_FORMAT_ERROR;
334 }
335
336 # This is called on IO errors.
337 sub _ioError    
338 {
339         shift if ref( $_[0] );
340         _printError( 'IO error:', @_, ':', $! );
341         return AZ_IO_ERROR;
342 }
343
344 # This is called on generic errors.
345 sub _error    
346 {
347         shift if ref( $_[0] );
348         _printError( 'error:', @_ );
349         return AZ_ERROR;
350 }
351
352 # Called when a subclass should have implemented
353 # something but didn't
354 sub _subclassResponsibility    
355 {
356         Carp::croak("subclass Responsibility\n");
357 }
358
359 # Try to set the given file handle or object into binary mode.
360 sub _binmode    
361 {
362         my $fh = shift;
363         return UNIVERSAL::can( $fh, 'binmode' ) ? $fh->binmode() : binmode($fh);
364 }
365
366 # Attempt to guess whether file handle is seekable.
367 # Because of problems with Windoze, this only returns true when
368 # the file handle is a real file.  
369 sub _isSeekable    
370 {
371         my $fh = shift;
372         if ( UNIVERSAL::isa($fh, 'IO::Scalar') ) {
373                 return 0;
374         }
375         if ( UNIVERSAL::isa($fh, 'IO::String') ) {
376                 return 1;
377         }
378         if ( UNIVERSAL::isa($fh, 'IO::Seekable') ) {
379                 # Unfortunately, some things like FileHandle objects
380                 # return true for Seekable, but AREN'T!!!!!
381                 if ( UNIVERSAL::isa($fh, 'FileHandle') ) {
382                         return 0;
383                 }
384                 return 1;
385         }
386         if ( UNIVERSAL::can($fh, 'stat') ) {
387                 return -f $fh;
388         }
389         return (
390                 UNIVERSAL::can($fh, 'seek') and UNIVERSAL::can($fh, 'tell')
391                 ) ? 1 : 0;
392 }
393
394 # Return an opened IO::Handle
395 # my ( $status, fh ) = _newFileHandle( 'fileName', 'w' );
396 # Can take a filename, file handle, or ref to GLOB
397 # Or, if given something that is a ref but not an IO::Handle,
398 # passes back the same thing.
399 sub _newFileHandle    
400 {
401         my $fd     = shift;
402         my $status = 1;
403         my $handle;
404
405         if ( ref($fd) )
406         {
407                 if ( UNIVERSAL::isa( $fd, 'IO::Scalar' )
408                         or UNIVERSAL::isa( $fd, 'IO::String' ) )
409                 {
410                         $handle = $fd;
411                 }
412                 elsif ( UNIVERSAL::isa( $fd, 'IO::Handle' )
413                         or UNIVERSAL::isa( $fd, 'GLOB' ) )
414                 {
415                         $handle = IO::File->new();
416                         $status = $handle->fdopen( $fd, @_ );
417                 }
418                 else
419                 {
420                         $handle = $fd;
421                 }
422         }
423         else
424         {
425                 $handle = IO::File->new();
426                 $status = $handle->open( $fd, @_ );
427         }
428
429         return ( $status, $handle );
430 }
431
432 # Returns next signature from given file handle, leaves
433 # file handle positioned afterwards.
434 # In list context, returns ($status, $signature)
435 # ( $status, $signature) = _readSignature( $fh, $fileName );
436
437 sub _readSignature    
438 {
439         my $fh                = shift;
440         my $fileName          = shift;
441         my $expectedSignature = shift;    # optional
442
443         my $signatureData;
444         my $bytesRead = $fh->read( $signatureData, SIGNATURE_LENGTH );
445         return _ioError("reading header signature")
446           if $bytesRead != SIGNATURE_LENGTH;
447         my $signature = unpack( SIGNATURE_FORMAT, $signatureData );
448         my $status    = AZ_OK;
449
450         # compare with expected signature, if any, or any known signature.
451         if ( ( defined($expectedSignature) && $signature != $expectedSignature )
452                 || ( !defined($expectedSignature)
453                         && $signature != CENTRAL_DIRECTORY_FILE_HEADER_SIGNATURE
454                         && $signature != LOCAL_FILE_HEADER_SIGNATURE
455                         && $signature != END_OF_CENTRAL_DIRECTORY_SIGNATURE
456                         && $signature != DATA_DESCRIPTOR_SIGNATURE ) )
457         {
458                 my $errmsg = sprintf( "bad signature: 0x%08x", $signature );
459                 if ( _isSeekable($fh) )
460                 {
461                         $errmsg .=
462                           sprintf( " at offset %d", $fh->tell() - SIGNATURE_LENGTH );
463                 }
464
465                 $status = _formatError("$errmsg in file $fileName");
466         }
467
468         return ( $status, $signature );
469 }
470
471 # Utility method to make and open a temp file.
472 # Will create $temp_dir if it doesn't exist.
473 # Returns file handle and name:
474 #
475 # my ($fh, $name) = Archive::Zip::tempFile();
476 # my ($fh, $name) = Archive::Zip::tempFile('mytempdir');
477 #
478
479 sub tempFile    
480 {
481         my $dir = shift;
482         my ( $fh, $filename ) = File::Temp::tempfile(
483                 SUFFIX => '.zip',
484                 UNLINK => 0,        # we will delete it!
485                 $dir ? ( DIR => $dir ) : ()
486         );
487         return ( undef, undef ) unless $fh;
488         my ( $status, $newfh ) = _newFileHandle( $fh, 'w+' );
489         return ( $newfh, $filename );
490 }
491
492 # Return the normalized directory name as used in a zip file (path
493 # separators become slashes, etc.). 
494 # Will translate internal slashes in path components (i.e. on Macs) to
495 # underscores.  Discards volume names.
496 # When $forceDir is set, returns paths with trailing slashes (or arrays
497 # with trailing blank members).
498 #
499 # If third argument is a reference, returns volume information there.
500 #
501 # input         output
502 # .                             ('.')   '.'
503 # ./a                   ('a')   a
504 # ./a/b                 ('a','b')       a/b
505 # ./a/b/                ('a','b')       a/b
506 # a/b/                  ('a','b')       a/b
507 # /a/b/                 ('','a','b')    /a/b
508 # c:\a\b\c.doc  ('','a','b','c.doc')    /a/b/c.doc              # on Windoze
509 # "i/o maps:whatever"   ('i_o maps', 'whatever')  "i_o maps/whatever"   # on Macs
510 sub _asZipDirName    
511 {
512         my $name      = shift;
513         my $forceDir  = shift;
514         my $volReturn = shift;
515         my ( $volume, $directories, $file ) =
516           File::Spec->splitpath( File::Spec->canonpath($name), $forceDir );
517         $$volReturn = $volume if ( ref($volReturn) );
518         my @dirs = map { $_ =~ s{/}{_}g; $_ } File::Spec->splitdir($directories);
519         if ( @dirs > 0 ) { pop (@dirs) unless $dirs[-1] }   # remove empty component
520         push ( @dirs, $file || '' );
521         #return wantarray ? @dirs : join ( '/', @dirs );
522     return join ( '/', @dirs );
523 }
524
525 # Return an absolute local name for a zip name.
526 # Assume a directory if zip name has trailing slash.
527 # Takes an optional volume name in FS format (like 'a:').
528 #
529 sub _asLocalName    
530 {
531         my $name   = shift;    # zip format
532         my $volume = shift;
533         $volume = '' unless defined($volume);    # local FS format
534
535         my @paths = split ( /\//, $name );
536         my $filename = pop (@paths);
537         $filename = '' unless defined($filename);
538         my $localDirs = @paths?File::Spec->catdir(@paths):'';
539         my $localName = File::Spec->catpath( $volume, $localDirs, $filename );
540         $localName = File::Spec->rel2abs($localName) unless $volume;
541         return $localName;
542 }
543
544 1;
545
546 __END__
547
548 =pod
549
550 =head1 NAME
551
552 Archive::Zip - Provide an interface to ZIP archive files.
553
554 =head1 SYNOPSIS
555
556    # Create a Zip file
557    use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
558    my $zip = Archive::Zip->new();
559    
560    # Add a directory
561    my $dir_member = $zip->addDirectory( 'dirname/' );
562    
563    # Add a file from a string with compression
564    my $string_member = $zip->addString( 'This is a test', 'stringMember.txt' );
565    $string_member->desiredCompressionMethod( COMPRESSION_DEFLATED );
566    
567    # Add a file from disk
568    my $file_member = $zip->addFile( 'xyz.pl', 'AnotherName.pl' );
569    
570    # Save the Zip file
571    unless ( $zip->writeToFileNamed('someZip.zip') == AZ_OK ) {
572        die 'write error';
573    }
574    
575    # Read a Zip file
576    my $somezip = Archive::Zip->new();
577    unless ( $somezip->read( 'someZip.zip' ) == AZ_OK ) {
578        die 'read error';
579    }
580    
581    # Change the compression type for a file in the Zip
582    my $member = $somezip->memberNamed( 'stringMember.txt' );
583    $member->desiredCompressionMethod( COMPRESSION_STORED );
584    unless ( $zip->writeToFileNamed( 'someOtherZip.zip' ) == AZ_OK ) {
585        die 'write error';
586    }
587
588 =head1 DESCRIPTION
589
590 The Archive::Zip module allows a Perl program to create, manipulate, read,
591 and write Zip archive files.
592
593 Zip archives can be created, or you can read from existing zip files.
594
595 Once created, they can be written to files, streams, or strings. Members
596 can be added, removed, extracted, replaced, rearranged, and enumerated.
597 They can also be renamed or have their dates, comments, or other attributes
598 queried or modified. Their data can be compressed or uncompressed as needed.
599
600 Members can be created from members in existing Zip files, or from existing
601 directories, files, or strings.
602
603 This module uses the L<Compress::Zlib> library to read and write the
604 compressed streams inside the files.
605
606 =head2 File Naming
607
608 Regardless of what your local file system uses for file naming, names in a
609 Zip file are in Unix format (I<forward> slashes (/) separating directory
610 names, etc.).
611
612 C<Archive::Zip> tries to be consistent with file naming conventions, and will
613 translate back and forth between native and Zip file names.
614
615 However, it can't guess which format names are in. So two rules control what
616 kind of file name you must pass various routines:
617
618 =over 4
619
620 =item Names of files are in local format.
621
622 C<File::Spec> and C<File::Basename> are used for various file
623 operations. When you're referring to a file on your system, use its
624 file naming conventions.
625
626 =item Names of archive members are in Unix format.
627
628 This applies to every method that refers to an archive member, or
629 provides a name for new archive members. The C<extract()> methods
630 that can take one or two names will convert from local to zip names
631 if you call them with a single name.
632
633 =back
634
635 =head2 Archive::Zip Object Model
636
637 =head2 Overview
638
639 Archive::Zip::Archive objects are what you ordinarily deal with.
640 These maintain the structure of a zip file, without necessarily
641 holding data. When a zip is read from a disk file, the (possibly
642 compressed) data still lives in the file, not in memory. Archive
643 members hold information about the individual members, but not
644 (usually) the actual member data. When the zip is written to a
645 (different) file, the member data is compressed or copied as needed.
646 It is possible to make archive members whose data is held in a string
647 in memory, but this is not done when a zip file is read. Directory
648 members don't have any data.
649
650 =head2 Inheritance
651
652   Exporter
653    Archive::Zip                            Common base class, has defs.
654        Archive::Zip::Archive               A Zip archive.
655        Archive::Zip::Member                Abstract superclass for all members.
656            Archive::Zip::StringMember      Member made from a string
657            Archive::Zip::FileMember        Member made from an external file
658                Archive::Zip::ZipFileMember Member that lives in a zip file
659                Archive::Zip::NewFileMember Member whose data is in a file
660            Archive::Zip::DirectoryMember   Member that is a directory
661
662 =head1 EXPORTS
663
664 =over 4
665
666 =item :CONSTANTS
667
668 Exports the following constants:
669
670 FA_MSDOS FA_UNIX GPBF_ENCRYPTED_MASK
671 GPBF_DEFLATING_COMPRESSION_MASK GPBF_HAS_DATA_DESCRIPTOR_MASK
672 COMPRESSION_STORED COMPRESSION_DEFLATED IFA_TEXT_FILE_MASK
673 IFA_TEXT_FILE IFA_BINARY_FILE COMPRESSION_LEVEL_NONE
674 COMPRESSION_LEVEL_DEFAULT COMPRESSION_LEVEL_FASTEST
675 COMPRESSION_LEVEL_BEST_COMPRESSION
676
677 =item :MISC_CONSTANTS
678
679 Exports the following constants (only necessary for extending the
680 module):
681
682 FA_AMIGA FA_VAX_VMS FA_VM_CMS FA_ATARI_ST FA_OS2_HPFS
683 FA_MACINTOSH FA_Z_SYSTEM FA_CPM FA_WINDOWS_NTFS
684 GPBF_IMPLODING_8K_SLIDING_DICTIONARY_MASK
685 GPBF_IMPLODING_3_SHANNON_FANO_TREES_MASK
686 GPBF_IS_COMPRESSED_PATCHED_DATA_MASK COMPRESSION_SHRUNK
687 DEFLATING_COMPRESSION_NORMAL DEFLATING_COMPRESSION_MAXIMUM
688 DEFLATING_COMPRESSION_FAST DEFLATING_COMPRESSION_SUPER_FAST
689 COMPRESSION_REDUCED_1 COMPRESSION_REDUCED_2 COMPRESSION_REDUCED_3
690 COMPRESSION_REDUCED_4 COMPRESSION_IMPLODED COMPRESSION_TOKENIZED
691 COMPRESSION_DEFLATED_ENHANCED
692 COMPRESSION_PKWARE_DATA_COMPRESSION_LIBRARY_IMPLODED
693
694 =item :ERROR_CODES
695
696 Explained below. Returned from most methods.
697
698 AZ_OK AZ_STREAM_END AZ_ERROR AZ_FORMAT_ERROR AZ_IO_ERROR
699
700 =back
701
702 =head1 ERROR CODES
703
704 Many of the methods in Archive::Zip return error codes. These are implemented
705 as inline subroutines, using the C<use constant> pragma. They can be imported
706 into your namespace using the C<:ERROR_CODES> tag:
707
708   use Archive::Zip qw( :ERROR_CODES );
709   
710   ...
711   
712   unless ( $zip->read( 'myfile.zip' ) == AZ_OK ) {
713       die "whoops!";
714   }
715
716 =over 4
717
718 =item AZ_OK (0)
719
720 Everything is fine.
721
722 =item AZ_STREAM_END (1)
723
724 The read stream (or central directory) ended normally.
725
726 =item AZ_ERROR (2)
727
728 There was some generic kind of error.
729
730 =item AZ_FORMAT_ERROR (3)
731
732 There is a format error in a ZIP file being read.
733
734 =item AZ_IO_ERROR (4)
735
736 There was an IO error.
737
738 =back
739
740 =head2 Compression
741
742 Archive::Zip allows each member of a ZIP file to be compressed (using the
743 Deflate algorithm) or uncompressed.
744
745 Other compression algorithms that some versions of ZIP have been able to
746 produce are not supported. Each member has two compression methods: the
747 one it's stored as (this is always COMPRESSION_STORED for string and external
748 file members), and the one you desire for the member in the zip file.
749
750 These can be different, of course, so you can make a zip member that is not
751 compressed out of one that is, and vice versa.
752
753 You can inquire about the current compression and set the desired
754 compression method:
755
756   my $member = $zip->memberNamed( 'xyz.txt' );
757   $member->compressionMethod();    # return current compression
758   
759   # set to read uncompressed
760   $member->desiredCompressionMethod( COMPRESSION_STORED );
761   
762   # set to read compressed
763   $member->desiredCompressionMethod( COMPRESSION_DEFLATED );
764
765 There are two different compression methods:
766
767 =over 4
768
769 =item COMPRESSION_STORED
770
771 File is stored (no compression)
772
773 =item COMPRESSION_DEFLATED
774
775 File is Deflated
776
777 =back
778
779 =head2 Compression Levels
780
781 If a member's desiredCompressionMethod is COMPRESSION_DEFLATED, you
782 can choose different compression levels. This choice may affect the
783 speed of compression and decompression, as well as the size of the
784 compressed member data.
785
786   $member->desiredCompressionLevel( 9 );
787
788 The levels given can be:
789
790 =over 4
791
792 =item 0 or COMPRESSION_LEVEL_NONE
793
794 This is the same as saying
795
796   $member->desiredCompressionMethod( COMPRESSION_STORED );
797
798 =item 1 .. 9
799
800 1 gives the best speed and worst compression, and 9 gives the
801 best compression and worst speed.
802
803 =item COMPRESSION_LEVEL_FASTEST
804
805 This is a synonym for level 1.
806
807 =item COMPRESSION_LEVEL_BEST_COMPRESSION
808
809 This is a synonym for level 9.
810
811 =item COMPRESSION_LEVEL_DEFAULT
812
813 This gives a good compromise between speed and compression,
814 and is currently equivalent to 6 (this is in the zlib code).
815 This is the level that will be used if not specified.
816
817 =back
818
819 =head1 Archive::Zip Methods
820
821 The Archive::Zip class (and its invisible subclass Archive::Zip::Archive)
822 implement generic zip file functionality. Creating a new Archive::Zip object
823 actually makes an Archive::Zip::Archive object, but you don't have to worry
824 about this unless you're subclassing.
825
826 =head2 Constructor
827
828 =over 4
829
830 =item new( [$fileName] )
831
832 Make a new, empty zip archive.
833
834     my $zip = Archive::Zip->new();
835
836 If an additional argument is passed, new() will call read()
837 to read the contents of an archive:
838
839     my $zip = Archive::Zip->new( 'xyz.zip' );
840
841 If a filename argument is passed and the read fails for any
842 reason, new will return undef. For this reason, it may be
843 better to call read separately.
844
845 =back
846
847 =head2 Zip Archive Utility Methods
848
849 These Archive::Zip methods may be called as functions or as object
850 methods. Do not call them as class methods:
851
852     $zip = Archive::Zip->new();
853     $crc = Archive::Zip::computeCRC32( 'ghijkl' );    # OK
854     $crc = $zip->computeCRC32( 'ghijkl' );            # also OK
855     $crc = Archive::Zip->computeCRC32( 'ghijkl' );    # NOT OK
856
857 =over 4
858
859 =item Archive::Zip::computeCRC32( $string [, $crc] )
860
861 This is a utility function that uses the Compress::Zlib CRC
862 routine to compute a CRC-32. You can get the CRC of a string:
863
864     $crc = Archive::Zip::computeCRC32( $string );
865
866 Or you can compute the running CRC:
867
868     $crc = 0;
869     $crc = Archive::Zip::computeCRC32( 'abcdef', $crc );
870     $crc = Archive::Zip::computeCRC32( 'ghijkl', $crc );
871
872 =item Archive::Zip::setChunkSize( $number )
873
874 Report or change chunk size used for reading and writing.
875 This can make big differences in dealing with large files.
876 Currently, this defaults to 32K. This also changes the chunk
877 size used for Compress::Zlib. You must call setChunkSize()
878 before reading or writing. This is not exportable, so you
879 must call it like:
880
881     Archive::Zip::setChunkSize( 4096 );
882
883 or as a method on a zip (though this is a global setting).
884 Returns old chunk size.
885
886 =item Archive::Zip::chunkSize()
887
888 Returns the current chunk size:
889
890     my $chunkSize = Archive::Zip::chunkSize();
891
892 =item Archive::Zip::setErrorHandler( \&subroutine )
893
894 Change the subroutine called with error strings. This
895 defaults to \&Carp::carp, but you may want to change it to
896 get the error strings. This is not exportable, so you must
897 call it like:
898
899     Archive::Zip::setErrorHandler( \&myErrorHandler );
900
901 If myErrorHandler is undef, resets handler to default.
902 Returns old error handler. Note that if you call Carp::carp
903 or a similar routine or if you're chaining to the default
904 error handler from your error handler, you may want to
905 increment the number of caller levels that are skipped (do
906 not just set it to a number):
907
908     $Carp::CarpLevel++;
909
910 =item Archive::Zip::tempFile( [$tmpdir] )
911
912 Create a uniquely named temp file. It will be returned open
913 for read/write. If C<$tmpdir> is given, it is used as the
914 name of a directory to create the file in. If not given,
915 creates the file using C<File::Spec::tmpdir()>. Generally, you can
916 override this choice using the
917
918     $ENV{TMPDIR}
919
920 environment variable. But see the L<File::Spec|File::Spec>
921 documentation for your system. Note that on many systems, if you're
922 running in taint mode, then you must make sure that C<$ENV{TMPDIR}> is
923 untainted for it to be used.
924 Will I<NOT> create C<$tmpdir> if it doesn't exist (this is a change
925 from prior versions!). Returns file handle and name:
926
927     my ($fh, $name) = Archive::Zip::tempFile();
928     my ($fh, $name) = Archive::Zip::tempFile('myTempDir');
929     my $fh = Archive::Zip::tempFile();  # if you don't need the name
930
931 =back
932
933 =head2 Zip Archive Accessors
934
935 =over 4
936
937 =item members()
938
939 Return a copy of the members array
940
941     my @members = $zip->members();
942
943 =item numberOfMembers()
944
945 Return the number of members I have
946
947 =item memberNames()
948
949 Return a list of the (internal) file names of the zip members
950
951 =item memberNamed( $string )
952
953 Return ref to member whose filename equals given filename or
954 undef. C<$string> must be in Zip (Unix) filename format.
955
956 =item membersMatching( $regex )
957
958 Return array of members whose filenames match given regular
959 expression in list context. Returns number of matching
960 members in scalar context.
961
962     my @textFileMembers = $zip->membersMatching( '.*\.txt' );
963     # or
964     my $numberOfTextFiles = $zip->membersMatching( '.*\.txt' );
965
966 =item diskNumber()
967
968 Return the disk that I start on. Not used for writing zips,
969 but might be interesting if you read a zip in. This should be
970 0, as Archive::Zip does not handle multi-volume archives.
971
972 =item diskNumberWithStartOfCentralDirectory()
973
974 Return the disk number that holds the beginning of the
975 central directory. Not used for writing zips, but might be
976 interesting if you read a zip in. This should be 0, as
977 Archive::Zip does not handle multi-volume archives.
978
979 =item numberOfCentralDirectoriesOnThisDisk()
980
981 Return the number of CD structures in the zipfile last read in.
982 Not used for writing zips, but might be interesting if you read a zip
983 in.
984
985 =item numberOfCentralDirectories()
986
987 Return the number of CD structures in the zipfile last read in.
988 Not used for writing zips, but might be interesting if you read a zip
989 in.
990
991 =item centralDirectorySize()
992
993 Returns central directory size, as read from an external zip
994 file. Not used for writing zips, but might be interesting if
995 you read a zip in.
996
997 =item centralDirectoryOffsetWRTStartingDiskNumber()
998
999 Returns the offset into the zip file where the CD begins. Not
1000 used for writing zips, but might be interesting if you read a
1001 zip in.
1002
1003 =item zipfileComment( [$string] )
1004
1005 Get or set the zipfile comment. Returns the old comment.
1006
1007     print $zip->zipfileComment();
1008     $zip->zipfileComment( 'New Comment' );
1009
1010 =item eocdOffset()
1011
1012 Returns the (unexpected) number of bytes between where the
1013 EOCD was found and where it expected to be. This is normally
1014 0, but would be positive if something (a virus, perhaps) had
1015 added bytes somewhere before the EOCD. Not used for writing
1016 zips, but might be interesting if you read a zip in. Here is
1017 an example of how you can diagnose this:
1018
1019   my $zip = Archive::Zip->new('somefile.zip');
1020   if ($zip->eocdOffset())
1021   {
1022     warn "A virus has added ", $zip->eocdOffset, " bytes of garbage\n";
1023   }
1024
1025 The C<eocdOffset()> is used to adjust the starting position of member
1026 headers, if necessary.
1027
1028 =item fileName()
1029
1030 Returns the name of the file last read from. If nothing has
1031 been read yet, returns an empty string; if read from a file
1032 handle, returns the handle in string form.
1033
1034 =back
1035
1036 =head2 Zip Archive Member Operations
1037
1038 Various operations on a zip file modify members. When a member is
1039 passed as an argument, you can either use a reference to the member
1040 itself, or the name of a member. Of course, using the name requires
1041 that names be unique within a zip (this is not enforced).
1042
1043 =over 4
1044
1045 =item removeMember( $memberOrName )
1046
1047 Remove and return the given member, or match its name and
1048 remove it. Returns undef if member or name doesn't exist in this
1049 Zip. No-op if member does not belong to this zip.
1050
1051 =item replaceMember( $memberOrName, $newMember )
1052
1053 Remove and return the given member, or match its name and
1054 remove it. Replace with new member. Returns undef if member or
1055 name doesn't exist in this Zip, or if C<$newMember> is undefined.
1056
1057 It is an (undiagnosed) error to provide a C<$newMember> that is a
1058 member of the zip being modified.
1059
1060     my $member1 = $zip->removeMember( 'xyz' );
1061     my $member2 = $zip->replaceMember( 'abc', $member1 );
1062     # now, $member2 (named 'abc') is not in $zip,
1063     # and $member1 (named 'xyz') is, having taken $member2's place.
1064
1065 =item extractMember( $memberOrName [, $extractedName ] )
1066
1067 Extract the given member, or match its name and extract it.
1068 Returns undef if member doesn't exist in this Zip. If
1069 optional second arg is given, use it as the name of the
1070 extracted member. Otherwise, the internal filename of the
1071 member is used as the name of the extracted file or
1072 directory.
1073 If you pass C<$extractedName>, it should be in the local file
1074 system's format.
1075 All necessary directories will be created. Returns C<AZ_OK>
1076 on success.
1077
1078 =item extractMemberWithoutPaths( $memberOrName [, $extractedName ] )
1079
1080 Extract the given member, or match its name and extract it.
1081 Does not use path information (extracts into the current
1082 directory). Returns undef if member doesn't exist in this
1083 Zip.
1084 If optional second arg is given, use it as the name of the
1085 extracted member (its paths will be deleted too). Otherwise,
1086 the internal filename of the member (minus paths) is used as
1087 the name of the extracted file or directory. Returns C<AZ_OK>
1088 on success.
1089
1090 =item addMember( $member )
1091
1092 Append a member (possibly from another zip file) to the zip
1093 file. Returns the new member. Generally, you will use
1094 addFile(), addDirectory(), addFileOrDirectory(), addString(),
1095 or read() to add members.
1096
1097     # Move member named 'abc' to end of zip:
1098     my $member = $zip->removeMember( 'abc' );
1099     $zip->addMember( $member );
1100
1101 =item updateMember( $memberOrName, $fileName )
1102
1103 Update a single member from the file or directory named C<$fileName>.
1104 Returns the (possibly added or updated) member, if any; C<undef> on
1105 errors.
1106 The comparison is based on C<lastModTime()> and (in the case of a
1107 non-directory) the size of the file.
1108
1109 =item addFile( $fileName [, $newName ] )
1110
1111 Append a member whose data comes from an external file,
1112 returning the member or undef. The member will have its file
1113 name set to the name of the external file, and its
1114 desiredCompressionMethod set to COMPRESSION_DEFLATED. The
1115 file attributes and last modification time will be set from
1116 the file.
1117 If the name given does not represent a readable plain file or
1118 symbolic link, undef will be returned. C<$fileName> must be
1119 in the format required for the local file system.
1120 The optional C<$newName> argument sets the internal file name
1121 to something different than the given $fileName. C<$newName>,
1122 if given, must be in Zip name format (i.e. Unix).
1123 The text mode bit will be set if the contents appears to be
1124 text (as returned by the C<-T> perl operator).
1125
1126
1127 I<NOTE> that you shouldn't (generally) use absolute path names
1128 in zip member names, as this will cause problems with some zip
1129 tools as well as introduce a security hole and make the zip
1130 harder to use.
1131
1132 =item addDirectory( $directoryName [, $fileName ] )
1133
1134
1135
1136 Append a member created from the given directory name. The
1137 directory name does not have to name an existing directory.
1138 If the named directory exists, the file modification time and
1139 permissions are set from the existing directory, otherwise
1140 they are set to now and permissive default permissions.
1141 C<$directoryName> must be in local file system format.
1142 The optional second argument sets the name of the archive
1143 member (which defaults to C<$directoryName>). If given, it
1144 must be in Zip (Unix) format.
1145 Returns the new member.
1146
1147 =item addFileOrDirectory( $name [, $newName ] )
1148
1149
1150
1151 Append a member from the file or directory named $name. If
1152 $newName is given, use it for the name of the new member.
1153 Will add or remove trailing slashes from $newName as needed.
1154 C<$name> must be in local file system format.
1155 The optional second argument sets the name of the archive
1156 member (which defaults to C<$name>). If given, it must be in
1157 Zip (Unix) format.
1158
1159 =item addString( $stringOrStringRef, $name )
1160
1161
1162
1163 Append a member created from the given string or string
1164 reference. The name is given by the second argument.
1165 Returns the new member. The last modification time will be
1166 set to now, and the file attributes will be set to permissive
1167 defaults.
1168
1169     my $member = $zip->addString( 'This is a test', 'test.txt' );
1170
1171 =item contents( $memberOrMemberName [, $newContents ] )
1172
1173
1174
1175 Returns the uncompressed data for a particular member, or
1176 undef.
1177
1178     print "xyz.txt contains " . $zip->contents( 'xyz.txt' );
1179
1180 Also can change the contents of a member:
1181
1182     $zip->contents( 'xyz.txt', 'This is the new contents' );
1183
1184 If called expecting an array as the return value, it will include
1185 the status as the second value in the array.
1186
1187     ($content, $status) = $zip->contents( 'xyz.txt');
1188
1189 =back
1190
1191 =head2 Zip Archive I/O operations
1192
1193
1194 A Zip archive can be written to a file or file handle, or read from
1195 one.
1196
1197 =over 4
1198
1199 =item writeToFileNamed( $fileName )
1200
1201
1202
1203 Write a zip archive to named file. Returns C<AZ_OK> on
1204 success.
1205
1206     my $status = $zip->writeToFileNamed( 'xx.zip' );
1207     die "error somewhere" if $status != AZ_OK;
1208
1209 Note that if you use the same name as an existing zip file
1210 that you read in, you will clobber ZipFileMembers. So
1211 instead, write to a different file name, then delete the
1212 original.
1213 If you use the C<overwrite()> or C<overwriteAs()> methods, you can
1214 re-write the original zip in this way.
1215 C<$fileName> should be a valid file name on your system.
1216
1217 =item writeToFileHandle( $fileHandle [, $seekable] )
1218
1219 Write a zip archive to a file handle. Return AZ_OK on
1220 success. The optional second arg tells whether or not to try
1221 to seek backwards to re-write headers. If not provided, it is
1222 set if the Perl C<-f> test returns true. This could fail on
1223 some operating systems, though.
1224
1225     my $fh = IO::File->new( 'someFile.zip', 'w' );
1226     unless ( $zip->writeToFileHandle( $fh ) != AZ_OK ) {
1227         # error handling
1228     }
1229
1230 If you pass a file handle that is not seekable (like if
1231 you're writing to a pipe or a socket), pass a false second
1232 argument:
1233
1234     my $fh = IO::File->new( '| cat > somefile.zip', 'w' );
1235     $zip->writeToFileHandle( $fh, 0 );   # fh is not seekable
1236
1237 If this method fails during the write of a member, that
1238 member and all following it will return false from
1239 C<wasWritten()>. See writeCentralDirectory() for a way to
1240 deal with this.
1241 If you want, you can write data to the file handle before
1242 passing it to writeToFileHandle(); this could be used (for
1243 instance) for making self-extracting archives. However, this
1244 only works reliably when writing to a real file (as opposed
1245 to STDOUT or some other possible non-file).
1246
1247 See examples/selfex.pl for how to write a self-extracting
1248 archive.
1249
1250 =item writeCentralDirectory( $fileHandle [, $offset ] )
1251
1252 Writes the central directory structure to the given file
1253 handle.
1254
1255 Returns AZ_OK on success. If given an $offset, will
1256 seek to that point before writing. This can be used for
1257 recovery in cases where writeToFileHandle or writeToFileNamed
1258 returns an IO error because of running out of space on the
1259 destination file.
1260
1261 You can truncate the zip by seeking backwards and then writing the
1262 directory:
1263
1264     my $fh = IO::File->new( 'someFile.zip', 'w' );
1265         my $retval = $zip->writeToFileHandle( $fh );
1266     if ( $retval == AZ_IO_ERROR ) {
1267         my @unwritten = grep { not $_->wasWritten() } $zip->members();
1268         if (@unwritten) {
1269             $zip->removeMember( $member ) foreach my $member ( @unwritten );
1270             $zip->writeCentralDirectory( $fh,
1271             $unwritten[0]->writeLocalHeaderRelativeOffset());
1272         }
1273     }
1274
1275 =item overwriteAs( $newName )
1276
1277 Write the zip to the specified file, as safely as possible.
1278 This is done by first writing to a temp file, then renaming
1279 the original if it exists, then renaming the temp file, then
1280 deleting the renamed original if it exists. Returns AZ_OK if
1281 successful.
1282
1283 =item overwrite()
1284
1285 Write back to the original zip file. See overwriteAs() above.
1286 If the zip was not ever read from a file, this generates an
1287 error.
1288
1289 =item read( $fileName )
1290
1291 Read zipfile headers from a zip file, appending new members.
1292 Returns C<AZ_OK> or error code.
1293
1294     my $zipFile = Archive::Zip->new();
1295     my $status = $zipFile->read( '/some/FileName.zip' );
1296
1297 =item readFromFileHandle( $fileHandle, $filename )
1298
1299 Read zipfile headers from an already-opened file handle,
1300 appending new members. Does not close the file handle.
1301 Returns C<AZ_OK> or error code. Note that this requires a
1302 seekable file handle; reading from a stream is not yet
1303 supported.
1304
1305     my $fh = IO::File->new( '/some/FileName.zip', 'r' );
1306     my $zip1 = Archive::Zip->new();
1307     my $status = $zip1->readFromFileHandle( $fh );
1308     my $zip2 = Archive::Zip->new();
1309     $status = $zip2->readFromFileHandle( $fh );
1310
1311 =back
1312
1313 =head2 Zip Archive Tree operations
1314
1315 These used to be in Archive::Zip::Tree but got moved into
1316 Archive::Zip. They enable operation on an entire tree of members or
1317 files.
1318 A usage example:
1319
1320   use Archive::Zip;
1321   my $zip = Archive::Zip->new();
1322   
1323   # add all readable files and directories below . as xyz/*
1324   $zip->addTree( '.', 'xyz' );
1325   
1326   # add all readable plain files below /abc as def/*
1327   $zip->addTree( '/abc', 'def', sub { -f && -r } );
1328   
1329   # add all .c files below /tmp as stuff/*
1330   $zip->addTreeMatching( '/tmp', 'stuff', '\.c$' );
1331   
1332   # add all .o files below /tmp as stuff/* if they aren't writable
1333   $zip->addTreeMatching( '/tmp', 'stuff', '\.o$', sub { ! -w } );
1334   
1335   # add all .so files below /tmp that are smaller than 200 bytes as stuff/*
1336   $zip->addTreeMatching( '/tmp', 'stuff', '\.o$', sub { -s < 200 } );
1337   
1338   # and write them into a file
1339   $zip->writeToFileNamed('xxx.zip');
1340   
1341   # now extract the same files into /tmpx
1342   $zip->extractTree( 'stuff', '/tmpx' );
1343
1344 =over 4
1345
1346 =item $zip->addTree( $root, $dest [,$pred] ) -- Add tree of files to a zip
1347
1348 C<$root> is the root of the tree of files and directories to be
1349 added. It is a valid directory name on your system. C<$dest> is
1350 the name for the root in the zip file (undef or blank means
1351 to use relative pathnames). It is a valid ZIP directory name
1352 (that is, it uses forward slashes (/) for separating
1353 directory components). C<$pred> is an optional subroutine
1354 reference to select files: it is passed the name of the
1355 prospective file or directory using C<$_>, and if it returns
1356 true, the file or directory will be included. The default is
1357 to add all readable files and directories. For instance,
1358 using
1359
1360   my $pred = sub { /\.txt/ };
1361   $zip->addTree( '.', '', $pred );
1362
1363 will add all the .txt files in and below the current
1364 directory, using relative names, and making the names
1365 identical in the zipfile:
1366
1367   original name           zip member name
1368   ./xyz                   xyz
1369   ./a/                    a/
1370   ./a/b                   a/b
1371
1372 To translate absolute to relative pathnames, just pass them
1373 in: $zip->addTree( '/c/d', 'a' );
1374
1375   original name           zip member name
1376   /c/d/xyz                a/xyz
1377   /c/d/a/                 a/a/
1378   /c/d/a/b                a/a/b
1379
1380 Returns AZ_OK on success. Note that this will not follow
1381 symbolic links to directories. Note also that this does not
1382 check for the validity of filenames.
1383
1384 Note that you generally I<don't> want to make zip archive member names
1385 absolute.
1386
1387 =item $zip->addTreeMatching( $root, $dest, $pattern [,$pred] )
1388
1389 $root is the root of the tree of files and directories to be
1390 added $dest is the name for the root in the zip file (undef
1391 means to use relative pathnames) $pattern is a (non-anchored)
1392 regular expression for filenames to match $pred is an
1393 optional subroutine reference to select files: it is passed
1394 the name of the prospective file or directory in C<$_>, and
1395 if it returns true, the file or directory will be included.
1396 The default is to add all readable files and directories. To
1397 add all files in and below the current dirctory whose names
1398 end in C<.pl>, and make them extract into a subdirectory
1399 named C<xyz>, do this:
1400
1401   $zip->addTreeMatching( '.', 'xyz', '\.pl$' )
1402
1403 To add all I<writable> files in and below the dirctory named
1404 C</abc> whose names end in C<.pl>, and make them extract into
1405 a subdirectory named C<xyz>, do this:
1406
1407   $zip->addTreeMatching( '/abc', 'xyz', '\.pl$', sub { -w } )
1408
1409 Returns AZ_OK on success. Note that this will not follow
1410 symbolic links to directories.
1411
1412 =item $zip->updateTree( $root, [ $dest, [ $pred [, $mirror]]] );
1413
1414
1415
1416 Update a zip file from a directory tree.
1417
1418 C<updateTree()> takes the same arguments as C<addTree()>, but first
1419 checks to see whether the file or directory already exists in the zip
1420 file, and whether it has been changed.
1421
1422 If the fourth argument C<$mirror> is true, then delete all my members
1423 if corresponding files weren't found.
1424
1425
1426 Returns an error code or AZ_OK if all is well.
1427
1428 =item $zip->extractTree()
1429
1430
1431
1432 =item $zip->extractTree( $root )
1433
1434
1435
1436 =item $zip->extractTree( $root, $dest )
1437
1438
1439
1440 =item $zip->extractTree( $root, $dest, $volume )
1441
1442
1443
1444 If you don't give any arguments at all, will extract all the
1445 files in the zip with their original names.
1446
1447
1448 If you supply one argument for C<$root>, C<extractTree> will extract
1449 all the members whose names start with C<$root> into the current
1450 directory, stripping off C<$root> first.
1451 C<$root> is in Zip (Unix) format.
1452 For instance,
1453
1454   $zip->extractTree( 'a' );
1455
1456 when applied to a zip containing the files:
1457 a/x a/b/c ax/d/e d/e will extract:
1458
1459
1460 a/x as ./x
1461
1462
1463 a/b/c as ./b/c
1464
1465
1466 If you give two arguments, C<extractTree> extracts all the members
1467 whose names start with C<$root>. It will translate C<$root> into
1468 C<$dest> to construct the destination file name.
1469 C<$root> and C<$dest> are in Zip (Unix) format.
1470 For instance,
1471
1472    $zip->extractTree( 'a', 'd/e' );
1473
1474 when applied to a zip containing the files:
1475 a/x a/b/c ax/d/e d/e will extract:
1476
1477
1478 a/x to d/e/x
1479
1480
1481 a/b/c to d/e/b/c and ignore ax/d/e and d/e
1482
1483
1484 If you give three arguments, C<extractTree> extracts all the members
1485 whose names start with C<$root>. It will translate C<$root> into
1486 C<$dest> to construct the destination file name, and then it will
1487 convert to local file system format, using C<$volume> as the name of
1488 the destination volume.
1489
1490
1491 C<$root> and C<$dest> are in Zip (Unix) format.
1492
1493
1494 C<$volume> is in local file system format.
1495
1496
1497 For instance, under Windows,
1498
1499    $zip->extractTree( 'a', 'd/e', 'f:' );
1500
1501 when applied to a zip containing the files:
1502 a/x a/b/c ax/d/e d/e will extract:
1503
1504
1505 a/x to f:d/e/x
1506
1507
1508 a/b/c to f:d/e/b/c and ignore ax/d/e and d/e
1509
1510
1511 If you want absolute paths (the prior example used paths relative to
1512 the current directory on the destination volume, you can specify these
1513 in C<$dest>:
1514
1515    $zip->extractTree( 'a', '/d/e', 'f:' );
1516
1517 when applied to a zip containing the files:
1518 a/x a/b/c ax/d/e d/e will extract:
1519
1520
1521 a/x to f:\d\e\x
1522
1523
1524 a/b/c to f:\d\e\b\c and ignore ax/d/e and d/e
1525
1526 Returns an error code or AZ_OK if everything worked OK.
1527
1528 =back
1529
1530 =head1 MEMBER OPERATIONS
1531
1532
1533 =head2 Member Class Methods
1534
1535
1536 Several constructors allow you to construct members without adding
1537 them to a zip archive. These work the same as the addFile(),
1538 addDirectory(), and addString() zip instance methods described above,
1539 but they don't add the new members to a zip.
1540
1541 =over 4
1542
1543 =item Archive::Zip::Member->newFromString( $stringOrStringRef [, $fileName] )
1544
1545
1546
1547 Construct a new member from the given string. Returns undef
1548 on error.
1549
1550     my $member = Archive::Zip::Member->newFromString( 'This is a test',
1551                                                  'xyz.txt' );
1552
1553 =item newFromFile( $fileName )
1554
1555
1556
1557 Construct a new member from the given file. Returns undef on
1558 error.
1559
1560     my $member = Archive::Zip::Member->newFromFile( 'xyz.txt' );
1561
1562 =item newDirectoryNamed( $directoryName [, $zipname ] )
1563
1564
1565
1566 Construct a new member from the given directory.
1567 C<$directoryName> must be a valid name on your file system; it doesn't
1568 have to exist.
1569
1570
1571 If given, C<$zipname> will be the name of the zip member; it must be a
1572 valid Zip (Unix) name. If not given, it will be converted from
1573 C<$directoryName>.
1574
1575
1576 Returns undef on error.
1577
1578     my $member = Archive::Zip::Member->newDirectoryNamed( 'CVS/' );
1579
1580 =back
1581
1582 =head2 Member Simple accessors
1583
1584
1585 These methods get (and/or set) member attribute values.
1586
1587 =over 4
1588
1589 =item versionMadeBy()
1590
1591
1592
1593 Gets the field from the member header.
1594
1595 =item fileAttributeFormat( [$format] )
1596
1597
1598
1599 Gets or sets the field from the member header. These are
1600 C<FA_*> values.
1601
1602 =item versionNeededToExtract()
1603
1604
1605
1606 Gets the field from the member header.
1607
1608 =item bitFlag()
1609
1610
1611
1612 Gets the general purpose bit field from the member header.
1613 This is where the C<GPBF_*> bits live.
1614
1615 =item compressionMethod()
1616
1617
1618
1619 Returns the member compression method. This is the method
1620 that is currently being used to compress the member data.
1621 This will be COMPRESSION_STORED for added string or file
1622 members, or any of the C<COMPRESSION_*> values for members
1623 from a zip file. However, this module can only handle members
1624 whose data is in COMPRESSION_STORED or COMPRESSION_DEFLATED
1625 format.
1626
1627 =item desiredCompressionMethod( [$method] )
1628
1629
1630
1631 Get or set the member's C<desiredCompressionMethod>. This is
1632 the compression method that will be used when the member is
1633 written. Returns prior desiredCompressionMethod. Only
1634 COMPRESSION_DEFLATED or COMPRESSION_STORED are valid
1635 arguments. Changing to COMPRESSION_STORED will change the
1636 member desiredCompressionLevel to 0; changing to
1637 COMPRESSION_DEFLATED will change the member
1638 desiredCompressionLevel to COMPRESSION_LEVEL_DEFAULT.
1639
1640 =item desiredCompressionLevel( [$method] )
1641
1642
1643
1644 Get or set the member's desiredCompressionLevel This is the
1645 method that will be used to write. Returns prior
1646 desiredCompressionLevel. Valid arguments are 0 through 9,
1647 COMPRESSION_LEVEL_NONE, COMPRESSION_LEVEL_DEFAULT,
1648 COMPRESSION_LEVEL_BEST_COMPRESSION, and
1649 COMPRESSION_LEVEL_FASTEST. 0 or COMPRESSION_LEVEL_NONE will
1650 change the desiredCompressionMethod to COMPRESSION_STORED.
1651 All other arguments will change the desiredCompressionMethod
1652 to COMPRESSION_DEFLATED.
1653
1654 =item externalFileName()
1655
1656
1657
1658 Return the member's external file name, if any, or undef.
1659
1660 =item fileName()
1661
1662
1663
1664 Get or set the member's internal filename. Returns the
1665 (possibly new) filename. Names will have backslashes
1666 converted to forward slashes, and will have multiple
1667 consecutive slashes converted to single ones.
1668
1669 =item lastModFileDateTime()
1670
1671
1672
1673 Return the member's last modification date/time stamp in
1674 MS-DOS format.
1675
1676 =item lastModTime()
1677
1678
1679
1680 Return the member's last modification date/time stamp,
1681 converted to unix localtime format.
1682
1683     print "Mod Time: " . scalar( localtime( $member->lastModTime() ) );
1684
1685 =item setLastModFileDateTimeFromUnix()
1686
1687 Set the member's lastModFileDateTime from the given unix
1688 time.
1689
1690     $member->setLastModFileDateTimeFromUnix( time() );
1691
1692 =item internalFileAttributes()
1693
1694 Return the internal file attributes field from the zip
1695 header. This is only set for members read from a zip file.
1696
1697 =item externalFileAttributes()
1698
1699 Return member attributes as read from the ZIP file. Note that
1700 these are NOT UNIX!
1701
1702 =item unixFileAttributes( [$newAttributes] )
1703
1704 Get or set the member's file attributes using UNIX file
1705 attributes. Returns old attributes.
1706
1707     my $oldAttribs = $member->unixFileAttributes( 0666 );
1708
1709 Note that the return value has more than just the file
1710 permissions, so you will have to mask off the lowest bits for
1711 comparisions.
1712
1713 =item localExtraField( [$newField] )
1714
1715 Gets or sets the extra field that was read from the local
1716 header. This is not set for a member from a zip file until
1717 after the member has been written out. The extra field must
1718 be in the proper format.
1719
1720 =item cdExtraField( [$newField] )
1721
1722 Gets or sets the extra field that was read from the central
1723 directory header. The extra field must be in the proper
1724 format.
1725
1726 =item extraFields()
1727
1728 Return both local and CD extra fields, concatenated.
1729
1730 =item fileComment( [$newComment] )
1731
1732 Get or set the member's file comment.
1733
1734 =item hasDataDescriptor()
1735
1736 Get or set the data descriptor flag. If this is set, the
1737 local header will not necessarily have the correct data
1738 sizes. Instead, a small structure will be stored at the end
1739 of the member data with these values. This should be
1740 transparent in normal operation.
1741
1742 =item crc32()
1743
1744 Return the CRC-32 value for this member. This will not be set
1745 for members that were constructed from strings or external
1746 files until after the member has been written.
1747
1748 =item crc32String()
1749
1750 Return the CRC-32 value for this member as an 8 character
1751 printable hex string. This will not be set for members that
1752 were constructed from strings or external files until after
1753 the member has been written.
1754
1755 =item compressedSize()
1756
1757 Return the compressed size for this member. This will not be
1758 set for members that were constructed from strings or
1759 external files until after the member has been written.
1760
1761 =item uncompressedSize()
1762
1763 Return the uncompressed size for this member.
1764
1765 =item isEncrypted()
1766
1767 Return true if this member is encrypted. The Archive::Zip
1768 module does not currently create or extract encrypted
1769 members.
1770
1771 =item isTextFile( [$flag] )
1772
1773 Returns true if I am a text file. Also can set the status if
1774 given an argument (then returns old state). Note that this
1775 module does not currently do anything with this flag upon
1776 extraction or storage. That is, bytes are stored in native
1777 format whether or not they came from a text file.
1778
1779 =item isBinaryFile()
1780
1781 Returns true if I am a binary file. Also can set the status
1782 if given an argument (then returns old state). Note that this
1783 module does not currently do anything with this flag upon
1784 extraction or storage. That is, bytes are stored in native
1785 format whether or not they came from a text file.
1786
1787 =item extractToFileNamed( $fileName )
1788
1789 Extract me to a file with the given name. The file will be
1790 created with default modes. Directories will be created as
1791 needed.
1792 The C<$fileName> argument should be a valid file name on your
1793 file system.
1794 Returns AZ_OK on success.
1795
1796 =item isDirectory()
1797
1798 Returns true if I am a directory.
1799
1800 =item writeLocalHeaderRelativeOffset()
1801
1802 Returns the file offset in bytes the last time I was written.
1803
1804 =item wasWritten()
1805
1806 Returns true if I was successfully written. Reset at the
1807 beginning of a write attempt.
1808
1809 =back
1810
1811 =head2 Low-level member data reading
1812
1813 It is possible to use lower-level routines to access member data
1814 streams, rather than the extract* methods and contents(). For
1815 instance, here is how to print the uncompressed contents of a member
1816 in chunks using these methods:
1817
1818     my ( $member, $status, $bufferRef );
1819     $member = $zip->memberNamed( 'xyz.txt' );
1820     $member->desiredCompressionMethod( COMPRESSION_STORED );
1821     $status = $member->rewindData();
1822     die "error $status" unless $status == AZ_OK;
1823     while ( ! $member->readIsDone() )
1824     {
1825     ( $bufferRef, $status ) = $member->readChunk();
1826     die "error $status"
1827                         if $status != AZ_OK && $status != AZ_STREAM_END;
1828     # do something with $bufferRef:
1829     print $$bufferRef;
1830     }
1831     $member->endRead();
1832
1833 =over 4
1834
1835 =item readChunk( [$chunkSize] )
1836
1837 This reads the next chunk of given size from the member's
1838 data stream and compresses or uncompresses it as necessary,
1839 returning a reference to the bytes read and a status. If size
1840 argument is not given, defaults to global set by
1841 Archive::Zip::setChunkSize. Status is AZ_OK on success until
1842 the last chunk, where it returns AZ_STREAM_END. Returns C<(
1843 \$bytes, $status)>.
1844
1845     my ( $outRef, $status ) = $self->readChunk();
1846     print $$outRef if $status != AZ_OK && $status != AZ_STREAM_END;
1847
1848 =item rewindData()
1849
1850 Rewind data and set up for reading data streams or writing
1851 zip files. Can take options for C<inflateInit()> or
1852 C<deflateInit()>, but this isn't likely to be necessary.
1853 Subclass overrides should call this method. Returns C<AZ_OK>
1854 on success.
1855
1856 =item endRead()
1857
1858 Reset the read variables and free the inflater or deflater.
1859 Must be called to close files, etc. Returns AZ_OK on success.
1860
1861 =item readIsDone()
1862
1863 Return true if the read has run out of data or errored out.
1864
1865 =item contents()
1866
1867 Return the entire uncompressed member data or undef in scalar
1868 context. When called in array context, returns C<( $string,
1869 $status )>; status will be AZ_OK on success:
1870
1871     my $string = $member->contents();
1872     # or
1873     my ( $string, $status ) = $member->contents();
1874     die "error $status" unless $status == AZ_OK;
1875
1876 Can also be used to set the contents of a member (this may
1877 change the class of the member):
1878
1879     $member->contents( "this is my new contents" );
1880
1881 =item extractToFileHandle( $fh )
1882
1883 Extract (and uncompress, if necessary) the member's contents
1884 to the given file handle. Return AZ_OK on success.
1885
1886 =back
1887
1888 =head1 Archive::Zip::FileMember methods
1889
1890 The Archive::Zip::FileMember class extends Archive::Zip::Member. It is the
1891 base class for both ZipFileMember and NewFileMember classes. This class adds
1892 an C<externalFileName> and an C<fh> member to keep track of the external
1893 file.
1894
1895 =over 4
1896
1897 =item externalFileName()
1898
1899 Return the member's external filename.
1900
1901 =item fh()
1902
1903 Return the member's read file handle. Automatically opens file if
1904 necessary.
1905
1906 =back
1907
1908 =head1 Archive::Zip::ZipFileMember methods
1909
1910 The Archive::Zip::ZipFileMember class represents members that have been read
1911 from external zip files.
1912
1913 =over 4
1914
1915 =item diskNumberStart()
1916
1917 Returns the disk number that the member's local header resides in.
1918 Should be 0.
1919
1920 =item localHeaderRelativeOffset()
1921
1922 Returns the offset into the zip file where the member's local header
1923 is.
1924
1925 =item dataOffset()
1926
1927 Returns the offset from the beginning of the zip file to the member's
1928 data.
1929
1930 =back
1931
1932 =head1 REQUIRED MODULES
1933
1934 L<Archive::Zip> requires several other modules:
1935
1936 L<Carp>
1937
1938 L<Compress::Zlib>
1939
1940 L<Cwd>
1941
1942 L<File::Basename>
1943
1944 L<File::Copy>
1945
1946 L<File::Find>
1947
1948 L<File::Path>
1949
1950 L<File::Spec>
1951
1952 L<File::Spec>
1953
1954 L<IO::File>
1955
1956 L<IO::Seekable>
1957
1958 L<Time::Local>
1959
1960 =head1 BUGS AND CAVEATS
1961
1962 =head2 When not to use Archive::Zip
1963
1964 If you are just going to be extracting zips (and/or other archives) you
1965 are recommended to look at using L<Archive::Extract> instead, as it is much
1966 easier to use and factors out archive-specific functionality.
1967
1968 =head2 Try to avoid IO::Scalar
1969
1970 One of the most common ways to use Archive::Zip is to generate Zip files
1971 in-memory. Most people have use L<IO::Scalar> for this purpose.
1972
1973 Unfortunately, as of 1.11 this module no longer works with L<IO::Scalar>
1974 as it incorrectly implements seeking.
1975
1976 Anybody using L<IO::Scalar> should consider porting to L<IO::String>,
1977 which is smaller, lighter, and is implemented to be perfectly compatible
1978 with regular seekable filehandles.
1979
1980 Support for L<IO::Scalar> most likely will B<not> be restored in the
1981 future, as L<IO::Scalar> itself cannot change the way it is implemented
1982 due to back-compatibility issues.
1983
1984 =head1 TO DO
1985
1986 * auto-choosing storing vs compression
1987
1988 * extra field hooks (see notes.txt)
1989
1990 * check for dups on addition/renaming?
1991
1992 * Text file extraction (line end translation)
1993
1994 * Reading zip files from non-seekable inputs
1995   (Perhaps by proxying through IO::String?)
1996
1997 * separate unused constants into separate module
1998
1999 * cookbook style docs
2000
2001 * Handle tainted paths correctly
2002
2003 * Work on better compatability with other IO:: modules
2004
2005 =head1 SUPPORT
2006
2007 Bugs should be reported via the CPAN bug tracker
2008
2009 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Archive-Zip>
2010
2011 For other issues contact the maintainer
2012
2013 =head1 AUTHOR
2014
2015 Adam Kennedy E<lt>adamk@cpan.orgE<gt>
2016
2017 Previously maintained by Steve Peters E<lt>steve@fisharerojo.orgE<gt>.
2018
2019 File attributes code by Maurice Aubrey E<lt>maurice@lovelyfilth.comE<gt>.
2020
2021 Originally by Ned Konz E<lt>nedkonz@cpan.orgE<gt>.
2022
2023 =head1 COPYRIGHT
2024
2025 Copyright (c) 2000-2004 Ned Konz. All rights reserved.
2026
2027 Some parts copyright (c) 2005 Steve Peters. All rights reserved.
2028
2029 Some parts copyright (c) 2006 Adam Kennedy. All rights reserved. 
2030
2031 This program is free software; you can redistribute it and/or modify it
2032 under the same terms as Perl itself.
2033
2034 =head1 SEE ALSO
2035
2036 L<Compress::Zlib>, L<Archive::Tar>, L<Archive::Extract>
2037
2038 There is a Japanese translation of this
2039 document at L<http://www.memb.jp/~deq/perl/doc-ja/Archive-Zip.html> that
2040 was done by DEQ E<lt>deq@oct.zaq.ne.jpE<gt> . Thanks! 
2041
2042 =cut