xref: /dokuwiki/vendor/splitbrain/php-archive/src/Zip.php (revision 361134418da8d033cd456de05c7a57c3cb528004)
1605f8e8dSAndreas Gohr<?php
2605f8e8dSAndreas Gohr
3605f8e8dSAndreas Gohrnamespace splitbrain\PHPArchive;
4605f8e8dSAndreas Gohr
5605f8e8dSAndreas Gohr/**
6605f8e8dSAndreas Gohr * Class Zip
7605f8e8dSAndreas Gohr *
8605f8e8dSAndreas Gohr * Creates or extracts Zip archives
9605f8e8dSAndreas Gohr *
102b6c6819SAndreas Gohr * for specs see http://www.pkware.com/appnote
112b6c6819SAndreas Gohr *
12605f8e8dSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
13605f8e8dSAndreas Gohr * @package splitbrain\PHPArchive
14605f8e8dSAndreas Gohr * @license MIT
15605f8e8dSAndreas Gohr */
16605f8e8dSAndreas Gohrclass Zip extends Archive
17605f8e8dSAndreas Gohr{
18605f8e8dSAndreas Gohr
19605f8e8dSAndreas Gohr    protected $file = '';
20605f8e8dSAndreas Gohr    protected $fh;
21605f8e8dSAndreas Gohr    protected $memory = '';
22605f8e8dSAndreas Gohr    protected $closed = true;
23605f8e8dSAndreas Gohr    protected $writeaccess = false;
24605f8e8dSAndreas Gohr    protected $ctrl_dir;
25605f8e8dSAndreas Gohr    protected $complevel = 9;
26605f8e8dSAndreas Gohr
27605f8e8dSAndreas Gohr    /**
28605f8e8dSAndreas Gohr     * Set the compression level.
29605f8e8dSAndreas Gohr     *
30605f8e8dSAndreas Gohr     * Compression Type is ignored for ZIP
31605f8e8dSAndreas Gohr     *
32605f8e8dSAndreas Gohr     * You can call this function before adding each file to set differen compression levels
33605f8e8dSAndreas Gohr     * for each file.
34605f8e8dSAndreas Gohr     *
35605f8e8dSAndreas Gohr     * @param int $level Compression level (0 to 9)
36605f8e8dSAndreas Gohr     * @param int $type  Type of compression to use ignored for ZIP
37605f8e8dSAndreas Gohr     * @return mixed
38605f8e8dSAndreas Gohr     */
39605f8e8dSAndreas Gohr    public function setCompression($level = 9, $type = Archive::COMPRESS_AUTO)
40605f8e8dSAndreas Gohr    {
41605f8e8dSAndreas Gohr        $this->complevel = $level;
42605f8e8dSAndreas Gohr    }
43605f8e8dSAndreas Gohr
44605f8e8dSAndreas Gohr    /**
45605f8e8dSAndreas Gohr     * Open an existing ZIP file for reading
46605f8e8dSAndreas Gohr     *
47605f8e8dSAndreas Gohr     * @param string $file
48605f8e8dSAndreas Gohr     * @throws ArchiveIOException
49605f8e8dSAndreas Gohr     */
50605f8e8dSAndreas Gohr    public function open($file)
51605f8e8dSAndreas Gohr    {
52605f8e8dSAndreas Gohr        $this->file = $file;
53605f8e8dSAndreas Gohr        $this->fh   = @fopen($this->file, 'rb');
54605f8e8dSAndreas Gohr        if (!$this->fh) {
55605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not open file for reading: '.$this->file);
56605f8e8dSAndreas Gohr        }
57605f8e8dSAndreas Gohr        $this->closed = false;
58605f8e8dSAndreas Gohr    }
59605f8e8dSAndreas Gohr
60605f8e8dSAndreas Gohr    /**
61605f8e8dSAndreas Gohr     * Read the contents of a ZIP archive
62605f8e8dSAndreas Gohr     *
63605f8e8dSAndreas Gohr     * This function lists the files stored in the archive, and returns an indexed array of FileInfo objects
64605f8e8dSAndreas Gohr     *
65605f8e8dSAndreas Gohr     * The archive is closed afer reading the contents, for API compatibility with TAR files
66605f8e8dSAndreas Gohr     * Reopen the file with open() again if you want to do additional operations
67605f8e8dSAndreas Gohr     *
68605f8e8dSAndreas Gohr     * @throws ArchiveIOException
69605f8e8dSAndreas Gohr     * @return FileInfo[]
70605f8e8dSAndreas Gohr     */
71605f8e8dSAndreas Gohr    public function contents()
72605f8e8dSAndreas Gohr    {
73605f8e8dSAndreas Gohr        if ($this->closed || !$this->file) {
74605f8e8dSAndreas Gohr            throw new ArchiveIOException('Can not read from a closed archive');
75605f8e8dSAndreas Gohr        }
76605f8e8dSAndreas Gohr
77605f8e8dSAndreas Gohr        $result = array();
78605f8e8dSAndreas Gohr
79605f8e8dSAndreas Gohr        $centd = $this->readCentralDir();
80605f8e8dSAndreas Gohr
81605f8e8dSAndreas Gohr        @rewind($this->fh);
82605f8e8dSAndreas Gohr        @fseek($this->fh, $centd['offset']);
83605f8e8dSAndreas Gohr
84605f8e8dSAndreas Gohr        for ($i = 0; $i < $centd['entries']; $i++) {
85605f8e8dSAndreas Gohr            $result[] = $this->header2fileinfo($this->readCentralFileHeader());
86605f8e8dSAndreas Gohr        }
87605f8e8dSAndreas Gohr
88605f8e8dSAndreas Gohr        $this->close();
89605f8e8dSAndreas Gohr        return $result;
90605f8e8dSAndreas Gohr    }
91605f8e8dSAndreas Gohr
92605f8e8dSAndreas Gohr    /**
93605f8e8dSAndreas Gohr     * Extract an existing ZIP archive
94605f8e8dSAndreas Gohr     *
95605f8e8dSAndreas Gohr     * The $strip parameter allows you to strip a certain number of path components from the filenames
96605f8e8dSAndreas Gohr     * found in the tar file, similar to the --strip-components feature of GNU tar. This is triggered when
97605f8e8dSAndreas Gohr     * an integer is passed as $strip.
98605f8e8dSAndreas Gohr     * Alternatively a fixed string prefix may be passed in $strip. If the filename matches this prefix,
99605f8e8dSAndreas Gohr     * the prefix will be stripped. It is recommended to give prefixes with a trailing slash.
100605f8e8dSAndreas Gohr     *
101605f8e8dSAndreas Gohr     * By default this will extract all files found in the archive. You can restrict the output using the $include
102605f8e8dSAndreas Gohr     * and $exclude parameter. Both expect a full regular expression (including delimiters and modifiers). If
103605f8e8dSAndreas Gohr     * $include is set only files that match this expression will be extracted. Files that match the $exclude
104605f8e8dSAndreas Gohr     * expression will never be extracted. Both parameters can be used in combination. Expressions are matched against
105605f8e8dSAndreas Gohr     * stripped filenames as described above.
106605f8e8dSAndreas Gohr     *
107605f8e8dSAndreas Gohr     * @param string     $outdir  the target directory for extracting
108605f8e8dSAndreas Gohr     * @param int|string $strip   either the number of path components or a fixed prefix to strip
109605f8e8dSAndreas Gohr     * @param string     $exclude a regular expression of files to exclude
110605f8e8dSAndreas Gohr     * @param string     $include a regular expression of files to include
111605f8e8dSAndreas Gohr     * @throws ArchiveIOException
112605f8e8dSAndreas Gohr     * @return FileInfo[]
113605f8e8dSAndreas Gohr     */
114605f8e8dSAndreas Gohr    function extract($outdir, $strip = '', $exclude = '', $include = '')
115605f8e8dSAndreas Gohr    {
116605f8e8dSAndreas Gohr        if ($this->closed || !$this->file) {
117605f8e8dSAndreas Gohr            throw new ArchiveIOException('Can not read from a closed archive');
118605f8e8dSAndreas Gohr        }
119605f8e8dSAndreas Gohr
120605f8e8dSAndreas Gohr        $outdir = rtrim($outdir, '/');
121605f8e8dSAndreas Gohr        @mkdir($outdir, 0777, true);
122605f8e8dSAndreas Gohr
123605f8e8dSAndreas Gohr        $extracted = array();
124605f8e8dSAndreas Gohr
125605f8e8dSAndreas Gohr        $cdir      = $this->readCentralDir();
126605f8e8dSAndreas Gohr        $pos_entry = $cdir['offset']; // begin of the central file directory
127605f8e8dSAndreas Gohr
128605f8e8dSAndreas Gohr        for ($i = 0; $i < $cdir['entries']; $i++) {
129605f8e8dSAndreas Gohr            // read file header
130605f8e8dSAndreas Gohr            @fseek($this->fh, $pos_entry);
131605f8e8dSAndreas Gohr            $header          = $this->readCentralFileHeader();
132605f8e8dSAndreas Gohr            $header['index'] = $i;
133605f8e8dSAndreas Gohr            $pos_entry       = ftell($this->fh); // position of the next file in central file directory
134605f8e8dSAndreas Gohr            fseek($this->fh, $header['offset']); // seek to beginning of file header
135605f8e8dSAndreas Gohr            $header   = $this->readFileHeader($header);
136605f8e8dSAndreas Gohr            $fileinfo = $this->header2fileinfo($header);
137605f8e8dSAndreas Gohr
138605f8e8dSAndreas Gohr            // apply strip rules
139605f8e8dSAndreas Gohr            $fileinfo->strip($strip);
140605f8e8dSAndreas Gohr
141605f8e8dSAndreas Gohr            // skip unwanted files
142605f8e8dSAndreas Gohr            if (!strlen($fileinfo->getPath()) || !$fileinfo->match($include, $exclude)) {
143605f8e8dSAndreas Gohr                continue;
144605f8e8dSAndreas Gohr            }
145605f8e8dSAndreas Gohr
146605f8e8dSAndreas Gohr            $extracted[] = $fileinfo;
147605f8e8dSAndreas Gohr
148605f8e8dSAndreas Gohr            // create output directory
149605f8e8dSAndreas Gohr            $output    = $outdir.'/'.$fileinfo->getPath();
150605f8e8dSAndreas Gohr            $directory = ($header['folder']) ? $output : dirname($output);
151605f8e8dSAndreas Gohr            @mkdir($directory, 0777, true);
152605f8e8dSAndreas Gohr
153605f8e8dSAndreas Gohr            // nothing more to do for directories
154605f8e8dSAndreas Gohr            if ($fileinfo->getIsdir()) {
155605f8e8dSAndreas Gohr                continue;
156605f8e8dSAndreas Gohr            }
157605f8e8dSAndreas Gohr
158605f8e8dSAndreas Gohr            // compressed files are written to temporary .gz file first
159605f8e8dSAndreas Gohr            if ($header['compression'] == 0) {
160605f8e8dSAndreas Gohr                $extractto = $output;
161605f8e8dSAndreas Gohr            } else {
162605f8e8dSAndreas Gohr                $extractto = $output.'.gz';
163605f8e8dSAndreas Gohr            }
164605f8e8dSAndreas Gohr
165605f8e8dSAndreas Gohr            // open file for writing
166605f8e8dSAndreas Gohr            $fp = fopen($extractto, "wb");
167605f8e8dSAndreas Gohr            if (!$fp) {
168605f8e8dSAndreas Gohr                throw new ArchiveIOException('Could not open file for writing: '.$extractto);
169605f8e8dSAndreas Gohr            }
170605f8e8dSAndreas Gohr
171605f8e8dSAndreas Gohr            // prepend compression header
172605f8e8dSAndreas Gohr            if ($header['compression'] != 0) {
173605f8e8dSAndreas Gohr                $binary_data = pack(
174605f8e8dSAndreas Gohr                    'va1a1Va1a1',
175605f8e8dSAndreas Gohr                    0x8b1f,
176605f8e8dSAndreas Gohr                    chr($header['compression']),
177605f8e8dSAndreas Gohr                    chr(0x00),
178605f8e8dSAndreas Gohr                    time(),
179605f8e8dSAndreas Gohr                    chr(0x00),
180605f8e8dSAndreas Gohr                    chr(3)
181605f8e8dSAndreas Gohr                );
182605f8e8dSAndreas Gohr                fwrite($fp, $binary_data, 10);
183605f8e8dSAndreas Gohr            }
184605f8e8dSAndreas Gohr
185605f8e8dSAndreas Gohr            // read the file and store it on disk
186605f8e8dSAndreas Gohr            $size = $header['compressed_size'];
187605f8e8dSAndreas Gohr            while ($size != 0) {
188605f8e8dSAndreas Gohr                $read_size   = ($size < 2048 ? $size : 2048);
189605f8e8dSAndreas Gohr                $buffer      = fread($this->fh, $read_size);
190605f8e8dSAndreas Gohr                $binary_data = pack('a'.$read_size, $buffer);
191605f8e8dSAndreas Gohr                fwrite($fp, $binary_data, $read_size);
192605f8e8dSAndreas Gohr                $size -= $read_size;
193605f8e8dSAndreas Gohr            }
194605f8e8dSAndreas Gohr
195605f8e8dSAndreas Gohr            // finalize compressed file
196605f8e8dSAndreas Gohr            if ($header['compression'] != 0) {
197605f8e8dSAndreas Gohr                $binary_data = pack('VV', $header['crc'], $header['size']);
198605f8e8dSAndreas Gohr                fwrite($fp, $binary_data, 8);
199605f8e8dSAndreas Gohr            }
200605f8e8dSAndreas Gohr
201605f8e8dSAndreas Gohr            // close file
202605f8e8dSAndreas Gohr            fclose($fp);
203605f8e8dSAndreas Gohr
204605f8e8dSAndreas Gohr            // unpack compressed file
205605f8e8dSAndreas Gohr            if ($header['compression'] != 0) {
206605f8e8dSAndreas Gohr                $gzp = @gzopen($extractto, 'rb');
207605f8e8dSAndreas Gohr                if (!$gzp) {
208605f8e8dSAndreas Gohr                    @unlink($extractto);
209605f8e8dSAndreas Gohr                    throw new ArchiveIOException('Failed file extracting. gzip support missing?');
210605f8e8dSAndreas Gohr                }
211605f8e8dSAndreas Gohr                $fp = @fopen($output, 'wb');
212605f8e8dSAndreas Gohr                if (!$fp) {
213605f8e8dSAndreas Gohr                    throw new ArchiveIOException('Could not open file for writing: '.$extractto);
214605f8e8dSAndreas Gohr                }
215605f8e8dSAndreas Gohr
216605f8e8dSAndreas Gohr                $size = $header['size'];
217605f8e8dSAndreas Gohr                while ($size != 0) {
218605f8e8dSAndreas Gohr                    $read_size   = ($size < 2048 ? $size : 2048);
219605f8e8dSAndreas Gohr                    $buffer      = gzread($gzp, $read_size);
220605f8e8dSAndreas Gohr                    $binary_data = pack('a'.$read_size, $buffer);
221605f8e8dSAndreas Gohr                    @fwrite($fp, $binary_data, $read_size);
222605f8e8dSAndreas Gohr                    $size -= $read_size;
223605f8e8dSAndreas Gohr                }
224605f8e8dSAndreas Gohr                fclose($fp);
225605f8e8dSAndreas Gohr                gzclose($gzp);
2264a690352SAndreas Gohr                unlink($extractto); // remove temporary gz file
227605f8e8dSAndreas Gohr            }
228605f8e8dSAndreas Gohr
229605f8e8dSAndreas Gohr            touch($output, $fileinfo->getMtime());
230605f8e8dSAndreas Gohr            //FIXME what about permissions?
231605f8e8dSAndreas Gohr        }
232605f8e8dSAndreas Gohr
233605f8e8dSAndreas Gohr        $this->close();
234605f8e8dSAndreas Gohr        return $extracted;
235605f8e8dSAndreas Gohr    }
236605f8e8dSAndreas Gohr
237605f8e8dSAndreas Gohr    /**
238605f8e8dSAndreas Gohr     * Create a new ZIP file
239605f8e8dSAndreas Gohr     *
240605f8e8dSAndreas Gohr     * If $file is empty, the zip file will be created in memory
241605f8e8dSAndreas Gohr     *
242605f8e8dSAndreas Gohr     * @param string $file
243605f8e8dSAndreas Gohr     * @throws ArchiveIOException
244605f8e8dSAndreas Gohr     */
245605f8e8dSAndreas Gohr    public function create($file = '')
246605f8e8dSAndreas Gohr    {
247605f8e8dSAndreas Gohr        $this->file   = $file;
248605f8e8dSAndreas Gohr        $this->memory = '';
249605f8e8dSAndreas Gohr        $this->fh     = 0;
250605f8e8dSAndreas Gohr
251605f8e8dSAndreas Gohr        if ($this->file) {
252605f8e8dSAndreas Gohr            $this->fh = @fopen($this->file, 'wb');
253605f8e8dSAndreas Gohr
254605f8e8dSAndreas Gohr            if (!$this->fh) {
255605f8e8dSAndreas Gohr                throw new ArchiveIOException('Could not open file for writing: '.$this->file);
256605f8e8dSAndreas Gohr            }
257605f8e8dSAndreas Gohr        }
258605f8e8dSAndreas Gohr        $this->writeaccess = true;
259605f8e8dSAndreas Gohr        $this->closed      = false;
260605f8e8dSAndreas Gohr        $this->ctrl_dir    = array();
261605f8e8dSAndreas Gohr    }
262605f8e8dSAndreas Gohr
263605f8e8dSAndreas Gohr    /**
264605f8e8dSAndreas Gohr     * Add a file to the current ZIP archive using an existing file in the filesystem
265605f8e8dSAndreas Gohr     *
266605f8e8dSAndreas Gohr     * @param string          $file     path to the original file
267605f8e8dSAndreas Gohr     * @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
268605f8e8dSAndreas Gohr     * @throws ArchiveIOException
269605f8e8dSAndreas Gohr     */
270605f8e8dSAndreas Gohr
271605f8e8dSAndreas Gohr    /**
272605f8e8dSAndreas Gohr     * Add a file to the current archive using an existing file in the filesystem
273605f8e8dSAndreas Gohr     *
274605f8e8dSAndreas Gohr     * @param string          $file     path to the original file
275*36113441SAndreas Gohr     * @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
276605f8e8dSAndreas Gohr     * @throws ArchiveIOException
277605f8e8dSAndreas Gohr     */
278605f8e8dSAndreas Gohr    public function addFile($file, $fileinfo = '')
279605f8e8dSAndreas Gohr    {
280605f8e8dSAndreas Gohr        if (is_string($fileinfo)) {
281605f8e8dSAndreas Gohr            $fileinfo = FileInfo::fromPath($file, $fileinfo);
282605f8e8dSAndreas Gohr        }
283605f8e8dSAndreas Gohr
284605f8e8dSAndreas Gohr        if ($this->closed) {
285605f8e8dSAndreas Gohr            throw new ArchiveIOException('Archive has been closed, files can no longer be added');
286605f8e8dSAndreas Gohr        }
287605f8e8dSAndreas Gohr
288605f8e8dSAndreas Gohr        $data = @file_get_contents($file);
289605f8e8dSAndreas Gohr        if ($data === false) {
290605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not open file for reading: '.$file);
291605f8e8dSAndreas Gohr        }
292605f8e8dSAndreas Gohr
293605f8e8dSAndreas Gohr        // FIXME could we stream writing compressed data? gzwrite on a fopen handle?
294605f8e8dSAndreas Gohr        $this->addData($fileinfo, $data);
295605f8e8dSAndreas Gohr    }
296605f8e8dSAndreas Gohr
297605f8e8dSAndreas Gohr    /**
298*36113441SAndreas Gohr     * Add a file to the current Zip archive using the given $data as content
299605f8e8dSAndreas Gohr     *
300605f8e8dSAndreas Gohr     * @param string|FileInfo $fileinfo either the name to us in archive (string) or a FileInfo oject with all meta data
301605f8e8dSAndreas Gohr     * @param string          $data     binary content of the file to add
302605f8e8dSAndreas Gohr     * @throws ArchiveIOException
303605f8e8dSAndreas Gohr     */
304605f8e8dSAndreas Gohr    public function addData($fileinfo, $data)
305605f8e8dSAndreas Gohr    {
306605f8e8dSAndreas Gohr        if (is_string($fileinfo)) {
307605f8e8dSAndreas Gohr            $fileinfo = new FileInfo($fileinfo);
308605f8e8dSAndreas Gohr        }
309605f8e8dSAndreas Gohr
310605f8e8dSAndreas Gohr        if ($this->closed) {
311605f8e8dSAndreas Gohr            throw new ArchiveIOException('Archive has been closed, files can no longer be added');
312605f8e8dSAndreas Gohr        }
313605f8e8dSAndreas Gohr
3142b6c6819SAndreas Gohr        // prepare info and compress data
315605f8e8dSAndreas Gohr        $size     = strlen($data);
316605f8e8dSAndreas Gohr        $crc      = crc32($data);
317605f8e8dSAndreas Gohr        if ($this->complevel) {
318605f8e8dSAndreas Gohr            $data = gzcompress($data, $this->complevel);
319605f8e8dSAndreas Gohr            $data = substr($data, 2, -4); // strip compression headers
320605f8e8dSAndreas Gohr        }
321605f8e8dSAndreas Gohr        $csize  = strlen($data);
322605f8e8dSAndreas Gohr        $offset = $this->dataOffset();
323605f8e8dSAndreas Gohr        $name   = $fileinfo->getPath();
3242b6c6819SAndreas Gohr        $time   = $fileinfo->getMtime();
3252b6c6819SAndreas Gohr
3262b6c6819SAndreas Gohr        // write local file header
3272b6c6819SAndreas Gohr        $this->writebytes($this->makeLocalFileHeader(
3282b6c6819SAndreas Gohr            $time,
3292b6c6819SAndreas Gohr            $crc,
3302b6c6819SAndreas Gohr            $size,
3312b6c6819SAndreas Gohr            $csize,
3322b6c6819SAndreas Gohr            $name,
3332b6c6819SAndreas Gohr            (bool) $this->complevel
3342b6c6819SAndreas Gohr        ));
3352b6c6819SAndreas Gohr
3362b6c6819SAndreas Gohr        // we store no encryption header
337605f8e8dSAndreas Gohr
338605f8e8dSAndreas Gohr        // write data
3392b6c6819SAndreas Gohr        $this->writebytes($data);
3402b6c6819SAndreas Gohr
3412b6c6819SAndreas Gohr        // we store no data descriptor
342605f8e8dSAndreas Gohr
343605f8e8dSAndreas Gohr        // add info to central file directory
3442b6c6819SAndreas Gohr        $this->ctrl_dir[] = $this->makeCentralFileRecord(
3452b6c6819SAndreas Gohr            $offset,
3462b6c6819SAndreas Gohr            $time,
3472b6c6819SAndreas Gohr            $crc,
3482b6c6819SAndreas Gohr            $size,
3492b6c6819SAndreas Gohr            $csize,
3502b6c6819SAndreas Gohr            $name,
3512b6c6819SAndreas Gohr            (bool) $this->complevel
3522b6c6819SAndreas Gohr        );
353605f8e8dSAndreas Gohr    }
354605f8e8dSAndreas Gohr
355605f8e8dSAndreas Gohr    /**
356605f8e8dSAndreas Gohr     * Add the closing footer to the archive if in write mode, close all file handles
357605f8e8dSAndreas Gohr     *
358605f8e8dSAndreas Gohr     * After a call to this function no more data can be added to the archive, for
359605f8e8dSAndreas Gohr     * read access no reading is allowed anymore
360605f8e8dSAndreas Gohr     */
361605f8e8dSAndreas Gohr    public function close()
362605f8e8dSAndreas Gohr    {
363605f8e8dSAndreas Gohr        if ($this->closed) {
364605f8e8dSAndreas Gohr            return;
365605f8e8dSAndreas Gohr        } // we did this already
366605f8e8dSAndreas Gohr
367605f8e8dSAndreas Gohr        if ($this->writeaccess) {
3682b6c6819SAndreas Gohr            // write central directory
369605f8e8dSAndreas Gohr            $offset = $this->dataOffset();
370605f8e8dSAndreas Gohr            $ctrldir = join('', $this->ctrl_dir);
371605f8e8dSAndreas Gohr            $this->writebytes($ctrldir);
3722b6c6819SAndreas Gohr
3732b6c6819SAndreas Gohr            // write end of central directory record
3742b6c6819SAndreas Gohr            $this->writebytes("\x50\x4b\x05\x06"); // end of central dir signature
3752b6c6819SAndreas Gohr            $this->writebytes(pack('v', 0)); // number of this disk
3762b6c6819SAndreas Gohr            $this->writebytes(pack('v', 0)); // number of the disk with the start of the central directory
3772b6c6819SAndreas Gohr            $this->writebytes(pack('v',
3782b6c6819SAndreas Gohr                count($this->ctrl_dir))); // total number of entries in the central directory on this disk
3792b6c6819SAndreas Gohr            $this->writebytes(pack('v', count($this->ctrl_dir))); // total number of entries in the central directory
3802b6c6819SAndreas Gohr            $this->writebytes(pack('V', strlen($ctrldir))); // size of the central directory
3812b6c6819SAndreas Gohr            $this->writebytes(pack('V',
3822b6c6819SAndreas Gohr                $offset)); // offset of start of central directory with respect to the starting disk number
3832b6c6819SAndreas Gohr            $this->writebytes(pack('v', 0)); // .ZIP file comment length
3842b6c6819SAndreas Gohr
385605f8e8dSAndreas Gohr            $this->ctrl_dir = array();
386605f8e8dSAndreas Gohr        }
387605f8e8dSAndreas Gohr
388605f8e8dSAndreas Gohr        // close file handles
389605f8e8dSAndreas Gohr        if ($this->file) {
390605f8e8dSAndreas Gohr            fclose($this->fh);
391605f8e8dSAndreas Gohr            $this->file = '';
392605f8e8dSAndreas Gohr            $this->fh   = 0;
393605f8e8dSAndreas Gohr        }
394605f8e8dSAndreas Gohr
395605f8e8dSAndreas Gohr        $this->writeaccess = false;
396605f8e8dSAndreas Gohr        $this->closed      = true;
397605f8e8dSAndreas Gohr    }
398605f8e8dSAndreas Gohr
399605f8e8dSAndreas Gohr    /**
400605f8e8dSAndreas Gohr     * Returns the created in-memory archive data
401605f8e8dSAndreas Gohr     *
402605f8e8dSAndreas Gohr     * This implicitly calls close() on the Archive
403605f8e8dSAndreas Gohr     */
404605f8e8dSAndreas Gohr    public function getArchive()
405605f8e8dSAndreas Gohr    {
406605f8e8dSAndreas Gohr        $this->close();
407605f8e8dSAndreas Gohr
408605f8e8dSAndreas Gohr        return $this->memory;
409605f8e8dSAndreas Gohr    }
410605f8e8dSAndreas Gohr
411605f8e8dSAndreas Gohr    /**
412605f8e8dSAndreas Gohr     * Save the created in-memory archive data
413605f8e8dSAndreas Gohr     *
414605f8e8dSAndreas Gohr     * Note: It's more memory effective to specify the filename in the create() function and
415605f8e8dSAndreas Gohr     * let the library work on the new file directly.
416605f8e8dSAndreas Gohr     *
417605f8e8dSAndreas Gohr     * @param     $file
418605f8e8dSAndreas Gohr     * @throws ArchiveIOException
419605f8e8dSAndreas Gohr     */
420605f8e8dSAndreas Gohr    public function save($file)
421605f8e8dSAndreas Gohr    {
422605f8e8dSAndreas Gohr        if (!file_put_contents($file, $this->getArchive())) {
423605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not write to file: '.$file);
424605f8e8dSAndreas Gohr        }
425605f8e8dSAndreas Gohr    }
426605f8e8dSAndreas Gohr
427605f8e8dSAndreas Gohr    /**
428605f8e8dSAndreas Gohr     * Read the central directory
429605f8e8dSAndreas Gohr     *
430605f8e8dSAndreas Gohr     * This key-value list contains general information about the ZIP file
431605f8e8dSAndreas Gohr     *
432605f8e8dSAndreas Gohr     * @return array
433605f8e8dSAndreas Gohr     */
434605f8e8dSAndreas Gohr    protected function readCentralDir()
435605f8e8dSAndreas Gohr    {
436605f8e8dSAndreas Gohr        $size = filesize($this->file);
437605f8e8dSAndreas Gohr        if ($size < 277) {
438605f8e8dSAndreas Gohr            $maximum_size = $size;
439605f8e8dSAndreas Gohr        } else {
440605f8e8dSAndreas Gohr            $maximum_size = 277;
441605f8e8dSAndreas Gohr        }
442605f8e8dSAndreas Gohr
443605f8e8dSAndreas Gohr        @fseek($this->fh, $size - $maximum_size);
444605f8e8dSAndreas Gohr        $pos   = ftell($this->fh);
445605f8e8dSAndreas Gohr        $bytes = 0x00000000;
446605f8e8dSAndreas Gohr
447605f8e8dSAndreas Gohr        while ($pos < $size) {
448605f8e8dSAndreas Gohr            $byte  = @fread($this->fh, 1);
449605f8e8dSAndreas Gohr            $bytes = (($bytes << 8) & 0xFFFFFFFF) | ord($byte);
450605f8e8dSAndreas Gohr            if ($bytes == 0x504b0506) {
451605f8e8dSAndreas Gohr                break;
452605f8e8dSAndreas Gohr            }
453605f8e8dSAndreas Gohr            $pos++;
454605f8e8dSAndreas Gohr        }
455605f8e8dSAndreas Gohr
456605f8e8dSAndreas Gohr        $data = unpack(
457605f8e8dSAndreas Gohr            'vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size',
458605f8e8dSAndreas Gohr            fread($this->fh, 18)
459605f8e8dSAndreas Gohr        );
460605f8e8dSAndreas Gohr
461605f8e8dSAndreas Gohr        if ($data['comment_size'] != 0) {
462605f8e8dSAndreas Gohr            $centd['comment'] = fread($this->fh, $data['comment_size']);
463605f8e8dSAndreas Gohr        } else {
464605f8e8dSAndreas Gohr            $centd['comment'] = '';
465605f8e8dSAndreas Gohr        }
466605f8e8dSAndreas Gohr        $centd['entries']      = $data['entries'];
467605f8e8dSAndreas Gohr        $centd['disk_entries'] = $data['disk_entries'];
468605f8e8dSAndreas Gohr        $centd['offset']       = $data['offset'];
469605f8e8dSAndreas Gohr        $centd['disk_start']   = $data['disk_start'];
470605f8e8dSAndreas Gohr        $centd['size']         = $data['size'];
471605f8e8dSAndreas Gohr        $centd['disk']         = $data['disk'];
472605f8e8dSAndreas Gohr        return $centd;
473605f8e8dSAndreas Gohr    }
474605f8e8dSAndreas Gohr
475605f8e8dSAndreas Gohr    /**
476605f8e8dSAndreas Gohr     * Read the next central file header
477605f8e8dSAndreas Gohr     *
478605f8e8dSAndreas Gohr     * Assumes the current file pointer is pointing at the right position
479605f8e8dSAndreas Gohr     *
480605f8e8dSAndreas Gohr     * @return array
481605f8e8dSAndreas Gohr     */
482605f8e8dSAndreas Gohr    protected function readCentralFileHeader()
483605f8e8dSAndreas Gohr    {
484605f8e8dSAndreas Gohr        $binary_data = fread($this->fh, 46);
485605f8e8dSAndreas Gohr        $header      = unpack(
486605f8e8dSAndreas Gohr            'vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset',
487605f8e8dSAndreas Gohr            $binary_data
488605f8e8dSAndreas Gohr        );
489605f8e8dSAndreas Gohr
490605f8e8dSAndreas Gohr        if ($header['filename_len'] != 0) {
491605f8e8dSAndreas Gohr            $header['filename'] = fread($this->fh, $header['filename_len']);
492605f8e8dSAndreas Gohr        } else {
493605f8e8dSAndreas Gohr            $header['filename'] = '';
494605f8e8dSAndreas Gohr        }
495605f8e8dSAndreas Gohr
496605f8e8dSAndreas Gohr        if ($header['extra_len'] != 0) {
497605f8e8dSAndreas Gohr            $header['extra'] = fread($this->fh, $header['extra_len']);
498*36113441SAndreas Gohr            $header['extradata'] = $this->parseExtra($header['extra']);
499605f8e8dSAndreas Gohr        } else {
500605f8e8dSAndreas Gohr            $header['extra'] = '';
501*36113441SAndreas Gohr            $header['extradata'] = array();
502605f8e8dSAndreas Gohr        }
503605f8e8dSAndreas Gohr
504605f8e8dSAndreas Gohr        if ($header['comment_len'] != 0) {
505605f8e8dSAndreas Gohr            $header['comment'] = fread($this->fh, $header['comment_len']);
506605f8e8dSAndreas Gohr        } else {
507605f8e8dSAndreas Gohr            $header['comment'] = '';
508605f8e8dSAndreas Gohr        }
509605f8e8dSAndreas Gohr
5102b6c6819SAndreas Gohr        $header['mtime']           = $this->makeUnixTime($header['mdate'], $header['mtime']);
511605f8e8dSAndreas Gohr        $header['stored_filename'] = $header['filename'];
512605f8e8dSAndreas Gohr        $header['status']          = 'ok';
513605f8e8dSAndreas Gohr        if (substr($header['filename'], -1) == '/') {
514605f8e8dSAndreas Gohr            $header['external'] = 0x41FF0010;
515605f8e8dSAndreas Gohr        }
516605f8e8dSAndreas Gohr        $header['folder'] = ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0;
517605f8e8dSAndreas Gohr
518605f8e8dSAndreas Gohr        return $header;
519605f8e8dSAndreas Gohr    }
520605f8e8dSAndreas Gohr
521605f8e8dSAndreas Gohr    /**
522605f8e8dSAndreas Gohr     * Reads the local file header
523605f8e8dSAndreas Gohr     *
524605f8e8dSAndreas Gohr     * This header precedes each individual file inside the zip file. Assumes the current file pointer is pointing at
5252b6c6819SAndreas Gohr     * the right position already. Enhances the given central header with the data found at the local header.
526605f8e8dSAndreas Gohr     *
527605f8e8dSAndreas Gohr     * @param array $header the central file header read previously (see above)
528605f8e8dSAndreas Gohr     * @return array
529605f8e8dSAndreas Gohr     */
5302b6c6819SAndreas Gohr    protected function readFileHeader($header)
531605f8e8dSAndreas Gohr    {
532605f8e8dSAndreas Gohr        $binary_data = fread($this->fh, 30);
533605f8e8dSAndreas Gohr        $data        = unpack(
534605f8e8dSAndreas Gohr            'vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len',
535605f8e8dSAndreas Gohr            $binary_data
536605f8e8dSAndreas Gohr        );
537605f8e8dSAndreas Gohr
538605f8e8dSAndreas Gohr        $header['filename'] = fread($this->fh, $data['filename_len']);
539605f8e8dSAndreas Gohr        if ($data['extra_len'] != 0) {
540605f8e8dSAndreas Gohr            $header['extra'] = fread($this->fh, $data['extra_len']);
541*36113441SAndreas Gohr            $header['extradata'] = array_merge($header['extradata'],  $this->parseExtra($header['extra']));
542605f8e8dSAndreas Gohr        } else {
543605f8e8dSAndreas Gohr            $header['extra'] = '';
544*36113441SAndreas Gohr            $header['extradata'] = array();
545605f8e8dSAndreas Gohr        }
546605f8e8dSAndreas Gohr
547605f8e8dSAndreas Gohr        $header['compression'] = $data['compression'];
548605f8e8dSAndreas Gohr        foreach (array(
549605f8e8dSAndreas Gohr                     'size',
550605f8e8dSAndreas Gohr                     'compressed_size',
551605f8e8dSAndreas Gohr                     'crc'
552605f8e8dSAndreas Gohr                 ) as $hd) { // On ODT files, these headers are 0. Keep the previous value.
553605f8e8dSAndreas Gohr            if ($data[$hd] != 0) {
554605f8e8dSAndreas Gohr                $header[$hd] = $data[$hd];
555605f8e8dSAndreas Gohr            }
556605f8e8dSAndreas Gohr        }
557605f8e8dSAndreas Gohr        $header['flag']  = $data['flag'];
5582b6c6819SAndreas Gohr        $header['mtime'] = $this->makeUnixTime($data['mdate'], $data['mtime']);
559605f8e8dSAndreas Gohr
560605f8e8dSAndreas Gohr        $header['stored_filename'] = $header['filename'];
561605f8e8dSAndreas Gohr        $header['status']          = "ok";
562605f8e8dSAndreas Gohr        $header['folder']          = ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0;
563605f8e8dSAndreas Gohr        return $header;
564605f8e8dSAndreas Gohr    }
565605f8e8dSAndreas Gohr
566605f8e8dSAndreas Gohr    /**
567*36113441SAndreas Gohr     * Parse the extra headers into fields
568*36113441SAndreas Gohr     *
569*36113441SAndreas Gohr     * @param string $header
570*36113441SAndreas Gohr     * @return array
571*36113441SAndreas Gohr     */
572*36113441SAndreas Gohr    protected function parseExtra($header)
573*36113441SAndreas Gohr    {
574*36113441SAndreas Gohr        $extra = array();
575*36113441SAndreas Gohr        // parse all extra fields as raw values
576*36113441SAndreas Gohr        while (strlen($header) !== 0) {
577*36113441SAndreas Gohr            $set = unpack('vid/vlen', $header);
578*36113441SAndreas Gohr            $header = substr($header, 4);
579*36113441SAndreas Gohr            $value = substr($header, 0, $set['len']);
580*36113441SAndreas Gohr            $header = substr($header, $set['len']);
581*36113441SAndreas Gohr            $extra[$set['id']] = $value;
582*36113441SAndreas Gohr        }
583*36113441SAndreas Gohr
584*36113441SAndreas Gohr        // handle known ones
585*36113441SAndreas Gohr        if(isset($extra[0x6375])) {
586*36113441SAndreas Gohr            $extra['utf8comment'] = substr($extra[0x7075], 5); // strip version and crc
587*36113441SAndreas Gohr        }
588*36113441SAndreas Gohr        if(isset($extra[0x7075])) {
589*36113441SAndreas Gohr            $extra['utf8path'] = substr($extra[0x7075], 5); // strip version and crc
590*36113441SAndreas Gohr        }
591*36113441SAndreas Gohr
592*36113441SAndreas Gohr        return $extra;
593*36113441SAndreas Gohr    }
594*36113441SAndreas Gohr
595*36113441SAndreas Gohr    /**
596605f8e8dSAndreas Gohr     * Create fileinfo object from header data
597605f8e8dSAndreas Gohr     *
598605f8e8dSAndreas Gohr     * @param $header
599605f8e8dSAndreas Gohr     * @return FileInfo
600605f8e8dSAndreas Gohr     */
601605f8e8dSAndreas Gohr    protected function header2fileinfo($header)
602605f8e8dSAndreas Gohr    {
603605f8e8dSAndreas Gohr        $fileinfo = new FileInfo();
604605f8e8dSAndreas Gohr        $fileinfo->setSize($header['size']);
605605f8e8dSAndreas Gohr        $fileinfo->setCompressedSize($header['compressed_size']);
606605f8e8dSAndreas Gohr        $fileinfo->setMtime($header['mtime']);
607605f8e8dSAndreas Gohr        $fileinfo->setComment($header['comment']);
608605f8e8dSAndreas Gohr        $fileinfo->setIsdir($header['external'] == 0x41FF0010 || $header['external'] == 16);
609*36113441SAndreas Gohr
610*36113441SAndreas Gohr        if(isset($header['extradata']['utf8path'])) {
611*36113441SAndreas Gohr            $fileinfo->setPath($header['extradata']['utf8path']);
612*36113441SAndreas Gohr        } else {
613*36113441SAndreas Gohr            $fileinfo->setPath($this->cpToUtf8($header['filename']));
614*36113441SAndreas Gohr        }
615*36113441SAndreas Gohr
616*36113441SAndreas Gohr        if(isset($header['extradata']['utf8comment'])) {
617*36113441SAndreas Gohr            $fileinfo->setComment($header['extradata']['utf8comment']);
618*36113441SAndreas Gohr        } else {
619*36113441SAndreas Gohr            $fileinfo->setComment($this->cpToUtf8($header['comment']));
620*36113441SAndreas Gohr        }
621*36113441SAndreas Gohr
622605f8e8dSAndreas Gohr        return $fileinfo;
623605f8e8dSAndreas Gohr    }
624605f8e8dSAndreas Gohr
625605f8e8dSAndreas Gohr    /**
626*36113441SAndreas Gohr     * Convert the given CP437 encoded string to UTF-8
627*36113441SAndreas Gohr     *
628*36113441SAndreas Gohr     * Tries iconv with the correct encoding first, falls back to mbstring with CP850 which is
629*36113441SAndreas Gohr     * similar enough. CP437 seems not to be available in mbstring. Lastly falls back to keeping the
630*36113441SAndreas Gohr     * string as is, which is still better than nothing.
631*36113441SAndreas Gohr     *
632*36113441SAndreas Gohr     * @param $string
633*36113441SAndreas Gohr     * @return string
634*36113441SAndreas Gohr     */
635*36113441SAndreas Gohr    protected function cpToUtf8($string)
636*36113441SAndreas Gohr    {
637*36113441SAndreas Gohr        if (function_exists('iconv')) {
638*36113441SAndreas Gohr            return iconv('CP437', 'UTF-8', $string);
639*36113441SAndreas Gohr        } elseif (function_exists('mb_convert_encoding')) {
640*36113441SAndreas Gohr            return mb_convert_encoding($string, 'UTF-8', 'CP850');
641*36113441SAndreas Gohr        } else {
642*36113441SAndreas Gohr            return $string;
643*36113441SAndreas Gohr        }
644*36113441SAndreas Gohr    }
645*36113441SAndreas Gohr
646*36113441SAndreas Gohr    /**
647*36113441SAndreas Gohr     * Convert the given UTF-8 encoded string to CP437
648*36113441SAndreas Gohr     *
649*36113441SAndreas Gohr     * Same caveats as for cpToUtf8() apply
650*36113441SAndreas Gohr     *
651*36113441SAndreas Gohr     * @param $string
652*36113441SAndreas Gohr     * @return string
653*36113441SAndreas Gohr     */
654*36113441SAndreas Gohr    protected function utf8ToCp($string)
655*36113441SAndreas Gohr    {
656*36113441SAndreas Gohr        // try iconv first
657*36113441SAndreas Gohr        if (function_exists('iconv')) {
658*36113441SAndreas Gohr            $conv = @iconv('UTF-8', 'CP437//IGNORE', $string);
659*36113441SAndreas Gohr            if($conv) return $conv; // it worked
660*36113441SAndreas Gohr        }
661*36113441SAndreas Gohr
662*36113441SAndreas Gohr        // still here? iconv failed to convert the string. Try another method
663*36113441SAndreas Gohr        // see http://php.net/manual/en/function.iconv.php#108643
664*36113441SAndreas Gohr
665*36113441SAndreas Gohr        if (function_exists('mb_convert_encoding')) {
666*36113441SAndreas Gohr            return mb_convert_encoding($string, 'CP850', 'UTF-8');
667*36113441SAndreas Gohr        } else {
668*36113441SAndreas Gohr            return $string;
669*36113441SAndreas Gohr        }
670*36113441SAndreas Gohr    }
671*36113441SAndreas Gohr
672*36113441SAndreas Gohr
673*36113441SAndreas Gohr    /**
674605f8e8dSAndreas Gohr     * Write to the open filepointer or memory
675605f8e8dSAndreas Gohr     *
676605f8e8dSAndreas Gohr     * @param string $data
677605f8e8dSAndreas Gohr     * @throws ArchiveIOException
678605f8e8dSAndreas Gohr     * @return int number of bytes written
679605f8e8dSAndreas Gohr     */
680605f8e8dSAndreas Gohr    protected function writebytes($data)
681605f8e8dSAndreas Gohr    {
682605f8e8dSAndreas Gohr        if (!$this->file) {
683605f8e8dSAndreas Gohr            $this->memory .= $data;
684605f8e8dSAndreas Gohr            $written = strlen($data);
685605f8e8dSAndreas Gohr        } else {
686605f8e8dSAndreas Gohr            $written = @fwrite($this->fh, $data);
687605f8e8dSAndreas Gohr        }
688605f8e8dSAndreas Gohr        if ($written === false) {
689605f8e8dSAndreas Gohr            throw new ArchiveIOException('Failed to write to archive stream');
690605f8e8dSAndreas Gohr        }
691605f8e8dSAndreas Gohr        return $written;
692605f8e8dSAndreas Gohr    }
693605f8e8dSAndreas Gohr
694605f8e8dSAndreas Gohr    /**
695605f8e8dSAndreas Gohr     * Current data pointer position
696605f8e8dSAndreas Gohr     *
697605f8e8dSAndreas Gohr     * @fixme might need a -1
698605f8e8dSAndreas Gohr     * @return int
699605f8e8dSAndreas Gohr     */
700605f8e8dSAndreas Gohr    protected function dataOffset()
701605f8e8dSAndreas Gohr    {
702605f8e8dSAndreas Gohr        if ($this->file) {
703605f8e8dSAndreas Gohr            return ftell($this->fh);
704605f8e8dSAndreas Gohr        } else {
705605f8e8dSAndreas Gohr            return strlen($this->memory);
706605f8e8dSAndreas Gohr        }
707605f8e8dSAndreas Gohr    }
708605f8e8dSAndreas Gohr
709605f8e8dSAndreas Gohr    /**
710605f8e8dSAndreas Gohr     * Create a DOS timestamp from a UNIX timestamp
711605f8e8dSAndreas Gohr     *
712605f8e8dSAndreas Gohr     * DOS timestamps start at 1980-01-01, earlier UNIX stamps will be set to this date
713605f8e8dSAndreas Gohr     *
714605f8e8dSAndreas Gohr     * @param $time
715605f8e8dSAndreas Gohr     * @return int
716605f8e8dSAndreas Gohr     */
717605f8e8dSAndreas Gohr    protected function makeDosTime($time)
718605f8e8dSAndreas Gohr    {
719605f8e8dSAndreas Gohr        $timearray = getdate($time);
720605f8e8dSAndreas Gohr        if ($timearray['year'] < 1980) {
721605f8e8dSAndreas Gohr            $timearray['year']    = 1980;
722605f8e8dSAndreas Gohr            $timearray['mon']     = 1;
723605f8e8dSAndreas Gohr            $timearray['mday']    = 1;
724605f8e8dSAndreas Gohr            $timearray['hours']   = 0;
725605f8e8dSAndreas Gohr            $timearray['minutes'] = 0;
726605f8e8dSAndreas Gohr            $timearray['seconds'] = 0;
727605f8e8dSAndreas Gohr        }
728605f8e8dSAndreas Gohr        return (($timearray['year'] - 1980) << 25) |
729605f8e8dSAndreas Gohr        ($timearray['mon'] << 21) |
730605f8e8dSAndreas Gohr        ($timearray['mday'] << 16) |
731605f8e8dSAndreas Gohr        ($timearray['hours'] << 11) |
732605f8e8dSAndreas Gohr        ($timearray['minutes'] << 5) |
733605f8e8dSAndreas Gohr        ($timearray['seconds'] >> 1);
734605f8e8dSAndreas Gohr    }
735605f8e8dSAndreas Gohr
7362b6c6819SAndreas Gohr    /**
7372b6c6819SAndreas Gohr     * Create a UNIX timestamp from a DOS timestamp
7382b6c6819SAndreas Gohr     *
7392b6c6819SAndreas Gohr     * @param $mdate
7402b6c6819SAndreas Gohr     * @param $mtime
7412b6c6819SAndreas Gohr     * @return int
7422b6c6819SAndreas Gohr     */
7432b6c6819SAndreas Gohr    protected function makeUnixTime($mdate = null, $mtime = null)
7442b6c6819SAndreas Gohr    {
7452b6c6819SAndreas Gohr        if ($mdate && $mtime) {
7462b6c6819SAndreas Gohr            $year = (($mdate & 0xFE00) >> 9) + 1980;
7472b6c6819SAndreas Gohr            $month = ($mdate & 0x01E0) >> 5;
7482b6c6819SAndreas Gohr            $day = $mdate & 0x001F;
7492b6c6819SAndreas Gohr
7502b6c6819SAndreas Gohr            $hour = ($mtime & 0xF800) >> 11;
7512b6c6819SAndreas Gohr            $minute = ($mtime & 0x07E0) >> 5;
7522b6c6819SAndreas Gohr            $seconde = ($mtime & 0x001F) << 1;
7532b6c6819SAndreas Gohr
7542b6c6819SAndreas Gohr            $mtime = mktime($hour, $minute, $seconde, $month, $day, $year);
7552b6c6819SAndreas Gohr        } else {
7562b6c6819SAndreas Gohr            $mtime = time();
7572b6c6819SAndreas Gohr        }
7582b6c6819SAndreas Gohr
7592b6c6819SAndreas Gohr        return $mtime;
7602b6c6819SAndreas Gohr    }
7612b6c6819SAndreas Gohr
7622b6c6819SAndreas Gohr    /**
7632b6c6819SAndreas Gohr     * Returns a local file header for the given data
7642b6c6819SAndreas Gohr     *
7652b6c6819SAndreas Gohr     * @param int $offset location of the local header
7662b6c6819SAndreas Gohr     * @param int $ts unix timestamp
7672b6c6819SAndreas Gohr     * @param int $crc CRC32 checksum of the uncompressed data
7682b6c6819SAndreas Gohr     * @param int $len length of the uncompressed data
7692b6c6819SAndreas Gohr     * @param int $clen length of the compressed data
7702b6c6819SAndreas Gohr     * @param string $name file name
7712b6c6819SAndreas Gohr     * @param boolean|null $comp if compression is used, if null it's determined from $len != $clen
7722b6c6819SAndreas Gohr     * @return string
7732b6c6819SAndreas Gohr     */
7742b6c6819SAndreas Gohr    protected function makeCentralFileRecord($offset, $ts, $crc, $len, $clen, $name, $comp = null)
7752b6c6819SAndreas Gohr    {
7762b6c6819SAndreas Gohr        if(is_null($comp)) $comp = $len != $clen;
7772b6c6819SAndreas Gohr        $comp = $comp ? 8 : 0;
7782b6c6819SAndreas Gohr        $dtime = dechex($this->makeDosTime($ts));
7792b6c6819SAndreas Gohr
780*36113441SAndreas Gohr        list($name, $extra) = $this->encodeFilename($name);
781*36113441SAndreas Gohr
7822b6c6819SAndreas Gohr        $header = "\x50\x4b\x01\x02"; // central file header signature
7832b6c6819SAndreas Gohr        $header .= pack('v', 14); // version made by - VFAT
7842b6c6819SAndreas Gohr        $header .= pack('v', 20); // version needed to extract - 2.0
7852b6c6819SAndreas Gohr        $header .= pack('v', 0); // general purpose flag - no flags set
7862b6c6819SAndreas Gohr        $header .= pack('v', $comp); // compression method - deflate|none
7872b6c6819SAndreas Gohr        $header .= pack(
7882b6c6819SAndreas Gohr            'H*',
7892b6c6819SAndreas Gohr            $dtime[6] . $dtime[7] .
7902b6c6819SAndreas Gohr            $dtime[4] . $dtime[5] .
7912b6c6819SAndreas Gohr            $dtime[2] . $dtime[3] .
7922b6c6819SAndreas Gohr            $dtime[0] . $dtime[1]
7932b6c6819SAndreas Gohr        ); //  last mod file time and date
7942b6c6819SAndreas Gohr        $header .= pack('V', $crc); // crc-32
7952b6c6819SAndreas Gohr        $header .= pack('V', $clen); // compressed size
7962b6c6819SAndreas Gohr        $header .= pack('V', $len); // uncompressed size
7972b6c6819SAndreas Gohr        $header .= pack('v', strlen($name)); // file name length
798*36113441SAndreas Gohr        $header .= pack('v', strlen($extra)); // extra field length
7992b6c6819SAndreas Gohr        $header .= pack('v', 0); // file comment length
8002b6c6819SAndreas Gohr        $header .= pack('v', 0); // disk number start
8012b6c6819SAndreas Gohr        $header .= pack('v', 0); // internal file attributes
8022b6c6819SAndreas Gohr        $header .= pack('V', 0); // external file attributes  @todo was 0x32!?
8032b6c6819SAndreas Gohr        $header .= pack('V', $offset); // relative offset of local header
8042b6c6819SAndreas Gohr        $header .= $name; // file name
805*36113441SAndreas Gohr        $header .= $extra; // extra (utf-8 filename)
8062b6c6819SAndreas Gohr
8072b6c6819SAndreas Gohr        return $header;
8082b6c6819SAndreas Gohr    }
8092b6c6819SAndreas Gohr
8102b6c6819SAndreas Gohr    /**
8112b6c6819SAndreas Gohr     * Returns a local file header for the given data
8122b6c6819SAndreas Gohr     *
8132b6c6819SAndreas Gohr     * @param int $ts unix timestamp
8142b6c6819SAndreas Gohr     * @param int $crc CRC32 checksum of the uncompressed data
8152b6c6819SAndreas Gohr     * @param int $len length of the uncompressed data
8162b6c6819SAndreas Gohr     * @param int $clen length of the compressed data
8172b6c6819SAndreas Gohr     * @param string $name file name
8182b6c6819SAndreas Gohr     * @param boolean|null $comp if compression is used, if null it's determined from $len != $clen
8192b6c6819SAndreas Gohr     * @return string
8202b6c6819SAndreas Gohr     */
8212b6c6819SAndreas Gohr    protected function makeLocalFileHeader($ts, $crc, $len, $clen, $name, $comp = null)
8222b6c6819SAndreas Gohr    {
8232b6c6819SAndreas Gohr        if(is_null($comp)) $comp = $len != $clen;
8242b6c6819SAndreas Gohr        $comp = $comp ? 8 : 0;
8252b6c6819SAndreas Gohr        $dtime = dechex($this->makeDosTime($ts));
8262b6c6819SAndreas Gohr
827*36113441SAndreas Gohr        list($name, $extra) = $this->encodeFilename($name);
828*36113441SAndreas Gohr
8292b6c6819SAndreas Gohr        $header = "\x50\x4b\x03\x04"; //  local file header signature
8302b6c6819SAndreas Gohr        $header .= pack('v', 20); // version needed to extract - 2.0
8312b6c6819SAndreas Gohr        $header .= pack('v', 0); // general purpose flag - no flags set
8322b6c6819SAndreas Gohr        $header .= pack('v', $comp); // compression method - deflate|none
8332b6c6819SAndreas Gohr        $header .= pack(
8342b6c6819SAndreas Gohr            'H*',
8352b6c6819SAndreas Gohr            $dtime[6] . $dtime[7] .
8362b6c6819SAndreas Gohr            $dtime[4] . $dtime[5] .
8372b6c6819SAndreas Gohr            $dtime[2] . $dtime[3] .
8382b6c6819SAndreas Gohr            $dtime[0] . $dtime[1]
8392b6c6819SAndreas Gohr        ); //  last mod file time and date
8402b6c6819SAndreas Gohr        $header .= pack('V', $crc); // crc-32
8412b6c6819SAndreas Gohr        $header .= pack('V', $clen); // compressed size
8422b6c6819SAndreas Gohr        $header .= pack('V', $len); // uncompressed size
8432b6c6819SAndreas Gohr        $header .= pack('v', strlen($name)); // file name length
844*36113441SAndreas Gohr        $header .= pack('v', strlen($extra)); // extra field length
845*36113441SAndreas Gohr        $header .= $name; // file name
846*36113441SAndreas Gohr        $header .= $extra; // extra (utf-8 filename)
8472b6c6819SAndreas Gohr        return $header;
8482b6c6819SAndreas Gohr    }
849*36113441SAndreas Gohr
850*36113441SAndreas Gohr    /**
851*36113441SAndreas Gohr     * Returns an allowed filename and an extra field header
852*36113441SAndreas Gohr     *
853*36113441SAndreas Gohr     * When encoding stuff outside the 7bit ASCII range it needs to be placed in a separate
854*36113441SAndreas Gohr     * extra field
855*36113441SAndreas Gohr     *
856*36113441SAndreas Gohr     * @param $original
857*36113441SAndreas Gohr     * @return array($filename, $extra)
858*36113441SAndreas Gohr     */
859*36113441SAndreas Gohr    protected function encodeFilename($original)
860*36113441SAndreas Gohr    {
861*36113441SAndreas Gohr        $cp437 = $this->utf8ToCp($original);
862*36113441SAndreas Gohr        if ($cp437 === $original) {
863*36113441SAndreas Gohr            return array($original, '');
864*36113441SAndreas Gohr        }
865*36113441SAndreas Gohr
866*36113441SAndreas Gohr        $extra = pack(
867*36113441SAndreas Gohr            'vvCV',
868*36113441SAndreas Gohr            0x7075, // tag
869*36113441SAndreas Gohr            strlen($original) + 5, // length of file + version + crc
870*36113441SAndreas Gohr            1, // version
871*36113441SAndreas Gohr            crc32($original) // crc
872*36113441SAndreas Gohr        );
873*36113441SAndreas Gohr        $extra .= $original;
874*36113441SAndreas Gohr
875*36113441SAndreas Gohr        return array($cp437, $extra);
876*36113441SAndreas Gohr    }
877605f8e8dSAndreas Gohr}
878