xref: /dokuwiki/vendor/splitbrain/php-archive/src/Tar.php (revision 530d672995040c320a9506a0b93258a49c4d0b29)
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)
32605f8e8dSAndreas Gohr     * @return mixed
33605f8e8dSAndreas Gohr     */
34605f8e8dSAndreas Gohr    public function setCompression($level = 9, $type = Archive::COMPRESS_AUTO)
35605f8e8dSAndreas Gohr    {
36605f8e8dSAndreas Gohr        $this->compressioncheck($type);
37605f8e8dSAndreas Gohr        $this->comptype  = $type;
38605f8e8dSAndreas Gohr        $this->complevel = $level;
39*530d6729SAndreas Gohr        if($level == 0) $this->comptype = Archive::COMPRESS_NONE;
40*530d6729SAndreas Gohr        if($type == Archive::COMPRESS_NONE) $this->complevel = 0;
41605f8e8dSAndreas Gohr    }
42605f8e8dSAndreas Gohr
43605f8e8dSAndreas Gohr    /**
44605f8e8dSAndreas Gohr     * Open an existing TAR file for reading
45605f8e8dSAndreas Gohr     *
46605f8e8dSAndreas Gohr     * @param string $file
47605f8e8dSAndreas Gohr     * @throws ArchiveIOException
48605f8e8dSAndreas Gohr     */
49605f8e8dSAndreas Gohr    public function open($file)
50605f8e8dSAndreas Gohr    {
51605f8e8dSAndreas Gohr        $this->file = $file;
52605f8e8dSAndreas Gohr
53605f8e8dSAndreas Gohr        // update compression to mach file
54605f8e8dSAndreas Gohr        if ($this->comptype == Tar::COMPRESS_AUTO) {
55605f8e8dSAndreas Gohr            $this->setCompression($this->complevel, $this->filetype($file));
56605f8e8dSAndreas Gohr        }
57605f8e8dSAndreas Gohr
58605f8e8dSAndreas Gohr        // open file handles
59605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_GZIP) {
60605f8e8dSAndreas Gohr            $this->fh = @gzopen($this->file, 'rb');
61605f8e8dSAndreas Gohr        } elseif ($this->comptype === Archive::COMPRESS_BZIP) {
62605f8e8dSAndreas Gohr            $this->fh = @bzopen($this->file, 'r');
63605f8e8dSAndreas Gohr        } else {
64605f8e8dSAndreas Gohr            $this->fh = @fopen($this->file, 'rb');
65605f8e8dSAndreas Gohr        }
66605f8e8dSAndreas Gohr
67605f8e8dSAndreas Gohr        if (!$this->fh) {
68605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not open file for reading: '.$this->file);
69605f8e8dSAndreas Gohr        }
70605f8e8dSAndreas Gohr        $this->closed = false;
71605f8e8dSAndreas Gohr    }
72605f8e8dSAndreas Gohr
73605f8e8dSAndreas Gohr    /**
74605f8e8dSAndreas Gohr     * Read the contents of a TAR archive
75605f8e8dSAndreas Gohr     *
76605f8e8dSAndreas Gohr     * This function lists the files stored in the archive
77605f8e8dSAndreas Gohr     *
78605f8e8dSAndreas Gohr     * The archive is closed afer reading the contents, because rewinding is not possible in bzip2 streams.
79605f8e8dSAndreas Gohr     * Reopen the file with open() again if you want to do additional operations
80605f8e8dSAndreas Gohr     *
81605f8e8dSAndreas Gohr     * @throws ArchiveIOException
82605f8e8dSAndreas Gohr     * @returns FileInfo[]
83605f8e8dSAndreas Gohr     */
84605f8e8dSAndreas Gohr    public function contents()
85605f8e8dSAndreas Gohr    {
86605f8e8dSAndreas Gohr        if ($this->closed || !$this->file) {
87605f8e8dSAndreas Gohr            throw new ArchiveIOException('Can not read from a closed archive');
88605f8e8dSAndreas Gohr        }
89605f8e8dSAndreas Gohr
90605f8e8dSAndreas Gohr        $result = array();
91605f8e8dSAndreas Gohr        while ($read = $this->readbytes(512)) {
92605f8e8dSAndreas Gohr            $header = $this->parseHeader($read);
93605f8e8dSAndreas Gohr            if (!is_array($header)) {
94605f8e8dSAndreas Gohr                continue;
95605f8e8dSAndreas Gohr            }
96605f8e8dSAndreas Gohr
97605f8e8dSAndreas Gohr            $this->skipbytes(ceil($header['size'] / 512) * 512);
98605f8e8dSAndreas Gohr            $result[] = $this->header2fileinfo($header);
99605f8e8dSAndreas Gohr        }
100605f8e8dSAndreas Gohr
101605f8e8dSAndreas Gohr        $this->close();
102605f8e8dSAndreas Gohr        return $result;
103605f8e8dSAndreas Gohr    }
104605f8e8dSAndreas Gohr
105605f8e8dSAndreas Gohr    /**
106605f8e8dSAndreas Gohr     * Extract an existing TAR archive
107605f8e8dSAndreas Gohr     *
108605f8e8dSAndreas Gohr     * The $strip parameter allows you to strip a certain number of path components from the filenames
109605f8e8dSAndreas Gohr     * found in the tar file, similar to the --strip-components feature of GNU tar. This is triggered when
110605f8e8dSAndreas Gohr     * an integer is passed as $strip.
111605f8e8dSAndreas Gohr     * Alternatively a fixed string prefix may be passed in $strip. If the filename matches this prefix,
112605f8e8dSAndreas Gohr     * the prefix will be stripped. It is recommended to give prefixes with a trailing slash.
113605f8e8dSAndreas Gohr     *
114605f8e8dSAndreas Gohr     * By default this will extract all files found in the archive. You can restrict the output using the $include
115605f8e8dSAndreas Gohr     * and $exclude parameter. Both expect a full regular expression (including delimiters and modifiers). If
116605f8e8dSAndreas Gohr     * $include is set only files that match this expression will be extracted. Files that match the $exclude
117605f8e8dSAndreas Gohr     * expression will never be extracted. Both parameters can be used in combination. Expressions are matched against
118605f8e8dSAndreas Gohr     * stripped filenames as described above.
119605f8e8dSAndreas Gohr     *
120605f8e8dSAndreas Gohr     * The archive is closed afer reading the contents, because rewinding is not possible in bzip2 streams.
121605f8e8dSAndreas Gohr     * Reopen the file with open() again if you want to do additional operations
122605f8e8dSAndreas Gohr     *
123605f8e8dSAndreas Gohr     * @param string     $outdir  the target directory for extracting
124605f8e8dSAndreas Gohr     * @param int|string $strip   either the number of path components or a fixed prefix to strip
125605f8e8dSAndreas Gohr     * @param string     $exclude a regular expression of files to exclude
126605f8e8dSAndreas Gohr     * @param string     $include a regular expression of files to include
127605f8e8dSAndreas Gohr     * @throws ArchiveIOException
128605f8e8dSAndreas Gohr     * @return FileInfo[]
129605f8e8dSAndreas Gohr     */
130605f8e8dSAndreas Gohr    public function extract($outdir, $strip = '', $exclude = '', $include = '')
131605f8e8dSAndreas Gohr    {
132605f8e8dSAndreas Gohr        if ($this->closed || !$this->file) {
133605f8e8dSAndreas Gohr            throw new ArchiveIOException('Can not read from a closed archive');
134605f8e8dSAndreas Gohr        }
135605f8e8dSAndreas Gohr
136605f8e8dSAndreas Gohr        $outdir = rtrim($outdir, '/');
137605f8e8dSAndreas Gohr        @mkdir($outdir, 0777, true);
138605f8e8dSAndreas Gohr        if (!is_dir($outdir)) {
139605f8e8dSAndreas Gohr            throw new ArchiveIOException("Could not create directory '$outdir'");
140605f8e8dSAndreas Gohr        }
141605f8e8dSAndreas Gohr
142605f8e8dSAndreas Gohr        $extracted = array();
143605f8e8dSAndreas Gohr        while ($dat = $this->readbytes(512)) {
144605f8e8dSAndreas Gohr            // read the file header
145605f8e8dSAndreas Gohr            $header = $this->parseHeader($dat);
146605f8e8dSAndreas Gohr            if (!is_array($header)) {
147605f8e8dSAndreas Gohr                continue;
148605f8e8dSAndreas Gohr            }
149605f8e8dSAndreas Gohr            $fileinfo = $this->header2fileinfo($header);
150605f8e8dSAndreas Gohr
151605f8e8dSAndreas Gohr            // apply strip rules
152605f8e8dSAndreas Gohr            $fileinfo->strip($strip);
153605f8e8dSAndreas Gohr
154605f8e8dSAndreas Gohr            // skip unwanted files
155605f8e8dSAndreas Gohr            if (!strlen($fileinfo->getPath()) || !$fileinfo->match($include, $exclude)) {
156605f8e8dSAndreas Gohr                $this->skipbytes(ceil($header['size'] / 512) * 512);
157605f8e8dSAndreas Gohr                continue;
158605f8e8dSAndreas Gohr            }
159605f8e8dSAndreas Gohr
160605f8e8dSAndreas Gohr            // create output directory
161605f8e8dSAndreas Gohr            $output    = $outdir.'/'.$fileinfo->getPath();
162605f8e8dSAndreas Gohr            $directory = ($fileinfo->getIsdir()) ? $output : dirname($output);
163605f8e8dSAndreas Gohr            @mkdir($directory, 0777, true);
164605f8e8dSAndreas Gohr
165605f8e8dSAndreas Gohr            // extract data
166605f8e8dSAndreas Gohr            if (!$fileinfo->getIsdir()) {
167605f8e8dSAndreas Gohr                $fp = fopen($output, "wb");
168605f8e8dSAndreas Gohr                if (!$fp) {
169605f8e8dSAndreas Gohr                    throw new ArchiveIOException('Could not open file for writing: '.$output);
170605f8e8dSAndreas Gohr                }
171605f8e8dSAndreas Gohr
172605f8e8dSAndreas Gohr                $size = floor($header['size'] / 512);
173605f8e8dSAndreas Gohr                for ($i = 0; $i < $size; $i++) {
174605f8e8dSAndreas Gohr                    fwrite($fp, $this->readbytes(512), 512);
175605f8e8dSAndreas Gohr                }
176605f8e8dSAndreas Gohr                if (($header['size'] % 512) != 0) {
177605f8e8dSAndreas Gohr                    fwrite($fp, $this->readbytes(512), $header['size'] % 512);
178605f8e8dSAndreas Gohr                }
179605f8e8dSAndreas Gohr
180605f8e8dSAndreas Gohr                fclose($fp);
181605f8e8dSAndreas Gohr                touch($output, $fileinfo->getMtime());
182605f8e8dSAndreas Gohr                chmod($output, $fileinfo->getMode());
183605f8e8dSAndreas Gohr            } else {
184605f8e8dSAndreas Gohr                $this->skipbytes(ceil($header['size'] / 512) * 512); // the size is usually 0 for directories
185605f8e8dSAndreas Gohr            }
186605f8e8dSAndreas Gohr
187605f8e8dSAndreas Gohr            $extracted[] = $fileinfo;
188605f8e8dSAndreas Gohr        }
189605f8e8dSAndreas Gohr
190605f8e8dSAndreas Gohr        $this->close();
191605f8e8dSAndreas Gohr        return $extracted;
192605f8e8dSAndreas Gohr    }
193605f8e8dSAndreas Gohr
194605f8e8dSAndreas Gohr    /**
195605f8e8dSAndreas Gohr     * Create a new TAR file
196605f8e8dSAndreas Gohr     *
197605f8e8dSAndreas Gohr     * If $file is empty, the tar file will be created in memory
198605f8e8dSAndreas Gohr     *
199605f8e8dSAndreas Gohr     * @param string $file
200605f8e8dSAndreas Gohr     * @throws ArchiveIOException
201605f8e8dSAndreas Gohr     */
202605f8e8dSAndreas Gohr    public function create($file = '')
203605f8e8dSAndreas Gohr    {
204605f8e8dSAndreas Gohr        $this->file   = $file;
205605f8e8dSAndreas Gohr        $this->memory = '';
206605f8e8dSAndreas Gohr        $this->fh     = 0;
207605f8e8dSAndreas Gohr
208605f8e8dSAndreas Gohr        if ($this->file) {
209605f8e8dSAndreas Gohr            // determine compression
210605f8e8dSAndreas Gohr            if ($this->comptype == Archive::COMPRESS_AUTO) {
211605f8e8dSAndreas Gohr                $this->setCompression($this->complevel, $this->filetype($file));
212605f8e8dSAndreas Gohr            }
213605f8e8dSAndreas Gohr
214605f8e8dSAndreas Gohr            if ($this->comptype === Archive::COMPRESS_GZIP) {
215605f8e8dSAndreas Gohr                $this->fh = @gzopen($this->file, 'wb'.$this->complevel);
216605f8e8dSAndreas Gohr            } elseif ($this->comptype === Archive::COMPRESS_BZIP) {
217605f8e8dSAndreas Gohr                $this->fh = @bzopen($this->file, 'w');
218605f8e8dSAndreas Gohr            } else {
219605f8e8dSAndreas Gohr                $this->fh = @fopen($this->file, 'wb');
220605f8e8dSAndreas Gohr            }
221605f8e8dSAndreas Gohr
222605f8e8dSAndreas Gohr            if (!$this->fh) {
223605f8e8dSAndreas Gohr                throw new ArchiveIOException('Could not open file for writing: '.$this->file);
224605f8e8dSAndreas Gohr            }
225605f8e8dSAndreas Gohr        }
226605f8e8dSAndreas Gohr        $this->writeaccess = true;
227605f8e8dSAndreas Gohr        $this->closed      = false;
228605f8e8dSAndreas Gohr    }
229605f8e8dSAndreas Gohr
230605f8e8dSAndreas Gohr    /**
231605f8e8dSAndreas Gohr     * Add a file to the current TAR archive using an existing file in the filesystem
232605f8e8dSAndreas Gohr     *
233605f8e8dSAndreas Gohr     * @param string          $file     path to the original file
234605f8e8dSAndreas 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
235605f8e8dSAndreas Gohr     * @throws ArchiveIOException
236605f8e8dSAndreas Gohr     */
237605f8e8dSAndreas Gohr    public function addFile($file, $fileinfo = '')
238605f8e8dSAndreas Gohr    {
239605f8e8dSAndreas Gohr        if (is_string($fileinfo)) {
240605f8e8dSAndreas Gohr            $fileinfo = FileInfo::fromPath($file, $fileinfo);
241605f8e8dSAndreas Gohr        }
242605f8e8dSAndreas Gohr
243605f8e8dSAndreas Gohr        if ($this->closed) {
244605f8e8dSAndreas Gohr            throw new ArchiveIOException('Archive has been closed, files can no longer be added');
245605f8e8dSAndreas Gohr        }
246605f8e8dSAndreas Gohr
247605f8e8dSAndreas Gohr        $fp = fopen($file, 'rb');
248605f8e8dSAndreas Gohr        if (!$fp) {
249605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not open file for reading: '.$file);
250605f8e8dSAndreas Gohr        }
251605f8e8dSAndreas Gohr
252605f8e8dSAndreas Gohr        // create file header
253605f8e8dSAndreas Gohr        $this->writeFileHeader($fileinfo);
254605f8e8dSAndreas Gohr
255605f8e8dSAndreas Gohr        // write data
256605f8e8dSAndreas Gohr        while (!feof($fp)) {
257605f8e8dSAndreas Gohr            $data = fread($fp, 512);
258605f8e8dSAndreas Gohr            if ($data === false) {
259605f8e8dSAndreas Gohr                break;
260605f8e8dSAndreas Gohr            }
261605f8e8dSAndreas Gohr            if ($data === '') {
262605f8e8dSAndreas Gohr                break;
263605f8e8dSAndreas Gohr            }
264605f8e8dSAndreas Gohr            $packed = pack("a512", $data);
265605f8e8dSAndreas Gohr            $this->writebytes($packed);
266605f8e8dSAndreas Gohr        }
267605f8e8dSAndreas Gohr        fclose($fp);
268605f8e8dSAndreas Gohr    }
269605f8e8dSAndreas Gohr
270605f8e8dSAndreas Gohr    /**
271605f8e8dSAndreas Gohr     * Add a file to the current TAR archive using the given $data as content
272605f8e8dSAndreas Gohr     *
273605f8e8dSAndreas Gohr     * @param string|FileInfo $fileinfo either the name to us in archive (string) or a FileInfo oject with all meta data
274605f8e8dSAndreas Gohr     * @param string          $data     binary content of the file to add
275605f8e8dSAndreas Gohr     * @throws ArchiveIOException
276605f8e8dSAndreas Gohr     */
277605f8e8dSAndreas Gohr    public function addData($fileinfo, $data)
278605f8e8dSAndreas Gohr    {
279605f8e8dSAndreas Gohr        if (is_string($fileinfo)) {
280605f8e8dSAndreas Gohr            $fileinfo = new FileInfo($fileinfo);
281605f8e8dSAndreas Gohr        }
282605f8e8dSAndreas Gohr
283605f8e8dSAndreas Gohr        if ($this->closed) {
284605f8e8dSAndreas Gohr            throw new ArchiveIOException('Archive has been closed, files can no longer be added');
285605f8e8dSAndreas Gohr        }
286605f8e8dSAndreas Gohr
287605f8e8dSAndreas Gohr        $len = strlen($data);
288605f8e8dSAndreas Gohr        $fileinfo->setSize($len);
289605f8e8dSAndreas Gohr        $this->writeFileHeader($fileinfo);
290605f8e8dSAndreas Gohr
291605f8e8dSAndreas Gohr        for ($s = 0; $s < $len; $s += 512) {
292605f8e8dSAndreas Gohr            $this->writebytes(pack("a512", substr($data, $s, 512)));
293605f8e8dSAndreas Gohr        }
294605f8e8dSAndreas Gohr    }
295605f8e8dSAndreas Gohr
296605f8e8dSAndreas Gohr    /**
297605f8e8dSAndreas Gohr     * Add the closing footer to the archive if in write mode, close all file handles
298605f8e8dSAndreas Gohr     *
299605f8e8dSAndreas Gohr     * After a call to this function no more data can be added to the archive, for
300605f8e8dSAndreas Gohr     * read access no reading is allowed anymore
301605f8e8dSAndreas Gohr     *
302605f8e8dSAndreas Gohr     * "Physically, an archive consists of a series of file entries terminated by an end-of-archive entry, which
303605f8e8dSAndreas Gohr     * consists of two 512 blocks of zero bytes"
304605f8e8dSAndreas Gohr     *
305605f8e8dSAndreas Gohr     * @link http://www.gnu.org/software/tar/manual/html_chapter/tar_8.html#SEC134
306605f8e8dSAndreas Gohr     */
307605f8e8dSAndreas Gohr    public function close()
308605f8e8dSAndreas Gohr    {
309605f8e8dSAndreas Gohr        if ($this->closed) {
310605f8e8dSAndreas Gohr            return;
311605f8e8dSAndreas Gohr        } // we did this already
312605f8e8dSAndreas Gohr
313605f8e8dSAndreas Gohr        // write footer
314605f8e8dSAndreas Gohr        if ($this->writeaccess) {
315605f8e8dSAndreas Gohr            $this->writebytes(pack("a512", ""));
316605f8e8dSAndreas Gohr            $this->writebytes(pack("a512", ""));
317605f8e8dSAndreas Gohr        }
318605f8e8dSAndreas Gohr
319605f8e8dSAndreas Gohr        // close file handles
320605f8e8dSAndreas Gohr        if ($this->file) {
321605f8e8dSAndreas Gohr            if ($this->comptype === Archive::COMPRESS_GZIP) {
322605f8e8dSAndreas Gohr                gzclose($this->fh);
323605f8e8dSAndreas Gohr            } elseif ($this->comptype === Archive::COMPRESS_BZIP) {
324605f8e8dSAndreas Gohr                bzclose($this->fh);
325605f8e8dSAndreas Gohr            } else {
326605f8e8dSAndreas Gohr                fclose($this->fh);
327605f8e8dSAndreas Gohr            }
328605f8e8dSAndreas Gohr
329605f8e8dSAndreas Gohr            $this->file = '';
330605f8e8dSAndreas Gohr            $this->fh   = 0;
331605f8e8dSAndreas Gohr        }
332605f8e8dSAndreas Gohr
333605f8e8dSAndreas Gohr        $this->writeaccess = false;
334605f8e8dSAndreas Gohr        $this->closed      = true;
335605f8e8dSAndreas Gohr    }
336605f8e8dSAndreas Gohr
337605f8e8dSAndreas Gohr    /**
338605f8e8dSAndreas Gohr     * Returns the created in-memory archive data
339605f8e8dSAndreas Gohr     *
340605f8e8dSAndreas Gohr     * This implicitly calls close() on the Archive
341605f8e8dSAndreas Gohr     */
342605f8e8dSAndreas Gohr    public function getArchive()
343605f8e8dSAndreas Gohr    {
344605f8e8dSAndreas Gohr        $this->close();
345605f8e8dSAndreas Gohr
346605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_AUTO) {
347605f8e8dSAndreas Gohr            $this->comptype = Archive::COMPRESS_NONE;
348605f8e8dSAndreas Gohr        }
349605f8e8dSAndreas Gohr
350605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_GZIP) {
351605f8e8dSAndreas Gohr            return gzcompress($this->memory, $this->complevel);
352605f8e8dSAndreas Gohr        }
353605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_BZIP) {
354605f8e8dSAndreas Gohr            return bzcompress($this->memory);
355605f8e8dSAndreas Gohr        }
356605f8e8dSAndreas Gohr        return $this->memory;
357605f8e8dSAndreas Gohr    }
358605f8e8dSAndreas Gohr
359605f8e8dSAndreas Gohr    /**
360605f8e8dSAndreas Gohr     * Save the created in-memory archive data
361605f8e8dSAndreas Gohr     *
362605f8e8dSAndreas Gohr     * Note: It more memory effective to specify the filename in the create() function and
363605f8e8dSAndreas Gohr     * let the library work on the new file directly.
364605f8e8dSAndreas Gohr     *
365605f8e8dSAndreas Gohr     * @param string $file
366605f8e8dSAndreas Gohr     * @throws ArchiveIOException
367605f8e8dSAndreas Gohr     */
368605f8e8dSAndreas Gohr    public function save($file)
369605f8e8dSAndreas Gohr    {
370605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_AUTO) {
371*530d6729SAndreas Gohr            $this->setCompression($this->complevel, $this->filetype($file));
372605f8e8dSAndreas Gohr        }
373605f8e8dSAndreas Gohr
374605f8e8dSAndreas Gohr        if (!file_put_contents($file, $this->getArchive())) {
375605f8e8dSAndreas Gohr            throw new ArchiveIOException('Could not write to file: '.$file);
376605f8e8dSAndreas Gohr        }
377605f8e8dSAndreas Gohr    }
378605f8e8dSAndreas Gohr
379605f8e8dSAndreas Gohr    /**
380605f8e8dSAndreas Gohr     * Read from the open file pointer
381605f8e8dSAndreas Gohr     *
382605f8e8dSAndreas Gohr     * @param int $length bytes to read
383605f8e8dSAndreas Gohr     * @return string
384605f8e8dSAndreas Gohr     */
385605f8e8dSAndreas Gohr    protected function readbytes($length)
386605f8e8dSAndreas Gohr    {
387605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_GZIP) {
388605f8e8dSAndreas Gohr            return @gzread($this->fh, $length);
389605f8e8dSAndreas Gohr        } elseif ($this->comptype === Archive::COMPRESS_BZIP) {
390605f8e8dSAndreas Gohr            return @bzread($this->fh, $length);
391605f8e8dSAndreas Gohr        } else {
392605f8e8dSAndreas Gohr            return @fread($this->fh, $length);
393605f8e8dSAndreas Gohr        }
394605f8e8dSAndreas Gohr    }
395605f8e8dSAndreas Gohr
396605f8e8dSAndreas Gohr    /**
397605f8e8dSAndreas Gohr     * Write to the open filepointer or memory
398605f8e8dSAndreas Gohr     *
399605f8e8dSAndreas Gohr     * @param string $data
400605f8e8dSAndreas Gohr     * @throws ArchiveIOException
401605f8e8dSAndreas Gohr     * @return int number of bytes written
402605f8e8dSAndreas Gohr     */
403605f8e8dSAndreas Gohr    protected function writebytes($data)
404605f8e8dSAndreas Gohr    {
405605f8e8dSAndreas Gohr        if (!$this->file) {
406605f8e8dSAndreas Gohr            $this->memory .= $data;
407605f8e8dSAndreas Gohr            $written = strlen($data);
408605f8e8dSAndreas Gohr        } elseif ($this->comptype === Archive::COMPRESS_GZIP) {
409605f8e8dSAndreas Gohr            $written = @gzwrite($this->fh, $data);
410605f8e8dSAndreas Gohr        } elseif ($this->comptype === Archive::COMPRESS_BZIP) {
411605f8e8dSAndreas Gohr            $written = @bzwrite($this->fh, $data);
412605f8e8dSAndreas Gohr        } else {
413605f8e8dSAndreas Gohr            $written = @fwrite($this->fh, $data);
414605f8e8dSAndreas Gohr        }
415605f8e8dSAndreas Gohr        if ($written === false) {
416605f8e8dSAndreas Gohr            throw new ArchiveIOException('Failed to write to archive stream');
417605f8e8dSAndreas Gohr        }
418605f8e8dSAndreas Gohr        return $written;
419605f8e8dSAndreas Gohr    }
420605f8e8dSAndreas Gohr
421605f8e8dSAndreas Gohr    /**
422605f8e8dSAndreas Gohr     * Skip forward in the open file pointer
423605f8e8dSAndreas Gohr     *
424605f8e8dSAndreas Gohr     * This is basically a wrapper around seek() (and a workaround for bzip2)
425605f8e8dSAndreas Gohr     *
426605f8e8dSAndreas Gohr     * @param int $bytes seek to this position
427605f8e8dSAndreas Gohr     */
428605f8e8dSAndreas Gohr    function skipbytes($bytes)
429605f8e8dSAndreas Gohr    {
430605f8e8dSAndreas Gohr        if ($this->comptype === Archive::COMPRESS_GZIP) {
431605f8e8dSAndreas Gohr            @gzseek($this->fh, $bytes, SEEK_CUR);
432605f8e8dSAndreas Gohr        } elseif ($this->comptype === Archive::COMPRESS_BZIP) {
433605f8e8dSAndreas Gohr            // there is no seek in bzip2, we simply read on
434*530d6729SAndreas Gohr            // bzread allows to read a max of 8kb at once
435*530d6729SAndreas Gohr            while($bytes) {
436*530d6729SAndreas Gohr                $toread = min(8192, $bytes);
437*530d6729SAndreas Gohr                @bzread($this->fh, $toread);
438*530d6729SAndreas Gohr                $bytes -= $toread;
439*530d6729SAndreas Gohr            }
440605f8e8dSAndreas Gohr        } else {
441605f8e8dSAndreas Gohr            @fseek($this->fh, $bytes, SEEK_CUR);
442605f8e8dSAndreas Gohr        }
443605f8e8dSAndreas Gohr    }
444605f8e8dSAndreas Gohr
445605f8e8dSAndreas Gohr    /**
446605f8e8dSAndreas Gohr     * Write the given file metat data as header
447605f8e8dSAndreas Gohr     *
448605f8e8dSAndreas Gohr     * @param FileInfo $fileinfo
449605f8e8dSAndreas Gohr     */
450605f8e8dSAndreas Gohr    protected function writeFileHeader(FileInfo $fileinfo)
451605f8e8dSAndreas Gohr    {
452605f8e8dSAndreas Gohr        $this->writeRawFileHeader(
453605f8e8dSAndreas Gohr            $fileinfo->getPath(),
454605f8e8dSAndreas Gohr            $fileinfo->getUid(),
455605f8e8dSAndreas Gohr            $fileinfo->getGid(),
456605f8e8dSAndreas Gohr            $fileinfo->getMode(),
457605f8e8dSAndreas Gohr            $fileinfo->getSize(),
458605f8e8dSAndreas Gohr            $fileinfo->getMtime(),
459605f8e8dSAndreas Gohr            $fileinfo->getIsdir() ? '5' : '0'
460605f8e8dSAndreas Gohr        );
461605f8e8dSAndreas Gohr    }
462605f8e8dSAndreas Gohr
463605f8e8dSAndreas Gohr    /**
464605f8e8dSAndreas Gohr     * Write a file header to the stream
465605f8e8dSAndreas Gohr     *
466605f8e8dSAndreas Gohr     * @param string $name
467605f8e8dSAndreas Gohr     * @param int    $uid
468605f8e8dSAndreas Gohr     * @param int    $gid
469605f8e8dSAndreas Gohr     * @param int    $perm
470605f8e8dSAndreas Gohr     * @param int    $size
471605f8e8dSAndreas Gohr     * @param int    $mtime
472605f8e8dSAndreas Gohr     * @param string $typeflag Set to '5' for directories
473605f8e8dSAndreas Gohr     */
474605f8e8dSAndreas Gohr    protected function writeRawFileHeader($name, $uid, $gid, $perm, $size, $mtime, $typeflag = '')
475605f8e8dSAndreas Gohr    {
476605f8e8dSAndreas Gohr        // handle filename length restrictions
477605f8e8dSAndreas Gohr        $prefix  = '';
478605f8e8dSAndreas Gohr        $namelen = strlen($name);
479605f8e8dSAndreas Gohr        if ($namelen > 100) {
480605f8e8dSAndreas Gohr            $file = basename($name);
481605f8e8dSAndreas Gohr            $dir  = dirname($name);
482605f8e8dSAndreas Gohr            if (strlen($file) > 100 || strlen($dir) > 155) {
483605f8e8dSAndreas Gohr                // we're still too large, let's use GNU longlink
484605f8e8dSAndreas Gohr                $this->writeRawFileHeader('././@LongLink', 0, 0, 0, $namelen, 0, 'L');
485605f8e8dSAndreas Gohr                for ($s = 0; $s < $namelen; $s += 512) {
486605f8e8dSAndreas Gohr                    $this->writebytes(pack("a512", substr($name, $s, 512)));
487605f8e8dSAndreas Gohr                }
488605f8e8dSAndreas Gohr                $name = substr($name, 0, 100); // cut off name
489605f8e8dSAndreas Gohr            } else {
490605f8e8dSAndreas Gohr                // we're fine when splitting, use POSIX ustar
491605f8e8dSAndreas Gohr                $prefix = $dir;
492605f8e8dSAndreas Gohr                $name   = $file;
493605f8e8dSAndreas Gohr            }
494605f8e8dSAndreas Gohr        }
495605f8e8dSAndreas Gohr
496605f8e8dSAndreas Gohr        // values are needed in octal
497605f8e8dSAndreas Gohr        $uid   = sprintf("%6s ", decoct($uid));
498605f8e8dSAndreas Gohr        $gid   = sprintf("%6s ", decoct($gid));
499605f8e8dSAndreas Gohr        $perm  = sprintf("%6s ", decoct($perm));
500605f8e8dSAndreas Gohr        $size  = sprintf("%11s ", decoct($size));
501605f8e8dSAndreas Gohr        $mtime = sprintf("%11s", decoct($mtime));
502605f8e8dSAndreas Gohr
503605f8e8dSAndreas Gohr        $data_first = pack("a100a8a8a8a12A12", $name, $perm, $uid, $gid, $size, $mtime);
504605f8e8dSAndreas Gohr        $data_last  = pack("a1a100a6a2a32a32a8a8a155a12", $typeflag, '', 'ustar', '', '', '', '', '', $prefix, "");
505605f8e8dSAndreas Gohr
506605f8e8dSAndreas Gohr        for ($i = 0, $chks = 0; $i < 148; $i++) {
507605f8e8dSAndreas Gohr            $chks += ord($data_first[$i]);
508605f8e8dSAndreas Gohr        }
509605f8e8dSAndreas Gohr
510605f8e8dSAndreas Gohr        for ($i = 156, $chks += 256, $j = 0; $i < 512; $i++, $j++) {
511605f8e8dSAndreas Gohr            $chks += ord($data_last[$j]);
512605f8e8dSAndreas Gohr        }
513605f8e8dSAndreas Gohr
514605f8e8dSAndreas Gohr        $this->writebytes($data_first);
515605f8e8dSAndreas Gohr
516605f8e8dSAndreas Gohr        $chks = pack("a8", sprintf("%6s ", decoct($chks)));
517605f8e8dSAndreas Gohr        $this->writebytes($chks.$data_last);
518605f8e8dSAndreas Gohr    }
519605f8e8dSAndreas Gohr
520605f8e8dSAndreas Gohr    /**
521605f8e8dSAndreas Gohr     * Decode the given tar file header
522605f8e8dSAndreas Gohr     *
523*530d6729SAndreas Gohr     * @param string $block a 512 byte block containing the header data
524*530d6729SAndreas Gohr     * @return array|false returns false when this was a null block
525*530d6729SAndreas Gohr     * @throws ArchiveCorruptedException
526605f8e8dSAndreas Gohr     */
527605f8e8dSAndreas Gohr    protected function parseHeader($block)
528605f8e8dSAndreas Gohr    {
529605f8e8dSAndreas Gohr        if (!$block || strlen($block) != 512) {
530*530d6729SAndreas Gohr            throw new ArchiveCorruptedException('Unexpected length of header');
531605f8e8dSAndreas Gohr        }
532605f8e8dSAndreas Gohr
533*530d6729SAndreas Gohr        // null byte blocks are ignored
534*530d6729SAndreas Gohr        if(trim($block) === '') return false;
535*530d6729SAndreas Gohr
536605f8e8dSAndreas Gohr        for ($i = 0, $chks = 0; $i < 148; $i++) {
537605f8e8dSAndreas Gohr            $chks += ord($block[$i]);
538605f8e8dSAndreas Gohr        }
539605f8e8dSAndreas Gohr
540605f8e8dSAndreas Gohr        for ($i = 156, $chks += 256; $i < 512; $i++) {
541605f8e8dSAndreas Gohr            $chks += ord($block[$i]);
542605f8e8dSAndreas Gohr        }
543605f8e8dSAndreas Gohr
544605f8e8dSAndreas Gohr        $header = @unpack(
545605f8e8dSAndreas Gohr            "a100filename/a8perm/a8uid/a8gid/a12size/a12mtime/a8checksum/a1typeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor/a155prefix",
546605f8e8dSAndreas Gohr            $block
547605f8e8dSAndreas Gohr        );
548605f8e8dSAndreas Gohr        if (!$header) {
549*530d6729SAndreas Gohr            throw new ArchiveCorruptedException('Failed to parse header');
550605f8e8dSAndreas Gohr        }
551605f8e8dSAndreas Gohr
552605f8e8dSAndreas Gohr        $return['checksum'] = OctDec(trim($header['checksum']));
553605f8e8dSAndreas Gohr        if ($return['checksum'] != $chks) {
554*530d6729SAndreas Gohr            throw new ArchiveCorruptedException('Header does not match it\'s checksum');
555605f8e8dSAndreas Gohr        }
556605f8e8dSAndreas Gohr
557605f8e8dSAndreas Gohr        $return['filename'] = trim($header['filename']);
558605f8e8dSAndreas Gohr        $return['perm']     = OctDec(trim($header['perm']));
559605f8e8dSAndreas Gohr        $return['uid']      = OctDec(trim($header['uid']));
560605f8e8dSAndreas Gohr        $return['gid']      = OctDec(trim($header['gid']));
561605f8e8dSAndreas Gohr        $return['size']     = OctDec(trim($header['size']));
562605f8e8dSAndreas Gohr        $return['mtime']    = OctDec(trim($header['mtime']));
563605f8e8dSAndreas Gohr        $return['typeflag'] = $header['typeflag'];
564605f8e8dSAndreas Gohr        $return['link']     = trim($header['link']);
565605f8e8dSAndreas Gohr        $return['uname']    = trim($header['uname']);
566605f8e8dSAndreas Gohr        $return['gname']    = trim($header['gname']);
567605f8e8dSAndreas Gohr
568605f8e8dSAndreas Gohr        // Handle ustar Posix compliant path prefixes
569605f8e8dSAndreas Gohr        if (trim($header['prefix'])) {
570605f8e8dSAndreas Gohr            $return['filename'] = trim($header['prefix']).'/'.$return['filename'];
571605f8e8dSAndreas Gohr        }
572605f8e8dSAndreas Gohr
573605f8e8dSAndreas Gohr        // Handle Long-Link entries from GNU Tar
574605f8e8dSAndreas Gohr        if ($return['typeflag'] == 'L') {
575605f8e8dSAndreas Gohr            // following data block(s) is the filename
576605f8e8dSAndreas Gohr            $filename = trim($this->readbytes(ceil($header['size'] / 512) * 512));
577605f8e8dSAndreas Gohr            // next block is the real header
578605f8e8dSAndreas Gohr            $block  = $this->readbytes(512);
579605f8e8dSAndreas Gohr            $return = $this->parseHeader($block);
580605f8e8dSAndreas Gohr            // overwrite the filename
581605f8e8dSAndreas Gohr            $return['filename'] = $filename;
582605f8e8dSAndreas Gohr        }
583605f8e8dSAndreas Gohr
584605f8e8dSAndreas Gohr        return $return;
585605f8e8dSAndreas Gohr    }
586605f8e8dSAndreas Gohr
587605f8e8dSAndreas Gohr    /**
588605f8e8dSAndreas Gohr     * Creates a FileInfo object from the given parsed header
589605f8e8dSAndreas Gohr     *
590605f8e8dSAndreas Gohr     * @param $header
591605f8e8dSAndreas Gohr     * @return FileInfo
592605f8e8dSAndreas Gohr     */
593605f8e8dSAndreas Gohr    protected function header2fileinfo($header)
594605f8e8dSAndreas Gohr    {
595605f8e8dSAndreas Gohr        $fileinfo = new FileInfo();
596605f8e8dSAndreas Gohr        $fileinfo->setPath($header['filename']);
597605f8e8dSAndreas Gohr        $fileinfo->setMode($header['perm']);
598605f8e8dSAndreas Gohr        $fileinfo->setUid($header['uid']);
599605f8e8dSAndreas Gohr        $fileinfo->setGid($header['gid']);
600605f8e8dSAndreas Gohr        $fileinfo->setSize($header['size']);
601605f8e8dSAndreas Gohr        $fileinfo->setMtime($header['mtime']);
602605f8e8dSAndreas Gohr        $fileinfo->setOwner($header['uname']);
603605f8e8dSAndreas Gohr        $fileinfo->setGroup($header['gname']);
604605f8e8dSAndreas Gohr        $fileinfo->setIsdir((bool) $header['typeflag']);
605605f8e8dSAndreas Gohr
606605f8e8dSAndreas Gohr        return $fileinfo;
607605f8e8dSAndreas Gohr    }
608605f8e8dSAndreas Gohr
609605f8e8dSAndreas Gohr    /**
610605f8e8dSAndreas Gohr     * Checks if the given compression type is available and throws an exception if not
611605f8e8dSAndreas Gohr     *
612605f8e8dSAndreas Gohr     * @param $comptype
613605f8e8dSAndreas Gohr     * @throws ArchiveIllegalCompressionException
614605f8e8dSAndreas Gohr     */
615605f8e8dSAndreas Gohr    protected function compressioncheck($comptype)
616605f8e8dSAndreas Gohr    {
617605f8e8dSAndreas Gohr        if ($comptype === Archive::COMPRESS_GZIP && !function_exists('gzopen')) {
618605f8e8dSAndreas Gohr            throw new ArchiveIllegalCompressionException('No gzip support available');
619605f8e8dSAndreas Gohr        }
620605f8e8dSAndreas Gohr
621605f8e8dSAndreas Gohr        if ($comptype === Archive::COMPRESS_BZIP && !function_exists('bzopen')) {
622605f8e8dSAndreas Gohr            throw new ArchiveIllegalCompressionException('No bzip2 support available');
623605f8e8dSAndreas Gohr        }
624605f8e8dSAndreas Gohr    }
625605f8e8dSAndreas Gohr
626605f8e8dSAndreas Gohr    /**
627*530d6729SAndreas Gohr     * Guesses the wanted compression from the given file
628*530d6729SAndreas Gohr     *
629*530d6729SAndreas Gohr     * Uses magic bytes for existing files, the file extension otherwise
630605f8e8dSAndreas Gohr     *
631605f8e8dSAndreas Gohr     * You don't need to call this yourself. It's used when you pass Archive::COMPRESS_AUTO somewhere
632605f8e8dSAndreas Gohr     *
633605f8e8dSAndreas Gohr     * @param string $file
634605f8e8dSAndreas Gohr     * @return int
635605f8e8dSAndreas Gohr     */
636605f8e8dSAndreas Gohr    public function filetype($file)
637605f8e8dSAndreas Gohr    {
638*530d6729SAndreas Gohr        // for existing files, try to read the magic bytes
639*530d6729SAndreas Gohr        if(file_exists($file) && is_readable($file) && filesize($file) > 5) {
640*530d6729SAndreas Gohr            $fh = fopen($file, 'rb');
641*530d6729SAndreas Gohr            if(!$fh) return false;
642*530d6729SAndreas Gohr            $magic = fread($fh, 5);
643*530d6729SAndreas Gohr            fclose($fh);
644*530d6729SAndreas Gohr
645*530d6729SAndreas Gohr            if(strpos($magic, "\x42\x5a") === 0) return Archive::COMPRESS_BZIP;
646*530d6729SAndreas Gohr            if(strpos($magic, "\x1f\x8b") === 0) return Archive::COMPRESS_GZIP;
647*530d6729SAndreas Gohr        }
648*530d6729SAndreas Gohr
649*530d6729SAndreas Gohr        // otherwise rely on file name
650605f8e8dSAndreas Gohr        $file = strtolower($file);
651605f8e8dSAndreas Gohr        if (substr($file, -3) == '.gz' || substr($file, -4) == '.tgz') {
652*530d6729SAndreas Gohr            return Archive::COMPRESS_GZIP;
653605f8e8dSAndreas Gohr        } elseif (substr($file, -4) == '.bz2' || substr($file, -4) == '.tbz') {
654*530d6729SAndreas Gohr            return Archive::COMPRESS_BZIP;
655605f8e8dSAndreas Gohr        }
656*530d6729SAndreas Gohr
657*530d6729SAndreas Gohr        return Archive::COMPRESS_NONE;
658605f8e8dSAndreas Gohr    }
659605f8e8dSAndreas Gohr}
660