/
Zip.php
639 lines (613 loc) · 22 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
<?php
namespace Concrete\Core\File\Service;
use Concrete\Core\Foundation\Environment\FunctionInspector;
use DateTime;
use Exception;
use Illuminate\Filesystem\Filesystem;
use ZipArchive;
/**
* Wrapper for ZIP functions.
*/
class Zip
{
/**
* The Filesystem instance to use.
*
* @var Filesystem
*/
protected $filesystem;
/**
* The FunctionInspector instance to use.
*
* @var FunctionInspector
*/
protected $functionInspector;
/**
* Initialize the instance.
*
* @param Filesystem $filesystem
* @param FunctionInspector $functionInspector
*/
public function __construct(Filesystem $filesystem, FunctionInspector $functionInspector)
{
$this->filesystem = $filesystem;
$this->functionInspector = $functionInspector;
}
/**
* Set the Filesystem instance to use.
*
* @param Filesystem $filesystem
*/
public function setFilesystem(Filesystem $filesystem)
{
$this->filesystem = $filesystem;
}
/**
* Get the Filesystem instance to use.
*
* @return Filesystem
*/
public function getFilesystem()
{
return $this->filesystem;
}
/**
* Can we try to use native commands?
*
* @var bool
*/
protected $enableNativeCommands = true;
/**
* State that we can try to use native commands.
*/
public function enableNativeCommands()
{
$this->enableNativeCommands = true;
}
/**
* State that we can NOT try to use native commands.
*/
public function disableNativeCommands()
{
$this->enableNativeCommands = false;
}
/**
* Can we try to use native commands?
*
* @return bool
*/
public function nativeCommandsEnabled()
{
return $this->enableNativeCommands;
}
/**
* Cache for the available native commands.
*
* @var array
*/
protected $availableNativeCommands = [];
/**
* Check if a native command is available.
*
* @param string $command
*
* @return bool
*/
public function isNativeCommandAvailable($command)
{
switch ($command) {
case 'zip':
case 'unzip':
break;
default:
return false;
}
if (!isset($this->availableNativeCommands[$command])) {
$this->availableNativeCommands[$command] = false;
if ($this->functionInspector->functionAvailable('exec')) {
$rc = 1;
$output = [];
@exec($command . ' -v 2>&1', $output, $rc);
if ($rc === 0) {
$stdOut = implode("\n", $output);
if (stripos($stdOut, 'info-zip') !== false || stripos($stdOut, 'infozip') !== false) {
$this->availableNativeCommands[$command] = true;
}
}
}
}
return $this->availableNativeCommands[$command];
}
/**
* Check if a native command is available and if we may use it.
*
* @param string $command
*
* @return bool
*/
protected function mayUseNativeCommand($command)
{
return $this->enableNativeCommands ? $this->isNativeCommandAvailable($command) : false;
}
/**
* Decompress a ZIP archive to a directory.
*
* @param string $zipFile the source ZIP archive
* @param string $destinationDirectory the destination folder
* @param array $options {
* @var bool $skipCheck Skip test compressed archive data
* }
*
* @throws Exception
*/
public function unzip($zipFile, $destinationDirectory, array $options = [])
{
$fs = $this->getFilesystem();
$normalized = @realpath($zipFile);
if ($normalized === false || !$fs->isFile($normalized)) {
throw new Exception(t('Unable to find the ZIP file %s', $zipFile));
}
$zipFile = str_replace(DIRECTORY_SEPARATOR, '/', $normalized);
$normalized = @realpath($destinationDirectory);
if ($normalized === false || !$fs->isDirectory($normalized)) {
throw new Exception(t('Unable to find the directory %s', $destinationDirectory));
}
if (!$fs->isWritable($normalized)) {
throw new Exception(t('The directory "%s" is not writable', $destinationDirectory));
}
$destinationDirectory = str_replace(DIRECTORY_SEPARATOR, '/', $normalized);
$options += [
'skipCheck' => false,
];
if ($this->mayUseNativeCommand('unzip')) {
$this->unzipNative($zipFile, $destinationDirectory, $options);
} else {
$this->unzipPHP($zipFile, $destinationDirectory, $options);
}
}
/**
* Compress the contents of a directory to a ZIP archive.
*
* @param string $sourceDirectory the directory to compress
* @param string $zipFile the ZIP file to create (it will be deleted if already existing, unless the 'append' option is set to true)
* @param array $options {
* @var bool $includeDotFiles Shall the zip file include files and folders whose name starts with a dot?
* @var bool $skipCheck Skip test compressed archive data
* @var int $level Compression level (0 to 9)
* @var bool $append Append to an existing archive instead of overwriting it?
* }
*
* @throws Exception
*/
public function zip($sourceDirectory, $zipFile, array $options = [])
{
$fs = $this->getFilesystem();
$normalized = @realpath($sourceDirectory);
if ($normalized === false || !$fs->isDirectory($normalized)) {
throw new Exception(t('Unable to find the directory %s', $destinationDirectory));
}
$sourceDirectory = $normalized;
$zipFile = str_replace('/', DIRECTORY_SEPARATOR, $zipFile);
if ($fs->exists($zipFile)) {
if ($fs->isDirectory($zipFile)) {
throw new Exception(t('The specified path of the ZIP archive (%s) is a directory, not a file', $zipFile));
}
$options['append'] = isset($options['append']) ? (bool) $options['append'] : false;
if (!$options['append']) {
if (@$fs->delete([$zipFile]) === false) {
throw new Exception(t('Failed to delete file %s', $zipFile));
}
}
} else {
$options['append'] = false;
}
$options += [
'includeDotFiles' => false,
'skipCheck' => false,
'level' => 9,
];
if ($this->mayUseNativeCommand('zip')) {
$this->zipNative($sourceDirectory, $zipFile, $options);
} else {
$this->zipPHP($sourceDirectory, $zipFile, $options);
}
}
/**
* List the contents of a ZIP archive.
*
* @param string $zipFile the ZIP file to inspect
* @param array $options {
* @var bool $skipCheck Skip test compressed archive data
* @var bool $excludeDirs Don't include directories
* @var bool $excludeFiles Don't include files
* }
*
* @throws Exception
*
* @return array The keys of the resulting array contain the paths to the items, and the values will be arrays, whose keys are:
* - string 'type' For directories it will be 'D', for files it will be 'F'
* - \DateTime 'date' Last modification date/time
* - int 'originalSize' (only for files) Uncompressed size of the file
* - int 'compressedSize' (only for files) Compressed size of the file
*/
public function listContents($zipFile, array $options = [])
{
$fs = $this->getFilesystem();
if (!$fs->isFile($zipFile)) {
throw new Exception(t('Unable to find the ZIP file %s', $zipFile));
}
$options += [
'skipCheck' => false,
'excludeDirs' => false,
'excludeFiles' => false,
];
$result = [];
$zip = new ZipArchive();
try {
$flags = 0;
if (!$options['skipCheck']) {
$flags |= ZipArchive::CHECKCONS;
}
$zipErr = @$zip->open($zipFile, $flags);
if ($zipErr !== true) {
throw new Exception($this->describeZipArchiveError($zip, $zipErr));
}
for ($index = 0; $index < $zip->numFiles; ++$index) {
$stat = @$zip->statIndex($index);
if ($stat === false) {
throw new Exception(t('Failed to retrieve the details of a ZIP archive entry.'));
}
$isDir = substr($stat['name'], -1) === '/' || substr($stat['name'], -1) === '\\';
if ($isDir) {
if ($options['excludeDirs']) {
continue;
}
} else {
if ($options['excludeFiles']) {
continue;
}
}
$item = [
'type' => $isDir ? 'D' : 'F',
'date' => (isset($stat['mtime']) && $stat['mtime']) ? DateTime::createFromFormat('U', $stat['mtime']) : null,
];
if (!$isDir) {
$item += [
'originalSize' => isset($stat['size']) ? (int) $stat['size'] : null,
'compressedSize' => isset($stat['comp_size']) ? (int) $stat['comp_size'] : null,
];
}
$result[trim($stat['name'], '/\\')] = $item;
}
@$zip->close();
$zip = null;
} catch (Exception $x) {
if ($zip !== null) {
try {
@$zip->close();
} catch (\Exception $foo) {
}
$zip = null;
}
throw $x;
}
return $result;
}
/**
* Describe a ZipArchive related problem.
*
* @param ZipArchive $zip
* @param int $errorCode
*
* @return string
*/
protected function describeZipArchiveError(ZipArchive $zip, $errorCode)
{
$result = '';
switch ($errorCode) {
case ZipArchive::ER_OK:
break;
case ZipArchive::ER_MULTIDISK:
$result = t('Multi-disk ZIP archives are not supported.');
break;
case ZipArchive::ER_RENAME:
$result = t('Renaming a temporary file failed working with a ZIP archive.');
break;
case ZipArchive::ER_CLOSE:
$result = t('Closing ZIP archive failed.');
break;
case ZipArchive::ER_SEEK:
$result = t('Seek error working with a ZIP archive.');
break;
case ZipArchive::ER_READ:
$result = t('Error reading a file working with a ZIP archive.');
break;
case ZipArchive::ER_WRITE:
$result = t('Error writing a file working with a ZIP archive.');
break;
case ZipArchive::ER_CRC:
$result = t('CRC error working with a ZIP archive.');
break;
case ZipArchive::ER_ZIPCLOSED:
$result = t('ZIP archive was closed.');
break;
case ZipArchive::ER_NOENT:
$result = t('File not found working with a ZIP archive.');
break;
case ZipArchive::ER_EXISTS:
$result = t('File already exists working with a ZIP archive.');
break;
case ZipArchive::ER_OPEN:
$result = t('Failed to open a file working with a ZIP archive.');
break;
case ZipArchive::ER_TMPOPEN:
$result = t('Failed to open a temporary file working with a ZIP archive.');
break;
case ZipArchive::ER_ZLIB:
$result = t('ZLIB error working with a ZIP archive.');
break;
case ZipArchive::ER_MEMORY:
$result = t('Out of memory problems working with a ZIP archive.');
break;
case ZipArchive::ER_CHANGED:
$result = t('Entry has been changed working with a ZIP archive.');
break;
case ZipArchive::ER_COMPNOTSUPP:
$result = t('Compression method not supported working with a ZIP archive.');
break;
case ZipArchive::ER_EOF:
$result = t('Premature end of file working with a ZIP archive.');
break;
case ZipArchive::ER_INVAL:
$result = t('Invalid argument working with a ZIP archive.');
break;
case ZipArchive::ER_NOZIP:
$result = t('Not a ZIP archive.');
break;
case ZipArchive::ER_INTERNAL:
$result = t('Internal error working with a ZIP archive.');
break;
case ZipArchive::ER_INCONS:
$result = t('ZIP archive is inconsistent.');
break;
case ZipArchive::ER_REMOVE:
$result = t('Can\'t remove file working with a ZIP archive.');
break;
case ZipArchive::ER_DELETED:
$result = t('Entry has been deleted working with a ZIP archive.');
break;
default:
$result = t('Unknown ZIP-related problem (code: %s).', $errorCode);
break;
}
$status = @$zip->getStatusString();
if (is_string($status) && $status !== '') {
if ($result === '') {
$result = $status;
} else {
$result .= "\n" . $status;
}
}
if ($result === '') {
$result = t('Unknown ZIP-related problem');
}
return $result;
}
/**
* Decompress a ZIP archive to a directory using the native 'unzip' command.
*
* @param string $zipFile
* @param string $destinationDirectory
* @param array $options
*
* @throws Exception
*/
protected function unzipNative($zipFile, $destinationDirectory, array $options)
{
$cmd = 'unzip';
$cmd .= ' -o'; // overwrite files WITHOUT prompting
$cmd .= ' -q'; // quiet mode, to avoid overflow of stdout
$cmd .= ' ' . escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $zipFile)); // file to extract
$cmd .= ' -d ' . escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $destinationDirectory)); // destination directory
$rc = 1;
$output = [];
@exec($cmd . ' 2>&1', $output, $rc);
if ($rc !== 0) {
$error = trim(implode("\n", $output)) ?: t('Unknown error decompressing a ZIP archive');
throw new Exception($error);
}
}
/**
* Decompress a ZIP archive to a directory using the PHP functions.
*
* @param string $zipFile
* @param string $destinationDirectory
* @param array $options
*
* @throws Exception
*/
protected function unzipPHP($zipFile, $destinationDirectory, array $options)
{
if (!class_exists('ZipArchive')) {
throw new Exception('Unable to unzip files using ZipArchive. Please ensure the Zip extension is installed.');
}
$zip = new ZipArchive();
try {
$flags = 0;
if (!$options['skipCheck']) {
$flags |= ZipArchive::CHECKCONS;
}
$zipErr = @$zip->open($zipFile, $flags);
if ($zipErr !== true) {
throw new Exception($this->describeZipArchiveError($zip, $zipErr));
}
if (@$zip->extractTo($destinationDirectory) !== true) {
throw new Exception($this->describeZipArchiveError($zip, ZipArchive::ER_OK));
}
@$zip->close();
$zip = null;
} catch (Exception $x) {
if ($zip !== null) {
try {
@$zip->close();
} catch (\Exception $foo) {
}
$zip = null;
}
throw $x;
}
}
/**
* Compress the contents of a directory to a ZIP archive using the native 'zip' command.
*
* @param string $sourceDirectory
* @param string $zipFile
* @param array $options
*
* @throws Exception
*/
protected function zipNative($sourceDirectory, $zipFile, array $options)
{
if (!$options['includeDotFiles'] && stripos(PHP_OS, 'WIN') === 0) {
$this->zipPHP($sourceDirectory, $zipFile, $options);
return;
}
$fs = $this->getFilesystem();
$originalZipFile = $zipFile;
$revertName = false;
if (!strpos(basename($zipFile), '.')) {
for ($i = 0; ; ++$i) {
$tmp = "$zipFile-$i.zip";
if (!$fs->exists($tmp)) {
$zipFile = $tmp;
break;
}
}
if ($options['append']) {
if (@$fs->move($originalZipFile, $zipFile) === false) {
throw new Exception(t('Failed to move a temporary file.'));
}
$revertName = true;
}
}
try {
$cmd = 'zip';
$level = (isset($options['level']) && is_numeric($options['level'])) ? @intval($options['level']) : null;
if ($level !== null && $level >= 0 && $level <= 9) {
$cmd .= ' -' . $level;
}
$cmd .= ' -q'; // quiet mode, to avoid overflow of stdout
$cmd .= ' -r'; // recurse into directories
$cmd .= ' ' . escapeshellarg($zipFile); // destination ZIP archive
if ($options['includeDotFiles']) {
$cmd .= ' .* *';
} else {
$cmd .= ' * -x \*/.\*';
}
$rc = 1;
$output = [];
$prevDir = @getcwd();
if ($prevDir === false) {
throw new Exception(t('Failed to determine current directory'));
}
if (@chdir($sourceDirectory) === false) {
throw new Exception(t('Failed to enter directory ' . $sourceDirectory));
}
@exec($cmd . ' 2>&1', $output, $rc);
@chdir($prevDir);
if ($rc !== 0) {
$error = trim(implode("\n", $output)) ?: t('Unknown error compressing a directory');
throw new Exception($error);
}
} catch (Exception $x) {
if ($fs->exists($zipFile)) {
if ($revertName) {
@$fs->move($zipFile, $originalZipFile);
} elseif (!$options['append']) {
@$fs->delete([$zipFile]);
}
}
throw $x;
}
if ($originalZipFile !== $zipFile) {
if (@$fs->move($zipFile, $originalZipFile) === false) {
@$fs->delete([$zipFile]);
throw new Exception(t('Failed to move a temporary file.'));
}
}
}
/**
* Compress the contents of a directory to a ZIP archive using the PHP functions.
*
* @param string $sourceDirectory
* @param string $zipFile
* @param array $options
*
* @throws Exception
*/
protected function zipPHP($sourceDirectory, $zipFile, array $options)
{
if (!class_exists('ZipArchive')) {
throw new Exception('Unable to zip files using ZipArchive. Please ensure the Zip extension is installed.');
}
$zip = new ZipArchive();
try {
$flags = ZipArchive::CREATE;
if (!$options['skipCheck']) {
$flags |= ZipArchive::CHECKCONS;
}
$zipErr = @$zip->open($zipFile, $flags);
if ($zipErr !== true) {
throw new Exception($this->describeZipArchiveError($zip, $zipErr));
}
$skipPathLength = strlen(rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $sourceDirectory), '/')) + 1;
$contents = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($sourceDirectory),
\RecursiveIteratorIterator::SELF_FIRST
);
foreach ($contents as $item) {
switch ($item->getFilename()) {
case '.':
case '..':
break;
default:
$itemFullPath = $item->getRealPath();
$itemRelPath = substr(str_replace(DIRECTORY_SEPARATOR, '/', $itemFullPath), $skipPathLength);
if (
$options['includeDotFiles']
||
(
strpos($itemRelPath, '.') !== 0
&&
strpos($itemRelPath, '/.') === false
)
) {
if ($item->isDir()) {
$added = @$zip->addEmptyDir($itemRelPath);
} else {
$added = @$zip->addFile($itemFullPath, $itemRelPath);
}
if ($added !== true) {
throw new Exception($this->describeZipArchiveError($zip, ZipArchive::ER_OK));
}
}
break;
}
}
if (@$zip->close() !== true) {
throw new Exception($this->describeZipArchiveError($zip, ZipArchive::ER_OK));
}
$zip = null;
} catch (Exception $x) {
if ($zip !== null) {
try {
@$zip->close();
} catch (\Exception $foo) {
}
$zip = null;
}
@$this->getFilesystem()->delete([$zipFile]);
throw $x;
}
}
}