File Coverage

blib/lib/Archive/Zip.pm
Criterion Covered Total %
statement 318 354 89.8
branch 22 58 37.9
condition 13 29 44.8
subroutine 96 102 94.1
pod 6 6 100.0
total 455 549 82.9


line stmt bran cond sub pod time code
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 6     6   74 require 5.003_96;
18             }
19 6     6   374 use strict;
  6         55  
  6         164  
20 6     6   3191 use UNIVERSAL ();
  6         73  
  6         102  
21 6     6   93 use Carp ();
  6         54  
  6         55  
22 6     6   181 use IO::File ();
  6         62  
  6         60  
23 6     6   163 use IO::Seekable ();
  6         202  
  6         223  
24 6     6   177 use Compress::Zlib ();
  6         65  
  6         62  
25 6     6   289 use File::Spec ();
  6         65  
  6         58  
26 6     6   267 use File::Temp ();
  6         118  
  6         59  
27              
28 6     6   104 use vars qw( $VERSION @ISA );
  6         55  
  6         377  
29             BEGIN {
30 6     6   80 $VERSION = '1.18';
31 6         217 $VERSION = eval $VERSION;
32              
33 6         169 require Exporter;
34 6         85 @ISA = qw( Exporter );
35             }
36              
37 6     6   121 use vars qw( $ChunkSize $ErrorHandler );
  6         56  
  6         81  
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 6     6   95 use vars qw( @EXPORT_OK %EXPORT_TAGS );
  6         54  
  6         75  
48             BEGIN {
49 6     6   103 @EXPORT_OK   = ('computeCRC32');
50 6         689 %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 6         90 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 6     6   102 use constant AZ_OK => 0;
  6         57  
  6         119  
161 6     6   103 use constant AZ_STREAM_END => 1;
  6         56  
  6         74  
162 6     6   85 use constant AZ_ERROR => 2;
  6         55  
  6         71  
163 6     6   89 use constant AZ_FORMAT_ERROR => 3;
  6         55  
  6         148  
164 6     6   87 use constant AZ_IO_ERROR => 4;
  6         56  
  6         75  
165              
166             # File types
167             # Values of Archive::Zip::Member->fileAttributeFormat()
168              
169 6     6   455 use constant FA_MSDOS => 0;
  6         71  
  6         73  
170 6     6   96 use constant FA_AMIGA => 1;
  6         135  
  6         85  
171 6     6   157 use constant FA_VAX_VMS => 2;
  6         55  
  6         74  
172 6     6   114 use constant FA_UNIX => 3;
  6         55  
  6         72  
173 6     6   89 use constant FA_VM_CMS => 4;
  6         58  
  6         821  
174 6     6   102 use constant FA_ATARI_ST => 5;
  6         239  
  6         78  
175 6     6   102 use constant FA_OS2_HPFS => 6;
  6         55  
  6         73  
176 6     6   95 use constant FA_MACINTOSH => 7;
  6         55  
  6         74  
177 6     6   93 use constant FA_Z_SYSTEM => 8;
  6         83  
  6         78  
178 6     6   132 use constant FA_CPM => 9;
  6         95  
  6         76  
179 6     6   86 use constant FA_TOPS20 => 10;
  6         57  
  6         73  
180 6     6   177 use constant FA_WINDOWS_NTFS => 11;
  6         58  
  6         107  
181 6     6   86 use constant FA_QDOS => 12;
  6         56  
  6         107  
182 6     6   277 use constant FA_ACORN => 13;
  6         57  
  6         80  
183 6     6   87 use constant FA_VFAT => 14;
  6         58  
  6         92  
184 6     6   88 use constant FA_MVS => 15;
  6         55  
  6         126  
185 6     6   91 use constant FA_BEOS => 16;
  6         57  
  6         71  
186 6     6   86 use constant FA_TANDEM => 17;
  6         56  
  6         72  
187 6     6   235 use constant FA_THEOS => 18;
  6         56  
  6         74  
188              
189             # general-purpose bit flag masks
190             # Found in Archive::Zip::Member->bitFlag()
191              
192 6     6   87 use constant GPBF_ENCRYPTED_MASK => 1 << 0;
  6         52  
  6         75  
193 6     6   93 use constant GPBF_DEFLATING_COMPRESSION_MASK => 3 << 1;
  6         56  
  6         72  
194 6     6   89 use constant GPBF_HAS_DATA_DESCRIPTOR_MASK => 1 << 3;
  6         58  
  6         77  
195              
196             # deflating compression types, if compressionMethod == COMPRESSION_DEFLATED
197             # ( Archive::Zip::Member->bitFlag() & GPBF_DEFLATING_COMPRESSION_MASK )
198              
199 6     6   87 use constant DEFLATING_COMPRESSION_NORMAL => 0 << 1;
  6         55  
  6         77  
200 6     6   137 use constant DEFLATING_COMPRESSION_MAXIMUM => 1 << 1;
  6         57  
  6         145  
201 6     6   170 use constant DEFLATING_COMPRESSION_FAST => 2 << 1;
  6         56  
  6         75  
202 6     6   88 use constant DEFLATING_COMPRESSION_SUPER_FAST => 3 << 1;
  6         58  
  6         76  
203              
204             # compression method
205              
206             # these two are the only ones supported in this module
207 6     6   215 use constant COMPRESSION_STORED => 0; # file is stored (no compression)
  6         58  
  6         79  
208 6     6   90 use constant COMPRESSION_DEFLATED => 8; # file is Deflated
  6         84  
  6         72  
209 6     6   88 use constant COMPRESSION_LEVEL_NONE => 0;
  6         58  
  6         75  
210 6     6   88 use constant COMPRESSION_LEVEL_DEFAULT => -1;
  6         53  
  6         523  
211 6     6   89 use constant COMPRESSION_LEVEL_FASTEST => 1;
  6         102  
  6         72  
212 6     6   91 use constant COMPRESSION_LEVEL_BEST_COMPRESSION => 9;
  6         56  
  6         72  
213              
214             # internal file attribute bits
215             # Found in Archive::Zip::Member::internalFileAttributes()
216              
217 6     6   93 use constant IFA_TEXT_FILE_MASK => 1;
  6         55  
  6         76  
218 6     6   88 use constant IFA_TEXT_FILE => 1;
  6         82  
  6         74  
219 6     6   143 use constant IFA_BINARY_FILE => 0;
  6         82  
  6         737  
220              
221             # PKZIP file format miscellaneous constants (for internal use only)
222 6     6   90 use constant SIGNATURE_FORMAT => "V";
  6         53  
  6         214  
223 6     6   92 use constant SIGNATURE_LENGTH => 4;
  6         53  
  6         73  
224              
225             # these lengths are without the signature.
226 6     6   93 use constant LOCAL_FILE_HEADER_SIGNATURE => 0x04034b50;
  6         220  
  6         105  
227 6     6   115 use constant LOCAL_FILE_HEADER_FORMAT => "v3 V4 v2";
  6         54  
  6         71  
228 6     6   90 use constant LOCAL_FILE_HEADER_LENGTH => 26;
  6         56  
  6         74  
229              
230             # PKZIP docs don't mention the signature, but Info-Zip writes it.
231 6     6   85 use constant DATA_DESCRIPTOR_SIGNATURE => 0x08074b50;
  6         293  
  6         83  
232 6     6   92 use constant DATA_DESCRIPTOR_FORMAT => "V3";
  6         52  
  6         100  
233 6     6   89 use constant DATA_DESCRIPTOR_LENGTH => 12;
  6         57  
  6         72  
234              
235             # but the signature is apparently optional.
236 6     6   88 use constant DATA_DESCRIPTOR_FORMAT_NO_SIG => "V2";
  6         54  
  6         73  
237 6     6   128 use constant DATA_DESCRIPTOR_LENGTH_NO_SIG => 8;
  6         57  
  6         71  
238              
239 6     6   89 use constant CENTRAL_DIRECTORY_FILE_HEADER_SIGNATURE => 0x02014b50;
  6         55  
  6         169  
240 6     6   87 use constant CENTRAL_DIRECTORY_FILE_HEADER_FORMAT => "C2 v3 V4 v5 V2";
  6         56  
  6         73  
241 6     6   112 use constant CENTRAL_DIRECTORY_FILE_HEADER_LENGTH => 42;
  6         86  
  6         73  
242              
243 6     6   93 use constant END_OF_CENTRAL_DIRECTORY_SIGNATURE => 0x06054b50;
  6         56  
  6         74  
244 6         92 use constant END_OF_CENTRAL_DIRECTORY_SIGNATURE_STRING =>
245 6     6   94 pack( "V", END_OF_CENTRAL_DIRECTORY_SIGNATURE );
  6         99  
246 6     6   89 use constant END_OF_CENTRAL_DIRECTORY_FORMAT => "v4 V2 v";
  6         55  
  6         135  
247 6     6   2437 use constant END_OF_CENTRAL_DIRECTORY_LENGTH => 18;
  6         81  
  6         83  
248              
249 6     6   102 use constant GPBF_IMPLODING_8K_SLIDING_DICTIONARY_MASK => 1 << 1;
  6         58  
  6         77  
250 6     6   257 use constant GPBF_IMPLODING_3_SHANNON_FANO_TREES_MASK => 1 << 2;
  6         109  
  6         76  
251 6     6   92 use constant GPBF_IS_COMPRESSED_PATCHED_DATA_MASK => 1 << 5;
  6         54  
  6         73  
252              
253             # the rest of these are not supported in this module
254 6     6   113 use constant COMPRESSION_SHRUNK => 1; # file is Shrunk
  6         53  
  6         104  
255 6     6   120 use constant COMPRESSION_REDUCED_1 => 2; # file is Reduced CF=1
  6         56  
  6         100  
256 6     6   90 use constant COMPRESSION_REDUCED_2 => 3; # file is Reduced CF=2
  6         54  
  6         74  
257 6     6   89 use constant COMPRESSION_REDUCED_3 => 4; # file is Reduced CF=3
  6         211  
  6         105  
258 6     6   91 use constant COMPRESSION_REDUCED_4 => 5; # file is Reduced CF=4
  6         56  
  6         75  
259 6     6   121 use constant COMPRESSION_IMPLODED => 6; # file is Imploded
  6         56  
  6         92  
260 6     6   127 use constant COMPRESSION_TOKENIZED => 7; # reserved for Tokenizing compr.
  6         57  
  6         101  
261 6     6   90 use constant COMPRESSION_DEFLATED_ENHANCED => 9; # reserved for enh. Deflating
  6         54  
  6         74  
262 6     6   89 use constant COMPRESSION_PKWARE_DATA_COMPRESSION_LIBRARY_IMPLODED => 10;
  6         56  
  6         75  
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 6     6   95 use constant ZIPARCHIVECLASS => 'Archive::Zip::Archive';
  6         56  
  6         102  
274 6     6   96 use constant ZIPMEMBERCLASS => 'Archive::Zip::Member';
  6         52  
  6         80  
275              
276             sub new
277             {
278 7     7 1 608 my $class = shift;
279 7         287 return $class->ZIPARCHIVECLASS->new(@_);
280             }
281              
282             sub computeCRC32
283             {
284 81     81 1 4241 my $data = shift;
285 81 100       3999 $data = shift if ref($data); # allow calling as an obj method
286 81         739 my $crc = shift;
287 81         3032 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 0     0 1 0 my $chunkSize = shift;
295 0 0       0 $chunkSize = shift if ref($chunkSize); # object method on zip?
296 0         0 my $oldChunkSize = $Archive::Zip::ChunkSize;
297 0 0       0 $Archive::Zip::ChunkSize = $chunkSize if ($chunkSize);
298 0         0 return $oldChunkSize;
299             }
300              
301             sub chunkSize
302             {
303 6     6 1 106 return $Archive::Zip::ChunkSize;
304             }
305              
306             sub setErrorHandler (&)
307             {
308 0     0 1 0 my $errorHandler = shift;
309 0 0       0 $errorHandler = \&Carp::carp unless defined($errorHandler);
310 0         0 my $oldErrorHandler = $Archive::Zip::ErrorHandler;
311 0         0 $Archive::Zip::ErrorHandler = $errorHandler;
312 0         0 return $oldErrorHandler;
313             }
314              
315             # ----------------------------------------------------------------------
316             # Private utility functions (not methods).
317             # ----------------------------------------------------------------------
318              
319             sub _printError
320             {
321 1     1   13 my $string = join ( ' ', @_, "\n" );
322 1         11 my $oldCarpLevel = $Carp::CarpLevel;
323 1         10 $Carp::CarpLevel += 2;
324 1         10 &{$ErrorHandler} ($string);
  1         12  
325 1         16 $Carp::CarpLevel = $oldCarpLevel;
326             }
327              
328             # This is called on format errors.
329             sub _formatError
330             {
331 0 0   0   0 shift if ref( $_[0] );
332 0         0 _printError( 'format error:', @_ );
333 0         0 return AZ_FORMAT_ERROR;
334             }
335              
336             # This is called on IO errors.
337             sub _ioError
338             {
339 0 0   0   0 shift if ref( $_[0] );
340 0         0 _printError( 'IO error:', @_, ':', $! );
341 0         0 return AZ_IO_ERROR;
342             }
343              
344             # This is called on generic errors.
345             sub _error
346             {
347 1 50   1   13 shift if ref( $_[0] );
348 1         13 _printError( 'error:', @_ );
349 1         11 return AZ_ERROR;
350             }
351              
352             # Called when a subclass should have implemented
353             # something but didn't
354             sub _subclassResponsibility
355             {
356 0     0   0 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 75     75   1094 my $fh = shift;
363 75 50       1690 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 4     4   76 my $fh = shift;
372 4 50       806 if ( UNIVERSAL::isa($fh, 'IO::Scalar') ) {
373 0         0 return 0;
374             }
375 4 50       121 if ( UNIVERSAL::isa($fh, 'IO::String') ) {
376 0         0 return 1;
377             }
378 4 50       90 if ( UNIVERSAL::isa($fh, 'IO::Seekable') ) {
379             # Unfortunately, some things like FileHandle objects
380             # return true for Seekable, but AREN'T!!!!!
381 4 100       277 if ( UNIVERSAL::isa($fh, 'FileHandle') ) {
382 1         65 return 0;
383             }
384 3         43 return 1;
385             }
386 0 0       0 if ( UNIVERSAL::can($fh, 'stat') ) {
387 0         0 return -f $fh;
388             }
389             return (
390 0 0 0     0 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 74     74   1469 my $fd = shift;
402 74         1420 my $status = 1;
403 74         1867 my $handle;
404              
405 74 50       2374 if ( ref($fd) )
406             {
407 0 0 0     0 if ( UNIVERSAL::isa( $fd, 'IO::Scalar' )
    0 0        
408             or UNIVERSAL::isa( $fd, 'IO::String' ) )
409             {
410 0         0 $handle = $fd;
411             }
412             elsif ( UNIVERSAL::isa( $fd, 'IO::Handle' )
413             or UNIVERSAL::isa( $fd, 'GLOB' ) )
414             {
415 0         0 $handle = IO::File->new();
416 0         0 $status = $handle->fdopen( $fd, @_ );
417             }
418             else
419             {
420 0         0 $handle = $fd;
421             }
422             }
423             else
424             {
425 74         5239 $handle = IO::File->new();
426 74         19247 $status = $handle->open( $fd, @_ );
427             }
428              
429 74         21257 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 31     31   286 my $fh = shift;
440 31         597 my $fileName = shift;
441 31         263 my $expectedSignature = shift; # optional
442              
443 31         290 my $signatureData;
444 31         561 my $bytesRead = $fh->read( $signatureData, SIGNATURE_LENGTH );
445 31 50       3217 return _ioError("reading header signature")
446             if $bytesRead != SIGNATURE_LENGTH;
447 31         513 my $signature = unpack( SIGNATURE_FORMAT, $signatureData );
448 31         2727 my $status = AZ_OK;
449              
450             # compare with expected signature, if any, or any known signature.
451 31 50 66     1218 if ( ( defined($expectedSignature) && $signature != $expectedSignature )
      100        
      66        
      66        
      33        
      33        
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 0         0 my $errmsg = sprintf( "bad signature: 0x%08x", $signature );
459 0 0       0 if ( _isSeekable($fh) )
460             {
461 0         0 $errmsg .=
462             sprintf( " at offset %d", $fh->tell() - SIGNATURE_LENGTH );
463             }
464              
465 0         0 $status = _formatError("$errmsg in file $fileName");
466             }
467              
468 31         562 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 0     0 1 0 my $dir = shift;
482 0 0       0 my ( $fh, $filename ) = File::Temp::tempfile(
483             SUFFIX => '.zip',
484             UNLINK => 0, # we will delete it!
485             $dir ? ( DIR => $dir ) : ()
486             );
487 0 0       0 return ( undef, undef ) unless $fh;
488 0         0 my ( $status, $newfh ) = _newFileHandle( $fh, 'w+' );
489 0         0 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 99     99   1045 my $name = shift;
513 99         979 my $forceDir = shift;
514 99         953 my $volReturn = shift;
515 99         2392 my ( $volume, $directories, $file ) =
516             File::Spec->splitpath( File::Spec->canonpath($name), $forceDir );
517 99 50       1098 $$volReturn = $volume if ( ref($volReturn) );
518 99         2273 my @dirs = map { $_ =~ s{/}{_}g; $_ } File::Spec->splitdir($directories);
  161         7475  
  161         15711  
519 99 100       1254 if ( @dirs > 0 ) { pop (@dirs) unless $dirs[-1] } # remove empty component
  83 100       927  
520 99   100     2065 push ( @dirs, $file || '' );
521             #return wantarray ? @dirs : join ( '/', @dirs );
522 99         1644     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 26     26   569 my $name = shift; # zip format
532 26         229 my $volume = shift;
533 26 50       539 $volume = '' unless defined($volume); # local FS format
534              
535 26         372 my @paths = split ( /\//, $name );
536 26         285 my $filename = pop (@paths);
537 26 50       306 $filename = '' unless defined($filename);
538 26 100       678 my $localDirs = @paths?File::Spec->catdir(@paths):'';
539 26         2634 my $localName = File::Spec->catpath( $volume, $localDirs, $filename );
540 26 50       7108 $localName = File::Spec->rel2abs($localName) unless $volume;
541 26         4669 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