xref: /dokuwiki/vendor/splitbrain/php-archive/src/Tar.php (revision e43cd7e11322648414daef21f777734a2cafc5c8)
1605f8e8dSAndreas Gohr<?php
2605f8e8dSAndreas Gohr
3605f8e8dSAndreas Gohrnamespace splitbrain\PHPArchive;
4605f8e8dSAndreas Gohr
5605f8e8dSAndreas Gohr/**
6605f8e8dSAndreas Gohr * Class Tar
7605f8e8dSAndreas Gohr *
8605f8e8dSAndreas Gohr * Creates or extracts Tar archives. Supports gz and bzip compression
9605f8e8dSAndreas Gohr *
10605f8e8dSAndreas Gohr * Long pathnames (>100 chars) are supported in POSIX ustar and GNU longlink formats.
11605f8e8dSAndreas Gohr *
12605f8e8dSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
13605f8e8dSAndreas Gohr * @package splitbrain\PHPArchive
14605f8e8dSAndreas Gohr * @license MIT
15605f8e8dSAndreas Gohr */
16605f8e8dSAndreas Gohrclass Tar extends Archive
17605f8e8dSAndreas Gohr{
18605f8e8dSAndreas Gohr
19605f8e8dSAndreas Gohr    protected $file = '';
20605f8e8dSAndreas Gohr    protected $comptype = Archive::COMPRESS_AUTO;
21605f8e8dSAndreas Gohr    protected $complevel = 9;
22605f8e8dSAndreas Gohr    protected $fh;
23605f8e8dSAndreas Gohr    protected $memory = '';
24605f8e8dSAndreas Gohr    protected $closed = true;
25605f8e8dSAndreas Gohr    protected $writeaccess = false;
26605f8e8dSAndreas Gohr
27605f8e8dSAndreas Gohr    /**
28605f8e8dSAndreas Gohr     * Sets the compression to use
29605f8e8dSAndreas Gohr     *
30605f8e8dSAndreas Gohr     * @param int $level Compression level (0 to 9)
31605f8e8dSAndreas Gohr     * @param int $type Type of compression to use (use COMPRESS_* constants)
32*e43cd7e1SAndreas Gohr     * @throws ArchiveIllegalCompressionException
33605f8e8dSAndreas Gohr     */
34605f8e8dSAndreas Gohr    public function setCompression($level = 9, $type = Archive::COMPRESS_AUTO)
35605f8e8dSAndreas Gohr    {
36605f8e8dSAndreas Gohr        $this->compressioncheck($type);
37*e43cd7e1SAndreas Gohr        if ($level < -1 || $level > 9) {
38*e43cd7e1SAndreas Gohr            throw new ArchiveIllegalCompressionException('Compression level should be between -1 and 9');
39*e43cd7e1SAndreas Gohr        }
40605f8e8dSAndreas Gohr        $this->comptype  = $type;
41605f8e8dSAndreas Gohr        $this->complevel = $level;
42530d6729SAndreas Gohr        if($level == 0) $this->comptype = Archive::COMPRESS_NONE;
43530d6729SAndreas Gohr        if($type == Archive::COMPRESS_NONE) $this->complevel = 0;
44605f8e8dSAndreas Gohr    }
45605f8e8dSAndreas Gohr
46605f8e8dSAndreas Gohr    /**
47605f8e8dSAndreas Gohr     * Open an existing TAR file for reading
48605f8e8dSAndreas Gohr     *
49605f8e8dSAndreas Gohr     * @param string $file
50605f8e8dSAndreas Gohr     * @throws ArchiveIOException
51*e43cd7e1SAndreas Gohr     * @throws ArchiveIllegalCompressionException
52605f8e8dSAndreas Gohr     */
53605f8e8dSAndreas Gohr    public function open($file)
54605f8e8dSAndreas Gohr    {
55605f8e8dSAndreas Gohr        $this->file = $file;
56605f8e8dSAndreas Gohr
57605f8e8dSAndreas Gohr        // update compression to mach file
58605f8e8dSAndreas Gohr        if ($this->comptype == Tar::COMPRESS_AUTO) {
59605f8e8dSAndreas Gohr            $this->setCompression($this->complevel, $this->filetype($file));
60605f8e8dSAndreas Gohr        }
61605f8e8dSAndreas Gohr
62605f8e8dSAndreas Gohr        // open file handles
63605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_GZIP) {
64605f8e8dSAndreas Gohr            $this->fh = @gzopen($this->file, 'rb');
65605f8e8dSAndreas Gohr        } elseif ($this->comptype === Archive::COMPRESS_BZIP) {
66605f8e8dSAndreas Gohr            $this->fh = @bzopen($this->file, 'r');
67605f8e8dSAndreas Gohr        } else {
68605f8e8dSAndreas Gohr            $this->fh = @fopen($this->file, 'rb');
69605f8e8dSAndreas Gohr        }
70605f8e8dSAndreas Gohr
71605f8e8dSAndreas Gohr        if (!$this->fh) {
72605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not open file for reading: '.$this->file);
73605f8e8dSAndreas Gohr        }
74605f8e8dSAndreas Gohr        $this->closed = false;
75605f8e8dSAndreas Gohr    }
76605f8e8dSAndreas Gohr
77605f8e8dSAndreas Gohr    /**
78605f8e8dSAndreas Gohr     * Read the contents of a TAR archive
79605f8e8dSAndreas Gohr     *
80605f8e8dSAndreas Gohr     * This function lists the files stored in the archive
81605f8e8dSAndreas Gohr     *
82605f8e8dSAndreas Gohr     * The archive is closed afer reading the contents, because rewinding is not possible in bzip2 streams.
83605f8e8dSAndreas Gohr     * Reopen the file with open() again if you want to do additional operations
84605f8e8dSAndreas Gohr     *
85605f8e8dSAndreas Gohr     * @throws ArchiveIOException
86*e43cd7e1SAndreas Gohr     * @throws ArchiveCorruptedException
87605f8e8dSAndreas Gohr     * @returns FileInfo[]
88605f8e8dSAndreas Gohr     */
89605f8e8dSAndreas Gohr    public function contents()
90605f8e8dSAndreas Gohr    {
91605f8e8dSAndreas Gohr        if ($this->closed || !$this->file) {
92605f8e8dSAndreas Gohr            throw new ArchiveIOException('Can not read from a closed archive');
93605f8e8dSAndreas Gohr        }
94605f8e8dSAndreas Gohr
95605f8e8dSAndreas Gohr        $result = array();
96605f8e8dSAndreas Gohr        while ($read = $this->readbytes(512)) {
97605f8e8dSAndreas Gohr            $header = $this->parseHeader($read);
98605f8e8dSAndreas Gohr            if (!is_array($header)) {
99605f8e8dSAndreas Gohr                continue;
100605f8e8dSAndreas Gohr            }
101605f8e8dSAndreas Gohr
102605f8e8dSAndreas Gohr            $this->skipbytes(ceil($header['size'] / 512) * 512);
103605f8e8dSAndreas Gohr            $result[] = $this->header2fileinfo($header);
104605f8e8dSAndreas Gohr        }
105605f8e8dSAndreas Gohr
106605f8e8dSAndreas Gohr        $this->close();
107605f8e8dSAndreas Gohr        return $result;
108605f8e8dSAndreas Gohr    }
109605f8e8dSAndreas Gohr
110605f8e8dSAndreas Gohr    /**
111605f8e8dSAndreas Gohr     * Extract an existing TAR archive
112605f8e8dSAndreas Gohr     *
113605f8e8dSAndreas Gohr     * The $strip parameter allows you to strip a certain number of path components from the filenames
114605f8e8dSAndreas Gohr     * found in the tar file, similar to the --strip-components feature of GNU tar. This is triggered when
115605f8e8dSAndreas Gohr     * an integer is passed as $strip.
116605f8e8dSAndreas Gohr     * Alternatively a fixed string prefix may be passed in $strip. If the filename matches this prefix,
117605f8e8dSAndreas Gohr     * the prefix will be stripped. It is recommended to give prefixes with a trailing slash.
118605f8e8dSAndreas Gohr     *
119605f8e8dSAndreas Gohr     * By default this will extract all files found in the archive. You can restrict the output using the $include
120605f8e8dSAndreas Gohr     * and $exclude parameter. Both expect a full regular expression (including delimiters and modifiers). If
121605f8e8dSAndreas Gohr     * $include is set only files that match this expression will be extracted. Files that match the $exclude
122605f8e8dSAndreas Gohr     * expression will never be extracted. Both parameters can be used in combination. Expressions are matched against
123605f8e8dSAndreas Gohr     * stripped filenames as described above.
124605f8e8dSAndreas Gohr     *
125605f8e8dSAndreas Gohr     * The archive is closed afer reading the contents, because rewinding is not possible in bzip2 streams.
126605f8e8dSAndreas Gohr     * Reopen the file with open() again if you want to do additional operations
127605f8e8dSAndreas Gohr     *
128605f8e8dSAndreas Gohr     * @param string $outdir the target directory for extracting
129605f8e8dSAndreas Gohr     * @param int|string $strip either the number of path components or a fixed prefix to strip
130605f8e8dSAndreas Gohr     * @param string $exclude a regular expression of files to exclude
131605f8e8dSAndreas Gohr     * @param string $include a regular expression of files to include
132605f8e8dSAndreas Gohr     * @throws ArchiveIOException
133*e43cd7e1SAndreas Gohr     * @throws ArchiveCorruptedException
134605f8e8dSAndreas Gohr     * @return FileInfo[]
135605f8e8dSAndreas Gohr     */
136605f8e8dSAndreas Gohr    public function extract($outdir, $strip = '', $exclude = '', $include = '')
137605f8e8dSAndreas Gohr    {
138605f8e8dSAndreas Gohr        if ($this->closed || !$this->file) {
139605f8e8dSAndreas Gohr            throw new ArchiveIOException('Can not read from a closed archive');
140605f8e8dSAndreas Gohr        }
141605f8e8dSAndreas Gohr
142605f8e8dSAndreas Gohr        $outdir = rtrim($outdir, '/');
143605f8e8dSAndreas Gohr        @mkdir($outdir, 0777, true);
144605f8e8dSAndreas Gohr        if (!is_dir($outdir)) {
145605f8e8dSAndreas Gohr            throw new ArchiveIOException("Could not create directory '$outdir'");
146605f8e8dSAndreas Gohr        }
147605f8e8dSAndreas Gohr
148605f8e8dSAndreas Gohr        $extracted = array();
149605f8e8dSAndreas Gohr        while ($dat = $this->readbytes(512)) {
150605f8e8dSAndreas Gohr            // read the file header
151605f8e8dSAndreas Gohr            $header = $this->parseHeader($dat);
152605f8e8dSAndreas Gohr            if (!is_array($header)) {
153605f8e8dSAndreas Gohr                continue;
154605f8e8dSAndreas Gohr            }
155605f8e8dSAndreas Gohr            $fileinfo = $this->header2fileinfo($header);
156605f8e8dSAndreas Gohr
157605f8e8dSAndreas Gohr            // apply strip rules
158605f8e8dSAndreas Gohr            $fileinfo->strip($strip);
159605f8e8dSAndreas Gohr
160605f8e8dSAndreas Gohr            // skip unwanted files
161605f8e8dSAndreas Gohr            if (!strlen($fileinfo->getPath()) || !$fileinfo->match($include, $exclude)) {
162605f8e8dSAndreas Gohr                $this->skipbytes(ceil($header['size'] / 512) * 512);
163605f8e8dSAndreas Gohr                continue;
164605f8e8dSAndreas Gohr            }
165605f8e8dSAndreas Gohr
166605f8e8dSAndreas Gohr            // create output directory
167605f8e8dSAndreas Gohr            $output    = $outdir.'/'.$fileinfo->getPath();
168605f8e8dSAndreas Gohr            $directory = ($fileinfo->getIsdir()) ? $output : dirname($output);
169605f8e8dSAndreas Gohr            @mkdir($directory, 0777, true);
170605f8e8dSAndreas Gohr
171605f8e8dSAndreas Gohr            // extract data
172605f8e8dSAndreas Gohr            if (!$fileinfo->getIsdir()) {
173ddb94cf0SAndreas Gohr                $fp = @fopen($output, "wb");
174605f8e8dSAndreas Gohr                if (!$fp) {
175605f8e8dSAndreas Gohr                    throw new ArchiveIOException('Could not open file for writing: '.$output);
176605f8e8dSAndreas Gohr                }
177605f8e8dSAndreas Gohr
178605f8e8dSAndreas Gohr                $size = floor($header['size'] / 512);
179605f8e8dSAndreas Gohr                for ($i = 0; $i < $size; $i++) {
180605f8e8dSAndreas Gohr                    fwrite($fp, $this->readbytes(512), 512);
181605f8e8dSAndreas Gohr                }
182605f8e8dSAndreas Gohr                if (($header['size'] % 512) != 0) {
183605f8e8dSAndreas Gohr                    fwrite($fp, $this->readbytes(512), $header['size'] % 512);
184605f8e8dSAndreas Gohr                }
185605f8e8dSAndreas Gohr
186605f8e8dSAndreas Gohr                fclose($fp);
187*e43cd7e1SAndreas Gohr                @touch($output, $fileinfo->getMtime());
188*e43cd7e1SAndreas Gohr                @chmod($output, $fileinfo->getMode());
189605f8e8dSAndreas Gohr            } else {
190605f8e8dSAndreas Gohr                $this->skipbytes(ceil($header['size'] / 512) * 512); // the size is usually 0 for directories
191605f8e8dSAndreas Gohr            }
192605f8e8dSAndreas Gohr
193*e43cd7e1SAndreas Gohr            if(is_callable($this->callback)) {
194*e43cd7e1SAndreas Gohr                call_user_func($this->callback, $fileinfo);
195*e43cd7e1SAndreas Gohr            }
196605f8e8dSAndreas Gohr            $extracted[] = $fileinfo;
197605f8e8dSAndreas Gohr        }
198605f8e8dSAndreas Gohr
199605f8e8dSAndreas Gohr        $this->close();
200605f8e8dSAndreas Gohr        return $extracted;
201605f8e8dSAndreas Gohr    }
202605f8e8dSAndreas Gohr
203605f8e8dSAndreas Gohr    /**
204605f8e8dSAndreas Gohr     * Create a new TAR file
205605f8e8dSAndreas Gohr     *
206605f8e8dSAndreas Gohr     * If $file is empty, the tar file will be created in memory
207605f8e8dSAndreas Gohr     *
208605f8e8dSAndreas Gohr     * @param string $file
209605f8e8dSAndreas Gohr     * @throws ArchiveIOException
210*e43cd7e1SAndreas Gohr     * @throws ArchiveIllegalCompressionException
211605f8e8dSAndreas Gohr     */
212605f8e8dSAndreas Gohr    public function create($file = '')
213605f8e8dSAndreas Gohr    {
214605f8e8dSAndreas Gohr        $this->file   = $file;
215605f8e8dSAndreas Gohr        $this->memory = '';
216605f8e8dSAndreas Gohr        $this->fh     = 0;
217605f8e8dSAndreas Gohr
218605f8e8dSAndreas Gohr        if ($this->file) {
219605f8e8dSAndreas Gohr            // determine compression
220605f8e8dSAndreas Gohr            if ($this->comptype == Archive::COMPRESS_AUTO) {
221605f8e8dSAndreas Gohr                $this->setCompression($this->complevel, $this->filetype($file));
222605f8e8dSAndreas Gohr            }
223605f8e8dSAndreas Gohr
224605f8e8dSAndreas Gohr            if ($this->comptype === Archive::COMPRESS_GZIP) {
225605f8e8dSAndreas Gohr                $this->fh = @gzopen($this->file, 'wb'.$this->complevel);
226605f8e8dSAndreas Gohr            } elseif ($this->comptype === Archive::COMPRESS_BZIP) {
227605f8e8dSAndreas Gohr                $this->fh = @bzopen($this->file, 'w');
228605f8e8dSAndreas Gohr            } else {
229605f8e8dSAndreas Gohr                $this->fh = @fopen($this->file, 'wb');
230605f8e8dSAndreas Gohr            }
231605f8e8dSAndreas Gohr
232605f8e8dSAndreas Gohr            if (!$this->fh) {
233605f8e8dSAndreas Gohr                throw new ArchiveIOException('Could not open file for writing: '.$this->file);
234605f8e8dSAndreas Gohr            }
235605f8e8dSAndreas Gohr        }
236605f8e8dSAndreas Gohr        $this->writeaccess = true;
237605f8e8dSAndreas Gohr        $this->closed      = false;
238605f8e8dSAndreas Gohr    }
239605f8e8dSAndreas Gohr
240605f8e8dSAndreas Gohr    /**
241605f8e8dSAndreas Gohr     * Add a file to the current TAR archive using an existing file in the filesystem
242605f8e8dSAndreas Gohr     *
243605f8e8dSAndreas Gohr     * @param string $file path to the original file
244605f8e8dSAndreas 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
24536113441SAndreas Gohr     * @throws ArchiveCorruptedException when the file changes while reading it, the archive will be corrupt and should be deleted
24636113441SAndreas Gohr     * @throws ArchiveIOException there was trouble reading the given file, it was not added
247*e43cd7e1SAndreas Gohr     * @throws FileInfoException trouble reading file info, it was not added
248605f8e8dSAndreas Gohr     */
249605f8e8dSAndreas Gohr    public function addFile($file, $fileinfo = '')
250605f8e8dSAndreas Gohr    {
251605f8e8dSAndreas Gohr        if (is_string($fileinfo)) {
252605f8e8dSAndreas Gohr            $fileinfo = FileInfo::fromPath($file, $fileinfo);
253605f8e8dSAndreas Gohr        }
254605f8e8dSAndreas Gohr
255605f8e8dSAndreas Gohr        if ($this->closed) {
256605f8e8dSAndreas Gohr            throw new ArchiveIOException('Archive has been closed, files can no longer be added');
257605f8e8dSAndreas Gohr        }
258605f8e8dSAndreas Gohr
259ddb94cf0SAndreas Gohr        $fp = @fopen($file, 'rb');
260605f8e8dSAndreas Gohr        if (!$fp) {
261605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not open file for reading: '.$file);
262605f8e8dSAndreas Gohr        }
263605f8e8dSAndreas Gohr
264605f8e8dSAndreas Gohr        // create file header
265605f8e8dSAndreas Gohr        $this->writeFileHeader($fileinfo);
266605f8e8dSAndreas Gohr
267605f8e8dSAndreas Gohr        // write data
26836113441SAndreas Gohr        $read = 0;
269605f8e8dSAndreas Gohr        while (!feof($fp)) {
270605f8e8dSAndreas Gohr            $data = fread($fp, 512);
27136113441SAndreas Gohr            $read += strlen($data);
272605f8e8dSAndreas Gohr            if ($data === false) {
273605f8e8dSAndreas Gohr                break;
274605f8e8dSAndreas Gohr            }
275605f8e8dSAndreas Gohr            if ($data === '') {
276605f8e8dSAndreas Gohr                break;
277605f8e8dSAndreas Gohr            }
278605f8e8dSAndreas Gohr            $packed = pack("a512", $data);
279605f8e8dSAndreas Gohr            $this->writebytes($packed);
280605f8e8dSAndreas Gohr        }
281605f8e8dSAndreas Gohr        fclose($fp);
28236113441SAndreas Gohr
28336113441SAndreas Gohr        if($read != $fileinfo->getSize()) {
28436113441SAndreas Gohr            $this->close();
28536113441SAndreas Gohr            throw new ArchiveCorruptedException("The size of $file changed while reading, archive corrupted. read $read expected ".$fileinfo->getSize());
28636113441SAndreas Gohr        }
287*e43cd7e1SAndreas Gohr
288*e43cd7e1SAndreas Gohr        if(is_callable($this->callback)) {
289*e43cd7e1SAndreas Gohr            call_user_func($this->callback, $fileinfo);
290*e43cd7e1SAndreas Gohr        }
291605f8e8dSAndreas Gohr    }
292605f8e8dSAndreas Gohr
293605f8e8dSAndreas Gohr    /**
294605f8e8dSAndreas Gohr     * Add a file to the current TAR archive using the given $data as content
295605f8e8dSAndreas Gohr     *
296605f8e8dSAndreas Gohr     * @param string|FileInfo $fileinfo either the name to us in archive (string) or a FileInfo oject with all meta data
297605f8e8dSAndreas Gohr     * @param string          $data     binary content of the file to add
298605f8e8dSAndreas Gohr     * @throws ArchiveIOException
299605f8e8dSAndreas Gohr     */
300605f8e8dSAndreas Gohr    public function addData($fileinfo, $data)
301605f8e8dSAndreas Gohr    {
302605f8e8dSAndreas Gohr        if (is_string($fileinfo)) {
303605f8e8dSAndreas Gohr            $fileinfo = new FileInfo($fileinfo);
304605f8e8dSAndreas Gohr        }
305605f8e8dSAndreas Gohr
306605f8e8dSAndreas Gohr        if ($this->closed) {
307605f8e8dSAndreas Gohr            throw new ArchiveIOException('Archive has been closed, files can no longer be added');
308605f8e8dSAndreas Gohr        }
309605f8e8dSAndreas Gohr
310605f8e8dSAndreas Gohr        $len = strlen($data);
311605f8e8dSAndreas Gohr        $fileinfo->setSize($len);
312605f8e8dSAndreas Gohr        $this->writeFileHeader($fileinfo);
313605f8e8dSAndreas Gohr
314605f8e8dSAndreas Gohr        for ($s = 0; $s < $len; $s += 512) {
315605f8e8dSAndreas Gohr            $this->writebytes(pack("a512", substr($data, $s, 512)));
316605f8e8dSAndreas Gohr        }
317*e43cd7e1SAndreas Gohr
318*e43cd7e1SAndreas Gohr        if (is_callable($this->callback)) {
319*e43cd7e1SAndreas Gohr            call_user_func($this->callback, $fileinfo);
320*e43cd7e1SAndreas Gohr        }
321605f8e8dSAndreas Gohr    }
322605f8e8dSAndreas Gohr
323605f8e8dSAndreas Gohr    /**
324605f8e8dSAndreas Gohr     * Add the closing footer to the archive if in write mode, close all file handles
325605f8e8dSAndreas Gohr     *
326605f8e8dSAndreas Gohr     * After a call to this function no more data can be added to the archive, for
327605f8e8dSAndreas Gohr     * read access no reading is allowed anymore
328605f8e8dSAndreas Gohr     *
329605f8e8dSAndreas Gohr     * "Physically, an archive consists of a series of file entries terminated by an end-of-archive entry, which
330605f8e8dSAndreas Gohr     * consists of two 512 blocks of zero bytes"
331605f8e8dSAndreas Gohr     *
332605f8e8dSAndreas Gohr     * @link http://www.gnu.org/software/tar/manual/html_chapter/tar_8.html#SEC134
333*e43cd7e1SAndreas Gohr     * @throws ArchiveIOException
334605f8e8dSAndreas Gohr     */
335605f8e8dSAndreas Gohr    public function close()
336605f8e8dSAndreas Gohr    {
337605f8e8dSAndreas Gohr        if ($this->closed) {
338605f8e8dSAndreas Gohr            return;
339605f8e8dSAndreas Gohr        } // we did this already
340605f8e8dSAndreas Gohr
341605f8e8dSAndreas Gohr        // write footer
342605f8e8dSAndreas Gohr        if ($this->writeaccess) {
343605f8e8dSAndreas Gohr            $this->writebytes(pack("a512", ""));
344605f8e8dSAndreas Gohr            $this->writebytes(pack("a512", ""));
345605f8e8dSAndreas Gohr        }
346605f8e8dSAndreas Gohr
347605f8e8dSAndreas Gohr        // close file handles
348605f8e8dSAndreas Gohr        if ($this->file) {
349605f8e8dSAndreas Gohr            if ($this->comptype === Archive::COMPRESS_GZIP) {
350605f8e8dSAndreas Gohr                gzclose($this->fh);
351605f8e8dSAndreas Gohr            } elseif ($this->comptype === Archive::COMPRESS_BZIP) {
352605f8e8dSAndreas Gohr                bzclose($this->fh);
353605f8e8dSAndreas Gohr            } else {
354605f8e8dSAndreas Gohr                fclose($this->fh);
355605f8e8dSAndreas Gohr            }
356605f8e8dSAndreas Gohr
357605f8e8dSAndreas Gohr            $this->file = '';
358605f8e8dSAndreas Gohr            $this->fh   = 0;
359605f8e8dSAndreas Gohr        }
360605f8e8dSAndreas Gohr
361605f8e8dSAndreas Gohr        $this->writeaccess = false;
362605f8e8dSAndreas Gohr        $this->closed      = true;
363605f8e8dSAndreas Gohr    }
364605f8e8dSAndreas Gohr
365605f8e8dSAndreas Gohr    /**
366605f8e8dSAndreas Gohr     * Returns the created in-memory archive data
367605f8e8dSAndreas Gohr     *
368605f8e8dSAndreas Gohr     * This implicitly calls close() on the Archive
369*e43cd7e1SAndreas Gohr     * @throws ArchiveIOException
370605f8e8dSAndreas Gohr     */
371605f8e8dSAndreas Gohr    public function getArchive()
372605f8e8dSAndreas Gohr    {
373605f8e8dSAndreas Gohr        $this->close();
374605f8e8dSAndreas Gohr
375605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_AUTO) {
376605f8e8dSAndreas Gohr            $this->comptype = Archive::COMPRESS_NONE;
377605f8e8dSAndreas Gohr        }
378605f8e8dSAndreas Gohr
379605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_GZIP) {
380dd7064d9SAndreas Gohr            return gzencode($this->memory, $this->complevel);
381605f8e8dSAndreas Gohr        }
382605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_BZIP) {
383605f8e8dSAndreas Gohr            return bzcompress($this->memory);
384605f8e8dSAndreas Gohr        }
385605f8e8dSAndreas Gohr        return $this->memory;
386605f8e8dSAndreas Gohr    }
387605f8e8dSAndreas Gohr
388605f8e8dSAndreas Gohr    /**
389605f8e8dSAndreas Gohr     * Save the created in-memory archive data
390605f8e8dSAndreas Gohr     *
391605f8e8dSAndreas Gohr     * Note: It more memory effective to specify the filename in the create() function and
392605f8e8dSAndreas Gohr     * let the library work on the new file directly.
393605f8e8dSAndreas Gohr     *
394605f8e8dSAndreas Gohr     * @param string $file
395605f8e8dSAndreas Gohr     * @throws ArchiveIOException
396*e43cd7e1SAndreas Gohr     * @throws ArchiveIllegalCompressionException
397605f8e8dSAndreas Gohr     */
398605f8e8dSAndreas Gohr    public function save($file)
399605f8e8dSAndreas Gohr    {
400605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_AUTO) {
401530d6729SAndreas Gohr            $this->setCompression($this->complevel, $this->filetype($file));
402605f8e8dSAndreas Gohr        }
403605f8e8dSAndreas Gohr
404ddb94cf0SAndreas Gohr        if (!@file_put_contents($file, $this->getArchive())) {
405605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not write to file: '.$file);
406605f8e8dSAndreas Gohr        }
407605f8e8dSAndreas Gohr    }
408605f8e8dSAndreas Gohr
409605f8e8dSAndreas Gohr    /**
410605f8e8dSAndreas Gohr     * Read from the open file pointer
411605f8e8dSAndreas Gohr     *
412605f8e8dSAndreas Gohr     * @param int $length bytes to read
413605f8e8dSAndreas Gohr     * @return string
414605f8e8dSAndreas Gohr     */
415605f8e8dSAndreas Gohr    protected function readbytes($length)
416605f8e8dSAndreas Gohr    {
417605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_GZIP) {
418605f8e8dSAndreas Gohr            return @gzread($this->fh, $length);
419605f8e8dSAndreas Gohr        } elseif ($this->comptype === Archive::COMPRESS_BZIP) {
420605f8e8dSAndreas Gohr            return @bzread($this->fh, $length);
421605f8e8dSAndreas Gohr        } else {
422605f8e8dSAndreas Gohr            return @fread($this->fh, $length);
423605f8e8dSAndreas Gohr        }
424605f8e8dSAndreas Gohr    }
425605f8e8dSAndreas Gohr
426605f8e8dSAndreas Gohr    /**
427605f8e8dSAndreas Gohr     * Write to the open filepointer or memory
428605f8e8dSAndreas Gohr     *
429605f8e8dSAndreas Gohr     * @param string $data
430605f8e8dSAndreas Gohr     * @throws ArchiveIOException
431605f8e8dSAndreas Gohr     * @return int number of bytes written
432605f8e8dSAndreas Gohr     */
433605f8e8dSAndreas Gohr    protected function writebytes($data)
434605f8e8dSAndreas Gohr    {
435605f8e8dSAndreas Gohr        if (!$this->file) {
436605f8e8dSAndreas Gohr            $this->memory .= $data;
437605f8e8dSAndreas Gohr            $written = strlen($data);
438605f8e8dSAndreas Gohr        } elseif ($this->comptype === Archive::COMPRESS_GZIP) {
439605f8e8dSAndreas Gohr            $written = @gzwrite($this->fh, $data);
440605f8e8dSAndreas Gohr        } elseif ($this->comptype === Archive::COMPRESS_BZIP) {
441605f8e8dSAndreas Gohr            $written = @bzwrite($this->fh, $data);
442605f8e8dSAndreas Gohr        } else {
443605f8e8dSAndreas Gohr            $written = @fwrite($this->fh, $data);
444605f8e8dSAndreas Gohr        }
445605f8e8dSAndreas Gohr        if ($written === false) {
446605f8e8dSAndreas Gohr            throw new ArchiveIOException('Failed to write to archive stream');
447605f8e8dSAndreas Gohr        }
448605f8e8dSAndreas Gohr        return $written;
449605f8e8dSAndreas Gohr    }
450605f8e8dSAndreas Gohr
451605f8e8dSAndreas Gohr    /**
452605f8e8dSAndreas Gohr     * Skip forward in the open file pointer
453605f8e8dSAndreas Gohr     *
454605f8e8dSAndreas Gohr     * This is basically a wrapper around seek() (and a workaround for bzip2)
455605f8e8dSAndreas Gohr     *
456605f8e8dSAndreas Gohr     * @param int $bytes seek to this position
457605f8e8dSAndreas Gohr     */
458ddb94cf0SAndreas Gohr    protected function skipbytes($bytes)
459605f8e8dSAndreas Gohr    {
460605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_GZIP) {
461605f8e8dSAndreas Gohr            @gzseek($this->fh, $bytes, SEEK_CUR);
462605f8e8dSAndreas Gohr        } elseif ($this->comptype === Archive::COMPRESS_BZIP) {
463605f8e8dSAndreas Gohr            // there is no seek in bzip2, we simply read on
464530d6729SAndreas Gohr            // bzread allows to read a max of 8kb at once
465530d6729SAndreas Gohr            while($bytes) {
466530d6729SAndreas Gohr                $toread = min(8192, $bytes);
467530d6729SAndreas Gohr                @bzread($this->fh, $toread);
468530d6729SAndreas Gohr                $bytes -= $toread;
469530d6729SAndreas Gohr            }
470605f8e8dSAndreas Gohr        } else {
471605f8e8dSAndreas Gohr            @fseek($this->fh, $bytes, SEEK_CUR);
472605f8e8dSAndreas Gohr        }
473605f8e8dSAndreas Gohr    }
474605f8e8dSAndreas Gohr
475605f8e8dSAndreas Gohr    /**
476*e43cd7e1SAndreas Gohr     * Write the given file meta data as header
477605f8e8dSAndreas Gohr     *
478605f8e8dSAndreas Gohr     * @param FileInfo $fileinfo
479*e43cd7e1SAndreas Gohr     * @throws ArchiveIOException
480605f8e8dSAndreas Gohr     */
481605f8e8dSAndreas Gohr    protected function writeFileHeader(FileInfo $fileinfo)
482605f8e8dSAndreas Gohr    {
483605f8e8dSAndreas Gohr        $this->writeRawFileHeader(
484605f8e8dSAndreas Gohr            $fileinfo->getPath(),
485605f8e8dSAndreas Gohr            $fileinfo->getUid(),
486605f8e8dSAndreas Gohr            $fileinfo->getGid(),
487605f8e8dSAndreas Gohr            $fileinfo->getMode(),
488605f8e8dSAndreas Gohr            $fileinfo->getSize(),
489605f8e8dSAndreas Gohr            $fileinfo->getMtime(),
490605f8e8dSAndreas Gohr            $fileinfo->getIsdir() ? '5' : '0'
491605f8e8dSAndreas Gohr        );
492605f8e8dSAndreas Gohr    }
493605f8e8dSAndreas Gohr
494605f8e8dSAndreas Gohr    /**
495605f8e8dSAndreas Gohr     * Write a file header to the stream
496605f8e8dSAndreas Gohr     *
497605f8e8dSAndreas Gohr     * @param string $name
498605f8e8dSAndreas Gohr     * @param int $uid
499605f8e8dSAndreas Gohr     * @param int $gid
500605f8e8dSAndreas Gohr     * @param int $perm
501605f8e8dSAndreas Gohr     * @param int $size
502605f8e8dSAndreas Gohr     * @param int $mtime
503605f8e8dSAndreas Gohr     * @param string $typeflag Set to '5' for directories
504*e43cd7e1SAndreas Gohr     * @throws ArchiveIOException
505605f8e8dSAndreas Gohr     */
506605f8e8dSAndreas Gohr    protected function writeRawFileHeader($name, $uid, $gid, $perm, $size, $mtime, $typeflag = '')
507605f8e8dSAndreas Gohr    {
508605f8e8dSAndreas Gohr        // handle filename length restrictions
509605f8e8dSAndreas Gohr        $prefix  = '';
510605f8e8dSAndreas Gohr        $namelen = strlen($name);
511605f8e8dSAndreas Gohr        if ($namelen > 100) {
512605f8e8dSAndreas Gohr            $file = basename($name);
513605f8e8dSAndreas Gohr            $dir  = dirname($name);
514605f8e8dSAndreas Gohr            if (strlen($file) > 100 || strlen($dir) > 155) {
515605f8e8dSAndreas Gohr                // we're still too large, let's use GNU longlink
516605f8e8dSAndreas Gohr                $this->writeRawFileHeader('././@LongLink', 0, 0, 0, $namelen, 0, 'L');
517605f8e8dSAndreas Gohr                for ($s = 0; $s < $namelen; $s += 512) {
518605f8e8dSAndreas Gohr                    $this->writebytes(pack("a512", substr($name, $s, 512)));
519605f8e8dSAndreas Gohr                }
520605f8e8dSAndreas Gohr                $name = substr($name, 0, 100); // cut off name
521605f8e8dSAndreas Gohr            } else {
522605f8e8dSAndreas Gohr                // we're fine when splitting, use POSIX ustar
523605f8e8dSAndreas Gohr                $prefix = $dir;
524605f8e8dSAndreas Gohr                $name   = $file;
525605f8e8dSAndreas Gohr            }
526605f8e8dSAndreas Gohr        }
527605f8e8dSAndreas Gohr
528605f8e8dSAndreas Gohr        // values are needed in octal
529605f8e8dSAndreas Gohr        $uid   = sprintf("%6s ", decoct($uid));
530605f8e8dSAndreas Gohr        $gid   = sprintf("%6s ", decoct($gid));
531605f8e8dSAndreas Gohr        $perm  = sprintf("%6s ", decoct($perm));
532605f8e8dSAndreas Gohr        $size  = sprintf("%11s ", decoct($size));
533605f8e8dSAndreas Gohr        $mtime = sprintf("%11s", decoct($mtime));
534605f8e8dSAndreas Gohr
535605f8e8dSAndreas Gohr        $data_first = pack("a100a8a8a8a12A12", $name, $perm, $uid, $gid, $size, $mtime);
536605f8e8dSAndreas Gohr        $data_last  = pack("a1a100a6a2a32a32a8a8a155a12", $typeflag, '', 'ustar', '', '', '', '', '', $prefix, "");
537605f8e8dSAndreas Gohr
538605f8e8dSAndreas Gohr        for ($i = 0, $chks = 0; $i < 148; $i++) {
539605f8e8dSAndreas Gohr            $chks += ord($data_first[$i]);
540605f8e8dSAndreas Gohr        }
541605f8e8dSAndreas Gohr
542605f8e8dSAndreas Gohr        for ($i = 156, $chks += 256, $j = 0; $i < 512; $i++, $j++) {
543605f8e8dSAndreas Gohr            $chks += ord($data_last[$j]);
544605f8e8dSAndreas Gohr        }
545605f8e8dSAndreas Gohr
546605f8e8dSAndreas Gohr        $this->writebytes($data_first);
547605f8e8dSAndreas Gohr
548605f8e8dSAndreas Gohr        $chks = pack("a8", sprintf("%6s ", decoct($chks)));
549605f8e8dSAndreas Gohr        $this->writebytes($chks.$data_last);
550605f8e8dSAndreas Gohr    }
551605f8e8dSAndreas Gohr
552605f8e8dSAndreas Gohr    /**
553605f8e8dSAndreas Gohr     * Decode the given tar file header
554605f8e8dSAndreas Gohr     *
555530d6729SAndreas Gohr     * @param string $block a 512 byte block containing the header data
556530d6729SAndreas Gohr     * @return array|false returns false when this was a null block
557530d6729SAndreas Gohr     * @throws ArchiveCorruptedException
558605f8e8dSAndreas Gohr     */
559605f8e8dSAndreas Gohr    protected function parseHeader($block)
560605f8e8dSAndreas Gohr    {
561605f8e8dSAndreas Gohr        if (!$block || strlen($block) != 512) {
562530d6729SAndreas Gohr            throw new ArchiveCorruptedException('Unexpected length of header');
563605f8e8dSAndreas Gohr        }
564605f8e8dSAndreas Gohr
565530d6729SAndreas Gohr        // null byte blocks are ignored
566530d6729SAndreas Gohr        if(trim($block) === '') return false;
567530d6729SAndreas Gohr
568605f8e8dSAndreas Gohr        for ($i = 0, $chks = 0; $i < 148; $i++) {
569605f8e8dSAndreas Gohr            $chks += ord($block[$i]);
570605f8e8dSAndreas Gohr        }
571605f8e8dSAndreas Gohr
572605f8e8dSAndreas Gohr        for ($i = 156, $chks += 256; $i < 512; $i++) {
573605f8e8dSAndreas Gohr            $chks += ord($block[$i]);
574605f8e8dSAndreas Gohr        }
575605f8e8dSAndreas Gohr
576605f8e8dSAndreas Gohr        $header = @unpack(
577605f8e8dSAndreas Gohr            "a100filename/a8perm/a8uid/a8gid/a12size/a12mtime/a8checksum/a1typeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor/a155prefix",
578605f8e8dSAndreas Gohr            $block
579605f8e8dSAndreas Gohr        );
580605f8e8dSAndreas Gohr        if (!$header) {
581530d6729SAndreas Gohr            throw new ArchiveCorruptedException('Failed to parse header');
582605f8e8dSAndreas Gohr        }
583605f8e8dSAndreas Gohr
584605f8e8dSAndreas Gohr        $return['checksum'] = OctDec(trim($header['checksum']));
585605f8e8dSAndreas Gohr        if ($return['checksum'] != $chks) {
586530d6729SAndreas Gohr            throw new ArchiveCorruptedException('Header does not match it\'s checksum');
587605f8e8dSAndreas Gohr        }
588605f8e8dSAndreas Gohr
589605f8e8dSAndreas Gohr        $return['filename'] = trim($header['filename']);
590605f8e8dSAndreas Gohr        $return['perm']     = OctDec(trim($header['perm']));
591605f8e8dSAndreas Gohr        $return['uid']      = OctDec(trim($header['uid']));
592605f8e8dSAndreas Gohr        $return['gid']      = OctDec(trim($header['gid']));
593605f8e8dSAndreas Gohr        $return['size']     = OctDec(trim($header['size']));
594605f8e8dSAndreas Gohr        $return['mtime']    = OctDec(trim($header['mtime']));
595605f8e8dSAndreas Gohr        $return['typeflag'] = $header['typeflag'];
596605f8e8dSAndreas Gohr        $return['link']     = trim($header['link']);
597605f8e8dSAndreas Gohr        $return['uname']    = trim($header['uname']);
598605f8e8dSAndreas Gohr        $return['gname']    = trim($header['gname']);
599605f8e8dSAndreas Gohr
600605f8e8dSAndreas Gohr        // Handle ustar Posix compliant path prefixes
601605f8e8dSAndreas Gohr        if (trim($header['prefix'])) {
602605f8e8dSAndreas Gohr            $return['filename'] = trim($header['prefix']).'/'.$return['filename'];
603605f8e8dSAndreas Gohr        }
604605f8e8dSAndreas Gohr
605605f8e8dSAndreas Gohr        // Handle Long-Link entries from GNU Tar
606605f8e8dSAndreas Gohr        if ($return['typeflag'] == 'L') {
607605f8e8dSAndreas Gohr            // following data block(s) is the filename
60836113441SAndreas Gohr            $filename = trim($this->readbytes(ceil($return['size'] / 512) * 512));
609605f8e8dSAndreas Gohr            // next block is the real header
610605f8e8dSAndreas Gohr            $block  = $this->readbytes(512);
611605f8e8dSAndreas Gohr            $return = $this->parseHeader($block);
612605f8e8dSAndreas Gohr            // overwrite the filename
613605f8e8dSAndreas Gohr            $return['filename'] = $filename;
614605f8e8dSAndreas Gohr        }
615605f8e8dSAndreas Gohr
616605f8e8dSAndreas Gohr        return $return;
617605f8e8dSAndreas Gohr    }
618605f8e8dSAndreas Gohr
619605f8e8dSAndreas Gohr    /**
620605f8e8dSAndreas Gohr     * Creates a FileInfo object from the given parsed header
621605f8e8dSAndreas Gohr     *
622605f8e8dSAndreas Gohr     * @param $header
623605f8e8dSAndreas Gohr     * @return FileInfo
624605f8e8dSAndreas Gohr     */
625605f8e8dSAndreas Gohr    protected function header2fileinfo($header)
626605f8e8dSAndreas Gohr    {
627605f8e8dSAndreas Gohr        $fileinfo = new FileInfo();
628605f8e8dSAndreas Gohr        $fileinfo->setPath($header['filename']);
629605f8e8dSAndreas Gohr        $fileinfo->setMode($header['perm']);
630605f8e8dSAndreas Gohr        $fileinfo->setUid($header['uid']);
631605f8e8dSAndreas Gohr        $fileinfo->setGid($header['gid']);
632605f8e8dSAndreas Gohr        $fileinfo->setSize($header['size']);
633605f8e8dSAndreas Gohr        $fileinfo->setMtime($header['mtime']);
634605f8e8dSAndreas Gohr        $fileinfo->setOwner($header['uname']);
635605f8e8dSAndreas Gohr        $fileinfo->setGroup($header['gname']);
636605f8e8dSAndreas Gohr        $fileinfo->setIsdir((bool) $header['typeflag']);
637605f8e8dSAndreas Gohr
638605f8e8dSAndreas Gohr        return $fileinfo;
639605f8e8dSAndreas Gohr    }
640605f8e8dSAndreas Gohr
641605f8e8dSAndreas Gohr    /**
642605f8e8dSAndreas Gohr     * Checks if the given compression type is available and throws an exception if not
643605f8e8dSAndreas Gohr     *
644605f8e8dSAndreas Gohr     * @param $comptype
645605f8e8dSAndreas Gohr     * @throws ArchiveIllegalCompressionException
646605f8e8dSAndreas Gohr     */
647605f8e8dSAndreas Gohr    protected function compressioncheck($comptype)
648605f8e8dSAndreas Gohr    {
649605f8e8dSAndreas Gohr        if ($comptype === Archive::COMPRESS_GZIP && !function_exists('gzopen')) {
650605f8e8dSAndreas Gohr            throw new ArchiveIllegalCompressionException('No gzip support available');
651605f8e8dSAndreas Gohr        }
652605f8e8dSAndreas Gohr
653605f8e8dSAndreas Gohr        if ($comptype === Archive::COMPRESS_BZIP && !function_exists('bzopen')) {
654605f8e8dSAndreas Gohr            throw new ArchiveIllegalCompressionException('No bzip2 support available');
655605f8e8dSAndreas Gohr        }
656605f8e8dSAndreas Gohr    }
657605f8e8dSAndreas Gohr
658605f8e8dSAndreas Gohr    /**
659530d6729SAndreas Gohr     * Guesses the wanted compression from the given file
660530d6729SAndreas Gohr     *
661530d6729SAndreas Gohr     * Uses magic bytes for existing files, the file extension otherwise
662605f8e8dSAndreas Gohr     *
663605f8e8dSAndreas Gohr     * You don't need to call this yourself. It's used when you pass Archive::COMPRESS_AUTO somewhere
664605f8e8dSAndreas Gohr     *
665605f8e8dSAndreas Gohr     * @param string $file
666605f8e8dSAndreas Gohr     * @return int
667605f8e8dSAndreas Gohr     */
668605f8e8dSAndreas Gohr    public function filetype($file)
669605f8e8dSAndreas Gohr    {
670530d6729SAndreas Gohr        // for existing files, try to read the magic bytes
671530d6729SAndreas Gohr        if(file_exists($file) && is_readable($file) && filesize($file) > 5) {
672ddb94cf0SAndreas Gohr            $fh = @fopen($file, 'rb');
673530d6729SAndreas Gohr            if(!$fh) return false;
674530d6729SAndreas Gohr            $magic = fread($fh, 5);
675530d6729SAndreas Gohr            fclose($fh);
676530d6729SAndreas Gohr
677530d6729SAndreas Gohr            if(strpos($magic, "\x42\x5a") === 0) return Archive::COMPRESS_BZIP;
678530d6729SAndreas Gohr            if(strpos($magic, "\x1f\x8b") === 0) return Archive::COMPRESS_GZIP;
679530d6729SAndreas Gohr        }
680530d6729SAndreas Gohr
681530d6729SAndreas Gohr        // otherwise rely on file name
682605f8e8dSAndreas Gohr        $file = strtolower($file);
683605f8e8dSAndreas Gohr        if (substr($file, -3) == '.gz' || substr($file, -4) == '.tgz') {
684530d6729SAndreas Gohr            return Archive::COMPRESS_GZIP;
685605f8e8dSAndreas Gohr        } elseif (substr($file, -4) == '.bz2' || substr($file, -4) == '.tbz') {
686530d6729SAndreas Gohr            return Archive::COMPRESS_BZIP;
687605f8e8dSAndreas Gohr        }
688530d6729SAndreas Gohr
689530d6729SAndreas Gohr        return Archive::COMPRESS_NONE;
690605f8e8dSAndreas Gohr    }
691*e43cd7e1SAndreas Gohr
692605f8e8dSAndreas Gohr}
693