1 package IO::Compress::Zip ;
7 use IO::Compress::Base::Common 2.021 qw(:Status createSelfTiedObject);
8 use IO::Compress::RawDeflate 2.021 ;
9 use IO::Compress::Adapter::Deflate 2.021 ;
10 use IO::Compress::Adapter::Identity 2.021 ;
11 use IO::Compress::Zlib::Extra 2.021 ;
12 use IO::Compress::Zip::Constants 2.021 ;
15 use Compress::Raw::Zlib 2.021 qw(crc32) ;
18 eval { require IO::Compress::Adapter::Bzip2 ;
19 import IO::Compress::Adapter::Bzip2 2.021 ;
20 require IO::Compress::Bzip2 ;
21 import IO::Compress::Bzip2 2.021 ;
23 eval { require IO::Compress::Adapter::Lzma ;
24 import IO::Compress::Adapter::Lzma 2.020 ;
25 require IO::Compress::Lzma ;
26 import IO::Compress::Lzma 2.020 ;
33 our ($VERSION, @ISA, @EXPORT_OK, %EXPORT_TAGS, $ZipError);
38 @ISA = qw(Exporter IO::Compress::RawDeflate);
39 @EXPORT_OK = qw( $ZipError zip ) ;
40 %EXPORT_TAGS = %IO::Compress::RawDeflate::DEFLATE_CONSTANTS ;
41 push @{ $EXPORT_TAGS{all} }, @EXPORT_OK ;
43 $EXPORT_TAGS{zip_method} = [qw( ZIP_CM_STORE ZIP_CM_DEFLATE ZIP_CM_BZIP2 ZIP_CM_LZMA)];
44 push @{ $EXPORT_TAGS{all} }, @{ $EXPORT_TAGS{zip_method} };
46 Exporter::export_ok_tags('all');
52 my $obj = createSelfTiedObject($class, \$ZipError);
53 $obj->_create(undef, @_);
58 my $obj = createSelfTiedObject(undef, \$ZipError);
59 return $obj->_def(@_);
67 my ($obj, $errstr, $errno) ;
69 if (*$self->{ZipData}{Method} == ZIP_CM_STORE) {
70 ($obj, $errstr, $errno) = IO::Compress::Adapter::Identity::mkCompObject(
72 $got->value('Strategy')
74 *$self->{ZipData}{CRC32} = crc32(undef);
76 elsif (*$self->{ZipData}{Method} == ZIP_CM_DEFLATE) {
77 ($obj, $errstr, $errno) = IO::Compress::Adapter::Deflate::mkCompObject(
79 $got->value('Adler32'),
81 $got->value('Strategy')
84 elsif (*$self->{ZipData}{Method} == ZIP_CM_BZIP2) {
85 ($obj, $errstr, $errno) = IO::Compress::Adapter::Bzip2::mkCompObject(
86 $got->value('BlockSize100K'),
87 $got->value('WorkFactor'),
88 $got->value('Verbosity')
90 *$self->{ZipData}{CRC32} = crc32(undef);
92 elsif (*$self->{ZipData}{Method} == ZIP_CM_LZMA) {
93 ($obj, $errstr, $errno) = IO::Compress::Adapter::Lzma::mkCompObject();
94 *$self->{ZipData}{CRC32} = crc32(undef);
97 return $self->saveErrorString(undef, $errstr, $errno)
100 if (! defined *$self->{ZipData}{SizesOffset}) {
101 *$self->{ZipData}{SizesOffset} = 0;
102 *$self->{ZipData}{Offset} = new U64 ;
105 *$self->{ZipData}{AnyZip64} = 0
106 if ! defined *$self->{ZipData}{AnyZip64} ;
115 *$self->{Compress}->reset();
116 *$self->{ZipData}{CRC32} = Compress::Raw::Zlib::crc32('');
121 sub filterUncompressed
125 if (*$self->{ZipData}{Method} == ZIP_CM_DEFLATE) {
126 *$self->{ZipData}{CRC32} = *$self->{Compress}->crc32();
129 *$self->{ZipData}{CRC32} = crc32(${$_[0]}, *$self->{ZipData}{CRC32});
140 *$self->{ZipData}{LocalHdrOffset} = U64::clone(*$self->{ZipData}{Offset});
143 $filename = $param->value('Name') || '';
146 $comment = $param->value('Comment') || '';
150 my $time = _unixToDosTime($param->value('Time'));
155 my $osCode = $param->value('OS_Code') ;
156 my $extFileAttr = 0 ;
158 # This code assumes Unix.
159 $extFileAttr = 0666 << 16
160 if $osCode == ZIP_OS_CODE_UNIX ;
162 if (*$self->{ZipData}{Zip64}) {
166 $x .= pack "V V", 0, 0 ; # uncompressedLength
167 $x .= pack "V V", 0, 0 ; # compressedLength
168 $extra .= IO::Compress::Zlib::Extra::mkSubField(ZIP_EXTRA_ID_ZIP64, $x);
171 if (! $param->value('Minimal')) {
172 if (defined $param->value('exTime'))
174 $extra .= mkExtendedTime($param->value('MTime'),
175 $param->value('ATime'),
176 $param->value('CTime'));
178 $ctlExtra .= mkExtendedTime($param->value('MTime'));
181 if ( $param->value('UID') && $osCode == ZIP_OS_CODE_UNIX)
183 $extra .= mkUnix2Extra( $param->value('UID'), $param->value('GID'));
184 $ctlExtra .= mkUnix2Extra();
187 $extFileAttr = $param->value('ExtAttr')
188 if defined $param->value('ExtAttr') ;
190 $extra .= $param->value('ExtraFieldLocal')
191 if defined $param->value('ExtraFieldLocal');
193 $ctlExtra .= $param->value('ExtraFieldCentral')
194 if defined $param->value('ExtraFieldCentral');
198 $gpFlag |= ZIP_GP_FLAG_STREAMING_MASK
199 if *$self->{ZipData}{Stream} ;
201 my $method = *$self->{ZipData}{Method} ;
203 my $version = $ZIP_CM_MIN_VERSIONS{$method};
204 $version = ZIP64_MIN_VERSION
205 if ZIP64_MIN_VERSION > $version && *$self->{ZipData}{Zip64};
206 my $madeBy = ($param->value('OS_Code') << 8) + $version;
207 my $extract = $version;
209 *$self->{ZipData}{Version} = $version;
210 *$self->{ZipData}{MadeBy} = $madeBy;
213 $ifa |= ZIP_IFA_TEXT_MASK
214 if $param->value('TextFlag');
216 $hdr .= pack "V", ZIP_LOCAL_HDR_SIG ; # signature
217 $hdr .= pack 'v', $extract ; # extract Version & OS
218 $hdr .= pack 'v', $gpFlag ; # general purpose flag (set streaming mode)
219 $hdr .= pack 'v', $method ; # compression method (deflate)
220 $hdr .= pack 'V', $time ; # last mod date/time
221 $hdr .= pack 'V', 0 ; # crc32 - 0 when streaming
222 $hdr .= pack 'V', $empty ; # compressed length - 0 when streaming
223 $hdr .= pack 'V', $empty ; # uncompressed length - 0 when streaming
224 $hdr .= pack 'v', length $filename ; # filename length
225 $hdr .= pack 'v', length $extra ; # extra length
229 # Remember the offset for the compressed & uncompressed lengths in the
231 if (*$self->{ZipData}{Zip64}) {
232 *$self->{ZipData}{SizesOffset} = *$self->{ZipData}{Offset}->get64bit()
236 *$self->{ZipData}{SizesOffset} = *$self->{ZipData}{Offset}->get64bit()
245 $ctl .= pack "V", ZIP_CENTRAL_HDR_SIG ; # signature
246 $ctl .= pack 'v', $madeBy ; # version made by
247 $ctl .= pack 'v', $extract ; # extract Version
248 $ctl .= pack 'v', $gpFlag ; # general purpose flag (streaming mode)
249 $ctl .= pack 'v', $method ; # compression method (deflate)
250 $ctl .= pack 'V', $time ; # last mod date/time
251 $ctl .= pack 'V', 0 ; # crc32
252 $ctl .= pack 'V', $empty ; # compressed length
253 $ctl .= pack 'V', $empty ; # uncompressed length
254 $ctl .= pack 'v', length $filename ; # filename length
256 *$self->{ZipData}{ExtraOffset} = length $ctl;
257 *$self->{ZipData}{ExtraSize} = length $ctlExtra ;
259 $ctl .= pack 'v', length $ctlExtra ; # extra length
260 $ctl .= pack 'v', length $comment ; # file comment length
261 $ctl .= pack 'v', 0 ; # disk number start
262 $ctl .= pack 'v', $ifa ; # internal file attributes
263 $ctl .= pack 'V', $extFileAttr ; # external file attributes
265 # offset to local hdr
266 if (*$self->{ZipData}{LocalHdrOffset}->is64bit() ) {
267 $ctl .= pack 'V', 0xFFFFFFFF ;
270 $ctl .= *$self->{ZipData}{LocalHdrOffset}->getPacked_V32() ;
277 *$self->{ZipData}{Offset}->add(length $hdr) ;
279 *$self->{ZipData}{CentralHeader} = $ctl;
289 if (*$self->{ZipData}{Method} == ZIP_CM_DEFLATE) {
290 $crc32 = pack "V", *$self->{Compress}->crc32();
293 $crc32 = pack "V", *$self->{ZipData}{CRC32};
296 my $ctl = *$self->{ZipData}{CentralHeader} ;
299 if (! *$self->{ZipData}{Zip64}) {
300 $sizes .= *$self->{CompSize}->getPacked_V32() ; # Compressed size
301 $sizes .= *$self->{UnCompSize}->getPacked_V32() ; # Uncompressed size
304 $sizes .= *$self->{CompSize}->getPacked_V64() ; # Compressed size
305 $sizes .= *$self->{UnCompSize}->getPacked_V64() ; # Uncompressed size
308 my $data = $crc32 . $sizes ;
310 my $xtrasize = *$self->{UnCompSize}->getPacked_V64() ; # Uncompressed size
311 $xtrasize .= *$self->{CompSize}->getPacked_V64() ; # Compressed size
315 if (*$self->{ZipData}{Stream}) {
316 $hdr = pack "V", ZIP_DATA_HDR_SIG ; # signature
320 $self->writeAt(*$self->{ZipData}{LocalHdrOffset}->get64bit() + 14, $crc32)
322 $self->writeAt(*$self->{ZipData}{SizesOffset},
323 *$self->{ZipData}{Zip64} ? $xtrasize : $sizes)
327 # Central Header Record/Zip64 extended field
329 substr($ctl, 16, length $crc32) = $crc32 ;
333 # uncompressed length
334 if (*$self->{UnCompSize}->is64bit() ) {
335 $x .= *$self->{UnCompSize}->getPacked_V64() ;
337 substr($ctl, 24, 4) = *$self->{UnCompSize}->getPacked_V32() ;
341 if (*$self->{CompSize}->is64bit() ) {
342 $x .= *$self->{CompSize}->getPacked_V64() ;
344 substr($ctl, 20, 4) = *$self->{CompSize}->getPacked_V32() ;
347 # Local Header offset
348 $x .= *$self->{ZipData}{LocalHdrOffset}->getPacked_V64()
349 if *$self->{ZipData}{LocalHdrOffset}->is64bit() ;
351 # disk no - always zero, so don't need it
355 my $xtra = IO::Compress::Zlib::Extra::mkSubField(ZIP_EXTRA_ID_ZIP64, $x);
357 substr($ctl, *$self->{ZipData}{ExtraOffset}, 2) =
358 pack 'v', *$self->{ZipData}{ExtraSize} + length $xtra;
360 *$self->{ZipData}{AnyZip64} = 1;
363 *$self->{ZipData}{Offset}->add(length($hdr));
364 *$self->{ZipData}{Offset}->add( *$self->{CompSize} );
365 push @{ *$self->{ZipData}{CentralDir} }, $ctl ;
375 $comment = *$self->{ZipData}{ZipComment} ;
377 my $cd_offset = *$self->{ZipData}{Offset}->get32bit() ; # offset to start central dir
379 my $entries = @{ *$self->{ZipData}{CentralDir} };
380 my $cd = join '', @{ *$self->{ZipData}{CentralDir} };
381 my $cd_len = length $cd ;
385 if ( *$self->{ZipData}{AnyZip64} ) {
387 my $v = *$self->{ZipData}{Version} ;
388 my $mb = *$self->{ZipData}{MadeBy} ;
389 $z64e .= pack 'v', $mb ; # Version made by
390 $z64e .= pack 'v', $v ; # Version to extract
391 $z64e .= pack 'V', 0 ; # number of disk
392 $z64e .= pack 'V', 0 ; # number of disk with central dir
393 $z64e .= U64::pack_V64 $entries ; # entries in central dir on this disk
394 $z64e .= U64::pack_V64 $entries ; # entries in central dir
395 $z64e .= U64::pack_V64 $cd_len ; # size of central dir
396 $z64e .= *$self->{ZipData}{Offset}->getPacked_V64() ; # offset to start central dir
398 $z64e = pack("V", ZIP64_END_CENTRAL_REC_HDR_SIG) # signature
399 . U64::pack_V64(length $z64e)
402 *$self->{ZipData}{Offset}->add(length $cd) ;
404 $z64e .= pack "V", ZIP64_END_CENTRAL_LOC_HDR_SIG; # signature
405 $z64e .= pack 'V', 0 ; # number of disk with central dir
406 $z64e .= *$self->{ZipData}{Offset}->getPacked_V64() ; # offset to end zip64 central dir
407 $z64e .= pack 'V', 1 ; # Total number of disks
409 $cd_offset = 0xFFFFFFFF ;
410 $cd_len = 0xFFFFFFFF if $cd_len >= 0xFFFFFFFF ;
411 $entries = 0xFFFF if $entries >= 0xFFFF ;
415 $ecd .= pack "V", ZIP_END_CENTRAL_HDR_SIG ; # signature
416 $ecd .= pack 'v', 0 ; # number of disk
417 $ecd .= pack 'v', 0 ; # number of disk with central dir
418 $ecd .= pack 'v', $entries ; # entries in central dir on this disk
419 $ecd .= pack 'v', $entries ; # entries in central dir
420 $ecd .= pack 'V', $cd_len ; # size of central dir
421 $ecd .= pack 'V', $cd_offset ; # offset to start central dir
422 $ecd .= pack 'v', length $comment ; # zipfile comment length
425 return $cd . $z64e . $ecd ;
433 $got->value('CRC32' => 1);
435 if (! $got->parsed('Time') ) {
436 # Modification time defaults to now.
437 $got->value('Time' => time) ;
440 if ($got->parsed('exTime') ) {
441 my $timeRef = $got->value('exTime');
442 if ( defined $timeRef) {
443 return $self->saveErrorString(undef, "exTime not a 3-element array ref")
444 if ref $timeRef ne 'ARRAY' || @$timeRef != 3;
447 $got->value("MTime", $timeRef->[1]);
448 $got->value("ATime", $timeRef->[0]);
449 $got->value("CTime", $timeRef->[2]);
452 # Unix2 Extended Attribute
453 if ($got->parsed('exUnix2') ) {
454 my $timeRef = $got->value('exUnix2');
455 if ( defined $timeRef) {
456 return $self->saveErrorString(undef, "exUnix2 not a 2-element array ref")
457 if ref $timeRef ne 'ARRAY' || @$timeRef != 2;
460 $got->value("UID", $timeRef->[0]);
461 $got->value("GID", $timeRef->[1]);
464 *$self->{ZipData}{AnyZip64} = 1
465 if $got->value('Zip64');
466 *$self->{ZipData}{Zip64} = $got->value('Zip64');
467 *$self->{ZipData}{Stream} = $got->value('Stream');
469 my $method = $got->value('Method');
470 return $self->saveErrorString(undef, "Unknown Method '$method'")
471 if ! defined $ZIP_CM_MIN_VERSIONS{$method};
473 return $self->saveErrorString(undef, "Bzip2 not available")
474 if $method == ZIP_CM_BZIP2 and
475 ! defined $IO::Compress::Adapter::Bzip2::VERSION;
477 return $self->saveErrorString(undef, "Lzma not available")
478 if $method == ZIP_CM_LZMA and
479 ! defined $IO::Compress::Adapter::Lzma::VERSION;
481 *$self->{ZipData}{Method} = $method;
483 *$self->{ZipData}{ZipComment} = $got->value('ZipComment') ;
485 for my $name (qw( ExtraFieldLocal ExtraFieldCentral ))
487 my $data = $got->value($name) ;
489 my $bad = IO::Compress::Zlib::Extra::parseExtraField($data, 1, 0) ;
490 return $self->saveErrorString(undef, "Error with $name Parameter: $bad")
493 $got->value($name, $data) ;
498 if defined $IO::Compress::Bzip2::VERSION
499 and ! IO::Compress::Bzip2::ckParams($self, $got);
508 # return $self->mkHeader(*$self->{Got});
515 use IO::Compress::Base::Common 2.021 qw(:Parse);
516 use Compress::Raw::Zlib 2.021 qw(Z_DEFLATED Z_DEFAULT_COMPRESSION Z_DEFAULT_STRATEGY);
520 @Bzip2 = IO::Compress::Bzip2::getExtraParams($self)
521 if defined $IO::Compress::Bzip2::VERSION;
525 $self->getZlibParams(),
527 'Stream' => [1, 1, Parse_boolean, 1],
528 #'Store' => [0, 1, Parse_boolean, 0],
529 'Method' => [0, 1, Parse_unsigned, ZIP_CM_DEFLATE],
531 # # Zip header fields
532 'Minimal' => [0, 1, Parse_boolean, 0],
533 'Zip64' => [0, 1, Parse_boolean, 0],
534 'Comment' => [0, 1, Parse_any, ''],
535 'ZipComment'=> [0, 1, Parse_any, ''],
536 'Name' => [0, 1, Parse_any, ''],
537 'Time' => [0, 1, Parse_any, undef],
538 'exTime' => [0, 1, Parse_any, undef],
539 'exUnix2' => [0, 1, Parse_any, undef],
540 'ExtAttr' => [0, 1, Parse_any, 0],
541 'OS_Code' => [0, 1, Parse_unsigned, $Compress::Raw::Zlib::gzip_os_code],
543 'TextFlag' => [0, 1, Parse_boolean, 0],
544 'ExtraFieldLocal' => [0, 1, Parse_any, undef],
545 'ExtraFieldCentral'=> [0, 1, Parse_any, undef],
553 return ('IO::Uncompress::Unzip',
554 \$IO::Uncompress::Unzip::UnzipError);
561 my $filename = shift ;
563 my ($mode, $uid, $gid, $atime, $mtime, $ctime)
564 = (stat($filename))[2, 4,5, 8,9,10] ;
566 $params->value('Name' => $filename)
567 if ! $params->parsed('Name') ;
569 $params->value('Time' => $mtime)
570 if ! $params->parsed('Time') ;
572 if ( ! $params->parsed('exTime'))
574 $params->value('MTime' => $mtime) ;
575 $params->value('ATime' => $atime) ;
576 $params->value('CTime' => undef) ; # No Creation time
577 $params->value("exTime", [$mtime, $atime, undef]);
580 # NOTE - Unix specific code alert
581 $params->value('ExtAttr' => $mode << 16)
582 if ! $params->parsed('ExtAttr');
584 $params->value('UID' => $uid) ;
585 $params->value('GID' => $gid) ;
591 # order expected is m, a, c
602 $times .= pack("V", $time);
608 return IO::Compress::Zlib::Extra::mkSubField(ZIP_EXTRA_ID_EXT_TIMESTAMP,
609 pack("C", $flags) . $times);
617 $ids .= pack("v", $id);
620 return IO::Compress::Zlib::Extra::mkSubField(ZIP_EXTRA_ID_INFO_ZIP_UNIX2,
626 sub _unixToDosTime # Archive::Zip::Member
629 # TODO - add something to cope with unix time < 1980
630 my ( $sec, $min, $hour, $mday, $mon, $year ) = localtime($time_t);
632 $dt += ( $sec >> 1 );
633 $dt += ( $min << 5 );
634 $dt += ( $hour << 11 );
635 $dt += ( $mday << 16 );
636 $dt += ( ( $mon + 1 ) << 21 );
637 $dt += ( ( $year - 80 ) << 25 );
647 IO::Compress::Zip - Write zip files/buffers
653 use IO::Compress::Zip qw(zip $ZipError) ;
655 my $status = zip $input => $output [,OPTS]
656 or die "zip failed: $ZipError\n";
658 my $z = new IO::Compress::Zip $output [,OPTS]
659 or die "zip failed: $ZipError\n";
662 $z->printf($format, $string);
664 $z->syswrite($string [, $length, $offset]);
668 $z->seek($position, $whence);
673 $z->input_line_number();
674 $z->newStream( [OPTS] );
685 printf $z $format, $string;
688 seek $z, $position, $whence
696 This module provides a Perl interface that allows writing zip
697 compressed data to files or buffer.
699 The primary purpose of this module is to provide streaming write access to
700 zip files and buffers. It is not a general-purpose file archiver. If that
701 is what you want, check out C<Archive::Zip>.
703 At present three compression methods are supported by IO::Compress::Zip,
704 namely Store (no compression at all), Deflate and Bzip2.
706 Note that to create Bzip2 content, the module C<IO::Compress::Bzip2> must
709 For reading zip files/buffers, see the companion module
710 L<IO::Uncompress::Unzip|IO::Uncompress::Unzip>.
712 =head1 Functional Interface
714 A top-level function, C<zip>, is provided to carry out
715 "one-shot" compression between buffers and/or files. For finer
716 control over the compression process, see the L</"OO Interface">
719 use IO::Compress::Zip qw(zip $ZipError) ;
721 zip $input => $output [,OPTS]
722 or die "zip failed: $ZipError\n";
724 The functional interface needs Perl5.005 or better.
726 =head2 zip $input => $output [, OPTS]
728 C<zip> expects at least two parameters, C<$input> and C<$output>.
730 =head3 The C<$input> parameter
732 The parameter, C<$input>, is used to define the source of
733 the uncompressed data.
735 It can take one of the following forms:
741 If the C<$input> parameter is a simple scalar, it is assumed to be a
742 filename. This file will be opened for reading and the input data
743 will be read from it.
747 If the C<$input> parameter is a filehandle, the input data will be
749 The string '-' can be used as an alias for standard input.
751 =item A scalar reference
753 If C<$input> is a scalar reference, the input data will be read
756 =item An array reference
758 If C<$input> is an array reference, each element in the array must be a
761 The input data will be read from each file in turn.
763 The complete array will be walked to ensure that it only
764 contains valid filenames before any data is compressed.
766 =item An Input FileGlob string
768 If C<$input> is a string that is delimited by the characters "<" and ">"
769 C<zip> will assume that it is an I<input fileglob string>. The
770 input is the list of files that match the fileglob.
772 If the fileglob does not match any files ...
774 See L<File::GlobMapper|File::GlobMapper> for more details.
778 If the C<$input> parameter is any other type, C<undef> will be returned.
780 In addition, if C<$input> is a simple filename, the default values for
781 the C<Name>, C<Time>, C<ExtAttr> and C<exTime> options will be sourced from that file.
783 If you do not want to use these defaults they can be overridden by
784 explicitly setting the C<Name>, C<Time>, C<ExtAttr> and C<exTime> options or by setting the
785 C<Minimal> parameter.
787 =head3 The C<$output> parameter
789 The parameter C<$output> is used to control the destination of the
790 compressed data. This parameter can take one of these forms.
796 If the C<$output> parameter is a simple scalar, it is assumed to be a
797 filename. This file will be opened for writing and the compressed
798 data will be written to it.
802 If the C<$output> parameter is a filehandle, the compressed data
803 will be written to it.
804 The string '-' can be used as an alias for standard output.
806 =item A scalar reference
808 If C<$output> is a scalar reference, the compressed data will be
809 stored in C<$$output>.
811 =item An Array Reference
813 If C<$output> is an array reference, the compressed data will be
814 pushed onto the array.
816 =item An Output FileGlob
818 If C<$output> is a string that is delimited by the characters "<" and ">"
819 C<zip> will assume that it is an I<output fileglob string>. The
820 output is the list of files that match the fileglob.
822 When C<$output> is an fileglob string, C<$input> must also be a fileglob
823 string. Anything else is an error.
827 If the C<$output> parameter is any other type, C<undef> will be returned.
831 When C<$input> maps to multiple files/buffers and C<$output> is a single
832 file/buffer the input files/buffers will each be stored
833 in C<$output> as a distinct entry.
835 =head2 Optional Parameters
837 Unless specified below, the optional parameters for C<zip>,
838 C<OPTS>, are the same as those used with the OO interface defined in the
839 L</"Constructor Options"> section below.
843 =item C<< AutoClose => 0|1 >>
845 This option applies to any input or output data streams to
846 C<zip> that are filehandles.
848 If C<AutoClose> is specified, and the value is true, it will result in all
849 input and/or output filehandles being closed once C<zip> has
852 This parameter defaults to 0.
854 =item C<< BinModeIn => 0|1 >>
856 When reading from a file or filehandle, set C<binmode> before reading.
860 =item C<< Append => 0|1 >>
868 To read the contents of the file C<file1.txt> and write the compressed
869 data to the file C<file1.txt.zip>.
873 use IO::Compress::Zip qw(zip $ZipError) ;
875 my $input = "file1.txt";
876 zip $input => "$input.zip"
877 or die "zip failed: $ZipError\n";
879 To read from an existing Perl filehandle, C<$input>, and write the
880 compressed data to a buffer, C<$buffer>.
884 use IO::Compress::Zip qw(zip $ZipError) ;
887 my $input = new IO::File "<file1.txt"
888 or die "Cannot open 'file1.txt': $!\n" ;
890 zip $input => \$buffer
891 or die "zip failed: $ZipError\n";
893 To compress all files in the directory "/my/home" that match "*.txt"
894 and store the compressed data in the same directory
898 use IO::Compress::Zip qw(zip $ZipError) ;
900 zip '</my/home/*.txt>' => '<*.zip>'
901 or die "zip failed: $ZipError\n";
903 and if you want to compress each file one at a time, this will do the trick
907 use IO::Compress::Zip qw(zip $ZipError) ;
909 for my $input ( glob "/my/home/*.txt" )
911 my $output = "$input.zip" ;
912 zip $input => $output
913 or die "Error compressing '$input': $ZipError\n";
920 The format of the constructor for C<IO::Compress::Zip> is shown below
922 my $z = new IO::Compress::Zip $output [,OPTS]
923 or die "IO::Compress::Zip failed: $ZipError\n";
925 It returns an C<IO::Compress::Zip> object on success and undef on failure.
926 The variable C<$ZipError> will contain an error message on failure.
928 If you are running Perl 5.005 or better the object, C<$z>, returned from
929 IO::Compress::Zip can be used exactly like an L<IO::File|IO::File> filehandle.
930 This means that all normal output file operations can be carried out
932 For example, to write to a compressed file/buffer you can use either of
935 $z->print("hello world\n");
936 print $z "hello world\n";
938 The mandatory parameter C<$output> is used to control the destination
939 of the compressed data. This parameter can take one of these forms.
945 If the C<$output> parameter is a simple scalar, it is assumed to be a
946 filename. This file will be opened for writing and the compressed data
947 will be written to it.
951 If the C<$output> parameter is a filehandle, the compressed data will be
953 The string '-' can be used as an alias for standard output.
955 =item A scalar reference
957 If C<$output> is a scalar reference, the compressed data will be stored
962 If the C<$output> parameter is any other type, C<IO::Compress::Zip>::new will
965 =head2 Constructor Options
967 C<OPTS> is any combination of the following options:
971 =item C<< AutoClose => 0|1 >>
973 This option is only valid when the C<$output> parameter is a filehandle. If
974 specified, and the value is true, it will result in the C<$output> being
975 closed once either the C<close> method is called or the C<IO::Compress::Zip>
978 This parameter defaults to 0.
980 =item C<< Append => 0|1 >>
982 Opens C<$output> in append mode.
984 The behaviour of this option is dependent on the type of C<$output>.
990 If C<$output> is a buffer and C<Append> is enabled, all compressed data
991 will be append to the end if C<$output>. Otherwise C<$output> will be
992 cleared before any data is written to it.
996 If C<$output> is a filename and C<Append> is enabled, the file will be
997 opened in append mode. Otherwise the contents of the file, if any, will be
998 truncated before any compressed data is written to it.
1000 =item * A Filehandle
1002 If C<$output> is a filehandle, the file pointer will be positioned to the
1003 end of the file via a call to C<seek> before any compressed data is written
1004 to it. Otherwise the file pointer will not be moved.
1008 This parameter defaults to 0.
1010 =item C<< Name => $string >>
1012 Stores the contents of C<$string> in the zip filename header field. If
1013 C<Name> is not specified, no zip filename field will be created.
1015 =item C<< Time => $number >>
1017 Sets the last modified time field in the zip header to $number.
1019 This field defaults to the time the C<IO::Compress::Zip> object was created
1020 if this option is not specified.
1022 =item C<< ExtAttr => $attr >>
1024 This option controls the "external file attributes" field in the central
1025 header of the zip file. This is a 4 byte field.
1027 If you are running a Unix derivative this value defaults to
1031 This should allow read/write access to any files that are extracted from
1032 the zip file/buffer.
1034 For all other systems it defaults to 0.
1036 =item C<< exTime => [$atime, $mtime, $ctime] >>
1038 This option expects an array reference with exactly three elements:
1039 C<$atime>, C<mtime> and C<$ctime>. These correspond to the last access
1040 time, last modification time and creation time respectively.
1042 It uses these values to set the extended timestamp field (ID is "UT") in
1043 the local zip header using the three values, $atime, $mtime, $ctime. In
1044 addition it sets the extended timestamp field in the central zip header
1047 If any of the three values is C<undef> that time value will not be used.
1048 So, for example, to set only the C<$mtime> you would use this
1050 exTime => [undef, $mtime, undef]
1052 If the C<Minimal> option is set to true, this option will be ignored.
1054 By default no extended time field is created.
1056 =item C<< exUnix2 => [$uid, $gid] >>
1058 This option expects an array reference with exactly two elements: C<$uid>
1059 and C<$gid>. These values correspond to the numeric user ID and group ID
1060 of the owner of the files respectively.
1062 When the C<exUnix2> option is present it will trigger the creation of a
1063 Unix2 extra field (ID is "Ux") in the local zip. This will be populated
1064 with C<$uid> and C<$gid>. In addition an empty Unix2 extra field will also
1065 be created in the central zip header
1067 If the C<Minimal> option is set to true, this option will be ignored.
1069 By default no Unix2 extra field is created.
1071 =item C<< Comment => $comment >>
1073 Stores the contents of C<$comment> in the Central File Header of
1076 By default, no comment field is written to the zip file.
1078 =item C<< ZipComment => $comment >>
1080 Stores the contents of C<$comment> in the End of Central Directory record
1083 By default, no comment field is written to the zip file.
1085 =item C<< Method => $method >>
1087 Controls which compression method is used. At present three compression
1088 methods are supported, namely Store (no compression at all), Deflate and
1091 The symbols, ZIP_CM_STORE, ZIP_CM_DEFLATE and ZIP_CM_BZIP2 are used to
1092 select the compression method.
1094 These constants are not imported by C<IO::Compress::Zip> by default.
1096 use IO::Compress::Zip qw(:zip_method);
1097 use IO::Compress::Zip qw(:constants);
1098 use IO::Compress::Zip qw(:all);
1100 Note that to create Bzip2 content, the module C<IO::Compress::Bzip2> must
1101 be installed. A fatal error will be thrown if you attempt to create Bzip2
1102 content when C<IO::Compress::Bzip2> is not available.
1104 The default method is ZIP_CM_DEFLATE.
1106 =item C<< Stream => 0|1 >>
1108 This option controls whether the zip file/buffer output is created in
1111 Note that when outputting to a file with streaming mode disabled (C<Stream>
1112 is 0), the output file must be seekable.
1116 =item C<< Zip64 => 0|1 >>
1118 Create a Zip64 zip file/buffer. This option should only be used if you want
1119 to store files larger than 4 Gig.
1121 If you intend to manipulate the Zip64 zip files created with this module
1122 using an external zip/unzip make sure that it supports Zip64.
1124 In particular, if you are using Info-Zip you need to have zip version 3.x
1125 or better to update a Zip64 archive and unzip version 6.x to read a zip64
1130 =item C<< TextFlag => 0|1 >>
1132 This parameter controls the setting of a bit in the zip central header. It
1133 is used to signal that the data stored in the zip file/buffer is probably
1138 =item C<< ExtraFieldLocal => $data >>
1139 =item C<< ExtraFieldCentral => $data >>
1141 The C<ExtraFieldLocal> option is used to store additional metadata in the
1142 local header for the zip file/buffer. The C<ExtraFieldCentral> does the
1143 same for the matching central header.
1145 An extra field consists of zero or more subfields. Each subfield consists
1146 of a two byte header followed by the subfield data.
1148 The list of subfields can be supplied in any of the following formats
1150 ExtraFieldLocal => [$id1, $data1,
1155 ExtraFieldLocal => [ [$id1 => $data1],
1160 ExtraFieldLocal => { $id1 => $data1,
1165 Where C<$id1>, C<$id2> are two byte subfield ID's.
1167 If you use the hash syntax, you have no control over the order in which
1168 the ExtraSubFields are stored, plus you cannot have SubFields with
1171 Alternatively the list of subfields can by supplied as a scalar, thus
1173 ExtraField => $rawdata
1175 The Extended Time field (ID "UT"), set using the C<exTime> option, and the
1176 Unix2 extra field (ID "Ux), set using the C<exUnix2> option, are examples
1179 If the C<Minimal> option is set to true, this option will be ignored.
1181 The maximum size of an extra field 65535 bytes.
1183 =item C<< Minimal => 1|0 >>
1185 If specified, this option will disable the creation of all extra fields
1186 in the zip local and central headers. So the C<exTime>, C<exUnix2>,
1187 C<ExtraFieldLocal> and C<ExtraFieldCentral> options will be ignored.
1189 This parameter defaults to 0.
1191 =item C<< BlockSize100K => number >>
1193 Specify the number of 100K blocks bzip2 uses during compression.
1195 Valid values are from 1 to 9, where 9 is best compression.
1197 This option is only valid if the C<Method> is ZIP_CM_BZIP2. It is ignored
1202 =item C<< WorkFactor => number >>
1204 Specifies how much effort bzip2 should take before resorting to a slower
1205 fallback compression algorithm.
1207 Valid values range from 0 to 250, where 0 means use the default value 30.
1209 This option is only valid if the C<Method> is ZIP_CM_BZIP2. It is ignored
1216 Defines the compression level used by zlib. The value should either be
1217 a number between 0 and 9 (0 means no compression and 9 is maximum
1218 compression), or one of the symbolic constants defined below.
1223 Z_DEFAULT_COMPRESSION
1225 The default is Z_DEFAULT_COMPRESSION.
1227 Note, these constants are not imported by C<IO::Compress::Zip> by default.
1229 use IO::Compress::Zip qw(:strategy);
1230 use IO::Compress::Zip qw(:constants);
1231 use IO::Compress::Zip qw(:all);
1235 Defines the strategy used to tune the compression. Use one of the symbolic
1236 constants defined below.
1244 The default is Z_DEFAULT_STRATEGY.
1246 =item C<< Strict => 0|1 >>
1248 This is a placeholder option.
1265 Compresses and outputs the contents of the C<$data> parameter. This
1266 has the same behaviour as the C<print> built-in.
1268 Returns true if successful.
1274 $z->printf($format, $data)
1275 printf $z $format, $data
1277 Compresses and outputs the contents of the C<$data> parameter.
1279 Returns true if successful.
1286 $z->syswrite $data, $length
1287 $z->syswrite $data, $length, $offset
1289 Compresses and outputs the contents of the C<$data> parameter.
1291 Returns the number of uncompressed bytes written, or C<undef> if
1299 $z->write $data, $length
1300 $z->write $data, $length, $offset
1302 Compresses and outputs the contents of the C<$data> parameter.
1304 Returns the number of uncompressed bytes written, or C<undef> if
1312 $z->flush($flush_type);
1314 Flushes any pending compressed data to the output file/buffer.
1316 This method takes an optional parameter, C<$flush_type>, that controls
1317 how the flushing will be carried out. By default the C<$flush_type>
1318 used is C<Z_FINISH>. Other valid values for C<$flush_type> are
1319 C<Z_NO_FLUSH>, C<Z_SYNC_FLUSH>, C<Z_FULL_FLUSH> and C<Z_BLOCK>. It is
1320 strongly recommended that you only set the C<flush_type> parameter if
1321 you fully understand the implications of what it does - overuse of C<flush>
1322 can seriously degrade the level of compression achieved. See the C<zlib>
1323 documentation for details.
1325 Returns true on success.
1334 Returns the uncompressed file offset.
1343 Returns true if the C<close> method has been called.
1347 $z->seek($position, $whence);
1348 seek($z, $position, $whence);
1350 Provides a sub-set of the C<seek> functionality, with the restriction
1351 that it is only legal to seek forward in the output file/buffer.
1352 It is a fatal error to attempt to seek backward.
1354 Empty parts of the file/buffer will have NULL (0x00) bytes written to them.
1356 The C<$whence> parameter takes one the usual values, namely SEEK_SET,
1357 SEEK_CUR or SEEK_END.
1359 Returns 1 on success, 0 on failure.
1368 This is a noop provided for completeness.
1374 Returns true if the object currently refers to a opened file/buffer.
1378 my $prev = $z->autoflush()
1379 my $prev = $z->autoflush(EXPR)
1381 If the C<$z> object is associated with a file or a filehandle, this method
1382 returns the current autoflush setting for the underlying filehandle. If
1383 C<EXPR> is present, and is non-zero, it will enable flushing after every
1384 write/print operation.
1386 If C<$z> is associated with a buffer, this method has no effect and always
1389 B<Note> that the special variable C<$|> B<cannot> be used to set or
1390 retrieve the autoflush setting.
1392 =head2 input_line_number
1394 $z->input_line_number()
1395 $z->input_line_number(EXPR)
1397 This method always returns C<undef> when compressing.
1404 If the C<$z> object is associated with a file or a filehandle, C<fileno>
1405 will return the underlying file descriptor. Once the C<close> method is
1406 called C<fileno> will return C<undef>.
1408 If the C<$z> object is is associated with a buffer, this method will return
1416 Flushes any pending compressed data and then closes the output file/buffer.
1418 For most versions of Perl this method will be automatically invoked if
1419 the IO::Compress::Zip object is destroyed (either explicitly or by the
1420 variable with the reference to the object going out of scope). The
1421 exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In
1422 these cases, the C<close> method will be called automatically, but
1423 not until global destruction of all live objects when the program is
1426 Therefore, if you want your scripts to be able to run on all versions
1427 of Perl, you should call C<close> explicitly and not rely on automatic
1430 Returns true on success, otherwise 0.
1432 If the C<AutoClose> option has been enabled when the IO::Compress::Zip
1433 object was created, and the object is associated with a file, the
1434 underlying file will also be closed.
1436 =head2 newStream([OPTS])
1440 $z->newStream( [OPTS] )
1442 Closes the current compressed data stream and starts a new one.
1444 OPTS consists of any of the the options that are available when creating
1447 See the L</"Constructor Options"> section for more details.
1449 =head2 deflateParams
1459 A number of symbolic constants are required by some methods in
1460 C<IO::Compress::Zip>. None are imported by default.
1466 Imports C<zip>, C<$ZipError> and all symbolic
1467 constants that can be used by C<IO::Compress::Zip>. Same as doing this
1469 use IO::Compress::Zip qw(zip $ZipError :constants) ;
1473 Import all symbolic constants. Same as doing this
1475 use IO::Compress::Zip qw(:flush :level :strategy :zip_method) ;
1479 These symbolic constants are used by the C<flush> method.
1490 These symbolic constants are used by the C<Level> option in the constructor.
1495 Z_DEFAULT_COMPRESSION
1499 These symbolic constants are used by the C<Strategy> option in the constructor.
1509 These symbolic constants are used by the C<Method> option in the
1523 =head2 Apache::GZip Revisited
1525 See L<IO::Compress::FAQ|IO::Compress::FAQ/"Apache::GZip Revisited">
1529 =head2 Working with Net::FTP
1531 See L<IO::Compress::FAQ|IO::Compress::FAQ/"Compressed files and Net::FTP">
1535 L<Compress::Zlib>, L<IO::Compress::Gzip>, L<IO::Uncompress::Gunzip>, L<IO::Compress::Deflate>, L<IO::Uncompress::Inflate>, L<IO::Compress::RawDeflate>, L<IO::Uncompress::RawInflate>, L<IO::Compress::Bzip2>, L<IO::Uncompress::Bunzip2>, L<IO::Compress::Lzop>, L<IO::Uncompress::UnLzop>, L<IO::Compress::Lzf>, L<IO::Uncompress::UnLzf>, L<IO::Uncompress::AnyInflate>, L<IO::Uncompress::AnyUncompress>
1537 L<Compress::Zlib::FAQ|Compress::Zlib::FAQ>
1539 L<File::GlobMapper|File::GlobMapper>, L<Archive::Zip|Archive::Zip>,
1540 L<Archive::Tar|Archive::Tar>,
1541 L<IO::Zlib|IO::Zlib>
1543 For RFC 1950, 1951 and 1952 see
1544 F<http://www.faqs.org/rfcs/rfc1950.html>,
1545 F<http://www.faqs.org/rfcs/rfc1951.html> and
1546 F<http://www.faqs.org/rfcs/rfc1952.html>
1548 The I<zlib> compression library was written by Jean-loup Gailly
1549 F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>.
1551 The primary site for the I<zlib> compression library is
1552 F<http://www.zlib.org>.
1554 The primary site for gzip is F<http://www.gzip.org>.
1558 This module was written by Paul Marquess, F<pmqs@cpan.org>.
1560 =head1 MODIFICATION HISTORY
1562 See the Changes file.
1564 =head1 COPYRIGHT AND LICENSE
1566 Copyright (c) 2005-2009 Paul Marquess. All rights reserved.
1568 This program is free software; you can redistribute it and/or
1569 modify it under the same terms as Perl itself.