ZipFile.php 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005
  1. <?php
  2. /** @noinspection AdditionOperationOnArraysInspection */
  3. /** @noinspection PhpUsageOfSilenceOperatorInspection */
  4. namespace PhpZip;
  5. use PhpZip\Constants\UnixStat;
  6. use PhpZip\Constants\ZipCompressionLevel;
  7. use PhpZip\Constants\ZipCompressionMethod;
  8. use PhpZip\Constants\ZipEncryptionMethod;
  9. use PhpZip\Constants\ZipOptions;
  10. use PhpZip\Constants\ZipPlatform;
  11. use PhpZip\Exception\InvalidArgumentException;
  12. use PhpZip\Exception\ZipEntryNotFoundException;
  13. use PhpZip\Exception\ZipException;
  14. use PhpZip\IO\Stream\ResponseStream;
  15. use PhpZip\IO\Stream\ZipEntryStreamWrapper;
  16. use PhpZip\IO\ZipReader;
  17. use PhpZip\IO\ZipWriter;
  18. use PhpZip\Model\Data\ZipFileData;
  19. use PhpZip\Model\Data\ZipNewData;
  20. use PhpZip\Model\ImmutableZipContainer;
  21. use PhpZip\Model\ZipContainer;
  22. use PhpZip\Model\ZipEntry;
  23. use PhpZip\Model\ZipEntryMatcher;
  24. use PhpZip\Model\ZipInfo;
  25. use PhpZip\Util\FilesUtil;
  26. use PhpZip\Util\StringUtil;
  27. use Psr\Http\Message\ResponseInterface;
  28. use Symfony\Component\Finder\Finder;
  29. use Symfony\Component\Finder\SplFileInfo as SymfonySplFileInfo;
  30. /**
  31. * Create, open .ZIP files, modify, get info and extract files.
  32. *
  33. * Implemented support traditional PKWARE encryption and WinZip AES encryption.
  34. * Implemented support ZIP64.
  35. * Support ZipAlign functional.
  36. *
  37. * @see https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT .ZIP File Format Specification
  38. *
  39. * @author Ne-Lexa alexey@nelexa.ru
  40. * @license MIT
  41. */
  42. class ZipFile implements ZipFileInterface
  43. {
  44. /** @var array default mime types */
  45. private static $defaultMimeTypes = [
  46. 'zip' => 'application/zip',
  47. 'apk' => 'application/vnd.android.package-archive',
  48. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  49. 'epub' => 'application/epub+zip',
  50. 'jar' => 'application/java-archive',
  51. 'odt' => 'application/vnd.oasis.opendocument.text',
  52. 'pptx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  53. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  54. 'xpi' => 'application/x-xpinstall',
  55. ];
  56. /** @var ZipContainer */
  57. protected $zipContainer;
  58. /** @var ZipReader|null */
  59. private $reader;
  60. /**
  61. * ZipFile constructor.
  62. */
  63. public function __construct()
  64. {
  65. $this->zipContainer = $this->createZipContainer(null);
  66. }
  67. /**
  68. * @param resource $inputStream
  69. * @param array $options
  70. *
  71. * @return ZipReader
  72. */
  73. protected function createZipReader($inputStream, array $options = [])
  74. {
  75. return new ZipReader($inputStream, $options);
  76. }
  77. /**
  78. * @return ZipWriter
  79. */
  80. protected function createZipWriter()
  81. {
  82. return new ZipWriter($this->zipContainer);
  83. }
  84. /**
  85. * @param ImmutableZipContainer|null $sourceContainer
  86. *
  87. * @return ZipContainer
  88. */
  89. protected function createZipContainer(ImmutableZipContainer $sourceContainer = null)
  90. {
  91. return new ZipContainer($sourceContainer);
  92. }
  93. /**
  94. * Open zip archive from file.
  95. *
  96. * @param string $filename
  97. * @param array $options
  98. *
  99. * @throws ZipException if can't open file
  100. *
  101. * @return ZipFile
  102. */
  103. public function openFile($filename, array $options = [])
  104. {
  105. if (!file_exists($filename)) {
  106. throw new ZipException("File {$filename} does not exist.");
  107. }
  108. if (!($handle = @fopen($filename, 'rb'))) {
  109. throw new ZipException("File {$filename} can't open.");
  110. }
  111. return $this->openFromStream($handle, $options);
  112. }
  113. /**
  114. * Open zip archive from raw string data.
  115. *
  116. * @param string $data
  117. * @param array $options
  118. *
  119. * @throws ZipException if can't open temp stream
  120. *
  121. * @return ZipFile
  122. */
  123. public function openFromString($data, array $options = [])
  124. {
  125. if ($data === null || $data === '') {
  126. throw new InvalidArgumentException('Empty string passed');
  127. }
  128. if (!($handle = fopen('php://temp', 'r+b'))) {
  129. // @codeCoverageIgnoreStart
  130. throw new ZipException("Can't open temp stream.");
  131. // @codeCoverageIgnoreEnd
  132. }
  133. fwrite($handle, $data);
  134. rewind($handle);
  135. return $this->openFromStream($handle, $options);
  136. }
  137. /**
  138. * Open zip archive from stream resource.
  139. *
  140. * @param resource $handle
  141. * @param array $options
  142. *
  143. * @throws ZipException
  144. *
  145. * @return ZipFile
  146. */
  147. public function openFromStream($handle, array $options = [])
  148. {
  149. $this->reader = $this->createZipReader($handle, $options);
  150. $this->zipContainer = $this->createZipContainer($this->reader->read());
  151. return $this;
  152. }
  153. /**
  154. * @return string[] returns the list files
  155. */
  156. public function getListFiles()
  157. {
  158. // strval is needed to cast entry names to string type
  159. return array_map('strval', array_keys($this->zipContainer->getEntries()));
  160. }
  161. /**
  162. * @return int returns the number of entries in this ZIP file
  163. */
  164. public function count()
  165. {
  166. return $this->zipContainer->count();
  167. }
  168. /**
  169. * Returns the file comment.
  170. *
  171. * @return string|null the file comment
  172. */
  173. public function getArchiveComment()
  174. {
  175. return $this->zipContainer->getArchiveComment();
  176. }
  177. /**
  178. * Set archive comment.
  179. *
  180. * @param string|null $comment
  181. *
  182. * @return ZipFile
  183. */
  184. public function setArchiveComment($comment = null)
  185. {
  186. $this->zipContainer->setArchiveComment($comment);
  187. return $this;
  188. }
  189. /**
  190. * Checks if there is an entry in the archive.
  191. *
  192. * @param string $entryName
  193. *
  194. * @return bool
  195. */
  196. public function hasEntry($entryName)
  197. {
  198. return $this->zipContainer->hasEntry($entryName);
  199. }
  200. /**
  201. * Returns ZipEntry object.
  202. *
  203. * @param string $entryName
  204. *
  205. * @throws ZipEntryNotFoundException
  206. *
  207. * @return ZipEntry
  208. */
  209. public function getEntry($entryName)
  210. {
  211. return $this->zipContainer->getEntry($entryName);
  212. }
  213. /**
  214. * Checks that the entry in the archive is a directory.
  215. * Returns true if and only if this ZIP entry represents a directory entry
  216. * (i.e. end with '/').
  217. *
  218. * @param string $entryName
  219. *
  220. * @throws ZipEntryNotFoundException
  221. *
  222. * @return bool
  223. */
  224. public function isDirectory($entryName)
  225. {
  226. return $this->getEntry($entryName)->isDirectory();
  227. }
  228. /**
  229. * Returns entry comment.
  230. *
  231. * @param string $entryName
  232. *
  233. * @throws ZipException
  234. * @throws ZipEntryNotFoundException
  235. *
  236. * @return string
  237. */
  238. public function getEntryComment($entryName)
  239. {
  240. return $this->getEntry($entryName)->getComment();
  241. }
  242. /**
  243. * Set entry comment.
  244. *
  245. * @param string $entryName
  246. * @param string|null $comment
  247. *
  248. * @throws ZipEntryNotFoundException
  249. * @throws ZipException
  250. *
  251. * @return ZipFile
  252. */
  253. public function setEntryComment($entryName, $comment = null)
  254. {
  255. $this->getEntry($entryName)->setComment($comment);
  256. return $this;
  257. }
  258. /**
  259. * Returns the entry contents.
  260. *
  261. * @param string $entryName
  262. *
  263. * @throws ZipEntryNotFoundException
  264. * @throws ZipException
  265. *
  266. * @return string
  267. */
  268. public function getEntryContents($entryName)
  269. {
  270. $zipData = $this->zipContainer->getEntry($entryName)->getData();
  271. if ($zipData === null) {
  272. throw new ZipException(sprintf('No data for zip entry %s', $entryName));
  273. }
  274. return $zipData->getDataAsString();
  275. }
  276. /**
  277. * @param string $entryName
  278. *
  279. * @throws ZipEntryNotFoundException
  280. * @throws ZipException
  281. *
  282. * @return resource
  283. */
  284. public function getEntryStream($entryName)
  285. {
  286. $resource = ZipEntryStreamWrapper::wrap($this->zipContainer->getEntry($entryName));
  287. rewind($resource);
  288. return $resource;
  289. }
  290. /**
  291. * Get info by entry.
  292. *
  293. * @param string|ZipEntry $entryName
  294. *
  295. * @throws ZipException
  296. * @throws ZipEntryNotFoundException
  297. *
  298. * @return ZipInfo
  299. */
  300. public function getEntryInfo($entryName)
  301. {
  302. return new ZipInfo($this->zipContainer->getEntry($entryName));
  303. }
  304. /**
  305. * Get info by all entries.
  306. *
  307. * @return ZipInfo[]
  308. */
  309. public function getAllInfo()
  310. {
  311. $infoMap = [];
  312. foreach ($this->zipContainer->getEntries() as $name => $entry) {
  313. $infoMap[$name] = new ZipInfo($entry);
  314. }
  315. return $infoMap;
  316. }
  317. /**
  318. * @return ZipEntryMatcher
  319. */
  320. public function matcher()
  321. {
  322. return $this->zipContainer->matcher();
  323. }
  324. /**
  325. * Returns an array of zip records (ex. for modify time).
  326. *
  327. * @return ZipEntry[] array of raw zip entries
  328. */
  329. public function getEntries()
  330. {
  331. return $this->zipContainer->getEntries();
  332. }
  333. /**
  334. * Extract the archive contents (unzip).
  335. *
  336. * Extract the complete archive or the given files to the specified destination.
  337. *
  338. * @param string $destDir location where to extract the files
  339. * @param array|string|null $entries entries to extract
  340. * @param array $options extract options
  341. * @param array $extractedEntries if the extractedEntries argument
  342. * is present, then the specified
  343. * array will be filled with
  344. * information about the
  345. * extracted entries
  346. *
  347. * @throws ZipException
  348. *
  349. * @return ZipFile
  350. */
  351. public function extractTo($destDir, $entries = null, array $options = [], &$extractedEntries = [])
  352. {
  353. if (!file_exists($destDir)) {
  354. throw new ZipException(sprintf('Destination %s not found', $destDir));
  355. }
  356. if (!is_dir($destDir)) {
  357. throw new ZipException('Destination is not directory');
  358. }
  359. if (!is_writable($destDir)) {
  360. throw new ZipException('Destination is not writable directory');
  361. }
  362. if ($extractedEntries === null) {
  363. $extractedEntries = [];
  364. }
  365. $defaultOptions = [
  366. ZipOptions::EXTRACT_SYMLINKS => false,
  367. ];
  368. $options += $defaultOptions;
  369. $zipEntries = $this->zipContainer->getEntries();
  370. if (!empty($entries)) {
  371. if (\is_string($entries)) {
  372. $entries = (array) $entries;
  373. }
  374. if (\is_array($entries)) {
  375. $entries = array_unique($entries);
  376. $zipEntries = array_intersect_key($zipEntries, array_flip($entries));
  377. }
  378. }
  379. if (empty($zipEntries)) {
  380. return $this;
  381. }
  382. /** @var int[] $lastModDirs */
  383. $lastModDirs = [];
  384. krsort($zipEntries, \SORT_NATURAL);
  385. $symlinks = [];
  386. $destDir = rtrim($destDir, '/\\');
  387. foreach ($zipEntries as $entryName => $entry) {
  388. $unixMode = $entry->getUnixMode();
  389. $entryName = FilesUtil::normalizeZipPath($entryName);
  390. $file = $destDir . \DIRECTORY_SEPARATOR . $entryName;
  391. if (\DIRECTORY_SEPARATOR === '\\') {
  392. $file = str_replace('/', '\\', $file);
  393. }
  394. $extractedEntries[$file] = $entry;
  395. $modifyTimestamp = $entry->getMTime()->getTimestamp();
  396. $atime = $entry->getATime();
  397. $accessTimestamp = $atime === null ? null : $atime->getTimestamp();
  398. $dir = $entry->isDirectory() ? $file : \dirname($file);
  399. if (!is_dir($dir)) {
  400. $dirMode = $entry->isDirectory() ? $unixMode : 0755;
  401. if ($dirMode === 0) {
  402. $dirMode = 0755;
  403. }
  404. if (!mkdir($dir, $dirMode, true) && !is_dir($dir)) {
  405. // @codeCoverageIgnoreStart
  406. throw new \RuntimeException(sprintf('Directory "%s" was not created', $dir));
  407. // @codeCoverageIgnoreEnd
  408. }
  409. chmod($dir, $dirMode);
  410. }
  411. $parts = explode('/', rtrim($entryName, '/'));
  412. $path = $destDir . \DIRECTORY_SEPARATOR;
  413. foreach ($parts as $part) {
  414. if (!isset($lastModDirs[$path]) || $lastModDirs[$path] > $modifyTimestamp) {
  415. $lastModDirs[$path] = $modifyTimestamp;
  416. }
  417. $path .= $part . \DIRECTORY_SEPARATOR;
  418. }
  419. if ($entry->isDirectory()) {
  420. $lastModDirs[$dir] = $modifyTimestamp;
  421. continue;
  422. }
  423. $zipData = $entry->getData();
  424. if ($zipData === null) {
  425. continue;
  426. }
  427. if ($entry->isUnixSymlink()) {
  428. $symlinks[$file] = $zipData->getDataAsString();
  429. continue;
  430. }
  431. /** @noinspection PhpUsageOfSilenceOperatorInspection */
  432. if (!($handle = @fopen($file, 'w+b'))) {
  433. // @codeCoverageIgnoreStart
  434. throw new ZipException(
  435. sprintf(
  436. 'Cannot extract zip entry %s. File %s cannot open for write.',
  437. $entry->getName(),
  438. $file
  439. )
  440. );
  441. // @codeCoverageIgnoreEnd
  442. }
  443. try {
  444. $zipData->copyDataToStream($handle);
  445. } catch (ZipException $e) {
  446. unlink($file);
  447. throw $e;
  448. }
  449. fclose($handle);
  450. if ($unixMode === 0) {
  451. $unixMode = 0644;
  452. }
  453. chmod($file, $unixMode);
  454. if ($accessTimestamp !== null) {
  455. /** @noinspection PotentialMalwareInspection */
  456. touch($file, $modifyTimestamp, $accessTimestamp);
  457. } else {
  458. touch($file, $modifyTimestamp);
  459. }
  460. }
  461. $allowSymlink = (bool) $options[ZipOptions::EXTRACT_SYMLINKS];
  462. foreach ($symlinks as $linkPath => $target) {
  463. if (!FilesUtil::symlink($target, $linkPath, $allowSymlink)) {
  464. unset($extractedEntries[$linkPath]);
  465. }
  466. }
  467. krsort($lastModDirs, \SORT_NATURAL);
  468. foreach ($lastModDirs as $dir => $lastMod) {
  469. touch($dir, $lastMod);
  470. }
  471. ksort($extractedEntries);
  472. return $this;
  473. }
  474. /**
  475. * Add entry from the string.
  476. *
  477. * @param string $entryName zip entry name
  478. * @param string $contents string contents
  479. * @param int|null $compressionMethod Compression method.
  480. * Use {@see ZipCompressionMethod::STORED},
  481. * {@see ZipCompressionMethod::DEFLATED} or
  482. * {@see ZipCompressionMethod::BZIP2}.
  483. * If null, then auto choosing method.
  484. *
  485. * @throws ZipException
  486. *
  487. * @return ZipFile
  488. */
  489. public function addFromString($entryName, $contents, $compressionMethod = null)
  490. {
  491. if ($entryName === null) {
  492. throw new InvalidArgumentException('Entry name is null');
  493. }
  494. if ($contents === null) {
  495. throw new InvalidArgumentException('Contents is null');
  496. }
  497. $entryName = ltrim((string) $entryName, '\\/');
  498. if ($entryName === '') {
  499. throw new InvalidArgumentException('Empty entry name');
  500. }
  501. $contents = (string) $contents;
  502. $length = \strlen($contents);
  503. if ($compressionMethod === null || $compressionMethod === ZipEntry::UNKNOWN) {
  504. if ($length < 512) {
  505. $compressionMethod = ZipCompressionMethod::STORED;
  506. } else {
  507. $mimeType = FilesUtil::getMimeTypeFromString($contents);
  508. $compressionMethod = FilesUtil::isBadCompressionMimeType($mimeType) ?
  509. ZipCompressionMethod::STORED :
  510. ZipCompressionMethod::DEFLATED;
  511. }
  512. }
  513. $zipEntry = new ZipEntry($entryName);
  514. $zipEntry->setData(new ZipNewData($zipEntry, $contents));
  515. $zipEntry->setUncompressedSize($length);
  516. $zipEntry->setCompressionMethod($compressionMethod);
  517. $zipEntry->setCreatedOS(ZipPlatform::OS_UNIX);
  518. $zipEntry->setExtractedOS(ZipPlatform::OS_UNIX);
  519. $zipEntry->setUnixMode(0100644);
  520. $zipEntry->setTime(time());
  521. $this->addZipEntry($zipEntry);
  522. return $this;
  523. }
  524. /**
  525. * @param Finder $finder
  526. * @param array $options
  527. *
  528. * @throws ZipException
  529. *
  530. * @return ZipEntry[]
  531. */
  532. public function addFromFinder(Finder $finder, array $options = [])
  533. {
  534. $defaultOptions = [
  535. ZipOptions::STORE_ONLY_FILES => false,
  536. ZipOptions::COMPRESSION_METHOD => null,
  537. ZipOptions::MODIFIED_TIME => null,
  538. ];
  539. $options += $defaultOptions;
  540. if ($options[ZipOptions::STORE_ONLY_FILES]) {
  541. $finder->files();
  542. }
  543. $entries = [];
  544. foreach ($finder as $fileInfo) {
  545. if ($fileInfo->isReadable()) {
  546. $entry = $this->addSplFile($fileInfo, null, $options);
  547. $entries[$entry->getName()] = $entry;
  548. }
  549. }
  550. return $entries;
  551. }
  552. /**
  553. * @param \SplFileInfo $file
  554. * @param string|null $entryName
  555. * @param array $options
  556. *
  557. * @throws ZipException
  558. *
  559. * @return ZipEntry
  560. */
  561. public function addSplFile(\SplFileInfo $file, $entryName = null, array $options = [])
  562. {
  563. if ($file instanceof \DirectoryIterator) {
  564. throw new InvalidArgumentException('File should not be \DirectoryIterator.');
  565. }
  566. $defaultOptions = [
  567. ZipOptions::COMPRESSION_METHOD => null,
  568. ZipOptions::MODIFIED_TIME => null,
  569. ];
  570. $options += $defaultOptions;
  571. if (!$file->isReadable()) {
  572. throw new InvalidArgumentException(sprintf('File %s is not readable', $file->getPathname()));
  573. }
  574. if ($entryName === null) {
  575. if ($file instanceof SymfonySplFileInfo) {
  576. $entryName = $file->getRelativePathname();
  577. } else {
  578. $entryName = $file->getBasename();
  579. }
  580. }
  581. $entryName = ltrim((string) $entryName, '\\/');
  582. if ($entryName === '') {
  583. throw new InvalidArgumentException('Empty entry name');
  584. }
  585. $entryName = $file->isDir() ? rtrim($entryName, '/\\') . '/' : $entryName;
  586. $zipEntry = new ZipEntry($entryName);
  587. $zipEntry->setCreatedOS(ZipPlatform::OS_UNIX);
  588. $zipEntry->setExtractedOS(ZipPlatform::OS_UNIX);
  589. $zipData = null;
  590. $filePerms = $file->getPerms();
  591. if ($file->isLink()) {
  592. $linkTarget = $file->getLinkTarget();
  593. $lengthLinkTarget = \strlen($linkTarget);
  594. $zipEntry->setCompressionMethod(ZipCompressionMethod::STORED);
  595. $zipEntry->setUncompressedSize($lengthLinkTarget);
  596. $zipEntry->setCompressedSize($lengthLinkTarget);
  597. $zipEntry->setCrc(crc32($linkTarget));
  598. $filePerms |= UnixStat::UNX_IFLNK;
  599. $zipData = new ZipNewData($zipEntry, $linkTarget);
  600. } elseif ($file->isFile()) {
  601. if (isset($options[ZipOptions::COMPRESSION_METHOD])) {
  602. $compressionMethod = $options[ZipOptions::COMPRESSION_METHOD];
  603. } elseif ($file->getSize() < 512) {
  604. $compressionMethod = ZipCompressionMethod::STORED;
  605. } else {
  606. $compressionMethod = FilesUtil::isBadCompressionFile($file->getPathname()) ?
  607. ZipCompressionMethod::STORED :
  608. ZipCompressionMethod::DEFLATED;
  609. }
  610. $zipEntry->setCompressionMethod($compressionMethod);
  611. $zipData = new ZipFileData($zipEntry, $file);
  612. } elseif ($file->isDir()) {
  613. $zipEntry->setCompressionMethod(ZipCompressionMethod::STORED);
  614. $zipEntry->setUncompressedSize(0);
  615. $zipEntry->setCompressedSize(0);
  616. $zipEntry->setCrc(0);
  617. }
  618. $zipEntry->setUnixMode($filePerms);
  619. $timestamp = null;
  620. if (isset($options[ZipOptions::MODIFIED_TIME])) {
  621. $mtime = $options[ZipOptions::MODIFIED_TIME];
  622. if ($mtime instanceof \DateTimeInterface) {
  623. $timestamp = $mtime->getTimestamp();
  624. } elseif (is_numeric($mtime)) {
  625. $timestamp = (int) $mtime;
  626. } elseif (\is_string($mtime)) {
  627. $timestamp = strtotime($mtime);
  628. if ($timestamp === false) {
  629. $timestamp = null;
  630. }
  631. }
  632. }
  633. if ($timestamp === null) {
  634. $timestamp = $file->getMTime();
  635. }
  636. $zipEntry->setTime($timestamp);
  637. $zipEntry->setData($zipData);
  638. $this->addZipEntry($zipEntry);
  639. return $zipEntry;
  640. }
  641. /**
  642. * @param ZipEntry $zipEntry
  643. */
  644. protected function addZipEntry(ZipEntry $zipEntry)
  645. {
  646. $this->zipContainer->addEntry($zipEntry);
  647. }
  648. /**
  649. * Add entry from the file.
  650. *
  651. * @param string $filename destination file
  652. * @param string|null $entryName zip Entry name
  653. * @param int|null $compressionMethod Compression method.
  654. * Use {@see ZipCompressionMethod::STORED},
  655. * {@see ZipCompressionMethod::DEFLATED} or
  656. * {@see ZipCompressionMethod::BZIP2}.
  657. * If null, then auto choosing method.
  658. *
  659. * @throws ZipException
  660. *
  661. * @return ZipFile
  662. */
  663. public function addFile($filename, $entryName = null, $compressionMethod = null)
  664. {
  665. if ($filename === null) {
  666. throw new InvalidArgumentException('Filename is null');
  667. }
  668. $this->addSplFile(
  669. new \SplFileInfo($filename),
  670. $entryName,
  671. [
  672. ZipOptions::COMPRESSION_METHOD => $compressionMethod,
  673. ]
  674. );
  675. return $this;
  676. }
  677. /**
  678. * Add entry from the stream.
  679. *
  680. * @param resource $stream stream resource
  681. * @param string $entryName zip Entry name
  682. * @param int|null $compressionMethod Compression method.
  683. * Use {@see ZipCompressionMethod::STORED},
  684. * {@see ZipCompressionMethod::DEFLATED} or
  685. * {@see ZipCompressionMethod::BZIP2}.
  686. * If null, then auto choosing method.
  687. *
  688. * @throws ZipException
  689. *
  690. * @return ZipFile
  691. */
  692. public function addFromStream($stream, $entryName, $compressionMethod = null)
  693. {
  694. if (!\is_resource($stream)) {
  695. throw new InvalidArgumentException('Stream is not resource');
  696. }
  697. if ($entryName === null) {
  698. throw new InvalidArgumentException('Entry name is null');
  699. }
  700. $entryName = ltrim((string) $entryName, '\\/');
  701. if ($entryName === '') {
  702. throw new InvalidArgumentException('Empty entry name');
  703. }
  704. $fstat = fstat($stream);
  705. $zipEntry = new ZipEntry($entryName);
  706. if ($fstat !== false) {
  707. $unixMode = $fstat['mode'];
  708. $length = $fstat['size'];
  709. if ($compressionMethod === null || $compressionMethod === ZipEntry::UNKNOWN) {
  710. if ($length < 512) {
  711. $compressionMethod = ZipCompressionMethod::STORED;
  712. } else {
  713. rewind($stream);
  714. $bufferContents = stream_get_contents($stream, min(1024, $length));
  715. rewind($stream);
  716. $mimeType = FilesUtil::getMimeTypeFromString($bufferContents);
  717. $compressionMethod = FilesUtil::isBadCompressionMimeType($mimeType) ?
  718. ZipCompressionMethod::STORED :
  719. ZipCompressionMethod::DEFLATED;
  720. }
  721. $zipEntry->setUncompressedSize($length);
  722. }
  723. } else {
  724. $unixMode = 0100644;
  725. if ($compressionMethod === null || $compressionMethod === ZipEntry::UNKNOWN) {
  726. $compressionMethod = ZipCompressionMethod::DEFLATED;
  727. }
  728. }
  729. $zipEntry->setCreatedOS(ZipPlatform::OS_UNIX);
  730. $zipEntry->setExtractedOS(ZipPlatform::OS_UNIX);
  731. $zipEntry->setUnixMode($unixMode);
  732. $zipEntry->setCompressionMethod($compressionMethod);
  733. $zipEntry->setTime(time());
  734. $zipEntry->setData(new ZipNewData($zipEntry, $stream));
  735. $this->addZipEntry($zipEntry);
  736. return $this;
  737. }
  738. /**
  739. * Add an empty directory in the zip archive.
  740. *
  741. * @param string $dirName
  742. *
  743. * @throws ZipException
  744. *
  745. * @return ZipFile
  746. */
  747. public function addEmptyDir($dirName)
  748. {
  749. if ($dirName === null) {
  750. throw new InvalidArgumentException('Dir name is null');
  751. }
  752. $dirName = ltrim((string) $dirName, '\\/');
  753. if ($dirName === '') {
  754. throw new InvalidArgumentException('Empty dir name');
  755. }
  756. $dirName = rtrim($dirName, '\\/') . '/';
  757. $zipEntry = new ZipEntry($dirName);
  758. $zipEntry->setCompressionMethod(ZipCompressionMethod::STORED);
  759. $zipEntry->setUncompressedSize(0);
  760. $zipEntry->setCompressedSize(0);
  761. $zipEntry->setCrc(0);
  762. $zipEntry->setCreatedOS(ZipPlatform::OS_UNIX);
  763. $zipEntry->setExtractedOS(ZipPlatform::OS_UNIX);
  764. $zipEntry->setUnixMode(040755);
  765. $zipEntry->setTime(time());
  766. $this->addZipEntry($zipEntry);
  767. return $this;
  768. }
  769. /**
  770. * Add directory not recursively to the zip archive.
  771. *
  772. * @param string $inputDir Input directory
  773. * @param string $localPath add files to this directory, or the root
  774. * @param int|null $compressionMethod Compression method.
  775. *
  776. * Use {@see ZipCompressionMethod::STORED}, {@see
  777. * ZipCompressionMethod::DEFLATED} or
  778. * {@see ZipCompressionMethod::BZIP2}. If null, then auto choosing method.
  779. *
  780. * @throws ZipException
  781. *
  782. * @return ZipFile
  783. */
  784. public function addDir($inputDir, $localPath = '/', $compressionMethod = null)
  785. {
  786. if ($inputDir === null) {
  787. throw new InvalidArgumentException('Input dir is null');
  788. }
  789. $inputDir = (string) $inputDir;
  790. if ($inputDir === '') {
  791. throw new InvalidArgumentException('The input directory is not specified');
  792. }
  793. if (!is_dir($inputDir)) {
  794. throw new InvalidArgumentException(sprintf('The "%s" directory does not exist.', $inputDir));
  795. }
  796. $inputDir = rtrim($inputDir, '/\\') . \DIRECTORY_SEPARATOR;
  797. $directoryIterator = new \DirectoryIterator($inputDir);
  798. return $this->addFilesFromIterator($directoryIterator, $localPath, $compressionMethod);
  799. }
  800. /**
  801. * Add recursive directory to the zip archive.
  802. *
  803. * @param string $inputDir Input directory
  804. * @param string $localPath add files to this directory, or the root
  805. * @param int|null $compressionMethod Compression method.
  806. * Use {@see ZipCompressionMethod::STORED}, {@see
  807. * ZipCompressionMethod::DEFLATED} or
  808. * {@see ZipCompressionMethod::BZIP2}. If null, then auto choosing method.
  809. *
  810. * @throws ZipException
  811. *
  812. * @return ZipFile
  813. *
  814. * @see ZipCompressionMethod::STORED
  815. * @see ZipCompressionMethod::DEFLATED
  816. * @see ZipCompressionMethod::BZIP2
  817. */
  818. public function addDirRecursive($inputDir, $localPath = '/', $compressionMethod = null)
  819. {
  820. if ($inputDir === null) {
  821. throw new InvalidArgumentException('Input dir is null');
  822. }
  823. $inputDir = (string) $inputDir;
  824. if ($inputDir === '') {
  825. throw new InvalidArgumentException('The input directory is not specified');
  826. }
  827. if (!is_dir($inputDir)) {
  828. throw new InvalidArgumentException(sprintf('The "%s" directory does not exist.', $inputDir));
  829. }
  830. $inputDir = rtrim($inputDir, '/\\') . \DIRECTORY_SEPARATOR;
  831. $directoryIterator = new \RecursiveDirectoryIterator($inputDir);
  832. return $this->addFilesFromIterator($directoryIterator, $localPath, $compressionMethod);
  833. }
  834. /**
  835. * Add directories from directory iterator.
  836. *
  837. * @param \Iterator $iterator directory iterator
  838. * @param string $localPath add files to this directory, or the root
  839. * @param int|null $compressionMethod Compression method.
  840. * Use {@see ZipCompressionMethod::STORED}, {@see
  841. * ZipCompressionMethod::DEFLATED} or
  842. * {@see ZipCompressionMethod::BZIP2}. If null, then auto choosing method.
  843. *
  844. * @throws ZipException
  845. *
  846. * @return ZipFile
  847. *
  848. * @see ZipCompressionMethod::STORED
  849. * @see ZipCompressionMethod::DEFLATED
  850. * @see ZipCompressionMethod::BZIP2
  851. */
  852. public function addFilesFromIterator(
  853. \Iterator $iterator,
  854. $localPath = '/',
  855. $compressionMethod = null
  856. ) {
  857. $localPath = (string) $localPath;
  858. if ($localPath !== '') {
  859. $localPath = trim($localPath, '\\/');
  860. } else {
  861. $localPath = '';
  862. }
  863. $iterator = $iterator instanceof \RecursiveIterator ?
  864. new \RecursiveIteratorIterator($iterator) :
  865. new \IteratorIterator($iterator);
  866. /**
  867. * @var string[] $files
  868. * @var string $path
  869. */
  870. $files = [];
  871. foreach ($iterator as $file) {
  872. if ($file instanceof \SplFileInfo) {
  873. if ($file->getBasename() === '..') {
  874. continue;
  875. }
  876. if ($file->getBasename() === '.') {
  877. $files[] = \dirname($file->getPathname());
  878. } else {
  879. $files[] = $file->getPathname();
  880. }
  881. }
  882. }
  883. if (empty($files)) {
  884. return $this;
  885. }
  886. natcasesort($files);
  887. $path = array_shift($files);
  888. $this->doAddFiles($path, $files, $localPath, $compressionMethod);
  889. return $this;
  890. }
  891. /**
  892. * Add files from glob pattern.
  893. *
  894. * @param string $inputDir Input directory
  895. * @param string $globPattern glob pattern
  896. * @param string $localPath add files to this directory, or the root
  897. * @param int|null $compressionMethod Compression method.
  898. * Use {@see ZipCompressionMethod::STORED},
  899. * {@see ZipCompressionMethod::DEFLATED} or
  900. * {@see ZipCompressionMethod::BZIP2}. If null, then auto choosing method.
  901. *
  902. * @throws ZipException
  903. *
  904. * @return ZipFile
  905. * @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax
  906. */
  907. public function addFilesFromGlob($inputDir, $globPattern, $localPath = '/', $compressionMethod = null)
  908. {
  909. return $this->addGlob($inputDir, $globPattern, $localPath, false, $compressionMethod);
  910. }
  911. /**
  912. * Add files from glob pattern.
  913. *
  914. * @param string $inputDir Input directory
  915. * @param string $globPattern glob pattern
  916. * @param string $localPath add files to this directory, or the root
  917. * @param bool $recursive recursive search
  918. * @param int|null $compressionMethod Compression method.
  919. * Use {@see ZipCompressionMethod::STORED},
  920. * {@see ZipCompressionMethod::DEFLATED} or
  921. * {@see ZipCompressionMethod::BZIP2}. If null, then auto choosing method.
  922. *
  923. * @throws ZipException
  924. *
  925. * @return ZipFile
  926. * @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax
  927. */
  928. private function addGlob(
  929. $inputDir,
  930. $globPattern,
  931. $localPath = '/',
  932. $recursive = true,
  933. $compressionMethod = null
  934. ) {
  935. if ($inputDir === null) {
  936. throw new InvalidArgumentException('Input dir is null');
  937. }
  938. $inputDir = (string) $inputDir;
  939. if ($inputDir === '') {
  940. throw new InvalidArgumentException('The input directory is not specified');
  941. }
  942. if (!is_dir($inputDir)) {
  943. throw new InvalidArgumentException(sprintf('The "%s" directory does not exist.', $inputDir));
  944. }
  945. $globPattern = (string) $globPattern;
  946. if (empty($globPattern)) {
  947. throw new InvalidArgumentException('The glob pattern is not specified');
  948. }
  949. $inputDir = rtrim($inputDir, '/\\') . \DIRECTORY_SEPARATOR;
  950. $globPattern = $inputDir . $globPattern;
  951. $filesFound = FilesUtil::globFileSearch($globPattern, \GLOB_BRACE, $recursive);
  952. if ($filesFound === false || empty($filesFound)) {
  953. return $this;
  954. }
  955. $this->doAddFiles($inputDir, $filesFound, $localPath, $compressionMethod);
  956. return $this;
  957. }
  958. /**
  959. * Add files recursively from glob pattern.
  960. *
  961. * @param string $inputDir Input directory
  962. * @param string $globPattern glob pattern
  963. * @param string $localPath add files to this directory, or the root
  964. * @param int|null $compressionMethod Compression method.
  965. * Use {@see ZipCompressionMethod::STORED},
  966. * {@see ZipCompressionMethod::DEFLATED} or
  967. * {@see ZipCompressionMethod::BZIP2}. If null, then auto choosing method.
  968. *
  969. * @throws ZipException
  970. *
  971. * @return ZipFile
  972. * @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax
  973. */
  974. public function addFilesFromGlobRecursive($inputDir, $globPattern, $localPath = '/', $compressionMethod = null)
  975. {
  976. return $this->addGlob($inputDir, $globPattern, $localPath, true, $compressionMethod);
  977. }
  978. /**
  979. * Add files from regex pattern.
  980. *
  981. * @param string $inputDir search files in this directory
  982. * @param string $regexPattern regex pattern
  983. * @param string $localPath add files to this directory, or the root
  984. * @param int|null $compressionMethod Compression method.
  985. * Use {@see ZipCompressionMethod::STORED},
  986. * {@see ZipCompressionMethod::DEFLATED} or
  987. * {@see ZipCompressionMethod::BZIP2}. If null, then auto choosing method.
  988. *
  989. * @throws ZipException
  990. *
  991. * @return ZipFile
  992. *
  993. * @internal param bool $recursive Recursive search
  994. */
  995. public function addFilesFromRegex($inputDir, $regexPattern, $localPath = '/', $compressionMethod = null)
  996. {
  997. return $this->addRegex($inputDir, $regexPattern, $localPath, false, $compressionMethod);
  998. }
  999. /**
  1000. * Add files from regex pattern.
  1001. *
  1002. * @param string $inputDir search files in this directory
  1003. * @param string $regexPattern regex pattern
  1004. * @param string $localPath add files to this directory, or the root
  1005. * @param bool $recursive recursive search
  1006. * @param int|null $compressionMethod Compression method.
  1007. * Use {@see ZipCompressionMethod::STORED},
  1008. * {@see ZipCompressionMethod::DEFLATED} or
  1009. * {@see ZipCompressionMethod::BZIP2}.
  1010. * If null, then auto choosing method.
  1011. *
  1012. * @throws ZipException
  1013. *
  1014. * @return ZipFile
  1015. */
  1016. private function addRegex(
  1017. $inputDir,
  1018. $regexPattern,
  1019. $localPath = '/',
  1020. $recursive = true,
  1021. $compressionMethod = null
  1022. ) {
  1023. $regexPattern = (string) $regexPattern;
  1024. if (empty($regexPattern)) {
  1025. throw new InvalidArgumentException('The regex pattern is not specified');
  1026. }
  1027. $inputDir = (string) $inputDir;
  1028. if ($inputDir === '') {
  1029. throw new InvalidArgumentException('The input directory is not specified');
  1030. }
  1031. if (!is_dir($inputDir)) {
  1032. throw new InvalidArgumentException(sprintf('The "%s" directory does not exist.', $inputDir));
  1033. }
  1034. $inputDir = rtrim($inputDir, '/\\') . \DIRECTORY_SEPARATOR;
  1035. $files = FilesUtil::regexFileSearch($inputDir, $regexPattern, $recursive);
  1036. if (empty($files)) {
  1037. return $this;
  1038. }
  1039. $this->doAddFiles($inputDir, $files, $localPath, $compressionMethod);
  1040. return $this;
  1041. }
  1042. /**
  1043. * @param string $fileSystemDir
  1044. * @param array $files
  1045. * @param string $zipPath
  1046. * @param int|null $compressionMethod
  1047. *
  1048. * @throws ZipException
  1049. */
  1050. private function doAddFiles($fileSystemDir, array $files, $zipPath, $compressionMethod = null)
  1051. {
  1052. $fileSystemDir = rtrim($fileSystemDir, '/\\') . \DIRECTORY_SEPARATOR;
  1053. if (!empty($zipPath) && \is_string($zipPath)) {
  1054. $zipPath = trim($zipPath, '\\/') . '/';
  1055. } else {
  1056. $zipPath = '/';
  1057. }
  1058. /**
  1059. * @var string $file
  1060. */
  1061. foreach ($files as $file) {
  1062. $filename = str_replace($fileSystemDir, $zipPath, $file);
  1063. $filename = ltrim($filename, '\\/');
  1064. if (is_dir($file) && FilesUtil::isEmptyDir($file)) {
  1065. $this->addEmptyDir($filename);
  1066. } elseif (is_file($file)) {
  1067. $this->addFile($file, $filename, $compressionMethod);
  1068. }
  1069. }
  1070. }
  1071. /**
  1072. * Add files recursively from regex pattern.
  1073. *
  1074. * @param string $inputDir search files in this directory
  1075. * @param string $regexPattern regex pattern
  1076. * @param string $localPath add files to this directory, or the root
  1077. * @param int|null $compressionMethod Compression method.
  1078. * Use {@see ZipCompressionMethod::STORED},
  1079. * {@see ZipCompressionMethod::DEFLATED} or
  1080. * {@see ZipCompressionMethod::BZIP2}. If null, then auto choosing method.
  1081. *
  1082. * @throws ZipException
  1083. *
  1084. * @return ZipFile
  1085. *
  1086. * @internal param bool $recursive Recursive search
  1087. */
  1088. public function addFilesFromRegexRecursive($inputDir, $regexPattern, $localPath = '/', $compressionMethod = null)
  1089. {
  1090. return $this->addRegex($inputDir, $regexPattern, $localPath, true, $compressionMethod);
  1091. }
  1092. /**
  1093. * Add array data to archive.
  1094. * Keys is local names.
  1095. * Values is contents.
  1096. *
  1097. * @param array $mapData associative array for added to zip
  1098. */
  1099. public function addAll(array $mapData)
  1100. {
  1101. foreach ($mapData as $localName => $content) {
  1102. $this[$localName] = $content;
  1103. }
  1104. }
  1105. /**
  1106. * Rename the entry.
  1107. *
  1108. * @param string $oldName old entry name
  1109. * @param string $newName new entry name
  1110. *
  1111. * @throws ZipException
  1112. *
  1113. * @return ZipFile
  1114. */
  1115. public function rename($oldName, $newName)
  1116. {
  1117. if ($oldName === null || $newName === null) {
  1118. throw new InvalidArgumentException('name is null');
  1119. }
  1120. $oldName = ltrim((string) $oldName, '\\/');
  1121. $newName = ltrim((string) $newName, '\\/');
  1122. if ($oldName !== $newName) {
  1123. $this->zipContainer->renameEntry($oldName, $newName);
  1124. }
  1125. return $this;
  1126. }
  1127. /**
  1128. * Delete entry by name.
  1129. *
  1130. * @param string $entryName zip Entry name
  1131. *
  1132. * @throws ZipEntryNotFoundException if entry not found
  1133. *
  1134. * @return ZipFile
  1135. */
  1136. public function deleteFromName($entryName)
  1137. {
  1138. $entryName = ltrim((string) $entryName, '\\/');
  1139. if (!$this->zipContainer->deleteEntry($entryName)) {
  1140. throw new ZipEntryNotFoundException($entryName);
  1141. }
  1142. return $this;
  1143. }
  1144. /**
  1145. * Delete entries by glob pattern.
  1146. *
  1147. * @param string $globPattern Glob pattern
  1148. *
  1149. * @return ZipFile
  1150. * @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax
  1151. */
  1152. public function deleteFromGlob($globPattern)
  1153. {
  1154. if ($globPattern === null || !\is_string($globPattern) || empty($globPattern)) {
  1155. throw new InvalidArgumentException('The glob pattern is not specified');
  1156. }
  1157. $globPattern = '~' . FilesUtil::convertGlobToRegEx($globPattern) . '~si';
  1158. $this->deleteFromRegex($globPattern);
  1159. return $this;
  1160. }
  1161. /**
  1162. * Delete entries by regex pattern.
  1163. *
  1164. * @param string $regexPattern Regex pattern
  1165. *
  1166. * @return ZipFile
  1167. */
  1168. public function deleteFromRegex($regexPattern)
  1169. {
  1170. if ($regexPattern === null || !\is_string($regexPattern) || empty($regexPattern)) {
  1171. throw new InvalidArgumentException('The regex pattern is not specified');
  1172. }
  1173. $this->matcher()->match($regexPattern)->delete();
  1174. return $this;
  1175. }
  1176. /**
  1177. * Delete all entries.
  1178. *
  1179. * @return ZipFile
  1180. */
  1181. public function deleteAll()
  1182. {
  1183. $this->zipContainer->deleteAll();
  1184. return $this;
  1185. }
  1186. /**
  1187. * Set compression level for new entries.
  1188. *
  1189. * @param int $compressionLevel
  1190. *
  1191. * @return ZipFile
  1192. *
  1193. * @see ZipCompressionLevel::NORMAL
  1194. * @see ZipCompressionLevel::SUPER_FAST
  1195. * @see ZipCompressionLevel::FAST
  1196. * @see ZipCompressionLevel::MAXIMUM
  1197. */
  1198. public function setCompressionLevel($compressionLevel = ZipCompressionLevel::NORMAL)
  1199. {
  1200. $compressionLevel = (int) $compressionLevel;
  1201. foreach ($this->zipContainer->getEntries() as $entry) {
  1202. $entry->setCompressionLevel($compressionLevel);
  1203. }
  1204. return $this;
  1205. }
  1206. /**
  1207. * @param string $entryName
  1208. * @param int $compressionLevel
  1209. *
  1210. * @throws ZipException
  1211. *
  1212. * @return ZipFile
  1213. *
  1214. * @see ZipCompressionLevel::NORMAL
  1215. * @see ZipCompressionLevel::SUPER_FAST
  1216. * @see ZipCompressionLevel::FAST
  1217. * @see ZipCompressionLevel::MAXIMUM
  1218. */
  1219. public function setCompressionLevelEntry($entryName, $compressionLevel)
  1220. {
  1221. $compressionLevel = (int) $compressionLevel;
  1222. $this->getEntry($entryName)->setCompressionLevel($compressionLevel);
  1223. return $this;
  1224. }
  1225. /**
  1226. * @param string $entryName
  1227. * @param int $compressionMethod Compression method.
  1228. * Use {@see ZipCompressionMethod::STORED}, {@see ZipCompressionMethod::DEFLATED}
  1229. * or
  1230. * {@see ZipCompressionMethod::BZIP2}. If null, then auto choosing method.
  1231. *
  1232. * @throws ZipException
  1233. *
  1234. * @return ZipFile
  1235. *
  1236. * @see ZipCompressionMethod::STORED
  1237. * @see ZipCompressionMethod::DEFLATED
  1238. * @see ZipCompressionMethod::BZIP2
  1239. */
  1240. public function setCompressionMethodEntry($entryName, $compressionMethod)
  1241. {
  1242. $this->zipContainer
  1243. ->getEntry($entryName)
  1244. ->setCompressionMethod($compressionMethod)
  1245. ;
  1246. return $this;
  1247. }
  1248. /**
  1249. * zipalign is optimization to Android application (APK) files.
  1250. *
  1251. * @param int|null $align
  1252. *
  1253. * @return ZipFile
  1254. *
  1255. * @see https://developer.android.com/studio/command-line/zipalign.html
  1256. */
  1257. public function setZipAlign($align = null)
  1258. {
  1259. $this->zipContainer->setZipAlign($align);
  1260. return $this;
  1261. }
  1262. /**
  1263. * Set password to all input encrypted entries.
  1264. *
  1265. * @param string $password Password
  1266. *
  1267. * @return ZipFile
  1268. */
  1269. public function setReadPassword($password)
  1270. {
  1271. $this->zipContainer->setReadPassword($password);
  1272. return $this;
  1273. }
  1274. /**
  1275. * Set password to concrete input entry.
  1276. *
  1277. * @param string $entryName
  1278. * @param string $password Password
  1279. *
  1280. * @throws ZipException
  1281. *
  1282. * @return ZipFile
  1283. */
  1284. public function setReadPasswordEntry($entryName, $password)
  1285. {
  1286. $this->zipContainer->setReadPasswordEntry($entryName, $password);
  1287. return $this;
  1288. }
  1289. /**
  1290. * Sets a new password for all files in the archive.
  1291. *
  1292. * @param string $password Password
  1293. * @param int|null $encryptionMethod Encryption method
  1294. *
  1295. * @return ZipFile
  1296. */
  1297. public function setPassword($password, $encryptionMethod = ZipEncryptionMethod::WINZIP_AES_256)
  1298. {
  1299. $this->zipContainer->setWritePassword($password);
  1300. if ($encryptionMethod !== null) {
  1301. $this->zipContainer->setEncryptionMethod($encryptionMethod);
  1302. }
  1303. return $this;
  1304. }
  1305. /**
  1306. * Sets a new password of an entry defined by its name.
  1307. *
  1308. * @param string $entryName
  1309. * @param string $password
  1310. * @param int|null $encryptionMethod
  1311. *
  1312. * @throws ZipException
  1313. *
  1314. * @return ZipFile
  1315. */
  1316. public function setPasswordEntry($entryName, $password, $encryptionMethod = null)
  1317. {
  1318. $this->getEntry($entryName)->setPassword($password, $encryptionMethod);
  1319. return $this;
  1320. }
  1321. /**
  1322. * Disable encryption for all entries that are already in the archive.
  1323. *
  1324. * @return ZipFile
  1325. */
  1326. public function disableEncryption()
  1327. {
  1328. $this->zipContainer->removePassword();
  1329. return $this;
  1330. }
  1331. /**
  1332. * Disable encryption of an entry defined by its name.
  1333. *
  1334. * @param string $entryName
  1335. *
  1336. * @return ZipFile
  1337. */
  1338. public function disableEncryptionEntry($entryName)
  1339. {
  1340. $this->zipContainer->removePasswordEntry($entryName);
  1341. return $this;
  1342. }
  1343. /**
  1344. * Undo all changes done in the archive.
  1345. *
  1346. * @return ZipFile
  1347. */
  1348. public function unchangeAll()
  1349. {
  1350. $this->zipContainer->unchangeAll();
  1351. return $this;
  1352. }
  1353. /**
  1354. * Undo change archive comment.
  1355. *
  1356. * @return ZipFile
  1357. */
  1358. public function unchangeArchiveComment()
  1359. {
  1360. $this->zipContainer->unchangeArchiveComment();
  1361. return $this;
  1362. }
  1363. /**
  1364. * Revert all changes done to an entry with the given name.
  1365. *
  1366. * @param string|ZipEntry $entry Entry name or ZipEntry
  1367. *
  1368. * @return ZipFile
  1369. */
  1370. public function unchangeEntry($entry)
  1371. {
  1372. $this->zipContainer->unchangeEntry($entry);
  1373. return $this;
  1374. }
  1375. /**
  1376. * Save as file.
  1377. *
  1378. * @param string $filename Output filename
  1379. *
  1380. * @throws ZipException
  1381. *
  1382. * @return ZipFile
  1383. */
  1384. public function saveAsFile($filename)
  1385. {
  1386. $filename = (string) $filename;
  1387. $tempFilename = $filename . '.temp' . uniqid('', true);
  1388. if (!($handle = @fopen($tempFilename, 'w+b'))) {
  1389. throw new InvalidArgumentException('File ' . $tempFilename . ' can not open from write.');
  1390. }
  1391. $this->saveAsStream($handle);
  1392. $reopen = false;
  1393. if ($this->reader !== null) {
  1394. $meta = $this->reader->getStreamMetaData();
  1395. if ($meta['wrapper_type'] === 'plainfile' && isset($meta['uri']) && $meta['uri'] === $filename) {
  1396. $this->reader->close();
  1397. $reopen = true;
  1398. }
  1399. }
  1400. if (!@rename($tempFilename, $filename)) {
  1401. if (is_file($tempFilename)) {
  1402. unlink($tempFilename);
  1403. }
  1404. throw new ZipException('Can not move ' . $tempFilename . ' to ' . $filename);
  1405. }
  1406. if ($reopen) {
  1407. return $this->openFile($filename);
  1408. }
  1409. return $this;
  1410. }
  1411. /**
  1412. * Save as stream.
  1413. *
  1414. * @param resource $handle Output stream resource
  1415. *
  1416. * @throws ZipException
  1417. *
  1418. * @return ZipFile
  1419. */
  1420. public function saveAsStream($handle)
  1421. {
  1422. if (!\is_resource($handle)) {
  1423. throw new InvalidArgumentException('handle is not resource');
  1424. }
  1425. ftruncate($handle, 0);
  1426. $this->writeZipToStream($handle);
  1427. fclose($handle);
  1428. return $this;
  1429. }
  1430. /**
  1431. * Output .ZIP archive as attachment.
  1432. * Die after output.
  1433. *
  1434. * @param string $outputFilename Output filename
  1435. * @param string|null $mimeType Mime-Type
  1436. * @param bool $attachment Http Header 'Content-Disposition' if true then attachment otherwise inline
  1437. *
  1438. * @throws ZipException
  1439. */
  1440. public function outputAsAttachment($outputFilename, $mimeType = null, $attachment = true)
  1441. {
  1442. $outputFilename = (string) $outputFilename;
  1443. if ($mimeType === null) {
  1444. $mimeType = $this->getMimeTypeByFilename($outputFilename);
  1445. }
  1446. if (!($handle = fopen('php://temp', 'w+b'))) {
  1447. throw new InvalidArgumentException('php://temp cannot open for write.');
  1448. }
  1449. $this->writeZipToStream($handle);
  1450. $this->close();
  1451. $size = fstat($handle)['size'];
  1452. $headerContentDisposition = 'Content-Disposition: ' . ($attachment ? 'attachment' : 'inline');
  1453. if (!empty($outputFilename)) {
  1454. $headerContentDisposition .= '; filename="' . basename($outputFilename) . '"';
  1455. }
  1456. header($headerContentDisposition);
  1457. header('Content-Type: ' . $mimeType);
  1458. header('Content-Length: ' . $size);
  1459. rewind($handle);
  1460. try {
  1461. echo stream_get_contents($handle, -1, 0);
  1462. } finally {
  1463. fclose($handle);
  1464. }
  1465. }
  1466. /**
  1467. * @param string $outputFilename
  1468. *
  1469. * @return string
  1470. */
  1471. protected function getMimeTypeByFilename($outputFilename)
  1472. {
  1473. $outputFilename = (string) $outputFilename;
  1474. $ext = strtolower(pathinfo($outputFilename, \PATHINFO_EXTENSION));
  1475. if (!empty($ext) && isset(self::$defaultMimeTypes[$ext])) {
  1476. return self::$defaultMimeTypes[$ext];
  1477. }
  1478. return self::$defaultMimeTypes['zip'];
  1479. }
  1480. /**
  1481. * Output .ZIP archive as PSR-7 Response.
  1482. *
  1483. * @param ResponseInterface $response Instance PSR-7 Response
  1484. * @param string $outputFilename Output filename
  1485. * @param string|null $mimeType Mime-Type
  1486. * @param bool $attachment Http Header 'Content-Disposition' if true then attachment otherwise inline
  1487. *
  1488. * @throws ZipException
  1489. *
  1490. * @return ResponseInterface
  1491. */
  1492. public function outputAsResponse(ResponseInterface $response, $outputFilename, $mimeType = null, $attachment = true)
  1493. {
  1494. $outputFilename = (string) $outputFilename;
  1495. if ($mimeType === null) {
  1496. $mimeType = $this->getMimeTypeByFilename($outputFilename);
  1497. }
  1498. if (!($handle = fopen('php://temp', 'w+b'))) {
  1499. throw new InvalidArgumentException('php://temp cannot open for write.');
  1500. }
  1501. $this->writeZipToStream($handle);
  1502. $this->close();
  1503. rewind($handle);
  1504. $contentDispositionValue = ($attachment ? 'attachment' : 'inline');
  1505. if (!empty($outputFilename)) {
  1506. $contentDispositionValue .= '; filename="' . basename($outputFilename) . '"';
  1507. }
  1508. $stream = new ResponseStream($handle);
  1509. $size = $stream->getSize();
  1510. if ($size !== null) {
  1511. /** @noinspection CallableParameterUseCaseInTypeContextInspection */
  1512. $response = $response->withHeader('Content-Length', (string) $size);
  1513. }
  1514. return $response
  1515. ->withHeader('Content-Type', $mimeType)
  1516. ->withHeader('Content-Disposition', $contentDispositionValue)
  1517. ->withBody($stream)
  1518. ;
  1519. }
  1520. /**
  1521. * @param resource $handle
  1522. *
  1523. * @throws ZipException
  1524. */
  1525. protected function writeZipToStream($handle)
  1526. {
  1527. $this->onBeforeSave();
  1528. $this->createZipWriter()->write($handle);
  1529. }
  1530. /**
  1531. * Returns the zip archive as a string.
  1532. *
  1533. * @throws ZipException
  1534. *
  1535. * @return string
  1536. */
  1537. public function outputAsString()
  1538. {
  1539. if (!($handle = fopen('php://temp', 'w+b'))) {
  1540. throw new InvalidArgumentException('php://temp cannot open for write.');
  1541. }
  1542. $this->writeZipToStream($handle);
  1543. rewind($handle);
  1544. try {
  1545. return stream_get_contents($handle);
  1546. } finally {
  1547. fclose($handle);
  1548. }
  1549. }
  1550. /**
  1551. * Event before save or output.
  1552. */
  1553. protected function onBeforeSave()
  1554. {
  1555. }
  1556. /**
  1557. * Close zip archive and release input stream.
  1558. */
  1559. public function close()
  1560. {
  1561. if ($this->reader !== null) {
  1562. $this->reader->close();
  1563. $this->reader = null;
  1564. }
  1565. $this->zipContainer = $this->createZipContainer(null);
  1566. gc_collect_cycles();
  1567. }
  1568. /**
  1569. * Save and reopen zip archive.
  1570. *
  1571. * @throws ZipException
  1572. *
  1573. * @return ZipFile
  1574. */
  1575. public function rewrite()
  1576. {
  1577. if ($this->reader === null) {
  1578. throw new ZipException('input stream is null');
  1579. }
  1580. $meta = $this->reader->getStreamMetaData();
  1581. if ($meta['wrapper_type'] !== 'plainfile' || !isset($meta['uri'])) {
  1582. throw new ZipException('Overwrite is only supported for open local files.');
  1583. }
  1584. return $this->saveAsFile($meta['uri']);
  1585. }
  1586. /**
  1587. * Release all resources.
  1588. */
  1589. public function __destruct()
  1590. {
  1591. $this->close();
  1592. }
  1593. /**
  1594. * Offset to set.
  1595. *
  1596. * @see http://php.net/manual/en/arrayaccess.offsetset.php
  1597. *
  1598. * @param string $entryName the offset to assign the value to
  1599. * @param string|\DirectoryIterator|\SplFileInfo|resource $contents the value to set
  1600. *
  1601. * @throws ZipException
  1602. *
  1603. * @see ZipFile::addFromString
  1604. * @see ZipFile::addEmptyDir
  1605. * @see ZipFile::addFile
  1606. * @see ZipFile::addFilesFromIterator
  1607. */
  1608. public function offsetSet($entryName, $contents)
  1609. {
  1610. if ($entryName === null) {
  1611. throw new InvalidArgumentException('Key must not be null, but must contain the name of the zip entry.');
  1612. }
  1613. $entryName = ltrim((string) $entryName, '\\/');
  1614. if ($entryName === '') {
  1615. throw new InvalidArgumentException('Key is empty, but must contain the name of the zip entry.');
  1616. }
  1617. if ($contents instanceof \DirectoryIterator) {
  1618. $this->addFilesFromIterator($contents, $entryName);
  1619. } elseif ($contents instanceof \SplFileInfo) {
  1620. $this->addSplFile($contents, $entryName);
  1621. } elseif (StringUtil::endsWith($entryName, '/')) {
  1622. $this->addEmptyDir($entryName);
  1623. } elseif (\is_resource($contents)) {
  1624. $this->addFromStream($contents, $entryName);
  1625. } else {
  1626. $this->addFromString($entryName, (string) $contents);
  1627. }
  1628. }
  1629. /**
  1630. * Offset to unset.
  1631. *
  1632. * @see http://php.net/manual/en/arrayaccess.offsetunset.php
  1633. *
  1634. * @param string $entryName the offset to unset
  1635. *
  1636. * @throws ZipEntryNotFoundException
  1637. */
  1638. public function offsetUnset($entryName)
  1639. {
  1640. $this->deleteFromName($entryName);
  1641. }
  1642. /**
  1643. * Return the current element.
  1644. *
  1645. * @see http://php.net/manual/en/iterator.current.php
  1646. *
  1647. * @throws ZipException
  1648. *
  1649. * @return mixed can return any type
  1650. *
  1651. * @since 5.0.0
  1652. */
  1653. public function current()
  1654. {
  1655. return $this->offsetGet($this->key());
  1656. }
  1657. /**
  1658. * Offset to retrieve.
  1659. *
  1660. * @see http://php.net/manual/en/arrayaccess.offsetget.php
  1661. *
  1662. * @param string $entryName the offset to retrieve
  1663. *
  1664. * @throws ZipException
  1665. *
  1666. * @return string|null
  1667. */
  1668. public function offsetGet($entryName)
  1669. {
  1670. return $this->getEntryContents($entryName);
  1671. }
  1672. /**
  1673. * Return the key of the current element.
  1674. *
  1675. * @see http://php.net/manual/en/iterator.key.php
  1676. *
  1677. * @return mixed scalar on success, or null on failure
  1678. *
  1679. * @since 5.0.0
  1680. */
  1681. public function key()
  1682. {
  1683. return key($this->zipContainer->getEntries());
  1684. }
  1685. /**
  1686. * Move forward to next element.
  1687. *
  1688. * @see http://php.net/manual/en/iterator.next.php
  1689. * @since 5.0.0
  1690. */
  1691. public function next()
  1692. {
  1693. next($this->zipContainer->getEntries());
  1694. }
  1695. /**
  1696. * Checks if current position is valid.
  1697. *
  1698. * @see http://php.net/manual/en/iterator.valid.php
  1699. *
  1700. * @return bool The return value will be casted to boolean and then evaluated.
  1701. * Returns true on success or false on failure.
  1702. *
  1703. * @since 5.0.0
  1704. */
  1705. public function valid()
  1706. {
  1707. return $this->offsetExists($this->key());
  1708. }
  1709. /**
  1710. * Whether a offset exists.
  1711. *
  1712. * @see http://php.net/manual/en/arrayaccess.offsetexists.php
  1713. *
  1714. * @param string $entryName an offset to check for
  1715. *
  1716. * @return bool true on success or false on failure.
  1717. * The return value will be casted to boolean if non-boolean was returned.
  1718. */
  1719. public function offsetExists($entryName)
  1720. {
  1721. return $this->hasEntry($entryName);
  1722. }
  1723. /**
  1724. * Rewind the Iterator to the first element.
  1725. *
  1726. * @see http://php.net/manual/en/iterator.rewind.php
  1727. * @since 5.0.0
  1728. */
  1729. public function rewind()
  1730. {
  1731. reset($this->zipContainer->getEntries());
  1732. }
  1733. }