forked from Grandt/PHPZip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Zip.php
643 lines (565 loc) · 20.3 KB
/
Zip.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
<?php
/**
* Class to create and manage a Zip file.
*
* Inspired by CreateZipFile by Rochak Chauhan www.rochakchauhan.com (http://www.phpclasses.org/browse/package/2322.html)
* and
* http://www.pkware.com/documents/casestudies/APPNOTE.TXT Zip file specification.
*
* License: GNU LGPL, Attribution required for commercial implementations, requested for everything else.
*
* @author A. Grandt
* @copyright A. Grandt 2009-2011
* @license GNU LGPL, Attribution required for commercial implementations, requested for everything else.
* @link http://www.phpclasses.org/package/6110
* @version 1.28
*/
class Zip {
const VERSION = 1.28;
const ZIP_LOCAL_FILE_HEADER = "\x50\x4b\x03\x04"; // Local file header signature
const ZIP_CENTRAL_FILE_HEADER = "\x50\x4b\x01\x02"; // Central file header signature
const ZIP_END_OF_CENTRAL_DIRECTORY = "\x50\x4b\x05\x06\x00\x00\x00\x00"; //end of Central directory record
const EXT_FILE_ATTR_DIR = "\x10\x40\xed\x41"; // Unix : Dir + mod:755
const EXT_FILE_ATTR_FILE = "\x00\x40\xa4\x81"; // Unix : File + mod:644
const ATTR_VERSION_TO_EXTRACT = "\x0A\x00"; // Version needed to extract
const ATTR_MADE_BY_VERSION = "\x15\x03"; // Made By Version
private $zipMemoryThreshold = 1048576; // Autocreate tempfile if the zip data exceeds 1048576 bytes (1 MB)
private $zipData = NULL;
private $zipFile = NULL;
private $zipComment = NULL;
private $cdRec = array(); // central directory
private $offset = 0;
private $isFinalized = FALSE;
private $addExtraFields = TRUE;
private $streamChunkSize = 65536;
private $streamFilePath = NULL;
private $streamTimeStamp = NULL;
private $streamComment = NULL;
private $streamFile = NULL;
private $streamData = NULL;
private $streamFileLength = 0;
/**
* Constructor.
*
* @param $useZipFile boolean. Write temp zip data to tempFile? Default FALSE
*/
function __construct($useZipFile = FALSE) {
if ($useZipFile) {
$this->zipFile = tmpfile();
} else {
$this->zipData = "";
}
}
function __destruct() {
if (!is_null($this->zipFile)) {
fclose($this->zipFile);
}
$this->zipData = NULL;
}
/**
* Extra fields on the Zip directory records are Unix time codes needed for compatibility on the default Mac zip archive tool.
* These are enabled as default, as they do no harm elsewhere and only add 26 bytes per file added.
*
* @param bool $setExtraField TRUE (default) will enable adding of extra fields, anything else will disable it.
*/
function setExtraField($setExtraField = TRUE) {
$this->addExtraFields = ($setExtraField === TRUE);
}
/**
* Set Zip archive comment.
*
* @param String $newComment New comment. NULL to clear.
* @return bool $success
*/
public function setComment($newComment = NULL) {
if ($this->isFinalized) {
return FALSE;
}
$this->zipComment = $newComment;
return TRUE;
}
/**
* Set zip file to write zip data to.
* This will cause all present and future data written to this class to be written to this file.
* This can be used at any time, even after the Zip Archive have been finalized. Any previous file will be closed.
* Warning: If the given file already exists, it will be overwritten.
*
* @param String $fileName
* @return bool $success
*/
public function setZipFile($fileName) {
if (file_exists($fileName)) {
unlink ($fileName);
}
$fd=fopen($fileName, "x+b");
if (!is_null($this->zipFile)) {
rewind($this->zipFile);
while(!feof($this->zipFile)) {
fwrite($fd, fread($this->zipFile, $this->streamChunkSize));
}
fclose($this->zipFile);
} else {
fwrite($fd, $this->zipData);
$this->zipData = NULL;
}
$this->zipFile = $fd;
return TRUE;
}
/**
* Add an empty directory entry to the zip archive.
* Basically this is only used if an empty directory is added.
*
* @param String $directoryPath Directory Path and name to be added to the archive.
* @param int $timestamp (Optional) Timestamp for the added directory, if omitted or set to 0, the current time will be used.
* @param String $fileComment (Optional) Comment to be added to the archive for this directory. To use fileComment, timestamp must be given.
* @return bool $success
*/
public function addDirectory($directoryPath, $timestamp = 0, $fileComment = NULL) {
if ($this->isFinalized) {
return FALSE;
}
$this->buildZipEntry($directoryPath, $fileComment, "\x00\x00", "\x00\x00", $timestamp, "\x00\x00\x00\x00", 0, 0, self::EXT_FILE_ATTR_DIR);
return TRUE;
}
/**
* Add a file to the archive at the specified location and file name.
*
* @param String $data File data.
* @param String $filePath Filepath and name to be used in the archive.
* @param int $timestamp (Optional) Timestamp for the added file, if omitted or set to 0, the current time will be used.
* @param String $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given.
* @return bool $success
*/
public function addFile($data, $filePath, $timestamp = 0, $fileComment = NULL) {
if ($this->isFinalized) {
return FALSE;
}
$gzType = "\x08\x00"; // Compression type 8 = deflate
$gpFlags = "\x02\x00"; // General Purpose bit flags for compression type 8 it is: 0=Normal, 1=Maximum, 2=Fast, 3=super fast compression.
$dataLength = strlen($data);
$fileCRC32 = pack("V", crc32($data));
$gzData = gzcompress($data);
$gzData = substr( substr($gzData, 0, strlen($gzData) - 4), 2); // gzcompress adds a 2 byte header and 4 byte CRC we can't use.
// The 2 byte header does contain useful data, though in this case the 2 parameters we'd be interrested in will always be 8 for compression type, and 2 for General purpose flag.
$gzLength = strlen($gzData);
if ($gzLength >= $dataLength) {
$gzLength = $dataLength;
$gzData = $data;
$gzType = "\x00\x00"; // Compression type 0 = stored
$gpFlags = "\x00\x00"; // Compression type 0 = stored
}
if (is_null($this->zipFile) && ($this->offset + $gzLength) > $this->zipMemoryThreshold) {
$this->zipFile = tmpfile();
fwrite($this->zipFile, $this->zipData);
$this->zipData = NULL;
}
$this->buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, self::EXT_FILE_ATTR_FILE);
if (is_null($this->zipFile)) {
$this->zipData .= $gzData;
} else {
fwrite($this->zipFile, $gzData);
}
return TRUE;
}
/**
* Add the content to a directory.
*
* @author Adam Schmalhofer <[email protected]>
* @author A. Grandt
*
* @param String $realPath Path on the file system.
* @param String $zipPath Filepath and name to be used in the archive.
* @param bool $recursive Add content recursively, default is TRUE.
* @param bool $followSymlinks Follow and add symbolic links, if they are accessible, default is TRUE.
* @param array $addedFiles Reference to the added files, this is used to prevent duplicates, efault is an empty array.
* If you start the function by parsing an array, the array will be populated with the realPath
* and zipPath kay/value pairs added to the archive by the function.
*/
public function addDirectoryContent($realPath, $zipPath, $recursive = TRUE, $followSymlinks = TRUE, &$addedFiles = array()) {
if (file_exists($realPath) && !isset($addedFiles[realpath($realPath)])) {
if (is_dir($realPath)) {
$this->addDirectory($zipPath);
}
$addedFiles[realpath($realPath)] = $zipPath;
$iter = new DirectoryIterator($realPath);
foreach ($iter as $file) {
if ($file->isDot()) {
continue;
}
$newRealPath = $file->getPathname();
$newZipPath = self::pathJoin($zipPath, $file->getFilename());
if(file_exists($newRealPath) && ($folowSymliks === TRUE || !is_link($newRealPath))) {
if ($file->isFile()) {
$addedFiles[realpath($newRealPath)] = $newZipPath;
$this->addLargeFile($newRealPath, $newZipPath);
} else if ($recursive === TRUE) {
$this->addDirectoryContent($newRealPath, $newZipPath, $recursive);
} else {
$this->addDirectory($zipPath);
}
}
}
}
}
/**
* Add a file to the archive at the specified location and file name.
*
* @param String $dataFile File name/path.
* @param String $filePath Filepath and name to be used in the archive.
* @param int $timestamp (Optional) Timestamp for the added file, if omitted or set to 0, the current time will be used.
* @param String $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given.
* @return bool $success
*/
public function addLargeFile($dataFile, $filePath, $timestamp = 0, $fileComment = NULL) {
if ($this->isFinalized) {
return FALSE;
}
$this->openStream($filePath, $timestamp, $fileComment);
$fh = fopen($dataFile, "rb");
while(!feof($fh)) {
$this->addStreamData(fread($fh, $this->streamChunkSize));
}
fclose($fh);
$this->closeStream($this->addExtraField);
return TRUE;
}
/**
* Create a stream to be used for large entries.
*
* @param String $filePath Filepath and name to be used in the archive.
* @param int $timestamp (Optional) Timestamp for the added file, if omitted or set to 0, the current time will be used.
* @param String $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given.
* @return bool $success
*/
public function openStream($filePath, $timestamp = 0, $fileComment = NULL) {
if ( !function_exists('sys_get_temp_dir')) {
die ("ERROR: Zip " . self::VERSION . " requires PHP version 5.2.1 or above if large files are used.");
}
if ($this->isFinalized) {
return FALSE;
}
if (is_null($this->zipFile)) {
$this->zipFile = tmpfile();
fwrite($this->zipFile, $this->zipData);
$this->zipData = NULL;
}
if (strlen($this->streamFilePath) > 0) {
closeStream();
}
$this->streamFile = tempnam(sys_get_temp_dir(), 'Zip');
$this->streamData = gzopen($this->streamFile, "w9");
$this->streamFilePath = $filePath;
$this->streamTimestamp = $timestamp;
$this->streamFileComment = $fileComment;
$this->streamFileLength = 0;
return TRUE;
}
/**
* Add data to the open stream.
*
* @param String $data
* @return $length bytes added or FALSE if the archive is finalized or there are no open stream.
*/
public function addStreamData($data) {
if ($this->isFinalized || strlen($this->streamFilePath) == 0) {
return FALSE;
}
$length = gzwrite($this->streamData, $data, strlen($data));
if ($length != strlen($data)) {
print "<p>Length mismatch</p>\n";
}
$this->streamFileLength += $length;
return $length;
}
/**
* Close the current stream.
*
* @return bool $success
*/
public function closeStream() {
if ($this->isFinalized || strlen($this->streamFilePath) == 0) {
return FALSE;
}
fflush($this->streamData);
gzclose($this->streamData);
$gzType = "\x08\x00"; // Compression type 8 = deflate
$gpFlags = "\x02\x00"; // General Purpose bit flags for compression type 8 it is: 0=Normal, 1=Maximum, 2=Fast, 3=super fast compression.
$file_handle = fopen($this->streamFile, "rb");
$stats = fstat($file_handle);
$eof = $stats['size'];
fseek($file_handle, $eof-8);
$fileCRC32 = fread($file_handle, 4);
$dataLength = $this->streamFileLength;//$gzl[1];
$gzLength = $eof-10;
$eof -= 9;
fseek($file_handle, 10);
$this->buildZipEntry($this->streamFilePath, $this->streamFileComment, $gpFlags, $gzType, $this->streamTimestamp, $fileCRC32, $gzLength, $dataLength, self::EXT_FILE_ATTR_FILE);
while(!feof($file_handle)) {
fwrite($this->zipFile, fread($file_handle, $this->streamChunkSize));
}
unlink($this->streamFile);
$this->streamFile = NULL;
$this->streamData = NULL;
$this->streamFilePath = NULL;
$this->streamTimestamp = NULL;
$this->streamFileComment = NULL;
$this->streamFileLength = 0;
return TRUE;
}
/**
* Close the archive.
* A closed archive can no longer have new files added to it.
*
* @return bool $success
*/
public function finalize() {
if(!$this->isFinalized) {
if (strlen($this->streamFilePath) > 0) {
$this->closeStream();
}
$cd = implode("", $this->cdRec);
$cdRec = $cd . self::ZIP_END_OF_CENTRAL_DIRECTORY
. pack("v", sizeof($this->cdRec))
. pack("v", sizeof($this->cdRec))
. pack("V", strlen($cd))
. pack("V", $this->offset);
if (!is_null($this->zipComment)) {
$cdRec .= pack("v", strlen($this->zipComment)) . $this->zipComment;
} else {
$cdRec .= "\x00\x00";
}
if (is_null($this->zipFile)) {
$this->zipData .= $cdRec;
} else {
fwrite($this->zipFile, $cdRec);
fflush($this->zipFile);
}
$this->isFinalized = TRUE;
$cd = NULL;
$this->cdRec = NULL;
return TRUE;
}
return FALSE;
}
/**
* Get the handle ressource for the archive zip file.
* If the zip haven't been finalized yet, this will cause it to become finalized
*
* @return zip file handle
*/
public function getZipFile() {
if(!$this->isFinalized) {
$this->finalize();
}
if (is_null($this->zipFile)) {
$this->zipFile = tmpfile();
fwrite($this->zipFile, $this->zipData);
$this->zipData = NULL;
}
rewind($this->zipFile);
return $this->zipFile;
}
/**
* Get the zip file contents
* If the zip haven't been finalized yet, this will cause it to become finalized
*
* @return zip data
*/
public function getZipData() {
if(!$this->isFinalized) {
$this->finalize();
}
if (is_null($this->zipFile)) {
return $this->zipData;
} else {
rewind($this->zipFile);
$filestat = fstat($this->zipFile);
return fread($this->zipFile, $filestat['size']);
}
}
/**
* Send the archive as a zip download
*
* @param String $fileName The name of the Zip archive, ie. "archive.zip".
* @param String $contentType Content mime type. Optional, defaults to "application/zip".
* @return bool $success
*/
function sendZip($fileName, $contentType = "application/zip") {
if(!$this->isFinalized) {
$this->finalize();
}
if (!headers_sent($headerFile, $headerLine) or die("<p><strong>Error:</strong> Unable to send file $fileName. HTML Headers have already been sent from <strong>$headerFile</strong> in line <strong>$headerLine</strong></p>")) {
if ((ob_get_contents() === FALSE || ob_get_contents() == '') or die("\n<p><strong>Error:</strong> Unable to send file <strong>$fileName.epub</strong>. Output buffer contains the following text (typically warnings or errors):<br>" . ob_get_contents() . "</p>")) {
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
header("Pragma: public");
header("Last-Modified: " . gmdate("D, d M Y H:i:s T"));
header("Expires: 0");
header("Accept-Ranges: bytes");
header("Connection: close");
header("Content-Type: " . $contentType);
header('Content-Disposition: attachment; filename="' . $fileName . '";' );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ". $this->getArchiveSize());
if (is_null($this->zipFile)) {
echo $this->zipData;
} else {
rewind($this->zipFile);
while(!feof($this->zipFile)) {
echo fread($this->zipFile, $this->streamChunkSize);
}
}
}
return TRUE;
}
return FALSE;
}
/**
* Return the current size of the archive
*
* @return $size Size of the archive
*/
public function getArchiveSize() {
if (is_null($this->zipFile)) {
return strlen($this->zipData);
}
$filestat = fstat($this->zipFile);
return $filestat['size'];
}
/**
* Calculate the 2 byte dostime used in the zip entries.
*
* @param int $timestamp
* @return 2-byte encoded DOS Date
*/
private function getDosTime($timestamp = 0) {
$timestamp = (int)$timestamp;
$date = ($timestamp == 0 ? getdate() : getDate($timestamp));
if ($date["year"] >= 1980) {
return pack("V", (($date["mday"] + ($date["mon"] << 5) + (($date["year"]-1980) << 9)) << 16) |
(($date["seconds"] >> 1) + ($date["minutes"] << 5) + ($date["hours"] << 11)));
}
return "\x00\x00\x00\x00";
}
/**
* Build the Zip file structures
*
* @param String $filePath
* @param String $fileComment
* @param String $gpFlags
* @param String $gzType
* @param int $timestamp
* @param string $fileCRC32
* @param int $gzLength
* @param int $dataLength
* @param integer $extFileAttr Use self::EXT_FILE_ATTR_FILE for files, self::EXT_FILE_ATTR_DIR for Directories.
*/
private function buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, $extFileAttr) {
$filePath = str_replace("\\", "/", $filePath);
$fileCommentLength = (is_null($fileComment) ? 0 : strlen($fileComment));
$timestamp = (int)$timestamp;
$timestamp = ($timestamp == 0 ? time() : $timestamp);
$dosTime = $this->getDosTime($timestamp);
$zipEntry = self::ZIP_LOCAL_FILE_HEADER;
$zipEntry .= self::ATTR_VERSION_TO_EXTRACT;
$zipEntry .= $gpFlags . $gzType . $dosTime. $fileCRC32;
$zipEntry .= pack("VV", $gzLength, $dataLength);
$zipEntry .= pack("v", strlen($filePath) ); // File name length
$zipEntry .= $this->addExtraField ? "\x10\x00" : "\x00\x00"; // Extra field length
$zipEntry .= $filePath; // FileName
// Extra fields
if ($this->addExtraField) {
$zipEntry .= "\x55\x58"; // 0x5855 Short tag for this extra block type ("UX")
$zipEntry .= "\x0c\x00"; // TSize Short total data size for this block
$zipEntry .= pack("V", $timestamp); // AcTime Long time of last access (UTC/GMT)
$zipEntry .= pack("V", $timestamp); // ModTime Long time of last modification (UTC/GMT)
$zipEntry .= "\x00\x00\x00\x00";
}
if (is_null($this->zipFile)) {
$this->zipData .= $zipEntry;
} else {
fwrite($this->zipFile, $zipEntry);
}
$cdEntry = self::ZIP_CENTRAL_FILE_HEADER;
$cdEntry .= self::ATTR_MADE_BY_VERSION;
$cdEntry .= self::ATTR_VERSION_TO_EXTRACT;
$cdEntry .= $gpFlags . $gzType . $dosTime. $fileCRC32;
$cdEntry .= pack("VV", $gzLength, $dataLength);
$cdEntry .= pack("v", strlen($filePath)); // Filename length
$cdEntry .= $this->addExtraField ? "\x0c\x00" : "\x00\x00"; // Extra field length
$cdEntry .= pack("v", $fileCommentLength); // File comment length
$cdEntry .= "\x00\x00"; // Disk number start
$cdEntry .= "\x00\x00"; // internal file attributes
$cdEntry .= $extFileAttr; // External file attributes
$cdEntry .= pack("V", $this->offset ); // Relative offset of local header
$cdEntry .= $filePath; // FileName
// Extra fields
if ($this->addExtraField) {
$cdEntry .= "\x55\x58"; // 0x5855 Short tag for this extra block type ("UX")
$cdEntry .= "\x08\x00"; // TSize Short total data size for this block
$cdEntry .= pack("V", $timestamp); // AcTime Long time of last access (UTC/GMT)
$cdEntry .= pack("V", $timestamp); // ModTime Long time of last modification (UTC/GMT)
}
if (!is_null($fileComment)) {
$cdEntry .= $fileComment; // Comment
}
$this->cdRec[] = $cdEntry;
$this->offset += strlen($zipEntry) + $gzLength;
}
/**
* Join $file to $dir path, and clean up any excess slashes.
*
* @param String $dir
* @param String $file
*/
public static function pathJoin($dir, $file) {
if (empty($dir) || empty($file)) {
return self::getRelativePath($dir . $file);
}
return self::getRelativePath($dir . '/' . $file);
}
/**
* Clean up a path, removing any unnecessary elements such as /./, // or redundant ../ segments.
* If the path starts with a "/", it is deemed an absolute path and any /../ in the beginning is stripped off.
* The returned path will not end in a "/".
*
* @param String $relPath The path to clean up
* @return String the clean path
*/
public static function getRelativePath($path) {
$path = preg_replace("#/+\.?/+#", "/", str_replace("\\", "/", $path));
$dirs = explode("/", rtrim(preg_replace('#^(\./)+#', '', $path), '/'));
$offset = 0;
$sub = 0;
$subOffset = 0;
$root = "";
if (empty($dirs[0])) {
$root = "/";
$dirs = array_splice($dirs, 1);
} else if (preg_match("#[A-Za-z]:#", $dirs[0])) {
$root = strtoupper($dirs[0]) . "/";
$dirs = array_splice($dirs, 1);
}
$newDirs = array();
foreach($dirs as $dir) {
if ($dir !== "..") {
$subOffset--;
$newDirs[++$offset] = $dir;
} else {
$subOffset++;
if (--$offset < 0) {
$offset = 0;
if ($subOffset > $sub) {
$sub++;
}
}
}
}
if (empty($root)) {
$root = str_repeat("../", $sub);
}
return $root . implode("/", array_slice($newDirs, 0, $offset));
}
}
?>