1 package IO::Compress::Zip ;
7 use IO::Compress::Base::Common 2.017 qw(:Status createSelfTiedObject);
8 use IO::Compress::RawDeflate 2.017 ;
9 use IO::Compress::Adapter::Deflate 2.017 ;
10 use IO::Compress::Adapter::Identity 2.017 ;
11 use IO::Compress::Zlib::Extra 2.017 ;
12 use IO::Compress::Zip::Constants 2.017 ;
15 use Compress::Raw::Zlib 2.017 qw(crc32) ;
18 eval { require IO::Compress::Adapter::Bzip2 ;
19 import IO::Compress::Adapter::Bzip2 2.017 ;
20 require IO::Compress::Bzip2 ;
21 import IO::Compress::Bzip2 2.017 ;
23 # eval { require IO::Compress::Adapter::Lzma ;
24 # import IO::Compress::Adapter::Lzma 2.017 ;
25 # require IO::Compress::Lzma ;
26 # import IO::Compress::Lzma 2.017 ;
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 )];
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')
75 elsif (*$self->{ZipData}{Method} == ZIP_CM_DEFLATE) {
76 ($obj, $errstr, $errno) = IO::Compress::Adapter::Deflate::mkCompObject(
78 $got->value('Adler32'),
80 $got->value('Strategy')
83 elsif (*$self->{ZipData}{Method} == ZIP_CM_BZIP2) {
84 ($obj, $errstr, $errno) = IO::Compress::Adapter::Bzip2::mkCompObject(
85 $got->value('BlockSize100K'),
86 $got->value('WorkFactor'),
87 $got->value('Verbosity')
89 *$self->{ZipData}{CRC32} = crc32(undef);
91 # elsif (*$self->{ZipData}{Method} == ZIP_CM_LZMA) {
92 # ($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}{StartOffset}) {
101 *$self->{ZipData}{StartOffset} = 0;
102 *$self->{ZipData}{Offset} = new U64 ;
112 *$self->{Compress}->reset();
113 *$self->{ZipData}{CRC32} = Compress::Raw::Zlib::crc32('');
118 sub filterUncompressed
122 if (*$self->{ZipData}{Method} == ZIP_CM_DEFLATE) {
123 *$self->{ZipData}{CRC32} = *$self->{Compress}->crc32();
126 *$self->{ZipData}{CRC32} = crc32(${$_[0]}, *$self->{ZipData}{CRC32});
136 *$self->{ZipData}{StartOffset} = *$self->{ZipData}{Offset}->get32bit() ;
139 $filename = $param->value('Name') || '';
142 $comment = $param->value('Comment') || '';
146 my $time = _unixToDosTime($param->value('Time'));
151 my $osCode = $param->value('OS_Code') ;
152 my $extFileAttr = 0 ;
154 # This code assumes Unix.
155 $extFileAttr = 0666 << 16
156 if $osCode == ZIP_OS_CODE_UNIX ;
158 if (*$self->{ZipData}{Zip64}) {
162 $x .= pack "V V", 0, 0 ; # uncompressedLength
163 $x .= pack "V V", 0, 0 ; # compressedLength
164 $x .= *$self->{ZipData}{Offset}->getPacked_V64() ; # offset to local hdr
165 $x .= pack "V", 0 ; # disk no
167 $x = IO::Compress::Zlib::Extra::mkSubField(ZIP_EXTRA_ID_ZIP64, $x);
172 if (! $param->value('Minimal')) {
173 if (defined $param->value('exTime'))
175 $extra .= mkExtendedTime($param->value('MTime'),
176 $param->value('ATime'),
177 $param->value('CTime'));
179 $ctlExtra .= mkExtendedTime($param->value('MTime'));
182 if ( $param->value('UID') && $osCode == ZIP_OS_CODE_UNIX)
184 $extra .= mkUnix2Extra( $param->value('UID'), $param->value('GID'));
185 $ctlExtra .= mkUnix2Extra();
188 $extFileAttr = $param->value('ExtAttr')
189 if defined $param->value('ExtAttr') ;
191 $extra .= $param->value('ExtraFieldLocal')
192 if defined $param->value('ExtraFieldLocal');
194 $ctlExtra .= $param->value('ExtraFieldCentral')
195 if defined $param->value('ExtraFieldCentral');
199 $gpFlag |= ZIP_GP_FLAG_STREAMING_MASK
200 if *$self->{ZipData}{Stream} ;
202 my $method = *$self->{ZipData}{Method} ;
204 my $version = $ZIP_CM_MIN_VERSIONS{$method};
205 $version = ZIP64_MIN_VERSION
206 if ZIP64_MIN_VERSION > $version && *$self->{ZipData}{Zip64};
207 my $madeBy = ($param->value('OS_Code') << 8) + $version;
208 my $extract = $version;
210 *$self->{ZipData}{Version} = $version;
211 *$self->{ZipData}{MadeBy} = $madeBy;
214 $ifa |= ZIP_IFA_TEXT_MASK
215 if $param->value('TextFlag');
217 $hdr .= pack "V", ZIP_LOCAL_HDR_SIG ; # signature
218 $hdr .= pack 'v', $extract ; # extract Version & OS
219 $hdr .= pack 'v', $gpFlag ; # general purpose flag (set streaming mode)
220 $hdr .= pack 'v', $method ; # compression method (deflate)
221 $hdr .= pack 'V', $time ; # last mod date/time
222 $hdr .= pack 'V', 0 ; # crc32 - 0 when streaming
223 $hdr .= pack 'V', $empty ; # compressed length - 0 when streaming
224 $hdr .= pack 'V', $empty ; # uncompressed length - 0 when streaming
225 $hdr .= pack 'v', length $filename ; # filename length
226 $hdr .= pack 'v', length $extra ; # extra length
234 $ctl .= pack "V", ZIP_CENTRAL_HDR_SIG ; # signature
235 $ctl .= pack 'v', $madeBy ; # version made by
236 $ctl .= pack 'v', $extract ; # extract Version
237 $ctl .= pack 'v', $gpFlag ; # general purpose flag (streaming mode)
238 $ctl .= pack 'v', $method ; # compression method (deflate)
239 $ctl .= pack 'V', $time ; # last mod date/time
240 $ctl .= pack 'V', 0 ; # crc32
241 $ctl .= pack 'V', $empty ; # compressed length
242 $ctl .= pack 'V', $empty ; # uncompressed length
243 $ctl .= pack 'v', length $filename ; # filename length
244 $ctl .= pack 'v', length $ctlExtra ; # extra length
245 $ctl .= pack 'v', length $comment ; # file comment length
246 $ctl .= pack 'v', 0 ; # disk number start
247 $ctl .= pack 'v', $ifa ; # internal file attributes
248 $ctl .= pack 'V', $extFileAttr ; # external file attributes
249 if (! *$self->{ZipData}{Zip64}) {
250 $ctl .= pack 'V', *$self->{ZipData}{Offset}->get32bit() ; # offset to local header
253 $ctl .= pack 'V', $empty ; # offset to local header
257 *$self->{ZipData}{StartOffset64} = 4 + length $ctl;
261 *$self->{ZipData}{Offset}->add(length $hdr) ;
263 *$self->{ZipData}{CentralHeader} = $ctl;
273 if (*$self->{ZipData}{Method} == ZIP_CM_DEFLATE) {
274 $crc32 = pack "V", *$self->{Compress}->crc32();
277 $crc32 = pack "V", *$self->{ZipData}{CRC32};
280 my $ctl = *$self->{ZipData}{CentralHeader} ;
283 if (! *$self->{ZipData}{Zip64}) {
284 $sizes .= *$self->{CompSize}->getPacked_V32() ; # Compressed size
285 $sizes .= *$self->{UnCompSize}->getPacked_V32() ; # Uncompressed size
288 $sizes .= *$self->{CompSize}->getPacked_V64() ; # Compressed size
289 $sizes .= *$self->{UnCompSize}->getPacked_V64() ; # Uncompressed size
292 my $data = $crc32 . $sizes ;
297 if (*$self->{ZipData}{Stream}) {
298 $hdr = pack "V", ZIP_DATA_HDR_SIG ; # signature
302 $self->writeAt(*$self->{ZipData}{StartOffset} + 14, $data)
306 if (! *$self->{ZipData}{Zip64})
307 { substr($ctl, 16, length $data) = $data }
309 substr($ctl, 16, length $crc32) = $crc32 ;
310 my $s = *$self->{UnCompSize}->getPacked_V64() ; # Uncompressed size
311 $s .= *$self->{CompSize}->getPacked_V64() ; # Compressed size
312 substr($ctl, *$self->{ZipData}{StartOffset64}, length $s) = $s ;
315 *$self->{ZipData}{Offset}->add(length($hdr));
316 *$self->{ZipData}{Offset}->add( *$self->{CompSize} );
317 push @{ *$self->{ZipData}{CentralDir} }, $ctl ;
327 $comment = *$self->{ZipData}{ZipComment} ;
329 my $cd_offset = *$self->{ZipData}{Offset}->get32bit() ; # offset to start central dir
331 my $entries = @{ *$self->{ZipData}{CentralDir} };
332 my $cd = join '', @{ *$self->{ZipData}{CentralDir} };
333 my $cd_len = length $cd ;
337 if ( *$self->{ZipData}{Zip64} ) {
339 my $v = *$self->{ZipData}{Version} ;
340 my $mb = *$self->{ZipData}{MadeBy} ;
341 $z64e .= pack 'v', $v ; # Version made by
342 $z64e .= pack 'v', $mb ; # Version to extract
343 $z64e .= pack 'V', 0 ; # number of disk
344 $z64e .= pack 'V', 0 ; # number of disk with central dir
345 $z64e .= U64::pack_V64 $entries ; # entries in central dir on this disk
346 $z64e .= U64::pack_V64 $entries ; # entries in central dir
347 $z64e .= U64::pack_V64 $cd_len ; # size of central dir
348 $z64e .= *$self->{ZipData}{Offset}->getPacked_V64() ; # offset to start central dir
350 $z64e = pack("V", ZIP64_END_CENTRAL_REC_HDR_SIG) # signature
351 . U64::pack_V64(length $z64e)
354 *$self->{ZipData}{Offset}->add(length $cd) ;
356 $z64e .= pack "V", ZIP64_END_CENTRAL_LOC_HDR_SIG; # signature
357 $z64e .= pack 'V', 0 ; # number of disk with central dir
358 $z64e .= *$self->{ZipData}{Offset}->getPacked_V64() ; # offset to end zip64 central dir
359 $z64e .= pack 'V', 1 ; # Total number of disks
361 # TODO - fix these when info-zip 3 is fixed.
368 $ecd .= pack "V", ZIP_END_CENTRAL_HDR_SIG ; # signature
369 $ecd .= pack 'v', 0 ; # number of disk
370 $ecd .= pack 'v', 0 ; # number of disk with central dir
371 $ecd .= pack 'v', $entries ; # entries in central dir on this disk
372 $ecd .= pack 'v', $entries ; # entries in central dir
373 $ecd .= pack 'V', $cd_len ; # size of central dir
374 $ecd .= pack 'V', $cd_offset ; # offset to start central dir
375 $ecd .= pack 'v', length $comment ; # zipfile comment length
378 return $cd . $z64e . $ecd ;
386 $got->value('CRC32' => 1);
388 if (! $got->parsed('Time') ) {
389 # Modification time defaults to now.
390 $got->value('Time' => time) ;
393 if (! $got->parsed('exTime') ) {
394 my $timeRef = $got->value('exTime');
395 if ( defined $timeRef) {
396 return $self->saveErrorString(undef, "exTime not a 3-element array ref")
397 if ref $timeRef ne 'ARRAY' || @$timeRef != 3;
400 $got->value("MTime", $timeRef->[1]);
401 $got->value("ATime", $timeRef->[0]);
402 $got->value("CTime", $timeRef->[2]);
405 # Unix2 Extended Attribute
406 if (! $got->parsed('exUnix2') ) {
407 my $timeRef = $got->value('exUnix2');
408 if ( defined $timeRef) {
409 return $self->saveErrorString(undef, "exUnix2 not a 2-element array ref")
410 if ref $timeRef ne 'ARRAY' || @$timeRef != 2;
413 $got->value("UID", $timeRef->[0]);
414 $got->value("GID", $timeRef->[1]);
417 *$self->{ZipData}{Zip64} = $got->value('Zip64');
418 *$self->{ZipData}{Stream} = $got->value('Stream');
420 return $self->saveErrorString(undef, "Zip64 only supported if Stream enabled")
421 if *$self->{ZipData}{Zip64} && ! *$self->{ZipData}{Stream} ;
423 my $method = $got->value('Method');
424 return $self->saveErrorString(undef, "Unknown Method '$method'")
425 if ! defined $ZIP_CM_MIN_VERSIONS{$method};
427 return $self->saveErrorString(undef, "Bzip2 not available")
428 if $method == ZIP_CM_BZIP2 and
429 ! defined $IO::Compress::Adapter::Bzip2::VERSION;
431 # return $self->saveErrorString(undef, "Lzma not available")
432 # if $method == ZIP_CM_LZMA and
433 # ! defined $IO::Compress::Adapter::Lzma::VERSION;
435 *$self->{ZipData}{Method} = $method;
437 *$self->{ZipData}{ZipComment} = $got->value('ZipComment') ;
439 for my $name (qw( ExtraFieldLocal ExtraFieldCentral ))
441 my $data = $got->value($name) ;
443 my $bad = IO::Compress::Zlib::Extra::parseExtraField($data, 1, 0) ;
444 return $self->saveErrorString(undef, "Error with $name Parameter: $bad")
447 $got->value($name, $data) ;
452 if defined $IO::Compress::Bzip2::VERSION
453 and ! IO::Compress::Bzip2::ckParams($self, $got);
462 # return $self->mkHeader(*$self->{Got});
469 use IO::Compress::Base::Common 2.017 qw(:Parse);
470 use Compress::Raw::Zlib 2.017 qw(Z_DEFLATED Z_DEFAULT_COMPRESSION Z_DEFAULT_STRATEGY);
474 @Bzip2 = IO::Compress::Bzip2::getExtraParams($self)
475 if defined $IO::Compress::Bzip2::VERSION;
479 $self->getZlibParams(),
481 'Stream' => [1, 1, Parse_boolean, 1],
482 #'Store' => [0, 1, Parse_boolean, 0],
483 'Method' => [0, 1, Parse_unsigned, ZIP_CM_DEFLATE],
485 # # Zip header fields
486 'Minimal' => [0, 1, Parse_boolean, 0],
487 'Zip64' => [0, 1, Parse_boolean, 0],
488 'Comment' => [0, 1, Parse_any, ''],
489 'ZipComment'=> [0, 1, Parse_any, ''],
490 'Name' => [0, 1, Parse_any, ''],
491 'Time' => [0, 1, Parse_any, undef],
492 'exTime' => [0, 1, Parse_any, undef],
493 'exUnix2' => [0, 1, Parse_any, undef],
494 'ExtAttr' => [0, 1, Parse_any, 0],
495 'OS_Code' => [0, 1, Parse_unsigned, $Compress::Raw::Zlib::gzip_os_code],
497 'TextFlag' => [0, 1, Parse_boolean, 0],
498 'ExtraFieldLocal' => [0, 1, Parse_any, undef],
499 'ExtraFieldCentral'=> [0, 1, Parse_any, undef],
507 return ('IO::Uncompress::Unzip',
508 \$IO::Uncompress::Unzip::UnzipError);
515 my $filename = shift ;
517 my ($mode, $uid, $gid, $atime, $mtime, $ctime)
518 = (stat($filename))[2, 4,5, 8,9,10] ;
520 $params->value('Name' => $filename)
521 if ! $params->parsed('Name') ;
523 $params->value('Time' => $mtime)
524 if ! $params->parsed('Time') ;
526 if ( ! $params->parsed('exTime'))
528 $params->value('MTime' => $mtime) ;
529 $params->value('ATime' => $atime) ;
530 $params->value('CTime' => undef) ; # No Creation time
533 # NOTE - Unix specific code alert
534 $params->value('ExtAttr' => $mode << 16)
535 if ! $params->parsed('ExtAttr');
537 $params->value('UID' => $uid) ;
538 $params->value('GID' => $gid) ;
544 # order expected is m, a, c
555 $times .= pack("V", $time);
561 return IO::Compress::Zlib::Extra::mkSubField(ZIP_EXTRA_ID_EXT_TIMESTAMP,
562 pack("C", $flags) . $times);
570 $ids .= pack("v", $id);
573 return IO::Compress::Zlib::Extra::mkSubField(ZIP_EXTRA_ID_INFO_ZIP_UNIX2,
579 sub _unixToDosTime # Archive::Zip::Member
582 # TODO - add something to cope with unix time < 1980
583 my ( $sec, $min, $hour, $mday, $mon, $year ) = localtime($time_t);
585 $dt += ( $sec >> 1 );
586 $dt += ( $min << 5 );
587 $dt += ( $hour << 11 );
588 $dt += ( $mday << 16 );
589 $dt += ( ( $mon + 1 ) << 21 );
590 $dt += ( ( $year - 80 ) << 25 );
600 IO::Compress::Zip - Write zip files/buffers
606 use IO::Compress::Zip qw(zip $ZipError) ;
608 my $status = zip $input => $output [,OPTS]
609 or die "zip failed: $ZipError\n";
611 my $z = new IO::Compress::Zip $output [,OPTS]
612 or die "zip failed: $ZipError\n";
615 $z->printf($format, $string);
617 $z->syswrite($string [, $length, $offset]);
621 $z->seek($position, $whence);
626 $z->input_line_number();
627 $z->newStream( [OPTS] );
638 printf $z $format, $string;
641 seek $z, $position, $whence
649 This module provides a Perl interface that allows writing zip
650 compressed data to files or buffer.
652 The primary purpose of this module is to provide streaming write access to
653 zip files and buffers. It is not a general-purpose file archiver. If that
654 is what you want, check out C<Archive::Zip>.
656 At present three compression methods are supported by IO::Compress::Zip,
657 namely Store (no compression at all), Deflate and Bzip2.
659 Note that to create Bzip2 content, the module C<IO::Compress::Bzip2> must
662 For reading zip files/buffers, see the companion module
663 L<IO::Uncompress::Unzip|IO::Uncompress::Unzip>.
665 =head1 Functional Interface
667 A top-level function, C<zip>, is provided to carry out
668 "one-shot" compression between buffers and/or files. For finer
669 control over the compression process, see the L</"OO Interface">
672 use IO::Compress::Zip qw(zip $ZipError) ;
674 zip $input => $output [,OPTS]
675 or die "zip failed: $ZipError\n";
677 The functional interface needs Perl5.005 or better.
679 =head2 zip $input => $output [, OPTS]
681 C<zip> expects at least two parameters, C<$input> and C<$output>.
683 =head3 The C<$input> parameter
685 The parameter, C<$input>, is used to define the source of
686 the uncompressed data.
688 It can take one of the following forms:
694 If the C<$input> parameter is a simple scalar, it is assumed to be a
695 filename. This file will be opened for reading and the input data
696 will be read from it.
700 If the C<$input> parameter is a filehandle, the input data will be
702 The string '-' can be used as an alias for standard input.
704 =item A scalar reference
706 If C<$input> is a scalar reference, the input data will be read
709 =item An array reference
711 If C<$input> is an array reference, each element in the array must be a
714 The input data will be read from each file in turn.
716 The complete array will be walked to ensure that it only
717 contains valid filenames before any data is compressed.
719 =item An Input FileGlob string
721 If C<$input> is a string that is delimited by the characters "<" and ">"
722 C<zip> will assume that it is an I<input fileglob string>. The
723 input is the list of files that match the fileglob.
725 If the fileglob does not match any files ...
727 See L<File::GlobMapper|File::GlobMapper> for more details.
731 If the C<$input> parameter is any other type, C<undef> will be returned.
733 In addition, if C<$input> is a simple filename, the default values for
734 the C<Name>, C<Time>, C<ExtAttr> and C<exTime> options will be sourced from that file.
736 If you do not want to use these defaults they can be overridden by
737 explicitly setting the C<Name>, C<Time>, C<ExtAttr> and C<exTime> options or by setting the
738 C<Minimal> parameter.
740 =head3 The C<$output> parameter
742 The parameter C<$output> is used to control the destination of the
743 compressed data. This parameter can take one of these forms.
749 If the C<$output> parameter is a simple scalar, it is assumed to be a
750 filename. This file will be opened for writing and the compressed
751 data will be written to it.
755 If the C<$output> parameter is a filehandle, the compressed data
756 will be written to it.
757 The string '-' can be used as an alias for standard output.
759 =item A scalar reference
761 If C<$output> is a scalar reference, the compressed data will be
762 stored in C<$$output>.
764 =item An Array Reference
766 If C<$output> is an array reference, the compressed data will be
767 pushed onto the array.
769 =item An Output FileGlob
771 If C<$output> is a string that is delimited by the characters "<" and ">"
772 C<zip> will assume that it is an I<output fileglob string>. The
773 output is the list of files that match the fileglob.
775 When C<$output> is an fileglob string, C<$input> must also be a fileglob
776 string. Anything else is an error.
780 If the C<$output> parameter is any other type, C<undef> will be returned.
784 When C<$input> maps to multiple files/buffers and C<$output> is a single
785 file/buffer the input files/buffers will each be stored
786 in C<$output> as a distinct entry.
788 =head2 Optional Parameters
790 Unless specified below, the optional parameters for C<zip>,
791 C<OPTS>, are the same as those used with the OO interface defined in the
792 L</"Constructor Options"> section below.
796 =item C<< AutoClose => 0|1 >>
798 This option applies to any input or output data streams to
799 C<zip> that are filehandles.
801 If C<AutoClose> is specified, and the value is true, it will result in all
802 input and/or output filehandles being closed once C<zip> has
805 This parameter defaults to 0.
807 =item C<< BinModeIn => 0|1 >>
809 When reading from a file or filehandle, set C<binmode> before reading.
813 =item C<< Append => 0|1 >>
821 To read the contents of the file C<file1.txt> and write the compressed
822 data to the file C<file1.txt.zip>.
826 use IO::Compress::Zip qw(zip $ZipError) ;
828 my $input = "file1.txt";
829 zip $input => "$input.zip"
830 or die "zip failed: $ZipError\n";
832 To read from an existing Perl filehandle, C<$input>, and write the
833 compressed data to a buffer, C<$buffer>.
837 use IO::Compress::Zip qw(zip $ZipError) ;
840 my $input = new IO::File "<file1.txt"
841 or die "Cannot open 'file1.txt': $!\n" ;
843 zip $input => \$buffer
844 or die "zip failed: $ZipError\n";
846 To compress all files in the directory "/my/home" that match "*.txt"
847 and store the compressed data in the same directory
851 use IO::Compress::Zip qw(zip $ZipError) ;
853 zip '</my/home/*.txt>' => '<*.zip>'
854 or die "zip failed: $ZipError\n";
856 and if you want to compress each file one at a time, this will do the trick
860 use IO::Compress::Zip qw(zip $ZipError) ;
862 for my $input ( glob "/my/home/*.txt" )
864 my $output = "$input.zip" ;
865 zip $input => $output
866 or die "Error compressing '$input': $ZipError\n";
873 The format of the constructor for C<IO::Compress::Zip> is shown below
875 my $z = new IO::Compress::Zip $output [,OPTS]
876 or die "IO::Compress::Zip failed: $ZipError\n";
878 It returns an C<IO::Compress::Zip> object on success and undef on failure.
879 The variable C<$ZipError> will contain an error message on failure.
881 If you are running Perl 5.005 or better the object, C<$z>, returned from
882 IO::Compress::Zip can be used exactly like an L<IO::File|IO::File> filehandle.
883 This means that all normal output file operations can be carried out
885 For example, to write to a compressed file/buffer you can use either of
888 $z->print("hello world\n");
889 print $z "hello world\n";
891 The mandatory parameter C<$output> is used to control the destination
892 of the compressed data. This parameter can take one of these forms.
898 If the C<$output> parameter is a simple scalar, it is assumed to be a
899 filename. This file will be opened for writing and the compressed data
900 will be written to it.
904 If the C<$output> parameter is a filehandle, the compressed data will be
906 The string '-' can be used as an alias for standard output.
908 =item A scalar reference
910 If C<$output> is a scalar reference, the compressed data will be stored
915 If the C<$output> parameter is any other type, C<IO::Compress::Zip>::new will
918 =head2 Constructor Options
920 C<OPTS> is any combination of the following options:
924 =item C<< AutoClose => 0|1 >>
926 This option is only valid when the C<$output> parameter is a filehandle. If
927 specified, and the value is true, it will result in the C<$output> being
928 closed once either the C<close> method is called or the C<IO::Compress::Zip>
931 This parameter defaults to 0.
933 =item C<< Append => 0|1 >>
935 Opens C<$output> in append mode.
937 The behaviour of this option is dependent on the type of C<$output>.
943 If C<$output> is a buffer and C<Append> is enabled, all compressed data
944 will be append to the end if C<$output>. Otherwise C<$output> will be
945 cleared before any data is written to it.
949 If C<$output> is a filename and C<Append> is enabled, the file will be
950 opened in append mode. Otherwise the contents of the file, if any, will be
951 truncated before any compressed data is written to it.
955 If C<$output> is a filehandle, the file pointer will be positioned to the
956 end of the file via a call to C<seek> before any compressed data is written
957 to it. Otherwise the file pointer will not be moved.
961 This parameter defaults to 0.
963 =item C<< Name => $string >>
965 Stores the contents of C<$string> in the zip filename header field. If
966 C<Name> is not specified, no zip filename field will be created.
968 =item C<< Time => $number >>
970 Sets the last modified time field in the zip header to $number.
972 This field defaults to the time the C<IO::Compress::Zip> object was created
973 if this option is not specified.
975 =item C<< ExtAttr => $attr >>
977 This option controls the "external file attributes" field in the central
978 header of the zip file. This is a 4 byte field.
980 If you are running a Unix derivative this value defaults to
984 This should allow read/write access to any files that are extracted from
987 For all other systems it defaults to 0.
989 =item C<< exTime => [$atime, $mtime, $ctime] >>
991 This option expects an array reference with exactly three elements:
992 C<$atime>, C<mtime> and C<$ctime>. These correspond to the last access
993 time, last modification time and creation time respectively.
995 It uses these values to set the extended timestamp field (ID is "UT") in
996 the local zip header using the three values, $atime, $mtime, $ctime. In
997 addition it sets the extended timestamp field in the central zip header
1000 If any of the three values is C<undef> that time value will not be used.
1001 So, for example, to set only the C<$mtime> you would use this
1003 exTime => [undef, $mtime, undef]
1005 If the C<Minimal> option is set to true, this option will be ignored.
1007 By default no extended time field is created.
1009 =item C<< exUnix2 => [$uid, $gid] >>
1011 This option expects an array reference with exactly two elements: C<$uid>
1012 and C<$gid>. These values correspond to the numeric user ID and group ID
1013 of the owner of the files respectively.
1015 When the C<exUnix2> option is present it will trigger the creation of a
1016 Unix2 extra field (ID is "Ux") in the local zip. This will be populated
1017 with C<$uid> and C<$gid>. In addition an empty Unix2 extra field will also
1018 be created in the central zip header
1020 If the C<Minimal> option is set to true, this option will be ignored.
1022 By default no Unix2 extra field is created.
1024 =item C<< Comment => $comment >>
1026 Stores the contents of C<$comment> in the Central File Header of
1029 By default, no comment field is written to the zip file.
1031 =item C<< ZipComment => $comment >>
1033 Stores the contents of C<$comment> in the End of Central Directory record
1036 By default, no comment field is written to the zip file.
1038 =item C<< Method => $method >>
1040 Controls which compression method is used. At present three compression
1041 methods are supported, namely Store (no compression at all), Deflate and
1044 The symbols, ZIP_CM_STORE, ZIP_CM_DEFLATE and ZIP_CM_BZIP2 are used to
1045 select the compression method.
1047 These constants are not imported by C<IO::Compress::Zip> by default.
1049 use IO::Compress::Zip qw(:zip_method);
1050 use IO::Compress::Zip qw(:constants);
1051 use IO::Compress::Zip qw(:all);
1053 Note that to create Bzip2 content, the module C<IO::Compress::Bzip2> must
1054 be installed. A fatal error will be thrown if you attempt to create Bzip2
1055 content when C<IO::Compress::Bzip2> is not available.
1057 The default method is ZIP_CM_DEFLATE.
1059 =item C<< Stream => 0|1 >>
1061 This option controls whether the zip file/buffer output is created in
1064 Note that when outputting to a file with streaming mode disabled (C<Stream>
1065 is 0), the output file must be seekable.
1069 =item C<< Zip64 => 0|1 >>
1071 Create a Zip64 zip file/buffer. This option should only be used if you want
1072 to store files larger than 4 Gig.
1074 If you intend to manipulate the Zip64 zip files created with this module
1075 using an external zip/unzip make sure that it supports streaming Zip64.
1077 In particular, if you are using Info-Zip you need to have zip version 3.x
1078 or better to update a Zip64 archive and unzip version 6.x to read a zip64
1079 archive. At the time of writing both are beta status.
1081 When the C<Zip64> option is enabled, the C<Stream> option I<must> be
1086 =item C<< TextFlag => 0|1 >>
1088 This parameter controls the setting of a bit in the zip central header. It
1089 is used to signal that the data stored in the zip file/buffer is probably
1094 =item C<< ExtraFieldLocal => $data >>
1095 =item C<< ExtraFieldCentral => $data >>
1097 The C<ExtraFieldLocal> option is used to store additional metadata in the
1098 local header for the zip file/buffer. The C<ExtraFieldCentral> does the
1099 same for the matching central header.
1101 An extra field consists of zero or more subfields. Each subfield consists
1102 of a two byte header followed by the subfield data.
1104 The list of subfields can be supplied in any of the following formats
1106 ExtraFieldLocal => [$id1, $data1,
1111 ExtraFieldLocal => [ [$id1 => $data1],
1116 ExtraFieldLocal => { $id1 => $data1,
1121 Where C<$id1>, C<$id2> are two byte subfield ID's.
1123 If you use the hash syntax, you have no control over the order in which
1124 the ExtraSubFields are stored, plus you cannot have SubFields with
1127 Alternatively the list of subfields can by supplied as a scalar, thus
1129 ExtraField => $rawdata
1131 The Extended Time field (ID "UT"), set using the C<exTime> option, and the
1132 Unix2 extra field (ID "Ux), set using the C<exUnix2> option, are examples
1135 If the C<Minimal> option is set to true, this option will be ignored.
1137 The maximum size of an extra field 65535 bytes.
1139 =item C<< Minimal => 1|0 >>
1141 If specified, this option will disable the creation of all extra fields
1142 in the zip local and central headers. So the C<exTime>, C<exUnix2>,
1143 C<ExtraFieldLocal> and C<ExtraFieldCentral> options will be ignored.
1145 This parameter defaults to 0.
1147 =item C<< BlockSize100K => number >>
1149 Specify the number of 100K blocks bzip2 uses during compression.
1151 Valid values are from 1 to 9, where 9 is best compression.
1153 This option is only valid if the C<Method> is ZIP_CM_BZIP2. It is ignored
1158 =item C<< WorkFactor => number >>
1160 Specifies how much effort bzip2 should take before resorting to a slower
1161 fallback compression algorithm.
1163 Valid values range from 0 to 250, where 0 means use the default value 30.
1165 This option is only valid if the C<Method> is ZIP_CM_BZIP2. It is ignored
1172 Defines the compression level used by zlib. The value should either be
1173 a number between 0 and 9 (0 means no compression and 9 is maximum
1174 compression), or one of the symbolic constants defined below.
1179 Z_DEFAULT_COMPRESSION
1181 The default is Z_DEFAULT_COMPRESSION.
1183 Note, these constants are not imported by C<IO::Compress::Zip> by default.
1185 use IO::Compress::Zip qw(:strategy);
1186 use IO::Compress::Zip qw(:constants);
1187 use IO::Compress::Zip qw(:all);
1191 Defines the strategy used to tune the compression. Use one of the symbolic
1192 constants defined below.
1200 The default is Z_DEFAULT_STRATEGY.
1202 =item C<< Strict => 0|1 >>
1204 This is a placeholder option.
1221 Compresses and outputs the contents of the C<$data> parameter. This
1222 has the same behaviour as the C<print> built-in.
1224 Returns true if successful.
1230 $z->printf($format, $data)
1231 printf $z $format, $data
1233 Compresses and outputs the contents of the C<$data> parameter.
1235 Returns true if successful.
1242 $z->syswrite $data, $length
1243 $z->syswrite $data, $length, $offset
1245 Compresses and outputs the contents of the C<$data> parameter.
1247 Returns the number of uncompressed bytes written, or C<undef> if
1255 $z->write $data, $length
1256 $z->write $data, $length, $offset
1258 Compresses and outputs the contents of the C<$data> parameter.
1260 Returns the number of uncompressed bytes written, or C<undef> if
1268 $z->flush($flush_type);
1270 Flushes any pending compressed data to the output file/buffer.
1272 This method takes an optional parameter, C<$flush_type>, that controls
1273 how the flushing will be carried out. By default the C<$flush_type>
1274 used is C<Z_FINISH>. Other valid values for C<$flush_type> are
1275 C<Z_NO_FLUSH>, C<Z_SYNC_FLUSH>, C<Z_FULL_FLUSH> and C<Z_BLOCK>. It is
1276 strongly recommended that you only set the C<flush_type> parameter if
1277 you fully understand the implications of what it does - overuse of C<flush>
1278 can seriously degrade the level of compression achieved. See the C<zlib>
1279 documentation for details.
1281 Returns true on success.
1290 Returns the uncompressed file offset.
1299 Returns true if the C<close> method has been called.
1303 $z->seek($position, $whence);
1304 seek($z, $position, $whence);
1306 Provides a sub-set of the C<seek> functionality, with the restriction
1307 that it is only legal to seek forward in the output file/buffer.
1308 It is a fatal error to attempt to seek backward.
1310 Empty parts of the file/buffer will have NULL (0x00) bytes written to them.
1312 The C<$whence> parameter takes one the usual values, namely SEEK_SET,
1313 SEEK_CUR or SEEK_END.
1315 Returns 1 on success, 0 on failure.
1324 This is a noop provided for completeness.
1330 Returns true if the object currently refers to a opened file/buffer.
1334 my $prev = $z->autoflush()
1335 my $prev = $z->autoflush(EXPR)
1337 If the C<$z> object is associated with a file or a filehandle, this method
1338 returns the current autoflush setting for the underlying filehandle. If
1339 C<EXPR> is present, and is non-zero, it will enable flushing after every
1340 write/print operation.
1342 If C<$z> is associated with a buffer, this method has no effect and always
1345 B<Note> that the special variable C<$|> B<cannot> be used to set or
1346 retrieve the autoflush setting.
1348 =head2 input_line_number
1350 $z->input_line_number()
1351 $z->input_line_number(EXPR)
1353 This method always returns C<undef> when compressing.
1360 If the C<$z> object is associated with a file or a filehandle, C<fileno>
1361 will return the underlying file descriptor. Once the C<close> method is
1362 called C<fileno> will return C<undef>.
1364 If the C<$z> object is is associated with a buffer, this method will return
1372 Flushes any pending compressed data and then closes the output file/buffer.
1374 For most versions of Perl this method will be automatically invoked if
1375 the IO::Compress::Zip object is destroyed (either explicitly or by the
1376 variable with the reference to the object going out of scope). The
1377 exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In
1378 these cases, the C<close> method will be called automatically, but
1379 not until global destruction of all live objects when the program is
1382 Therefore, if you want your scripts to be able to run on all versions
1383 of Perl, you should call C<close> explicitly and not rely on automatic
1386 Returns true on success, otherwise 0.
1388 If the C<AutoClose> option has been enabled when the IO::Compress::Zip
1389 object was created, and the object is associated with a file, the
1390 underlying file will also be closed.
1392 =head2 newStream([OPTS])
1396 $z->newStream( [OPTS] )
1398 Closes the current compressed data stream and starts a new one.
1400 OPTS consists of any of the the options that are available when creating
1403 See the L</"Constructor Options"> section for more details.
1405 =head2 deflateParams
1415 A number of symbolic constants are required by some methods in
1416 C<IO::Compress::Zip>. None are imported by default.
1422 Imports C<zip>, C<$ZipError> and all symbolic
1423 constants that can be used by C<IO::Compress::Zip>. Same as doing this
1425 use IO::Compress::Zip qw(zip $ZipError :constants) ;
1429 Import all symbolic constants. Same as doing this
1431 use IO::Compress::Zip qw(:flush :level :strategy :zip_method) ;
1435 These symbolic constants are used by the C<flush> method.
1446 These symbolic constants are used by the C<Level> option in the constructor.
1451 Z_DEFAULT_COMPRESSION
1455 These symbolic constants are used by the C<Strategy> option in the constructor.
1465 These symbolic constants are used by the C<Method> option in the
1479 =head2 Apache::GZip Revisited
1481 See L<IO::Compress::FAQ|IO::Compress::FAQ/"Apache::GZip Revisited">
1485 =head2 Working with Net::FTP
1487 See L<IO::Compress::FAQ|IO::Compress::FAQ/"Compressed files and Net::FTP">
1491 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>
1493 L<Compress::Zlib::FAQ|Compress::Zlib::FAQ>
1495 L<File::GlobMapper|File::GlobMapper>, L<Archive::Zip|Archive::Zip>,
1496 L<Archive::Tar|Archive::Tar>,
1497 L<IO::Zlib|IO::Zlib>
1499 For RFC 1950, 1951 and 1952 see
1500 F<http://www.faqs.org/rfcs/rfc1950.html>,
1501 F<http://www.faqs.org/rfcs/rfc1951.html> and
1502 F<http://www.faqs.org/rfcs/rfc1952.html>
1504 The I<zlib> compression library was written by Jean-loup Gailly
1505 F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>.
1507 The primary site for the I<zlib> compression library is
1508 F<http://www.zlib.org>.
1510 The primary site for gzip is F<http://www.gzip.org>.
1514 This module was written by Paul Marquess, F<pmqs@cpan.org>.
1516 =head1 MODIFICATION HISTORY
1518 See the Changes file.
1520 =head1 COPYRIGHT AND LICENSE
1522 Copyright (c) 2005-2009 Paul Marquess. All rights reserved.
1524 This program is free software; you can redistribute it and/or
1525 modify it under the same terms as Perl itself.