1
0
mirror of https://github.com/Ne-Lexa/php-zip.git synced 2025-08-02 21:47:23 +02:00

minor fixes, ZipEntry tests

This commit is contained in:
wapplay
2020-01-06 11:53:17 +03:00
parent 70bb598fa6
commit a16b0e7c15
21 changed files with 1906 additions and 141 deletions

3
.gitattributes vendored
View File

@@ -1,7 +1,8 @@
.gitattributes export-ignore .gitattributes export-ignore
.github export-ignore .github export-ignore
.gitignore export-ignore .gitignore export-ignore
.travis.yml export-ignore
.php_cs export-ignore .php_cs export-ignore
.travis.yml export-ignore
bootstrap.php export-ignore
phpunit.xml export-ignore phpunit.xml export-ignore
tests export-ignore tests export-ignore

View File

@@ -26,6 +26,8 @@ namespace PHPSTORM_META {
expectedArguments(\PhpZip\ZipFile::addFilesFromRegex(), 3, argumentsSet("compression_methods")); expectedArguments(\PhpZip\ZipFile::addFilesFromRegex(), 3, argumentsSet("compression_methods"));
expectedArguments(\PhpZip\ZipFile::addFilesFromRegexRecursive(), 3, argumentsSet("compression_methods")); expectedArguments(\PhpZip\ZipFile::addFilesFromRegexRecursive(), 3, argumentsSet("compression_methods"));
expectedArguments(\PhpZip\ZipFile::setCompressionMethodEntry(), 1, argumentsSet("compression_methods")); expectedArguments(\PhpZip\ZipFile::setCompressionMethodEntry(), 1, argumentsSet("compression_methods"));
expectedArguments(\PhpZip\Model\ZipEntry::setCompressionMethod(), 0, argumentsSet("compression_methods"));
expectedArguments(\PhpZip\Model\ZipEntry::setMethod(), 0, argumentsSet("compression_methods"));
registerArgumentsSet( registerArgumentsSet(
'compression_levels', 'compression_levels',
@@ -36,6 +38,7 @@ namespace PHPSTORM_META {
); );
expectedArguments(\PhpZip\ZipFile::setCompressionLevel(), 0, argumentsSet("compression_levels")); expectedArguments(\PhpZip\ZipFile::setCompressionLevel(), 0, argumentsSet("compression_levels"));
expectedArguments(\PhpZip\ZipFile::setCompressionLevelEntry(), 1, argumentsSet("compression_levels")); expectedArguments(\PhpZip\ZipFile::setCompressionLevelEntry(), 1, argumentsSet("compression_levels"));
expectedArguments(\PhpZip\Model\ZipEntry::setCompressionLevel(), 0, argumentsSet("compression_levels"));
registerArgumentsSet( registerArgumentsSet(
'encryption_methods', 'encryption_methods',
@@ -46,6 +49,8 @@ namespace PHPSTORM_META {
); );
expectedArguments(\PhpZip\ZipFile::setPassword(), 1, argumentsSet("encryption_methods")); expectedArguments(\PhpZip\ZipFile::setPassword(), 1, argumentsSet("encryption_methods"));
expectedArguments(\PhpZip\ZipFile::setPasswordEntry(), 2, argumentsSet("encryption_methods")); expectedArguments(\PhpZip\ZipFile::setPasswordEntry(), 2, argumentsSet("encryption_methods"));
expectedArguments(\PhpZip\Model\ZipEntry::setEncryptionMethod(), 0, argumentsSet("encryption_methods"));
expectedArguments(\PhpZip\Model\ZipEntry::setPassword(), 1, argumentsSet("encryption_methods"));
registerArgumentsSet( registerArgumentsSet(
'zip_mime_types', 'zip_mime_types',
@@ -57,6 +62,49 @@ namespace PHPSTORM_META {
expectedArguments(\PhpZip\ZipFile::outputAsAttachment(), 1, argumentsSet("zip_mime_types")); expectedArguments(\PhpZip\ZipFile::outputAsAttachment(), 1, argumentsSet("zip_mime_types"));
expectedArguments(\PhpZip\ZipFile::outputAsAttachment(), 2, argumentsSet("bool")); expectedArguments(\PhpZip\ZipFile::outputAsAttachment(), 2, argumentsSet("bool"));
expectedArguments(\PhpZip\ZipFileI::outputAsResponse(), 2, argumentsSet("zip_mime_types")); expectedArguments(\PhpZip\ZipFile::outputAsResponse(), 2, argumentsSet("zip_mime_types"));
expectedArguments(\PhpZip\ZipFileI::outputAsResponse(), 3, argumentsSet("bool")); expectedArguments(\PhpZip\ZipFile::outputAsResponse(), 3, argumentsSet("bool"));
registerArgumentsSet(
'dos_charset',
\PhpZip\Constants\DosCodePage::CP_LATIN_US,
\PhpZip\Constants\DosCodePage::CP_GREEK,
\PhpZip\Constants\DosCodePage::CP_BALT_RIM,
\PhpZip\Constants\DosCodePage::CP_LATIN1,
\PhpZip\Constants\DosCodePage::CP_LATIN2,
\PhpZip\Constants\DosCodePage::CP_CYRILLIC,
\PhpZip\Constants\DosCodePage::CP_TURKISH,
\PhpZip\Constants\DosCodePage::CP_PORTUGUESE,
\PhpZip\Constants\DosCodePage::CP_ICELANDIC,
\PhpZip\Constants\DosCodePage::CP_HEBREW,
\PhpZip\Constants\DosCodePage::CP_CANADA,
\PhpZip\Constants\DosCodePage::CP_ARABIC,
\PhpZip\Constants\DosCodePage::CP_NORDIC,
\PhpZip\Constants\DosCodePage::CP_CYRILLIC_RUSSIAN,
\PhpZip\Constants\DosCodePage::CP_GREEK2,
\PhpZip\Constants\DosCodePage::CP_THAI,
);
expectedArguments(\PhpZip\Model\ZipEntry::setCharset(), 0, argumentsSet('dos_charset'));
expectedArguments(\PhpZip\Constants\DosCodePage::toUTF8(), 1, argumentsSet('dos_charset'));
expectedArguments(\PhpZip\Constants\DosCodePage::fromUTF8(), 1, argumentsSet('dos_charset'));
registerArgumentsSet(
"zip_os",
\PhpZip\Constants\ZipPlatform::OS_UNIX,
\PhpZip\Constants\ZipPlatform::OS_DOS,
\PhpZip\Constants\ZipPlatform::OS_MAC_OSX,
);
expectedArguments(\PhpZip\Model\ZipEntry::setCreatedOS(), 0, argumentsSet('zip_os'));
expectedArguments(\PhpZip\Model\ZipEntry::setExtractedOS(), 0, argumentsSet('zip_os'));
expectedArguments(\PhpZip\Model\ZipEntry::setPlatform(), 0, argumentsSet('zip_os'));
registerArgumentsSet(
"zip_gpbf",
\PhpZip\Constants\GeneralPurposeBitFlag::ENCRYPTION |
\PhpZip\Constants\GeneralPurposeBitFlag::DATA_DESCRIPTOR |
\PhpZip\Constants\GeneralPurposeBitFlag::COMPRESSION_FLAG1 |
\PhpZip\Constants\GeneralPurposeBitFlag::COMPRESSION_FLAG2 |
\PhpZip\Constants\GeneralPurposeBitFlag::UTF8
);
expectedArguments(\PhpZip\Model\ZipEntry::setGeneralPurposeBitFlags(), 0, argumentsSet('zip_gpbf'));
} }

6
bootstrap.php Normal file
View File

@@ -0,0 +1,6 @@
<?php
// see https://stackoverflow.com/questions/33299149/phpstorm-8-and-phpunit-problems-with-runinseparateprocess/37174348#37174348
if (!defined('PHPUNIT_COMPOSER_INSTALL')) {
define('PHPUNIT_COMPOSER_INSTALL', __DIR__ . '/vendor/autoload.php');
}

View File

@@ -4,7 +4,7 @@
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.8/phpunit.xsd" xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.8/phpunit.xsd"
backupGlobals="false" backupGlobals="false"
colors="true" colors="true"
bootstrap="vendor/autoload.php"> bootstrap="bootstrap.php">
<php> <php>
<ini name="error_reporting" value="-1"/> <ini name="error_reporting" value="-1"/>
</php> </php>

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace PhpZip\IO\Filter\Cipher\Traditional; namespace PhpZip\IO\Filter\Cipher\Pkware;
use PhpZip\Exception\RuntimeException; use PhpZip\Exception\RuntimeException;
use PhpZip\Exception\ZipAuthenticationException; use PhpZip\Exception\ZipAuthenticationException;

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace PhpZip\IO\Filter\Cipher\Traditional; namespace PhpZip\IO\Filter\Cipher\Pkware;
use PhpZip\Exception\ZipException; use PhpZip\Exception\ZipException;
use PhpZip\Model\ZipEntry; use PhpZip\Model\ZipEntry;

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace PhpZip\IO\Filter\Cipher\Traditional; namespace PhpZip\IO\Filter\Cipher\Pkware;
use PhpZip\Exception\RuntimeException; use PhpZip\Exception\RuntimeException;
use PhpZip\Model\ZipEntry; use PhpZip\Model\ZipEntry;
@@ -66,7 +66,7 @@ class PKEncryptionStreamFilter extends \php_user_filter
// init keys // init keys
$this->context = new PKCryptContext($password); $this->context = new PKCryptContext($password);
$crc = $entry->isDataDescriptorRequired() ? $crc = $entry->isDataDescriptorRequired() || $entry->getCrc() === ZipEntry::UNKNOWN ?
($entry->getDosTime() & 0x0000ffff) << 16 : ($entry->getDosTime() & 0x0000ffff) << 16 :
$entry->getCrc(); $entry->getCrc();

View File

@@ -11,7 +11,7 @@ use PhpZip\Constants\ZipOptions;
use PhpZip\Exception\Crc32Exception; use PhpZip\Exception\Crc32Exception;
use PhpZip\Exception\InvalidArgumentException; use PhpZip\Exception\InvalidArgumentException;
use PhpZip\Exception\ZipException; use PhpZip\Exception\ZipException;
use PhpZip\IO\Filter\Cipher\Traditional\PKDecryptionStreamFilter; use PhpZip\IO\Filter\Cipher\Pkware\PKDecryptionStreamFilter;
use PhpZip\IO\Filter\Cipher\WinZipAes\WinZipAesDecryptionStreamFilter; use PhpZip\IO\Filter\Cipher\WinZipAes\WinZipAesDecryptionStreamFilter;
use PhpZip\Model\Data\ZipSourceFileData; use PhpZip\Model\Data\ZipSourceFileData;
use PhpZip\Model\EndOfCentralDirectory; use PhpZip\Model\EndOfCentralDirectory;
@@ -713,7 +713,7 @@ class ZipReader
throw new InvalidArgumentException('outStream is not resource'); throw new InvalidArgumentException('outStream is not resource');
} }
$entry = $zipFileData->getZipEntry(); $entry = $zipFileData->getSourceEntry();
// if ($entry->isDirectory()) { // if ($entry->isDirectory()) {
// throw new InvalidArgumentException('Streams not supported for directories'); // throw new InvalidArgumentException('Streams not supported for directories');

View File

@@ -10,7 +10,7 @@ use PhpZip\Constants\ZipPlatform;
use PhpZip\Constants\ZipVersion; use PhpZip\Constants\ZipVersion;
use PhpZip\Exception\ZipException; use PhpZip\Exception\ZipException;
use PhpZip\Exception\ZipUnsupportMethodException; use PhpZip\Exception\ZipUnsupportMethodException;
use PhpZip\IO\Filter\Cipher\Traditional\PKEncryptionStreamFilter; use PhpZip\IO\Filter\Cipher\Pkware\PKEncryptionStreamFilter;
use PhpZip\IO\Filter\Cipher\WinZipAes\WinZipAesEncryptionStreamFilter; use PhpZip\IO\Filter\Cipher\WinZipAes\WinZipAesEncryptionStreamFilter;
use PhpZip\Model\Data\ZipSourceFileData; use PhpZip\Model\Data\ZipSourceFileData;
use PhpZip\Model\Extra\Fields\ApkAlignmentExtraField; use PhpZip\Model\Extra\Fields\ApkAlignmentExtraField;
@@ -109,7 +109,6 @@ class ZipWriter
$compressedSize = $entry->getCompressedSize(); $compressedSize = $entry->getCompressedSize();
$uncompressedSize = $entry->getUncompressedSize(); $uncompressedSize = $entry->getUncompressedSize();
// todo check on 32bit system
$entry->getLocalExtraFields()->remove(Zip64ExtraField::HEADER_ID); $entry->getLocalExtraFields()->remove(Zip64ExtraField::HEADER_ID);
if ($compressedSize > ZipConstants::ZIP64_MAGIC || $uncompressedSize > ZipConstants::ZIP64_MAGIC) { if ($compressedSize > ZipConstants::ZIP64_MAGIC || $uncompressedSize > ZipConstants::ZIP64_MAGIC) {
@@ -331,7 +330,7 @@ class ZipWriter
// (PHP cannot apply the filter for encryption after the compression // (PHP cannot apply the filter for encryption after the compression
// filter, so a temporary stream is created for the compressed data) // filter, so a temporary stream is created for the compressed data)
if ($zipData instanceof ZipSourceFileData && !$this->zipContainer->hasRecompressData($entry)) { if ($zipData instanceof ZipSourceFileData && !$zipData->hasRecompressData($entry)) {
// data of source zip file -> copy compressed data // data of source zip file -> copy compressed data
$zipData->copyCompressedDataToStream($outStream); $zipData->copyCompressedDataToStream($outStream);
@@ -631,7 +630,6 @@ class ZipWriter
$uncompressedSize = $entry->getUncompressedSize(); $uncompressedSize = $entry->getUncompressedSize();
$localHeaderOffset = $entry->getLocalHeaderOffset(); $localHeaderOffset = $entry->getLocalHeaderOffset();
// todo check on 32bit system
$entry->getCdExtraFields()->remove(Zip64ExtraField::HEADER_ID); $entry->getCdExtraFields()->remove(Zip64ExtraField::HEADER_ID);
if ( if (

View File

@@ -20,7 +20,7 @@ class ZipSourceFileData implements ZipData
private $stream; private $stream;
/** @var ZipEntry */ /** @var ZipEntry */
private $zipEntry; private $sourceEntry;
/** @var int */ /** @var int */
private $offset; private $offset;
@@ -42,11 +42,28 @@ class ZipSourceFileData implements ZipData
{ {
$this->zipReader = $zipReader; $this->zipReader = $zipReader;
$this->offset = $offsetData; $this->offset = $offsetData;
$this->zipEntry = $zipEntry; $this->sourceEntry = $zipEntry;
$this->compressedSize = $zipEntry->getCompressedSize(); $this->compressedSize = $zipEntry->getCompressedSize();
$this->uncompressedSize = $zipEntry->getUncompressedSize(); $this->uncompressedSize = $zipEntry->getUncompressedSize();
} }
/**
* @param ZipEntry $entry
*
* @return bool
*/
public function hasRecompressData(ZipEntry $entry)
{
return $this->sourceEntry->getCompressionLevel() !== $entry->getCompressionLevel() ||
$this->sourceEntry->getCompressionMethod() !== $entry->getCompressionMethod() ||
$this->sourceEntry->isEncrypted() !== $entry->isEncrypted() ||
$this->sourceEntry->getEncryptionMethod() !== $entry->getEncryptionMethod() ||
$this->sourceEntry->getPassword() !== $entry->getPassword() ||
$this->sourceEntry->getCompressedSize() !== $entry->getCompressedSize() ||
$this->sourceEntry->getUncompressedSize() !== $entry->getUncompressedSize() ||
$this->sourceEntry->getCrc() !== $entry->getCrc();
}
/** /**
* @throws ZipException * @throws ZipException
* *
@@ -114,9 +131,9 @@ class ZipSourceFileData implements ZipData
/** /**
* @return ZipEntry * @return ZipEntry
*/ */
public function getZipEntry() public function getSourceEntry()
{ {
return $this->zipEntry; return $this->sourceEntry;
} }
/** /**

View File

@@ -33,13 +33,13 @@ class NtfsExtraField implements ZipExtraField
*/ */
const EPOCH_OFFSET = -11644473600; const EPOCH_OFFSET = -11644473600;
/** @var int Modify time timestamp */ /** @var int Modify ntfs time */
private $modifyTime; private $modifyTime;
/** @var int Access time timestamp */ /** @var int Access ntfs time */
private $accessTime; private $accessTime;
/** @var int Create time timestamp */ /** @var int Create ntfs time */
private $createTime; private $createTime;
/** /**
@@ -54,6 +54,22 @@ class NtfsExtraField implements ZipExtraField
$this->createTime = (int) $createTime; $this->createTime = (int) $createTime;
} }
/**
* @param \DateTimeInterface $mtime
* @param \DateTimeInterface $atime
* @param \DateTimeInterface $ctime
*
* @return NtfsExtraField
*/
public static function create(\DateTimeInterface $mtime, \DateTimeInterface $atime, \DateTimeInterface $ctime)
{
return new self(
self::dateTimeToNtfsTime($mtime),
self::dateTimeToNtfsTime($atime),
self::dateTimeToNtfsTime($ctime)
);
}
/** /**
* Returns the Header ID (type) of this Extra Field. * Returns the Header ID (type) of this Extra Field.
* The Header ID is an unsigned short integer (two bytes) * The Header ID is an unsigned short integer (two bytes)
@@ -145,7 +161,7 @@ class NtfsExtraField implements ZipExtraField
*/ */
public function getModifyDateTime() public function getModifyDateTime()
{ {
return $this->ntfsTimeToDateTime($this->modifyTime); return self::ntfsTimeToDateTime($this->modifyTime);
} }
/** /**
@@ -153,7 +169,7 @@ class NtfsExtraField implements ZipExtraField
*/ */
public function setModifyDateTime(\DateTimeInterface $modifyTime) public function setModifyDateTime(\DateTimeInterface $modifyTime)
{ {
$this->modifyTime = $this->dateTimeToNtfsTime($modifyTime); $this->modifyTime = self::dateTimeToNtfsTime($modifyTime);
} }
/** /**
@@ -161,7 +177,7 @@ class NtfsExtraField implements ZipExtraField
*/ */
public function getAccessDateTime() public function getAccessDateTime()
{ {
return $this->ntfsTimeToDateTime($this->accessTime); return self::ntfsTimeToDateTime($this->accessTime);
} }
/** /**
@@ -169,7 +185,7 @@ class NtfsExtraField implements ZipExtraField
*/ */
public function setAccessDateTime(\DateTimeInterface $accessTime) public function setAccessDateTime(\DateTimeInterface $accessTime)
{ {
$this->accessTime = $this->dateTimeToNtfsTime($accessTime); $this->accessTime = self::dateTimeToNtfsTime($accessTime);
} }
/** /**
@@ -177,7 +193,7 @@ class NtfsExtraField implements ZipExtraField
*/ */
public function getCreateDateTime() public function getCreateDateTime()
{ {
return $this->ntfsTimeToDateTime($this->createTime); return self::ntfsTimeToDateTime($this->createTime);
} }
/** /**
@@ -185,7 +201,7 @@ class NtfsExtraField implements ZipExtraField
*/ */
public function setCreateDateTime(\DateTimeInterface $createTime) public function setCreateDateTime(\DateTimeInterface $createTime)
{ {
$this->createTime = $this->dateTimeToNtfsTime($createTime); $this->createTime = self::dateTimeToNtfsTime($createTime);
} }
/** /**
@@ -193,7 +209,7 @@ class NtfsExtraField implements ZipExtraField
* *
* @return int * @return int
*/ */
protected function dateTimeToNtfsTime(\DateTimeInterface $dateTime) public static function dateTimeToNtfsTime(\DateTimeInterface $dateTime)
{ {
return $dateTime->getTimestamp() * 10000000 + self::EPOCH_OFFSET; return $dateTime->getTimestamp() * 10000000 + self::EPOCH_OFFSET;
} }
@@ -203,7 +219,7 @@ class NtfsExtraField implements ZipExtraField
* *
* @return \DateTimeInterface * @return \DateTimeInterface
*/ */
protected function ntfsTimeToDateTime($time) public static function ntfsTimeToDateTime($time)
{ {
$timestamp = (int) ($time / 10000000 + self::EPOCH_OFFSET); $timestamp = (int) ($time / 10000000 + self::EPOCH_OFFSET);

View File

@@ -281,34 +281,6 @@ class ZipContainer extends ImmutableZipContainer
$this->archiveComment = $archiveComment; $this->archiveComment = $archiveComment;
} }
/**
* @param ZipEntry $entry
*
* @return bool
*/
public function hasRecompressData(ZipEntry $entry)
{
// todo test with rename, check exists ZipSourceData
if ($this->sourceContainer && isset($this->sourceContainer->entries[$entry->getName()])) {
$sourceEntry = $this->sourceContainer->entries[$entry->getName()];
if (
$sourceEntry->getCompressionLevel() !== $entry->getCompressionLevel() ||
$sourceEntry->getCompressionMethod() !== $entry->getCompressionMethod() ||
$sourceEntry->isEncrypted() !== $entry->isEncrypted() ||
$sourceEntry->getEncryptionMethod() !== $entry->getEncryptionMethod() ||
$sourceEntry->getPassword() !== $entry->getPassword() ||
$sourceEntry->getCompressedSize() !== $entry->getCompressedSize() ||
$sourceEntry->getUncompressedSize() !== $entry->getUncompressedSize() ||
$sourceEntry->getCrc() !== $entry->getCrc()
) {
return true;
}
}
return false;
}
/** /**
* @return ZipEntryMatcher * @return ZipEntryMatcher
*/ */

View File

@@ -31,9 +31,9 @@ use PhpZip\Util\StringUtil;
/** /**
* ZIP file entry. * ZIP file entry.
* *
* @see https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT .ZIP File Format Specification * @see https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT .ZIP File Format Specification
* *
* @author Ne-Lexa alexey@nelexa.ru * @author Ne-Lexa alexey@nelexa.ru
* @license MIT * @license MIT
*/ */
class ZipEntry class ZipEntry
@@ -152,11 +152,12 @@ class ZipEntry
/** /**
* ZipEntry constructor. * ZipEntry constructor.
* *
* @param string $name Entry name * @param string $name Entry name
* @param string|null $charset DOS charset
*/ */
public function __construct($name) public function __construct($name, $charset = null)
{ {
$this->setName($name); $this->setName($name, $charset);
$this->cdExtraFields = new ExtraFieldsCollection(); $this->cdExtraFields = new ExtraFieldsCollection();
$this->localExtraFields = new ExtraFieldsCollection(); $this->localExtraFields = new ExtraFieldsCollection();
@@ -185,6 +186,7 @@ class ZipEntry
* @return ZipEntry * @return ZipEntry
* *
* @internal * @internal
*
* @noinspection PhpTooManyParametersInspection * @noinspection PhpTooManyParametersInspection
*/ */
public static function create( public static function create(
@@ -229,11 +231,12 @@ class ZipEntry
/** /**
* Set entry name. * Set entry name.
* *
* @param string $name New entry name * @param string $name New entry name
* @param string|null $charset
* *
* @return ZipEntry * @return ZipEntry
*/ */
private function setName($name) private function setName($name, $charset = null)
{ {
if ($name === null) { if ($name === null) {
throw new InvalidArgumentException('zip entry name is null'); throw new InvalidArgumentException('zip entry name is null');
@@ -252,13 +255,24 @@ class ZipEntry
throw new InvalidArgumentException('Illegal zip entry name parameter'); throw new InvalidArgumentException('Illegal zip entry name parameter');
} }
if (!StringUtil::isASCII($name)) { $this->setCharset($charset);
if ($this->charset === null && !StringUtil::isASCII($name)) {
$this->enableUtf8Name(true); $this->enableUtf8Name(true);
} }
$this->name = $name; $this->name = $name;
$this->isDirectory = ($length = \strlen($name)) >= 1 && $name[$length - 1] === '/'; $this->isDirectory = ($length = \strlen($name)) >= 1 && $name[$length - 1] === '/';
$this->externalAttributes = $this->isDirectory ? DosAttrs::DOS_DIRECTORY : DosAttrs::DOS_ARCHIVE; $this->externalAttributes = $this->isDirectory ? DosAttrs::DOS_DIRECTORY : DosAttrs::DOS_ARCHIVE;
if ($this->extractVersion !== self::UNKNOWN) {
$this->extractVersion = max(
$this->extractVersion,
$this->isDirectory ?
ZipVersion::v20_DEFLATED_FOLDER_ZIPCRYPTO :
ZipVersion::v10_DEFAULT_MIN
);
}
return $this; return $this;
} }
@@ -291,6 +305,8 @@ class ZipEntry
* @param string $newName New entry name * @param string $newName New entry name
* *
* @return ZipEntry new {@see ZipEntry} object with new name * @return ZipEntry new {@see ZipEntry} object with new name
*
* @internal
*/ */
public function rename($newName) public function rename($newName)
{ {
@@ -314,6 +330,8 @@ class ZipEntry
/** /**
* @return ZipData|null * @return ZipData|null
*
* @internal
*/ */
public function getData() public function getData()
{ {
@@ -322,6 +340,8 @@ class ZipEntry
/** /**
* @param ZipData|null $data * @param ZipData|null $data
*
* @internal
*/ */
public function setData($data) public function setData($data)
{ {
@@ -458,7 +478,7 @@ class ZipEntry
return ZipVersion::v51_ENCR_AES_RC2_CORRECT; return ZipVersion::v51_ENCR_AES_RC2_CORRECT;
} }
if ($this->getCompressionMethod() === ZipCompressionMethod::BZIP2) { if ($this->compressionMethod === ZipCompressionMethod::BZIP2) {
return ZipVersion::v46_BZIP2; return ZipVersion::v46_BZIP2;
} }
@@ -466,9 +486,15 @@ class ZipEntry
return ZipVersion::v45_ZIP64_EXT; return ZipVersion::v45_ZIP64_EXT;
} }
return $this->getCompressionMethod() === ZipCompressionMethod::DEFLATED || $this->isDirectory() ? if (
ZipVersion::v20_DEFLATED_FOLDER_ZIPCRYPTO : $this->compressionMethod === ZipCompressionMethod::DEFLATED ||
ZipVersion::v10_DEFAULT_MIN; $this->isDirectory ||
$this->encryptionMethod === ZipEncryptionMethod::PKWARE
) {
return ZipVersion::v20_DEFLATED_FOLDER_ZIPCRYPTO;
}
return ZipVersion::v10_DEFAULT_MIN;
} }
return $this->extractVersion; return $this->extractVersion;
@@ -520,9 +546,16 @@ class ZipEntry
* @param int $compressedSize the Compressed Size * @param int $compressedSize the Compressed Size
* *
* @return ZipEntry * @return ZipEntry
*
* @internal
*/ */
public function setCompressedSize($compressedSize) public function setCompressedSize($compressedSize)
{ {
$compressedSize = (int) $compressedSize;
if ($compressedSize < self::UNKNOWN) {
throw new InvalidArgumentException('Compressed size < ' . self::UNKNOWN);
}
$this->compressedSize = $compressedSize; $this->compressedSize = $compressedSize;
return $this; return $this;
@@ -550,6 +583,8 @@ class ZipEntry
* @return ZipEntry * @return ZipEntry
* *
* @deprecated Use {@see ZipEntry::setUncompressedSize()} * @deprecated Use {@see ZipEntry::setUncompressedSize()}
*
* @internal
*/ */
public function setSize($size) public function setSize($size)
{ {
@@ -574,9 +609,16 @@ class ZipEntry
* @param int $uncompressedSize the (Uncompressed) Size * @param int $uncompressedSize the (Uncompressed) Size
* *
* @return ZipEntry * @return ZipEntry
*
* @internal
*/ */
public function setUncompressedSize($uncompressedSize) public function setUncompressedSize($uncompressedSize)
{ {
$uncompressedSize = (int) $uncompressedSize;
if ($uncompressedSize < self::UNKNOWN) {
throw new InvalidArgumentException('Uncompressed size < ' . self::UNKNOWN);
}
$this->uncompressedSize = $uncompressedSize; $this->uncompressedSize = $uncompressedSize;
return $this; return $this;
@@ -596,10 +638,17 @@ class ZipEntry
* @param int $localHeaderOffset * @param int $localHeaderOffset
* *
* @return ZipEntry * @return ZipEntry
*
* @internal
*/ */
public function setLocalHeaderOffset($localHeaderOffset) public function setLocalHeaderOffset($localHeaderOffset)
{ {
$this->localHeaderOffset = (int) $localHeaderOffset; $localHeaderOffset = (int) $localHeaderOffset;
if ($localHeaderOffset < 0) {
throw new InvalidArgumentException('Negative $localHeaderOffset');
}
$this->localHeaderOffset = $localHeaderOffset;
return $this; return $this;
} }
@@ -627,6 +676,8 @@ class ZipEntry
* @return ZipEntry * @return ZipEntry
* *
* @deprecated Use {@see ZipEntry::setLocalHeaderOffset()} * @deprecated Use {@see ZipEntry::setLocalHeaderOffset()}
*
* @internal
*/ */
public function setOffset($offset) public function setOffset($offset)
{ {
@@ -645,24 +696,26 @@ class ZipEntry
*/ */
public function getGeneralPurposeBitFlags() public function getGeneralPurposeBitFlags()
{ {
return $this->generalPurposeBitFlags & 0xffff; return $this->generalPurposeBitFlags;
} }
/** /**
* Sets the General Purpose Bit Flags. * Sets the General Purpose Bit Flags.
* *
* @param mixed $general * @param int $gpbf general purpose bit flags
* *
* @return ZipEntry * @return ZipEntry
* *
* @var int general * @internal
*/ */
public function setGeneralPurposeBitFlags($general) public function setGeneralPurposeBitFlags($gpbf)
{ {
if ($general < 0x0000 || $general > 0xffff) { $gpbf = (int) $gpbf;
throw new InvalidArgumentException('general out of range');
if ($gpbf < 0x0000 || $gpbf > 0xffff) {
throw new InvalidArgumentException('general purpose bit flags out of range');
} }
$this->generalPurposeBitFlags = $general; $this->generalPurposeBitFlags = $gpbf;
$this->updateCompressionLevel(); $this->updateCompressionLevel();
return $this; return $this;
@@ -710,7 +763,7 @@ class ZipEntry
*/ */
private function isSetGeneralBitFlag($mask) private function isSetGeneralBitFlag($mask)
{ {
return ($this->generalPurposeBitFlags & $mask) !== 0; return ($this->generalPurposeBitFlags & $mask) === $mask;
} }
/** /**
@@ -775,7 +828,9 @@ class ZipEntry
{ {
$this->setEncrypted(false); $this->setEncrypted(false);
$this->removeExtraField(WinZipAesExtraField::HEADER_ID); $this->removeExtraField(WinZipAesExtraField::HEADER_ID);
$this->encryptionMethod = ZipEncryptionMethod::NONE;
$this->password = null; $this->password = null;
$this->extractVersion = self::UNKNOWN;
return $this; return $this;
} }
@@ -858,7 +913,9 @@ class ZipEntry
*/ */
public function setCompressionMethod($compressionMethod) public function setCompressionMethod($compressionMethod)
{ {
if (($compressionMethod < 0x0000 || $compressionMethod > 0xffff) && $compressionMethod !== self::UNKNOWN) { $compressionMethod = (int) $compressionMethod;
if ($compressionMethod < 0x0000 || $compressionMethod > 0xffff) {
throw new InvalidArgumentException('method out of range: ' . $compressionMethod); throw new InvalidArgumentException('method out of range: ' . $compressionMethod);
} }
@@ -866,6 +923,7 @@ class ZipEntry
$this->compressionMethod = $compressionMethod; $this->compressionMethod = $compressionMethod;
$this->updateCompressionLevel(); $this->updateCompressionLevel();
$this->extractVersion = self::UNKNOWN;
return $this; return $this;
} }
@@ -881,7 +939,7 @@ class ZipEntry
return self::UNKNOWN; return self::UNKNOWN;
} }
return DateTimeConverter::toUnixTimestamp($this->getDosTime()); return DateTimeConverter::msDosToUnix($this->getDosTime());
} }
/** /**
@@ -922,10 +980,8 @@ class ZipEntry
*/ */
public function setTime($unixTimestamp) public function setTime($unixTimestamp)
{ {
$known = $unixTimestamp !== self::UNKNOWN; if ($unixTimestamp !== self::UNKNOWN) {
$this->setDosTime(DateTimeConverter::unixToMsDos($unixTimestamp));
if ($known) {
$this->dosTime = DateTimeConverter::toDosTime($unixTimestamp);
} else { } else {
$this->dosTime = 0; $this->dosTime = 0;
} }
@@ -954,6 +1010,11 @@ class ZipEntry
{ {
$this->externalAttributes = (int) $externalAttributes; $this->externalAttributes = (int) $externalAttributes;
if ($externalAttributes < 0x00000000 || $externalAttributes > 0xffffffff) {
throw new InvalidArgumentException('external attributes out of range: ' . $externalAttributes);
}
$this->externalAttributes = $externalAttributes;
return $this; return $this;
} }
@@ -970,13 +1031,18 @@ class ZipEntry
/** /**
* Sets the internal file attributes. * Sets the internal file attributes.
* *
* @param int $attributes the internal file attributes * @param int $internalAttributes the internal file attributes
* *
* @return ZipEntry * @return ZipEntry
*/ */
public function setInternalAttributes($attributes) public function setInternalAttributes($internalAttributes)
{ {
$this->internalAttributes = (int) $attributes; $internalAttributes = (int) $internalAttributes;
if ($internalAttributes < 0x0000 || $internalAttributes > 0xffff) {
throw new InvalidArgumentException('internal attributes out of range');
}
$this->internalAttributes = $internalAttributes;
return $this; return $this;
} }
@@ -1094,6 +1160,31 @@ class ZipEntry
$this->localExtraFields->remove($headerId); $this->localExtraFields->remove($headerId);
} }
/**
* @param ZipExtraField $zipExtraField
*/
public function addExtraField(ZipExtraField $zipExtraField)
{
$this->addLocalExtraField($zipExtraField);
$this->addCdExtraField($zipExtraField);
}
/**
* @param ZipExtraField $zipExtraField
*/
public function addLocalExtraField(ZipExtraField $zipExtraField)
{
$this->localExtraFields->add($zipExtraField);
}
/**
* @param ZipExtraField $zipExtraField
*/
public function addCdExtraField(ZipExtraField $zipExtraField)
{
$this->cdExtraFields->add($zipExtraField);
}
/** /**
* Returns comment entry. * Returns comment entry.
* *
@@ -1116,11 +1207,11 @@ class ZipEntry
if ($comment !== null) { if ($comment !== null) {
$commentLength = \strlen($comment); $commentLength = \strlen($comment);
if ($commentLength < 0x0000 || $commentLength > 0xffff) { if ($commentLength > 0xffff) {
throw new InvalidArgumentException('Comment too long'); throw new InvalidArgumentException('Comment too long');
} }
if (!StringUtil::isASCII($comment)) { if ($this->charset === null && !StringUtil::isASCII($comment)) {
$this->enableUtf8Name(true); $this->enableUtf8Name(true);
} }
} }
@@ -1153,6 +1244,8 @@ class ZipEntry
* @param int $crc * @param int $crc
* *
* @return ZipEntry * @return ZipEntry
*
* @internal
*/ */
public function setCrc($crc) public function setCrc($crc)
{ {
@@ -1180,15 +1273,19 @@ class ZipEntry
public function setPassword($password, $encryptionMethod = null) public function setPassword($password, $encryptionMethod = null)
{ {
if (!$this->isDirectory) { if (!$this->isDirectory) {
if ($encryptionMethod !== null) {
$this->setEncryptionMethod($encryptionMethod);
}
if ($password === null || $password === '') { if ($password === null || $password === '') {
$this->password = null; $this->password = null;
$this->disableEncryption(); $this->disableEncryption();
} else { } else {
$this->password = (string) $password; $this->password = (string) $password;
if ($encryptionMethod === null && $this->encryptionMethod === ZipEncryptionMethod::NONE) {
$encryptionMethod = ZipEncryptionMethod::WINZIP_AES_256;
}
if ($encryptionMethod !== null) {
$this->setEncryptionMethod($encryptionMethod);
}
$this->setEncrypted(true); $this->setEncrypted(true);
} }
} }
@@ -1228,6 +1325,7 @@ class ZipEntry
$this->encryptionMethod = $encryptionMethod; $this->encryptionMethod = $encryptionMethod;
$this->setEncrypted($this->encryptionMethod !== ZipEncryptionMethod::NONE); $this->setEncrypted($this->encryptionMethod !== ZipEncryptionMethod::NONE);
$this->extractVersion = self::UNKNOWN;
return $this; return $this;
} }
@@ -1329,18 +1427,21 @@ class ZipEntry
*/ */
public function getUnixMode() public function getUnixMode()
{ {
/** @var AsiExtraField|null $asiExtraField */ $mode = 0;
$asiExtraField = $this->getExtraField(AsiExtraField::HEADER_ID);
if ($asiExtraField !== null) {
return $asiExtraField->getMode();
}
if ($this->createdOS === ZipPlatform::OS_UNIX) { if ($this->createdOS === ZipPlatform::OS_UNIX) {
return ($this->externalAttributes >> 16) & 0xFFFF; $mode = ($this->externalAttributes >> 16) & 0xFFFF;
} elseif ($this->hasExtraField(AsiExtraField::HEADER_ID)) {
/** @var AsiExtraField $asiExtraField */
$asiExtraField = $this->getExtraField(AsiExtraField::HEADER_ID);
$mode = $asiExtraField->getMode();
} }
return $this->isDirectory ? 040755 : 0100664; if ($mode > 0) {
return $mode;
}
return $this->isDirectory ? 040755 : 0100644;
} }
/** /**
@@ -1351,8 +1452,8 @@ class ZipEntry
*/ */
public function isZip64ExtensionsRequired() public function isZip64ExtensionsRequired()
{ {
return $this->compressedSize >= ZipConstants::ZIP64_MAGIC return $this->compressedSize > ZipConstants::ZIP64_MAGIC
|| $this->uncompressedSize >= ZipConstants::ZIP64_MAGIC; || $this->uncompressedSize > ZipConstants::ZIP64_MAGIC;
} }
/** /**

View File

@@ -5,6 +5,21 @@ namespace PhpZip\Util;
/** /**
* Convert unix timestamp values to DOS date/time values and vice versa. * Convert unix timestamp values to DOS date/time values and vice versa.
* *
* The DOS date/time format is a bitmask:
*
* 24 16 8 0
* +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
* |Y|Y|Y|Y|Y|Y|Y|M| |M|M|M|D|D|D|D|D| |h|h|h|h|h|m|m|m| |m|m|m|s|s|s|s|s|
* +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
* \___________/\________/\_________/ \________/\____________/\_________/
* year month day hour minute second
*
* The year is stored as an offset from 1980.
* Seconds are stored in two-second increments.
* (So if the "second" value is 15, it actually represents 30 seconds.)
*
* @see https://docs.microsoft.com/ru-ru/windows/win32/api/winbase/nf-winbase-filetimetodosdatetime?redirectedfrom=MSDN
*
* @author Ne-Lexa alexey@nelexa.ru * @author Ne-Lexa alexey@nelexa.ru
* @license MIT * @license MIT
* *
@@ -31,21 +46,21 @@ class DateTimeConverter
* *
* @return int Unix timestamp * @return int Unix timestamp
*/ */
public static function toUnixTimestamp($dosTime) public static function msDosToUnix($dosTime)
{ {
if ($dosTime < self::MIN_DOS_TIME) { if ($dosTime <= self::MIN_DOS_TIME) {
$dosTime = self::MIN_DOS_TIME; $dosTime = 0;
} elseif ($dosTime > self::MAX_DOS_TIME) { } elseif ($dosTime > self::MAX_DOS_TIME) {
$dosTime = self::MAX_DOS_TIME; $dosTime = self::MAX_DOS_TIME;
} }
// date_default_timezone_set('UTC');
return mktime( return mktime(
($dosTime >> 11) & 0x1f, // hour (($dosTime >> 11) & 0x1f), // hours
($dosTime >> 5) & 0x3f, // minute (($dosTime >> 5) & 0x3f), // minutes
2 * ($dosTime & 0x1f), // second (($dosTime << 1) & 0x3e), // seconds
($dosTime >> 21) & 0x0f, // month (($dosTime >> 21) & 0x0f), // month
($dosTime >> 16) & 0x1f, // day (($dosTime >> 16) & 0x1f), // day
1980 + (($dosTime >> 25) & 0x7f) // year ((($dosTime >> 25) & 0x7f) + 1980) // year
); );
} }
@@ -59,22 +74,26 @@ class DateTimeConverter
* rounded down to even seconds * rounded down to even seconds
* and is in between DateTimeConverter::MIN_DOS_TIME and DateTimeConverter::MAX_DOS_TIME * and is in between DateTimeConverter::MIN_DOS_TIME and DateTimeConverter::MAX_DOS_TIME
*/ */
public static function toDosTime($unixTimestamp) public static function unixToMsDos($unixTimestamp)
{ {
if ($unixTimestamp < 0) { if ($unixTimestamp < 0) {
throw new \InvalidArgumentException('Negative unix timestamp: ' . $unixTimestamp); throw new \InvalidArgumentException('Negative unix timestamp: ' . $unixTimestamp);
} }
$date = getdate($unixTimestamp); $date = getdate($unixTimestamp);
$dosTime = (
(($date['year'] - 1980) << 25) |
($date['mon'] << 21) |
($date['mday'] << 16) |
($date['hours'] << 11) |
($date['minutes'] << 5) |
($date['seconds'] >> 1)
);
if ($date['year'] < 1980) { if ($dosTime <= self::MIN_DOS_TIME) {
return self::MIN_DOS_TIME; $dosTime = 0;
} }
$date['year'] -= 1980; return $dosTime;
return $date['year'] << 25 | $date['mon'] << 21 |
$date['mday'] << 16 | $date['hours'] << 11 |
$date['minutes'] << 5 | $date['seconds'] >> 1;
} }
} }

View File

@@ -9,17 +9,6 @@ namespace PhpZip\Util;
*/ */
final class StringUtil final class StringUtil
{ {
/**
* @param string $haystack
* @param string $needle
*
* @return bool
*/
public static function startsWith($haystack, $needle)
{
return $needle === '' || strrpos($haystack, $needle, -\strlen($haystack)) !== false;
}
/** /**
* @param string $haystack * @param string $haystack
* @param string $needle * @param string $needle
@@ -28,8 +17,13 @@ final class StringUtil
*/ */
public static function endsWith($haystack, $needle) public static function endsWith($haystack, $needle)
{ {
return $needle === '' || (($temp = \strlen($haystack) - \strlen($needle)) >= 0 $length = \strlen($needle);
&& strpos($haystack, $needle, $temp) !== false);
if ($length === 0) {
return true;
}
return substr($haystack, -$length) === $needle;
} }
/** /**

View File

@@ -570,7 +570,7 @@ class ZipFile implements ZipFileInterface
$zipEntry->setCompressionMethod($compressionMethod); $zipEntry->setCompressionMethod($compressionMethod);
$zipEntry->setCreatedOS(ZipPlatform::OS_UNIX); $zipEntry->setCreatedOS(ZipPlatform::OS_UNIX);
$zipEntry->setExtractedOS(ZipPlatform::OS_UNIX); $zipEntry->setExtractedOS(ZipPlatform::OS_UNIX);
$zipEntry->setUnixMode(010644); $zipEntry->setUnixMode(0100644);
$zipEntry->setTime(time()); $zipEntry->setTime(time());
$this->addZipEntry($zipEntry); $this->addZipEntry($zipEntry);
@@ -794,7 +794,7 @@ class ZipFile implements ZipFileInterface
$zipEntry = new ZipEntry($entryName); $zipEntry = new ZipEntry($entryName);
if ($fstat !== false) { if ($fstat !== false) {
$unixMode = (int) sprintf('%o', $fstat['mode']); $unixMode = $fstat['mode'];
$length = $fstat['size']; $length = $fstat['size'];
if ($compressionMethod === null || $compressionMethod === ZipEntry::UNKNOWN) { if ($compressionMethod === null || $compressionMethod === ZipEntry::UNKNOWN) {
@@ -812,7 +812,7 @@ class ZipFile implements ZipFileInterface
$zipEntry->setUncompressedSize($length); $zipEntry->setUncompressedSize($length);
} }
} else { } else {
$unixMode = 010644; $unixMode = 0100644;
if ($compressionMethod === null || $compressionMethod === ZipEntry::UNKNOWN) { if ($compressionMethod === null || $compressionMethod === ZipEntry::UNKNOWN) {
$compressionMethod = ZipCompressionMethod::DEFLATED; $compressionMethod = ZipCompressionMethod::DEFLATED;

View File

@@ -17,8 +17,6 @@ class Zip64Test extends ZipTestCase
{ {
/** /**
* @throws ZipException * @throws ZipException
*
* @runInSeparateProcess
*/ */
public function testCreateLargeZip64File() public function testCreateLargeZip64File()
{ {

View File

@@ -22,6 +22,12 @@ class Zip64Test extends ZipTestCase
*/ */
public function testOver65535FilesInZip() public function testOver65535FilesInZip()
{ {
if (\PHP_INT_SIZE === 4) { // php 32 bit
static::markTestSkipped('Only php-64 bit.');
return;
}
$countFiles = 0xffff + 1; $countFiles = 0xffff + 1;
$zipFile = new ZipFile(); $zipFile = new ZipFile();

1561
tests/ZipEntryTest.php Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -2389,4 +2389,33 @@ class ZipFileTest extends ZipTestCase
} }
$zipFile->close(); $zipFile->close();
} }
/**
* @throws ZipException
*/
public function testRenameWithRecompressData()
{
$entryName = 'file.txt';
$newEntryName = 'rename_file.txt';
$contents = str_repeat('Test' . \PHP_EOL, 1024);
$zipFile = new ZipFile();
$zipFile->addFromString($entryName, $contents, ZipCompressionMethod::DEFLATED);
$zipFile->saveAsFile($this->outputFilename);
$zipFile->close();
self::assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename);
$zipFile->rename($entryName, $newEntryName);
$zipFile->setCompressionMethodEntry($newEntryName, ZipCompressionMethod::STORED);
$zipFile->saveAsFile($this->outputFilename);
$zipFile->close();
self::assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename);
static::assertSame($zipFile->getEntry($newEntryName)->getCompressionMethod(), ZipCompressionMethod::STORED);
$zipFile->close();
}
} }

View File

@@ -57,8 +57,7 @@ class ZipPasswordTest extends ZipFileSetTestCase
try { try {
$zipFile[$entryName]; $zipFile[$entryName];
static::fail('Expected Exception has not been raised.'); static::fail('Expected Exception has not been raised.');
} catch (ZipAuthenticationException $ae) { } catch (ZipException $e) {
static::assertContains('Invalid password', $ae->getMessage());
} }
} }