1 package IO::Compress::Zip ;
7 use IO::Compress::Base::Common 2.018 qw(:Status createSelfTiedObject);
8 use IO::Compress::RawDeflate 2.018 ;
9 use IO::Compress::Adapter::Deflate 2.018 ;
10 use IO::Compress::Adapter::Identity 2.018 ;
11 use IO::Compress::Zlib::Extra 2.018 ;
12 use IO::Compress::Zip::Constants 2.018 ;
15 use Compress::Raw::Zlib 2.018 qw(crc32) ;
18 eval { require IO::Compress::Adapter::Bzip2 ;
19 import IO::Compress::Adapter::Bzip2 2.018 ;
20 require IO::Compress::Bzip2 ;
21 import IO::Compress::Bzip2 2.018 ;
23 # eval { require IO::Compress::Adapter::Lzma ;
24 # import IO::Compress::Adapter::Lzma 2.018 ;
25 # require IO::Compress::Lzma ;
26 # import IO::Compress::Lzma 2.018 ;
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')
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(
95 # *$self->{ZipData}{CRC32} = crc32(undef);
98 return $self->saveErrorString(undef, $errstr, $errno)
101 if (! defined *$self->{ZipData}{StartOffset}) {
102 *$self->{ZipData}{StartOffset} = 0;
103 *$self->{ZipData}{Offset} = new U64 ;
113 *$self->{Compress}->reset();
114 *$self->{ZipData}{CRC32} = Compress::Raw::Zlib::crc32('');
119 sub filterUncompressed
123 if (*$self->{ZipData}{Method} == ZIP_CM_DEFLATE) {
124 *$self->{ZipData}{CRC32} = *$self->{Compress}->crc32();
127 *$self->{ZipData}{CRC32} = crc32(${$_[0]}, *$self->{ZipData}{CRC32});
137 *$self->{ZipData}{StartOffset} = *$self->{ZipData}{Offset}->get32bit() ;
140 $filename = $param->value('Name') || '';
143 $comment = $param->value('Comment') || '';
147 my $time = _unixToDosTime($param->value('Time'));
152 my $osCode = $param->value('OS_Code') ;
153 my $extFileAttr = 0 ;
155 # This code assumes Unix.
156 $extFileAttr = 0666 << 16
157 if $osCode == ZIP_OS_CODE_UNIX ;
159 if (*$self->{ZipData}{Zip64}) {
163 $x .= pack "V V", 0, 0 ; # uncompressedLength
164 $x .= pack "V V", 0, 0 ; # compressedLength
165 $x .= *$self->{ZipData}{Offset}->getPacked_V64() ; # offset to local hdr
166 $x .= pack "V", 0 ; # disk no
168 $x = IO::Compress::Zlib::Extra::mkSubField(ZIP_EXTRA_ID_ZIP64, $x);
173 if (! $param->value('Minimal')) {
174 if (defined $param->value('exTime'))
176 $extra .= mkExtendedTime($param->value('MTime'),
177 $param->value('ATime'),
178 $param->value('CTime'));
180 $ctlExtra .= mkExtendedTime($param->value('MTime'));
183 if ( $param->value('UID') && $osCode == ZIP_OS_CODE_UNIX)
185 $extra .= mkUnix2Extra( $param->value('UID'), $param->value('GID'));
186 $ctlExtra .= mkUnix2Extra();
189 $extFileAttr = $param->value('ExtAttr')
190 if defined $param->value('ExtAttr') ;
192 $extra .= $param->value('ExtraFieldLocal')
193 if defined $param->value('ExtraFieldLocal');
195 $ctlExtra .= $param->value('ExtraFieldCentral')
196 if defined $param->value('ExtraFieldCentral');
200 $gpFlag |= ZIP_GP_FLAG_STREAMING_MASK
201 if *$self->{ZipData}{Stream} ;
203 my $method = *$self->{ZipData}{Method} ;
205 my $version = $ZIP_CM_MIN_VERSIONS{$method};
206 $version = ZIP64_MIN_VERSION
207 if ZIP64_MIN_VERSION > $version && *$self->{ZipData}{Zip64};
208 my $madeBy = ($param->value('OS_Code') << 8) + $version;
209 my $extract = $version;
211 *$self->{ZipData}{Version} = $version;
212 *$self->{ZipData}{MadeBy} = $madeBy;
215 $ifa |= ZIP_IFA_TEXT_MASK
216 if $param->value('TextFlag');
218 $hdr .= pack "V", ZIP_LOCAL_HDR_SIG ; # signature
219 $hdr .= pack 'v', $extract ; # extract Version & OS
220 $hdr .= pack 'v', $gpFlag ; # general purpose flag (set streaming mode)
221 $hdr .= pack 'v', $method ; # compression method (deflate)
222 $hdr .= pack 'V', $time ; # last mod date/time
223 $hdr .= pack 'V', 0 ; # crc32 - 0 when streaming
224 $hdr .= pack 'V', $empty ; # compressed length - 0 when streaming
225 $hdr .= pack 'V', $empty ; # uncompressed length - 0 when streaming
226 $hdr .= pack 'v', length $filename ; # filename length
227 $hdr .= pack 'v', length $extra ; # extra length
235 $ctl .= pack "V", ZIP_CENTRAL_HDR_SIG ; # signature
236 $ctl .= pack 'v', $madeBy ; # version made by
237 $ctl .= pack 'v', $extract ; # extract Version
238 $ctl .= pack 'v', $gpFlag ; # general purpose flag (streaming mode)
239 $ctl .= pack 'v', $method ; # compression method (deflate)
240 $ctl .= pack 'V', $time ; # last mod date/time
241 $ctl .= pack 'V', 0 ; # crc32
242 $ctl .= pack 'V', $empty ; # compressed length
243 $ctl .= pack 'V', $empty ; # uncompressed length
244 $ctl .= pack 'v', length $filename ; # filename length
245 $ctl .= pack 'v', length $ctlExtra ; # extra length
246 $ctl .= pack 'v', length $comment ; # file comment length
247 $ctl .= pack 'v', 0 ; # disk number start
248 $ctl .= pack 'v', $ifa ; # internal file attributes
249 $ctl .= pack 'V', $extFileAttr ; # external file attributes
250 if (! *$self->{ZipData}{Zip64}) {
251 $ctl .= pack 'V', *$self->{ZipData}{Offset}->get32bit() ; # offset to local header
254 $ctl .= pack 'V', $empty ; # offset to local header
258 *$self->{ZipData}{StartOffset64} = 4 + length $ctl;
262 *$self->{ZipData}{Offset}->add(length $hdr) ;
264 *$self->{ZipData}{CentralHeader} = $ctl;
274 if (*$self->{ZipData}{Method} == ZIP_CM_DEFLATE) {
275 $crc32 = pack "V", *$self->{Compress}->crc32();
278 $crc32 = pack "V", *$self->{ZipData}{CRC32};
281 my $ctl = *$self->{ZipData}{CentralHeader} ;
284 if (! *$self->{ZipData}{Zip64}) {
285 $sizes .= *$self->{CompSize}->getPacked_V32() ; # Compressed size
286 $sizes .= *$self->{UnCompSize}->getPacked_V32() ; # Uncompressed size
289 $sizes .= *$self->{CompSize}->getPacked_V64() ; # Compressed size
290 $sizes .= *$self->{UnCompSize}->getPacked_V64() ; # Uncompressed size
293 my $data = $crc32 . $sizes ;
298 if (*$self->{ZipData}{Stream}) {
299 $hdr = pack "V", ZIP_DATA_HDR_SIG ; # signature
303 $self->writeAt(*$self->{ZipData}{StartOffset} + 14, $data)
307 if (! *$self->{ZipData}{Zip64})
308 { substr($ctl, 16, length $data) = $data }
310 substr($ctl, 16, length $crc32) = $crc32 ;
311 my $s = *$self->{UnCompSize}->getPacked_V64() ; # Uncompressed size
312 $s .= *$self->{CompSize}->getPacked_V64() ; # Compressed size
313 substr($ctl, *$self->{ZipData}{StartOffset64}, length $s) = $s ;
316 *$self->{ZipData}{Offset}->add(length($hdr));
317 *$self->{ZipData}{Offset}->add( *$self->{CompSize} );
318 push @{ *$self->{ZipData}{CentralDir} }, $ctl ;
328 $comment = *$self->{ZipData}{ZipComment} ;
330 my $cd_offset = *$self->{ZipData}{Offset}->get32bit() ; # offset to start central dir
332 my $entries = @{ *$self->{ZipData}{CentralDir} };
333 my $cd = join '', @{ *$self->{ZipData}{CentralDir} };
334 my $cd_len = length $cd ;
338 if ( *$self->{ZipData}{Zip64} ) {
340 my $v = *$self->{ZipData}{Version} ;
341 my $mb = *$self->{ZipData}{MadeBy} ;
342 $z64e .= pack 'v', $v ; # Version made by
343 $z64e .= pack 'v', $mb ; # Version to extract
344 $z64e .= pack 'V', 0 ; # number of disk
345 $z64e .= pack 'V', 0 ; # number of disk with central dir
346 $z64e .= U64::pack_V64 $entries ; # entries in central dir on this disk
347 $z64e .= U64::pack_V64 $entries ; # entries in central dir
348 $z64e .= U64::pack_V64 $cd_len ; # size of central dir
349 $z64e .= *$self->{ZipData}{Offset}->getPacked_V64() ; # offset to start central dir
351 $z64e = pack("V", ZIP64_END_CENTRAL_REC_HDR_SIG) # signature
352 . U64::pack_V64(length $z64e)
355 *$self->{ZipData}{Offset}->add(length $cd) ;
357 $z64e .= pack "V", ZIP64_END_CENTRAL_LOC_HDR_SIG; # signature
358 $z64e .= pack 'V', 0 ; # number of disk with central dir
359 $z64e .= *$self->{ZipData}{Offset}->getPacked_V64() ; # offset to end zip64 central dir
360 $z64e .= pack 'V', 1 ; # Total number of disks
362 # TODO - fix these when info-zip 3 is fixed.
369 $ecd .= pack "V", ZIP_END_CENTRAL_HDR_SIG ; # signature
370 $ecd .= pack 'v', 0 ; # number of disk
371 $ecd .= pack 'v', 0 ; # number of disk with central dir
372 $ecd .= pack 'v', $entries ; # entries in central dir on this disk
373 $ecd .= pack 'v', $entries ; # entries in central dir
374 $ecd .= pack 'V', $cd_len ; # size of central dir
375 $ecd .= pack 'V', $cd_offset ; # offset to start central dir
376 $ecd .= pack 'v', length $comment ; # zipfile comment length
379 return $cd . $z64e . $ecd ;
387 $got->value('CRC32' => 1);
389 if (! $got->parsed('Time') ) {
390 # Modification time defaults to now.
391 $got->value('Time' => time) ;
394 if ($got->parsed('exTime') ) {
395 my $timeRef = $got->value('exTime');
396 if ( defined $timeRef) {
397 return $self->saveErrorString(undef, "exTime not a 3-element array ref")
398 if ref $timeRef ne 'ARRAY' || @$timeRef != 3;
401 $got->value("MTime", $timeRef->[1]);
402 $got->value("ATime", $timeRef->[0]);
403 $got->value("CTime", $timeRef->[2]);
406 # Unix2 Extended Attribute
407 if ($got->parsed('exUnix2') ) {
408 my $timeRef = $got->value('exUnix2');
409 if ( defined $timeRef) {
410 return $self->saveErrorString(undef, "exUnix2 not a 2-element array ref")
411 if ref $timeRef ne 'ARRAY' || @$timeRef != 2;
414 $got->value("UID", $timeRef->[0]);
415 $got->value("GID", $timeRef->[1]);
418 *$self->{ZipData}{Zip64} = $got->value('Zip64');
419 *$self->{ZipData}{Stream} = $got->value('Stream');
421 return $self->saveErrorString(undef, "Zip64 only supported if Stream enabled")
422 if *$self->{ZipData}{Zip64} && ! *$self->{ZipData}{Stream} ;
424 my $method = $got->value('Method');
425 return $self->saveErrorString(undef, "Unknown Method '$method'")
426 if ! defined $ZIP_CM_MIN_VERSIONS{$method};
428 return $self->saveErrorString(undef, "Bzip2 not available")
429 if $method == ZIP_CM_BZIP2 and
430 ! defined $IO::Compress::Adapter::Bzip2::VERSION;
432 # return $self->saveErrorString(undef, "Lzma not available")
433 # if $method == ZIP_CM_LZMA and
434 # ! defined $IO::Compress::Adapter::Lzma::VERSION;
436 *$self->{ZipData}{Method} = $method;
438 *$self->{ZipData}{ZipComment} = $got->value('ZipComment') ;
440 for my $name (qw( ExtraFieldLocal ExtraFieldCentral ))
442 my $data = $got->value($name) ;
444 my $bad = IO::Compress::Zlib::Extra::parseExtraField($data, 1, 0) ;
445 return $self->saveErrorString(undef, "Error with $name Parameter: $bad")
448 $got->value($name, $data) ;
453 if defined $IO::Compress::Bzip2::VERSION
454 and ! IO::Compress::Bzip2::ckParams($self, $got);
463 # return $self->mkHeader(*$self->{Got});
470 use IO::Compress::Base::Common 2.018 qw(:Parse);
471 use Compress::Raw::Zlib 2.018 qw(Z_DEFLATED Z_DEFAULT_COMPRESSION Z_DEFAULT_STRATEGY);
475 @Bzip2 = IO::Compress::Bzip2::getExtraParams($self)
476 if defined $IO::Compress::Bzip2::VERSION;
480 $self->getZlibParams(),
482 'Stream' => [1, 1, Parse_boolean, 1],
483 #'Store' => [0, 1, Parse_boolean, 0],
484 'Method' => [0, 1, Parse_unsigned, ZIP_CM_DEFLATE],
486 # # Zip header fields
487 'Minimal' => [0, 1, Parse_boolean, 0],
488 'Zip64' => [0, 1, Parse_boolean, 0],
489 'Comment' => [0, 1, Parse_any, ''],
490 'ZipComment'=> [0, 1, Parse_any, ''],
491 'Name' => [0, 1, Parse_any, ''],
492 'Time' => [0, 1, Parse_any, undef],
493 'exTime' => [0, 1, Parse_any, undef],
494 'exUnix2' => [0, 1, Parse_any, undef],
495 'ExtAttr' => [0, 1, Parse_any, 0],
496 'OS_Code' => [0, 1, Parse_unsigned, $Compress::Raw::Zlib::gzip_os_code],
498 'TextFlag' => [0, 1, Parse_boolean, 0],
499 'ExtraFieldLocal' => [0, 1, Parse_any, undef],
500 'ExtraFieldCentral'=> [0, 1, Parse_any, undef],
508 return ('IO::Uncompress::Unzip',
509 \$IO::Uncompress::Unzip::UnzipError);
516 my $filename = shift ;
518 my ($mode, $uid, $gid, $atime, $mtime, $ctime)
519 = (stat($filename))[2, 4,5, 8,9,10] ;
521 $params->value('Name' => $filename)
522 if ! $params->parsed('Name') ;
524 $params->value('Time' => $mtime)
525 if ! $params->parsed('Time') ;
527 if ( ! $params->parsed('exTime'))
529 $params->value('MTime' => $mtime) ;
530 $params->value('ATime' => $atime) ;
531 $params->value('CTime' => undef) ; # No Creation time
532 $params->value("exTime", [$mtime, $atime, undef]);
535 # NOTE - Unix specific code alert
536 $params->value('ExtAttr' => $mode << 16)
537 if ! $params->parsed('ExtAttr');
539 $params->value('UID' => $uid) ;
540 $params->value('GID' => $gid) ;
546 # order expected is m, a, c
557 $times .= pack("V", $time);
563 return IO::Compress::Zlib::Extra::mkSubField(ZIP_EXTRA_ID_EXT_TIMESTAMP,
564 pack("C", $flags) . $times);
572 $ids .= pack("v", $id);
575 return IO::Compress::Zlib::Extra::mkSubField(ZIP_EXTRA_ID_INFO_ZIP_UNIX2,
581 sub _unixToDosTime # Archive::Zip::Member
584 # TODO - add something to cope with unix time < 1980
585 my ( $sec, $min, $hour, $mday, $mon, $year ) = localtime($time_t);
587 $dt += ( $sec >> 1 );
588 $dt += ( $min << 5 );
589 $dt += ( $hour << 11 );
590 $dt += ( $mday << 16 );
591 $dt += ( ( $mon + 1 ) << 21 );
592 $dt += ( ( $year - 80 ) << 25 );
602 IO::Compress::Zip - Write zip files/buffers
608 use IO::Compress::Zip qw(zip $ZipError) ;
610 my $status = zip $input => $output [,OPTS]
611 or die "zip failed: $ZipError\n";
613 my $z = new IO::Compress::Zip $output [,OPTS]
614 or die "zip failed: $ZipError\n";
617 $z->printf($format, $string);
619 $z->syswrite($string [, $length, $offset]);
623 $z->seek($position, $whence);
628 $z->input_line_number();
629 $z->newStream( [OPTS] );
640 printf $z $format, $string;
643 seek $z, $position, $whence
651 This module provides a Perl interface that allows writing zip
652 compressed data to files or buffer.
654 The primary purpose of this module is to provide streaming write access to
655 zip files and buffers. It is not a general-purpose file archiver. If that
656 is what you want, check out C<Archive::Zip>.
658 At present three compression methods are supported by IO::Compress::Zip,
659 namely Store (no compression at all), Deflate and Bzip2.
661 Note that to create Bzip2 content, the module C<IO::Compress::Bzip2> must
664 For reading zip files/buffers, see the companion module
665 L<IO::Uncompress::Unzip|IO::Uncompress::Unzip>.
667 =head1 Functional Interface
669 A top-level function, C<zip>, is provided to carry out
670 "one-shot" compression between buffers and/or files. For finer
671 control over the compression process, see the L</"OO Interface">
674 use IO::Compress::Zip qw(zip $ZipError) ;
676 zip $input => $output [,OPTS]
677 or die "zip failed: $ZipError\n";
679 The functional interface needs Perl5.005 or better.
681 =head2 zip $input => $output [, OPTS]
683 C<zip> expects at least two parameters, C<$input> and C<$output>.
685 =head3 The C<$input> parameter
687 The parameter, C<$input>, is used to define the source of
688 the uncompressed data.
690 It can take one of the following forms:
696 If the C<$input> parameter is a simple scalar, it is assumed to be a
697 filename. This file will be opened for reading and the input data
698 will be read from it.
702 If the C<$input> parameter is a filehandle, the input data will be
704 The string '-' can be used as an alias for standard input.
706 =item A scalar reference
708 If C<$input> is a scalar reference, the input data will be read
711 =item An array reference
713 If C<$input> is an array reference, each element in the array must be a
716 The input data will be read from each file in turn.
718 The complete array will be walked to ensure that it only
719 contains valid filenames before any data is compressed.
721 =item An Input FileGlob string
723 If C<$input> is a string that is delimited by the characters "<" and ">"
724 C<zip> will assume that it is an I<input fileglob string>. The
725 input is the list of files that match the fileglob.
727 If the fileglob does not match any files ...
729 See L<File::GlobMapper|File::GlobMapper> for more details.
733 If the C<$input> parameter is any other type, C<undef> will be returned.
735 In addition, if C<$input> is a simple filename, the default values for
736 the C<Name>, C<Time>, C<ExtAttr> and C<exTime> options will be sourced from that file.
738 If you do not want to use these defaults they can be overridden by
739 explicitly setting the C<Name>, C<Time>, C<ExtAttr> and C<exTime> options or by setting the
740 C<Minimal> parameter.
742 =head3 The C<$output> parameter
744 The parameter C<$output> is used to control the destination of the
745 compressed data. This parameter can take one of these forms.
751 If the C<$output> parameter is a simple scalar, it is assumed to be a
752 filename. This file will be opened for writing and the compressed
753 data will be written to it.
757 If the C<$output> parameter is a filehandle, the compressed data
758 will be written to it.
759 The string '-' can be used as an alias for standard output.
761 =item A scalar reference
763 If C<$output> is a scalar reference, the compressed data will be
764 stored in C<$$output>.
766 =item An Array Reference
768 If C<$output> is an array reference, the compressed data will be
769 pushed onto the array.
771 =item An Output FileGlob
773 If C<$output> is a string that is delimited by the characters "<" and ">"
774 C<zip> will assume that it is an I<output fileglob string>. The
775 output is the list of files that match the fileglob.
777 When C<$output> is an fileglob string, C<$input> must also be a fileglob
778 string. Anything else is an error.
782 If the C<$output> parameter is any other type, C<undef> will be returned.
786 When C<$input> maps to multiple files/buffers and C<$output> is a single
787 file/buffer the input files/buffers will each be stored
788 in C<$output> as a distinct entry.
790 =head2 Optional Parameters
792 Unless specified below, the optional parameters for C<zip>,
793 C<OPTS>, are the same as those used with the OO interface defined in the
794 L</"Constructor Options"> section below.
798 =item C<< AutoClose => 0|1 >>
800 This option applies to any input or output data streams to
801 C<zip> that are filehandles.
803 If C<AutoClose> is specified, and the value is true, it will result in all
804 input and/or output filehandles being closed once C<zip> has
807 This parameter defaults to 0.
809 =item C<< BinModeIn => 0|1 >>
811 When reading from a file or filehandle, set C<binmode> before reading.
815 =item C<< Append => 0|1 >>
823 To read the contents of the file C<file1.txt> and write the compressed
824 data to the file C<file1.txt.zip>.
828 use IO::Compress::Zip qw(zip $ZipError) ;
830 my $input = "file1.txt";
831 zip $input => "$input.zip"
832 or die "zip failed: $ZipError\n";
834 To read from an existing Perl filehandle, C<$input>, and write the
835 compressed data to a buffer, C<$buffer>.
839 use IO::Compress::Zip qw(zip $ZipError) ;
842 my $input = new IO::File "<file1.txt"
843 or die "Cannot open 'file1.txt': $!\n" ;
845 zip $input => \$buffer
846 or die "zip failed: $ZipError\n";
848 To compress all files in the directory "/my/home" that match "*.txt"
849 and store the compressed data in the same directory
853 use IO::Compress::Zip qw(zip $ZipError) ;
855 zip '</my/home/*.txt>' => '<*.zip>'
856 or die "zip failed: $ZipError\n";
858 and if you want to compress each file one at a time, this will do the trick
862 use IO::Compress::Zip qw(zip $ZipError) ;
864 for my $input ( glob "/my/home/*.txt" )
866 my $output = "$input.zip" ;
867 zip $input => $output
868 or die "Error compressing '$input': $ZipError\n";
875 The format of the constructor for C<IO::Compress::Zip> is shown below
877 my $z = new IO::Compress::Zip $output [,OPTS]
878 or die "IO::Compress::Zip failed: $ZipError\n";
880 It returns an C<IO::Compress::Zip> object on success and undef on failure.
881 The variable C<$ZipError> will contain an error message on failure.
883 If you are running Perl 5.005 or better the object, C<$z>, returned from
884 IO::Compress::Zip can be used exactly like an L<IO::File|IO::File> filehandle.
885 This means that all normal output file operations can be carried out
887 For example, to write to a compressed file/buffer you can use either of
890 $z->print("hello world\n");
891 print $z "hello world\n";
893 The mandatory parameter C<$output> is used to control the destination
894 of the compressed data. This parameter can take one of these forms.
900 If the C<$output> parameter is a simple scalar, it is assumed to be a
901 filename. This file will be opened for writing and the compressed data
902 will be written to it.
906 If the C<$output> parameter is a filehandle, the compressed data will be
908 The string '-' can be used as an alias for standard output.
910 =item A scalar reference
912 If C<$output> is a scalar reference, the compressed data will be stored
917 If the C<$output> parameter is any other type, C<IO::Compress::Zip>::new will
920 =head2 Constructor Options
922 C<OPTS> is any combination of the following options:
926 =item C<< AutoClose => 0|1 >>
928 This option is only valid when the C<$output> parameter is a filehandle. If
929 specified, and the value is true, it will result in the C<$output> being
930 closed once either the C<close> method is called or the C<IO::Compress::Zip>
933 This parameter defaults to 0.
935 =item C<< Append => 0|1 >>
937 Opens C<$output> in append mode.
939 The behaviour of this option is dependent on the type of C<$output>.
945 If C<$output> is a buffer and C<Append> is enabled, all compressed data
946 will be append to the end if C<$output>. Otherwise C<$output> will be
947 cleared before any data is written to it.
951 If C<$output> is a filename and C<Append> is enabled, the file will be
952 opened in append mode. Otherwise the contents of the file, if any, will be
953 truncated before any compressed data is written to it.
957 If C<$output> is a filehandle, the file pointer will be positioned to the
958 end of the file via a call to C<seek> before any compressed data is written
959 to it. Otherwise the file pointer will not be moved.
963 This parameter defaults to 0.
965 =item C<< Name => $string >>
967 Stores the contents of C<$string> in the zip filename header field. If
968 C<Name> is not specified, no zip filename field will be created.
970 =item C<< Time => $number >>
972 Sets the last modified time field in the zip header to $number.
974 This field defaults to the time the C<IO::Compress::Zip> object was created
975 if this option is not specified.
977 =item C<< ExtAttr => $attr >>
979 This option controls the "external file attributes" field in the central
980 header of the zip file. This is a 4 byte field.
982 If you are running a Unix derivative this value defaults to
986 This should allow read/write access to any files that are extracted from
989 For all other systems it defaults to 0.
991 =item C<< exTime => [$atime, $mtime, $ctime] >>
993 This option expects an array reference with exactly three elements:
994 C<$atime>, C<mtime> and C<$ctime>. These correspond to the last access
995 time, last modification time and creation time respectively.
997 It uses these values to set the extended timestamp field (ID is "UT") in
998 the local zip header using the three values, $atime, $mtime, $ctime. In
999 addition it sets the extended timestamp field in the central zip header
1002 If any of the three values is C<undef> that time value will not be used.
1003 So, for example, to set only the C<$mtime> you would use this
1005 exTime => [undef, $mtime, undef]
1007 If the C<Minimal> option is set to true, this option will be ignored.
1009 By default no extended time field is created.
1011 =item C<< exUnix2 => [$uid, $gid] >>
1013 This option expects an array reference with exactly two elements: C<$uid>
1014 and C<$gid>. These values correspond to the numeric user ID and group ID
1015 of the owner of the files respectively.
1017 When the C<exUnix2> option is present it will trigger the creation of a
1018 Unix2 extra field (ID is "Ux") in the local zip. This will be populated
1019 with C<$uid> and C<$gid>. In addition an empty Unix2 extra field will also
1020 be created in the central zip header
1022 If the C<Minimal> option is set to true, this option will be ignored.
1024 By default no Unix2 extra field is created.
1026 =item C<< Comment => $comment >>
1028 Stores the contents of C<$comment> in the Central File Header of
1031 By default, no comment field is written to the zip file.
1033 =item C<< ZipComment => $comment >>
1035 Stores the contents of C<$comment> in the End of Central Directory record
1038 By default, no comment field is written to the zip file.
1040 =item C<< Method => $method >>
1042 Controls which compression method is used. At present three compression
1043 methods are supported, namely Store (no compression at all), Deflate and
1046 The symbols, ZIP_CM_STORE, ZIP_CM_DEFLATE and ZIP_CM_BZIP2 are used to
1047 select the compression method.
1049 These constants are not imported by C<IO::Compress::Zip> by default.
1051 use IO::Compress::Zip qw(:zip_method);
1052 use IO::Compress::Zip qw(:constants);
1053 use IO::Compress::Zip qw(:all);
1055 Note that to create Bzip2 content, the module C<IO::Compress::Bzip2> must
1056 be installed. A fatal error will be thrown if you attempt to create Bzip2
1057 content when C<IO::Compress::Bzip2> is not available.
1059 The default method is ZIP_CM_DEFLATE.
1061 =item C<< Stream => 0|1 >>
1063 This option controls whether the zip file/buffer output is created in
1066 Note that when outputting to a file with streaming mode disabled (C<Stream>
1067 is 0), the output file must be seekable.
1071 =item C<< Zip64 => 0|1 >>
1073 Create a Zip64 zip file/buffer. This option should only be used if you want
1074 to store files larger than 4 Gig.
1076 If you intend to manipulate the Zip64 zip files created with this module
1077 using an external zip/unzip make sure that it supports streaming Zip64.
1079 In particular, if you are using Info-Zip you need to have zip version 3.x
1080 or better to update a Zip64 archive and unzip version 6.x to read a zip64
1081 archive. At the time of writing both are beta status.
1083 When the C<Zip64> option is enabled, the C<Stream> option I<must> be
1088 =item C<< TextFlag => 0|1 >>
1090 This parameter controls the setting of a bit in the zip central header. It
1091 is used to signal that the data stored in the zip file/buffer is probably
1096 =item C<< ExtraFieldLocal => $data >>
1097 =item C<< ExtraFieldCentral => $data >>
1099 The C<ExtraFieldLocal> option is used to store additional metadata in the
1100 local header for the zip file/buffer. The C<ExtraFieldCentral> does the
1101 same for the matching central header.
1103 An extra field consists of zero or more subfields. Each subfield consists
1104 of a two byte header followed by the subfield data.
1106 The list of subfields can be supplied in any of the following formats
1108 ExtraFieldLocal => [$id1, $data1,
1113 ExtraFieldLocal => [ [$id1 => $data1],
1118 ExtraFieldLocal => { $id1 => $data1,
1123 Where C<$id1>, C<$id2> are two byte subfield ID's.
1125 If you use the hash syntax, you have no control over the order in which
1126 the ExtraSubFields are stored, plus you cannot have SubFields with
1129 Alternatively the list of subfields can by supplied as a scalar, thus
1131 ExtraField => $rawdata
1133 The Extended Time field (ID "UT"), set using the C<exTime> option, and the
1134 Unix2 extra field (ID "Ux), set using the C<exUnix2> option, are examples
1137 If the C<Minimal> option is set to true, this option will be ignored.
1139 The maximum size of an extra field 65535 bytes.
1141 =item C<< Minimal => 1|0 >>
1143 If specified, this option will disable the creation of all extra fields
1144 in the zip local and central headers. So the C<exTime>, C<exUnix2>,
1145 C<ExtraFieldLocal> and C<ExtraFieldCentral> options will be ignored.
1147 This parameter defaults to 0.
1149 =item C<< BlockSize100K => number >>
1151 Specify the number of 100K blocks bzip2 uses during compression.
1153 Valid values are from 1 to 9, where 9 is best compression.
1155 This option is only valid if the C<Method> is ZIP_CM_BZIP2. It is ignored
1160 =item C<< WorkFactor => number >>
1162 Specifies how much effort bzip2 should take before resorting to a slower
1163 fallback compression algorithm.
1165 Valid values range from 0 to 250, where 0 means use the default value 30.
1167 This option is only valid if the C<Method> is ZIP_CM_BZIP2. It is ignored
1174 Defines the compression level used by zlib. The value should either be
1175 a number between 0 and 9 (0 means no compression and 9 is maximum
1176 compression), or one of the symbolic constants defined below.
1181 Z_DEFAULT_COMPRESSION
1183 The default is Z_DEFAULT_COMPRESSION.
1185 Note, these constants are not imported by C<IO::Compress::Zip> by default.
1187 use IO::Compress::Zip qw(:strategy);
1188 use IO::Compress::Zip qw(:constants);
1189 use IO::Compress::Zip qw(:all);
1193 Defines the strategy used to tune the compression. Use one of the symbolic
1194 constants defined below.
1202 The default is Z_DEFAULT_STRATEGY.
1204 =item C<< Strict => 0|1 >>
1206 This is a placeholder option.
1223 Compresses and outputs the contents of the C<$data> parameter. This
1224 has the same behaviour as the C<print> built-in.
1226 Returns true if successful.
1232 $z->printf($format, $data)
1233 printf $z $format, $data
1235 Compresses and outputs the contents of the C<$data> parameter.
1237 Returns true if successful.
1244 $z->syswrite $data, $length
1245 $z->syswrite $data, $length, $offset
1247 Compresses and outputs the contents of the C<$data> parameter.
1249 Returns the number of uncompressed bytes written, or C<undef> if
1257 $z->write $data, $length
1258 $z->write $data, $length, $offset
1260 Compresses and outputs the contents of the C<$data> parameter.
1262 Returns the number of uncompressed bytes written, or C<undef> if
1270 $z->flush($flush_type);
1272 Flushes any pending compressed data to the output file/buffer.
1274 This method takes an optional parameter, C<$flush_type>, that controls
1275 how the flushing will be carried out. By default the C<$flush_type>
1276 used is C<Z_FINISH>. Other valid values for C<$flush_type> are
1277 C<Z_NO_FLUSH>, C<Z_SYNC_FLUSH>, C<Z_FULL_FLUSH> and C<Z_BLOCK>. It is
1278 strongly recommended that you only set the C<flush_type> parameter if
1279 you fully understand the implications of what it does - overuse of C<flush>
1280 can seriously degrade the level of compression achieved. See the C<zlib>
1281 documentation for details.
1283 Returns true on success.
1292 Returns the uncompressed file offset.
1301 Returns true if the C<close> method has been called.
1305 $z->seek($position, $whence);
1306 seek($z, $position, $whence);
1308 Provides a sub-set of the C<seek> functionality, with the restriction
1309 that it is only legal to seek forward in the output file/buffer.
1310 It is a fatal error to attempt to seek backward.
1312 Empty parts of the file/buffer will have NULL (0x00) bytes written to them.
1314 The C<$whence> parameter takes one the usual values, namely SEEK_SET,
1315 SEEK_CUR or SEEK_END.
1317 Returns 1 on success, 0 on failure.
1326 This is a noop provided for completeness.
1332 Returns true if the object currently refers to a opened file/buffer.
1336 my $prev = $z->autoflush()
1337 my $prev = $z->autoflush(EXPR)
1339 If the C<$z> object is associated with a file or a filehandle, this method
1340 returns the current autoflush setting for the underlying filehandle. If
1341 C<EXPR> is present, and is non-zero, it will enable flushing after every
1342 write/print operation.
1344 If C<$z> is associated with a buffer, this method has no effect and always
1347 B<Note> that the special variable C<$|> B<cannot> be used to set or
1348 retrieve the autoflush setting.
1350 =head2 input_line_number
1352 $z->input_line_number()
1353 $z->input_line_number(EXPR)
1355 This method always returns C<undef> when compressing.
1362 If the C<$z> object is associated with a file or a filehandle, C<fileno>
1363 will return the underlying file descriptor. Once the C<close> method is
1364 called C<fileno> will return C<undef>.
1366 If the C<$z> object is is associated with a buffer, this method will return
1374 Flushes any pending compressed data and then closes the output file/buffer.
1376 For most versions of Perl this method will be automatically invoked if
1377 the IO::Compress::Zip object is destroyed (either explicitly or by the
1378 variable with the reference to the object going out of scope). The
1379 exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In
1380 these cases, the C<close> method will be called automatically, but
1381 not until global destruction of all live objects when the program is
1384 Therefore, if you want your scripts to be able to run on all versions
1385 of Perl, you should call C<close> explicitly and not rely on automatic
1388 Returns true on success, otherwise 0.
1390 If the C<AutoClose> option has been enabled when the IO::Compress::Zip
1391 object was created, and the object is associated with a file, the
1392 underlying file will also be closed.
1394 =head2 newStream([OPTS])
1398 $z->newStream( [OPTS] )
1400 Closes the current compressed data stream and starts a new one.
1402 OPTS consists of any of the the options that are available when creating
1405 See the L</"Constructor Options"> section for more details.
1407 =head2 deflateParams
1417 A number of symbolic constants are required by some methods in
1418 C<IO::Compress::Zip>. None are imported by default.
1424 Imports C<zip>, C<$ZipError> and all symbolic
1425 constants that can be used by C<IO::Compress::Zip>. Same as doing this
1427 use IO::Compress::Zip qw(zip $ZipError :constants) ;
1431 Import all symbolic constants. Same as doing this
1433 use IO::Compress::Zip qw(:flush :level :strategy :zip_method) ;
1437 These symbolic constants are used by the C<flush> method.
1448 These symbolic constants are used by the C<Level> option in the constructor.
1453 Z_DEFAULT_COMPRESSION
1457 These symbolic constants are used by the C<Strategy> option in the constructor.
1467 These symbolic constants are used by the C<Method> option in the
1481 =head2 Apache::GZip Revisited
1483 See L<IO::Compress::FAQ|IO::Compress::FAQ/"Apache::GZip Revisited">
1487 =head2 Working with Net::FTP
1489 See L<IO::Compress::FAQ|IO::Compress::FAQ/"Compressed files and Net::FTP">
1493 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>
1495 L<Compress::Zlib::FAQ|Compress::Zlib::FAQ>
1497 L<File::GlobMapper|File::GlobMapper>, L<Archive::Zip|Archive::Zip>,
1498 L<Archive::Tar|Archive::Tar>,
1499 L<IO::Zlib|IO::Zlib>
1501 For RFC 1950, 1951 and 1952 see
1502 F<http://www.faqs.org/rfcs/rfc1950.html>,
1503 F<http://www.faqs.org/rfcs/rfc1951.html> and
1504 F<http://www.faqs.org/rfcs/rfc1952.html>
1506 The I<zlib> compression library was written by Jean-loup Gailly
1507 F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>.
1509 The primary site for the I<zlib> compression library is
1510 F<http://www.zlib.org>.
1512 The primary site for gzip is F<http://www.gzip.org>.
1516 This module was written by Paul Marquess, F<pmqs@cpan.org>.
1518 =head1 MODIFICATION HISTORY
1520 See the Changes file.
1522 =head1 COPYRIGHT AND LICENSE
1524 Copyright (c) 2005-2009 Paul Marquess. All rights reserved.
1526 This program is free software; you can redistribute it and/or
1527 modify it under the same terms as Perl itself.