File Coverage

blib/lib/Archive/Zip.pm
Criterion Covered Total %
statement 403 425 94.8
branch 38 80 47.5
condition 21 38 55.2
subroutine 119 122 97.5
pod 6 6 100.0
total 587 671 87.4


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