xref: /dokuwiki/vendor/splitbrain/php-archive/src/Zip.php (revision a3bfbb3c10892fbcc5149af0165d186e5fa0c6cc)
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
37e43cd7e1SAndreas Gohr     * @throws ArchiveIllegalCompressionException
38605f8e8dSAndreas Gohr     */
39605f8e8dSAndreas Gohr    public function setCompression($level = 9, $type = Archive::COMPRESS_AUTO)
40605f8e8dSAndreas Gohr    {
41e43cd7e1SAndreas Gohr        if ($level < -1 || $level > 9) {
42e43cd7e1SAndreas Gohr            throw new ArchiveIllegalCompressionException('Compression level should be between -1 and 9');
43e43cd7e1SAndreas Gohr        }
44605f8e8dSAndreas Gohr        $this->complevel = $level;
45605f8e8dSAndreas Gohr    }
46605f8e8dSAndreas Gohr
47605f8e8dSAndreas Gohr    /**
48605f8e8dSAndreas Gohr     * Open an existing ZIP file for reading
49605f8e8dSAndreas Gohr     *
50605f8e8dSAndreas Gohr     * @param string $file
51605f8e8dSAndreas Gohr     * @throws ArchiveIOException
52605f8e8dSAndreas Gohr     */
53605f8e8dSAndreas Gohr    public function open($file)
54605f8e8dSAndreas Gohr    {
55605f8e8dSAndreas Gohr        $this->file = $file;
56605f8e8dSAndreas Gohr        $this->fh   = @fopen($this->file, 'rb');
57605f8e8dSAndreas Gohr        if (!$this->fh) {
58605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not open file for reading: '.$this->file);
59605f8e8dSAndreas Gohr        }
60605f8e8dSAndreas Gohr        $this->closed = false;
61605f8e8dSAndreas Gohr    }
62605f8e8dSAndreas Gohr
63605f8e8dSAndreas Gohr    /**
64605f8e8dSAndreas Gohr     * Read the contents of a ZIP archive
65605f8e8dSAndreas Gohr     *
66605f8e8dSAndreas Gohr     * This function lists the files stored in the archive, and returns an indexed array of FileInfo objects
67605f8e8dSAndreas Gohr     *
68605f8e8dSAndreas Gohr     * The archive is closed afer reading the contents, for API compatibility with TAR files
69605f8e8dSAndreas Gohr     * Reopen the file with open() again if you want to do additional operations
70605f8e8dSAndreas Gohr     *
71605f8e8dSAndreas Gohr     * @throws ArchiveIOException
72605f8e8dSAndreas Gohr     * @return FileInfo[]
73605f8e8dSAndreas Gohr     */
74605f8e8dSAndreas Gohr    public function contents()
75605f8e8dSAndreas Gohr    {
76605f8e8dSAndreas Gohr        if ($this->closed || !$this->file) {
77605f8e8dSAndreas Gohr            throw new ArchiveIOException('Can not read from a closed archive');
78605f8e8dSAndreas Gohr        }
79605f8e8dSAndreas Gohr
80605f8e8dSAndreas Gohr        $result = array();
81605f8e8dSAndreas Gohr
82605f8e8dSAndreas Gohr        $centd = $this->readCentralDir();
83605f8e8dSAndreas Gohr
84605f8e8dSAndreas Gohr        @rewind($this->fh);
85605f8e8dSAndreas Gohr        @fseek($this->fh, $centd['offset']);
86605f8e8dSAndreas Gohr
87605f8e8dSAndreas Gohr        for ($i = 0; $i < $centd['entries']; $i++) {
88605f8e8dSAndreas Gohr            $result[] = $this->header2fileinfo($this->readCentralFileHeader());
89605f8e8dSAndreas Gohr        }
90605f8e8dSAndreas Gohr
91605f8e8dSAndreas Gohr        $this->close();
92605f8e8dSAndreas Gohr        return $result;
93605f8e8dSAndreas Gohr    }
94605f8e8dSAndreas Gohr
95605f8e8dSAndreas Gohr    /**
96605f8e8dSAndreas Gohr     * Extract an existing ZIP archive
97605f8e8dSAndreas Gohr     *
98605f8e8dSAndreas Gohr     * The $strip parameter allows you to strip a certain number of path components from the filenames
99605f8e8dSAndreas Gohr     * found in the tar file, similar to the --strip-components feature of GNU tar. This is triggered when
100605f8e8dSAndreas Gohr     * an integer is passed as $strip.
101605f8e8dSAndreas Gohr     * Alternatively a fixed string prefix may be passed in $strip. If the filename matches this prefix,
102605f8e8dSAndreas Gohr     * the prefix will be stripped. It is recommended to give prefixes with a trailing slash.
103605f8e8dSAndreas Gohr     *
104605f8e8dSAndreas Gohr     * By default this will extract all files found in the archive. You can restrict the output using the $include
105605f8e8dSAndreas Gohr     * and $exclude parameter. Both expect a full regular expression (including delimiters and modifiers). If
106605f8e8dSAndreas Gohr     * $include is set only files that match this expression will be extracted. Files that match the $exclude
107605f8e8dSAndreas Gohr     * expression will never be extracted. Both parameters can be used in combination. Expressions are matched against
108605f8e8dSAndreas Gohr     * stripped filenames as described above.
109605f8e8dSAndreas Gohr     *
110605f8e8dSAndreas Gohr     * @param string     $outdir  the target directory for extracting
111605f8e8dSAndreas Gohr     * @param int|string $strip   either the number of path components or a fixed prefix to strip
112605f8e8dSAndreas Gohr     * @param string     $exclude a regular expression of files to exclude
113605f8e8dSAndreas Gohr     * @param string     $include a regular expression of files to include
114605f8e8dSAndreas Gohr     * @throws ArchiveIOException
115605f8e8dSAndreas Gohr     * @return FileInfo[]
116605f8e8dSAndreas Gohr     */
117ddb94cf0SAndreas Gohr    public function extract($outdir, $strip = '', $exclude = '', $include = '')
118605f8e8dSAndreas Gohr    {
119605f8e8dSAndreas Gohr        if ($this->closed || !$this->file) {
120605f8e8dSAndreas Gohr            throw new ArchiveIOException('Can not read from a closed archive');
121605f8e8dSAndreas Gohr        }
122605f8e8dSAndreas Gohr
123605f8e8dSAndreas Gohr        $outdir = rtrim($outdir, '/');
124605f8e8dSAndreas Gohr        @mkdir($outdir, 0777, true);
125605f8e8dSAndreas Gohr
126605f8e8dSAndreas Gohr        $extracted = array();
127605f8e8dSAndreas Gohr
128605f8e8dSAndreas Gohr        $cdir      = $this->readCentralDir();
129605f8e8dSAndreas Gohr        $pos_entry = $cdir['offset']; // begin of the central file directory
130605f8e8dSAndreas Gohr
131605f8e8dSAndreas Gohr        for ($i = 0; $i < $cdir['entries']; $i++) {
132605f8e8dSAndreas Gohr            // read file header
133605f8e8dSAndreas Gohr            @fseek($this->fh, $pos_entry);
134605f8e8dSAndreas Gohr            $header          = $this->readCentralFileHeader();
135605f8e8dSAndreas Gohr            $header['index'] = $i;
136605f8e8dSAndreas Gohr            $pos_entry       = ftell($this->fh); // position of the next file in central file directory
137605f8e8dSAndreas Gohr            fseek($this->fh, $header['offset']); // seek to beginning of file header
138605f8e8dSAndreas Gohr            $header   = $this->readFileHeader($header);
139605f8e8dSAndreas Gohr            $fileinfo = $this->header2fileinfo($header);
140605f8e8dSAndreas Gohr
141605f8e8dSAndreas Gohr            // apply strip rules
142605f8e8dSAndreas Gohr            $fileinfo->strip($strip);
143605f8e8dSAndreas Gohr
144605f8e8dSAndreas Gohr            // skip unwanted files
145*a3bfbb3cSAndreas Gohr            if (!strlen($fileinfo->getPath()) || !$fileinfo->matchExpression($include, $exclude)) {
146605f8e8dSAndreas Gohr                continue;
147605f8e8dSAndreas Gohr            }
148605f8e8dSAndreas Gohr
149605f8e8dSAndreas Gohr            $extracted[] = $fileinfo;
150605f8e8dSAndreas Gohr
151605f8e8dSAndreas Gohr            // create output directory
152605f8e8dSAndreas Gohr            $output    = $outdir.'/'.$fileinfo->getPath();
153605f8e8dSAndreas Gohr            $directory = ($header['folder']) ? $output : dirname($output);
154605f8e8dSAndreas Gohr            @mkdir($directory, 0777, true);
155605f8e8dSAndreas Gohr
156605f8e8dSAndreas Gohr            // nothing more to do for directories
157605f8e8dSAndreas Gohr            if ($fileinfo->getIsdir()) {
158e43cd7e1SAndreas Gohr                if(is_callable($this->callback)) {
159e43cd7e1SAndreas Gohr                    call_user_func($this->callback, $fileinfo);
160e43cd7e1SAndreas Gohr                }
161605f8e8dSAndreas Gohr                continue;
162605f8e8dSAndreas Gohr            }
163605f8e8dSAndreas Gohr
164605f8e8dSAndreas Gohr            // compressed files are written to temporary .gz file first
165605f8e8dSAndreas Gohr            if ($header['compression'] == 0) {
166605f8e8dSAndreas Gohr                $extractto = $output;
167605f8e8dSAndreas Gohr            } else {
168605f8e8dSAndreas Gohr                $extractto = $output.'.gz';
169605f8e8dSAndreas Gohr            }
170605f8e8dSAndreas Gohr
171605f8e8dSAndreas Gohr            // open file for writing
172ddb94cf0SAndreas Gohr            $fp = @fopen($extractto, "wb");
173605f8e8dSAndreas Gohr            if (!$fp) {
174605f8e8dSAndreas Gohr                throw new ArchiveIOException('Could not open file for writing: '.$extractto);
175605f8e8dSAndreas Gohr            }
176605f8e8dSAndreas Gohr
177605f8e8dSAndreas Gohr            // prepend compression header
178605f8e8dSAndreas Gohr            if ($header['compression'] != 0) {
179605f8e8dSAndreas Gohr                $binary_data = pack(
180605f8e8dSAndreas Gohr                    'va1a1Va1a1',
181605f8e8dSAndreas Gohr                    0x8b1f,
182605f8e8dSAndreas Gohr                    chr($header['compression']),
183605f8e8dSAndreas Gohr                    chr(0x00),
184605f8e8dSAndreas Gohr                    time(),
185605f8e8dSAndreas Gohr                    chr(0x00),
186605f8e8dSAndreas Gohr                    chr(3)
187605f8e8dSAndreas Gohr                );
188605f8e8dSAndreas Gohr                fwrite($fp, $binary_data, 10);
189605f8e8dSAndreas Gohr            }
190605f8e8dSAndreas Gohr
191605f8e8dSAndreas Gohr            // read the file and store it on disk
192605f8e8dSAndreas Gohr            $size = $header['compressed_size'];
193605f8e8dSAndreas Gohr            while ($size != 0) {
194605f8e8dSAndreas Gohr                $read_size   = ($size < 2048 ? $size : 2048);
195605f8e8dSAndreas Gohr                $buffer      = fread($this->fh, $read_size);
196605f8e8dSAndreas Gohr                $binary_data = pack('a'.$read_size, $buffer);
197605f8e8dSAndreas Gohr                fwrite($fp, $binary_data, $read_size);
198605f8e8dSAndreas Gohr                $size -= $read_size;
199605f8e8dSAndreas Gohr            }
200605f8e8dSAndreas Gohr
201605f8e8dSAndreas Gohr            // finalize compressed file
202605f8e8dSAndreas Gohr            if ($header['compression'] != 0) {
203605f8e8dSAndreas Gohr                $binary_data = pack('VV', $header['crc'], $header['size']);
204605f8e8dSAndreas Gohr                fwrite($fp, $binary_data, 8);
205605f8e8dSAndreas Gohr            }
206605f8e8dSAndreas Gohr
207605f8e8dSAndreas Gohr            // close file
208605f8e8dSAndreas Gohr            fclose($fp);
209605f8e8dSAndreas Gohr
210605f8e8dSAndreas Gohr            // unpack compressed file
211605f8e8dSAndreas Gohr            if ($header['compression'] != 0) {
212605f8e8dSAndreas Gohr                $gzp = @gzopen($extractto, 'rb');
213605f8e8dSAndreas Gohr                if (!$gzp) {
214605f8e8dSAndreas Gohr                    @unlink($extractto);
215605f8e8dSAndreas Gohr                    throw new ArchiveIOException('Failed file extracting. gzip support missing?');
216605f8e8dSAndreas Gohr                }
217605f8e8dSAndreas Gohr                $fp = @fopen($output, 'wb');
218605f8e8dSAndreas Gohr                if (!$fp) {
219605f8e8dSAndreas Gohr                    throw new ArchiveIOException('Could not open file for writing: '.$extractto);
220605f8e8dSAndreas Gohr                }
221605f8e8dSAndreas Gohr
222605f8e8dSAndreas Gohr                $size = $header['size'];
223605f8e8dSAndreas Gohr                while ($size != 0) {
224605f8e8dSAndreas Gohr                    $read_size   = ($size < 2048 ? $size : 2048);
225605f8e8dSAndreas Gohr                    $buffer      = gzread($gzp, $read_size);
226605f8e8dSAndreas Gohr                    $binary_data = pack('a'.$read_size, $buffer);
227605f8e8dSAndreas Gohr                    @fwrite($fp, $binary_data, $read_size);
228605f8e8dSAndreas Gohr                    $size -= $read_size;
229605f8e8dSAndreas Gohr                }
230605f8e8dSAndreas Gohr                fclose($fp);
231605f8e8dSAndreas Gohr                gzclose($gzp);
2324a690352SAndreas Gohr                unlink($extractto); // remove temporary gz file
233605f8e8dSAndreas Gohr            }
234605f8e8dSAndreas Gohr
235e43cd7e1SAndreas Gohr            @touch($output, $fileinfo->getMtime());
236605f8e8dSAndreas Gohr            //FIXME what about permissions?
237e43cd7e1SAndreas Gohr            if(is_callable($this->callback)) {
238e43cd7e1SAndreas Gohr                call_user_func($this->callback, $fileinfo);
239e43cd7e1SAndreas Gohr            }
240605f8e8dSAndreas Gohr        }
241605f8e8dSAndreas Gohr
242605f8e8dSAndreas Gohr        $this->close();
243605f8e8dSAndreas Gohr        return $extracted;
244605f8e8dSAndreas Gohr    }
245605f8e8dSAndreas Gohr
246605f8e8dSAndreas Gohr    /**
247605f8e8dSAndreas Gohr     * Create a new ZIP file
248605f8e8dSAndreas Gohr     *
249605f8e8dSAndreas Gohr     * If $file is empty, the zip file will be created in memory
250605f8e8dSAndreas Gohr     *
251605f8e8dSAndreas Gohr     * @param string $file
252605f8e8dSAndreas Gohr     * @throws ArchiveIOException
253605f8e8dSAndreas Gohr     */
254605f8e8dSAndreas Gohr    public function create($file = '')
255605f8e8dSAndreas Gohr    {
256605f8e8dSAndreas Gohr        $this->file   = $file;
257605f8e8dSAndreas Gohr        $this->memory = '';
258605f8e8dSAndreas Gohr        $this->fh     = 0;
259605f8e8dSAndreas Gohr
260605f8e8dSAndreas Gohr        if ($this->file) {
261605f8e8dSAndreas Gohr            $this->fh = @fopen($this->file, 'wb');
262605f8e8dSAndreas Gohr
263605f8e8dSAndreas Gohr            if (!$this->fh) {
264605f8e8dSAndreas Gohr                throw new ArchiveIOException('Could not open file for writing: '.$this->file);
265605f8e8dSAndreas Gohr            }
266605f8e8dSAndreas Gohr        }
267605f8e8dSAndreas Gohr        $this->writeaccess = true;
268605f8e8dSAndreas Gohr        $this->closed      = false;
269605f8e8dSAndreas Gohr        $this->ctrl_dir    = array();
270605f8e8dSAndreas Gohr    }
271605f8e8dSAndreas Gohr
272605f8e8dSAndreas Gohr    /**
273605f8e8dSAndreas Gohr     * Add a file to the current ZIP archive using an existing file in the filesystem
274605f8e8dSAndreas Gohr     *
275605f8e8dSAndreas Gohr     * @param string          $file     path to the original file
276605f8e8dSAndreas 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
277605f8e8dSAndreas Gohr     * @throws ArchiveIOException
278605f8e8dSAndreas Gohr     */
279605f8e8dSAndreas Gohr
280605f8e8dSAndreas Gohr    /**
281605f8e8dSAndreas Gohr     * Add a file to the current archive using an existing file in the filesystem
282605f8e8dSAndreas Gohr     *
283605f8e8dSAndreas Gohr     * @param string $file path to the original file
28436113441SAndreas 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
285605f8e8dSAndreas Gohr     * @throws ArchiveIOException
286e43cd7e1SAndreas Gohr     * @throws FileInfoException
287605f8e8dSAndreas Gohr     */
288605f8e8dSAndreas Gohr    public function addFile($file, $fileinfo = '')
289605f8e8dSAndreas Gohr    {
290605f8e8dSAndreas Gohr        if (is_string($fileinfo)) {
291605f8e8dSAndreas Gohr            $fileinfo = FileInfo::fromPath($file, $fileinfo);
292605f8e8dSAndreas Gohr        }
293605f8e8dSAndreas Gohr
294605f8e8dSAndreas Gohr        if ($this->closed) {
295605f8e8dSAndreas Gohr            throw new ArchiveIOException('Archive has been closed, files can no longer be added');
296605f8e8dSAndreas Gohr        }
297605f8e8dSAndreas Gohr
298605f8e8dSAndreas Gohr        $data = @file_get_contents($file);
299605f8e8dSAndreas Gohr        if ($data === false) {
300605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not open file for reading: '.$file);
301605f8e8dSAndreas Gohr        }
302605f8e8dSAndreas Gohr
303605f8e8dSAndreas Gohr        // FIXME could we stream writing compressed data? gzwrite on a fopen handle?
304605f8e8dSAndreas Gohr        $this->addData($fileinfo, $data);
305605f8e8dSAndreas Gohr    }
306605f8e8dSAndreas Gohr
307605f8e8dSAndreas Gohr    /**
30836113441SAndreas Gohr     * Add a file to the current Zip archive using the given $data as content
309605f8e8dSAndreas Gohr     *
310605f8e8dSAndreas Gohr     * @param string|FileInfo $fileinfo either the name to us in archive (string) or a FileInfo oject with all meta data
311605f8e8dSAndreas Gohr     * @param string          $data     binary content of the file to add
312605f8e8dSAndreas Gohr     * @throws ArchiveIOException
313605f8e8dSAndreas Gohr     */
314605f8e8dSAndreas Gohr    public function addData($fileinfo, $data)
315605f8e8dSAndreas Gohr    {
316605f8e8dSAndreas Gohr        if (is_string($fileinfo)) {
317605f8e8dSAndreas Gohr            $fileinfo = new FileInfo($fileinfo);
318605f8e8dSAndreas Gohr        }
319605f8e8dSAndreas Gohr
320605f8e8dSAndreas Gohr        if ($this->closed) {
321605f8e8dSAndreas Gohr            throw new ArchiveIOException('Archive has been closed, files can no longer be added');
322605f8e8dSAndreas Gohr        }
323605f8e8dSAndreas Gohr
3242b6c6819SAndreas Gohr        // prepare info and compress data
325605f8e8dSAndreas Gohr        $size     = strlen($data);
326605f8e8dSAndreas Gohr        $crc      = crc32($data);
327605f8e8dSAndreas Gohr        if ($this->complevel) {
328605f8e8dSAndreas Gohr            $data = gzcompress($data, $this->complevel);
329605f8e8dSAndreas Gohr            $data = substr($data, 2, -4); // strip compression headers
330605f8e8dSAndreas Gohr        }
331605f8e8dSAndreas Gohr        $csize  = strlen($data);
332605f8e8dSAndreas Gohr        $offset = $this->dataOffset();
333605f8e8dSAndreas Gohr        $name   = $fileinfo->getPath();
3342b6c6819SAndreas Gohr        $time   = $fileinfo->getMtime();
3352b6c6819SAndreas Gohr
3362b6c6819SAndreas Gohr        // write local file header
3372b6c6819SAndreas Gohr        $this->writebytes($this->makeLocalFileHeader(
3382b6c6819SAndreas Gohr            $time,
3392b6c6819SAndreas Gohr            $crc,
3402b6c6819SAndreas Gohr            $size,
3412b6c6819SAndreas Gohr            $csize,
3422b6c6819SAndreas Gohr            $name,
3432b6c6819SAndreas Gohr            (bool) $this->complevel
3442b6c6819SAndreas Gohr        ));
3452b6c6819SAndreas Gohr
3462b6c6819SAndreas Gohr        // we store no encryption header
347605f8e8dSAndreas Gohr
348605f8e8dSAndreas Gohr        // write data
3492b6c6819SAndreas Gohr        $this->writebytes($data);
3502b6c6819SAndreas Gohr
3512b6c6819SAndreas Gohr        // we store no data descriptor
352605f8e8dSAndreas Gohr
353605f8e8dSAndreas Gohr        // add info to central file directory
3542b6c6819SAndreas Gohr        $this->ctrl_dir[] = $this->makeCentralFileRecord(
3552b6c6819SAndreas Gohr            $offset,
3562b6c6819SAndreas Gohr            $time,
3572b6c6819SAndreas Gohr            $crc,
3582b6c6819SAndreas Gohr            $size,
3592b6c6819SAndreas Gohr            $csize,
3602b6c6819SAndreas Gohr            $name,
3612b6c6819SAndreas Gohr            (bool) $this->complevel
3622b6c6819SAndreas Gohr        );
363e43cd7e1SAndreas Gohr
364e43cd7e1SAndreas Gohr        if(is_callable($this->callback)) {
365e43cd7e1SAndreas Gohr            call_user_func($this->callback, $fileinfo);
366e43cd7e1SAndreas Gohr        }
367605f8e8dSAndreas Gohr    }
368605f8e8dSAndreas Gohr
369605f8e8dSAndreas Gohr    /**
370605f8e8dSAndreas Gohr     * Add the closing footer to the archive if in write mode, close all file handles
371605f8e8dSAndreas Gohr     *
372605f8e8dSAndreas Gohr     * After a call to this function no more data can be added to the archive, for
373605f8e8dSAndreas Gohr     * read access no reading is allowed anymore
374e43cd7e1SAndreas Gohr     * @throws ArchiveIOException
375605f8e8dSAndreas Gohr     */
376605f8e8dSAndreas Gohr    public function close()
377605f8e8dSAndreas Gohr    {
378605f8e8dSAndreas Gohr        if ($this->closed) {
379605f8e8dSAndreas Gohr            return;
380605f8e8dSAndreas Gohr        } // we did this already
381605f8e8dSAndreas Gohr
382605f8e8dSAndreas Gohr        if ($this->writeaccess) {
3832b6c6819SAndreas Gohr            // write central directory
384605f8e8dSAndreas Gohr            $offset = $this->dataOffset();
385605f8e8dSAndreas Gohr            $ctrldir = join('', $this->ctrl_dir);
386605f8e8dSAndreas Gohr            $this->writebytes($ctrldir);
3872b6c6819SAndreas Gohr
3882b6c6819SAndreas Gohr            // write end of central directory record
3892b6c6819SAndreas Gohr            $this->writebytes("\x50\x4b\x05\x06"); // end of central dir signature
3902b6c6819SAndreas Gohr            $this->writebytes(pack('v', 0)); // number of this disk
3912b6c6819SAndreas Gohr            $this->writebytes(pack('v', 0)); // number of the disk with the start of the central directory
3922b6c6819SAndreas Gohr            $this->writebytes(pack('v',
3932b6c6819SAndreas Gohr                count($this->ctrl_dir))); // total number of entries in the central directory on this disk
3942b6c6819SAndreas Gohr            $this->writebytes(pack('v', count($this->ctrl_dir))); // total number of entries in the central directory
3952b6c6819SAndreas Gohr            $this->writebytes(pack('V', strlen($ctrldir))); // size of the central directory
3962b6c6819SAndreas Gohr            $this->writebytes(pack('V',
3972b6c6819SAndreas Gohr                $offset)); // offset of start of central directory with respect to the starting disk number
3982b6c6819SAndreas Gohr            $this->writebytes(pack('v', 0)); // .ZIP file comment length
3992b6c6819SAndreas Gohr
400605f8e8dSAndreas Gohr            $this->ctrl_dir = array();
401605f8e8dSAndreas Gohr        }
402605f8e8dSAndreas Gohr
403605f8e8dSAndreas Gohr        // close file handles
404605f8e8dSAndreas Gohr        if ($this->file) {
405605f8e8dSAndreas Gohr            fclose($this->fh);
406605f8e8dSAndreas Gohr            $this->file = '';
407605f8e8dSAndreas Gohr            $this->fh   = 0;
408605f8e8dSAndreas Gohr        }
409605f8e8dSAndreas Gohr
410605f8e8dSAndreas Gohr        $this->writeaccess = false;
411605f8e8dSAndreas Gohr        $this->closed      = true;
412605f8e8dSAndreas Gohr    }
413605f8e8dSAndreas Gohr
414605f8e8dSAndreas Gohr    /**
415605f8e8dSAndreas Gohr     * Returns the created in-memory archive data
416605f8e8dSAndreas Gohr     *
417605f8e8dSAndreas Gohr     * This implicitly calls close() on the Archive
418e43cd7e1SAndreas Gohr     * @throws ArchiveIOException
419605f8e8dSAndreas Gohr     */
420605f8e8dSAndreas Gohr    public function getArchive()
421605f8e8dSAndreas Gohr    {
422605f8e8dSAndreas Gohr        $this->close();
423605f8e8dSAndreas Gohr
424605f8e8dSAndreas Gohr        return $this->memory;
425605f8e8dSAndreas Gohr    }
426605f8e8dSAndreas Gohr
427605f8e8dSAndreas Gohr    /**
428605f8e8dSAndreas Gohr     * Save the created in-memory archive data
429605f8e8dSAndreas Gohr     *
430605f8e8dSAndreas Gohr     * Note: It's more memory effective to specify the filename in the create() function and
431605f8e8dSAndreas Gohr     * let the library work on the new file directly.
432605f8e8dSAndreas Gohr     *
433605f8e8dSAndreas Gohr     * @param     $file
434605f8e8dSAndreas Gohr     * @throws ArchiveIOException
435605f8e8dSAndreas Gohr     */
436605f8e8dSAndreas Gohr    public function save($file)
437605f8e8dSAndreas Gohr    {
438ddb94cf0SAndreas Gohr        if (!@file_put_contents($file, $this->getArchive())) {
439605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not write to file: '.$file);
440605f8e8dSAndreas Gohr        }
441605f8e8dSAndreas Gohr    }
442605f8e8dSAndreas Gohr
443605f8e8dSAndreas Gohr    /**
444605f8e8dSAndreas Gohr     * Read the central directory
445605f8e8dSAndreas Gohr     *
446605f8e8dSAndreas Gohr     * This key-value list contains general information about the ZIP file
447605f8e8dSAndreas Gohr     *
448605f8e8dSAndreas Gohr     * @return array
449605f8e8dSAndreas Gohr     */
450605f8e8dSAndreas Gohr    protected function readCentralDir()
451605f8e8dSAndreas Gohr    {
452605f8e8dSAndreas Gohr        $size = filesize($this->file);
453605f8e8dSAndreas Gohr        if ($size < 277) {
454605f8e8dSAndreas Gohr            $maximum_size = $size;
455605f8e8dSAndreas Gohr        } else {
456605f8e8dSAndreas Gohr            $maximum_size = 277;
457605f8e8dSAndreas Gohr        }
458605f8e8dSAndreas Gohr
459605f8e8dSAndreas Gohr        @fseek($this->fh, $size - $maximum_size);
460605f8e8dSAndreas Gohr        $pos   = ftell($this->fh);
461605f8e8dSAndreas Gohr        $bytes = 0x00000000;
462605f8e8dSAndreas Gohr
463605f8e8dSAndreas Gohr        while ($pos < $size) {
464605f8e8dSAndreas Gohr            $byte  = @fread($this->fh, 1);
465605f8e8dSAndreas Gohr            $bytes = (($bytes << 8) & 0xFFFFFFFF) | ord($byte);
466605f8e8dSAndreas Gohr            if ($bytes == 0x504b0506) {
467605f8e8dSAndreas Gohr                break;
468605f8e8dSAndreas Gohr            }
469605f8e8dSAndreas Gohr            $pos++;
470605f8e8dSAndreas Gohr        }
471605f8e8dSAndreas Gohr
472605f8e8dSAndreas Gohr        $data = unpack(
473605f8e8dSAndreas Gohr            'vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size',
474605f8e8dSAndreas Gohr            fread($this->fh, 18)
475605f8e8dSAndreas Gohr        );
476605f8e8dSAndreas Gohr
477605f8e8dSAndreas Gohr        if ($data['comment_size'] != 0) {
478605f8e8dSAndreas Gohr            $centd['comment'] = fread($this->fh, $data['comment_size']);
479605f8e8dSAndreas Gohr        } else {
480605f8e8dSAndreas Gohr            $centd['comment'] = '';
481605f8e8dSAndreas Gohr        }
482605f8e8dSAndreas Gohr        $centd['entries']      = $data['entries'];
483605f8e8dSAndreas Gohr        $centd['disk_entries'] = $data['disk_entries'];
484605f8e8dSAndreas Gohr        $centd['offset']       = $data['offset'];
485605f8e8dSAndreas Gohr        $centd['disk_start']   = $data['disk_start'];
486605f8e8dSAndreas Gohr        $centd['size']         = $data['size'];
487605f8e8dSAndreas Gohr        $centd['disk']         = $data['disk'];
488605f8e8dSAndreas Gohr        return $centd;
489605f8e8dSAndreas Gohr    }
490605f8e8dSAndreas Gohr
491605f8e8dSAndreas Gohr    /**
492605f8e8dSAndreas Gohr     * Read the next central file header
493605f8e8dSAndreas Gohr     *
494605f8e8dSAndreas Gohr     * Assumes the current file pointer is pointing at the right position
495605f8e8dSAndreas Gohr     *
496605f8e8dSAndreas Gohr     * @return array
497605f8e8dSAndreas Gohr     */
498605f8e8dSAndreas Gohr    protected function readCentralFileHeader()
499605f8e8dSAndreas Gohr    {
500605f8e8dSAndreas Gohr        $binary_data = fread($this->fh, 46);
501605f8e8dSAndreas Gohr        $header      = unpack(
502605f8e8dSAndreas Gohr            'vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset',
503605f8e8dSAndreas Gohr            $binary_data
504605f8e8dSAndreas Gohr        );
505605f8e8dSAndreas Gohr
506605f8e8dSAndreas Gohr        if ($header['filename_len'] != 0) {
507605f8e8dSAndreas Gohr            $header['filename'] = fread($this->fh, $header['filename_len']);
508605f8e8dSAndreas Gohr        } else {
509605f8e8dSAndreas Gohr            $header['filename'] = '';
510605f8e8dSAndreas Gohr        }
511605f8e8dSAndreas Gohr
512605f8e8dSAndreas Gohr        if ($header['extra_len'] != 0) {
513605f8e8dSAndreas Gohr            $header['extra'] = fread($this->fh, $header['extra_len']);
51436113441SAndreas Gohr            $header['extradata'] = $this->parseExtra($header['extra']);
515605f8e8dSAndreas Gohr        } else {
516605f8e8dSAndreas Gohr            $header['extra'] = '';
51736113441SAndreas Gohr            $header['extradata'] = array();
518605f8e8dSAndreas Gohr        }
519605f8e8dSAndreas Gohr
520605f8e8dSAndreas Gohr        if ($header['comment_len'] != 0) {
521605f8e8dSAndreas Gohr            $header['comment'] = fread($this->fh, $header['comment_len']);
522605f8e8dSAndreas Gohr        } else {
523605f8e8dSAndreas Gohr            $header['comment'] = '';
524605f8e8dSAndreas Gohr        }
525605f8e8dSAndreas Gohr
5262b6c6819SAndreas Gohr        $header['mtime']           = $this->makeUnixTime($header['mdate'], $header['mtime']);
527605f8e8dSAndreas Gohr        $header['stored_filename'] = $header['filename'];
528605f8e8dSAndreas Gohr        $header['status']          = 'ok';
529605f8e8dSAndreas Gohr        if (substr($header['filename'], -1) == '/') {
530605f8e8dSAndreas Gohr            $header['external'] = 0x41FF0010;
531605f8e8dSAndreas Gohr        }
532605f8e8dSAndreas Gohr        $header['folder'] = ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0;
533605f8e8dSAndreas Gohr
534605f8e8dSAndreas Gohr        return $header;
535605f8e8dSAndreas Gohr    }
536605f8e8dSAndreas Gohr
537605f8e8dSAndreas Gohr    /**
538605f8e8dSAndreas Gohr     * Reads the local file header
539605f8e8dSAndreas Gohr     *
540605f8e8dSAndreas Gohr     * This header precedes each individual file inside the zip file. Assumes the current file pointer is pointing at
5412b6c6819SAndreas Gohr     * the right position already. Enhances the given central header with the data found at the local header.
542605f8e8dSAndreas Gohr     *
543605f8e8dSAndreas Gohr     * @param array $header the central file header read previously (see above)
544605f8e8dSAndreas Gohr     * @return array
545605f8e8dSAndreas Gohr     */
5462b6c6819SAndreas Gohr    protected function readFileHeader($header)
547605f8e8dSAndreas Gohr    {
548605f8e8dSAndreas Gohr        $binary_data = fread($this->fh, 30);
549605f8e8dSAndreas Gohr        $data        = unpack(
550605f8e8dSAndreas Gohr            'vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len',
551605f8e8dSAndreas Gohr            $binary_data
552605f8e8dSAndreas Gohr        );
553605f8e8dSAndreas Gohr
554605f8e8dSAndreas Gohr        $header['filename'] = fread($this->fh, $data['filename_len']);
555605f8e8dSAndreas Gohr        if ($data['extra_len'] != 0) {
556605f8e8dSAndreas Gohr            $header['extra'] = fread($this->fh, $data['extra_len']);
55736113441SAndreas Gohr            $header['extradata'] = array_merge($header['extradata'],  $this->parseExtra($header['extra']));
558605f8e8dSAndreas Gohr        } else {
559605f8e8dSAndreas Gohr            $header['extra'] = '';
56036113441SAndreas Gohr            $header['extradata'] = array();
561605f8e8dSAndreas Gohr        }
562605f8e8dSAndreas Gohr
563605f8e8dSAndreas Gohr        $header['compression'] = $data['compression'];
564605f8e8dSAndreas Gohr        foreach (array(
565605f8e8dSAndreas Gohr                     'size',
566605f8e8dSAndreas Gohr                     'compressed_size',
567605f8e8dSAndreas Gohr                     'crc'
568605f8e8dSAndreas Gohr                 ) as $hd) { // On ODT files, these headers are 0. Keep the previous value.
569605f8e8dSAndreas Gohr            if ($data[$hd] != 0) {
570605f8e8dSAndreas Gohr                $header[$hd] = $data[$hd];
571605f8e8dSAndreas Gohr            }
572605f8e8dSAndreas Gohr        }
573605f8e8dSAndreas Gohr        $header['flag']  = $data['flag'];
5742b6c6819SAndreas Gohr        $header['mtime'] = $this->makeUnixTime($data['mdate'], $data['mtime']);
575605f8e8dSAndreas Gohr
576605f8e8dSAndreas Gohr        $header['stored_filename'] = $header['filename'];
577605f8e8dSAndreas Gohr        $header['status']          = "ok";
578605f8e8dSAndreas Gohr        $header['folder']          = ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0;
579605f8e8dSAndreas Gohr        return $header;
580605f8e8dSAndreas Gohr    }
581605f8e8dSAndreas Gohr
582605f8e8dSAndreas Gohr    /**
58336113441SAndreas Gohr     * Parse the extra headers into fields
58436113441SAndreas Gohr     *
58536113441SAndreas Gohr     * @param string $header
58636113441SAndreas Gohr     * @return array
58736113441SAndreas Gohr     */
58836113441SAndreas Gohr    protected function parseExtra($header)
58936113441SAndreas Gohr    {
59036113441SAndreas Gohr        $extra = array();
59136113441SAndreas Gohr        // parse all extra fields as raw values
59236113441SAndreas Gohr        while (strlen($header) !== 0) {
59336113441SAndreas Gohr            $set = unpack('vid/vlen', $header);
59436113441SAndreas Gohr            $header = substr($header, 4);
59536113441SAndreas Gohr            $value = substr($header, 0, $set['len']);
59636113441SAndreas Gohr            $header = substr($header, $set['len']);
59736113441SAndreas Gohr            $extra[$set['id']] = $value;
59836113441SAndreas Gohr        }
59936113441SAndreas Gohr
60036113441SAndreas Gohr        // handle known ones
60136113441SAndreas Gohr        if(isset($extra[0x6375])) {
60236113441SAndreas Gohr            $extra['utf8comment'] = substr($extra[0x7075], 5); // strip version and crc
60336113441SAndreas Gohr        }
60436113441SAndreas Gohr        if(isset($extra[0x7075])) {
60536113441SAndreas Gohr            $extra['utf8path'] = substr($extra[0x7075], 5); // strip version and crc
60636113441SAndreas Gohr        }
60736113441SAndreas Gohr
60836113441SAndreas Gohr        return $extra;
60936113441SAndreas Gohr    }
61036113441SAndreas Gohr
61136113441SAndreas Gohr    /**
612605f8e8dSAndreas Gohr     * Create fileinfo object from header data
613605f8e8dSAndreas Gohr     *
614605f8e8dSAndreas Gohr     * @param $header
615605f8e8dSAndreas Gohr     * @return FileInfo
616605f8e8dSAndreas Gohr     */
617605f8e8dSAndreas Gohr    protected function header2fileinfo($header)
618605f8e8dSAndreas Gohr    {
619605f8e8dSAndreas Gohr        $fileinfo = new FileInfo();
620605f8e8dSAndreas Gohr        $fileinfo->setSize($header['size']);
621605f8e8dSAndreas Gohr        $fileinfo->setCompressedSize($header['compressed_size']);
622605f8e8dSAndreas Gohr        $fileinfo->setMtime($header['mtime']);
623605f8e8dSAndreas Gohr        $fileinfo->setComment($header['comment']);
624605f8e8dSAndreas Gohr        $fileinfo->setIsdir($header['external'] == 0x41FF0010 || $header['external'] == 16);
62536113441SAndreas Gohr
62636113441SAndreas Gohr        if(isset($header['extradata']['utf8path'])) {
62736113441SAndreas Gohr            $fileinfo->setPath($header['extradata']['utf8path']);
62836113441SAndreas Gohr        } else {
62936113441SAndreas Gohr            $fileinfo->setPath($this->cpToUtf8($header['filename']));
63036113441SAndreas Gohr        }
63136113441SAndreas Gohr
63236113441SAndreas Gohr        if(isset($header['extradata']['utf8comment'])) {
63336113441SAndreas Gohr            $fileinfo->setComment($header['extradata']['utf8comment']);
63436113441SAndreas Gohr        } else {
63536113441SAndreas Gohr            $fileinfo->setComment($this->cpToUtf8($header['comment']));
63636113441SAndreas Gohr        }
63736113441SAndreas Gohr
638605f8e8dSAndreas Gohr        return $fileinfo;
639605f8e8dSAndreas Gohr    }
640605f8e8dSAndreas Gohr
641605f8e8dSAndreas Gohr    /**
64236113441SAndreas Gohr     * Convert the given CP437 encoded string to UTF-8
64336113441SAndreas Gohr     *
64436113441SAndreas Gohr     * Tries iconv with the correct encoding first, falls back to mbstring with CP850 which is
64536113441SAndreas Gohr     * similar enough. CP437 seems not to be available in mbstring. Lastly falls back to keeping the
64636113441SAndreas Gohr     * string as is, which is still better than nothing.
64736113441SAndreas Gohr     *
648ddb94cf0SAndreas Gohr     * On some systems iconv is available, but the codepage is not. We also check for that.
649ddb94cf0SAndreas Gohr     *
65036113441SAndreas Gohr     * @param $string
65136113441SAndreas Gohr     * @return string
65236113441SAndreas Gohr     */
65336113441SAndreas Gohr    protected function cpToUtf8($string)
65436113441SAndreas Gohr    {
655ddb94cf0SAndreas Gohr        if (function_exists('iconv') && @iconv_strlen('', 'CP437') !== false) {
65636113441SAndreas Gohr            return iconv('CP437', 'UTF-8', $string);
65736113441SAndreas Gohr        } elseif (function_exists('mb_convert_encoding')) {
65836113441SAndreas Gohr            return mb_convert_encoding($string, 'UTF-8', 'CP850');
65936113441SAndreas Gohr        } else {
66036113441SAndreas Gohr            return $string;
66136113441SAndreas Gohr        }
66236113441SAndreas Gohr    }
66336113441SAndreas Gohr
66436113441SAndreas Gohr    /**
66536113441SAndreas Gohr     * Convert the given UTF-8 encoded string to CP437
66636113441SAndreas Gohr     *
66736113441SAndreas Gohr     * Same caveats as for cpToUtf8() apply
66836113441SAndreas Gohr     *
66936113441SAndreas Gohr     * @param $string
67036113441SAndreas Gohr     * @return string
67136113441SAndreas Gohr     */
67236113441SAndreas Gohr    protected function utf8ToCp($string)
67336113441SAndreas Gohr    {
67436113441SAndreas Gohr        // try iconv first
67536113441SAndreas Gohr        if (function_exists('iconv')) {
67636113441SAndreas Gohr            $conv = @iconv('UTF-8', 'CP437//IGNORE', $string);
67736113441SAndreas Gohr            if($conv) return $conv; // it worked
67836113441SAndreas Gohr        }
67936113441SAndreas Gohr
68036113441SAndreas Gohr        // still here? iconv failed to convert the string. Try another method
68136113441SAndreas Gohr        // see http://php.net/manual/en/function.iconv.php#108643
68236113441SAndreas Gohr
68336113441SAndreas Gohr        if (function_exists('mb_convert_encoding')) {
68436113441SAndreas Gohr            return mb_convert_encoding($string, 'CP850', 'UTF-8');
68536113441SAndreas Gohr        } else {
68636113441SAndreas Gohr            return $string;
68736113441SAndreas Gohr        }
68836113441SAndreas Gohr    }
68936113441SAndreas Gohr
69036113441SAndreas Gohr
69136113441SAndreas Gohr    /**
692605f8e8dSAndreas Gohr     * Write to the open filepointer or memory
693605f8e8dSAndreas Gohr     *
694605f8e8dSAndreas Gohr     * @param string $data
695605f8e8dSAndreas Gohr     * @throws ArchiveIOException
696605f8e8dSAndreas Gohr     * @return int number of bytes written
697605f8e8dSAndreas Gohr     */
698605f8e8dSAndreas Gohr    protected function writebytes($data)
699605f8e8dSAndreas Gohr    {
700605f8e8dSAndreas Gohr        if (!$this->file) {
701605f8e8dSAndreas Gohr            $this->memory .= $data;
702605f8e8dSAndreas Gohr            $written = strlen($data);
703605f8e8dSAndreas Gohr        } else {
704605f8e8dSAndreas Gohr            $written = @fwrite($this->fh, $data);
705605f8e8dSAndreas Gohr        }
706605f8e8dSAndreas Gohr        if ($written === false) {
707605f8e8dSAndreas Gohr            throw new ArchiveIOException('Failed to write to archive stream');
708605f8e8dSAndreas Gohr        }
709605f8e8dSAndreas Gohr        return $written;
710605f8e8dSAndreas Gohr    }
711605f8e8dSAndreas Gohr
712605f8e8dSAndreas Gohr    /**
713605f8e8dSAndreas Gohr     * Current data pointer position
714605f8e8dSAndreas Gohr     *
715605f8e8dSAndreas Gohr     * @fixme might need a -1
716605f8e8dSAndreas Gohr     * @return int
717605f8e8dSAndreas Gohr     */
718605f8e8dSAndreas Gohr    protected function dataOffset()
719605f8e8dSAndreas Gohr    {
720605f8e8dSAndreas Gohr        if ($this->file) {
721605f8e8dSAndreas Gohr            return ftell($this->fh);
722605f8e8dSAndreas Gohr        } else {
723605f8e8dSAndreas Gohr            return strlen($this->memory);
724605f8e8dSAndreas Gohr        }
725605f8e8dSAndreas Gohr    }
726605f8e8dSAndreas Gohr
727605f8e8dSAndreas Gohr    /**
728605f8e8dSAndreas Gohr     * Create a DOS timestamp from a UNIX timestamp
729605f8e8dSAndreas Gohr     *
730605f8e8dSAndreas Gohr     * DOS timestamps start at 1980-01-01, earlier UNIX stamps will be set to this date
731605f8e8dSAndreas Gohr     *
732605f8e8dSAndreas Gohr     * @param $time
733605f8e8dSAndreas Gohr     * @return int
734605f8e8dSAndreas Gohr     */
735605f8e8dSAndreas Gohr    protected function makeDosTime($time)
736605f8e8dSAndreas Gohr    {
737605f8e8dSAndreas Gohr        $timearray = getdate($time);
738605f8e8dSAndreas Gohr        if ($timearray['year'] < 1980) {
739605f8e8dSAndreas Gohr            $timearray['year']    = 1980;
740605f8e8dSAndreas Gohr            $timearray['mon']     = 1;
741605f8e8dSAndreas Gohr            $timearray['mday']    = 1;
742605f8e8dSAndreas Gohr            $timearray['hours']   = 0;
743605f8e8dSAndreas Gohr            $timearray['minutes'] = 0;
744605f8e8dSAndreas Gohr            $timearray['seconds'] = 0;
745605f8e8dSAndreas Gohr        }
746605f8e8dSAndreas Gohr        return (($timearray['year'] - 1980) << 25) |
747605f8e8dSAndreas Gohr        ($timearray['mon'] << 21) |
748605f8e8dSAndreas Gohr        ($timearray['mday'] << 16) |
749605f8e8dSAndreas Gohr        ($timearray['hours'] << 11) |
750605f8e8dSAndreas Gohr        ($timearray['minutes'] << 5) |
751605f8e8dSAndreas Gohr        ($timearray['seconds'] >> 1);
752605f8e8dSAndreas Gohr    }
753605f8e8dSAndreas Gohr
7542b6c6819SAndreas Gohr    /**
7552b6c6819SAndreas Gohr     * Create a UNIX timestamp from a DOS timestamp
7562b6c6819SAndreas Gohr     *
7572b6c6819SAndreas Gohr     * @param $mdate
7582b6c6819SAndreas Gohr     * @param $mtime
7592b6c6819SAndreas Gohr     * @return int
7602b6c6819SAndreas Gohr     */
7612b6c6819SAndreas Gohr    protected function makeUnixTime($mdate = null, $mtime = null)
7622b6c6819SAndreas Gohr    {
7632b6c6819SAndreas Gohr        if ($mdate && $mtime) {
7642b6c6819SAndreas Gohr            $year = (($mdate & 0xFE00) >> 9) + 1980;
7652b6c6819SAndreas Gohr            $month = ($mdate & 0x01E0) >> 5;
7662b6c6819SAndreas Gohr            $day = $mdate & 0x001F;
7672b6c6819SAndreas Gohr
7682b6c6819SAndreas Gohr            $hour = ($mtime & 0xF800) >> 11;
7692b6c6819SAndreas Gohr            $minute = ($mtime & 0x07E0) >> 5;
7702b6c6819SAndreas Gohr            $seconde = ($mtime & 0x001F) << 1;
7712b6c6819SAndreas Gohr
7722b6c6819SAndreas Gohr            $mtime = mktime($hour, $minute, $seconde, $month, $day, $year);
7732b6c6819SAndreas Gohr        } else {
7742b6c6819SAndreas Gohr            $mtime = time();
7752b6c6819SAndreas Gohr        }
7762b6c6819SAndreas Gohr
7772b6c6819SAndreas Gohr        return $mtime;
7782b6c6819SAndreas Gohr    }
7792b6c6819SAndreas Gohr
7802b6c6819SAndreas Gohr    /**
7812b6c6819SAndreas Gohr     * Returns a local file header for the given data
7822b6c6819SAndreas Gohr     *
7832b6c6819SAndreas Gohr     * @param int $offset location of the local header
7842b6c6819SAndreas Gohr     * @param int $ts unix timestamp
7852b6c6819SAndreas Gohr     * @param int $crc CRC32 checksum of the uncompressed data
7862b6c6819SAndreas Gohr     * @param int $len length of the uncompressed data
7872b6c6819SAndreas Gohr     * @param int $clen length of the compressed data
7882b6c6819SAndreas Gohr     * @param string $name file name
7892b6c6819SAndreas Gohr     * @param boolean|null $comp if compression is used, if null it's determined from $len != $clen
7902b6c6819SAndreas Gohr     * @return string
7912b6c6819SAndreas Gohr     */
7922b6c6819SAndreas Gohr    protected function makeCentralFileRecord($offset, $ts, $crc, $len, $clen, $name, $comp = null)
7932b6c6819SAndreas Gohr    {
7942b6c6819SAndreas Gohr        if(is_null($comp)) $comp = $len != $clen;
7952b6c6819SAndreas Gohr        $comp = $comp ? 8 : 0;
7962b6c6819SAndreas Gohr        $dtime = dechex($this->makeDosTime($ts));
7972b6c6819SAndreas Gohr
79836113441SAndreas Gohr        list($name, $extra) = $this->encodeFilename($name);
79936113441SAndreas Gohr
8002b6c6819SAndreas Gohr        $header = "\x50\x4b\x01\x02"; // central file header signature
8012b6c6819SAndreas Gohr        $header .= pack('v', 14); // version made by - VFAT
8022b6c6819SAndreas Gohr        $header .= pack('v', 20); // version needed to extract - 2.0
8032b6c6819SAndreas Gohr        $header .= pack('v', 0); // general purpose flag - no flags set
8042b6c6819SAndreas Gohr        $header .= pack('v', $comp); // compression method - deflate|none
8052b6c6819SAndreas Gohr        $header .= pack(
8062b6c6819SAndreas Gohr            'H*',
8072b6c6819SAndreas Gohr            $dtime[6] . $dtime[7] .
8082b6c6819SAndreas Gohr            $dtime[4] . $dtime[5] .
8092b6c6819SAndreas Gohr            $dtime[2] . $dtime[3] .
8102b6c6819SAndreas Gohr            $dtime[0] . $dtime[1]
8112b6c6819SAndreas Gohr        ); //  last mod file time and date
8122b6c6819SAndreas Gohr        $header .= pack('V', $crc); // crc-32
8132b6c6819SAndreas Gohr        $header .= pack('V', $clen); // compressed size
8142b6c6819SAndreas Gohr        $header .= pack('V', $len); // uncompressed size
8152b6c6819SAndreas Gohr        $header .= pack('v', strlen($name)); // file name length
81636113441SAndreas Gohr        $header .= pack('v', strlen($extra)); // extra field length
8172b6c6819SAndreas Gohr        $header .= pack('v', 0); // file comment length
8182b6c6819SAndreas Gohr        $header .= pack('v', 0); // disk number start
8192b6c6819SAndreas Gohr        $header .= pack('v', 0); // internal file attributes
8202b6c6819SAndreas Gohr        $header .= pack('V', 0); // external file attributes  @todo was 0x32!?
8212b6c6819SAndreas Gohr        $header .= pack('V', $offset); // relative offset of local header
8222b6c6819SAndreas Gohr        $header .= $name; // file name
82336113441SAndreas Gohr        $header .= $extra; // extra (utf-8 filename)
8242b6c6819SAndreas Gohr
8252b6c6819SAndreas Gohr        return $header;
8262b6c6819SAndreas Gohr    }
8272b6c6819SAndreas Gohr
8282b6c6819SAndreas Gohr    /**
8292b6c6819SAndreas Gohr     * Returns a local file header for the given data
8302b6c6819SAndreas Gohr     *
8312b6c6819SAndreas Gohr     * @param int $ts unix timestamp
8322b6c6819SAndreas Gohr     * @param int $crc CRC32 checksum of the uncompressed data
8332b6c6819SAndreas Gohr     * @param int $len length of the uncompressed data
8342b6c6819SAndreas Gohr     * @param int $clen length of the compressed data
8352b6c6819SAndreas Gohr     * @param string $name file name
8362b6c6819SAndreas Gohr     * @param boolean|null $comp if compression is used, if null it's determined from $len != $clen
8372b6c6819SAndreas Gohr     * @return string
8382b6c6819SAndreas Gohr     */
8392b6c6819SAndreas Gohr    protected function makeLocalFileHeader($ts, $crc, $len, $clen, $name, $comp = null)
8402b6c6819SAndreas Gohr    {
8412b6c6819SAndreas Gohr        if(is_null($comp)) $comp = $len != $clen;
8422b6c6819SAndreas Gohr        $comp = $comp ? 8 : 0;
8432b6c6819SAndreas Gohr        $dtime = dechex($this->makeDosTime($ts));
8442b6c6819SAndreas Gohr
84536113441SAndreas Gohr        list($name, $extra) = $this->encodeFilename($name);
84636113441SAndreas Gohr
8472b6c6819SAndreas Gohr        $header = "\x50\x4b\x03\x04"; //  local file header signature
8482b6c6819SAndreas Gohr        $header .= pack('v', 20); // version needed to extract - 2.0
8492b6c6819SAndreas Gohr        $header .= pack('v', 0); // general purpose flag - no flags set
8502b6c6819SAndreas Gohr        $header .= pack('v', $comp); // compression method - deflate|none
8512b6c6819SAndreas Gohr        $header .= pack(
8522b6c6819SAndreas Gohr            'H*',
8532b6c6819SAndreas Gohr            $dtime[6] . $dtime[7] .
8542b6c6819SAndreas Gohr            $dtime[4] . $dtime[5] .
8552b6c6819SAndreas Gohr            $dtime[2] . $dtime[3] .
8562b6c6819SAndreas Gohr            $dtime[0] . $dtime[1]
8572b6c6819SAndreas Gohr        ); //  last mod file time and date
8582b6c6819SAndreas Gohr        $header .= pack('V', $crc); // crc-32
8592b6c6819SAndreas Gohr        $header .= pack('V', $clen); // compressed size
8602b6c6819SAndreas Gohr        $header .= pack('V', $len); // uncompressed size
8612b6c6819SAndreas Gohr        $header .= pack('v', strlen($name)); // file name length
86236113441SAndreas Gohr        $header .= pack('v', strlen($extra)); // extra field length
86336113441SAndreas Gohr        $header .= $name; // file name
86436113441SAndreas Gohr        $header .= $extra; // extra (utf-8 filename)
8652b6c6819SAndreas Gohr        return $header;
8662b6c6819SAndreas Gohr    }
86736113441SAndreas Gohr
86836113441SAndreas Gohr    /**
86936113441SAndreas Gohr     * Returns an allowed filename and an extra field header
87036113441SAndreas Gohr     *
87136113441SAndreas Gohr     * When encoding stuff outside the 7bit ASCII range it needs to be placed in a separate
87236113441SAndreas Gohr     * extra field
87336113441SAndreas Gohr     *
87436113441SAndreas Gohr     * @param $original
87536113441SAndreas Gohr     * @return array($filename, $extra)
87636113441SAndreas Gohr     */
87736113441SAndreas Gohr    protected function encodeFilename($original)
87836113441SAndreas Gohr    {
87936113441SAndreas Gohr        $cp437 = $this->utf8ToCp($original);
88036113441SAndreas Gohr        if ($cp437 === $original) {
88136113441SAndreas Gohr            return array($original, '');
88236113441SAndreas Gohr        }
88336113441SAndreas Gohr
88436113441SAndreas Gohr        $extra = pack(
88536113441SAndreas Gohr            'vvCV',
88636113441SAndreas Gohr            0x7075, // tag
88736113441SAndreas Gohr            strlen($original) + 5, // length of file + version + crc
88836113441SAndreas Gohr            1, // version
88936113441SAndreas Gohr            crc32($original) // crc
89036113441SAndreas Gohr        );
89136113441SAndreas Gohr        $extra .= $original;
89236113441SAndreas Gohr
89336113441SAndreas Gohr        return array($cp437, $extra);
89436113441SAndreas Gohr    }
895605f8e8dSAndreas Gohr}
896