TAR.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Christopher Schäpers <kondou@ts.unde.re>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Remco Brenninkmeijer <requist1@starmail.nl>
  13. * @author Robin Appelman <robin@icewind.nl>
  14. * @author Robin McCorkell <robin@mccorkell.me.uk>
  15. * @author Roeland Jago Douma <roeland@famdouma.nl>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OC\Archive;
  34. use Icewind\Streams\CallbackWrapper;
  35. class TAR extends Archive {
  36. public const PLAIN = 0;
  37. public const GZIP = 1;
  38. public const BZIP = 2;
  39. /**
  40. * @var string[]|false
  41. */
  42. private $fileList = false;
  43. /**
  44. * @var array|false
  45. */
  46. private $cachedHeaders = false;
  47. private \Archive_Tar $tar;
  48. private string $path;
  49. public function __construct(string $source) {
  50. $types = [null, 'gz', 'bz2'];
  51. $this->path = $source;
  52. $this->tar = new \Archive_Tar($source, $types[self::getTarType($source)]);
  53. }
  54. /**
  55. * try to detect the type of tar compression
  56. */
  57. public static function getTarType(string $file): int {
  58. if (strpos($file, '.')) {
  59. $extension = substr($file, strrpos($file, '.'));
  60. switch ($extension) {
  61. case '.gz':
  62. case '.tgz':
  63. return self::GZIP;
  64. case '.bz':
  65. case '.bz2':
  66. return self::BZIP;
  67. case '.tar':
  68. return self::PLAIN;
  69. default:
  70. return self::PLAIN;
  71. }
  72. } else {
  73. return self::PLAIN;
  74. }
  75. }
  76. /**
  77. * add an empty folder to the archive
  78. */
  79. public function addFolder(string $path): bool {
  80. $tmpBase = \OC::$server->getTempManager()->getTemporaryFolder();
  81. $path = rtrim($path, '/') . '/';
  82. if ($this->fileExists($path)) {
  83. return false;
  84. }
  85. $parts = explode('/', $path);
  86. $folder = $tmpBase;
  87. foreach ($parts as $part) {
  88. $folder .= '/' . $part;
  89. if (!is_dir($folder)) {
  90. mkdir($folder);
  91. }
  92. }
  93. $result = $this->tar->addModify([$tmpBase . $path], '', $tmpBase);
  94. rmdir($tmpBase . $path);
  95. $this->fileList = false;
  96. $this->cachedHeaders = false;
  97. return $result;
  98. }
  99. /**
  100. * add a file to the archive
  101. *
  102. * @param string $source either a local file or string data
  103. */
  104. public function addFile(string $path, string $source = ''): bool {
  105. if ($this->fileExists($path)) {
  106. $this->remove($path);
  107. }
  108. if ($source and $source[0] == '/' and file_exists($source)) {
  109. $source = file_get_contents($source);
  110. }
  111. $result = $this->tar->addString($path, $source);
  112. $this->fileList = false;
  113. $this->cachedHeaders = false;
  114. return $result;
  115. }
  116. /**
  117. * rename a file or folder in the archive
  118. */
  119. public function rename(string $source, string $dest): bool {
  120. //no proper way to delete, rename entire archive, rename file and remake archive
  121. $tmp = \OC::$server->getTempManager()->getTemporaryFolder();
  122. $this->tar->extract($tmp);
  123. rename($tmp . $source, $tmp . $dest);
  124. $this->tar->_close();
  125. unlink($this->path);
  126. $types = [null, 'gz', 'bz'];
  127. $this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
  128. $this->tar->createModify([$tmp], '', $tmp . '/');
  129. $this->fileList = false;
  130. $this->cachedHeaders = false;
  131. return true;
  132. }
  133. private function getHeader(string $file): ?array {
  134. if (!$this->cachedHeaders) {
  135. $this->cachedHeaders = $this->tar->listContent();
  136. }
  137. foreach ($this->cachedHeaders as $header) {
  138. if ($file == $header['filename']
  139. or $file . '/' == $header['filename']
  140. or '/' . $file . '/' == $header['filename']
  141. or '/' . $file == $header['filename']
  142. ) {
  143. return $header;
  144. }
  145. }
  146. return null;
  147. }
  148. /**
  149. * get the uncompressed size of a file in the archive
  150. */
  151. public function filesize(string $path): false|int|float {
  152. $stat = $this->getHeader($path);
  153. return $stat['size'] ?? false;
  154. }
  155. /**
  156. * get the last modified time of a file in the archive
  157. *
  158. * @return int|false
  159. */
  160. public function mtime(string $path) {
  161. $stat = $this->getHeader($path);
  162. return $stat['mtime'] ?? false;
  163. }
  164. /**
  165. * get the files in a folder
  166. */
  167. public function getFolder(string $path): array {
  168. $files = $this->getFiles();
  169. $folderContent = [];
  170. $pathLength = strlen($path);
  171. foreach ($files as $file) {
  172. if ($file[0] == '/') {
  173. $file = substr($file, 1);
  174. }
  175. if (substr($file, 0, $pathLength) == $path and $file != $path) {
  176. $result = substr($file, $pathLength);
  177. if ($pos = strpos($result, '/')) {
  178. $result = substr($result, 0, $pos + 1);
  179. }
  180. if (!in_array($result, $folderContent)) {
  181. $folderContent[] = $result;
  182. }
  183. }
  184. }
  185. return $folderContent;
  186. }
  187. /**
  188. * get all files in the archive
  189. */
  190. public function getFiles(): array {
  191. if ($this->fileList !== false) {
  192. return $this->fileList;
  193. }
  194. if ($this->cachedHeaders === false) {
  195. $headers = $this->tar->listContent();
  196. if (is_array($headers)) {
  197. $this->cachedHeaders = $headers;
  198. } else {
  199. return [];
  200. }
  201. }
  202. $files = [];
  203. foreach ($this->cachedHeaders as $header) {
  204. $files[] = $header['filename'];
  205. }
  206. $this->fileList = $files;
  207. return $files;
  208. }
  209. /**
  210. * get the content of a file
  211. *
  212. * @return string|false
  213. */
  214. public function getFile(string $path) {
  215. $string = $this->tar->extractInString($path);
  216. /** @var ?string $string */
  217. if (is_string($string)) {
  218. return $string;
  219. } else {
  220. return false;
  221. }
  222. }
  223. /**
  224. * extract a single file from the archive
  225. */
  226. public function extractFile(string $path, string $dest): bool {
  227. $tmp = \OC::$server->getTempManager()->getTemporaryFolder();
  228. if (!$this->fileExists($path)) {
  229. return false;
  230. }
  231. if ($this->fileExists('/' . $path)) {
  232. $success = $this->tar->extractList(['/' . $path], $tmp);
  233. } else {
  234. $success = $this->tar->extractList([$path], $tmp);
  235. }
  236. if ($success) {
  237. rename($tmp . $path, $dest);
  238. }
  239. \OCP\Files::rmdirr($tmp);
  240. return $success;
  241. }
  242. /**
  243. * extract the archive
  244. */
  245. public function extract(string $dest): bool {
  246. return $this->tar->extract($dest);
  247. }
  248. /**
  249. * check if a file or folder exists in the archive
  250. */
  251. public function fileExists(string $path): bool {
  252. $files = $this->getFiles();
  253. if ((in_array($path, $files)) or (in_array($path . '/', $files))) {
  254. return true;
  255. } else {
  256. $folderPath = rtrim($path, '/') . '/';
  257. $pathLength = strlen($folderPath);
  258. foreach ($files as $file) {
  259. if (strlen($file) > $pathLength and substr($file, 0, $pathLength) == $folderPath) {
  260. return true;
  261. }
  262. }
  263. }
  264. if ($path[0] != '/') { //not all programs agree on the use of a leading /
  265. return $this->fileExists('/' . $path);
  266. } else {
  267. return false;
  268. }
  269. }
  270. /**
  271. * remove a file or folder from the archive
  272. */
  273. public function remove(string $path): bool {
  274. if (!$this->fileExists($path)) {
  275. return false;
  276. }
  277. $this->fileList = false;
  278. $this->cachedHeaders = false;
  279. //no proper way to delete, extract entire archive, delete file and remake archive
  280. $tmp = \OC::$server->getTempManager()->getTemporaryFolder();
  281. $this->tar->extract($tmp);
  282. \OCP\Files::rmdirr($tmp . $path);
  283. unlink($this->path);
  284. $this->reopen();
  285. $this->tar->createModify([$tmp], '', $tmp);
  286. return true;
  287. }
  288. /**
  289. * get a file handler
  290. *
  291. * @return bool|resource
  292. */
  293. public function getStream(string $path, string $mode) {
  294. $lastPoint = strrpos($path, '.');
  295. if ($lastPoint !== false) {
  296. $ext = substr($path, $lastPoint);
  297. } else {
  298. $ext = '';
  299. }
  300. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  301. if ($this->fileExists($path)) {
  302. $this->extractFile($path, $tmpFile);
  303. } elseif ($mode == 'r' or $mode == 'rb') {
  304. return false;
  305. }
  306. if ($mode == 'r' or $mode == 'rb') {
  307. return fopen($tmpFile, $mode);
  308. } else {
  309. $handle = fopen($tmpFile, $mode);
  310. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  311. $this->writeBack($tmpFile, $path);
  312. });
  313. }
  314. }
  315. /**
  316. * write back temporary files
  317. */
  318. public function writeBack(string $tmpFile, string $path): void {
  319. $this->addFile($path, $tmpFile);
  320. unlink($tmpFile);
  321. }
  322. /**
  323. * reopen the archive to ensure everything is written
  324. */
  325. private function reopen(): void {
  326. $this->tar->_close();
  327. $types = [null, 'gz', 'bz'];
  328. $this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
  329. }
  330. /**
  331. * Get error object from archive_tar.
  332. */
  333. public function getError(): ?\PEAR_Error {
  334. if ($this->tar->error_object instanceof \PEAR_Error) {
  335. return $this->tar->error_object;
  336. }
  337. return null;
  338. }
  339. }