Local.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author aler9 <46489434+aler9@users.noreply.github.com>
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Boris Rybalkin <ribalkin@gmail.com>
  9. * @author Brice Maron <brice@bmaron.net>
  10. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  11. * @author J0WI <J0WI@users.noreply.github.com>
  12. * @author Jakob Sack <mail@jakobsack.de>
  13. * @author Joas Schilling <coding@schilljs.com>
  14. * @author Johannes Leuker <j.leuker@hosting.de>
  15. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  16. * @author Klaas Freitag <freitag@owncloud.com>
  17. * @author Lukas Reschke <lukas@statuscode.ch>
  18. * @author Martin Brugnara <martin@0x6d62.eu>
  19. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  20. * @author Morris Jobke <hey@morrisjobke.de>
  21. * @author Robin Appelman <robin@icewind.nl>
  22. * @author Roeland Jago Douma <roeland@famdouma.nl>
  23. * @author Sjors van der Pluijm <sjors@desjors.nl>
  24. * @author Stefan Weil <sw@weilnetz.de>
  25. * @author Thomas Müller <thomas.mueller@tmit.eu>
  26. * @author Tigran Mkrtchyan <tigran.mkrtchyan@desy.de>
  27. * @author Vincent Petry <vincent@nextcloud.com>
  28. *
  29. * @license AGPL-3.0
  30. *
  31. * This code is free software: you can redistribute it and/or modify
  32. * it under the terms of the GNU Affero General Public License, version 3,
  33. * as published by the Free Software Foundation.
  34. *
  35. * This program is distributed in the hope that it will be useful,
  36. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  37. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  38. * GNU Affero General Public License for more details.
  39. *
  40. * You should have received a copy of the GNU Affero General Public License, version 3,
  41. * along with this program. If not, see <http://www.gnu.org/licenses/>
  42. *
  43. */
  44. namespace OC\Files\Storage;
  45. use OC\Files\Filesystem;
  46. use OC\Files\Storage\Wrapper\Encryption;
  47. use OC\Files\Storage\Wrapper\Jail;
  48. use OCP\Constants;
  49. use OCP\Files\ForbiddenException;
  50. use OCP\Files\GenericFileException;
  51. use OCP\Files\IMimeTypeDetector;
  52. use OCP\Files\Storage\IStorage;
  53. use OCP\Files\StorageNotAvailableException;
  54. use OCP\IConfig;
  55. use OCP\Util;
  56. use Psr\Log\LoggerInterface;
  57. /**
  58. * for local filestore, we only have to map the paths
  59. */
  60. class Local extends \OC\Files\Storage\Common {
  61. protected $datadir;
  62. protected $dataDirLength;
  63. protected $realDataDir;
  64. private IConfig $config;
  65. private IMimeTypeDetector $mimeTypeDetector;
  66. private $defUMask;
  67. protected bool $unlinkOnTruncate;
  68. protected bool $caseInsensitive = false;
  69. public function __construct($arguments) {
  70. if (!isset($arguments['datadir']) || !is_string($arguments['datadir'])) {
  71. throw new \InvalidArgumentException('No data directory set for local storage');
  72. }
  73. $this->datadir = str_replace('//', '/', $arguments['datadir']);
  74. // some crazy code uses a local storage on root...
  75. if ($this->datadir === '/') {
  76. $this->realDataDir = $this->datadir;
  77. } else {
  78. $realPath = realpath($this->datadir) ?: $this->datadir;
  79. $this->realDataDir = rtrim($realPath, '/') . '/';
  80. }
  81. if (!str_ends_with($this->datadir, '/')) {
  82. $this->datadir .= '/';
  83. }
  84. $this->dataDirLength = strlen($this->realDataDir);
  85. $this->config = \OC::$server->get(IConfig::class);
  86. $this->mimeTypeDetector = \OC::$server->get(IMimeTypeDetector::class);
  87. $this->defUMask = $this->config->getSystemValue('localstorage.umask', 0022);
  88. $this->caseInsensitive = $this->config->getSystemValueBool('localstorage.case_insensitive', false);
  89. // support Write-Once-Read-Many file systems
  90. $this->unlinkOnTruncate = $this->config->getSystemValueBool('localstorage.unlink_on_truncate', false);
  91. if (isset($arguments['isExternal']) && $arguments['isExternal'] && !$this->stat('')) {
  92. // data dir not accessible or available, can happen when using an external storage of type Local
  93. // on an unmounted system mount point
  94. throw new StorageNotAvailableException('Local storage path does not exist "' . $this->getSourcePath('') . '"');
  95. }
  96. }
  97. public function __destruct() {
  98. }
  99. public function getId() {
  100. return 'local::' . $this->datadir;
  101. }
  102. public function mkdir($path) {
  103. $sourcePath = $this->getSourcePath($path);
  104. $oldMask = umask($this->defUMask);
  105. $result = @mkdir($sourcePath, 0777, true);
  106. umask($oldMask);
  107. return $result;
  108. }
  109. public function rmdir($path) {
  110. if (!$this->isDeletable($path)) {
  111. return false;
  112. }
  113. try {
  114. $it = new \RecursiveIteratorIterator(
  115. new \RecursiveDirectoryIterator($this->getSourcePath($path)),
  116. \RecursiveIteratorIterator::CHILD_FIRST
  117. );
  118. /**
  119. * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
  120. * This bug is fixed in PHP 5.5.9 or before
  121. * See #8376
  122. */
  123. $it->rewind();
  124. while ($it->valid()) {
  125. /**
  126. * @var \SplFileInfo $file
  127. */
  128. $file = $it->current();
  129. clearstatcache(true, $this->getSourcePath($file));
  130. if (in_array($file->getBasename(), ['.', '..'])) {
  131. $it->next();
  132. continue;
  133. } elseif ($file->isFile() || $file->isLink()) {
  134. unlink($file->getPathname());
  135. } elseif ($file->isDir()) {
  136. rmdir($file->getPathname());
  137. }
  138. $it->next();
  139. }
  140. clearstatcache(true, $this->getSourcePath($path));
  141. return rmdir($this->getSourcePath($path));
  142. } catch (\UnexpectedValueException $e) {
  143. return false;
  144. }
  145. }
  146. public function opendir($path) {
  147. return opendir($this->getSourcePath($path));
  148. }
  149. public function is_dir($path) {
  150. if ($this->caseInsensitive && !$this->file_exists($path)) {
  151. return false;
  152. }
  153. if (str_ends_with($path, '/')) {
  154. $path = substr($path, 0, -1);
  155. }
  156. return is_dir($this->getSourcePath($path));
  157. }
  158. public function is_file($path) {
  159. if ($this->caseInsensitive && !$this->file_exists($path)) {
  160. return false;
  161. }
  162. return is_file($this->getSourcePath($path));
  163. }
  164. public function stat($path) {
  165. $fullPath = $this->getSourcePath($path);
  166. clearstatcache(true, $fullPath);
  167. if (!file_exists($fullPath)) {
  168. return false;
  169. }
  170. $statResult = @stat($fullPath);
  171. if (PHP_INT_SIZE === 4 && $statResult && !$this->is_dir($path)) {
  172. $filesize = $this->filesize($path);
  173. $statResult['size'] = $filesize;
  174. $statResult[7] = $filesize;
  175. }
  176. if (is_array($statResult)) {
  177. $statResult['full_path'] = $fullPath;
  178. }
  179. return $statResult;
  180. }
  181. /**
  182. * @inheritdoc
  183. */
  184. public function getMetaData($path) {
  185. try {
  186. $stat = $this->stat($path);
  187. } catch (ForbiddenException $e) {
  188. return null;
  189. }
  190. if (!$stat) {
  191. return null;
  192. }
  193. $permissions = Constants::PERMISSION_SHARE;
  194. $statPermissions = $stat['mode'];
  195. $isDir = ($statPermissions & 0x4000) === 0x4000 && !($statPermissions & 0x8000);
  196. if ($statPermissions & 0x0100) {
  197. $permissions += Constants::PERMISSION_READ;
  198. }
  199. if ($statPermissions & 0x0080) {
  200. $permissions += Constants::PERMISSION_UPDATE;
  201. if ($isDir) {
  202. $permissions += Constants::PERMISSION_CREATE;
  203. }
  204. }
  205. if (!($path === '' || $path === '/')) { // deletable depends on the parents unix permissions
  206. $parent = dirname($stat['full_path']);
  207. if (is_writable($parent)) {
  208. $permissions += Constants::PERMISSION_DELETE;
  209. }
  210. }
  211. $data = [];
  212. $data['mimetype'] = $isDir ? 'httpd/unix-directory' : $this->mimeTypeDetector->detectPath($path);
  213. $data['mtime'] = $stat['mtime'];
  214. if ($data['mtime'] === false) {
  215. $data['mtime'] = time();
  216. }
  217. if ($isDir) {
  218. $data['size'] = -1; //unknown
  219. } else {
  220. $data['size'] = $stat['size'];
  221. }
  222. $data['etag'] = $this->calculateEtag($path, $stat);
  223. $data['storage_mtime'] = $data['mtime'];
  224. $data['permissions'] = $permissions;
  225. $data['name'] = basename($path);
  226. return $data;
  227. }
  228. public function filetype($path) {
  229. $filetype = filetype($this->getSourcePath($path));
  230. if ($filetype == 'link') {
  231. $filetype = filetype(realpath($this->getSourcePath($path)));
  232. }
  233. return $filetype;
  234. }
  235. public function filesize($path): false|int|float {
  236. if (!$this->is_file($path)) {
  237. return 0;
  238. }
  239. $fullPath = $this->getSourcePath($path);
  240. if (PHP_INT_SIZE === 4) {
  241. $helper = new \OC\LargeFileHelper;
  242. return $helper->getFileSize($fullPath);
  243. }
  244. return filesize($fullPath);
  245. }
  246. public function isReadable($path) {
  247. return is_readable($this->getSourcePath($path));
  248. }
  249. public function isUpdatable($path) {
  250. return is_writable($this->getSourcePath($path));
  251. }
  252. public function file_exists($path) {
  253. if ($this->caseInsensitive) {
  254. $fullPath = $this->getSourcePath($path);
  255. $content = scandir(dirname($fullPath), SCANDIR_SORT_NONE);
  256. return is_array($content) && array_search(basename($fullPath), $content) !== false;
  257. } else {
  258. return file_exists($this->getSourcePath($path));
  259. }
  260. }
  261. public function filemtime($path) {
  262. $fullPath = $this->getSourcePath($path);
  263. clearstatcache(true, $fullPath);
  264. if (!$this->file_exists($path)) {
  265. return false;
  266. }
  267. if (PHP_INT_SIZE === 4) {
  268. $helper = new \OC\LargeFileHelper();
  269. return $helper->getFileMtime($fullPath);
  270. }
  271. return filemtime($fullPath);
  272. }
  273. public function touch($path, $mtime = null) {
  274. // sets the modification time of the file to the given value.
  275. // If mtime is nil the current time is set.
  276. // note that the access time of the file always changes to the current time.
  277. if ($this->file_exists($path) and !$this->isUpdatable($path)) {
  278. return false;
  279. }
  280. $oldMask = umask($this->defUMask);
  281. if (!is_null($mtime)) {
  282. $result = @touch($this->getSourcePath($path), $mtime);
  283. } else {
  284. $result = @touch($this->getSourcePath($path));
  285. }
  286. umask($oldMask);
  287. if ($result) {
  288. clearstatcache(true, $this->getSourcePath($path));
  289. }
  290. return $result;
  291. }
  292. public function file_get_contents($path) {
  293. return file_get_contents($this->getSourcePath($path));
  294. }
  295. public function file_put_contents($path, $data) {
  296. $oldMask = umask($this->defUMask);
  297. if ($this->unlinkOnTruncate) {
  298. $this->unlink($path);
  299. }
  300. $result = file_put_contents($this->getSourcePath($path), $data);
  301. umask($oldMask);
  302. return $result;
  303. }
  304. public function unlink($path) {
  305. if ($this->is_dir($path)) {
  306. return $this->rmdir($path);
  307. } elseif ($this->is_file($path)) {
  308. return unlink($this->getSourcePath($path));
  309. } else {
  310. return false;
  311. }
  312. }
  313. private function checkTreeForForbiddenItems(string $path) {
  314. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
  315. foreach ($iterator as $file) {
  316. /** @var \SplFileInfo $file */
  317. if (Filesystem::isFileBlacklisted($file->getBasename())) {
  318. throw new ForbiddenException('Invalid path: ' . $file->getPathname(), false);
  319. }
  320. }
  321. }
  322. public function rename($source, $target): bool {
  323. $srcParent = dirname($source);
  324. $dstParent = dirname($target);
  325. if (!$this->isUpdatable($srcParent)) {
  326. \OC::$server->get(LoggerInterface::class)->error('unable to rename, source directory is not writable : ' . $srcParent, ['app' => 'core']);
  327. return false;
  328. }
  329. if (!$this->isUpdatable($dstParent)) {
  330. \OC::$server->get(LoggerInterface::class)->error('unable to rename, destination directory is not writable : ' . $dstParent, ['app' => 'core']);
  331. return false;
  332. }
  333. if (!$this->file_exists($source)) {
  334. \OC::$server->get(LoggerInterface::class)->error('unable to rename, file does not exists : ' . $source, ['app' => 'core']);
  335. return false;
  336. }
  337. if ($this->is_dir($target)) {
  338. $this->rmdir($target);
  339. } elseif ($this->is_file($target)) {
  340. $this->unlink($target);
  341. }
  342. if ($this->is_dir($source)) {
  343. $this->checkTreeForForbiddenItems($this->getSourcePath($source));
  344. }
  345. if (@rename($this->getSourcePath($source), $this->getSourcePath($target))) {
  346. if ($this->caseInsensitive) {
  347. if (mb_strtolower($target) === mb_strtolower($source) && !$this->file_exists($target)) {
  348. return false;
  349. }
  350. }
  351. return true;
  352. }
  353. return $this->copy($source, $target) && $this->unlink($source);
  354. }
  355. public function copy($source, $target) {
  356. if ($this->is_dir($source)) {
  357. return parent::copy($source, $target);
  358. } else {
  359. $oldMask = umask($this->defUMask);
  360. if ($this->unlinkOnTruncate) {
  361. $this->unlink($target);
  362. }
  363. $result = copy($this->getSourcePath($source), $this->getSourcePath($target));
  364. umask($oldMask);
  365. if ($this->caseInsensitive) {
  366. if (mb_strtolower($target) === mb_strtolower($source) && !$this->file_exists($target)) {
  367. return false;
  368. }
  369. }
  370. return $result;
  371. }
  372. }
  373. public function fopen($path, $mode) {
  374. $sourcePath = $this->getSourcePath($path);
  375. if (!file_exists($sourcePath) && $mode === 'r') {
  376. return false;
  377. }
  378. $oldMask = umask($this->defUMask);
  379. if (($mode === 'w' || $mode === 'w+') && $this->unlinkOnTruncate) {
  380. $this->unlink($path);
  381. }
  382. $result = @fopen($sourcePath, $mode);
  383. umask($oldMask);
  384. return $result;
  385. }
  386. public function hash($type, $path, $raw = false) {
  387. return hash_file($type, $this->getSourcePath($path), $raw);
  388. }
  389. public function free_space($path) {
  390. $sourcePath = $this->getSourcePath($path);
  391. // using !is_dir because $sourcePath might be a part file or
  392. // non-existing file, so we'd still want to use the parent dir
  393. // in such cases
  394. if (!is_dir($sourcePath)) {
  395. // disk_free_space doesn't work on files
  396. $sourcePath = dirname($sourcePath);
  397. }
  398. $space = (function_exists('disk_free_space') && is_dir($sourcePath)) ? disk_free_space($sourcePath) : false;
  399. if ($space === false || is_null($space)) {
  400. return \OCP\Files\FileInfo::SPACE_UNKNOWN;
  401. }
  402. return Util::numericToNumber($space);
  403. }
  404. public function search($query) {
  405. return $this->searchInDir($query);
  406. }
  407. public function getLocalFile($path) {
  408. return $this->getSourcePath($path);
  409. }
  410. /**
  411. * @param string $query
  412. * @param string $dir
  413. * @return array
  414. */
  415. protected function searchInDir($query, $dir = '') {
  416. $files = [];
  417. $physicalDir = $this->getSourcePath($dir);
  418. foreach (scandir($physicalDir) as $item) {
  419. if (\OC\Files\Filesystem::isIgnoredDir($item)) {
  420. continue;
  421. }
  422. $physicalItem = $physicalDir . '/' . $item;
  423. if (strstr(strtolower($item), strtolower($query)) !== false) {
  424. $files[] = $dir . '/' . $item;
  425. }
  426. if (is_dir($physicalItem)) {
  427. $files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
  428. }
  429. }
  430. return $files;
  431. }
  432. /**
  433. * check if a file or folder has been updated since $time
  434. *
  435. * @param string $path
  436. * @param int $time
  437. * @return bool
  438. */
  439. public function hasUpdated($path, $time) {
  440. if ($this->file_exists($path)) {
  441. return $this->filemtime($path) > $time;
  442. } else {
  443. return true;
  444. }
  445. }
  446. /**
  447. * Get the source path (on disk) of a given path
  448. *
  449. * @param string $path
  450. * @return string
  451. * @throws ForbiddenException
  452. */
  453. public function getSourcePath($path) {
  454. if (Filesystem::isFileBlacklisted($path)) {
  455. throw new ForbiddenException('Invalid path: ' . $path, false);
  456. }
  457. $fullPath = $this->datadir . $path;
  458. $currentPath = $path;
  459. $allowSymlinks = $this->config->getSystemValueBool('localstorage.allowsymlinks', false);
  460. if ($allowSymlinks || $currentPath === '') {
  461. return $fullPath;
  462. }
  463. $pathToResolve = $fullPath;
  464. $realPath = realpath($pathToResolve);
  465. while ($realPath === false) { // for non existing files check the parent directory
  466. $currentPath = dirname($currentPath);
  467. if ($currentPath === '' || $currentPath === '.') {
  468. return $fullPath;
  469. }
  470. $realPath = realpath($this->datadir . $currentPath);
  471. }
  472. if ($realPath) {
  473. $realPath = $realPath . '/';
  474. }
  475. if (substr($realPath, 0, $this->dataDirLength) === $this->realDataDir) {
  476. return $fullPath;
  477. }
  478. \OC::$server->get(LoggerInterface::class)->error("Following symlinks is not allowed ('$fullPath' -> '$realPath' not inside '{$this->realDataDir}')", ['app' => 'core']);
  479. throw new ForbiddenException('Following symlinks is not allowed', false);
  480. }
  481. /**
  482. * {@inheritdoc}
  483. */
  484. public function isLocal() {
  485. return true;
  486. }
  487. /**
  488. * get the ETag for a file or folder
  489. *
  490. * @param string $path
  491. * @return string
  492. */
  493. public function getETag($path) {
  494. return $this->calculateEtag($path, $this->stat($path));
  495. }
  496. private function calculateEtag(string $path, array $stat): string {
  497. if ($stat['mode'] & 0x4000 && !($stat['mode'] & 0x8000)) { // is_dir & not socket
  498. return parent::getETag($path);
  499. } else {
  500. if ($stat === false) {
  501. return md5('');
  502. }
  503. $toHash = '';
  504. if (isset($stat['mtime'])) {
  505. $toHash .= $stat['mtime'];
  506. }
  507. if (isset($stat['ino'])) {
  508. $toHash .= $stat['ino'];
  509. }
  510. if (isset($stat['dev'])) {
  511. $toHash .= $stat['dev'];
  512. }
  513. if (isset($stat['size'])) {
  514. $toHash .= $stat['size'];
  515. }
  516. return md5($toHash);
  517. }
  518. }
  519. private function canDoCrossStorageMove(IStorage $sourceStorage) {
  520. return $sourceStorage->instanceOfStorage(Local::class)
  521. // Don't treat ACLStorageWrapper like local storage where copy can be done directly.
  522. // Instead, use the slower recursive copying in php from Common::copyFromStorage with
  523. // more permissions checks.
  524. && !$sourceStorage->instanceOfStorage('OCA\GroupFolders\ACL\ACLStorageWrapper')
  525. // when moving encrypted files we have to handle keys and the target might not be encrypted
  526. && !$sourceStorage->instanceOfStorage(Encryption::class);
  527. }
  528. /**
  529. * @param IStorage $sourceStorage
  530. * @param string $sourceInternalPath
  531. * @param string $targetInternalPath
  532. * @param bool $preserveMtime
  533. * @return bool
  534. */
  535. public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
  536. if ($this->canDoCrossStorageMove($sourceStorage)) {
  537. if ($sourceStorage->instanceOfStorage(Jail::class)) {
  538. /**
  539. * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
  540. */
  541. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  542. }
  543. /**
  544. * @var \OC\Files\Storage\Local $sourceStorage
  545. */
  546. $rootStorage = new Local(['datadir' => '/']);
  547. return $rootStorage->copy($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
  548. } else {
  549. return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  550. }
  551. }
  552. /**
  553. * @param IStorage $sourceStorage
  554. * @param string $sourceInternalPath
  555. * @param string $targetInternalPath
  556. * @return bool
  557. */
  558. public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
  559. if ($this->canDoCrossStorageMove($sourceStorage)) {
  560. if ($sourceStorage->instanceOfStorage(Jail::class)) {
  561. /**
  562. * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
  563. */
  564. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  565. }
  566. /**
  567. * @var \OC\Files\Storage\Local $sourceStorage
  568. */
  569. $rootStorage = new Local(['datadir' => '/']);
  570. return $rootStorage->rename($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
  571. } else {
  572. return parent::moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  573. }
  574. }
  575. public function writeStream(string $path, $stream, int $size = null): int {
  576. /** @var int|false $result We consider here that returned size will never be a float because we write less than 4GB */
  577. $result = $this->file_put_contents($path, $stream);
  578. if (is_resource($stream)) {
  579. fclose($stream);
  580. }
  581. if ($result === false) {
  582. throw new GenericFileException("Failed write stream to $path");
  583. } else {
  584. return $result;
  585. }
  586. }
  587. }