-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTar.php
1174 lines (1050 loc) · 29.9 KB
/
Tar.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// CopyPaste from https://github.com/splitbrain/php-archive
namespace core;
/**
* Class FileInfo
*
* stores meta data about a file in an Archive
*
* @author Andreas Gohr <[email protected]>
* @package splitbrain\PHPArchive
* @license MIT
*/
class FileInfo
{
protected $isdir = false;
protected $path = '';
protected $size = 0;
protected $csize = 0;
protected $mtime = 0;
protected $mode = 0664;
protected $owner = '';
protected $group = '';
protected $uid = 0;
protected $gid = 0;
protected $comment = '';
/**
* initialize dynamic defaults
*
* @param string $path The path of the file, can also be set later through setPath()
*/
public function __construct($path = '')
{
$this->mtime = time();
$this->setPath($path);
}
/**
* Factory to build FileInfo from existing file or directory
*
* @param string $path path to a file on the local file system
* @param string $as optional path to use inside the archive
* @throws FileInfoException
* @return FileInfo
*/
public static function fromPath($path, $as = '')
{
clearstatcache(false, $path);
if (!file_exists($path)) {
throw new FileInfoException("$path does not exist");
}
$stat = stat($path);
$file = new FileInfo();
$file->setPath($path);
$file->setIsdir(is_dir($path));
$file->setMode(fileperms($path));
$file->setOwner(fileowner($path));
$file->setGroup(filegroup($path));
$file->setSize(filesize($path));
$file->setUid($stat['uid']);
$file->setGid($stat['gid']);
$file->setMtime($stat['mtime']);
if ($as) {
$file->setPath($as);
}
return $file;
}
/**
* @return int the filesize. always 0 for directories
*/
public function getSize()
{
if ($this->isdir) {
return 0;
}
return $this->size;
}
/**
* @param int $size
*/
public function setSize($size)
{
$this->size = $size;
}
/**
* @return int
*/
public function getCompressedSize()
{
return $this->csize;
}
/**
* @param int $csize
*/
public function setCompressedSize($csize)
{
$this->csize = $csize;
}
/**
* @return int
*/
public function getMtime()
{
return $this->mtime;
}
/**
* @param int $mtime
*/
public function setMtime($mtime)
{
$this->mtime = $mtime;
}
/**
* @return int
*/
public function getGid()
{
return $this->gid;
}
/**
* @param int $gid
*/
public function setGid($gid)
{
$this->gid = $gid;
}
/**
* @return int
*/
public function getUid()
{
return $this->uid;
}
/**
* @param int $uid
*/
public function setUid($uid)
{
$this->uid = $uid;
}
/**
* @return string
*/
public function getComment()
{
return $this->comment;
}
/**
* @param string $comment
*/
public function setComment($comment)
{
$this->comment = $comment;
}
/**
* @return string
*/
public function getGroup()
{
return $this->group;
}
/**
* @param string $group
*/
public function setGroup($group)
{
$this->group = $group;
}
/**
* @return boolean
*/
public function getIsdir()
{
return $this->isdir;
}
/**
* @param boolean $isdir
*/
public function setIsdir($isdir)
{
// default mode for directories
if ($isdir && $this->mode === 0664) {
$this->mode = 0775;
}
$this->isdir = $isdir;
}
/**
* @return int
*/
public function getMode()
{
return $this->mode;
}
/**
* @param int $mode
*/
public function setMode($mode)
{
$this->mode = $mode;
}
/**
* @return string
*/
public function getOwner()
{
return $this->owner;
}
/**
* @param string $owner
*/
public function setOwner($owner)
{
$this->owner = $owner;
}
/**
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* @param string $path
*/
public function setPath($path)
{
$this->path = $this->cleanPath($path);
}
/**
* Cleans up a path and removes relative parts, also strips leading slashes
*
* @param string $path
* @return string
*/
protected function cleanPath($path)
{
$path = str_replace('\\', '/', $path);
$path = explode('/', $path);
$newpath = [];
foreach ($path as $p) {
if ($p === '' || $p === '.') {
continue;
}
if ($p === '..') {
array_pop($newpath);
continue;
}
array_push($newpath, $p);
}
return trim(implode('/', $newpath), '/');
}
/**
* Strip given prefix or number of path segments from the filename
*
* The $strip parameter allows you to strip a certain number of path components from the filenames
* found in the tar file, similar to the --strip-components feature of GNU tar. This is triggered when
* an integer is passed as $strip.
* Alternatively a fixed string prefix may be passed in $strip. If the filename matches this prefix,
* the prefix will be stripped. It is recommended to give prefixes with a trailing slash.
*
* @param int|string $strip
*/
public function strip($strip)
{
$filename = $this->getPath();
$striplen = strlen($strip);
if (is_int($strip)) {
// if $strip is an integer we strip this many path components
$parts = explode('/', $filename);
if (!$this->getIsdir()) {
$base = array_pop($parts); // keep filename itself
} else {
$base = '';
}
$filename = join('/', array_slice($parts, $strip));
if ($base) {
$filename .= "/$base";
}
} else {
// if strip is a string, we strip a prefix here
if (substr($filename, 0, $striplen) == $strip) {
$filename = substr($filename, $striplen);
}
}
$this->setPath($filename);
}
/**
* Does the file match the given include and exclude expressions?
*
* Exclude rules take precedence over include rules
*
* @param string $include Regular expression of files to include
* @param string $exclude Regular expression of files to exclude
* @return bool
*/
public function match($include = '', $exclude = '')
{
$extract = true;
if ($include && !preg_match($include, $this->getPath())) {
$extract = false;
}
if ($exclude && preg_match($exclude, $this->getPath())) {
$extract = false;
}
return $extract;
}
}
abstract class Archive
{
const COMPRESS_AUTO = -1;
const COMPRESS_NONE = 0;
const COMPRESS_GZIP = 1;
const COMPRESS_BZIP = 2;
/** @var callable */
protected $callback;
/**
* Set the compression level and type
*
* @param int $level Compression level (0 to 9)
* @param int $type Type of compression to use (use COMPRESS_* constants)
* @throws ArchiveIllegalCompressionException
*/
abstract public function setCompression($level = 9, $type = Archive::COMPRESS_AUTO);
/**
* Open an existing archive file for reading
*
* @param string $file
* @throws ArchiveIOException
*/
abstract public function open($file);
/**
* Read the contents of an archive
*
* This function lists the files stored in the archive, and returns an indexed array of FileInfo objects
*
* The archive is closed afer reading the contents, because rewinding is not possible in bzip2 streams.
* Reopen the file with open() again if you want to do additional operations
*
* @return FileInfo[]
*/
abstract public function contents();
/**
* Extract an existing archive
*
* The $strip parameter allows you to strip a certain number of path components from the filenames
* found in the archive file, similar to the --strip-components feature of GNU tar. This is triggered when
* an integer is passed as $strip.
* Alternatively a fixed string prefix may be passed in $strip. If the filename matches this prefix,
* the prefix will be stripped. It is recommended to give prefixes with a trailing slash.
*
* By default this will extract all files found in the archive. You can restrict the output using the $include
* and $exclude parameter. Both expect a full regular expression (including delimiters and modifiers). If
* $include is set, only files that match this expression will be extracted. Files that match the $exclude
* expression will never be extracted. Both parameters can be used in combination. Expressions are matched against
* stripped filenames as described above.
*
* The archive is closed afterwards. Reopen the file with open() again if you want to do additional operations
*
* @param string $outdir the target directory for extracting
* @param int|string $strip either the number of path components or a fixed prefix to strip
* @param string $exclude a regular expression of files to exclude
* @param string $include a regular expression of files to include
* @throws ArchiveIOException
* @return array
*/
abstract public function extract($outdir, $strip = '', $exclude = '', $include = '');
/**
* Create a new archive file
*
* If $file is empty, the archive file will be created in memory
*
* @param string $file
*/
abstract public function create($file = '');
/**
* Add a file to the current archive using an existing file in the filesystem
*
* @param string $file path to the original file
* @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
* @throws ArchiveIOException
*/
abstract public function addFile($file, $fileinfo = '');
/**
* Add a file to the current archive using the given $data as content
*
* @param string|FileInfo $fileinfo either the name to us in archive (string) or a FileInfo oject with all meta data
* @param string $data binary content of the file to add
* @throws ArchiveIOException
*/
abstract public function addData($fileinfo, $data);
/**
* Close the archive, close all file handles
*
* After a call to this function no more data can be added to the archive, for
* read access no reading is allowed anymore
*/
abstract public function close();
/**
* Returns the created in-memory archive data
*
* This implicitly calls close() on the Archive
*/
abstract public function getArchive();
/**
* Save the created in-memory archive data
*
* Note: It is more memory effective to specify the filename in the create() function and
* let the library work on the new file directly.
*
* @param string $file
*/
abstract public function save($file);
/**
* Set a callback function to be called whenever a file is added or extracted.
*
* The callback is called with a FileInfo object as parameter. You can use this to show progress
* info during an operation.
*
* @param callable $callback
*/
public function setCallback($callback)
{
$this->callback = $callback;
}
}
/**
* Class Tar
*
* Creates or extracts Tar archives. Supports gz and bzip compression
*
* Long pathnames (>100 chars) are supported in POSIX ustar and GNU longlink formats.
*
* @author Andreas Gohr <[email protected]>
* @package splitbrain\PHPArchive
* @license MIT
*/
class Tar extends Archive
{
protected $file = '';
protected $comptype = Archive::COMPRESS_AUTO;
protected $complevel = 9;
protected $fh;
protected $memory = '';
protected $closed = true;
protected $writeaccess = false;
/**
* Sets the compression to use
*
* @param int $level Compression level (0 to 9)
* @param int $type Type of compression to use (use COMPRESS_* constants)
* @throws ArchiveIllegalCompressionException
*/
public function setCompression($level = 9, $type = Archive::COMPRESS_AUTO)
{
$this->compressioncheck($type);
if ($level < -1 || $level > 9) {
throw new ArchiveIllegalCompressionException('Compression level should be between -1 and 9');
}
$this->comptype = $type;
$this->complevel = $level;
if ($level == 0) {
$this->comptype = Archive::COMPRESS_NONE;
}
if ($type == Archive::COMPRESS_NONE) {
$this->complevel = 0;
}
}
/**
* Open an existing TAR file for reading
*
* @param string $file
* @throws ArchiveIOException
* @throws ArchiveIllegalCompressionException
*/
public function open($file)
{
$this->file = $file;
// update compression to mach file
if ($this->comptype == Tar::COMPRESS_AUTO) {
$this->setCompression($this->complevel, $this->filetype($file));
}
// open file handles
if ($this->comptype === Archive::COMPRESS_GZIP) {
$this->fh = @gzopen($this->file, 'rb');
} elseif ($this->comptype === Archive::COMPRESS_BZIP) {
$this->fh = @bzopen($this->file, 'r');
} else {
$this->fh = @fopen($this->file, 'rb');
}
if (!$this->fh) {
throw new ArchiveIOException('Could not open file for reading: '.$this->file);
}
$this->closed = false;
}
/**
* Read the contents of a TAR archive
*
* This function lists the files stored in the archive
*
* The archive is closed afer reading the contents, because rewinding is not possible in bzip2 streams.
* Reopen the file with open() again if you want to do additional operations
*
* @throws ArchiveIOException
* @throws ArchiveCorruptedException
* @returns FileInfo[]
*/
public function contents()
{
if ($this->closed || !$this->file) {
throw new ArchiveIOException('Can not read from a closed archive');
}
$result = [];
while ($read = $this->readbytes(512)) {
$header = $this->parseHeader($read);
if (!is_array($header)) {
continue;
}
$this->skipbytes(ceil($header['size'] / 512) * 512);
$result[] = $this->header2fileinfo($header);
}
$this->close();
return $result;
}
/**
* Extract an existing TAR archive
*
* The $strip parameter allows you to strip a certain number of path components from the filenames
* found in the tar file, similar to the --strip-components feature of GNU tar. This is triggered when
* an integer is passed as $strip.
* Alternatively a fixed string prefix may be passed in $strip. If the filename matches this prefix,
* the prefix will be stripped. It is recommended to give prefixes with a trailing slash.
*
* By default this will extract all files found in the archive. You can restrict the output using the $include
* and $exclude parameter. Both expect a full regular expression (including delimiters and modifiers). If
* $include is set only files that match this expression will be extracted. Files that match the $exclude
* expression will never be extracted. Both parameters can be used in combination. Expressions are matched against
* stripped filenames as described above.
*
* The archive is closed afer reading the contents, because rewinding is not possible in bzip2 streams.
* Reopen the file with open() again if you want to do additional operations
*
* @param string $outdir the target directory for extracting
* @param int|string $strip either the number of path components or a fixed prefix to strip
* @param string $exclude a regular expression of files to exclude
* @param string $include a regular expression of files to include
* @throws ArchiveIOException
* @throws ArchiveCorruptedException
* @return FileInfo[]
*/
public function extract($outdir, $strip = '', $exclude = '', $include = '')
{
if ($this->closed || !$this->file) {
throw new ArchiveIOException('Can not read from a closed archive');
}
$outdir = rtrim($outdir, '/');
if (! file_exists($outdir)) {
@mkdir($outdir, 0777, true);
}
if (!is_dir($outdir)) {
throw new ArchiveIOException("Could not create directory '$outdir'");
}
$extracted = [];
while ($dat = $this->readbytes(512)) {
// read the file header
$header = $this->parseHeader($dat);
if (!is_array($header)) {
continue;
}
$fileinfo = $this->header2fileinfo($header);
// apply strip rules
$fileinfo->strip($strip);
// skip unwanted files
if (!strlen($fileinfo->getPath()) || !$fileinfo->match($include, $exclude)) {
$this->skipbytes(ceil($header['size'] / 512) * 512);
continue;
}
// create output directory
$output = $outdir.'/'.$fileinfo->getPath();
$directory = ($fileinfo->getIsdir()) ? $output : dirname($output);
if (! file_exists($directory)) {
@mkdir($directory, 0777, true);
}
// extract data
if (!$fileinfo->getIsdir()) {
$fp = @fopen($output, "wb");
if (!$fp) {
throw new ArchiveIOException('Could not open file for writing: '.$output);
}
$size = floor($header['size'] / 512);
for ($i = 0; $i < $size; $i++) {
fwrite($fp, $this->readbytes(512), 512);
}
if (($header['size'] % 512) != 0) {
fwrite($fp, $this->readbytes(512), $header['size'] % 512);
}
fclose($fp);
@touch($output, $fileinfo->getMtime());
@chmod($output, $fileinfo->getMode());
} else {
$this->skipbytes(ceil($header['size'] / 512) * 512); // the size is usually 0 for directories
}
if (is_callable($this->callback)) {
call_user_func($this->callback, $fileinfo);
}
$extracted[] = $fileinfo;
}
$this->close();
return $extracted;
}
/**
* Create a new TAR file
*
* If $file is empty, the tar file will be created in memory
*
* @param string $file
* @throws ArchiveIOException
* @throws ArchiveIllegalCompressionException
*/
public function create($file = '')
{
$this->file = $file;
$this->memory = '';
$this->fh = 0;
if ($this->file) {
// determine compression
if ($this->comptype == Archive::COMPRESS_AUTO) {
$this->setCompression($this->complevel, $this->filetype($file));
}
if ($this->comptype === Archive::COMPRESS_GZIP) {
$this->fh = @gzopen($this->file, 'wb'.$this->complevel);
} elseif ($this->comptype === Archive::COMPRESS_BZIP) {
$this->fh = @bzopen($this->file, 'w');
} else {
$this->fh = @fopen($this->file, 'wb');
}
if (!$this->fh) {
throw new ArchiveIOException('Could not open file for writing: '.$this->file);
}
}
$this->writeaccess = true;
$this->closed = false;
}
/**
* Add a file to the current TAR archive using an existing file in the filesystem
*
* @param string $file path to the original file
* @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
* @throws ArchiveCorruptedException when the file changes while reading it, the archive will be corrupt and should be deleted
* @throws ArchiveIOException there was trouble reading the given file, it was not added
* @throws FileInfoException trouble reading file info, it was not added
*/
public function addFile($file, $fileinfo = '')
{
if (is_string($fileinfo)) {
$fileinfo = FileInfo::fromPath($file, $fileinfo);
}
if ($this->closed) {
throw new ArchiveIOException('Archive has been closed, files can no longer be added');
}
$fp = @fopen($file, 'rb');
if (!$fp) {
throw new ArchiveIOException('Could not open file for reading: '.$file);
}
// create file header
$this->writeFileHeader($fileinfo);
// write data
$read = 0;
while (!feof($fp)) {
$data = fread($fp, 512);
$read += strlen($data);
if ($data === false) {
break;
}
if ($data === '') {
break;
}
$packed = pack("a512", $data);
$this->writebytes($packed);
}
fclose($fp);
if ($read != $fileinfo->getSize()) {
$this->close();
throw new ArchiveCorruptedException("The size of $file changed while reading, archive corrupted. read $read expected ".$fileinfo->getSize());
}
if (is_callable($this->callback)) {
call_user_func($this->callback, $fileinfo);
}
}
/**
* Add a file to the current TAR archive using the given $data as content
*
* @param string|FileInfo $fileinfo either the name to us in archive (string) or a FileInfo oject with all meta data
* @param string $data binary content of the file to add
* @throws ArchiveIOException
*/
public function addData($fileinfo, $data)
{
if (is_string($fileinfo)) {
$fileinfo = new FileInfo($fileinfo);
}
if ($this->closed) {
throw new ArchiveIOException('Archive has been closed, files can no longer be added');
}
$len = strlen($data);
$fileinfo->setSize($len);
$this->writeFileHeader($fileinfo);
for ($s = 0; $s < $len; $s += 512) {
$this->writebytes(pack("a512", substr($data, $s, 512)));
}
if (is_callable($this->callback)) {
call_user_func($this->callback, $fileinfo);
}
}
/**
* Add the closing footer to the archive if in write mode, close all file handles
*
* After a call to this function no more data can be added to the archive, for
* read access no reading is allowed anymore
*
* "Physically, an archive consists of a series of file entries terminated by an end-of-archive entry, which
* consists of two 512 blocks of zero bytes"
*
* @link http://www.gnu.org/software/tar/manual/html_chapter/tar_8.html#SEC134
* @throws ArchiveIOException
*/
public function close()
{
if ($this->closed) {
return;
} // we did this already
// write footer
if ($this->writeaccess) {
$this->writebytes(pack("a512", ""));
$this->writebytes(pack("a512", ""));
}
// close file handles
if ($this->file) {
if ($this->comptype === Archive::COMPRESS_GZIP) {
gzclose($this->fh);
} elseif ($this->comptype === Archive::COMPRESS_BZIP) {
bzclose($this->fh);
} else {
fclose($this->fh);
}
$this->file = '';
$this->fh = 0;
}
$this->writeaccess = false;
$this->closed = true;
}
/**
* Returns the created in-memory archive data
*
* This implicitly calls close() on the Archive
* @throws ArchiveIOException
*/
public function getArchive()
{
$this->close();
if ($this->comptype === Archive::COMPRESS_AUTO) {
$this->comptype = Archive::COMPRESS_NONE;
}
if ($this->comptype === Archive::COMPRESS_GZIP) {
return gzencode($this->memory, $this->complevel);
}
if ($this->comptype === Archive::COMPRESS_BZIP) {
return bzcompress($this->memory);
}
return $this->memory;
}
/**
* Save the created in-memory archive data
*
* Note: It more memory effective to specify the filename in the create() function and
* let the library work on the new file directly.
*
* @param string $file
* @throws ArchiveIOException
* @throws ArchiveIllegalCompressionException
*/
public function save($file)
{
if ($this->comptype === Archive::COMPRESS_AUTO) {
$this->setCompression($this->complevel, $this->filetype($file));
}
if (!@file_put_contents($file, $this->getArchive())) {
throw new ArchiveIOException('Could not write to file: '.$file);
}
}
/**
* Read from the open file pointer
*
* @param int $length bytes to read
* @return string
*/
protected function readbytes($length)
{
if ($this->comptype === Archive::COMPRESS_GZIP) {
return @gzread($this->fh, $length);
} elseif ($this->comptype === Archive::COMPRESS_BZIP) {
return @bzread($this->fh, $length);
} else {
return @fread($this->fh, $length);
}
}
/**
* Write to the open filepointer or memory
*
* @param string $data
* @throws ArchiveIOException
* @return int number of bytes written
*/
protected function writebytes($data)
{
if (!$this->file) {
$this->memory .= $data;
$written = strlen($data);
} elseif ($this->comptype === Archive::COMPRESS_GZIP) {
$written = @gzwrite($this->fh, $data);
} elseif ($this->comptype === Archive::COMPRESS_BZIP) {
$written = @bzwrite($this->fh, $data);
} else {
$written = @fwrite($this->fh, $data);
}
if ($written === false) {
throw new ArchiveIOException('Failed to write to archive stream');
}
return $written;
}
/**
* Skip forward in the open file pointer
*
* This is basically a wrapper around seek() (and a workaround for bzip2)
*
* @param int $bytes seek to this position
*/
protected function skipbytes($bytes)
{
if ($this->comptype === Archive::COMPRESS_GZIP) {
@gzseek($this->fh, $bytes, SEEK_CUR);
} elseif ($this->comptype === Archive::COMPRESS_BZIP) {
// there is no seek in bzip2, we simply read on
// bzread allows to read a max of 8kb at once
while ($bytes) {
$toread = min(8192, $bytes);
@bzread($this->fh, $toread);
$bytes -= $toread;
}
} else {
@fseek($this->fh, $bytes, SEEK_CUR);
}
}
/**
* Write the given file meta data as header
*
* @param FileInfo $fileinfo
* @throws ArchiveIOException
*/
protected function writeFileHeader(FileInfo $fileinfo)
{
$this->writeRawFileHeader(
$fileinfo->getPath(),
$fileinfo->getUid(),
$fileinfo->getGid(),
$fileinfo->getMode(),
$fileinfo->getSize(),
$fileinfo->getMtime(),
$fileinfo->getIsdir() ? '5' : '0'
);
}
/**
* Write a file header to the stream
*
* @param string $name
* @param int $uid
* @param int $gid
* @param int $perm
* @param int $size
* @param int $mtime
* @param string $typeflag Set to '5' for directories
* @throws ArchiveIOException
*/
protected function writeRawFileHeader($name, $uid, $gid, $perm, $size, $mtime, $typeflag = '')
{
// handle filename length restrictions
$prefix = '';
$namelen = strlen($name);
if ($namelen > 100) {
$file = basename($name);
$dir = dirname($name);
if (strlen($file) > 100 || strlen($dir) > 155) {
// we're still too large, let's use GNU longlink
$this->writeRawFileHeader('././@LongLink', 0, 0, 0, $namelen, 0, 'L');
for ($s = 0; $s < $namelen; $s += 512) {
$this->writebytes(pack("a512", substr($name, $s, 512)));
}
$name = substr($name, 0, 100); // cut off name
} else {
// we're fine when splitting, use POSIX ustar
$prefix = $dir;
$name = $file;
}