1 package IO::Compress::Zip ;
7 use IO::Compress::Base::Common 2.010 qw(:Status createSelfTiedObject);
8 use IO::Compress::RawDeflate 2.010 ;
9 use IO::Compress::Adapter::Deflate 2.010 ;
10 use IO::Compress::Adapter::Identity 2.010 ;
11 use IO::Compress::Zlib::Extra 2.010 ;
12 use IO::Compress::Zip::Constants 2.010 ;
15 use Compress::Raw::Zlib 2.010 qw(crc32) ;
18 eval { require IO::Compress::Adapter::Bzip2 ;
19 import IO::Compress::Adapter::Bzip2 2.010 ;
20 require IO::Compress::Bzip2 ;
21 import IO::Compress::Bzip2 2.010 ;
28 our ($VERSION, @ISA, @EXPORT_OK, %EXPORT_TAGS, $ZipError);
33 @ISA = qw(Exporter IO::Compress::RawDeflate);
34 @EXPORT_OK = qw( $ZipError zip ) ;
35 %EXPORT_TAGS = %IO::Compress::RawDeflate::DEFLATE_CONSTANTS ;
36 push @{ $EXPORT_TAGS{all} }, @EXPORT_OK ;
38 $EXPORT_TAGS{zip_method} = [qw( ZIP_CM_STORE ZIP_CM_DEFLATE ZIP_CM_BZIP2 )];
39 push @{ $EXPORT_TAGS{all} }, @{ $EXPORT_TAGS{zip_method} };
41 Exporter::export_ok_tags('all');
47 my $obj = createSelfTiedObject($class, \$ZipError);
48 $obj->_create(undef, @_);
53 my $obj = createSelfTiedObject(undef, \$ZipError);
54 return $obj->_def(@_);
63 my ($obj, $errstr, $errno) ;
65 if (*$self->{ZipData}{Method} == ZIP_CM_STORE) {
66 ($obj, $errstr, $errno) = IO::Compress::Adapter::Identity::mkCompObject(
68 $got->value('Strategy')
71 elsif (*$self->{ZipData}{Method} == ZIP_CM_DEFLATE) {
72 ($obj, $errstr, $errno) = IO::Compress::Adapter::Deflate::mkCompObject(
74 $got->value('Adler32'),
76 $got->value('Strategy')
79 elsif (*$self->{ZipData}{Method} == ZIP_CM_BZIP2) {
80 ($obj, $errstr, $errno) = IO::Compress::Adapter::Bzip2::mkCompObject(
81 $got->value('BlockSize100K'),
82 $got->value('WorkFactor'),
83 $got->value('Verbosity')
85 *$self->{ZipData}{CRC32} = crc32(undef);
88 return $self->saveErrorString(undef, $errstr, $errno)
91 if (! defined *$self->{ZipData}{StartOffset}) {
92 *$self->{ZipData}{StartOffset} = 0;
93 *$self->{ZipData}{Offset} = new U64 ;
103 *$self->{Compress}->reset();
104 *$self->{ZipData}{CRC32} = Compress::Raw::Zlib::crc32('');
109 sub filterUncompressed
113 if (*$self->{ZipData}{Method} == ZIP_CM_DEFLATE) {
114 *$self->{ZipData}{CRC32} = *$self->{Compress}->crc32();
117 *$self->{ZipData}{CRC32} = crc32(${$_[0]}, *$self->{ZipData}{CRC32});
127 *$self->{ZipData}{StartOffset} = *$self->{ZipData}{Offset}->get32bit() ;
130 $filename = $param->value('Name') || '';
133 $comment = $param->value('Comment') || '';
137 my $time = _unixToDosTime($param->value('Time'));
142 my $osCode = $param->value('OS_Code') ;
143 my $extFileAttr = 0 ;
145 # This code assumes Unix.
146 $extFileAttr = 0666 << 16
147 if $osCode == ZIP_OS_CODE_UNIX ;
149 if (*$self->{ZipData}{Zip64}) {
153 $x .= pack "V V", 0, 0 ; # uncompressedLength
154 $x .= pack "V V", 0, 0 ; # compressedLength
155 $x .= *$self->{ZipData}{Offset}->getPacked_V64() ; # offset to local hdr
156 #$x .= pack "V ", 0 ; # disk no
158 $x = IO::Compress::Zlib::Extra::mkSubField(ZIP_EXTRA_ID_ZIP64, $x);
163 if (! $param->value('Minimal')) {
164 if (defined $param->value('exTime'))
166 $extra .= mkExtendedTime($param->value('MTime'),
167 $param->value('ATime'),
168 $param->value('CTime'));
170 $ctlExtra .= mkExtendedTime($param->value('MTime'));
173 if ( $param->value('UID') && $osCode == ZIP_OS_CODE_UNIX)
175 $extra .= mkUnix2Extra( $param->value('UID'), $param->value('GID'));
176 $ctlExtra .= mkUnix2Extra();
179 $extFileAttr = $param->value('ExtAttr')
180 if defined $param->value('ExtAttr') ;
182 $extra .= $param->value('ExtraFieldLocal')
183 if defined $param->value('ExtraFieldLocal');
185 $ctlExtra .= $param->value('ExtraFieldCentral')
186 if defined $param->value('ExtraFieldCentral');
190 $gpFlag |= ZIP_GP_FLAG_STREAMING_MASK
191 if *$self->{ZipData}{Stream} ;
193 my $method = *$self->{ZipData}{Method} ;
195 my $version = $ZIP_CM_MIN_VERSIONS{$method};
196 $version = ZIP64_MIN_VERSION
197 if ZIP64_MIN_VERSION > $version && *$self->{ZipData}{Zip64};
198 my $madeBy = ($param->value('OS_Code') << 8) + $version;
199 my $extract = $version;
201 *$self->{ZipData}{Version} = $version;
202 *$self->{ZipData}{MadeBy} = $madeBy;
205 $ifa |= ZIP_IFA_TEXT_MASK
206 if $param->value('TextFlag');
208 $hdr .= pack "V", ZIP_LOCAL_HDR_SIG ; # signature
209 $hdr .= pack 'v', $extract ; # extract Version & OS
210 $hdr .= pack 'v', $gpFlag ; # general purpose flag (set streaming mode)
211 $hdr .= pack 'v', $method ; # compression method (deflate)
212 $hdr .= pack 'V', $time ; # last mod date/time
213 $hdr .= pack 'V', 0 ; # crc32 - 0 when streaming
214 $hdr .= pack 'V', $empty ; # compressed length - 0 when streaming
215 $hdr .= pack 'V', $empty ; # uncompressed length - 0 when streaming
216 $hdr .= pack 'v', length $filename ; # filename length
217 $hdr .= pack 'v', length $extra ; # extra length
225 $ctl .= pack "V", ZIP_CENTRAL_HDR_SIG ; # signature
226 $ctl .= pack 'v', $madeBy ; # version made by
227 $ctl .= pack 'v', $extract ; # extract Version
228 $ctl .= pack 'v', $gpFlag ; # general purpose flag (streaming mode)
229 $ctl .= pack 'v', $method ; # compression method (deflate)
230 $ctl .= pack 'V', $time ; # last mod date/time
231 $ctl .= pack 'V', 0 ; # crc32
232 $ctl .= pack 'V', $empty ; # compressed length
233 $ctl .= pack 'V', $empty ; # uncompressed length
234 $ctl .= pack 'v', length $filename ; # filename length
235 $ctl .= pack 'v', length $ctlExtra ; # extra length
236 $ctl .= pack 'v', length $comment ; # file comment length
237 $ctl .= pack 'v', 0 ; # disk number start
238 $ctl .= pack 'v', $ifa ; # internal file attributes
239 $ctl .= pack 'V', $extFileAttr ; # external file attributes
240 if (! *$self->{ZipData}{Zip64}) {
241 $ctl .= pack 'V', *$self->{ZipData}{Offset}->get32bit() ; # offset to local header
244 $ctl .= pack 'V', $empty ; # offset to local header
248 *$self->{ZipData}{StartOffset64} = 4 + length $ctl;
252 *$self->{ZipData}{Offset}->add(length $hdr) ;
254 *$self->{ZipData}{CentralHeader} = $ctl;
264 if (*$self->{ZipData}{Method} == ZIP_CM_DEFLATE) {
265 $crc32 = pack "V", *$self->{Compress}->crc32();
268 $crc32 = pack "V", *$self->{ZipData}{CRC32};
271 my $ctl = *$self->{ZipData}{CentralHeader} ;
274 if (! *$self->{ZipData}{Zip64}) {
275 $sizes .= *$self->{CompSize}->getPacked_V32() ; # Compressed size
276 $sizes .= *$self->{UnCompSize}->getPacked_V32() ; # Uncompressed size
279 $sizes .= *$self->{CompSize}->getPacked_V64() ; # Compressed size
280 $sizes .= *$self->{UnCompSize}->getPacked_V64() ; # Uncompressed size
283 my $data = $crc32 . $sizes ;
288 if (*$self->{ZipData}{Stream}) {
289 $hdr = pack "V", ZIP_DATA_HDR_SIG ; # signature
293 $self->writeAt(*$self->{ZipData}{StartOffset} + 14, $data)
297 if (! *$self->{ZipData}{Zip64})
298 { substr($ctl, 16, length $data) = $data }
300 substr($ctl, 16, length $crc32) = $crc32 ;
301 my $s = *$self->{UnCompSize}->getPacked_V64() ; # Uncompressed size
302 $s .= *$self->{CompSize}->getPacked_V64() ; # Compressed size
303 substr($ctl, *$self->{ZipData}{StartOffset64}, length $s) = $s ;
306 *$self->{ZipData}{Offset}->add(length($hdr));
307 *$self->{ZipData}{Offset}->add( *$self->{CompSize} );
308 push @{ *$self->{ZipData}{CentralDir} }, $ctl ;
318 $comment = *$self->{ZipData}{ZipComment} ;
320 my $cd_offset = *$self->{ZipData}{Offset}->get32bit() ; # offset to start central dir
322 my $entries = @{ *$self->{ZipData}{CentralDir} };
323 my $cd = join '', @{ *$self->{ZipData}{CentralDir} };
324 my $cd_len = length $cd ;
328 if ( *$self->{ZipData}{Zip64} ) {
330 my $v = *$self->{ZipData}{Version} ;
331 my $mb = *$self->{ZipData}{MadeBy} ;
332 $z64e .= pack 'v', $v ; # Version made by
333 $z64e .= pack 'v', $mb ; # Version to extract
334 $z64e .= pack 'V', 0 ; # number of disk
335 $z64e .= pack 'V', 0 ; # number of disk with central dir
336 $z64e .= U64::pack_V64 $entries ; # entries in central dir on this disk
337 $z64e .= U64::pack_V64 $entries ; # entries in central dir
338 $z64e .= U64::pack_V64 $cd_len ; # size of central dir
339 $z64e .= *$self->{ZipData}{Offset}->getPacked_V64() ; # offset to start central dir
341 $z64e = pack("V", ZIP64_END_CENTRAL_REC_HDR_SIG) # signature
342 . U64::pack_V64(length $z64e)
345 *$self->{ZipData}{Offset}->add(length $cd) ;
347 $z64e .= pack "V", ZIP64_END_CENTRAL_LOC_HDR_SIG; # signature
348 $z64e .= pack 'V', 0 ; # number of disk with central dir
349 $z64e .= *$self->{ZipData}{Offset}->getPacked_V64() ; # offset to end zip64 central dir
350 $z64e .= pack 'V', 1 ; # Total number of disks
352 # TODO - fix these when info-zip 3 is fixed.
359 $ecd .= pack "V", ZIP_END_CENTRAL_HDR_SIG ; # signature
360 $ecd .= pack 'v', 0 ; # number of disk
361 $ecd .= pack 'v', 0 ; # number of disk with central dir
362 $ecd .= pack 'v', $entries ; # entries in central dir on this disk
363 $ecd .= pack 'v', $entries ; # entries in central dir
364 $ecd .= pack 'V', $cd_len ; # size of central dir
365 $ecd .= pack 'V', $cd_offset ; # offset to start central dir
366 $ecd .= pack 'v', length $comment ; # zipfile comment length
369 return $cd . $z64e . $ecd ;
377 $got->value('CRC32' => 1);
379 if (! $got->parsed('Time') ) {
380 # Modification time defaults to now.
381 $got->value('Time' => time) ;
384 if (! $got->parsed('exTime') ) {
385 my $timeRef = $got->value('exTime');
386 if ( defined $timeRef) {
387 return $self->saveErrorString(undef, "exTime not a 3-element array ref")
388 if ref $timeRef ne 'ARRAY' || @$timeRef != 3;
391 $got->value("MTime", $timeRef->[1]);
392 $got->value("ATime", $timeRef->[0]);
393 $got->value("CTime", $timeRef->[2]);
396 # Unix2 Extended Attribute
397 if (! $got->parsed('exUnix2') ) {
398 my $timeRef = $got->value('exUnix2');
399 if ( defined $timeRef) {
400 return $self->saveErrorString(undef, "exUnix2 not a 2-element array ref")
401 if ref $timeRef ne 'ARRAY' || @$timeRef != 2;
404 $got->value("UID", $timeRef->[0]);
405 $got->value("GID", $timeRef->[1]);
408 *$self->{ZipData}{Zip64} = $got->value('Zip64');
409 *$self->{ZipData}{Stream} = $got->value('Stream');
411 return $self->saveErrorString(undef, "Zip64 only supported if Stream enabled")
412 if *$self->{ZipData}{Zip64} && ! *$self->{ZipData}{Stream} ;
414 my $method = $got->value('Method');
415 return $self->saveErrorString(undef, "Unknown Method '$method'")
416 if ! defined $ZIP_CM_MIN_VERSIONS{$method};
418 return $self->saveErrorString(undef, "Bzip2 not available")
419 if $method == ZIP_CM_BZIP2 and
420 ! defined $IO::Compress::Adapter::Bzip2::VERSION;
422 *$self->{ZipData}{Method} = $method;
424 *$self->{ZipData}{ZipComment} = $got->value('ZipComment') ;
426 for my $name (qw( ExtraFieldLocal ExtraFieldCentral ))
428 my $data = $got->value($name) ;
430 my $bad = IO::Compress::Zlib::Extra::parseExtraField($data, 1, 0) ;
431 return $self->saveErrorString(undef, "Error with $name Parameter: $bad")
434 $got->value($name, $data) ;
439 if defined $IO::Compress::Bzip2::VERSION
440 and ! IO::Compress::Bzip2::ckParams($self, $got);
449 # return $self->mkHeader(*$self->{Got});
456 use IO::Compress::Base::Common 2.010 qw(:Parse);
457 use Compress::Raw::Zlib 2.010 qw(Z_DEFLATED Z_DEFAULT_COMPRESSION Z_DEFAULT_STRATEGY);
461 @Bzip2 = IO::Compress::Bzip2::getExtraParams($self)
462 if defined $IO::Compress::Bzip2::VERSION;
466 $self->getZlibParams(),
468 'Stream' => [1, 1, Parse_boolean, 1],
469 #'Store' => [0, 1, Parse_boolean, 0],
470 'Method' => [0, 1, Parse_unsigned, ZIP_CM_DEFLATE],
472 # # Zip header fields
473 'Minimal' => [0, 1, Parse_boolean, 0],
474 'Zip64' => [0, 1, Parse_boolean, 0],
475 'Comment' => [0, 1, Parse_any, ''],
476 'ZipComment'=> [0, 1, Parse_any, ''],
477 'Name' => [0, 1, Parse_any, ''],
478 'Time' => [0, 1, Parse_any, undef],
479 'exTime' => [0, 1, Parse_any, undef],
480 'exUnix2' => [0, 1, Parse_any, undef],
481 'ExtAttr' => [0, 1, Parse_any, 0],
482 'OS_Code' => [0, 1, Parse_unsigned, $Compress::Raw::Zlib::gzip_os_code],
484 'TextFlag' => [0, 1, Parse_boolean, 0],
485 'ExtraFieldLocal' => [0, 1, Parse_any, undef],
486 'ExtraFieldCentral'=> [0, 1, Parse_any, undef],
494 return ('IO::Uncompress::Unzip',
495 \$IO::Uncompress::Unzip::UnzipError);
502 my $filename = shift ;
504 my ($mode, $uid, $gid, $atime, $mtime, $ctime)
505 = (stat($filename))[2, 4,5, 8,9,10] ;
507 $params->value('Name' => $filename)
508 if ! $params->parsed('Name') ;
510 $params->value('Time' => $mtime)
511 if ! $params->parsed('Time') ;
513 if ( ! $params->parsed('exTime'))
515 $params->value('MTime' => $mtime) ;
516 $params->value('ATime' => $atime) ;
517 $params->value('CTime' => undef) ; # No Creation time
520 # NOTE - Unix specific code alert
521 $params->value('ExtAttr' => $mode << 16)
522 if ! $params->parsed('ExtAttr');
524 $params->value('UID' => $uid) ;
525 $params->value('GID' => $gid) ;
531 # order expected is m, a, c
542 $times .= pack("V", $time);
548 return IO::Compress::Zlib::Extra::mkSubField(ZIP_EXTRA_ID_EXT_TIMESTAMP,
549 pack("C", $flags) . $times);
557 $ids .= pack("v", $id);
560 return IO::Compress::Zlib::Extra::mkSubField(ZIP_EXTRA_ID_INFO_ZIP_UNIX2,
566 sub _unixToDosTime # Archive::Zip::Member
569 # TODO - add something to cope with unix time < 1980
570 my ( $sec, $min, $hour, $mday, $mon, $year ) = localtime($time_t);
572 $dt += ( $sec >> 1 );
573 $dt += ( $min << 5 );
574 $dt += ( $hour << 11 );
575 $dt += ( $mday << 16 );
576 $dt += ( ( $mon + 1 ) << 21 );
577 $dt += ( ( $year - 80 ) << 25 );
587 IO::Compress::Zip - Write zip files/buffers
593 use IO::Compress::Zip qw(zip $ZipError) ;
595 my $status = zip $input => $output [,OPTS]
596 or die "zip failed: $ZipError\n";
598 my $z = new IO::Compress::Zip $output [,OPTS]
599 or die "zip failed: $ZipError\n";
602 $z->printf($format, $string);
604 $z->syswrite($string [, $length, $offset]);
608 $z->seek($position, $whence);
613 $z->input_line_number();
614 $z->newStream( [OPTS] );
625 printf $z $format, $string;
628 seek $z, $position, $whence
636 This module provides a Perl interface that allows writing zip
637 compressed data to files or buffer.
639 The primary purpose of this module is to provide streaming write access to
640 zip files and buffers. It is not a general-purpose file archiver. If that
641 is what you want, check out C<Archive::Zip>.
643 At present three compression methods are supported by IO::Compress::Zip,
644 namely Store (no compression at all), Deflate and Bzip2.
646 Note that to create Bzip2 content, the module C<IO::Compress::Bzip2> must
649 For reading zip files/buffers, see the companion module
650 L<IO::Uncompress::Unzip|IO::Uncompress::Unzip>.
652 =head1 Functional Interface
654 A top-level function, C<zip>, is provided to carry out
655 "one-shot" compression between buffers and/or files. For finer
656 control over the compression process, see the L</"OO Interface">
659 use IO::Compress::Zip qw(zip $ZipError) ;
661 zip $input => $output [,OPTS]
662 or die "zip failed: $ZipError\n";
664 The functional interface needs Perl5.005 or better.
666 =head2 zip $input => $output [, OPTS]
668 C<zip> expects at least two parameters, C<$input> and C<$output>.
670 =head3 The C<$input> parameter
672 The parameter, C<$input>, is used to define the source of
673 the uncompressed data.
675 It can take one of the following forms:
681 If the C<$input> parameter is a simple scalar, it is assumed to be a
682 filename. This file will be opened for reading and the input data
683 will be read from it.
687 If the C<$input> parameter is a filehandle, the input data will be
689 The string '-' can be used as an alias for standard input.
691 =item A scalar reference
693 If C<$input> is a scalar reference, the input data will be read
696 =item An array reference
698 If C<$input> is an array reference, each element in the array must be a
701 The input data will be read from each file in turn.
703 The complete array will be walked to ensure that it only
704 contains valid filenames before any data is compressed.
706 =item An Input FileGlob string
708 If C<$input> is a string that is delimited by the characters "<" and ">"
709 C<zip> will assume that it is an I<input fileglob string>. The
710 input is the list of files that match the fileglob.
712 If the fileglob does not match any files ...
714 See L<File::GlobMapper|File::GlobMapper> for more details.
718 If the C<$input> parameter is any other type, C<undef> will be returned.
720 In addition, if C<$input> is a simple filename, the default values for
721 the C<Name>, C<Time>, C<ExtAttr> and C<exTime> options will be sourced from that file.
723 If you do not want to use these defaults they can be overridden by
724 explicitly setting the C<Name>, C<Time>, C<ExtAttr> and C<exTime> options or by setting the
725 C<Minimal> parameter.
727 =head3 The C<$output> parameter
729 The parameter C<$output> is used to control the destination of the
730 compressed data. This parameter can take one of these forms.
736 If the C<$output> parameter is a simple scalar, it is assumed to be a
737 filename. This file will be opened for writing and the compressed
738 data will be written to it.
742 If the C<$output> parameter is a filehandle, the compressed data
743 will be written to it.
744 The string '-' can be used as an alias for standard output.
746 =item A scalar reference
748 If C<$output> is a scalar reference, the compressed data will be
749 stored in C<$$output>.
751 =item An Array Reference
753 If C<$output> is an array reference, the compressed data will be
754 pushed onto the array.
756 =item An Output FileGlob
758 If C<$output> is a string that is delimited by the characters "<" and ">"
759 C<zip> will assume that it is an I<output fileglob string>. The
760 output is the list of files that match the fileglob.
762 When C<$output> is an fileglob string, C<$input> must also be a fileglob
763 string. Anything else is an error.
767 If the C<$output> parameter is any other type, C<undef> will be returned.
771 When C<$input> maps to multiple files/buffers and C<$output> is a single
772 file/buffer the input files/buffers will each be stored
773 in C<$output> as a distinct entry.
775 =head2 Optional Parameters
777 Unless specified below, the optional parameters for C<zip>,
778 C<OPTS>, are the same as those used with the OO interface defined in the
779 L</"Constructor Options"> section below.
783 =item C<< AutoClose => 0|1 >>
785 This option applies to any input or output data streams to
786 C<zip> that are filehandles.
788 If C<AutoClose> is specified, and the value is true, it will result in all
789 input and/or output filehandles being closed once C<zip> has
792 This parameter defaults to 0.
794 =item C<< BinModeIn => 0|1 >>
796 When reading from a file or filehandle, set C<binmode> before reading.
800 =item C<< Append => 0|1 >>
808 To read the contents of the file C<file1.txt> and write the compressed
809 data to the file C<file1.txt.zip>.
813 use IO::Compress::Zip qw(zip $ZipError) ;
815 my $input = "file1.txt";
816 zip $input => "$input.zip"
817 or die "zip failed: $ZipError\n";
819 To read from an existing Perl filehandle, C<$input>, and write the
820 compressed data to a buffer, C<$buffer>.
824 use IO::Compress::Zip qw(zip $ZipError) ;
827 my $input = new IO::File "<file1.txt"
828 or die "Cannot open 'file1.txt': $!\n" ;
830 zip $input => \$buffer
831 or die "zip failed: $ZipError\n";
833 To compress all files in the directory "/my/home" that match "*.txt"
834 and store the compressed data in the same directory
838 use IO::Compress::Zip qw(zip $ZipError) ;
840 zip '</my/home/*.txt>' => '<*.zip>'
841 or die "zip failed: $ZipError\n";
843 and if you want to compress each file one at a time, this will do the trick
847 use IO::Compress::Zip qw(zip $ZipError) ;
849 for my $input ( glob "/my/home/*.txt" )
851 my $output = "$input.zip" ;
852 zip $input => $output
853 or die "Error compressing '$input': $ZipError\n";
860 The format of the constructor for C<IO::Compress::Zip> is shown below
862 my $z = new IO::Compress::Zip $output [,OPTS]
863 or die "IO::Compress::Zip failed: $ZipError\n";
865 It returns an C<IO::Compress::Zip> object on success and undef on failure.
866 The variable C<$ZipError> will contain an error message on failure.
868 If you are running Perl 5.005 or better the object, C<$z>, returned from
869 IO::Compress::Zip can be used exactly like an L<IO::File|IO::File> filehandle.
870 This means that all normal output file operations can be carried out
872 For example, to write to a compressed file/buffer you can use either of
875 $z->print("hello world\n");
876 print $z "hello world\n";
878 The mandatory parameter C<$output> is used to control the destination
879 of the compressed data. This parameter can take one of these forms.
885 If the C<$output> parameter is a simple scalar, it is assumed to be a
886 filename. This file will be opened for writing and the compressed data
887 will be written to it.
891 If the C<$output> parameter is a filehandle, the compressed data will be
893 The string '-' can be used as an alias for standard output.
895 =item A scalar reference
897 If C<$output> is a scalar reference, the compressed data will be stored
902 If the C<$output> parameter is any other type, C<IO::Compress::Zip>::new will
905 =head2 Constructor Options
907 C<OPTS> is any combination of the following options:
911 =item C<< AutoClose => 0|1 >>
913 This option is only valid when the C<$output> parameter is a filehandle. If
914 specified, and the value is true, it will result in the C<$output> being
915 closed once either the C<close> method is called or the C<IO::Compress::Zip>
918 This parameter defaults to 0.
920 =item C<< Append => 0|1 >>
922 Opens C<$output> in append mode.
924 The behaviour of this option is dependent on the type of C<$output>.
930 If C<$output> is a buffer and C<Append> is enabled, all compressed data
931 will be append to the end if C<$output>. Otherwise C<$output> will be
932 cleared before any data is written to it.
936 If C<$output> is a filename and C<Append> is enabled, the file will be
937 opened in append mode. Otherwise the contents of the file, if any, will be
938 truncated before any compressed data is written to it.
942 If C<$output> is a filehandle, the file pointer will be positioned to the
943 end of the file via a call to C<seek> before any compressed data is written
944 to it. Otherwise the file pointer will not be moved.
948 This parameter defaults to 0.
950 =item C<< Name => $string >>
952 Stores the contents of C<$string> in the zip filename header field. If
953 C<Name> is not specified, no zip filename field will be created.
955 =item C<< Time => $number >>
957 Sets the last modified time field in the zip header to $number.
959 This field defaults to the time the C<IO::Compress::Zip> object was created
960 if this option is not specified.
962 =item C<< ExtAttr => $attr >>
964 This option controls the "external file attributes" field in the central
965 header of the zip file. This is a 4 byte field.
967 If you are running a Unix derivative this value defaults to
971 This should allow read/write access to any files that are extracted from
974 For all other systems it defaults to 0.
976 =item C<< exTime => [$atime, $mtime, $ctime] >>
978 This option expects an array reference with exactly three elements:
979 C<$atime>, C<mtime> and C<$ctime>. These correspond to the last access
980 time, last modification time and creation time respectively.
982 It uses these values to set the extended timestamp field (ID is "UT") in
983 the local zip header using the three values, $atime, $mtime, $ctime. In
984 addition it sets the extended timestamp field in the central zip header
987 If any of the three values is C<undef> that time value will not be used.
988 So, for example, to set only the C<$mtime> you would use this
990 exTime => [undef, $mtime, undef]
992 If the C<Minimal> option is set to true, this option will be ignored.
994 By default no extended time field is created.
996 =item C<< exUnix2 => [$uid, $gid] >>
998 This option expects an array reference with exactly two elements: C<$uid>
999 and C<$gid>. These values correspond to the numeric user ID and group ID
1000 of the owner of the files respectively.
1002 When the C<exUnix2> option is present it will trigger the creation of a
1003 Unix2 extra field (ID is "Ux") in the local zip. This will be populated
1004 with C<$uid> and C<$gid>. In addition an empty Unix2 extra field will also
1005 be created in the central zip header
1007 If the C<Minimal> option is set to true, this option will be ignored.
1009 By default no Unix2 extra field is created.
1011 =item C<< Comment => $comment >>
1013 Stores the contents of C<$comment> in the Central File Header of
1016 By default, no comment field is written to the zip file.
1018 =item C<< ZipComment => $comment >>
1020 Stores the contents of C<$comment> in the End of Central Directory record
1023 By default, no comment field is written to the zip file.
1025 =item C<< Method => $method >>
1027 Controls which compression method is used. At present three compression
1028 methods are supported, namely Store (no compression at all), Deflate and
1031 The symbols, ZIP_CM_STORE, ZIP_CM_DEFLATE and ZIP_CM_BZIP2 are used to
1032 select the compression method.
1034 These constants are not imported by C<IO::Compress::Zip> by default.
1036 use IO::Compress::Zip qw(:zip_method);
1037 use IO::Compress::Zip qw(:constants);
1038 use IO::Compress::Zip qw(:all);
1040 Note that to create Bzip2 content, the module C<IO::Compress::Bzip2> must
1041 be installed. A fatal error will be thrown if you attempt to create Bzip2
1042 content when C<IO::Compress::Bzip2> is not available.
1044 The default method is ZIP_CM_DEFLATE.
1046 =item C<< Stream => 0|1 >>
1048 This option controls whether the zip file/buffer output is created in
1051 Note that when outputting to a file with streaming mode disabled (C<Stream>
1052 is 0), the output file must be seekable.
1056 =item C<< Zip64 => 0|1 >>
1058 Create a Zip64 zip file/buffer. This option should only be used if you want
1059 to store files larger than 4 Gig.
1061 If you intend to manipulate the Zip64 zip files created with this module
1062 using an external zip/unzip make sure that it supports streaming Zip64.
1064 In particular, if you are using Info-Zip you need to have zip version 3.x
1065 or better to update a Zip64 archive and unzip version 6.x to read a zip64
1066 archive. At the time of writing both are beta status.
1068 When the C<Zip64> option is enabled, the C<Stream> option I<must> be
1073 =item C<< TextFlag => 0|1 >>
1075 This parameter controls the setting of a bit in the zip central header. It
1076 is used to signal that the data stored in the zip file/buffer is probably
1081 =item C<< ExtraFieldLocal => $data >>
1082 =item C<< ExtraFieldCentral => $data >>
1084 The C<ExtraFieldLocal> option is used to store additional metadata in the
1085 local header for the zip file/buffer. The C<ExtraFieldCentral> does the
1086 same for the matching central header.
1088 An extra field consists of zero or more subfields. Each subfield consists
1089 of a two byte header followed by the subfield data.
1091 The list of subfields can be supplied in any of the following formats
1093 ExtraFieldLocal => [$id1, $data1,
1098 ExtraFieldLocal => [ [$id1 => $data1],
1103 ExtraFieldLocal => { $id1 => $data1,
1108 Where C<$id1>, C<$id2> are two byte subfield ID's.
1110 If you use the hash syntax, you have no control over the order in which
1111 the ExtraSubFields are stored, plus you cannot have SubFields with
1114 Alternatively the list of subfields can by supplied as a scalar, thus
1116 ExtraField => $rawdata
1118 The Extended Time field (ID "UT"), set using the C<exTime> option, and the
1119 Unix2 extra field (ID "Ux), set using the C<exUnix2> option, are examples
1122 If the C<Minimal> option is set to true, this option will be ignored.
1124 The maximum size of an extra field 65535 bytes.
1126 =item C<< Minimal => 1|0 >>
1128 If specified, this option will disable the creation of all extra fields
1129 in the zip local and central headers. So the C<exTime>, C<exUnix2>,
1130 C<ExtraFieldLocal> and C<ExtraFieldCentral> options will be ignored.
1132 This parameter defaults to 0.
1134 =item C<< BlockSize100K => number >>
1136 Specify the number of 100K blocks bzip2 uses during compression.
1138 Valid values are from 1 to 9, where 9 is best compression.
1140 This option is only valid if the C<Method> is ZIP_CM_BZIP2. It is ignored
1145 =item C<< WorkFactor => number >>
1147 Specifies how much effort bzip2 should take before resorting to a slower
1148 fallback compression algorithm.
1150 Valid values range from 0 to 250, where 0 means use the default value 30.
1152 This option is only valid if the C<Method> is ZIP_CM_BZIP2. It is ignored
1159 Defines the compression level used by zlib. The value should either be
1160 a number between 0 and 9 (0 means no compression and 9 is maximum
1161 compression), or one of the symbolic constants defined below.
1166 Z_DEFAULT_COMPRESSION
1168 The default is Z_DEFAULT_COMPRESSION.
1170 Note, these constants are not imported by C<IO::Compress::Zip> by default.
1172 use IO::Compress::Zip qw(:strategy);
1173 use IO::Compress::Zip qw(:constants);
1174 use IO::Compress::Zip qw(:all);
1178 Defines the strategy used to tune the compression. Use one of the symbolic
1179 constants defined below.
1187 The default is Z_DEFAULT_STRATEGY.
1189 =item C<< Strict => 0|1 >>
1191 This is a placeholder option.
1208 Compresses and outputs the contents of the C<$data> parameter. This
1209 has the same behaviour as the C<print> built-in.
1211 Returns true if successful.
1217 $z->printf($format, $data)
1218 printf $z $format, $data
1220 Compresses and outputs the contents of the C<$data> parameter.
1222 Returns true if successful.
1229 $z->syswrite $data, $length
1230 $z->syswrite $data, $length, $offset
1232 Compresses and outputs the contents of the C<$data> parameter.
1234 Returns the number of uncompressed bytes written, or C<undef> if
1242 $z->write $data, $length
1243 $z->write $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->flush($flush_type);
1257 Flushes any pending compressed data to the output file/buffer.
1259 This method takes an optional parameter, C<$flush_type>, that controls
1260 how the flushing will be carried out. By default the C<$flush_type>
1261 used is C<Z_FINISH>. Other valid values for C<$flush_type> are
1262 C<Z_NO_FLUSH>, C<Z_SYNC_FLUSH>, C<Z_FULL_FLUSH> and C<Z_BLOCK>. It is
1263 strongly recommended that you only set the C<flush_type> parameter if
1264 you fully understand the implications of what it does - overuse of C<flush>
1265 can seriously degrade the level of compression achieved. See the C<zlib>
1266 documentation for details.
1268 Returns true on success.
1277 Returns the uncompressed file offset.
1286 Returns true if the C<close> method has been called.
1290 $z->seek($position, $whence);
1291 seek($z, $position, $whence);
1293 Provides a sub-set of the C<seek> functionality, with the restriction
1294 that it is only legal to seek forward in the output file/buffer.
1295 It is a fatal error to attempt to seek backward.
1297 Empty parts of the file/buffer will have NULL (0x00) bytes written to them.
1299 The C<$whence> parameter takes one the usual values, namely SEEK_SET,
1300 SEEK_CUR or SEEK_END.
1302 Returns 1 on success, 0 on failure.
1311 This is a noop provided for completeness.
1317 Returns true if the object currently refers to a opened file/buffer.
1321 my $prev = $z->autoflush()
1322 my $prev = $z->autoflush(EXPR)
1324 If the C<$z> object is associated with a file or a filehandle, this method
1325 returns the current autoflush setting for the underlying filehandle. If
1326 C<EXPR> is present, and is non-zero, it will enable flushing after every
1327 write/print operation.
1329 If C<$z> is associated with a buffer, this method has no effect and always
1332 B<Note> that the special variable C<$|> B<cannot> be used to set or
1333 retrieve the autoflush setting.
1335 =head2 input_line_number
1337 $z->input_line_number()
1338 $z->input_line_number(EXPR)
1340 This method always returns C<undef> when compressing.
1347 If the C<$z> object is associated with a file or a filehandle, C<fileno>
1348 will return the underlying file descriptor. Once the C<close> method is
1349 called C<fileno> will return C<undef>.
1351 If the C<$z> object is is associated with a buffer, this method will return
1359 Flushes any pending compressed data and then closes the output file/buffer.
1361 For most versions of Perl this method will be automatically invoked if
1362 the IO::Compress::Zip object is destroyed (either explicitly or by the
1363 variable with the reference to the object going out of scope). The
1364 exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In
1365 these cases, the C<close> method will be called automatically, but
1366 not until global destruction of all live objects when the program is
1369 Therefore, if you want your scripts to be able to run on all versions
1370 of Perl, you should call C<close> explicitly and not rely on automatic
1373 Returns true on success, otherwise 0.
1375 If the C<AutoClose> option has been enabled when the IO::Compress::Zip
1376 object was created, and the object is associated with a file, the
1377 underlying file will also be closed.
1379 =head2 newStream([OPTS])
1383 $z->newStream( [OPTS] )
1385 Closes the current compressed data stream and starts a new one.
1387 OPTS consists of any of the the options that are available when creating
1390 See the L</"Constructor Options"> section for more details.
1392 =head2 deflateParams
1402 A number of symbolic constants are required by some methods in
1403 C<IO::Compress::Zip>. None are imported by default.
1409 Imports C<zip>, C<$ZipError> and all symbolic
1410 constants that can be used by C<IO::Compress::Zip>. Same as doing this
1412 use IO::Compress::Zip qw(zip $ZipError :constants) ;
1416 Import all symbolic constants. Same as doing this
1418 use IO::Compress::Zip qw(:flush :level :strategy :zip_method) ;
1422 These symbolic constants are used by the C<flush> method.
1433 These symbolic constants are used by the C<Level> option in the constructor.
1438 Z_DEFAULT_COMPRESSION
1442 These symbolic constants are used by the C<Strategy> option in the constructor.
1452 These symbolic constants are used by the C<Method> option in the
1466 =head2 Apache::GZip Revisited
1468 See L<IO::Compress::Zlib::FAQ|IO::Compress::Zlib::FAQ/"Apache::GZip Revisited">
1472 =head2 Working with Net::FTP
1474 See L<IO::Compress::Zlib::FAQ|IO::Compress::Zlib::FAQ/"Compressed files and Net::FTP">
1478 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>
1480 L<Compress::Zlib::FAQ|Compress::Zlib::FAQ>
1482 L<File::GlobMapper|File::GlobMapper>, L<Archive::Zip|Archive::Zip>,
1483 L<Archive::Tar|Archive::Tar>,
1484 L<IO::Zlib|IO::Zlib>
1486 For RFC 1950, 1951 and 1952 see
1487 F<http://www.faqs.org/rfcs/rfc1950.html>,
1488 F<http://www.faqs.org/rfcs/rfc1951.html> and
1489 F<http://www.faqs.org/rfcs/rfc1952.html>
1491 The I<zlib> compression library was written by Jean-loup Gailly
1492 F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>.
1494 The primary site for the I<zlib> compression library is
1495 F<http://www.zlib.org>.
1497 The primary site for gzip is F<http://www.gzip.org>.
1501 This module was written by Paul Marquess, F<pmqs@cpan.org>.
1503 =head1 MODIFICATION HISTORY
1505 See the Changes file.
1507 =head1 COPYRIGHT AND LICENSE
1509 Copyright (c) 2005-2008 Paul Marquess. All rights reserved.
1511 This program is free software; you can redistribute it and/or
1512 modify it under the same terms as Perl itself.