/src/PhpWord/Shared/ZipArchive.php

https://github.com/cyrillkalita/PHPWord · PHP · 376 lines · 180 code · 43 blank · 153 comment · 34 complexity · c4fac2f853e6fbadadc3a81450c5c6d0 MD5 · raw file

  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. * @link https://github.com/PHPOffice/PHPWord
  14. * @copyright 2010-2014 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', sys_get_temp_dir() . '/');
  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. if (!$this->usePclzip) {
  120. $zip = new \ZipArchive();
  121. $result = $zip->open($this->filename, $flags);
  122. // Scrutizer will report the property numFiles does not exist
  123. // See https://github.com/scrutinizer-ci/php-analyzer/issues/190
  124. $this->numFiles = $zip->numFiles;
  125. } else {
  126. $zip = new \PclZip($this->filename);
  127. $this->tempDir = sys_get_temp_dir();
  128. $this->numFiles = count($zip->listContent());
  129. }
  130. $this->zip = $zip;
  131. return $result;
  132. }
  133. /**
  134. * Close the active archive
  135. *
  136. * @return bool
  137. * @throws \PhpOffice\PhpWord\Exception\Exception
  138. * @codeCoverageIgnore Can't find any test case. Uncomment when found.
  139. */
  140. public function close()
  141. {
  142. if (!$this->usePclzip) {
  143. if ($this->zip->close() === false) {
  144. throw new Exception("Could not close zip file $this->filename.");
  145. }
  146. }
  147. return true;
  148. }
  149. /**
  150. * Extract the archive contents (emulate \ZipArchive)
  151. *
  152. * @param string $destination
  153. * @param string|array $entries
  154. * @return bool
  155. * @since 0.10.0
  156. */
  157. public function extractTo($destination, $entries = null)
  158. {
  159. if (!is_dir($destination)) {
  160. return false;
  161. }
  162. if (!$this->usePclzip) {
  163. return $this->zip->extractTo($destination, $entries);
  164. } else {
  165. return $this->pclzipExtractTo($destination, $entries);
  166. }
  167. }
  168. /**
  169. * Extract file from archive by given file name (emulate \ZipArchive)
  170. *
  171. * @param string $filename Filename for the file in zip archive
  172. * @return string $contents File string contents
  173. */
  174. public function getFromName($filename)
  175. {
  176. if (!$this->usePclzip) {
  177. $contents = $this->zip->getFromName($filename);
  178. if ($contents === false) {
  179. $filename = substr($filename, 1);
  180. $contents = $this->zip->getFromName($filename);
  181. }
  182. } else {
  183. $contents = $this->pclzipGetFromName($filename);
  184. }
  185. return $contents;
  186. }
  187. /**
  188. * Add a new file to the zip archive (emulate \ZipArchive)
  189. *
  190. * @param string $filename Directory/Name of the file to add to the zip archive
  191. * @param string $localname Directory/Name of the file added to the zip
  192. * @return bool
  193. */
  194. public function pclzipAddFile($filename, $localname = null)
  195. {
  196. /** @var \PclZip $zip Type hint */
  197. $zip = $this->zip;
  198. $filename = realpath($filename);
  199. $filenameParts = pathinfo($filename);
  200. $localnameParts = pathinfo($localname);
  201. // To Rename the file while adding it to the zip we
  202. // need to create a temp file with the correct name
  203. if ($filenameParts['basename'] != $localnameParts['basename']) {
  204. $temppath = $this->tempDir . '/' . $localnameParts['basename'];
  205. copy($filename, $temppath);
  206. $filename = $temppath;
  207. $filenameParts = pathinfo($temppath);
  208. }
  209. $pathRemoved = $filenameParts['dirname'];
  210. $pathAdded = $localnameParts['dirname'];
  211. $res = $zip->add($filename, PCLZIP_OPT_REMOVE_PATH, $pathRemoved, PCLZIP_OPT_ADD_PATH, $pathAdded);
  212. return ($res == 0) ? false : true;
  213. }
  214. /**
  215. * Add a new file to the zip archive from a string of raw data (emulate \ZipArchive)
  216. *
  217. * @param string $localname Directory/Name of the file to add to the zip archive
  218. * @param string $contents String of data to add to the zip archive
  219. * @return bool
  220. */
  221. public function pclzipAddFromString($localname, $contents)
  222. {
  223. /** @var \PclZip $zip Type hint */
  224. $zip = $this->zip;
  225. $filenameParts = pathinfo($localname);
  226. // Write $contents to a temp file
  227. $handle = fopen($this->tempDir . '/' . $filenameParts["basename"], "wb");
  228. fwrite($handle, $contents);
  229. fclose($handle);
  230. // Add temp file to zip
  231. $filename = $this->tempDir . '/' . $filenameParts["basename"];
  232. $pathRemoved = $this->tempDir;
  233. $pathAdded = $filenameParts['dirname'];
  234. $res = $zip->add($filename, PCLZIP_OPT_REMOVE_PATH, $pathRemoved, PCLZIP_OPT_ADD_PATH, $pathAdded);
  235. // Remove temp file
  236. @unlink($this->tempDir . '/' . $filenameParts["basename"]);
  237. return ($res == 0) ? false : true;
  238. }
  239. /**
  240. * Extract the archive contents (emulate \ZipArchive)
  241. *
  242. * @param string $destination
  243. * @param string|array $entries
  244. * @return bool
  245. * @since 0.10.0
  246. */
  247. public function pclzipExtractTo($destination, $entries = null)
  248. {
  249. /** @var \PclZip $zip Type hint */
  250. $zip = $this->zip;
  251. // Extract all files
  252. if (is_null($entries)) {
  253. $result = $zip->extract(PCLZIP_OPT_PATH, $destination);
  254. return ($result > 0) ? true : false;
  255. }
  256. // Extract by entries
  257. if (!is_array($entries)) {
  258. $entries = array($entries);
  259. }
  260. foreach ($entries as $entry) {
  261. $entryIndex = $this->locateName($entry);
  262. $result = $zip->extractByIndex($entryIndex, PCLZIP_OPT_PATH, $destination);
  263. if ($result <= 0) {
  264. return false;
  265. }
  266. }
  267. return true;
  268. }
  269. /**
  270. * Extract file from archive by given file name (emulate \ZipArchive)
  271. *
  272. * @param string $filename Filename for the file in zip archive
  273. * @return string $contents File string contents
  274. */
  275. public function pclzipGetFromName($filename)
  276. {
  277. /** @var \PclZip $zip Type hint */
  278. $zip = $this->zip;
  279. $listIndex = $this->pclzipLocateName($filename);
  280. $contents = false;
  281. if ($listIndex !== false) {
  282. $extracted = $zip->extractByIndex($listIndex, PCLZIP_OPT_EXTRACT_AS_STRING);
  283. } else {
  284. $filename = substr($filename, 1);
  285. $listIndex = $this->pclzipLocateName($filename);
  286. $extracted = $zip->extractByIndex($listIndex, PCLZIP_OPT_EXTRACT_AS_STRING);
  287. }
  288. if ((is_array($extracted)) && ($extracted != 0)) {
  289. $contents = $extracted[0]["content"];
  290. }
  291. return $contents;
  292. }
  293. /**
  294. * Returns the name of an entry using its index (emulate \ZipArchive)
  295. *
  296. * @param int $index
  297. * @return string
  298. * @since 0.10.0
  299. */
  300. public function pclzipGetNameIndex($index)
  301. {
  302. /** @var \PclZip $zip Type hint */
  303. $zip = $this->zip;
  304. $list = $zip->listContent();
  305. if (isset($list[$index])) {
  306. return $list[$index]['filename'];
  307. } else {
  308. return false;
  309. }
  310. }
  311. /**
  312. * Returns the index of the entry in the archive (emulate \ZipArchive)
  313. *
  314. * @param string $filename Filename for the file in zip archive
  315. * @return int
  316. */
  317. public function pclzipLocateName($filename)
  318. {
  319. /** @var \PclZip $zip Type hint */
  320. $zip = $this->zip;
  321. $list = $zip->listContent();
  322. $listCount = count($list);
  323. $listIndex = -1;
  324. for ($i = 0; $i < $listCount; ++$i) {
  325. if (strtolower($list[$i]["filename"]) == strtolower($filename) ||
  326. strtolower($list[$i]["stored_filename"]) == strtolower($filename)) {
  327. $listIndex = $i;
  328. break;
  329. }
  330. }
  331. return ($listIndex > -1) ? $listIndex : false;
  332. }
  333. }