2
0

ZipInputStream.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. <?php
  2. namespace PhpZip\Stream;
  3. use PhpZip\Crypto\TraditionalPkwareEncryptionEngine;
  4. use PhpZip\Crypto\WinZipAesEngine;
  5. use PhpZip\Exception\Crc32Exception;
  6. use PhpZip\Exception\InvalidArgumentException;
  7. use PhpZip\Exception\RuntimeException;
  8. use PhpZip\Exception\ZipAuthenticationException;
  9. use PhpZip\Exception\ZipException;
  10. use PhpZip\Exception\ZipUnsupportMethodException;
  11. use PhpZip\Extra\ExtraFieldsCollection;
  12. use PhpZip\Extra\ExtraFieldsFactory;
  13. use PhpZip\Extra\Fields\ApkAlignmentExtraField;
  14. use PhpZip\Extra\Fields\WinZipAesEntryExtraField;
  15. use PhpZip\Model\EndOfCentralDirectory;
  16. use PhpZip\Model\Entry\ZipSourceEntry;
  17. use PhpZip\Model\ZipEntry;
  18. use PhpZip\Model\ZipModel;
  19. use PhpZip\Util\PackUtil;
  20. use PhpZip\Util\StringUtil;
  21. use PhpZip\ZipFile;
  22. /**
  23. * Read zip file.
  24. *
  25. * @author Ne-Lexa alexey@nelexa.ru
  26. * @license MIT
  27. */
  28. class ZipInputStream implements ZipInputStreamInterface
  29. {
  30. /** @var resource */
  31. protected $in;
  32. /** @var ZipModel */
  33. protected $zipModel;
  34. /**
  35. * ZipInputStream constructor.
  36. *
  37. * @param resource $in
  38. */
  39. public function __construct($in)
  40. {
  41. if (!\is_resource($in)) {
  42. throw new RuntimeException('$in must be resource');
  43. }
  44. $this->in = $in;
  45. }
  46. /**
  47. * @throws ZipException
  48. *
  49. * @return ZipModel
  50. */
  51. public function readZip()
  52. {
  53. $this->checkZipFileSignature();
  54. $endOfCentralDirectory = $this->readEndOfCentralDirectory();
  55. $entries = $this->mountCentralDirectory($endOfCentralDirectory);
  56. $this->zipModel = ZipModel::newSourceModel($entries, $endOfCentralDirectory);
  57. return $this->zipModel;
  58. }
  59. /**
  60. * Check zip file signature.
  61. *
  62. * @throws ZipException if this not .ZIP file.
  63. */
  64. protected function checkZipFileSignature()
  65. {
  66. rewind($this->in);
  67. // Constraint: A ZIP file must start with a Local File Header
  68. // or a (ZIP64) End Of Central Directory Record if it's empty.
  69. $signatureBytes = fread($this->in, 4);
  70. if (\strlen($signatureBytes) < 4) {
  71. throw new ZipException('Invalid zip file.');
  72. }
  73. $signature = unpack('V', $signatureBytes)[1];
  74. if (
  75. $signature !== ZipEntry::LOCAL_FILE_HEADER_SIG
  76. && $signature !== EndOfCentralDirectory::ZIP64_END_OF_CD_RECORD_SIG
  77. && $signature !== EndOfCentralDirectory::END_OF_CD_SIG
  78. ) {
  79. throw new ZipException(
  80. 'Expected Local File Header or (ZIP64) End Of Central Directory Record! Signature: ' . $signature
  81. );
  82. }
  83. }
  84. /**
  85. * @throws ZipException
  86. *
  87. * @return EndOfCentralDirectory
  88. */
  89. protected function readEndOfCentralDirectory()
  90. {
  91. if (!$this->findEndOfCentralDirectory()) {
  92. throw new ZipException('Invalid zip file. The end of the central directory could not be found.');
  93. }
  94. $positionECD = ftell($this->in) - 4;
  95. $buffer = fread($this->in, fstat($this->in)['size'] - $positionECD);
  96. $unpack = unpack(
  97. 'vdiskNo/vcdDiskNo/vcdEntriesDisk/' .
  98. 'vcdEntries/VcdSize/VcdPos/vcommentLength',
  99. substr($buffer, 0, 18)
  100. );
  101. if (
  102. $unpack['diskNo'] !== 0 ||
  103. $unpack['cdDiskNo'] !== 0 ||
  104. $unpack['cdEntriesDisk'] !== $unpack['cdEntries']
  105. ) {
  106. throw new ZipException(
  107. 'ZIP file spanning/splitting is not supported!'
  108. );
  109. }
  110. // .ZIP file comment (variable sizeECD)
  111. $comment = null;
  112. if ($unpack['commentLength'] > 0) {
  113. $comment = substr($buffer, 18, $unpack['commentLength']);
  114. }
  115. // Check for ZIP64 End Of Central Directory Locator exists.
  116. $zip64ECDLocatorPosition = $positionECD - EndOfCentralDirectory::ZIP64_END_OF_CD_LOCATOR_LEN;
  117. fseek($this->in, $zip64ECDLocatorPosition);
  118. // zip64 end of central dir locator
  119. // signature 4 bytes (0x07064b50)
  120. if ($zip64ECDLocatorPosition > 0 && unpack(
  121. 'V',
  122. fread($this->in, 4)
  123. )[1] === EndOfCentralDirectory::ZIP64_END_OF_CD_LOCATOR_SIG) {
  124. $positionECD = $this->findZip64ECDPosition();
  125. $endCentralDirectory = $this->readZip64EndOfCentralDirectory($positionECD);
  126. $endCentralDirectory->setComment($comment);
  127. } else {
  128. $endCentralDirectory = new EndOfCentralDirectory(
  129. $unpack['cdEntries'],
  130. $unpack['cdPos'],
  131. $unpack['cdSize'],
  132. false,
  133. $comment
  134. );
  135. }
  136. return $endCentralDirectory;
  137. }
  138. /**
  139. * @throws ZipException
  140. *
  141. * @return bool
  142. */
  143. protected function findEndOfCentralDirectory()
  144. {
  145. $max = fstat($this->in)['size'] - EndOfCentralDirectory::END_OF_CENTRAL_DIRECTORY_RECORD_MIN_LEN;
  146. if ($max < 0) {
  147. throw new ZipException('Too short to be a zip file');
  148. }
  149. $min = $max >= 0xffff ? $max - 0xffff : 0;
  150. // Search for End of central directory record.
  151. for ($position = $max; $position >= $min; $position--) {
  152. fseek($this->in, $position);
  153. // end of central dir signature 4 bytes (0x06054b50)
  154. if (unpack('V', fread($this->in, 4))[1] !== EndOfCentralDirectory::END_OF_CD_SIG) {
  155. continue;
  156. }
  157. return true;
  158. }
  159. return false;
  160. }
  161. /**
  162. * Read Zip64 end of central directory locator and returns
  163. * Zip64 end of central directory position.
  164. *
  165. * number of the disk with the
  166. * start of the zip64 end of
  167. * central directory 4 bytes
  168. * relative offset of the zip64
  169. * end of central directory record 8 bytes
  170. * total number of disks 4 bytes
  171. *
  172. * @throws ZipException
  173. *
  174. * @return int Zip64 End Of Central Directory position
  175. */
  176. protected function findZip64ECDPosition()
  177. {
  178. $diskNo = unpack('V', fread($this->in, 4))[1];
  179. $zip64ECDPos = PackUtil::unpackLongLE(fread($this->in, 8));
  180. $totalDisks = unpack('V', fread($this->in, 4))[1];
  181. if ($diskNo !== 0 || $totalDisks > 1) {
  182. throw new ZipException('ZIP file spanning/splitting is not supported!');
  183. }
  184. return $zip64ECDPos;
  185. }
  186. /**
  187. * Read zip64 end of central directory locator and zip64 end
  188. * of central directory record.
  189. *
  190. * zip64 end of central dir
  191. * signature 4 bytes (0x06064b50)
  192. * size of zip64 end of central
  193. * directory record 8 bytes
  194. * version made by 2 bytes
  195. * version needed to extract 2 bytes
  196. * number of this disk 4 bytes
  197. * number of the disk with the
  198. * start of the central directory 4 bytes
  199. * total number of entries in the
  200. * central directory on this disk 8 bytes
  201. * total number of entries in the
  202. * central directory 8 bytes
  203. * size of the central directory 8 bytes
  204. * offset of start of central
  205. * directory with respect to
  206. * the starting disk number 8 bytes
  207. * zip64 extensible data sector (variable size)
  208. *
  209. * @param int $zip64ECDPosition
  210. *
  211. * @throws ZipException
  212. *
  213. * @return EndOfCentralDirectory
  214. */
  215. protected function readZip64EndOfCentralDirectory($zip64ECDPosition)
  216. {
  217. fseek($this->in, $zip64ECDPosition);
  218. $buffer = fread($this->in, 56 /* zip64 end of cd rec length */);
  219. if (unpack('V', $buffer)[1] !== EndOfCentralDirectory::ZIP64_END_OF_CD_RECORD_SIG) {
  220. throw new ZipException('Expected ZIP64 End Of Central Directory Record!');
  221. }
  222. $data = unpack(
  223. 'VdiskNo/VcdDiskNo',
  224. substr($buffer, 16)
  225. );
  226. $cdEntriesDisk = PackUtil::unpackLongLE(substr($buffer, 24, 8));
  227. $entryCount = PackUtil::unpackLongLE(substr($buffer, 32, 8));
  228. $cdSize = PackUtil::unpackLongLE(substr($buffer, 40, 8));
  229. $cdPos = PackUtil::unpackLongLE(substr($buffer, 48, 8));
  230. if ($data['diskNo'] !== 0 || $data['cdDiskNo'] !== 0 || $entryCount !== $cdEntriesDisk) {
  231. throw new ZipException('ZIP file spanning/splitting is not supported!');
  232. }
  233. if ($entryCount < 0 || $entryCount > 0x7fffffff) {
  234. throw new ZipException('Total Number Of Entries In The Central Directory out of range!');
  235. }
  236. // skip zip64 extensible data sector (variable sizeEndCD)
  237. return new EndOfCentralDirectory(
  238. $entryCount,
  239. $cdPos,
  240. $cdSize,
  241. true
  242. );
  243. }
  244. /**
  245. * Reads the central directory from the given seekable byte channel
  246. * and populates the internal tables with ZipEntry instances.
  247. *
  248. * The ZipEntry's will know all data that can be obtained from the
  249. * central directory alone, but not the data that requires the local
  250. * file header or additional data to be read.
  251. *
  252. * @param EndOfCentralDirectory $endOfCentralDirectory
  253. *
  254. * @throws ZipException
  255. *
  256. * @return ZipEntry[]
  257. */
  258. protected function mountCentralDirectory(EndOfCentralDirectory $endOfCentralDirectory)
  259. {
  260. $entries = [];
  261. fseek($this->in, $endOfCentralDirectory->getCdOffset());
  262. if (!($cdStream = fopen('php://temp', 'w+b'))) {
  263. throw new ZipException('Temp resource can not open from write');
  264. }
  265. stream_copy_to_stream($this->in, $cdStream, $endOfCentralDirectory->getCdSize());
  266. rewind($cdStream);
  267. for ($numEntries = $endOfCentralDirectory->getEntryCount(); $numEntries > 0; $numEntries--) {
  268. $entry = $this->readCentralDirectoryEntry($cdStream);
  269. $entries[$entry->getName()] = $entry;
  270. }
  271. fclose($cdStream);
  272. return $entries;
  273. }
  274. /**
  275. * Read central directory entry.
  276. *
  277. * central file header signature 4 bytes (0x02014b50)
  278. * version made by 2 bytes
  279. * version needed to extract 2 bytes
  280. * general purpose bit flag 2 bytes
  281. * compression method 2 bytes
  282. * last mod file time 2 bytes
  283. * last mod file date 2 bytes
  284. * crc-32 4 bytes
  285. * compressed size 4 bytes
  286. * uncompressed size 4 bytes
  287. * file name length 2 bytes
  288. * extra field length 2 bytes
  289. * file comment length 2 bytes
  290. * disk number start 2 bytes
  291. * internal file attributes 2 bytes
  292. * external file attributes 4 bytes
  293. * relative offset of local header 4 bytes
  294. *
  295. * file name (variable size)
  296. * extra field (variable size)
  297. * file comment (variable size)
  298. *
  299. * @param resource $stream
  300. *
  301. * @throws ZipException
  302. *
  303. * @return ZipEntry
  304. */
  305. public function readCentralDirectoryEntry($stream)
  306. {
  307. if (unpack('V', fread($stream, 4))[1] !== ZipOutputStreamInterface::CENTRAL_FILE_HEADER_SIG) {
  308. throw new ZipException('Corrupt zip file. Cannot read central dir entry.');
  309. }
  310. $data = unpack(
  311. 'vversionMadeBy/vversionNeededToExtract/' .
  312. 'vgeneralPurposeBitFlag/vcompressionMethod/' .
  313. 'VlastModFile/Vcrc/VcompressedSize/' .
  314. 'VuncompressedSize/vfileNameLength/vextraFieldLength/' .
  315. 'vfileCommentLength/vdiskNumberStart/vinternalFileAttributes/' .
  316. 'VexternalFileAttributes/VoffsetLocalHeader',
  317. fread($stream, 42)
  318. );
  319. $createdOS = ($data['versionMadeBy'] & 0xFF00) >> 8;
  320. $softwareVersion = $data['versionMadeBy'] & 0x00FF;
  321. $extractOS = ($data['versionNeededToExtract'] & 0xFF00) >> 8;
  322. $extractVersion = $data['versionNeededToExtract'] & 0x00FF;
  323. $name = fread($stream, $data['fileNameLength']);
  324. $extra = '';
  325. if ($data['extraFieldLength'] > 0) {
  326. $extra = fread($stream, $data['extraFieldLength']);
  327. }
  328. $comment = null;
  329. if ($data['fileCommentLength'] > 0) {
  330. $comment = fread($stream, $data['fileCommentLength']);
  331. }
  332. $entry = new ZipSourceEntry($this);
  333. $entry->setName($name);
  334. $entry->setCreatedOS($createdOS);
  335. $entry->setSoftwareVersion($softwareVersion);
  336. $entry->setVersionNeededToExtract($extractVersion);
  337. $entry->setExtractedOS($extractOS);
  338. $entry->setMethod($data['compressionMethod']);
  339. $entry->setGeneralPurposeBitFlags($data['generalPurposeBitFlag']);
  340. $entry->setDosTime($data['lastModFile']);
  341. $entry->setCrc($data['crc']);
  342. $entry->setCompressedSize($data['compressedSize']);
  343. $entry->setSize($data['uncompressedSize']);
  344. $entry->setInternalAttributes($data['internalFileAttributes']);
  345. $entry->setExternalAttributes($data['externalFileAttributes']);
  346. $entry->setOffset($data['offsetLocalHeader']);
  347. $entry->setComment($comment);
  348. $entry->setExtra($extra);
  349. return $entry;
  350. }
  351. /**
  352. * @param ZipEntry $entry
  353. *
  354. * @throws ZipException
  355. *
  356. * @return string
  357. */
  358. public function readEntryContent(ZipEntry $entry)
  359. {
  360. if ($entry->isDirectory()) {
  361. return null;
  362. }
  363. if (!($entry instanceof ZipSourceEntry)) {
  364. throw new InvalidArgumentException('entry must be ' . ZipSourceEntry::class);
  365. }
  366. $isEncrypted = $entry->isEncrypted();
  367. if ($isEncrypted && $entry->getPassword() === null) {
  368. throw new ZipException('Can not password from entry ' . $entry->getName());
  369. }
  370. $startPos = $pos = $entry->getOffset();
  371. fseek($this->in, $startPos);
  372. // local file header signature 4 bytes (0x04034b50)
  373. if (unpack('V', fread($this->in, 4))[1] !== ZipEntry::LOCAL_FILE_HEADER_SIG) {
  374. throw new ZipException($entry->getName() . ' (expected Local File Header)');
  375. }
  376. fseek($this->in, $pos + ZipEntry::LOCAL_FILE_HEADER_FILE_NAME_LENGTH_POS);
  377. // file name length 2 bytes
  378. // extra field length 2 bytes
  379. $data = unpack('vfileLength/vextraLength', fread($this->in, 4));
  380. $pos += ZipEntry::LOCAL_FILE_HEADER_MIN_LEN + $data['fileLength'] + $data['extraLength'];
  381. if ($entry->getCrc() === ZipEntry::UNKNOWN) {
  382. throw new ZipException(sprintf('Missing crc for entry %s', $entry->getName()));
  383. }
  384. $method = $entry->getMethod();
  385. fseek($this->in, $pos);
  386. // Get raw entry content
  387. $compressedSize = $entry->getCompressedSize();
  388. $content = '';
  389. if ($compressedSize > 0) {
  390. $offset = 0;
  391. while ($offset < $compressedSize) {
  392. $read = min(8192 /* chunk size */, $compressedSize - $offset);
  393. $content .= fread($this->in, $read);
  394. $offset += $read;
  395. }
  396. }
  397. $skipCheckCrc = false;
  398. if ($isEncrypted) {
  399. if ($method === ZipEntry::METHOD_WINZIP_AES) {
  400. // Strong Encryption Specification - WinZip AES
  401. $winZipAesEngine = new WinZipAesEngine($entry);
  402. $content = $winZipAesEngine->decrypt($content);
  403. /**
  404. * @var WinZipAesEntryExtraField $field
  405. */
  406. $field = $entry->getExtraFieldsCollection()->get(WinZipAesEntryExtraField::getHeaderId());
  407. $method = $field->getMethod();
  408. $entry->setEncryptionMethod($field->getEncryptionMethod());
  409. $skipCheckCrc = true;
  410. } else {
  411. // Traditional PKWARE Decryption
  412. $zipCryptoEngine = new TraditionalPkwareEncryptionEngine($entry);
  413. $content = $zipCryptoEngine->decrypt($content);
  414. $entry->setEncryptionMethod(ZipFile::ENCRYPTION_METHOD_TRADITIONAL);
  415. }
  416. if (!$skipCheckCrc) {
  417. // Check CRC32 in the Local File Header or Data Descriptor.
  418. $localCrc = null;
  419. if ($entry->getGeneralPurposeBitFlag(ZipEntry::GPBF_DATA_DESCRIPTOR)) {
  420. // The CRC32 is in the Data Descriptor after the compressed size.
  421. // Note the Data Descriptor's Signature is optional:
  422. // All newer apps should write it (and so does TrueVFS),
  423. // but older apps might not.
  424. fseek($this->in, $pos + $compressedSize);
  425. $localCrc = unpack('V', fread($this->in, 4))[1];
  426. if ($localCrc === ZipEntry::DATA_DESCRIPTOR_SIG) {
  427. $localCrc = unpack('V', fread($this->in, 4))[1];
  428. }
  429. } else {
  430. fseek($this->in, $startPos + 14);
  431. // The CRC32 in the Local File Header.
  432. $localCrc = fread($this->in, 4)[1];
  433. }
  434. if (\PHP_INT_SIZE === 4) {
  435. if (sprintf('%u', $entry->getCrc()) === sprintf('%u', $localCrc)) {
  436. throw new Crc32Exception($entry->getName(), $entry->getCrc(), $localCrc);
  437. }
  438. } elseif ($localCrc !== $entry->getCrc()) {
  439. throw new Crc32Exception($entry->getName(), $entry->getCrc(), $localCrc);
  440. }
  441. }
  442. }
  443. switch ($method) {
  444. case ZipFile::METHOD_STORED:
  445. break;
  446. case ZipFile::METHOD_DEFLATED:
  447. /** @noinspection PhpUsageOfSilenceOperatorInspection */
  448. $content = @gzinflate($content);
  449. break;
  450. case ZipFile::METHOD_BZIP2:
  451. if (!\extension_loaded('bz2')) {
  452. throw new ZipException('Extension bzip2 not install');
  453. }
  454. /** @noinspection PhpComposerExtensionStubsInspection */
  455. $content = bzdecompress($content);
  456. if (\is_int($content)) { // decompress error
  457. $content = false;
  458. }
  459. break;
  460. default:
  461. throw new ZipUnsupportMethodException(
  462. $entry->getName() .
  463. ' (compression method ' . $method . ' is not supported)'
  464. );
  465. }
  466. if ($content === false) {
  467. if ($isEncrypted) {
  468. throw new ZipAuthenticationException(
  469. sprintf(
  470. 'Invalid password for zip entry "%s"',
  471. $entry->getName()
  472. )
  473. );
  474. }
  475. throw new ZipException(
  476. sprintf(
  477. 'Failed to get the contents of the zip entry "%s"',
  478. $entry->getName()
  479. )
  480. );
  481. }
  482. if (!$skipCheckCrc) {
  483. $localCrc = crc32($content);
  484. if (sprintf('%u', $entry->getCrc()) !== sprintf('%u', $localCrc)) {
  485. if ($isEncrypted) {
  486. throw new ZipAuthenticationException(
  487. sprintf(
  488. 'Invalid password for zip entry "%s"',
  489. $entry->getName()
  490. )
  491. );
  492. }
  493. throw new Crc32Exception($entry->getName(), $entry->getCrc(), $localCrc);
  494. }
  495. }
  496. return $content;
  497. }
  498. /**
  499. * @return resource
  500. */
  501. public function getStream()
  502. {
  503. return $this->in;
  504. }
  505. /**
  506. * Copy the input stream of the LOC entry zip and the data into
  507. * the output stream and zip the alignment if necessary.
  508. *
  509. * @param ZipEntry $entry
  510. * @param ZipOutputStreamInterface $out
  511. *
  512. * @throws ZipException
  513. */
  514. public function copyEntry(ZipEntry $entry, ZipOutputStreamInterface $out)
  515. {
  516. $pos = $entry->getOffset();
  517. if ($pos === ZipEntry::UNKNOWN) {
  518. throw new ZipException(sprintf('Missing local header offset for entry %s', $entry->getName()));
  519. }
  520. $nameLength = \strlen($entry->getName());
  521. fseek($this->in, $pos + ZipEntry::LOCAL_FILE_HEADER_MIN_LEN - 2, \SEEK_SET);
  522. $sourceExtraLength = $destExtraLength = unpack('v', fread($this->in, 2))[1];
  523. if ($sourceExtraLength > 0) {
  524. // read Local File Header extra fields
  525. fseek($this->in, $pos + ZipEntry::LOCAL_FILE_HEADER_MIN_LEN + $nameLength, \SEEK_SET);
  526. $extra = '';
  527. $offset = 0;
  528. while ($offset < $sourceExtraLength) {
  529. $read = min(8192 /* chunk size */, $sourceExtraLength - $offset);
  530. $extra .= fread($this->in, $read);
  531. $offset += $read;
  532. }
  533. $extraFieldsCollection = ExtraFieldsFactory::createExtraFieldCollections($extra, $entry);
  534. if (isset($extraFieldsCollection[ApkAlignmentExtraField::getHeaderId()]) && $this->zipModel->isZipAlign()) {
  535. unset($extraFieldsCollection[ApkAlignmentExtraField::getHeaderId()]);
  536. $destExtraLength = \strlen(ExtraFieldsFactory::createSerializedData($extraFieldsCollection));
  537. }
  538. } else {
  539. $extraFieldsCollection = new ExtraFieldsCollection();
  540. }
  541. $dataAlignmentMultiple = $this->zipModel->getZipAlign();
  542. $copyInToOutLength = $entry->getCompressedSize();
  543. fseek($this->in, $pos, \SEEK_SET);
  544. if (
  545. $this->zipModel->isZipAlign() &&
  546. !$entry->isEncrypted() &&
  547. $entry->getMethod() === ZipFile::METHOD_STORED
  548. ) {
  549. if (StringUtil::endsWith($entry->getName(), '.so')) {
  550. $dataAlignmentMultiple = ApkAlignmentExtraField::ANDROID_COMMON_PAGE_ALIGNMENT_BYTES;
  551. }
  552. $dataMinStartOffset =
  553. ftell($out->getStream()) +
  554. ZipEntry::LOCAL_FILE_HEADER_MIN_LEN +
  555. $destExtraLength +
  556. $nameLength +
  557. ApkAlignmentExtraField::ALIGNMENT_ZIP_EXTRA_MIN_SIZE_BYTES;
  558. $padding =
  559. ($dataAlignmentMultiple - ($dataMinStartOffset % $dataAlignmentMultiple))
  560. % $dataAlignmentMultiple;
  561. $alignExtra = new ApkAlignmentExtraField();
  562. $alignExtra->setMultiple($dataAlignmentMultiple);
  563. $alignExtra->setPadding($padding);
  564. $extraFieldsCollection->add($alignExtra);
  565. $extra = ExtraFieldsFactory::createSerializedData($extraFieldsCollection);
  566. // copy Local File Header without extra field length
  567. // from input stream to output stream
  568. stream_copy_to_stream($this->in, $out->getStream(), ZipEntry::LOCAL_FILE_HEADER_MIN_LEN - 2);
  569. // write new extra field length (2 bytes) to output stream
  570. fwrite($out->getStream(), pack('v', \strlen($extra)));
  571. // skip 2 bytes to input stream
  572. fseek($this->in, 2, \SEEK_CUR);
  573. // copy name from input stream to output stream
  574. stream_copy_to_stream($this->in, $out->getStream(), $nameLength);
  575. // write extra field to output stream
  576. fwrite($out->getStream(), $extra);
  577. // skip source extraLength from input stream
  578. fseek($this->in, $sourceExtraLength, \SEEK_CUR);
  579. } else {
  580. $copyInToOutLength += ZipEntry::LOCAL_FILE_HEADER_MIN_LEN + $sourceExtraLength + $nameLength;
  581. }
  582. if ($entry->getGeneralPurposeBitFlag(ZipEntry::GPBF_DATA_DESCRIPTOR)) {
  583. // crc-32 4 bytes
  584. // compressed size 4 bytes
  585. // uncompressed size 4 bytes
  586. $copyInToOutLength += 12;
  587. if ($entry->isZip64ExtensionsRequired()) {
  588. // compressed size +4 bytes
  589. // uncompressed size +4 bytes
  590. $copyInToOutLength += 8;
  591. }
  592. }
  593. // copy loc, data, data descriptor from input to output stream
  594. stream_copy_to_stream($this->in, $out->getStream(), $copyInToOutLength);
  595. }
  596. /**
  597. * @param ZipEntry $entry
  598. * @param ZipOutputStreamInterface $out
  599. */
  600. public function copyEntryData(ZipEntry $entry, ZipOutputStreamInterface $out)
  601. {
  602. $offset = $entry->getOffset();
  603. $nameLength = \strlen($entry->getName());
  604. fseek($this->in, $offset + ZipEntry::LOCAL_FILE_HEADER_MIN_LEN - 2, \SEEK_SET);
  605. $extraLength = unpack('v', fread($this->in, 2))[1];
  606. fseek($this->in, $offset + ZipEntry::LOCAL_FILE_HEADER_MIN_LEN + $nameLength + $extraLength, \SEEK_SET);
  607. // copy raw data from input stream to output stream
  608. stream_copy_to_stream($this->in, $out->getStream(), $entry->getCompressedSize());
  609. }
  610. public function __destruct()
  611. {
  612. $this->close();
  613. }
  614. public function close()
  615. {
  616. if ($this->in !== null) {
  617. fclose($this->in);
  618. $this->in = null;
  619. }
  620. }
  621. }