xref: /dokuwiki/vendor/splitbrain/php-archive/src/Zip.php (revision 2afbbbaeea08091e19cadcd631ed59a224ff0d59)
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{
18*2afbbbaeSAndreas Gohr    const LOCAL_FILE_HEADER_CRC_OFFSET = 14;
19605f8e8dSAndreas Gohr
20605f8e8dSAndreas Gohr    protected $file = '';
21605f8e8dSAndreas Gohr    protected $fh;
22605f8e8dSAndreas Gohr    protected $memory = '';
23605f8e8dSAndreas Gohr    protected $closed = true;
24605f8e8dSAndreas Gohr    protected $writeaccess = false;
25605f8e8dSAndreas Gohr    protected $ctrl_dir;
26605f8e8dSAndreas Gohr    protected $complevel = 9;
27605f8e8dSAndreas Gohr
28605f8e8dSAndreas Gohr    /**
29605f8e8dSAndreas Gohr     * Set the compression level.
30605f8e8dSAndreas Gohr     *
31605f8e8dSAndreas Gohr     * Compression Type is ignored for ZIP
32605f8e8dSAndreas Gohr     *
33605f8e8dSAndreas Gohr     * You can call this function before adding each file to set differen compression levels
34605f8e8dSAndreas Gohr     * for each file.
35605f8e8dSAndreas Gohr     *
36605f8e8dSAndreas Gohr     * @param int $level Compression level (0 to 9)
37605f8e8dSAndreas Gohr     * @param int $type  Type of compression to use ignored for ZIP
38e43cd7e1SAndreas Gohr     * @throws ArchiveIllegalCompressionException
39605f8e8dSAndreas Gohr     */
40605f8e8dSAndreas Gohr    public function setCompression($level = 9, $type = Archive::COMPRESS_AUTO)
41605f8e8dSAndreas Gohr    {
42e43cd7e1SAndreas Gohr        if ($level < -1 || $level > 9) {
43e43cd7e1SAndreas Gohr            throw new ArchiveIllegalCompressionException('Compression level should be between -1 and 9');
44e43cd7e1SAndreas Gohr        }
45605f8e8dSAndreas Gohr        $this->complevel = $level;
46605f8e8dSAndreas Gohr    }
47605f8e8dSAndreas Gohr
48605f8e8dSAndreas Gohr    /**
49605f8e8dSAndreas Gohr     * Open an existing ZIP file for reading
50605f8e8dSAndreas Gohr     *
51605f8e8dSAndreas Gohr     * @param string $file
52605f8e8dSAndreas Gohr     * @throws ArchiveIOException
53605f8e8dSAndreas Gohr     */
54605f8e8dSAndreas Gohr    public function open($file)
55605f8e8dSAndreas Gohr    {
56605f8e8dSAndreas Gohr        $this->file = $file;
57605f8e8dSAndreas Gohr        $this->fh   = @fopen($this->file, 'rb');
58605f8e8dSAndreas Gohr        if (!$this->fh) {
59605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not open file for reading: '.$this->file);
60605f8e8dSAndreas Gohr        }
61605f8e8dSAndreas Gohr        $this->closed = false;
62605f8e8dSAndreas Gohr    }
63605f8e8dSAndreas Gohr
64605f8e8dSAndreas Gohr    /**
65605f8e8dSAndreas Gohr     * Read the contents of a ZIP archive
66605f8e8dSAndreas Gohr     *
67605f8e8dSAndreas Gohr     * This function lists the files stored in the archive, and returns an indexed array of FileInfo objects
68605f8e8dSAndreas Gohr     *
69605f8e8dSAndreas Gohr     * The archive is closed afer reading the contents, for API compatibility with TAR files
70605f8e8dSAndreas Gohr     * Reopen the file with open() again if you want to do additional operations
71605f8e8dSAndreas Gohr     *
72605f8e8dSAndreas Gohr     * @throws ArchiveIOException
73605f8e8dSAndreas Gohr     * @return FileInfo[]
74605f8e8dSAndreas Gohr     */
75605f8e8dSAndreas Gohr    public function contents()
76605f8e8dSAndreas Gohr    {
77*2afbbbaeSAndreas Gohr        $result = array();
78*2afbbbaeSAndreas Gohr
79*2afbbbaeSAndreas Gohr        foreach ($this->yieldContents() as $fileinfo) {
80*2afbbbaeSAndreas Gohr            $result[] = $fileinfo;
81*2afbbbaeSAndreas Gohr        }
82*2afbbbaeSAndreas Gohr
83*2afbbbaeSAndreas Gohr        return $result;
84*2afbbbaeSAndreas Gohr    }
85*2afbbbaeSAndreas Gohr
86*2afbbbaeSAndreas Gohr    /**
87*2afbbbaeSAndreas Gohr     * Read the contents of a ZIP archive and return each entry using yield
88*2afbbbaeSAndreas Gohr     * for memory efficiency.
89*2afbbbaeSAndreas Gohr     *
90*2afbbbaeSAndreas Gohr     * @see contents()
91*2afbbbaeSAndreas Gohr     * @throws ArchiveIOException
92*2afbbbaeSAndreas Gohr     * @return FileInfo[]
93*2afbbbaeSAndreas Gohr     */
94*2afbbbaeSAndreas Gohr    public function yieldContents()
95*2afbbbaeSAndreas Gohr    {
96605f8e8dSAndreas Gohr        if ($this->closed || !$this->file) {
97605f8e8dSAndreas Gohr            throw new ArchiveIOException('Can not read from a closed archive');
98605f8e8dSAndreas Gohr        }
99605f8e8dSAndreas Gohr
100605f8e8dSAndreas Gohr        $centd = $this->readCentralDir();
101605f8e8dSAndreas Gohr
102605f8e8dSAndreas Gohr        @rewind($this->fh);
103605f8e8dSAndreas Gohr        @fseek($this->fh, $centd['offset']);
104605f8e8dSAndreas Gohr
105605f8e8dSAndreas Gohr        for ($i = 0; $i < $centd['entries']; $i++) {
106*2afbbbaeSAndreas Gohr            yield $this->header2fileinfo($this->readCentralFileHeader());
107605f8e8dSAndreas Gohr        }
108605f8e8dSAndreas Gohr
109605f8e8dSAndreas Gohr        $this->close();
110605f8e8dSAndreas Gohr    }
111605f8e8dSAndreas Gohr
112605f8e8dSAndreas Gohr    /**
113605f8e8dSAndreas Gohr     * Extract an existing ZIP archive
114605f8e8dSAndreas Gohr     *
115605f8e8dSAndreas Gohr     * The $strip parameter allows you to strip a certain number of path components from the filenames
116605f8e8dSAndreas Gohr     * found in the tar file, similar to the --strip-components feature of GNU tar. This is triggered when
117605f8e8dSAndreas Gohr     * an integer is passed as $strip.
118605f8e8dSAndreas Gohr     * Alternatively a fixed string prefix may be passed in $strip. If the filename matches this prefix,
119605f8e8dSAndreas Gohr     * the prefix will be stripped. It is recommended to give prefixes with a trailing slash.
120605f8e8dSAndreas Gohr     *
121605f8e8dSAndreas Gohr     * By default this will extract all files found in the archive. You can restrict the output using the $include
122605f8e8dSAndreas Gohr     * and $exclude parameter. Both expect a full regular expression (including delimiters and modifiers). If
123605f8e8dSAndreas Gohr     * $include is set only files that match this expression will be extracted. Files that match the $exclude
124605f8e8dSAndreas Gohr     * expression will never be extracted. Both parameters can be used in combination. Expressions are matched against
125605f8e8dSAndreas Gohr     * stripped filenames as described above.
126605f8e8dSAndreas Gohr     *
127605f8e8dSAndreas Gohr     * @param string     $outdir  the target directory for extracting
128605f8e8dSAndreas Gohr     * @param int|string $strip   either the number of path components or a fixed prefix to strip
129605f8e8dSAndreas Gohr     * @param string     $exclude a regular expression of files to exclude
130605f8e8dSAndreas Gohr     * @param string     $include a regular expression of files to include
131605f8e8dSAndreas Gohr     * @throws ArchiveIOException
132605f8e8dSAndreas Gohr     * @return FileInfo[]
133605f8e8dSAndreas Gohr     */
134ddb94cf0SAndreas Gohr    public function extract($outdir, $strip = '', $exclude = '', $include = '')
135605f8e8dSAndreas Gohr    {
136605f8e8dSAndreas Gohr        if ($this->closed || !$this->file) {
137605f8e8dSAndreas Gohr            throw new ArchiveIOException('Can not read from a closed archive');
138605f8e8dSAndreas Gohr        }
139605f8e8dSAndreas Gohr
140605f8e8dSAndreas Gohr        $outdir = rtrim($outdir, '/');
141605f8e8dSAndreas Gohr        @mkdir($outdir, 0777, true);
142605f8e8dSAndreas Gohr
143605f8e8dSAndreas Gohr        $extracted = array();
144605f8e8dSAndreas Gohr
145605f8e8dSAndreas Gohr        $cdir      = $this->readCentralDir();
146605f8e8dSAndreas Gohr        $pos_entry = $cdir['offset']; // begin of the central file directory
147605f8e8dSAndreas Gohr
148605f8e8dSAndreas Gohr        for ($i = 0; $i < $cdir['entries']; $i++) {
149605f8e8dSAndreas Gohr            // read file header
150605f8e8dSAndreas Gohr            @fseek($this->fh, $pos_entry);
151605f8e8dSAndreas Gohr            $header          = $this->readCentralFileHeader();
152605f8e8dSAndreas Gohr            $header['index'] = $i;
153605f8e8dSAndreas Gohr            $pos_entry       = ftell($this->fh); // position of the next file in central file directory
154605f8e8dSAndreas Gohr            fseek($this->fh, $header['offset']); // seek to beginning of file header
155605f8e8dSAndreas Gohr            $header   = $this->readFileHeader($header);
156605f8e8dSAndreas Gohr            $fileinfo = $this->header2fileinfo($header);
157605f8e8dSAndreas Gohr
158605f8e8dSAndreas Gohr            // apply strip rules
159605f8e8dSAndreas Gohr            $fileinfo->strip($strip);
160605f8e8dSAndreas Gohr
161605f8e8dSAndreas Gohr            // skip unwanted files
162a3bfbb3cSAndreas Gohr            if (!strlen($fileinfo->getPath()) || !$fileinfo->matchExpression($include, $exclude)) {
163605f8e8dSAndreas Gohr                continue;
164605f8e8dSAndreas Gohr            }
165605f8e8dSAndreas Gohr
166605f8e8dSAndreas Gohr            $extracted[] = $fileinfo;
167605f8e8dSAndreas Gohr
168605f8e8dSAndreas Gohr            // create output directory
169605f8e8dSAndreas Gohr            $output    = $outdir.'/'.$fileinfo->getPath();
170605f8e8dSAndreas Gohr            $directory = ($header['folder']) ? $output : dirname($output);
171605f8e8dSAndreas Gohr            @mkdir($directory, 0777, true);
172605f8e8dSAndreas Gohr
173605f8e8dSAndreas Gohr            // nothing more to do for directories
174605f8e8dSAndreas Gohr            if ($fileinfo->getIsdir()) {
175e43cd7e1SAndreas Gohr                if(is_callable($this->callback)) {
176e43cd7e1SAndreas Gohr                    call_user_func($this->callback, $fileinfo);
177e43cd7e1SAndreas Gohr                }
178605f8e8dSAndreas Gohr                continue;
179605f8e8dSAndreas Gohr            }
180605f8e8dSAndreas Gohr
181605f8e8dSAndreas Gohr            // compressed files are written to temporary .gz file first
182605f8e8dSAndreas Gohr            if ($header['compression'] == 0) {
183605f8e8dSAndreas Gohr                $extractto = $output;
184605f8e8dSAndreas Gohr            } else {
185605f8e8dSAndreas Gohr                $extractto = $output.'.gz';
186605f8e8dSAndreas Gohr            }
187605f8e8dSAndreas Gohr
188605f8e8dSAndreas Gohr            // open file for writing
189ddb94cf0SAndreas Gohr            $fp = @fopen($extractto, "wb");
190605f8e8dSAndreas Gohr            if (!$fp) {
191605f8e8dSAndreas Gohr                throw new ArchiveIOException('Could not open file for writing: '.$extractto);
192605f8e8dSAndreas Gohr            }
193605f8e8dSAndreas Gohr
194605f8e8dSAndreas Gohr            // prepend compression header
195605f8e8dSAndreas Gohr            if ($header['compression'] != 0) {
196605f8e8dSAndreas Gohr                $binary_data = pack(
197605f8e8dSAndreas Gohr                    'va1a1Va1a1',
198605f8e8dSAndreas Gohr                    0x8b1f,
199605f8e8dSAndreas Gohr                    chr($header['compression']),
200605f8e8dSAndreas Gohr                    chr(0x00),
201605f8e8dSAndreas Gohr                    time(),
202605f8e8dSAndreas Gohr                    chr(0x00),
203605f8e8dSAndreas Gohr                    chr(3)
204605f8e8dSAndreas Gohr                );
205605f8e8dSAndreas Gohr                fwrite($fp, $binary_data, 10);
206605f8e8dSAndreas Gohr            }
207605f8e8dSAndreas Gohr
208605f8e8dSAndreas Gohr            // read the file and store it on disk
209605f8e8dSAndreas Gohr            $size = $header['compressed_size'];
210605f8e8dSAndreas Gohr            while ($size != 0) {
211605f8e8dSAndreas Gohr                $read_size   = ($size < 2048 ? $size : 2048);
212605f8e8dSAndreas Gohr                $buffer      = fread($this->fh, $read_size);
213605f8e8dSAndreas Gohr                $binary_data = pack('a'.$read_size, $buffer);
214605f8e8dSAndreas Gohr                fwrite($fp, $binary_data, $read_size);
215605f8e8dSAndreas Gohr                $size -= $read_size;
216605f8e8dSAndreas Gohr            }
217605f8e8dSAndreas Gohr
218605f8e8dSAndreas Gohr            // finalize compressed file
219605f8e8dSAndreas Gohr            if ($header['compression'] != 0) {
220605f8e8dSAndreas Gohr                $binary_data = pack('VV', $header['crc'], $header['size']);
221605f8e8dSAndreas Gohr                fwrite($fp, $binary_data, 8);
222605f8e8dSAndreas Gohr            }
223605f8e8dSAndreas Gohr
224605f8e8dSAndreas Gohr            // close file
225605f8e8dSAndreas Gohr            fclose($fp);
226605f8e8dSAndreas Gohr
227605f8e8dSAndreas Gohr            // unpack compressed file
228605f8e8dSAndreas Gohr            if ($header['compression'] != 0) {
229605f8e8dSAndreas Gohr                $gzp = @gzopen($extractto, 'rb');
230605f8e8dSAndreas Gohr                if (!$gzp) {
231605f8e8dSAndreas Gohr                    @unlink($extractto);
232605f8e8dSAndreas Gohr                    throw new ArchiveIOException('Failed file extracting. gzip support missing?');
233605f8e8dSAndreas Gohr                }
234605f8e8dSAndreas Gohr                $fp = @fopen($output, 'wb');
235605f8e8dSAndreas Gohr                if (!$fp) {
236605f8e8dSAndreas Gohr                    throw new ArchiveIOException('Could not open file for writing: '.$extractto);
237605f8e8dSAndreas Gohr                }
238605f8e8dSAndreas Gohr
239605f8e8dSAndreas Gohr                $size = $header['size'];
240605f8e8dSAndreas Gohr                while ($size != 0) {
241605f8e8dSAndreas Gohr                    $read_size   = ($size < 2048 ? $size : 2048);
242605f8e8dSAndreas Gohr                    $buffer      = gzread($gzp, $read_size);
243605f8e8dSAndreas Gohr                    $binary_data = pack('a'.$read_size, $buffer);
244605f8e8dSAndreas Gohr                    @fwrite($fp, $binary_data, $read_size);
245605f8e8dSAndreas Gohr                    $size -= $read_size;
246605f8e8dSAndreas Gohr                }
247605f8e8dSAndreas Gohr                fclose($fp);
248605f8e8dSAndreas Gohr                gzclose($gzp);
2494a690352SAndreas Gohr                unlink($extractto); // remove temporary gz file
250605f8e8dSAndreas Gohr            }
251605f8e8dSAndreas Gohr
252e43cd7e1SAndreas Gohr            @touch($output, $fileinfo->getMtime());
253605f8e8dSAndreas Gohr            //FIXME what about permissions?
254e43cd7e1SAndreas Gohr            if(is_callable($this->callback)) {
255e43cd7e1SAndreas Gohr                call_user_func($this->callback, $fileinfo);
256e43cd7e1SAndreas Gohr            }
257605f8e8dSAndreas Gohr        }
258605f8e8dSAndreas Gohr
259605f8e8dSAndreas Gohr        $this->close();
260605f8e8dSAndreas Gohr        return $extracted;
261605f8e8dSAndreas Gohr    }
262605f8e8dSAndreas Gohr
263605f8e8dSAndreas Gohr    /**
264605f8e8dSAndreas Gohr     * Create a new ZIP file
265605f8e8dSAndreas Gohr     *
266605f8e8dSAndreas Gohr     * If $file is empty, the zip file will be created in memory
267605f8e8dSAndreas Gohr     *
268605f8e8dSAndreas Gohr     * @param string $file
269605f8e8dSAndreas Gohr     * @throws ArchiveIOException
270605f8e8dSAndreas Gohr     */
271605f8e8dSAndreas Gohr    public function create($file = '')
272605f8e8dSAndreas Gohr    {
273605f8e8dSAndreas Gohr        $this->file   = $file;
274605f8e8dSAndreas Gohr        $this->memory = '';
275605f8e8dSAndreas Gohr        $this->fh     = 0;
276605f8e8dSAndreas Gohr
277605f8e8dSAndreas Gohr        if ($this->file) {
278605f8e8dSAndreas Gohr            $this->fh = @fopen($this->file, 'wb');
279605f8e8dSAndreas Gohr
280605f8e8dSAndreas Gohr            if (!$this->fh) {
281605f8e8dSAndreas Gohr                throw new ArchiveIOException('Could not open file for writing: '.$this->file);
282605f8e8dSAndreas Gohr            }
283605f8e8dSAndreas Gohr        }
284605f8e8dSAndreas Gohr        $this->writeaccess = true;
285605f8e8dSAndreas Gohr        $this->closed      = false;
286605f8e8dSAndreas Gohr        $this->ctrl_dir    = array();
287605f8e8dSAndreas Gohr    }
288605f8e8dSAndreas Gohr
289605f8e8dSAndreas Gohr    /**
290605f8e8dSAndreas Gohr     * Add a file to the current ZIP archive using an existing file in the filesystem
291605f8e8dSAndreas Gohr     *
292605f8e8dSAndreas Gohr     * @param string          $file     path to the original file
293605f8e8dSAndreas 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
294605f8e8dSAndreas Gohr     * @throws ArchiveIOException
295605f8e8dSAndreas Gohr     */
296605f8e8dSAndreas Gohr
297605f8e8dSAndreas Gohr    /**
298605f8e8dSAndreas Gohr     * Add a file to the current archive using an existing file in the filesystem
299605f8e8dSAndreas Gohr     *
300605f8e8dSAndreas Gohr     * @param string $file path to the original file
30136113441SAndreas 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
302605f8e8dSAndreas Gohr     * @throws ArchiveIOException
303e43cd7e1SAndreas Gohr     * @throws FileInfoException
304605f8e8dSAndreas Gohr     */
305605f8e8dSAndreas Gohr    public function addFile($file, $fileinfo = '')
306605f8e8dSAndreas Gohr    {
307605f8e8dSAndreas Gohr        if (is_string($fileinfo)) {
308605f8e8dSAndreas Gohr            $fileinfo = FileInfo::fromPath($file, $fileinfo);
309605f8e8dSAndreas Gohr        }
310605f8e8dSAndreas Gohr
311605f8e8dSAndreas Gohr        if ($this->closed) {
312605f8e8dSAndreas Gohr            throw new ArchiveIOException('Archive has been closed, files can no longer be added');
313605f8e8dSAndreas Gohr        }
314605f8e8dSAndreas Gohr
315*2afbbbaeSAndreas Gohr        $fp = @fopen($file, 'rb');
316*2afbbbaeSAndreas Gohr        if ($fp === false) {
317605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not open file for reading: '.$file);
318605f8e8dSAndreas Gohr        }
319605f8e8dSAndreas Gohr
320*2afbbbaeSAndreas Gohr        $offset = $this->dataOffset();
321*2afbbbaeSAndreas Gohr        $name   = $fileinfo->getPath();
322*2afbbbaeSAndreas Gohr        $time   = $fileinfo->getMtime();
323*2afbbbaeSAndreas Gohr
324*2afbbbaeSAndreas Gohr        // write local file header (temporary CRC and size)
325*2afbbbaeSAndreas Gohr        $this->writebytes($this->makeLocalFileHeader(
326*2afbbbaeSAndreas Gohr            $time,
327*2afbbbaeSAndreas Gohr            0,
328*2afbbbaeSAndreas Gohr            0,
329*2afbbbaeSAndreas Gohr            0,
330*2afbbbaeSAndreas Gohr            $name,
331*2afbbbaeSAndreas Gohr            (bool) $this->complevel
332*2afbbbaeSAndreas Gohr        ));
333*2afbbbaeSAndreas Gohr
334*2afbbbaeSAndreas Gohr        // we store no encryption header
335*2afbbbaeSAndreas Gohr
336*2afbbbaeSAndreas Gohr        // prepare info, compress and write data to archive
337*2afbbbaeSAndreas Gohr        $deflate_context = deflate_init(ZLIB_ENCODING_DEFLATE, ['level' => $this->complevel]);
338*2afbbbaeSAndreas Gohr        $crc_context = hash_init('crc32b');
339*2afbbbaeSAndreas Gohr        $size = $csize = 0;
340*2afbbbaeSAndreas Gohr
341*2afbbbaeSAndreas Gohr        while (!feof($fp)) {
342*2afbbbaeSAndreas Gohr            $block = fread($fp, 512);
343*2afbbbaeSAndreas Gohr
344*2afbbbaeSAndreas Gohr            if ($this->complevel) {
345*2afbbbaeSAndreas Gohr                $is_first_block = $size === 0;
346*2afbbbaeSAndreas Gohr                $is_last_block = feof($fp);
347*2afbbbaeSAndreas Gohr
348*2afbbbaeSAndreas Gohr                if ($is_last_block) {
349*2afbbbaeSAndreas Gohr                    $c_block = deflate_add($deflate_context, $block, ZLIB_FINISH);
350*2afbbbaeSAndreas Gohr                    // get rid of the compression footer
351*2afbbbaeSAndreas Gohr                    $c_block = substr($c_block, 0, -4);
352*2afbbbaeSAndreas Gohr                } else {
353*2afbbbaeSAndreas Gohr                    $c_block = deflate_add($deflate_context, $block, ZLIB_NO_FLUSH);
354*2afbbbaeSAndreas Gohr                }
355*2afbbbaeSAndreas Gohr
356*2afbbbaeSAndreas Gohr                // get rid of the compression header
357*2afbbbaeSAndreas Gohr                if ($is_first_block) {
358*2afbbbaeSAndreas Gohr                    $c_block = substr($c_block, 2);
359*2afbbbaeSAndreas Gohr                }
360*2afbbbaeSAndreas Gohr
361*2afbbbaeSAndreas Gohr                $csize += strlen($c_block);
362*2afbbbaeSAndreas Gohr                $this->writebytes($c_block);
363*2afbbbaeSAndreas Gohr            } else {
364*2afbbbaeSAndreas Gohr                $this->writebytes($block);
365*2afbbbaeSAndreas Gohr            }
366*2afbbbaeSAndreas Gohr
367*2afbbbaeSAndreas Gohr            $size += strlen($block);
368*2afbbbaeSAndreas Gohr            hash_update($crc_context, $block);
369*2afbbbaeSAndreas Gohr        }
370*2afbbbaeSAndreas Gohr        fclose($fp);
371*2afbbbaeSAndreas Gohr
372*2afbbbaeSAndreas Gohr        // update the local file header with the computed CRC and size
373*2afbbbaeSAndreas Gohr        $crc = hexdec(hash_final($crc_context));
374*2afbbbaeSAndreas Gohr        $csize = $this->complevel ? $csize : $size;
375*2afbbbaeSAndreas Gohr        $this->writebytesAt($this->makeCrcAndSize(
376*2afbbbaeSAndreas Gohr            $crc,
377*2afbbbaeSAndreas Gohr            $size,
378*2afbbbaeSAndreas Gohr            $csize
379*2afbbbaeSAndreas Gohr        ), $offset + self::LOCAL_FILE_HEADER_CRC_OFFSET);
380*2afbbbaeSAndreas Gohr
381*2afbbbaeSAndreas Gohr        // we store no data descriptor
382*2afbbbaeSAndreas Gohr
383*2afbbbaeSAndreas Gohr        // add info to central file directory
384*2afbbbaeSAndreas Gohr        $this->ctrl_dir[] = $this->makeCentralFileRecord(
385*2afbbbaeSAndreas Gohr            $offset,
386*2afbbbaeSAndreas Gohr            $time,
387*2afbbbaeSAndreas Gohr            $crc,
388*2afbbbaeSAndreas Gohr            $size,
389*2afbbbaeSAndreas Gohr            $csize,
390*2afbbbaeSAndreas Gohr            $name,
391*2afbbbaeSAndreas Gohr            (bool) $this->complevel
392*2afbbbaeSAndreas Gohr        );
393*2afbbbaeSAndreas Gohr
394*2afbbbaeSAndreas Gohr        if(is_callable($this->callback)) {
395*2afbbbaeSAndreas Gohr            call_user_func($this->callback, $fileinfo);
396*2afbbbaeSAndreas Gohr        }
397605f8e8dSAndreas Gohr    }
398605f8e8dSAndreas Gohr
399605f8e8dSAndreas Gohr    /**
40036113441SAndreas Gohr     * Add a file to the current Zip archive using the given $data as content
401605f8e8dSAndreas Gohr     *
402605f8e8dSAndreas Gohr     * @param string|FileInfo $fileinfo either the name to us in archive (string) or a FileInfo oject with all meta data
403605f8e8dSAndreas Gohr     * @param string          $data     binary content of the file to add
404605f8e8dSAndreas Gohr     * @throws ArchiveIOException
405605f8e8dSAndreas Gohr     */
406605f8e8dSAndreas Gohr    public function addData($fileinfo, $data)
407605f8e8dSAndreas Gohr    {
408605f8e8dSAndreas Gohr        if (is_string($fileinfo)) {
409605f8e8dSAndreas Gohr            $fileinfo = new FileInfo($fileinfo);
410605f8e8dSAndreas Gohr        }
411605f8e8dSAndreas Gohr
412605f8e8dSAndreas Gohr        if ($this->closed) {
413605f8e8dSAndreas Gohr            throw new ArchiveIOException('Archive has been closed, files can no longer be added');
414605f8e8dSAndreas Gohr        }
415605f8e8dSAndreas Gohr
4162b6c6819SAndreas Gohr        // prepare info and compress data
417605f8e8dSAndreas Gohr        $size     = strlen($data);
418605f8e8dSAndreas Gohr        $crc      = crc32($data);
419605f8e8dSAndreas Gohr        if ($this->complevel) {
420605f8e8dSAndreas Gohr            $data = gzcompress($data, $this->complevel);
421605f8e8dSAndreas Gohr            $data = substr($data, 2, -4); // strip compression headers
422605f8e8dSAndreas Gohr        }
423605f8e8dSAndreas Gohr        $csize  = strlen($data);
424605f8e8dSAndreas Gohr        $offset = $this->dataOffset();
425605f8e8dSAndreas Gohr        $name   = $fileinfo->getPath();
4262b6c6819SAndreas Gohr        $time   = $fileinfo->getMtime();
4272b6c6819SAndreas Gohr
4282b6c6819SAndreas Gohr        // write local file header
4292b6c6819SAndreas Gohr        $this->writebytes($this->makeLocalFileHeader(
4302b6c6819SAndreas Gohr            $time,
4312b6c6819SAndreas Gohr            $crc,
4322b6c6819SAndreas Gohr            $size,
4332b6c6819SAndreas Gohr            $csize,
4342b6c6819SAndreas Gohr            $name,
4352b6c6819SAndreas Gohr            (bool) $this->complevel
4362b6c6819SAndreas Gohr        ));
4372b6c6819SAndreas Gohr
4382b6c6819SAndreas Gohr        // we store no encryption header
439605f8e8dSAndreas Gohr
440605f8e8dSAndreas Gohr        // write data
4412b6c6819SAndreas Gohr        $this->writebytes($data);
4422b6c6819SAndreas Gohr
4432b6c6819SAndreas Gohr        // we store no data descriptor
444605f8e8dSAndreas Gohr
445605f8e8dSAndreas Gohr        // add info to central file directory
4462b6c6819SAndreas Gohr        $this->ctrl_dir[] = $this->makeCentralFileRecord(
4472b6c6819SAndreas Gohr            $offset,
4482b6c6819SAndreas Gohr            $time,
4492b6c6819SAndreas Gohr            $crc,
4502b6c6819SAndreas Gohr            $size,
4512b6c6819SAndreas Gohr            $csize,
4522b6c6819SAndreas Gohr            $name,
4532b6c6819SAndreas Gohr            (bool) $this->complevel
4542b6c6819SAndreas Gohr        );
455e43cd7e1SAndreas Gohr
456e43cd7e1SAndreas Gohr        if(is_callable($this->callback)) {
457e43cd7e1SAndreas Gohr            call_user_func($this->callback, $fileinfo);
458e43cd7e1SAndreas Gohr        }
459605f8e8dSAndreas Gohr    }
460605f8e8dSAndreas Gohr
461605f8e8dSAndreas Gohr    /**
462605f8e8dSAndreas Gohr     * Add the closing footer to the archive if in write mode, close all file handles
463605f8e8dSAndreas Gohr     *
464605f8e8dSAndreas Gohr     * After a call to this function no more data can be added to the archive, for
465605f8e8dSAndreas Gohr     * read access no reading is allowed anymore
466e43cd7e1SAndreas Gohr     * @throws ArchiveIOException
467605f8e8dSAndreas Gohr     */
468605f8e8dSAndreas Gohr    public function close()
469605f8e8dSAndreas Gohr    {
470605f8e8dSAndreas Gohr        if ($this->closed) {
471605f8e8dSAndreas Gohr            return;
472605f8e8dSAndreas Gohr        } // we did this already
473605f8e8dSAndreas Gohr
474605f8e8dSAndreas Gohr        if ($this->writeaccess) {
4752b6c6819SAndreas Gohr            // write central directory
476605f8e8dSAndreas Gohr            $offset = $this->dataOffset();
477605f8e8dSAndreas Gohr            $ctrldir = join('', $this->ctrl_dir);
478605f8e8dSAndreas Gohr            $this->writebytes($ctrldir);
4792b6c6819SAndreas Gohr
4802b6c6819SAndreas Gohr            // write end of central directory record
4812b6c6819SAndreas Gohr            $this->writebytes("\x50\x4b\x05\x06"); // end of central dir signature
4822b6c6819SAndreas Gohr            $this->writebytes(pack('v', 0)); // number of this disk
4832b6c6819SAndreas Gohr            $this->writebytes(pack('v', 0)); // number of the disk with the start of the central directory
4842b6c6819SAndreas Gohr            $this->writebytes(pack('v',
4852b6c6819SAndreas Gohr                count($this->ctrl_dir))); // total number of entries in the central directory on this disk
4862b6c6819SAndreas Gohr            $this->writebytes(pack('v', count($this->ctrl_dir))); // total number of entries in the central directory
4872b6c6819SAndreas Gohr            $this->writebytes(pack('V', strlen($ctrldir))); // size of the central directory
4882b6c6819SAndreas Gohr            $this->writebytes(pack('V',
4892b6c6819SAndreas Gohr                $offset)); // offset of start of central directory with respect to the starting disk number
4902b6c6819SAndreas Gohr            $this->writebytes(pack('v', 0)); // .ZIP file comment length
4912b6c6819SAndreas Gohr
492605f8e8dSAndreas Gohr            $this->ctrl_dir = array();
493605f8e8dSAndreas Gohr        }
494605f8e8dSAndreas Gohr
495605f8e8dSAndreas Gohr        // close file handles
496605f8e8dSAndreas Gohr        if ($this->file) {
497605f8e8dSAndreas Gohr            fclose($this->fh);
498605f8e8dSAndreas Gohr            $this->file = '';
499605f8e8dSAndreas Gohr            $this->fh   = 0;
500605f8e8dSAndreas Gohr        }
501605f8e8dSAndreas Gohr
502605f8e8dSAndreas Gohr        $this->writeaccess = false;
503605f8e8dSAndreas Gohr        $this->closed      = true;
504605f8e8dSAndreas Gohr    }
505605f8e8dSAndreas Gohr
506605f8e8dSAndreas Gohr    /**
507605f8e8dSAndreas Gohr     * Returns the created in-memory archive data
508605f8e8dSAndreas Gohr     *
509605f8e8dSAndreas Gohr     * This implicitly calls close() on the Archive
510e43cd7e1SAndreas Gohr     * @throws ArchiveIOException
511605f8e8dSAndreas Gohr     */
512605f8e8dSAndreas Gohr    public function getArchive()
513605f8e8dSAndreas Gohr    {
514605f8e8dSAndreas Gohr        $this->close();
515605f8e8dSAndreas Gohr
516605f8e8dSAndreas Gohr        return $this->memory;
517605f8e8dSAndreas Gohr    }
518605f8e8dSAndreas Gohr
519605f8e8dSAndreas Gohr    /**
520605f8e8dSAndreas Gohr     * Save the created in-memory archive data
521605f8e8dSAndreas Gohr     *
522605f8e8dSAndreas Gohr     * Note: It's more memory effective to specify the filename in the create() function and
523605f8e8dSAndreas Gohr     * let the library work on the new file directly.
524605f8e8dSAndreas Gohr     *
525605f8e8dSAndreas Gohr     * @param     $file
526605f8e8dSAndreas Gohr     * @throws ArchiveIOException
527605f8e8dSAndreas Gohr     */
528605f8e8dSAndreas Gohr    public function save($file)
529605f8e8dSAndreas Gohr    {
530ddb94cf0SAndreas Gohr        if (!@file_put_contents($file, $this->getArchive())) {
531605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not write to file: '.$file);
532605f8e8dSAndreas Gohr        }
533605f8e8dSAndreas Gohr    }
534605f8e8dSAndreas Gohr
535605f8e8dSAndreas Gohr    /**
536605f8e8dSAndreas Gohr     * Read the central directory
537605f8e8dSAndreas Gohr     *
538605f8e8dSAndreas Gohr     * This key-value list contains general information about the ZIP file
539605f8e8dSAndreas Gohr     *
540605f8e8dSAndreas Gohr     * @return array
541605f8e8dSAndreas Gohr     */
542605f8e8dSAndreas Gohr    protected function readCentralDir()
543605f8e8dSAndreas Gohr    {
544605f8e8dSAndreas Gohr        $size = filesize($this->file);
545605f8e8dSAndreas Gohr        if ($size < 277) {
546605f8e8dSAndreas Gohr            $maximum_size = $size;
547605f8e8dSAndreas Gohr        } else {
548605f8e8dSAndreas Gohr            $maximum_size = 277;
549605f8e8dSAndreas Gohr        }
550605f8e8dSAndreas Gohr
551605f8e8dSAndreas Gohr        @fseek($this->fh, $size - $maximum_size);
552605f8e8dSAndreas Gohr        $pos   = ftell($this->fh);
553605f8e8dSAndreas Gohr        $bytes = 0x00000000;
554605f8e8dSAndreas Gohr
555605f8e8dSAndreas Gohr        while ($pos < $size) {
556605f8e8dSAndreas Gohr            $byte  = @fread($this->fh, 1);
557605f8e8dSAndreas Gohr            $bytes = (($bytes << 8) & 0xFFFFFFFF) | ord($byte);
558605f8e8dSAndreas Gohr            if ($bytes == 0x504b0506) {
559605f8e8dSAndreas Gohr                break;
560605f8e8dSAndreas Gohr            }
561605f8e8dSAndreas Gohr            $pos++;
562605f8e8dSAndreas Gohr        }
563605f8e8dSAndreas Gohr
564605f8e8dSAndreas Gohr        $data = unpack(
565605f8e8dSAndreas Gohr            'vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size',
566605f8e8dSAndreas Gohr            fread($this->fh, 18)
567605f8e8dSAndreas Gohr        );
568605f8e8dSAndreas Gohr
569605f8e8dSAndreas Gohr        if ($data['comment_size'] != 0) {
570605f8e8dSAndreas Gohr            $centd['comment'] = fread($this->fh, $data['comment_size']);
571605f8e8dSAndreas Gohr        } else {
572605f8e8dSAndreas Gohr            $centd['comment'] = '';
573605f8e8dSAndreas Gohr        }
574605f8e8dSAndreas Gohr        $centd['entries']      = $data['entries'];
575605f8e8dSAndreas Gohr        $centd['disk_entries'] = $data['disk_entries'];
576605f8e8dSAndreas Gohr        $centd['offset']       = $data['offset'];
577605f8e8dSAndreas Gohr        $centd['disk_start']   = $data['disk_start'];
578605f8e8dSAndreas Gohr        $centd['size']         = $data['size'];
579605f8e8dSAndreas Gohr        $centd['disk']         = $data['disk'];
580605f8e8dSAndreas Gohr        return $centd;
581605f8e8dSAndreas Gohr    }
582605f8e8dSAndreas Gohr
583605f8e8dSAndreas Gohr    /**
584605f8e8dSAndreas Gohr     * Read the next central file header
585605f8e8dSAndreas Gohr     *
586605f8e8dSAndreas Gohr     * Assumes the current file pointer is pointing at the right position
587605f8e8dSAndreas Gohr     *
588605f8e8dSAndreas Gohr     * @return array
589605f8e8dSAndreas Gohr     */
590605f8e8dSAndreas Gohr    protected function readCentralFileHeader()
591605f8e8dSAndreas Gohr    {
592605f8e8dSAndreas Gohr        $binary_data = fread($this->fh, 46);
593605f8e8dSAndreas Gohr        $header      = unpack(
594605f8e8dSAndreas Gohr            'vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset',
595605f8e8dSAndreas Gohr            $binary_data
596605f8e8dSAndreas Gohr        );
597605f8e8dSAndreas Gohr
598605f8e8dSAndreas Gohr        if ($header['filename_len'] != 0) {
599605f8e8dSAndreas Gohr            $header['filename'] = fread($this->fh, $header['filename_len']);
600605f8e8dSAndreas Gohr        } else {
601605f8e8dSAndreas Gohr            $header['filename'] = '';
602605f8e8dSAndreas Gohr        }
603605f8e8dSAndreas Gohr
604605f8e8dSAndreas Gohr        if ($header['extra_len'] != 0) {
605605f8e8dSAndreas Gohr            $header['extra'] = fread($this->fh, $header['extra_len']);
60636113441SAndreas Gohr            $header['extradata'] = $this->parseExtra($header['extra']);
607605f8e8dSAndreas Gohr        } else {
608605f8e8dSAndreas Gohr            $header['extra'] = '';
60936113441SAndreas Gohr            $header['extradata'] = array();
610605f8e8dSAndreas Gohr        }
611605f8e8dSAndreas Gohr
612605f8e8dSAndreas Gohr        if ($header['comment_len'] != 0) {
613605f8e8dSAndreas Gohr            $header['comment'] = fread($this->fh, $header['comment_len']);
614605f8e8dSAndreas Gohr        } else {
615605f8e8dSAndreas Gohr            $header['comment'] = '';
616605f8e8dSAndreas Gohr        }
617605f8e8dSAndreas Gohr
6182b6c6819SAndreas Gohr        $header['mtime']           = $this->makeUnixTime($header['mdate'], $header['mtime']);
619605f8e8dSAndreas Gohr        $header['stored_filename'] = $header['filename'];
620605f8e8dSAndreas Gohr        $header['status']          = 'ok';
621605f8e8dSAndreas Gohr        if (substr($header['filename'], -1) == '/') {
622605f8e8dSAndreas Gohr            $header['external'] = 0x41FF0010;
623605f8e8dSAndreas Gohr        }
624605f8e8dSAndreas Gohr        $header['folder'] = ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0;
625605f8e8dSAndreas Gohr
626605f8e8dSAndreas Gohr        return $header;
627605f8e8dSAndreas Gohr    }
628605f8e8dSAndreas Gohr
629605f8e8dSAndreas Gohr    /**
630605f8e8dSAndreas Gohr     * Reads the local file header
631605f8e8dSAndreas Gohr     *
632605f8e8dSAndreas Gohr     * This header precedes each individual file inside the zip file. Assumes the current file pointer is pointing at
6332b6c6819SAndreas Gohr     * the right position already. Enhances the given central header with the data found at the local header.
634605f8e8dSAndreas Gohr     *
635605f8e8dSAndreas Gohr     * @param array $header the central file header read previously (see above)
636605f8e8dSAndreas Gohr     * @return array
637605f8e8dSAndreas Gohr     */
6382b6c6819SAndreas Gohr    protected function readFileHeader($header)
639605f8e8dSAndreas Gohr    {
640605f8e8dSAndreas Gohr        $binary_data = fread($this->fh, 30);
641605f8e8dSAndreas Gohr        $data        = unpack(
642605f8e8dSAndreas Gohr            'vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len',
643605f8e8dSAndreas Gohr            $binary_data
644605f8e8dSAndreas Gohr        );
645605f8e8dSAndreas Gohr
646605f8e8dSAndreas Gohr        $header['filename'] = fread($this->fh, $data['filename_len']);
647605f8e8dSAndreas Gohr        if ($data['extra_len'] != 0) {
648605f8e8dSAndreas Gohr            $header['extra'] = fread($this->fh, $data['extra_len']);
64936113441SAndreas Gohr            $header['extradata'] = array_merge($header['extradata'],  $this->parseExtra($header['extra']));
650605f8e8dSAndreas Gohr        } else {
651605f8e8dSAndreas Gohr            $header['extra'] = '';
65236113441SAndreas Gohr            $header['extradata'] = array();
653605f8e8dSAndreas Gohr        }
654605f8e8dSAndreas Gohr
655605f8e8dSAndreas Gohr        $header['compression'] = $data['compression'];
656605f8e8dSAndreas Gohr        foreach (array(
657605f8e8dSAndreas Gohr                     'size',
658605f8e8dSAndreas Gohr                     'compressed_size',
659605f8e8dSAndreas Gohr                     'crc'
660605f8e8dSAndreas Gohr                 ) as $hd) { // On ODT files, these headers are 0. Keep the previous value.
661605f8e8dSAndreas Gohr            if ($data[$hd] != 0) {
662605f8e8dSAndreas Gohr                $header[$hd] = $data[$hd];
663605f8e8dSAndreas Gohr            }
664605f8e8dSAndreas Gohr        }
665605f8e8dSAndreas Gohr        $header['flag']  = $data['flag'];
6662b6c6819SAndreas Gohr        $header['mtime'] = $this->makeUnixTime($data['mdate'], $data['mtime']);
667605f8e8dSAndreas Gohr
668605f8e8dSAndreas Gohr        $header['stored_filename'] = $header['filename'];
669605f8e8dSAndreas Gohr        $header['status']          = "ok";
670605f8e8dSAndreas Gohr        $header['folder']          = ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0;
671605f8e8dSAndreas Gohr        return $header;
672605f8e8dSAndreas Gohr    }
673605f8e8dSAndreas Gohr
674605f8e8dSAndreas Gohr    /**
67536113441SAndreas Gohr     * Parse the extra headers into fields
67636113441SAndreas Gohr     *
67736113441SAndreas Gohr     * @param string $header
67836113441SAndreas Gohr     * @return array
67936113441SAndreas Gohr     */
68036113441SAndreas Gohr    protected function parseExtra($header)
68136113441SAndreas Gohr    {
68236113441SAndreas Gohr        $extra = array();
68336113441SAndreas Gohr        // parse all extra fields as raw values
68436113441SAndreas Gohr        while (strlen($header) !== 0) {
68536113441SAndreas Gohr            $set = unpack('vid/vlen', $header);
68636113441SAndreas Gohr            $header = substr($header, 4);
68736113441SAndreas Gohr            $value = substr($header, 0, $set['len']);
68836113441SAndreas Gohr            $header = substr($header, $set['len']);
68936113441SAndreas Gohr            $extra[$set['id']] = $value;
69036113441SAndreas Gohr        }
69136113441SAndreas Gohr
69236113441SAndreas Gohr        // handle known ones
69336113441SAndreas Gohr        if(isset($extra[0x6375])) {
69436113441SAndreas Gohr            $extra['utf8comment'] = substr($extra[0x7075], 5); // strip version and crc
69536113441SAndreas Gohr        }
69636113441SAndreas Gohr        if(isset($extra[0x7075])) {
69736113441SAndreas Gohr            $extra['utf8path'] = substr($extra[0x7075], 5); // strip version and crc
69836113441SAndreas Gohr        }
69936113441SAndreas Gohr
70036113441SAndreas Gohr        return $extra;
70136113441SAndreas Gohr    }
70236113441SAndreas Gohr
70336113441SAndreas Gohr    /**
704605f8e8dSAndreas Gohr     * Create fileinfo object from header data
705605f8e8dSAndreas Gohr     *
706605f8e8dSAndreas Gohr     * @param $header
707605f8e8dSAndreas Gohr     * @return FileInfo
708605f8e8dSAndreas Gohr     */
709605f8e8dSAndreas Gohr    protected function header2fileinfo($header)
710605f8e8dSAndreas Gohr    {
711605f8e8dSAndreas Gohr        $fileinfo = new FileInfo();
712605f8e8dSAndreas Gohr        $fileinfo->setSize($header['size']);
713605f8e8dSAndreas Gohr        $fileinfo->setCompressedSize($header['compressed_size']);
714605f8e8dSAndreas Gohr        $fileinfo->setMtime($header['mtime']);
715605f8e8dSAndreas Gohr        $fileinfo->setComment($header['comment']);
716605f8e8dSAndreas Gohr        $fileinfo->setIsdir($header['external'] == 0x41FF0010 || $header['external'] == 16);
71736113441SAndreas Gohr
71836113441SAndreas Gohr        if(isset($header['extradata']['utf8path'])) {
71936113441SAndreas Gohr            $fileinfo->setPath($header['extradata']['utf8path']);
72036113441SAndreas Gohr        } else {
72136113441SAndreas Gohr            $fileinfo->setPath($this->cpToUtf8($header['filename']));
72236113441SAndreas Gohr        }
72336113441SAndreas Gohr
72436113441SAndreas Gohr        if(isset($header['extradata']['utf8comment'])) {
72536113441SAndreas Gohr            $fileinfo->setComment($header['extradata']['utf8comment']);
72636113441SAndreas Gohr        } else {
72736113441SAndreas Gohr            $fileinfo->setComment($this->cpToUtf8($header['comment']));
72836113441SAndreas Gohr        }
72936113441SAndreas Gohr
730605f8e8dSAndreas Gohr        return $fileinfo;
731605f8e8dSAndreas Gohr    }
732605f8e8dSAndreas Gohr
733605f8e8dSAndreas Gohr    /**
73436113441SAndreas Gohr     * Convert the given CP437 encoded string to UTF-8
73536113441SAndreas Gohr     *
73636113441SAndreas Gohr     * Tries iconv with the correct encoding first, falls back to mbstring with CP850 which is
73736113441SAndreas Gohr     * similar enough. CP437 seems not to be available in mbstring. Lastly falls back to keeping the
73836113441SAndreas Gohr     * string as is, which is still better than nothing.
73936113441SAndreas Gohr     *
740ddb94cf0SAndreas Gohr     * On some systems iconv is available, but the codepage is not. We also check for that.
741ddb94cf0SAndreas Gohr     *
74236113441SAndreas Gohr     * @param $string
74336113441SAndreas Gohr     * @return string
74436113441SAndreas Gohr     */
74536113441SAndreas Gohr    protected function cpToUtf8($string)
74636113441SAndreas Gohr    {
747ddb94cf0SAndreas Gohr        if (function_exists('iconv') && @iconv_strlen('', 'CP437') !== false) {
74836113441SAndreas Gohr            return iconv('CP437', 'UTF-8', $string);
74936113441SAndreas Gohr        } elseif (function_exists('mb_convert_encoding')) {
75036113441SAndreas Gohr            return mb_convert_encoding($string, 'UTF-8', 'CP850');
75136113441SAndreas Gohr        } else {
75236113441SAndreas Gohr            return $string;
75336113441SAndreas Gohr        }
75436113441SAndreas Gohr    }
75536113441SAndreas Gohr
75636113441SAndreas Gohr    /**
75736113441SAndreas Gohr     * Convert the given UTF-8 encoded string to CP437
75836113441SAndreas Gohr     *
75936113441SAndreas Gohr     * Same caveats as for cpToUtf8() apply
76036113441SAndreas Gohr     *
76136113441SAndreas Gohr     * @param $string
76236113441SAndreas Gohr     * @return string
76336113441SAndreas Gohr     */
76436113441SAndreas Gohr    protected function utf8ToCp($string)
76536113441SAndreas Gohr    {
76636113441SAndreas Gohr        // try iconv first
76736113441SAndreas Gohr        if (function_exists('iconv')) {
76836113441SAndreas Gohr            $conv = @iconv('UTF-8', 'CP437//IGNORE', $string);
76936113441SAndreas Gohr            if($conv) return $conv; // it worked
77036113441SAndreas Gohr        }
77136113441SAndreas Gohr
77236113441SAndreas Gohr        // still here? iconv failed to convert the string. Try another method
77336113441SAndreas Gohr        // see http://php.net/manual/en/function.iconv.php#108643
77436113441SAndreas Gohr
77536113441SAndreas Gohr        if (function_exists('mb_convert_encoding')) {
77636113441SAndreas Gohr            return mb_convert_encoding($string, 'CP850', 'UTF-8');
77736113441SAndreas Gohr        } else {
77836113441SAndreas Gohr            return $string;
77936113441SAndreas Gohr        }
78036113441SAndreas Gohr    }
78136113441SAndreas Gohr
78236113441SAndreas Gohr
78336113441SAndreas Gohr    /**
784605f8e8dSAndreas Gohr     * Write to the open filepointer or memory
785605f8e8dSAndreas Gohr     *
786605f8e8dSAndreas Gohr     * @param string $data
787605f8e8dSAndreas Gohr     * @throws ArchiveIOException
788605f8e8dSAndreas Gohr     * @return int number of bytes written
789605f8e8dSAndreas Gohr     */
790605f8e8dSAndreas Gohr    protected function writebytes($data)
791605f8e8dSAndreas Gohr    {
792605f8e8dSAndreas Gohr        if (!$this->file) {
793605f8e8dSAndreas Gohr            $this->memory .= $data;
794605f8e8dSAndreas Gohr            $written = strlen($data);
795605f8e8dSAndreas Gohr        } else {
796605f8e8dSAndreas Gohr            $written = @fwrite($this->fh, $data);
797605f8e8dSAndreas Gohr        }
798605f8e8dSAndreas Gohr        if ($written === false) {
799605f8e8dSAndreas Gohr            throw new ArchiveIOException('Failed to write to archive stream');
800605f8e8dSAndreas Gohr        }
801605f8e8dSAndreas Gohr        return $written;
802605f8e8dSAndreas Gohr    }
803605f8e8dSAndreas Gohr
804605f8e8dSAndreas Gohr    /**
805*2afbbbaeSAndreas Gohr     * Write to the open filepointer or memory at the specified offset
806*2afbbbaeSAndreas Gohr     *
807*2afbbbaeSAndreas Gohr     * @param string $data
808*2afbbbaeSAndreas Gohr     * @param int $offset
809*2afbbbaeSAndreas Gohr     * @throws ArchiveIOException
810*2afbbbaeSAndreas Gohr     * @return int number of bytes written
811*2afbbbaeSAndreas Gohr     */
812*2afbbbaeSAndreas Gohr    protected function writebytesAt($data, $offset) {
813*2afbbbaeSAndreas Gohr        if (!$this->file) {
814*2afbbbaeSAndreas Gohr            $this->memory .= substr_replace($this->memory, $data, $offset);
815*2afbbbaeSAndreas Gohr            $written = strlen($data);
816*2afbbbaeSAndreas Gohr        } else {
817*2afbbbaeSAndreas Gohr            @fseek($this->fh, $offset);
818*2afbbbaeSAndreas Gohr            $written = @fwrite($this->fh, $data);
819*2afbbbaeSAndreas Gohr            @fseek($this->fh, 0, SEEK_END);
820*2afbbbaeSAndreas Gohr        }
821*2afbbbaeSAndreas Gohr        if ($written === false) {
822*2afbbbaeSAndreas Gohr            throw new ArchiveIOException('Failed to write to archive stream');
823*2afbbbaeSAndreas Gohr        }
824*2afbbbaeSAndreas Gohr        return $written;
825*2afbbbaeSAndreas Gohr    }
826*2afbbbaeSAndreas Gohr
827*2afbbbaeSAndreas Gohr    /**
828605f8e8dSAndreas Gohr     * Current data pointer position
829605f8e8dSAndreas Gohr     *
830605f8e8dSAndreas Gohr     * @fixme might need a -1
831605f8e8dSAndreas Gohr     * @return int
832605f8e8dSAndreas Gohr     */
833605f8e8dSAndreas Gohr    protected function dataOffset()
834605f8e8dSAndreas Gohr    {
835605f8e8dSAndreas Gohr        if ($this->file) {
836605f8e8dSAndreas Gohr            return ftell($this->fh);
837605f8e8dSAndreas Gohr        } else {
838605f8e8dSAndreas Gohr            return strlen($this->memory);
839605f8e8dSAndreas Gohr        }
840605f8e8dSAndreas Gohr    }
841605f8e8dSAndreas Gohr
842605f8e8dSAndreas Gohr    /**
843605f8e8dSAndreas Gohr     * Create a DOS timestamp from a UNIX timestamp
844605f8e8dSAndreas Gohr     *
845605f8e8dSAndreas Gohr     * DOS timestamps start at 1980-01-01, earlier UNIX stamps will be set to this date
846605f8e8dSAndreas Gohr     *
847605f8e8dSAndreas Gohr     * @param $time
848605f8e8dSAndreas Gohr     * @return int
849605f8e8dSAndreas Gohr     */
850605f8e8dSAndreas Gohr    protected function makeDosTime($time)
851605f8e8dSAndreas Gohr    {
852605f8e8dSAndreas Gohr        $timearray = getdate($time);
853605f8e8dSAndreas Gohr        if ($timearray['year'] < 1980) {
854605f8e8dSAndreas Gohr            $timearray['year']    = 1980;
855605f8e8dSAndreas Gohr            $timearray['mon']     = 1;
856605f8e8dSAndreas Gohr            $timearray['mday']    = 1;
857605f8e8dSAndreas Gohr            $timearray['hours']   = 0;
858605f8e8dSAndreas Gohr            $timearray['minutes'] = 0;
859605f8e8dSAndreas Gohr            $timearray['seconds'] = 0;
860605f8e8dSAndreas Gohr        }
861605f8e8dSAndreas Gohr        return (($timearray['year'] - 1980) << 25) |
862605f8e8dSAndreas Gohr        ($timearray['mon'] << 21) |
863605f8e8dSAndreas Gohr        ($timearray['mday'] << 16) |
864605f8e8dSAndreas Gohr        ($timearray['hours'] << 11) |
865605f8e8dSAndreas Gohr        ($timearray['minutes'] << 5) |
866605f8e8dSAndreas Gohr        ($timearray['seconds'] >> 1);
867605f8e8dSAndreas Gohr    }
868605f8e8dSAndreas Gohr
8692b6c6819SAndreas Gohr    /**
8702b6c6819SAndreas Gohr     * Create a UNIX timestamp from a DOS timestamp
8712b6c6819SAndreas Gohr     *
8722b6c6819SAndreas Gohr     * @param $mdate
8732b6c6819SAndreas Gohr     * @param $mtime
8742b6c6819SAndreas Gohr     * @return int
8752b6c6819SAndreas Gohr     */
8762b6c6819SAndreas Gohr    protected function makeUnixTime($mdate = null, $mtime = null)
8772b6c6819SAndreas Gohr    {
8782b6c6819SAndreas Gohr        if ($mdate && $mtime) {
8792b6c6819SAndreas Gohr            $year = (($mdate & 0xFE00) >> 9) + 1980;
8802b6c6819SAndreas Gohr            $month = ($mdate & 0x01E0) >> 5;
8812b6c6819SAndreas Gohr            $day = $mdate & 0x001F;
8822b6c6819SAndreas Gohr
8832b6c6819SAndreas Gohr            $hour = ($mtime & 0xF800) >> 11;
8842b6c6819SAndreas Gohr            $minute = ($mtime & 0x07E0) >> 5;
8852b6c6819SAndreas Gohr            $seconde = ($mtime & 0x001F) << 1;
8862b6c6819SAndreas Gohr
8872b6c6819SAndreas Gohr            $mtime = mktime($hour, $minute, $seconde, $month, $day, $year);
8882b6c6819SAndreas Gohr        } else {
8892b6c6819SAndreas Gohr            $mtime = time();
8902b6c6819SAndreas Gohr        }
8912b6c6819SAndreas Gohr
8922b6c6819SAndreas Gohr        return $mtime;
8932b6c6819SAndreas Gohr    }
8942b6c6819SAndreas Gohr
8952b6c6819SAndreas Gohr    /**
8962b6c6819SAndreas Gohr     * Returns a local file header for the given data
8972b6c6819SAndreas Gohr     *
8982b6c6819SAndreas Gohr     * @param int $offset location of the local header
8992b6c6819SAndreas Gohr     * @param int $ts unix timestamp
9002b6c6819SAndreas Gohr     * @param int $crc CRC32 checksum of the uncompressed data
9012b6c6819SAndreas Gohr     * @param int $len length of the uncompressed data
9022b6c6819SAndreas Gohr     * @param int $clen length of the compressed data
9032b6c6819SAndreas Gohr     * @param string $name file name
9042b6c6819SAndreas Gohr     * @param boolean|null $comp if compression is used, if null it's determined from $len != $clen
9052b6c6819SAndreas Gohr     * @return string
9062b6c6819SAndreas Gohr     */
9072b6c6819SAndreas Gohr    protected function makeCentralFileRecord($offset, $ts, $crc, $len, $clen, $name, $comp = null)
9082b6c6819SAndreas Gohr    {
9092b6c6819SAndreas Gohr        if(is_null($comp)) $comp = $len != $clen;
9102b6c6819SAndreas Gohr        $comp = $comp ? 8 : 0;
9112b6c6819SAndreas Gohr        $dtime = dechex($this->makeDosTime($ts));
9122b6c6819SAndreas Gohr
91336113441SAndreas Gohr        list($name, $extra) = $this->encodeFilename($name);
91436113441SAndreas Gohr
9152b6c6819SAndreas Gohr        $header = "\x50\x4b\x01\x02"; // central file header signature
9162b6c6819SAndreas Gohr        $header .= pack('v', 14); // version made by - VFAT
9172b6c6819SAndreas Gohr        $header .= pack('v', 20); // version needed to extract - 2.0
9182b6c6819SAndreas Gohr        $header .= pack('v', 0); // general purpose flag - no flags set
9192b6c6819SAndreas Gohr        $header .= pack('v', $comp); // compression method - deflate|none
9202b6c6819SAndreas Gohr        $header .= pack(
9212b6c6819SAndreas Gohr            'H*',
9222b6c6819SAndreas Gohr            $dtime[6] . $dtime[7] .
9232b6c6819SAndreas Gohr            $dtime[4] . $dtime[5] .
9242b6c6819SAndreas Gohr            $dtime[2] . $dtime[3] .
9252b6c6819SAndreas Gohr            $dtime[0] . $dtime[1]
9262b6c6819SAndreas Gohr        ); //  last mod file time and date
9272b6c6819SAndreas Gohr        $header .= pack('V', $crc); // crc-32
9282b6c6819SAndreas Gohr        $header .= pack('V', $clen); // compressed size
9292b6c6819SAndreas Gohr        $header .= pack('V', $len); // uncompressed size
9302b6c6819SAndreas Gohr        $header .= pack('v', strlen($name)); // file name length
93136113441SAndreas Gohr        $header .= pack('v', strlen($extra)); // extra field length
9322b6c6819SAndreas Gohr        $header .= pack('v', 0); // file comment length
9332b6c6819SAndreas Gohr        $header .= pack('v', 0); // disk number start
9342b6c6819SAndreas Gohr        $header .= pack('v', 0); // internal file attributes
9352b6c6819SAndreas Gohr        $header .= pack('V', 0); // external file attributes  @todo was 0x32!?
9362b6c6819SAndreas Gohr        $header .= pack('V', $offset); // relative offset of local header
9372b6c6819SAndreas Gohr        $header .= $name; // file name
93836113441SAndreas Gohr        $header .= $extra; // extra (utf-8 filename)
9392b6c6819SAndreas Gohr
9402b6c6819SAndreas Gohr        return $header;
9412b6c6819SAndreas Gohr    }
9422b6c6819SAndreas Gohr
9432b6c6819SAndreas Gohr    /**
9442b6c6819SAndreas Gohr     * Returns a local file header for the given data
9452b6c6819SAndreas Gohr     *
9462b6c6819SAndreas Gohr     * @param int $ts unix timestamp
9472b6c6819SAndreas Gohr     * @param int $crc CRC32 checksum of the uncompressed data
9482b6c6819SAndreas Gohr     * @param int $len length of the uncompressed data
9492b6c6819SAndreas Gohr     * @param int $clen length of the compressed data
9502b6c6819SAndreas Gohr     * @param string $name file name
9512b6c6819SAndreas Gohr     * @param boolean|null $comp if compression is used, if null it's determined from $len != $clen
9522b6c6819SAndreas Gohr     * @return string
9532b6c6819SAndreas Gohr     */
9542b6c6819SAndreas Gohr    protected function makeLocalFileHeader($ts, $crc, $len, $clen, $name, $comp = null)
9552b6c6819SAndreas Gohr    {
9562b6c6819SAndreas Gohr        if(is_null($comp)) $comp = $len != $clen;
9572b6c6819SAndreas Gohr        $comp = $comp ? 8 : 0;
9582b6c6819SAndreas Gohr        $dtime = dechex($this->makeDosTime($ts));
9592b6c6819SAndreas Gohr
96036113441SAndreas Gohr        list($name, $extra) = $this->encodeFilename($name);
96136113441SAndreas Gohr
9622b6c6819SAndreas Gohr        $header = "\x50\x4b\x03\x04"; //  local file header signature
9632b6c6819SAndreas Gohr        $header .= pack('v', 20); // version needed to extract - 2.0
9642b6c6819SAndreas Gohr        $header .= pack('v', 0); // general purpose flag - no flags set
9652b6c6819SAndreas Gohr        $header .= pack('v', $comp); // compression method - deflate|none
9662b6c6819SAndreas Gohr        $header .= pack(
9672b6c6819SAndreas Gohr            'H*',
9682b6c6819SAndreas Gohr            $dtime[6] . $dtime[7] .
9692b6c6819SAndreas Gohr            $dtime[4] . $dtime[5] .
9702b6c6819SAndreas Gohr            $dtime[2] . $dtime[3] .
9712b6c6819SAndreas Gohr            $dtime[0] . $dtime[1]
9722b6c6819SAndreas Gohr        ); //  last mod file time and date
9732b6c6819SAndreas Gohr        $header .= pack('V', $crc); // crc-32
9742b6c6819SAndreas Gohr        $header .= pack('V', $clen); // compressed size
9752b6c6819SAndreas Gohr        $header .= pack('V', $len); // uncompressed size
9762b6c6819SAndreas Gohr        $header .= pack('v', strlen($name)); // file name length
97736113441SAndreas Gohr        $header .= pack('v', strlen($extra)); // extra field length
97836113441SAndreas Gohr        $header .= $name; // file name
97936113441SAndreas Gohr        $header .= $extra; // extra (utf-8 filename)
9802b6c6819SAndreas Gohr        return $header;
9812b6c6819SAndreas Gohr    }
98236113441SAndreas Gohr
98336113441SAndreas Gohr    /**
984*2afbbbaeSAndreas Gohr     * Returns only a part of the local file header containing the CRC, size and compressed size.
985*2afbbbaeSAndreas Gohr     * Used to update these fields for an already written header.
986*2afbbbaeSAndreas Gohr     *
987*2afbbbaeSAndreas Gohr     * @param int $crc CRC32 checksum of the uncompressed data
988*2afbbbaeSAndreas Gohr     * @param int $len length of the uncompressed data
989*2afbbbaeSAndreas Gohr     * @param int $clen length of the compressed data
990*2afbbbaeSAndreas Gohr     * @return string
991*2afbbbaeSAndreas Gohr     */
992*2afbbbaeSAndreas Gohr    protected function makeCrcAndSize($crc, $len, $clen) {
993*2afbbbaeSAndreas Gohr        $header  = pack('V', $crc); // crc-32
994*2afbbbaeSAndreas Gohr        $header .= pack('V', $clen); // compressed size
995*2afbbbaeSAndreas Gohr        $header .= pack('V', $len); // uncompressed size
996*2afbbbaeSAndreas Gohr        return $header;
997*2afbbbaeSAndreas Gohr    }
998*2afbbbaeSAndreas Gohr
999*2afbbbaeSAndreas Gohr    /**
100036113441SAndreas Gohr     * Returns an allowed filename and an extra field header
100136113441SAndreas Gohr     *
100236113441SAndreas Gohr     * When encoding stuff outside the 7bit ASCII range it needs to be placed in a separate
100336113441SAndreas Gohr     * extra field
100436113441SAndreas Gohr     *
100536113441SAndreas Gohr     * @param $original
100636113441SAndreas Gohr     * @return array($filename, $extra)
100736113441SAndreas Gohr     */
100836113441SAndreas Gohr    protected function encodeFilename($original)
100936113441SAndreas Gohr    {
101036113441SAndreas Gohr        $cp437 = $this->utf8ToCp($original);
101136113441SAndreas Gohr        if ($cp437 === $original) {
101236113441SAndreas Gohr            return array($original, '');
101336113441SAndreas Gohr        }
101436113441SAndreas Gohr
101536113441SAndreas Gohr        $extra = pack(
101636113441SAndreas Gohr            'vvCV',
101736113441SAndreas Gohr            0x7075, // tag
101836113441SAndreas Gohr            strlen($original) + 5, // length of file + version + crc
101936113441SAndreas Gohr            1, // version
102036113441SAndreas Gohr            crc32($original) // crc
102136113441SAndreas Gohr        );
102236113441SAndreas Gohr        $extra .= $original;
102336113441SAndreas Gohr
102436113441SAndreas Gohr        return array($cp437, $extra);
102536113441SAndreas Gohr    }
1026605f8e8dSAndreas Gohr}
1027