ZipArchive.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. <?php
  2. /**
  3. * This file is part of PHPWord - A pure PHP library for reading and writing
  4. * word processing documents.
  5. *
  6. * PHPWord is free software distributed under the terms of the GNU Lesser
  7. * General Public License version 3 as published by the Free Software Foundation.
  8. *
  9. * For the full copyright and license information, please read the LICENSE
  10. * file that was distributed with this source code. For the full list of
  11. * contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
  12. *
  13. * @see https://github.com/PHPOffice/PHPWord
  14. * @copyright 2010-2018 PHPWord contributors
  15. * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
  16. */
  17. namespace PhpOffice\PhpWord\Shared;
  18. use PhpOffice\PhpWord\Exception\Exception;
  19. use PhpOffice\PhpWord\Settings;
  20. /**
  21. * ZipArchive wrapper
  22. *
  23. * Wraps zip archive functionality of PHP ZipArchive and PCLZip. PHP ZipArchive
  24. * properties and methods are bypassed and used as the model for the PCLZip
  25. * emulation. Only needed PHP ZipArchive features are implemented.
  26. *
  27. * @method bool addFile(string $filename, string $localname = null)
  28. * @method bool addFromString(string $localname, string $contents)
  29. * @method string getNameIndex(int $index)
  30. * @method int locateName(string $name)
  31. *
  32. * @since 0.10.0
  33. */
  34. class ZipArchive
  35. {
  36. /** @const int Flags for open method */
  37. const CREATE = 1; // Emulate \ZipArchive::CREATE
  38. const OVERWRITE = 8; // Emulate \ZipArchive::OVERWRITE
  39. /**
  40. * Number of files (emulate ZipArchive::$numFiles)
  41. *
  42. * @var int
  43. */
  44. public $numFiles = 0;
  45. /**
  46. * Archive filename (emulate ZipArchive::$filename)
  47. *
  48. * @var string
  49. */
  50. public $filename;
  51. /**
  52. * Temporary storage directory
  53. *
  54. * @var string
  55. */
  56. private $tempDir;
  57. /**
  58. * Internal zip archive object
  59. *
  60. * @var \ZipArchive|\PclZip
  61. */
  62. private $zip;
  63. /**
  64. * Use PCLZip (default behaviour)
  65. *
  66. * @var bool
  67. */
  68. private $usePclzip = true;
  69. /**
  70. * Create new instance
  71. */
  72. public function __construct()
  73. {
  74. $this->usePclzip = (Settings::getZipClass() != 'ZipArchive');
  75. if ($this->usePclzip) {
  76. if (!defined('PCLZIP_TEMPORARY_DIR')) {
  77. define('PCLZIP_TEMPORARY_DIR', Settings::getTempDir() . '/');
  78. }
  79. require_once 'PCLZip/pclzip.lib.php';
  80. }
  81. }
  82. /**
  83. * Catch function calls: pass to ZipArchive or PCLZip
  84. *
  85. * `call_user_func_array` can only used for public function, hence the `public` in all `pcl...` methods
  86. *
  87. * @param mixed $function
  88. * @param mixed $args
  89. * @return mixed
  90. */
  91. public function __call($function, $args)
  92. {
  93. // Set object and function
  94. $zipFunction = $function;
  95. if (!$this->usePclzip) {
  96. $zipObject = $this->zip;
  97. } else {
  98. $zipObject = $this;
  99. $zipFunction = "pclzip{$zipFunction}";
  100. }
  101. // Run function
  102. $result = false;
  103. if (method_exists($zipObject, $zipFunction)) {
  104. $result = @call_user_func_array(array($zipObject, $zipFunction), $args);
  105. }
  106. return $result;
  107. }
  108. /**
  109. * Open a new zip archive
  110. *
  111. * @param string $filename The file name of the ZIP archive to open
  112. * @param int $flags The mode to use to open the archive
  113. * @return bool
  114. */
  115. public function open($filename, $flags = null)
  116. {
  117. $result = true;
  118. $this->filename = $filename;
  119. $this->tempDir = Settings::getTempDir();
  120. if (!$this->usePclzip) {
  121. $zip = new \ZipArchive();
  122. $result = $zip->open($this->filename, $flags);
  123. // Scrutizer will report the property numFiles does not exist
  124. // See https://github.com/scrutinizer-ci/php-analyzer/issues/190
  125. $this->numFiles = $zip->numFiles;
  126. } else {
  127. $zip = new \PclZip($this->filename);
  128. $zipContent = $zip->listContent();
  129. $this->numFiles = is_array($zipContent) ? count($zipContent) : 0;
  130. }
  131. $this->zip = $zip;
  132. return $result;
  133. }
  134. /**
  135. * Close the active archive
  136. *
  137. * @throws \PhpOffice\PhpWord\Exception\Exception
  138. *
  139. * @return bool
  140. *
  141. * @codeCoverageIgnore Can't find any test case. Uncomment when found.
  142. */
  143. public function close()
  144. {
  145. if (!$this->usePclzip) {
  146. if ($this->zip->close() === false) {
  147. throw new Exception("Could not close zip file {$this->filename}: ");
  148. }
  149. }
  150. return true;
  151. }
  152. /**
  153. * Extract the archive contents (emulate \ZipArchive)
  154. *
  155. * @param string $destination
  156. * @param string|array $entries
  157. * @return bool
  158. * @since 0.10.0
  159. */
  160. public function extractTo($destination, $entries = null)
  161. {
  162. if (!is_dir($destination)) {
  163. return false;
  164. }
  165. if (!$this->usePclzip) {
  166. return $this->zip->extractTo($destination, $entries);
  167. }
  168. return $this->pclzipExtractTo($destination, $entries);
  169. }
  170. /**
  171. * Extract file from archive by given file name (emulate \ZipArchive)
  172. *
  173. * @param string $filename Filename for the file in zip archive
  174. * @return string $contents File string contents
  175. */
  176. public function getFromName($filename)
  177. {
  178. if (!$this->usePclzip) {
  179. $contents = $this->zip->getFromName($filename);
  180. if ($contents === false) {
  181. $filename = substr($filename, 1);
  182. $contents = $this->zip->getFromName($filename);
  183. }
  184. } else {
  185. $contents = $this->pclzipGetFromName($filename);
  186. }
  187. return $contents;
  188. }
  189. /**
  190. * Add a new file to the zip archive (emulate \ZipArchive)
  191. *
  192. * @param string $filename Directory/Name of the file to add to the zip archive
  193. * @param string $localname Directory/Name of the file added to the zip
  194. * @return bool
  195. */
  196. public function pclzipAddFile($filename, $localname = null)
  197. {
  198. /** @var \PclZip $zip Type hint */
  199. $zip = $this->zip;
  200. // Bugfix GH-261 https://github.com/PHPOffice/PHPWord/pull/261
  201. $realpathFilename = realpath($filename);
  202. if ($realpathFilename !== false) {
  203. $filename = $realpathFilename;
  204. }
  205. $filenameParts = pathinfo($filename);
  206. $localnameParts = pathinfo($localname);
  207. // To Rename the file while adding it to the zip we
  208. // need to create a temp file with the correct name
  209. $tempFile = false;
  210. if ($filenameParts['basename'] != $localnameParts['basename']) {
  211. $tempFile = true; // temp file created
  212. $temppath = $this->tempDir . DIRECTORY_SEPARATOR . $localnameParts['basename'];
  213. copy($filename, $temppath);
  214. $filename = $temppath;
  215. $filenameParts = pathinfo($temppath);
  216. }
  217. $pathRemoved = $filenameParts['dirname'];
  218. $pathAdded = $localnameParts['dirname'];
  219. if (!$this->usePclzip) {
  220. $pathAdded = $pathAdded . '/' . ltrim(str_replace('\\', '/', substr($filename, strlen($pathRemoved))), '/');
  221. //$res = $zip->addFile($filename, $pathAdded);
  222. $res = $zip->addFromString($pathAdded, file_get_contents($filename)); // addFile can't use subfolders in some cases
  223. } else {
  224. $res = $zip->add($filename, PCLZIP_OPT_REMOVE_PATH, $pathRemoved, PCLZIP_OPT_ADD_PATH, $pathAdded);
  225. }
  226. if ($tempFile) {
  227. // Remove temp file, if created
  228. unlink($this->tempDir . DIRECTORY_SEPARATOR . $localnameParts['basename']);
  229. }
  230. return $res != 0;
  231. }
  232. /**
  233. * Add a new file to the zip archive from a string of raw data (emulate \ZipArchive)
  234. *
  235. * @param string $localname Directory/Name of the file to add to the zip archive
  236. * @param string $contents String of data to add to the zip archive
  237. * @return bool
  238. */
  239. public function pclzipAddFromString($localname, $contents)
  240. {
  241. /** @var \PclZip $zip Type hint */
  242. $zip = $this->zip;
  243. $filenameParts = pathinfo($localname);
  244. // Write $contents to a temp file
  245. $handle = fopen($this->tempDir . DIRECTORY_SEPARATOR . $filenameParts['basename'], 'wb');
  246. fwrite($handle, $contents);
  247. fclose($handle);
  248. // Add temp file to zip
  249. $filename = $this->tempDir . DIRECTORY_SEPARATOR . $filenameParts['basename'];
  250. $pathRemoved = $this->tempDir;
  251. $pathAdded = $filenameParts['dirname'];
  252. $res = $zip->add($filename, PCLZIP_OPT_REMOVE_PATH, $pathRemoved, PCLZIP_OPT_ADD_PATH, $pathAdded);
  253. // Remove temp file
  254. @unlink($this->tempDir . DIRECTORY_SEPARATOR . $filenameParts['basename']);
  255. return $res != 0;
  256. }
  257. /**
  258. * Extract the archive contents (emulate \ZipArchive)
  259. *
  260. * @param string $destination
  261. * @param string|array $entries
  262. * @return bool
  263. * @since 0.10.0
  264. */
  265. public function pclzipExtractTo($destination, $entries = null)
  266. {
  267. /** @var \PclZip $zip Type hint */
  268. $zip = $this->zip;
  269. // Extract all files
  270. if (is_null($entries)) {
  271. $result = $zip->extract(PCLZIP_OPT_PATH, $destination);
  272. return $result > 0;
  273. }
  274. // Extract by entries
  275. if (!is_array($entries)) {
  276. $entries = array($entries);
  277. }
  278. foreach ($entries as $entry) {
  279. $entryIndex = $this->locateName($entry);
  280. $result = $zip->extractByIndex($entryIndex, PCLZIP_OPT_PATH, $destination);
  281. if ($result <= 0) {
  282. return false;
  283. }
  284. }
  285. return true;
  286. }
  287. /**
  288. * Extract file from archive by given file name (emulate \ZipArchive)
  289. *
  290. * @param string $filename Filename for the file in zip archive
  291. * @return string $contents File string contents
  292. */
  293. public function pclzipGetFromName($filename)
  294. {
  295. /** @var \PclZip $zip Type hint */
  296. $zip = $this->zip;
  297. $listIndex = $this->pclzipLocateName($filename);
  298. $contents = false;
  299. if ($listIndex !== false) {
  300. $extracted = $zip->extractByIndex($listIndex, PCLZIP_OPT_EXTRACT_AS_STRING);
  301. } else {
  302. $filename = substr($filename, 1);
  303. $listIndex = $this->pclzipLocateName($filename);
  304. $extracted = $zip->extractByIndex($listIndex, PCLZIP_OPT_EXTRACT_AS_STRING);
  305. }
  306. if ((is_array($extracted)) && ($extracted != 0)) {
  307. $contents = $extracted[0]['content'];
  308. }
  309. return $contents;
  310. }
  311. /**
  312. * Returns the name of an entry using its index (emulate \ZipArchive)
  313. *
  314. * @param int $index
  315. * @return string|bool
  316. * @since 0.10.0
  317. */
  318. public function pclzipGetNameIndex($index)
  319. {
  320. /** @var \PclZip $zip Type hint */
  321. $zip = $this->zip;
  322. $list = $zip->listContent();
  323. if (isset($list[$index])) {
  324. return $list[$index]['filename'];
  325. }
  326. return false;
  327. }
  328. /**
  329. * Returns the index of the entry in the archive (emulate \ZipArchive)
  330. *
  331. * @param string $filename Filename for the file in zip archive
  332. * @return int
  333. */
  334. public function pclzipLocateName($filename)
  335. {
  336. /** @var \PclZip $zip Type hint */
  337. $zip = $this->zip;
  338. $list = $zip->listContent();
  339. $listCount = count($list);
  340. $listIndex = -1;
  341. for ($i = 0; $i < $listCount; ++$i) {
  342. if (strtolower($list[$i]['filename']) == strtolower($filename) ||
  343. strtolower($list[$i]['stored_filename']) == strtolower($filename)) {
  344. $listIndex = $i;
  345. break;
  346. }
  347. }
  348. return ($listIndex > -1) ? $listIndex : false;
  349. }
  350. }