-
Notifications
You must be signed in to change notification settings - Fork 9
/
szipinfo.php
1509 lines (1347 loc) · 43.7 KB
/
szipinfo.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
require_once dirname(__FILE__).'/archivereader.php';
require_once dirname(__FILE__).'/pipereader.php';
/**
* SzipInfo class.
*
* A simple class for inspecting 7-zip (.7z) archive files and listing information
* about their contents. Data can be streamed from a file or loaded directly.
*
* Technical note: this class is quite flakey, because of the many quirks of the 7z
* format spec. If you really must use it, you should be aware that:
*
* 1) The headers for 7z archives are at the start and the end of files. Most of
* the useful info about file contents is in the end headers. The data streams
* are packed in blocks between the start and end headers, without separators.
*
* 2) If you're handling 7z fragments, aim for the end of the file, or the last
* volume in a split set. That should at least get some filenames. Probably.
* The other volumes contain no headers at all, just split streams.
*
* 3) Headers are compressed by default by the 7-zip client, although this can be
* disabled manually with a switch that nobody uses. So ... this class is just
* about useless without using an external client to extract the headers.
*
* You probably want to give up at this point and try one of the wrappers for the
* 7-zip/7za clients or something with direct bindings, like these:
*
* Archive_7Z for PHP : https://github.com/Gemorroj/Archive_7z
* pyLZMA for Python : http://www.joachim-bauch.de/projects/pylzma/
*
* What you'll be missing is integration with the rest of the library, handling of
* archive fragments, and full recursive support through ArchiveInfo. Or just a
* way of digging deeper into the archive structure if needed. But configure that
* external client first! 7za.exe (Windows) or p7zip (*nix):
*
* @link http://www.7-zip.org/download.html
* @link http://p7zip.sourceforge.net/
*
* @author Hecks
* @copyright (c) 2010-2013 Hecks
* @license Modified BSD
* @version 1.4
*/
class SzipInfo extends ArchiveReader
{
// ------ Class constants -----------------------------------------------------
/**#@+
* 7z file format values
*/
// Main header types
const PROPERTY_HEADER = 0x01;
const PROPERTY_ARCHIVE_PROPERTIES = 0x02;
const PROPERTY_ADDITIONAL_STREAMS_INFO = 0x03;
const PROPERTY_MAIN_STREAMS_INFO = 0x04;
const PROPERTY_FILES_INFO = 0x05;
const PROPERTY_ENCODED_HEADER = 0x17;
// Streams Info
const PROPERTY_PACK_INFO = 0x06;
const PROPERTY_UNPACK_INFO = 0x07;
const PROPERTY_SUBSTREAMS_INFO = 0x08;
// Pack Info etc.
const PROPERTY_SIZE = 0x09;
const PROPERTY_CRC = 0x0a;
// Unpack Info
const PROPERTY_FOLDER = 0x0b;
const PROPERTY_CODERS_UNPACK_SIZE = 0x0c;
// Substreams Info
const PROPERTY_NUM_UNPACK_STREAM = 0x0d;
// Files Info
const PROPERTY_EMPTY_STREAM = 0x0e;
const PROPERTY_EMPTY_FILE = 0x0f;
const PROPERTY_ANTI = 0x10;
const PROPERTY_NAME = 0x11;
const PROPERTY_CREATION_TIME = 0x12;
const PROPERTY_LAST_ACCESS_TIME = 0x13;
const PROPERTY_LAST_WRITE_TIME = 0x14;
const PROPERTY_ATTRIBUTES = 0x15;
// General properties
const PROPERTY_END = 0x00;
const PROPERTY_COMMENT = 0x16;
const PROPERTY_START_POSITION = 0x18;
const PROPERTY_DUMMY = 0x19;
// Encoding methods
const METHOD_COPY = '00';
const METHOD_LZMA = '03';
const METHOD_CRYPTO = '06';
const METHOD_7Z_AES = '06f10701';
/**#@-*/
/**
* Byte string marking the start of the file/data.
*/
const MARKER_SIGNATURE = "7z\xbc\xaf\x27\x1c";
/**
* Type, format and size of the Start header following the signature.
*/
const START_HEADER = 0x100;
const START_HEADER_FORMAT = 'Cversion_major/Cversion_minor/Vhead_crc/Vnext_head_offset/Vnext_head_offset_high/Vnext_head_size/Vnext_head_size_high/Vnext_head_crc';
const START_HEADER_SIZE = 26;
// ------ Instance variables and methods ---------------------------------------
/**
* List of header names corresponding to header types.
* @var array
*/
protected $headerNames = array(
self::START_HEADER => 'Start',
self::PROPERTY_HEADER => 'Header',
self::PROPERTY_ADDITIONAL_STREAMS_INFO => 'Additional Streams Info',
self::PROPERTY_MAIN_STREAMS_INFO => 'Main Streams Info',
self::PROPERTY_FILES_INFO => 'Files Info',
self::PROPERTY_ENCODED_HEADER => 'Encoded Header',
self::PROPERTY_END => 'End',
);
/**
* Are the archive headers encrypted?
* @var boolean
*/
public $isEncrypted = false;
/**
* Is the archive packed as a solid stream?
* @var boolean
*/
public $isSolid = false;
/**
* The number of packed streams in the archive.
* @var integer
*/
public $blockCount = 0;
/**
* Convenience method that outputs a summary list of the file/data information,
* useful for pretty-printing.
*
* @param boolean $full add file list to output?
* @param boolean $skipDirs should directory entries be skipped?
* @return array file/data summary
*/
public function getSummary($full=false, $skipDirs=false)
{
$summary = array(
'file_name' => $this->file,
'file_size' => $this->fileSize,
'data_size' => $this->dataSize,
'use_range' => "{$this->start}-{$this->end}",
'solid_pack' => (int) $this->isSolid,
'enc_header' => (int) $this->hasEncodedHeader,
'is_encrypted' => (int) $this->isEncrypted,
'num_blocks' => $this->blockCount,
);
$fileList = $this->getFileList($skipDirs);
$summary['file_count'] = count($fileList);
if ($full) {
$summary['file_list'] = $fileList;
}
if ($this->error) {
$summary['error'] = $this->error;
}
return $summary;
}
/**
* Returns a list of the 7z headers found in the file/data in human-readable
* format (for debugging purposes only).
*
* @return array|boolean list of stored headers, or false if none available
*/
public function getHeaders()
{
if (empty($this->headers)) {return false;}
$ret = array();
foreach ($this->headers as $header) {
$h = array();
$h['type_name'] = isset($this->headerNames[$header['type']])
? $this->headerNames[$header['type']] : 'Unknown';
$h += $header;
$ret[] = $h;
}
return $ret;
}
/**
* Parses the stored headers and returns a list of records for each of the
* files in the archive.
*
* @param boolean $skipDirs should directory entries be skipped?
* @return array list of file records, empty if none are available
*/
public function getFileList($skipDirs=false)
{
// Check that headers are stored
if (!($info = $this->getFilesHeaderInfo()) || empty($info['files']))
return array();
// Files may be stored in their own folders or as substreams
$streams = $this->getMainStreamsInfo();
if (!empty($streams['substreams']['unpack_sizes'])) {
$unpackSizes = $streams['substreams']['unpack_sizes'];
} elseif (!empty($streams['folders'])) {
foreach ($streams['folders'] as $folder) {
$unpackSizes[] = $this->getFolderUnpackSize($folder);
}
}
$packRanges = $this->getPackedRanges();
$ret = array();
// Collate the file & streams info
$folderIndex = $sizeIndex = $streamIndex = 0;
foreach ($info['files'] as $file) {
$item = array(
'name' => substr($file['file_name'], 0, $this->maxFilenameLength),
'size' => ($file['has_stream'] && isset($unpackSizes[$sizeIndex])) ? $unpackSizes[$sizeIndex] : 0,
'date' => isset($file['utime']) ? $file['utime'] : 0,
'pass' => 0,
'compressed' => 0,
);
if (!empty($file['is_dir'])) {
if ($skipDirs) {continue;}
$item['is_dir'] = 1;
}
if ($file['has_stream']) {
$numStreamsInFolder = 1;
if (!empty($streams['folders'][$folderIndex])) {
$folder = $streams['folders'][$folderIndex];
$item['pass'] = $folder['is_encrypted'];
$item['compressed'] = $folder['is_compressed'];
$item['block'] = $folderIndex;
if (isset($streams['substreams']['num_unpack_streams'][$folderIndex])) {
$numStreamsInFolder = $streams['substreams']['num_unpack_streams'][$folderIndex];
}
}
if ($packRanges[$folderIndex] != null) {
$item['range'] = $packRanges[$folderIndex];
}
if (!empty($streams['substreams']['digests_defined'][$sizeIndex])) {
$item['crc32'] = dechex($streams['substreams']['digests'][$sizeIndex]);
}
if (++$streamIndex == $numStreamsInFolder) {
$streamIndex = 0;
$folderIndex++;
}
$sizeIndex++;
}
$ret[] = $item;
}
return $ret;
}
/**
* Retrieves the raw data for the given filename. Note that this is only useful
* if the file hasn't been compressed or encrypted.
*
* @param string $filename name of the file to retrieve
* @return mixed file data, or false if no file info available
*/
public function getFileData($filename)
{
// Check that headers are stored and data source is available
if (empty($this->headers) || ($this->data == '' && $this->handle == null)) {
return false;
}
// Get the absolute start/end positions
if (!($info = $this->getFileInfo($filename)) || empty($info['range'])) {
$this->error = "Could not find file info for: ({$filename})";
return false;
}
$this->error = '';
return $this->getRange(explode('-', $info['range']));
}
/**
* Saves the raw data for the given filename to the given destination. Note
* that this is only useful if the file isn't compressed or encrypted.
*
* @param string $filename name of the file to extract
* @param string $destination full path of the file to create
* @return integer|boolean number of bytes saved or false on error
*/
public function saveFileData($filename, $destination)
{
// Check that headers are stored and data source is available
if (empty($this->headers) || ($this->data == '' && $this->handle == null)) {
return false;
}
// Get the absolute start/end positions
if (!($info = $this->getFileInfo($filename)) || empty($info['range'])) {
$this->error = "Could not find file info for: ({$filename})";
return false;
}
$this->error = '';
return $this->saveRange(explode('-', $info['range']), $destination);
}
/**
* Sets the archive password for decoding encypted headers.
*
* @param string $password the password
* @return void
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Sets the absolute path to the external 7za client.
*
* @param string $client path to the client
* @return void
* @throws InvalidArgumentException
*/
public function setExternalClient($client)
{
if ($client && (!is_file($client) || !is_executable($client)))
throw new InvalidArgumentException("Not a valid client: {$client}");
$this->externalClient = $client;
}
/**
* Extracts a compressed or encrypted file using the configured external 7za
* client, optionally returning the data or saving it to file.
*
* @param string $filename name of the file to extract
* @param string $destination full path of the file to create
* @param string $password password to use for decryption
* @return mixed extracted data, number of bytes saved or false on error
*/
public function extractFile($filename, $destination=null, $password=null)
{
if (!$this->externalClient || (!$this->file && !$this->data)) {
$this->error = 'An external client and valid data source are needed';
return false;
}
// Check that the file is extractable
if (!($info = $this->getFileInfo($filename))) {
$this->error = "Could not find file info for: ({$filename})";
return false;
}
if (!empty($info['pass']) && $password == null) {
$this->error = "The file is passworded: ({$filename})";
return false;
}
// Set the data file source
$source = $this->file ? $this->file : $this->createTempDataFile();
// Set the external command
$pass = $password ? '-p'.escapeshellarg($password) : '';
$command = '"'.$this->externalClient.'"'
." e -so -bd -y -t7z {$pass} -- "
.escapeshellarg($source).' '.escapeshellarg($filename);
// Set STDERR to write to a temporary file
list($hash, $errorFile) = $this->getTempFileName($source.'errors');
$this->tempFiles[$hash] = $errorFile;
$command .= ' 2> '.escapeshellarg($errorFile);
// Start the new pipe reader
$pipe = new PipeReader;
if (!$pipe->open($command)) {
$this->error = $pipe->error;
return false;
}
$this->error = '';
// Open destination file or start buffer
if ($destination) {
$handle = fopen($destination, 'wb');
$written = 0;
} else {
$data = '';
}
// Buffer the piped data or save it to file
while ($read = $pipe->read(1024, false)) {
if ($destination) {
$written += fwrite($handle, $read);
} else {
$data .= $read;
}
}
if ($destination) {fclose($handle);}
$pipe->close();
// Check for errors (only after the pipe is closed)
if (($error = @file_get_contents($errorFile)) && strpos($error, 'Everything is Ok') === false) {
if ($destination) {@unlink($destination);}
$this->error = $error;
return false;
}
return $destination ? $written : $data;
}
/**
* Returns the position of the starting header signature in the file/data.
*
* @return mixed start position, or false if no valid signature found
*/
public function findMarker()
{
if ($this->markerPosition !== null)
return $this->markerPosition;
try {
$buff = $this->read(min($this->length, $this->maxReadBytes));
$this->rewind();
return $this->markerPosition = strpos($buff, self::MARKER_SIGNATURE);
} catch (Exception $e) {
return false;
}
}
/**
* List of headers found in the file/data.
* @var array
*/
protected $headers = array();
/**
* Are the archive headers encoded?
* @var boolean
*/
protected $hasEncodedHeader = false;
/**
* The archive password for decoding encrypted headers.
* @var string
*/
protected $password = '';
/**
* Full path to the external 7za client.
* @var string
*/
protected $externalClient = '';
/**
* Parses the 7z data and stores a list of valid headers locally.
*
* @return boolean false if parsing fails
*/
protected function analyze()
{
// Find the marker signature, if there is one
$startPos = $this->findMarker();
if ($startPos === false && !$this->isFragment) {
// Not a 7z fragment or valid file, so abort here
$this->error = 'Could not find marker signature, not a valid 7z file';
return false;
} elseif ($startPos !== false) {
// Unpack the Start header
$this->seek($startPos + strlen(self::MARKER_SIGNATURE));
$header = $this->readStartHeader();
$this->headers[] = $header;
// Go to the next header if available
$this->seek(min($header['next_offset'], $this->length));
} elseif ($this->isFragment) {
// Search for a valid header and continue unpacking from there
if (($startPos = $this->findHeader()) === false) {
$this->error = 'Could not find a valid 7z header';
return false;
}
$this->seek($startPos);
}
// Analyze all headers
while ($this->offset < $this->length) try {
// Get the next header
if (($header = $this->readNextHeader()) === false)
break;
// Add the current header to the list
$this->headers[] = $header;
// Skip to the next header, if any
if ($this->offset != $header['next_offset']) {
$this->seek($header['next_offset']);
}
// Sanity check
if ($header['offset'] == $this->offset) {
$this->error = 'Parsing seems to be stuck';
$this->close();
return false;
}
// No more readable data, or read error
} catch (Exception $e) {
if ($this->error) {$this->close(); return false;}
break;
}
// Check for valid headers
if (empty($this->headers)) {
$this->error = 'No valid 7z headers were found';
return false;
}
// Analysis was successful
if ($this->hasEncodedHeader && $this->externalClient) {
return $this->extractHeaders();
}
return true;
}
/**
* Searches for the position of a valid header up to maxReadBytes, and sets
* it as the start of the data to analyze.
*
* @return integer|boolean the header offset, or false if none is found
*/
protected function findHeader()
{
// Buffer the data to search
$start = $this->offset;
try {
$buffer = $this->read(min($this->length, $this->maxReadBytes));
$this->rewind();
} catch (Exception $e) {return false;}
// Get all the offsets to test
$searches = array(
'unencoded' => pack('C*', self::PROPERTY_HEADER, self::PROPERTY_MAIN_STREAMS_INFO),
'encoded' => pack('C*', self::PROPERTY_ENCODED_HEADER, self::PROPERTY_PACK_INFO),
);
if (!($positions = self::strposall($buffer, $searches)))
return false;
foreach ($positions as $offset => $matches) try {
$offset += $start;
$this->seek(($matches[0] == 'encoded') ? $offset : $offset + 1);
// Verify the Header or Encoded Header data
if (($header = $this->readNextHeader()) && $this->sanityCheckStreamsInfo($header)) {
return $this->markerPosition = $offset;
}
// No more readable data, or read error
} catch (Exception $e) {continue;}
return false;
}
/**
* Unpacks the Start header info from the current offset.
*
* @return array|boolean the Start header info, or false on error
*/
protected function readStartHeader()
{
$header = array(
'offset' => $this->offset,
'type' => self::START_HEADER,
);
try {
$header += self::unpack(self::START_HEADER_FORMAT, $this->read(self::START_HEADER_SIZE));
} catch (Exception $e) {
return false;
}
$header['next_head_offset'] = self::int64($header['next_head_offset'], $header['next_head_offset_high']);
$header['next_head_size'] = self::int64($header['next_head_size'], $header['next_head_size_high']);
$header['next_offset'] = $this->offset + $header['next_head_offset'];
$header['data_offset'] = $this->offset;
return $header;
}
/**
* Reads the start of the next header before further processing by type.
*
* @return array|boolean the next header info, or false on error
*/
protected function readNextHeader()
{
$header = array(
'offset' => $this->offset,
'type' => ord($this->read(1)),
'next_offset' => $this->length,
);
switch ($header['type']) {
// Start/end header markers
case self::PROPERTY_HEADER:
case self::PROPERTY_END:
$header['next_offset'] = $header['offset'] + 1;
return $header;
case self::PROPERTY_ARCHIVE_PROPERTIES:
return $this->processArchiveProperties($header);
case self::PROPERTY_ADDITIONAL_STREAMS_INFO:
case self::PROPERTY_MAIN_STREAMS_INFO:
case self::PROPERTY_ENCODED_HEADER:
return $this->processStreamsInfo($header);
case self::PROPERTY_FILES_INFO:
return $this->processFilesInfo($header);
// Unknown types
default:
return $header;
}
}
/**
* Reads & parses info about various archive streams from the current offset,
* and adds it to the given header record.
*
* @param array $header a valid header record
* @return boolean false on error
*/
protected function processStreamsInfo(&$header)
{
$nid = ord($this->read(1));
// Pack Info
if ($nid == self::PROPERTY_PACK_INFO) {
if (!$this->processPackInfo($header))
return false;
$this->isSolid = (bool) $header['is_solid'];
$nid = ord($this->read(1));
}
// Unpack Info
if ($nid == self::PROPERTY_UNPACK_INFO) {
if (!$this->processUnpackInfo($header))
return false;
$this->blockCount = $header['num_folders'];
$nid = ord($this->read(1));
}
// Substreams Info
if ($nid == self::PROPERTY_SUBSTREAMS_INFO) {
if (!$this->processSubstreamsInfo($header))
return false;
$nid = ord($this->read(1));
}
// End Streams Info
if (!$this->checkIsEnd($nid)) {return false;}
$this->hasEncodedHeader = ($header['type'] == self::PROPERTY_ENCODED_HEADER);
$header['next_offset'] = $this->offset;
return $header;
}
/**
* Reads & parses basic info about the packed streams in the archive.
*
* @param array $header a valid header record
* @return boolean false on error
*/
protected function processPackInfo(&$header)
{
$header['pack_offset'] = $this->readNumber();
$header['num_streams'] = $this->readNumber();
$header['is_solid'] = (int) ($header['num_streams'] == 1);
$nid = ord($this->read(1));
// Packed sizes
if ($nid == self::PROPERTY_SIZE) {
$header['pack_sizes'] = array();
for ($i = 0; $i < $header['num_streams']; $i++) {
$header['pack_sizes'][$i] = $this->readNumber();
}
$nid = ord($this->read(1));
// Packed CRC digests
if ($nid == self::PROPERTY_CRC) {
$digests = $this->readDigests($header['num_streams']);
$header['pack_digests_defined'] = array();
$header['pack_crcs'] = array();
for ($i = 0; $i < $header['num_streams']; $i++) {
$header['pack_digests_defined'][$i] = $digests['defined'][$i];
$header['pack_crcs'][$i] = $digests['crcs'][$i];
}
$nid = ord($this->read(1));
}
}
return $this->checkIsEnd($nid);
}
/**
* Reads & parses further info about the contents of the packed streams.
*
* @param array $header a valid header record
* @return boolean false on error
*/
protected function processUnpackInfo(&$header)
{
$nid = ord($this->read(1));
// Folders (packed stream blocks)
if ($nid != self::PROPERTY_FOLDER) {
$this->error = "Expecting PROPERTY_FOLDER but found: {$nid} at: ".($this->offset - 1);
return false;
}
$header['num_folders'] = $this->readNumber();
if (!$this->checkExternal()) {return false;}
$this->processFolders($header);
$nid = ord($this->read(1));
// Unpack sizes
if ($nid != self::PROPERTY_CODERS_UNPACK_SIZE) {
$this->error = "Expecting PROPERTY_CODERS_UNPACK_SIZE but found: {$nid} at: ".($this->offset - 1);
return false;
}
foreach ($header['folders'] as &$folder) {
$folder['unpack_sizes'] = array();
for ($i = 0; $i < $folder['total_out_streams']; $i++) {
$folder['unpack_sizes'][] = $this->readNumber();
}
}
$nid = ord($this->read(1));
// Unpack digests
if ($nid == self::PROPERTY_CRC) {
$digests = $this->readDigests($header['num_folders']);
for ($i = 0; $i < $header['num_folders']; $i++) {
$header['folders'][$i]['digest_defined'] = $digests['defined'][$i];
$header['folders'][$i]['unpack_crc'] = $digests['crcs'][$i];
}
$nid = ord($this->read(1));
}
return $this->checkIsEnd($nid);
}
/**
* Reads & parses info about the packed 'folders' or stream blocks. These
* may combine data from multiple files as substreams to improve compression,
* and may each use multiple (chained) encoding methods.
*
* @param array $header a valid header record
* @return void
*/
protected function processFolders(&$header)
{
$header['folders'] = array();
for ($f = 0; $f < $header['num_folders']; $f++) {
$folder = array(
'is_encrypted' => 0,
'is_compressed' => 0,
'num_coders' => $this->readNumber(),
);
$totalInStreams = $totalOutStreams = 0;
// Coders info
$folder['coders'] = array();
for ($c = 0; $c < $folder['num_coders']; $c++) {
$coder = array();
$coder['flags'] = ord($this->read(1));
$codecSize = $coder['flags'] & 0x0f;
$isComplex = $coder['flags'] & 0x10;
$hasProps = $coder['flags'] & 0x20;
// In/out streams
$coder += self::unpack('H*method', $this->read($codecSize));
$coder['num_in_streams'] = $isComplex ? $this->readNumber() : 1;
$coder['num_out_streams'] = $isComplex ? $this->readNumber() : 1;
$totalInStreams += $coder['num_in_streams'];
$totalOutStreams += $coder['num_out_streams'];
// Properties
if ($hasProps) {
$propSize = $this->readNumber();
$coder['prop_size'] = $propSize;
$coder += self::unpack('H*properties', $this->read($propSize));
}
$folder['coders'][] = $coder;
// Encryption & compression
if ($coder['method'] == self::METHOD_7Z_AES) {
$folder['is_encrypted'] = 1;
if ($header['type'] == self::PROPERTY_ENCODED_HEADER) {
$this->isEncrypted = true;
}
} elseif ($coder['method'] != self::METHOD_COPY) {
$folder['is_compressed'] = 1;
}
}
$folder['total_out_streams'] = $totalOutStreams;
$folder['total_in_streams'] = $totalInStreams;
// Bind pairs
$folder['num_bind_pairs'] = $numBindPairs = $totalOutStreams - 1;
$bindPairs = array();
if ($numBindPairs > 0) {
for ($p = 0; $p < $numBindPairs; $p++) {
$bindPairs[] = array(
'in' => $this->readNumber(),
'out' => $this->readNumber(),
);
}
$folder['bind_pairs'] = $bindPairs;
}
// Packed indexes
$folder['num_packed_streams'] = $numPackedStreams = $totalInStreams - $numBindPairs;
$packedIndexes = array();
if ($numPackedStreams == 1) {
for ($i = 0; $i < $totalInStreams; $i++) {
if ($this->findBindPair($bindPairs, $i, 'in') < 1) {
$packedIndexes[] = $i;
}
}
} elseif ($numPackedStreams > 1) {
for ($i = 0; $i < $numPackedStreams; $i++) {
$packedIndexes[] = $this->readNumber();
}
}
$folder['packed_indexes'] = $packedIndexes;
$header['folders'][] = $folder;
}
}
/**
* Reads & parses info about the substreams in each packed 'folder'.
*
* @param array $header a valid header record
* @return boolean false on error
*/
protected function processSubstreamsInfo(&$header)
{
if (empty($header['folders'])) {
$this->error = 'No folders found, cannot process substreams info';
return false;
}
$nid = ord($this->read(1));
$subs = array();
// Number of unpack streams in each folder
if ($nid == self::PROPERTY_NUM_UNPACK_STREAM) {
$subs['num_unpack_streams'] = array();
for ($i = 0; $i < $header['num_folders']; $i++) {
$subs['num_unpack_streams'][] = $this->readNumber();
}
$nid = ord($this->read(1));
} else {
$subs['num_unpack_streams'] = array_fill(0, $header['num_folders'], 1);
}
// Substream unpack sizes
if ($nid == self::PROPERTY_SIZE) {
$subs['unpack_sizes'] = array();
for ($i = 0; $i < $header['num_folders']; $i++) {
$sum = 0;
if (($numStreams = $subs['num_unpack_streams'][$i]) == 0)
continue;
for ($j = 1; $j < $numStreams; $j++) {
$size = $this->readNumber();
$subs['unpack_sizes'][] = $size;
$sum += $size;
}
$subs['unpack_sizes'][] = $this->getFolderUnpackSize($header['folders'][$i]) - $sum;
}
$nid = ord($this->read(1));
}
// Substream unpack digests (for streams with unknown CRC)
$numDigests = $numDigestsTotal = 0;
for ($i = 0; $i < $header['num_folders']; $i++) {
$numStreams = $subs['num_unpack_streams'][$i];
if ($numStreams != 1 || empty($header['folders'][$i]['digest_defined'])) {
$numDigests += $numStreams;
}
$numDigestsTotal += $numStreams;
}
if ($nid == self::PROPERTY_CRC) {
$subs['digests_defined'] = array();
$subs['digests'] = array();
$digests = $this->readDigests($numDigests);
$digestIndex = 0;
for ($i = 0; $i < $header['num_folders']; $i++) {
$numStreams = $subs['num_unpack_streams'][$i];
if ($numStreams == 1 && !empty($header['folders'][$i]['digest_defined'])) {
$subs['digests_defined'][] = 1;
$subs['digests'][] = $header['folders'][$i]['unpack_crc'];
} else {
for ($j = 0; $j < $numStreams; $j++, $digestIndex++) {
$subs['digests_defined'][] = $digests['defined'][$digestIndex];
$subs['digests'][] = $digests['crcs'][$digestIndex];
}
}
}
$nid = ord($this->read(1));
} else {
$subs['digests_defined'] = array_fill(0, $numDigestsTotal, 0);
$subs['digests'] = array_fill(0, $numDigestsTotal, 0);
}
$header['substreams'] = $subs;
return $this->checkIsEnd($nid);
}
/**
* Reads & parses information about the files stored in the archive.
*
* @param array $header a valid header record
* @return boolean false on error
*/
protected function processFilesInfo(&$header)
{
// Start the file list
$header['num_files'] = $this->fileCount = $this->readNumber();
$header['files'] = array();
for ($i = 0; $i < $header['num_files']; $i++) {
$header['files'][$i]['has_stream'] = 1;
}
$numEmptyStreams = 0;
// Read the file info properties
while ($this->offset < $this->length) {
// Property type & size
$type = $this->readNumber();
if ($type > 255) {
$this->error = "Invalid type, must be below 256: {$type} at: ".($this->offset - 1);
return false;
} elseif ($type == self::PROPERTY_END) {
break;
}
$size = $this->readNumber();
// File names
if ($type == self::PROPERTY_NAME) {
if (!$this->checkExternal()) {return false;}
foreach ($header['files'] as &$file) {
$name = '';
while ($this->offset < $this->length) {
$data = $this->read(2);
if ($data == "\x00\x00") {
$file['file_name'] = @iconv('UTF-16LE', 'UTF-8//IGNORE//TRANSLIT', $name);
break;
}
$name .= $data;
}
}
}
// File times
elseif ($type == self::PROPERTY_LAST_WRITE_TIME) {
$this->processFileTimes($header, 'mtime');
}
elseif ($type == self::PROPERTY_CREATION_TIME) {
$this->processFileTimes($header, 'ctime');
}
elseif ($type == self::PROPERTY_LAST_ACCESS_TIME) {
$this->processFileTimes($header, 'atime');
}
// File attributes
elseif ($type == self::PROPERTY_ATTRIBUTES) {
$defined = $this->readBooleans($header['num_files'], true);
if (!$this->checkExternal()) {return false;}
foreach ($header['files'] as $i => &$file) {
if ($defined[$i] == 1) {
$file += self::unpack('Vattributes', $this->read(4));
} else {
$file['attributes'] = null;
}
}
}