forked from joomla/joomla-cms
-
Notifications
You must be signed in to change notification settings - Fork 2
/
extract.php
1985 lines (1646 loc) · 59.8 KB
/
extract.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
/**
* @package Joomla.Administrator
* @subpackage com_joomlaupdate
*
* @copyright (C) 2021 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*
* @phpcs:disable PSR1.Classes.ClassDeclaration.MissingNamespace
*/
/**
* Should you want to debug this file, please add a new line ABOVE this comment with the following
* contents (excluding the space star space at the start of this line):
*
* define('_JOOMLA_UPDATE_DEBUG', 1);
*
* This will do two things:
* - it will create the joomla_update.txt file in your site's temporary directory (default: tmp).
* This file contains a debug log, detailing everything extract.php is doing during the extraction
* of the Joomla update ZIP file.
* - It will prevent extract.php from being overwritten during the update with a new version. This
* is useful if you are testing any changes in extract.php you do not want accidentally
* overwritten, or if you are given a modified extract.php by a Joomla core contributor with
* changes which might fix your update problem.
*/
\define('_JOOMLA_UPDATE', 1);
/**
* ZIP archive extraction class
*
* This is a derivative work of Akeeba Restore which is Copyright (c)2008-2021 Nicholas K.
* Dionysopoulos and Akeeba Ltd, distributed under the terms of GNU General Public License version 3
* or later.
*
* The author of the original work has decided to relicense the derivative work under the terms of
* the GNU General Public License version 2 or later and share the copyright of the derivative work
* with Open Source Matters, Inc (OSM), granting OSM non-exclusive rights to this work per the terms
* of the Joomla Contributor Agreement (JCA) the author signed back in 2011 and which is still in
* effect. This is affirmed by the cryptographically signed commits in the Git repository containing
* this file, the copyright messages and this notice here.
*
* @since 4.0.4
*/
class ZIPExtraction
{
/**
* How much data to read at once when processing files
*
* @var int
* @since 4.0.4
*/
private const CHUNK_SIZE = 524288;
/**
* Maximum execution time (seconds).
*
* Each page load will take at most this much time. Please note that if the ZIP archive contains fairly large,
* compressed files we may overshoot this time since we can't interrupt the decompression. This should not be an
* issue in the context of updating Joomla as the ZIP archive contains fairly small files.
*
* If this is too low it will cause too many requests to hit the server, potentially triggering a DoS protection and
* causing the extraction to fail. If this is too big the extraction will not be as verbose and the user might think
* something is broken. A value between 3 and 7 seconds is, therefore, recommended.
*
* @var int
* @since 4.0.4
*/
private const MAX_EXEC_TIME = 4;
/**
* Run-time execution bias (percentage points).
*
* We evaluate the time remaining on the timer before processing each file on the ZIP archive. If we have already
* consumed at least this much percentage of the MAX_EXEC_TIME we will stop processing the archive in this page
* load, return the result to the client and wait for it to call us again so we can resume the extraction.
*
* This becomes important when the MAX_EXEC_TIME is close to the PHP, PHP-FPM or Apache timeout on the server
* (whichever is lowest) and there are fairly large files in the backup archive. If we start extracting a large,
* compressed file close to a hard server timeout it's possible that we will overshoot that hard timeout and see the
* extraction failing.
*
* Since Joomla Update is used to extract a ZIP archive with many small files we can keep at a fairly high 90%
* without much fear that something will break.
*
* Example: if MAX_EXEC_TIME is 10 seconds and RUNTIME_BIAS is 80 each page load will take between 80% and 100% of
* the MAX_EXEC_TIME, i.e. anywhere between 8 and 10 seconds.
*
* Lower values make it less likely to overshoot MAX_EXEC_TIME when extracting large files.
*
* @var int
* @since 4.0.4
*/
private const RUNTIME_BIAS = 90;
/**
* Minimum execution time (seconds).
*
* A request cannot take less than this many seconds. If it does, we add “dead time” (sleep) where the script does
* nothing except wait. This is essentially a rate limiting feature to avoid hitting a server-side DoS protection
* which could be triggered if we ended up sending too many requests in a limited amount of time.
*
* This should normally be less than MAX_EXEC * (RUNTIME_BIAS / 100). Values between that and MAX_EXEC_TIME have the
* effect of almost always adding dead time in each request, unless a really large file is being extracted from the
* ZIP archive. Values larger than MAX_EXEC will always add dead time to the request. This can be useful to
* artificially reduce the CPU usage limit. Some servers might kill the request if they see a sustained CPU usage
* spike over a short period of time.
*
* The chosen value of 3 seconds belongs to the first category, essentially making sure that we have a decent rate
* limiting without annoying the user too much but also catering for the most badly configured of shared
* hosting. It's a happy medium which works for the majority (~90%) of commercial servers out there.
*
* @var int
* @since 4.0.4
*/
private const MIN_EXEC_TIME = 3;
/**
* Internal state when extracting files: we need to be initialised
*
* @var int
* @since 4.0.4
*/
private const AK_STATE_INITIALIZE = -1;
/**
* Internal state when extracting files: no file currently being extracted
*
* @var int
* @since 4.0.4
*/
private const AK_STATE_NOFILE = 0;
/**
* Internal state when extracting files: reading the file header
*
* @var int
* @since 4.0.4
*/
private const AK_STATE_HEADER = 1;
/**
* Internal state when extracting files: reading file data
*
* @var int
* @since 4.0.4
*/
private const AK_STATE_DATA = 2;
/**
* Internal state when extracting files: file data has been read thoroughly
*
* @var int
* @since 4.0.4
*/
private const AK_STATE_DATAREAD = 3;
/**
* Internal state when extracting files: post-processing the file
*
* @var int
* @since 4.0.4
*/
private const AK_STATE_POSTPROC = 4;
/**
* Internal state when extracting files: done with this file
*
* @var int
* @since 4.0.4
*/
private const AK_STATE_DONE = 5;
/**
* Internal state when extracting files: finished extracting the ZIP file
*
* @var int
* @since 4.0.4
*/
private const AK_STATE_FINISHED = 999;
/**
* Internal logging level: debug
*
* @var int
* @since 4.0.4
*/
private const LOG_DEBUG = 1;
/**
* Internal logging level: information
*
* @var int
* @since 4.0.4
*/
private const LOG_INFO = 10;
/**
* Internal logging level: warning
*
* @var int
* @since 4.0.4
*/
private const LOG_WARNING = 50;
/**
* Internal logging level: error
*
* @var int
* @since 4.0.4
*/
private const LOG_ERROR = 90;
/**
* Singleton instance
*
* @var null|self
* @since 4.0.4
*/
private static $instance = null;
/**
* Debug log file pointer resource
*
* @var null|resource|boolean
* @since 4.0.4
*/
private static $logFP = null;
/**
* Debug log filename
*
* @var null|string
* @since 4.0.4
*/
private static $logFilePath = null;
/**
* The total size of the ZIP archive
*
* @var integer
* @since 4.0.4
*/
public $totalSize = 0;
/**
* Which files to skip
*
* @var array
* @since 4.0.4
*/
public $skipFiles = [];
/**
* Current tally of compressed size read
*
* @var integer
* @since 4.0.4
*/
public $compressedTotal = 0;
/**
* Current tally of bytes written to disk
*
* @var integer
* @since 4.0.4
*/
public $uncompressedTotal = 0;
/**
* Current tally of files extracted
*
* @var integer
* @since 4.0.4
*/
public $filesProcessed = 0;
/**
* Maximum execution time allowance per step
*
* @var integer
* @since 4.0.4
*/
private $maxExecTime = null;
/**
* Timestamp of execution start
*
* @var integer
* @since 4.0.4
*/
private $startTime;
/**
* The last error message
*
* @var string|null
* @since 4.0.4
*/
private $lastErrorMessage = null;
/**
* Archive filename
*
* @var string
* @since 4.0.4
*/
private $filename = null;
/**
* Current archive part number
*
* @var boolean
* @since 4.0.4
*/
private $archiveFileIsBeingRead = false;
/**
* The offset inside the current part
*
* @var integer
* @since 4.0.4
*/
private $currentOffset = 0;
/**
* Absolute path to prepend to extracted files
*
* @var string
* @since 4.0.4
*/
private $addPath = '';
/**
* File pointer to the current archive part file
*
* @var resource|null
* @since 4.0.4
*/
private $fp = null;
/**
* Run state when processing the current archive file
*
* @var integer
* @since 4.0.4
*/
private $runState = self::AK_STATE_INITIALIZE;
/**
* File header data, as read by the readFileHeader() method
*
* @var stdClass
* @since 4.0.4
*/
private $fileHeader = null;
/**
* How much of the uncompressed data we've read so far
*
* @var integer
* @since 4.0.4
*/
private $dataReadLength = 0;
/**
* Unwritable files in these directories are always ignored and do not cause errors when not
* extracted.
*
* @var array
* @since 4.0.4
*/
private $ignoreDirectories = [];
/**
* Internal flag, set when the ZIP file has a data descriptor (which we will be ignoring)
*
* @var boolean
* @since 4.0.4
*/
private $expectDataDescriptor = false;
/**
* The UNIX last modification timestamp of the file last extracted
*
* @var integer
* @since 4.0.4
*/
private $lastExtractedFileTimestamp = 0;
/**
* The file path of the file last extracted
*
* @var string
* @since 4.0.4
*/
private $lastExtractedFilename = null;
/**
* Public constructor.
*
* Sets up the internal timer.
*
* @since 4.0.4
*/
public function __construct()
{
$this->setupMaxExecTime();
// Initialize start time
$this->startTime = microtime(true);
}
/**
* Singleton implementation.
*
* @return static
* @since 4.0.4
*/
public static function getInstance(): self
{
if (\is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Returns a serialised copy of the object.
*
* This is different to calling serialise() directly. This operates on a copy of the object which undergoes a
* call to shutdown() first so any open files are closed first.
*
* @return string The serialised data, potentially base64 encoded.
* @since 4.0.4
*/
public static function getSerialised(): string
{
$clone = clone self::getInstance();
$clone->shutdown();
$serialized = serialize($clone);
return (\function_exists('base64_encode') && \function_exists('base64_decode')) ? base64_encode($serialized) : $serialized;
}
/**
* Restores a serialised instance into the singleton implementation and returns it.
*
* If the serialised data is corrupt it will return null.
*
* @param string $serialised The serialised data, potentially base64 encoded, to deserialize.
*
* @return static|null The instance of the object, NULL if it cannot be deserialised.
* @since 4.0.4
*/
public static function unserialiseInstance(string $serialised): ?self
{
if (\function_exists('base64_encode') && \function_exists('base64_decode')) {
$serialised = base64_decode($serialised);
}
$instance = @unserialize($serialised, [
'allowed_classes' => [
self::class,
stdClass::class,
],
]);
if (($instance === false) || !\is_object($instance) || !($instance instanceof self)) {
return null;
}
self::$instance = $instance;
return self::$instance;
}
/**
* Wakeup function, called whenever the class is deserialized.
*
* This method does the following:
* - Restart the timer.
* - Reopen the archive file, if one is defined.
* - Seek to the correct offset of the file.
*
* @return void
* @since 4.0.4
* @internal
*/
public function __wakeup(): void
{
// Reset the timer when deserializing the object.
$this->startTime = microtime(true);
if (!$this->archiveFileIsBeingRead) {
return;
}
$this->fp = @fopen($this->filename, 'rb');
if ((\is_resource($this->fp)) && ($this->currentOffset > 0)) {
@fseek($this->fp, $this->currentOffset);
}
}
/**
* Enforce the minimum execution time.
*
* @return void
* @since 4.0.4
*/
public function enforceMinimumExecutionTime()
{
$elapsed = $this->getRunningTime() * 1000;
$minExecTime = 1000.0 * min(1, (min(self::MIN_EXEC_TIME, $this->getPhpMaxExecTime()) - 1));
// Only run a sleep delay if we haven't reached the minimum execution time
if (($minExecTime <= $elapsed) || ($elapsed <= 0)) {
return;
}
$sleepMillisec = \intval($minExecTime - $elapsed);
/**
* If we need to sleep for more than 1 second we should be using sleep() or time_sleep_until() to prevent high
* CPU usage, also because some OS might not support sleeping for over 1 second using these functions. In all
* other cases we will try to use usleep or time_nanosleep instead.
*/
$longSleep = $sleepMillisec > 1000;
$miniSleepSupported = \function_exists('usleep') || \function_exists('time_nanosleep');
if (!$longSleep && $miniSleepSupported) {
if (\function_exists('usleep') && ($sleepMillisec < 1000)) {
usleep(1000 * $sleepMillisec);
return;
}
if (\function_exists('time_nanosleep') && ($sleepMillisec < 1000)) {
time_nanosleep(0, 1000000 * $sleepMillisec);
return;
}
}
if (\function_exists('sleep')) {
sleep(ceil($sleepMillisec / 1000));
return;
}
if (\function_exists('time_sleep_until')) {
time_sleep_until(time() + ceil($sleepMillisec / 1000));
}
}
/**
* Set the filepath to the ZIP archive which will be extracted.
*
* @param string $value The filepath to the archive. Only LOCAL files are allowed!
*
* @return void
* @since 4.0.4
*/
public function setFilename(string $value)
{
// Security check: disallow remote filenames
if (!empty($value) && strpos($value, '://') !== false) {
$this->setError('Invalid archive location');
return;
}
$this->filename = $value;
$this->initializeLog(\dirname($this->filename));
}
/**
* Sets the path to prefix all extracted files with. Essentially, where the archive will be extracted to.
*
* @param string $addPath The path where the archive will be extracted.
*
* @return void
* @since 4.0.4
*/
public function setAddPath(string $addPath): void
{
$this->addPath = $addPath;
$this->addPath = str_replace('\\', '/', $this->addPath);
$this->addPath = rtrim($this->addPath, '/');
if (!empty($this->addPath)) {
$this->addPath .= '/';
}
}
/**
* Set the list of files to skip when extracting the ZIP file.
*
* @param array $skipFiles A list of files to skip when extracting the ZIP archive
*
* @return void
* @since 4.0.4
*/
public function setSkipFiles(array $skipFiles): void
{
$this->skipFiles = array_values($skipFiles);
}
/**
* Set the directories to skip over when extracting the ZIP archive
*
* @param array $ignoreDirectories The list of directories to ignore.
*
* @return void
* @since 4.0.4
*/
public function setIgnoreDirectories(array $ignoreDirectories): void
{
$this->ignoreDirectories = array_values($ignoreDirectories);
}
/**
* Prepares for the archive extraction
*
* @return void
* @since 4.0.4
*/
public function initialize(): void
{
$this->debugMsg(sprintf('Initializing extraction. Filepath: %s', $this->filename));
$this->totalSize = @filesize($this->filename) ?: 0;
$this->archiveFileIsBeingRead = false;
$this->currentOffset = 0;
$this->runState = self::AK_STATE_NOFILE;
$this->readArchiveHeader();
if (!empty($this->getError())) {
$this->debugMsg(sprintf('Error: %s', $this->getError()), self::LOG_ERROR);
return;
}
$this->archiveFileIsBeingRead = true;
$this->runState = self::AK_STATE_NOFILE;
$this->debugMsg('Setting state to NOFILE', self::LOG_DEBUG);
}
/**
* Executes a step of the archive extraction
*
* @return boolean True if we are done extracting or an error occurred
* @since 4.0.4
*/
public function step(): bool
{
$status = true;
$this->debugMsg('Starting a new step', self::LOG_INFO);
while ($status && ($this->getTimeLeft() > 0)) {
switch ($this->runState) {
case self::AK_STATE_INITIALIZE:
$this->debugMsg('Current run state: INITIALIZE', self::LOG_DEBUG);
$this->initialize();
break;
case self::AK_STATE_NOFILE:
$this->debugMsg('Current run state: NOFILE', self::LOG_DEBUG);
$status = $this->readFileHeader();
if ($status) {
$this->debugMsg('Found file header; updating number of files processed and bytes in/out', self::LOG_DEBUG);
// Update running tallies when we start extracting a file
$this->filesProcessed++;
$this->compressedTotal += \array_key_exists('compressed', get_object_vars($this->fileHeader))
? $this->fileHeader->compressed : 0;
$this->uncompressedTotal += $this->fileHeader->uncompressed;
}
break;
case self::AK_STATE_HEADER:
case self::AK_STATE_DATA:
$runStateHuman = $this->runState === self::AK_STATE_HEADER ? 'HEADER' : 'DATA';
$this->debugMsg(sprintf('Current run state: %s', $runStateHuman), self::LOG_DEBUG);
$status = $this->processFileData();
break;
case self::AK_STATE_DATAREAD:
case self::AK_STATE_POSTPROC:
$runStateHuman = $this->runState === self::AK_STATE_DATAREAD ? 'DATAREAD' : 'POSTPROC';
$this->debugMsg(sprintf('Current run state: %s', $runStateHuman), self::LOG_DEBUG);
$this->setLastExtractedFileTimestamp($this->fileHeader->timestamp);
$this->processLastExtractedFile();
$status = true;
$this->runState = self::AK_STATE_DONE;
break;
case self::AK_STATE_DONE:
default:
$this->debugMsg('Current run state: DONE', self::LOG_DEBUG);
$this->runState = self::AK_STATE_NOFILE;
break;
case self::AK_STATE_FINISHED:
$this->debugMsg('Current run state: FINISHED', self::LOG_DEBUG);
$status = false;
break;
}
if ($this->getTimeLeft() <= 0) {
$this->debugMsg('Ran out of time; the step will break.');
} elseif (!$status) {
$this->debugMsg('Last step status is false; the step will break.');
}
}
$error = $this->getError();
if (!empty($error)) {
$this->debugMsg(sprintf('Step failed with error: %s', $error), self::LOG_ERROR);
}
// Did we just finish or run into an error?
if (!empty($error) || $this->runState === self::AK_STATE_FINISHED) {
$this->debugMsg('Returning true (must stop running) from step()', self::LOG_DEBUG);
// Reset internal state, prevents __wakeup from trying to open a non-existent file
$this->archiveFileIsBeingRead = false;
return true;
}
$this->debugMsg('Returning false (must continue running) from step()', self::LOG_DEBUG);
return false;
}
/**
* Get the most recent error message
*
* @return string|null The message string, null if there's no error
* @since 4.0.4
*/
public function getError(): ?string
{
return $this->lastErrorMessage;
}
/**
* Gets the number of seconds left, before we hit the "must break" threshold
*
* @return float
* @since 4.0.4
*/
private function getTimeLeft(): float
{
return $this->maxExecTime - $this->getRunningTime();
}
/**
* Gets the time elapsed since object creation/unserialization, effectively how
* long Akeeba Engine has been processing data
*
* @return float
* @since 4.0.4
*/
private function getRunningTime(): float
{
return microtime(true) - $this->startTime;
}
/**
* Process the last extracted file or directory
*
* This invalidates OPcache for .php files. Also applies the correct permissions and timestamp.
*
* @return void
* @since 4.0.4
*/
private function processLastExtractedFile(): void
{
$this->debugMsg(sprintf('Processing last extracted entity: %s', $this->lastExtractedFilename), self::LOG_DEBUG);
if (@is_file($this->lastExtractedFilename)) {
@chmod($this->lastExtractedFilename, 0644);
clearFileInOPCache($this->lastExtractedFilename);
} else {
@chmod($this->lastExtractedFilename, 0755);
}
if ($this->lastExtractedFileTimestamp > 0) {
@touch($this->lastExtractedFilename, $this->lastExtractedFileTimestamp);
}
}
/**
* Set the last extracted filename
*
* @param string|null $lastExtractedFilename The last extracted filename
*
* @return void
* @since 4.0.4
*/
private function setLastExtractedFilename(?string $lastExtractedFilename): void
{
$this->lastExtractedFilename = $lastExtractedFilename;
}
/**
* Set the last modification UNIX timestamp for the last extracted file
*
* @param int $lastExtractedFileTimestamp The timestamp
*
* @return void
* @since 4.0.4
*/
private function setLastExtractedFileTimestamp(int $lastExtractedFileTimestamp): void
{
$this->lastExtractedFileTimestamp = $lastExtractedFileTimestamp;
}
/**
* Sleep function, called whenever the class is serialized
*
* @return void
* @since 4.0.4
* @internal
*/
private function shutdown(): void
{
if (\is_resource(self::$logFP)) {
@fclose(self::$logFP);
}
if (!\is_resource($this->fp)) {
return;
}
$this->currentOffset = @ftell($this->fp);
@fclose($this->fp);
}
/**
* Unicode-safe binary data length
*
* @param string|null $string The binary data to get the length for
*
* @return integer
* @since 4.0.4
*/
private function binStringLength(?string $string): int
{
if (\is_null($string)) {
return 0;
}
if (\function_exists('mb_strlen')) {
return mb_strlen($string, '8bit') ?: 0;
}
return \strlen($string) ?: 0;
}
/**
* Add an error message
*
* @param string $error Error message
*
* @return void
* @since 4.0.4
*/
private function setError(string $error): void
{
$this->lastErrorMessage = $error;
}
/**
* Reads data from the archive.
*
* @param resource $fp The file pointer to read data from
* @param int|null $length The volume of data to read, in bytes
*
* @return string The data read from the file
* @since 4.0.4
*/
private function fread($fp, ?int $length = null): string
{
$readLength = (is_numeric($length) && ($length > 0)) ? $length : PHP_INT_MAX;
$data = fread($fp, $readLength);
if ($data === false) {
$this->debugMsg('No more data could be read from the file', self::LOG_WARNING);
$data = '';
}
return $data;
}
/**
* Read the header of the archive, making sure it's a valid ZIP file.
*
* @return void
* @since 4.0.4
*/
private function readArchiveHeader(): void
{
$this->debugMsg('Reading the archive header.', self::LOG_DEBUG);
// Open the first part
$this->openArchiveFile();
// Fail for unreadable files
if ($this->fp === false) {
return;
}
// Read the header data.
$sigBinary = fread($this->fp, 4);
$headerData = unpack('Vsig', $sigBinary);
// We only support single part ZIP files
if ($headerData['sig'] != 0x04034b50) {
$this->setError('The archive file is corrupt: bad header');
return;
}
// Roll back the file pointer
fseek($this->fp, -4, SEEK_CUR);
$this->currentOffset = @ftell($this->fp);
$this->dataReadLength = 0;
}
/**
* Concrete classes must use this method to read the file header
*
* @return boolean True if reading the file was successful, false if an error occurred or we
* reached end of archive.
* @since 4.0.4
*/
private function readFileHeader(): bool
{
$this->debugMsg('Reading the file entry header.', self::LOG_DEBUG);
if (!\is_resource($this->fp)) {
$this->setError('The archive is not open for reading.');
return false;
}
// Unexpected end of file
if ($this->isEOF()) {
$this->debugMsg('EOF when reading file header data', self::LOG_WARNING);
$this->setError('The archive is corrupt or truncated');
return false;
}
$this->currentOffset = ftell($this->fp);
if ($this->expectDataDescriptor) {
$this->debugMsg('Expecting data descriptor (bit 3 of general purpose flag was set).', self::LOG_DEBUG);
/**
* The last file had bit 3 of the general purpose bit flag set. This means that we have a 12 byte data
* descriptor we need to skip. To make things worse, there might also be a 4 byte optional data descriptor
* header (0x08074b50).
*/
$junk = @fread($this->fp, 4);
$junk = unpack('Vsig', $junk);
$readLength = ($junk['sig'] == 0x08074b50) ? 12 : 8;
$junk = @fread($this->fp, $readLength);
// And check for EOF, too
if ($this->isEOF()) {
$this->debugMsg('EOF when reading data descriptor', self::LOG_WARNING);
$this->setError('The archive is corrupt or truncated');
return false;
}
}
// Get and decode Local File Header
$headerBinary = fread($this->fp, 30);
$format = 'Vsig/C2ver/vbitflag/vcompmethod/vlastmodtime/vlastmoddate/Vcrc/Vcompsize/'