xref: /dokuwiki/vendor/splitbrain/php-archive/src/Zip.php (revision ddd7c157dce95be9083a32a5c95c29b0690dff1b)
1<?php
2
3namespace splitbrain\PHPArchive;
4
5/**
6 * Class Zip
7 *
8 * Creates or extracts Zip archives
9 *
10 * for specs see http://www.pkware.com/appnote
11 *
12 * @author  Andreas Gohr <andi@splitbrain.org>
13 * @package splitbrain\PHPArchive
14 * @license MIT
15 */
16class Zip extends Archive
17{
18
19    protected $file = '';
20    protected $fh;
21    protected $memory = '';
22    protected $closed = true;
23    protected $writeaccess = false;
24    protected $ctrl_dir;
25    protected $complevel = 9;
26
27    /**
28     * Set the compression level.
29     *
30     * Compression Type is ignored for ZIP
31     *
32     * You can call this function before adding each file to set differen compression levels
33     * for each file.
34     *
35     * @param int $level Compression level (0 to 9)
36     * @param int $type  Type of compression to use ignored for ZIP
37     * @return mixed
38     */
39    public function setCompression($level = 9, $type = Archive::COMPRESS_AUTO)
40    {
41        $this->complevel = $level;
42    }
43
44    /**
45     * Open an existing ZIP file for reading
46     *
47     * @param string $file
48     * @throws ArchiveIOException
49     */
50    public function open($file)
51    {
52        $this->file = $file;
53        $this->fh   = @fopen($this->file, 'rb');
54        if (!$this->fh) {
55            throw new ArchiveIOException('Could not open file for reading: '.$this->file);
56        }
57        $this->closed = false;
58    }
59
60    /**
61     * Read the contents of a ZIP archive
62     *
63     * This function lists the files stored in the archive, and returns an indexed array of FileInfo objects
64     *
65     * The archive is closed afer reading the contents, for API compatibility with TAR files
66     * Reopen the file with open() again if you want to do additional operations
67     *
68     * @throws ArchiveIOException
69     * @return FileInfo[]
70     */
71    public function contents()
72    {
73        if ($this->closed || !$this->file) {
74            throw new ArchiveIOException('Can not read from a closed archive');
75        }
76
77        $result = array();
78
79        $centd = $this->readCentralDir();
80
81        @rewind($this->fh);
82        @fseek($this->fh, $centd['offset']);
83
84        for ($i = 0; $i < $centd['entries']; $i++) {
85            $result[] = $this->header2fileinfo($this->readCentralFileHeader());
86        }
87
88        $this->close();
89        return $result;
90    }
91
92    /**
93     * Extract an existing ZIP archive
94     *
95     * The $strip parameter allows you to strip a certain number of path components from the filenames
96     * found in the tar file, similar to the --strip-components feature of GNU tar. This is triggered when
97     * an integer is passed as $strip.
98     * Alternatively a fixed string prefix may be passed in $strip. If the filename matches this prefix,
99     * the prefix will be stripped. It is recommended to give prefixes with a trailing slash.
100     *
101     * By default this will extract all files found in the archive. You can restrict the output using the $include
102     * and $exclude parameter. Both expect a full regular expression (including delimiters and modifiers). If
103     * $include is set only files that match this expression will be extracted. Files that match the $exclude
104     * expression will never be extracted. Both parameters can be used in combination. Expressions are matched against
105     * stripped filenames as described above.
106     *
107     * @param string     $outdir  the target directory for extracting
108     * @param int|string $strip   either the number of path components or a fixed prefix to strip
109     * @param string     $exclude a regular expression of files to exclude
110     * @param string     $include a regular expression of files to include
111     * @throws ArchiveIOException
112     * @return FileInfo[]
113     */
114    function extract($outdir, $strip = '', $exclude = '', $include = '')
115    {
116        if ($this->closed || !$this->file) {
117            throw new ArchiveIOException('Can not read from a closed archive');
118        }
119
120        $outdir = rtrim($outdir, '/');
121        @mkdir($outdir, 0777, true);
122
123        $extracted = array();
124
125        $cdir      = $this->readCentralDir();
126        $pos_entry = $cdir['offset']; // begin of the central file directory
127
128        for ($i = 0; $i < $cdir['entries']; $i++) {
129            // read file header
130            @fseek($this->fh, $pos_entry);
131            $header          = $this->readCentralFileHeader();
132            $header['index'] = $i;
133            $pos_entry       = ftell($this->fh); // position of the next file in central file directory
134            fseek($this->fh, $header['offset']); // seek to beginning of file header
135            $header   = $this->readFileHeader($header);
136            $fileinfo = $this->header2fileinfo($header);
137
138            // apply strip rules
139            $fileinfo->strip($strip);
140
141            // skip unwanted files
142            if (!strlen($fileinfo->getPath()) || !$fileinfo->match($include, $exclude)) {
143                continue;
144            }
145
146            $extracted[] = $fileinfo;
147
148            // create output directory
149            $output    = $outdir.'/'.$fileinfo->getPath();
150            $directory = ($header['folder']) ? $output : dirname($output);
151            @mkdir($directory, 0777, true);
152
153            // nothing more to do for directories
154            if ($fileinfo->getIsdir()) {
155                continue;
156            }
157
158            // compressed files are written to temporary .gz file first
159            if ($header['compression'] == 0) {
160                $extractto = $output;
161            } else {
162                $extractto = $output.'.gz';
163            }
164
165            // open file for writing
166            $fp = fopen($extractto, "wb");
167            if (!$fp) {
168                throw new ArchiveIOException('Could not open file for writing: '.$extractto);
169            }
170
171            // prepend compression header
172            if ($header['compression'] != 0) {
173                $binary_data = pack(
174                    'va1a1Va1a1',
175                    0x8b1f,
176                    chr($header['compression']),
177                    chr(0x00),
178                    time(),
179                    chr(0x00),
180                    chr(3)
181                );
182                fwrite($fp, $binary_data, 10);
183            }
184
185            // read the file and store it on disk
186            $size = $header['compressed_size'];
187            while ($size != 0) {
188                $read_size   = ($size < 2048 ? $size : 2048);
189                $buffer      = fread($this->fh, $read_size);
190                $binary_data = pack('a'.$read_size, $buffer);
191                fwrite($fp, $binary_data, $read_size);
192                $size -= $read_size;
193            }
194
195            // finalize compressed file
196            if ($header['compression'] != 0) {
197                $binary_data = pack('VV', $header['crc'], $header['size']);
198                fwrite($fp, $binary_data, 8);
199            }
200
201            // close file
202            fclose($fp);
203
204            // unpack compressed file
205            if ($header['compression'] != 0) {
206                $gzp = @gzopen($extractto, 'rb');
207                if (!$gzp) {
208                    @unlink($extractto);
209                    throw new ArchiveIOException('Failed file extracting. gzip support missing?');
210                }
211                $fp = @fopen($output, 'wb');
212                if (!$fp) {
213                    throw new ArchiveIOException('Could not open file for writing: '.$extractto);
214                }
215
216                $size = $header['size'];
217                while ($size != 0) {
218                    $read_size   = ($size < 2048 ? $size : 2048);
219                    $buffer      = gzread($gzp, $read_size);
220                    $binary_data = pack('a'.$read_size, $buffer);
221                    @fwrite($fp, $binary_data, $read_size);
222                    $size -= $read_size;
223                }
224                fclose($fp);
225                gzclose($gzp);
226                unlink($extractto); // remove temporary gz file
227            }
228
229            touch($output, $fileinfo->getMtime());
230            //FIXME what about permissions?
231        }
232
233        $this->close();
234        return $extracted;
235    }
236
237    /**
238     * Create a new ZIP file
239     *
240     * If $file is empty, the zip file will be created in memory
241     *
242     * @param string $file
243     * @throws ArchiveIOException
244     */
245    public function create($file = '')
246    {
247        $this->file   = $file;
248        $this->memory = '';
249        $this->fh     = 0;
250
251        if ($this->file) {
252            $this->fh = @fopen($this->file, 'wb');
253
254            if (!$this->fh) {
255                throw new ArchiveIOException('Could not open file for writing: '.$this->file);
256            }
257        }
258        $this->writeaccess = true;
259        $this->closed      = false;
260        $this->ctrl_dir    = array();
261    }
262
263    /**
264     * Add a file to the current ZIP archive using an existing file in the filesystem
265     *
266     * @param string          $file     path to the original file
267     * @param string|FileInfo $fileinfo either the name to us in archive (string) or a FileInfo oject with all meta data, empty to take from original
268     * @throws ArchiveIOException
269     */
270
271    /**
272     * Add a file to the current archive using an existing file in the filesystem
273     *
274     * @param string          $file     path to the original file
275     * @param string|FileInfo $fileinfo either the name to use in archive (string) or a FileInfo oject with all meta data, empty to take from original
276     * @throws ArchiveIOException
277     */
278    public function addFile($file, $fileinfo = '')
279    {
280        if (is_string($fileinfo)) {
281            $fileinfo = FileInfo::fromPath($file, $fileinfo);
282        }
283
284        if ($this->closed) {
285            throw new ArchiveIOException('Archive has been closed, files can no longer be added');
286        }
287
288        $data = @file_get_contents($file);
289        if ($data === false) {
290            throw new ArchiveIOException('Could not open file for reading: '.$file);
291        }
292
293        // FIXME could we stream writing compressed data? gzwrite on a fopen handle?
294        $this->addData($fileinfo, $data);
295    }
296
297    /**
298     * Add a file to the current Zip archive using the given $data as content
299     *
300     * @param string|FileInfo $fileinfo either the name to us in archive (string) or a FileInfo oject with all meta data
301     * @param string          $data     binary content of the file to add
302     * @throws ArchiveIOException
303     */
304    public function addData($fileinfo, $data)
305    {
306        if (is_string($fileinfo)) {
307            $fileinfo = new FileInfo($fileinfo);
308        }
309
310        if ($this->closed) {
311            throw new ArchiveIOException('Archive has been closed, files can no longer be added');
312        }
313
314        // prepare info and compress data
315        $size     = strlen($data);
316        $crc      = crc32($data);
317        if ($this->complevel) {
318            $data = gzcompress($data, $this->complevel);
319            $data = substr($data, 2, -4); // strip compression headers
320        }
321        $csize  = strlen($data);
322        $offset = $this->dataOffset();
323        $name   = $fileinfo->getPath();
324        $time   = $fileinfo->getMtime();
325
326        // write local file header
327        $this->writebytes($this->makeLocalFileHeader(
328            $time,
329            $crc,
330            $size,
331            $csize,
332            $name,
333            (bool) $this->complevel
334        ));
335
336        // we store no encryption header
337
338        // write data
339        $this->writebytes($data);
340
341        // we store no data descriptor
342
343        // add info to central file directory
344        $this->ctrl_dir[] = $this->makeCentralFileRecord(
345            $offset,
346            $time,
347            $crc,
348            $size,
349            $csize,
350            $name,
351            (bool) $this->complevel
352        );
353    }
354
355    /**
356     * Add the closing footer to the archive if in write mode, close all file handles
357     *
358     * After a call to this function no more data can be added to the archive, for
359     * read access no reading is allowed anymore
360     */
361    public function close()
362    {
363        if ($this->closed) {
364            return;
365        } // we did this already
366
367        if ($this->writeaccess) {
368            // write central directory
369            $offset = $this->dataOffset();
370            $ctrldir = join('', $this->ctrl_dir);
371            $this->writebytes($ctrldir);
372
373            // write end of central directory record
374            $this->writebytes("\x50\x4b\x05\x06"); // end of central dir signature
375            $this->writebytes(pack('v', 0)); // number of this disk
376            $this->writebytes(pack('v', 0)); // number of the disk with the start of the central directory
377            $this->writebytes(pack('v',
378                count($this->ctrl_dir))); // total number of entries in the central directory on this disk
379            $this->writebytes(pack('v', count($this->ctrl_dir))); // total number of entries in the central directory
380            $this->writebytes(pack('V', strlen($ctrldir))); // size of the central directory
381            $this->writebytes(pack('V',
382                $offset)); // offset of start of central directory with respect to the starting disk number
383            $this->writebytes(pack('v', 0)); // .ZIP file comment length
384
385            $this->ctrl_dir = array();
386        }
387
388        // close file handles
389        if ($this->file) {
390            fclose($this->fh);
391            $this->file = '';
392            $this->fh   = 0;
393        }
394
395        $this->writeaccess = false;
396        $this->closed      = true;
397    }
398
399    /**
400     * Returns the created in-memory archive data
401     *
402     * This implicitly calls close() on the Archive
403     */
404    public function getArchive()
405    {
406        $this->close();
407
408        return $this->memory;
409    }
410
411    /**
412     * Save the created in-memory archive data
413     *
414     * Note: It's more memory effective to specify the filename in the create() function and
415     * let the library work on the new file directly.
416     *
417     * @param     $file
418     * @throws ArchiveIOException
419     */
420    public function save($file)
421    {
422        if (!file_put_contents($file, $this->getArchive())) {
423            throw new ArchiveIOException('Could not write to file: '.$file);
424        }
425    }
426
427    /**
428     * Read the central directory
429     *
430     * This key-value list contains general information about the ZIP file
431     *
432     * @return array
433     */
434    protected function readCentralDir()
435    {
436        $size = filesize($this->file);
437        if ($size < 277) {
438            $maximum_size = $size;
439        } else {
440            $maximum_size = 277;
441        }
442
443        @fseek($this->fh, $size - $maximum_size);
444        $pos   = ftell($this->fh);
445        $bytes = 0x00000000;
446
447        while ($pos < $size) {
448            $byte  = @fread($this->fh, 1);
449            $bytes = (($bytes << 8) & 0xFFFFFFFF) | ord($byte);
450            if ($bytes == 0x504b0506) {
451                break;
452            }
453            $pos++;
454        }
455
456        $data = unpack(
457            'vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size',
458            fread($this->fh, 18)
459        );
460
461        if ($data['comment_size'] != 0) {
462            $centd['comment'] = fread($this->fh, $data['comment_size']);
463        } else {
464            $centd['comment'] = '';
465        }
466        $centd['entries']      = $data['entries'];
467        $centd['disk_entries'] = $data['disk_entries'];
468        $centd['offset']       = $data['offset'];
469        $centd['disk_start']   = $data['disk_start'];
470        $centd['size']         = $data['size'];
471        $centd['disk']         = $data['disk'];
472        return $centd;
473    }
474
475    /**
476     * Read the next central file header
477     *
478     * Assumes the current file pointer is pointing at the right position
479     *
480     * @return array
481     */
482    protected function readCentralFileHeader()
483    {
484        $binary_data = fread($this->fh, 46);
485        $header      = unpack(
486            'vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset',
487            $binary_data
488        );
489
490        if ($header['filename_len'] != 0) {
491            $header['filename'] = fread($this->fh, $header['filename_len']);
492        } else {
493            $header['filename'] = '';
494        }
495
496        if ($header['extra_len'] != 0) {
497            $header['extra'] = fread($this->fh, $header['extra_len']);
498            $header['extradata'] = $this->parseExtra($header['extra']);
499        } else {
500            $header['extra'] = '';
501            $header['extradata'] = array();
502        }
503
504        if ($header['comment_len'] != 0) {
505            $header['comment'] = fread($this->fh, $header['comment_len']);
506        } else {
507            $header['comment'] = '';
508        }
509
510        $header['mtime']           = $this->makeUnixTime($header['mdate'], $header['mtime']);
511        $header['stored_filename'] = $header['filename'];
512        $header['status']          = 'ok';
513        if (substr($header['filename'], -1) == '/') {
514            $header['external'] = 0x41FF0010;
515        }
516        $header['folder'] = ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0;
517
518        return $header;
519    }
520
521    /**
522     * Reads the local file header
523     *
524     * This header precedes each individual file inside the zip file. Assumes the current file pointer is pointing at
525     * the right position already. Enhances the given central header with the data found at the local header.
526     *
527     * @param array $header the central file header read previously (see above)
528     * @return array
529     */
530    protected function readFileHeader($header)
531    {
532        $binary_data = fread($this->fh, 30);
533        $data        = unpack(
534            'vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len',
535            $binary_data
536        );
537
538        $header['filename'] = fread($this->fh, $data['filename_len']);
539        if ($data['extra_len'] != 0) {
540            $header['extra'] = fread($this->fh, $data['extra_len']);
541            $header['extradata'] = array_merge($header['extradata'],  $this->parseExtra($header['extra']));
542        } else {
543            $header['extra'] = '';
544            $header['extradata'] = array();
545        }
546
547        $header['compression'] = $data['compression'];
548        foreach (array(
549                     'size',
550                     'compressed_size',
551                     'crc'
552                 ) as $hd) { // On ODT files, these headers are 0. Keep the previous value.
553            if ($data[$hd] != 0) {
554                $header[$hd] = $data[$hd];
555            }
556        }
557        $header['flag']  = $data['flag'];
558        $header['mtime'] = $this->makeUnixTime($data['mdate'], $data['mtime']);
559
560        $header['stored_filename'] = $header['filename'];
561        $header['status']          = "ok";
562        $header['folder']          = ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0;
563        return $header;
564    }
565
566    /**
567     * Parse the extra headers into fields
568     *
569     * @param string $header
570     * @return array
571     */
572    protected function parseExtra($header)
573    {
574        $extra = array();
575        // parse all extra fields as raw values
576        while (strlen($header) !== 0) {
577            $set = unpack('vid/vlen', $header);
578            $header = substr($header, 4);
579            $value = substr($header, 0, $set['len']);
580            $header = substr($header, $set['len']);
581            $extra[$set['id']] = $value;
582        }
583
584        // handle known ones
585        if(isset($extra[0x6375])) {
586            $extra['utf8comment'] = substr($extra[0x7075], 5); // strip version and crc
587        }
588        if(isset($extra[0x7075])) {
589            $extra['utf8path'] = substr($extra[0x7075], 5); // strip version and crc
590        }
591
592        return $extra;
593    }
594
595    /**
596     * Create fileinfo object from header data
597     *
598     * @param $header
599     * @return FileInfo
600     */
601    protected function header2fileinfo($header)
602    {
603        $fileinfo = new FileInfo();
604        $fileinfo->setSize($header['size']);
605        $fileinfo->setCompressedSize($header['compressed_size']);
606        $fileinfo->setMtime($header['mtime']);
607        $fileinfo->setComment($header['comment']);
608        $fileinfo->setIsdir($header['external'] == 0x41FF0010 || $header['external'] == 16);
609
610        if(isset($header['extradata']['utf8path'])) {
611            $fileinfo->setPath($header['extradata']['utf8path']);
612        } else {
613            $fileinfo->setPath($this->cpToUtf8($header['filename']));
614        }
615
616        if(isset($header['extradata']['utf8comment'])) {
617            $fileinfo->setComment($header['extradata']['utf8comment']);
618        } else {
619            $fileinfo->setComment($this->cpToUtf8($header['comment']));
620        }
621
622        return $fileinfo;
623    }
624
625    /**
626     * Convert the given CP437 encoded string to UTF-8
627     *
628     * Tries iconv with the correct encoding first, falls back to mbstring with CP850 which is
629     * similar enough. CP437 seems not to be available in mbstring. Lastly falls back to keeping the
630     * string as is, which is still better than nothing.
631     *
632     * @param $string
633     * @return string
634     */
635    protected function cpToUtf8($string)
636    {
637        if (function_exists('iconv')) {
638            return iconv('CP437', 'UTF-8', $string);
639        } elseif (function_exists('mb_convert_encoding')) {
640            return mb_convert_encoding($string, 'UTF-8', 'CP850');
641        } else {
642            return $string;
643        }
644    }
645
646    /**
647     * Convert the given UTF-8 encoded string to CP437
648     *
649     * Same caveats as for cpToUtf8() apply
650     *
651     * @param $string
652     * @return string
653     */
654    protected function utf8ToCp($string)
655    {
656        // try iconv first
657        if (function_exists('iconv')) {
658            $conv = @iconv('UTF-8', 'CP437//IGNORE', $string);
659            if($conv) return $conv; // it worked
660        }
661
662        // still here? iconv failed to convert the string. Try another method
663        // see http://php.net/manual/en/function.iconv.php#108643
664
665        if (function_exists('mb_convert_encoding')) {
666            return mb_convert_encoding($string, 'CP850', 'UTF-8');
667        } else {
668            return $string;
669        }
670    }
671
672
673    /**
674     * Write to the open filepointer or memory
675     *
676     * @param string $data
677     * @throws ArchiveIOException
678     * @return int number of bytes written
679     */
680    protected function writebytes($data)
681    {
682        if (!$this->file) {
683            $this->memory .= $data;
684            $written = strlen($data);
685        } else {
686            $written = @fwrite($this->fh, $data);
687        }
688        if ($written === false) {
689            throw new ArchiveIOException('Failed to write to archive stream');
690        }
691        return $written;
692    }
693
694    /**
695     * Current data pointer position
696     *
697     * @fixme might need a -1
698     * @return int
699     */
700    protected function dataOffset()
701    {
702        if ($this->file) {
703            return ftell($this->fh);
704        } else {
705            return strlen($this->memory);
706        }
707    }
708
709    /**
710     * Create a DOS timestamp from a UNIX timestamp
711     *
712     * DOS timestamps start at 1980-01-01, earlier UNIX stamps will be set to this date
713     *
714     * @param $time
715     * @return int
716     */
717    protected function makeDosTime($time)
718    {
719        $timearray = getdate($time);
720        if ($timearray['year'] < 1980) {
721            $timearray['year']    = 1980;
722            $timearray['mon']     = 1;
723            $timearray['mday']    = 1;
724            $timearray['hours']   = 0;
725            $timearray['minutes'] = 0;
726            $timearray['seconds'] = 0;
727        }
728        return (($timearray['year'] - 1980) << 25) |
729        ($timearray['mon'] << 21) |
730        ($timearray['mday'] << 16) |
731        ($timearray['hours'] << 11) |
732        ($timearray['minutes'] << 5) |
733        ($timearray['seconds'] >> 1);
734    }
735
736    /**
737     * Create a UNIX timestamp from a DOS timestamp
738     *
739     * @param $mdate
740     * @param $mtime
741     * @return int
742     */
743    protected function makeUnixTime($mdate = null, $mtime = null)
744    {
745        if ($mdate && $mtime) {
746            $year = (($mdate & 0xFE00) >> 9) + 1980;
747            $month = ($mdate & 0x01E0) >> 5;
748            $day = $mdate & 0x001F;
749
750            $hour = ($mtime & 0xF800) >> 11;
751            $minute = ($mtime & 0x07E0) >> 5;
752            $seconde = ($mtime & 0x001F) << 1;
753
754            $mtime = mktime($hour, $minute, $seconde, $month, $day, $year);
755        } else {
756            $mtime = time();
757        }
758
759        return $mtime;
760    }
761
762    /**
763     * Returns a local file header for the given data
764     *
765     * @param int $offset location of the local header
766     * @param int $ts unix timestamp
767     * @param int $crc CRC32 checksum of the uncompressed data
768     * @param int $len length of the uncompressed data
769     * @param int $clen length of the compressed data
770     * @param string $name file name
771     * @param boolean|null $comp if compression is used, if null it's determined from $len != $clen
772     * @return string
773     */
774    protected function makeCentralFileRecord($offset, $ts, $crc, $len, $clen, $name, $comp = null)
775    {
776        if(is_null($comp)) $comp = $len != $clen;
777        $comp = $comp ? 8 : 0;
778        $dtime = dechex($this->makeDosTime($ts));
779
780        list($name, $extra) = $this->encodeFilename($name);
781
782        $header = "\x50\x4b\x01\x02"; // central file header signature
783        $header .= pack('v', 14); // version made by - VFAT
784        $header .= pack('v', 20); // version needed to extract - 2.0
785        $header .= pack('v', 0); // general purpose flag - no flags set
786        $header .= pack('v', $comp); // compression method - deflate|none
787        $header .= pack(
788            'H*',
789            $dtime[6] . $dtime[7] .
790            $dtime[4] . $dtime[5] .
791            $dtime[2] . $dtime[3] .
792            $dtime[0] . $dtime[1]
793        ); //  last mod file time and date
794        $header .= pack('V', $crc); // crc-32
795        $header .= pack('V', $clen); // compressed size
796        $header .= pack('V', $len); // uncompressed size
797        $header .= pack('v', strlen($name)); // file name length
798        $header .= pack('v', strlen($extra)); // extra field length
799        $header .= pack('v', 0); // file comment length
800        $header .= pack('v', 0); // disk number start
801        $header .= pack('v', 0); // internal file attributes
802        $header .= pack('V', 0); // external file attributes  @todo was 0x32!?
803        $header .= pack('V', $offset); // relative offset of local header
804        $header .= $name; // file name
805        $header .= $extra; // extra (utf-8 filename)
806
807        return $header;
808    }
809
810    /**
811     * Returns a local file header for the given data
812     *
813     * @param int $ts unix timestamp
814     * @param int $crc CRC32 checksum of the uncompressed data
815     * @param int $len length of the uncompressed data
816     * @param int $clen length of the compressed data
817     * @param string $name file name
818     * @param boolean|null $comp if compression is used, if null it's determined from $len != $clen
819     * @return string
820     */
821    protected function makeLocalFileHeader($ts, $crc, $len, $clen, $name, $comp = null)
822    {
823        if(is_null($comp)) $comp = $len != $clen;
824        $comp = $comp ? 8 : 0;
825        $dtime = dechex($this->makeDosTime($ts));
826
827        list($name, $extra) = $this->encodeFilename($name);
828
829        $header = "\x50\x4b\x03\x04"; //  local file header signature
830        $header .= pack('v', 20); // version needed to extract - 2.0
831        $header .= pack('v', 0); // general purpose flag - no flags set
832        $header .= pack('v', $comp); // compression method - deflate|none
833        $header .= pack(
834            'H*',
835            $dtime[6] . $dtime[7] .
836            $dtime[4] . $dtime[5] .
837            $dtime[2] . $dtime[3] .
838            $dtime[0] . $dtime[1]
839        ); //  last mod file time and date
840        $header .= pack('V', $crc); // crc-32
841        $header .= pack('V', $clen); // compressed size
842        $header .= pack('V', $len); // uncompressed size
843        $header .= pack('v', strlen($name)); // file name length
844        $header .= pack('v', strlen($extra)); // extra field length
845        $header .= $name; // file name
846        $header .= $extra; // extra (utf-8 filename)
847        return $header;
848    }
849
850    /**
851     * Returns an allowed filename and an extra field header
852     *
853     * When encoding stuff outside the 7bit ASCII range it needs to be placed in a separate
854     * extra field
855     *
856     * @param $original
857     * @return array($filename, $extra)
858     */
859    protected function encodeFilename($original)
860    {
861        $cp437 = $this->utf8ToCp($original);
862        if ($cp437 === $original) {
863            return array($original, '');
864        }
865
866        $extra = pack(
867            'vvCV',
868            0x7075, // tag
869            strlen($original) + 5, // length of file + version + crc
870            1, // version
871            crc32($original) // crc
872        );
873        $extra .= $original;
874
875        return array($cp437, $extra);
876    }
877}
878