You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2200 lines
64 KiB

3 years ago
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Florin Peter <github@florin-peter.de>
  10. * @author Jesús Macias <jmacias@solidgear.es>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  13. * @author Julius Härtl <jus@bitgrid.net>
  14. * @author karakayasemi <karakayasemi@itu.edu.tr>
  15. * @author Klaas Freitag <freitag@owncloud.com>
  16. * @author korelstar <korelstar@users.noreply.github.com>
  17. * @author Lukas Reschke <lukas@statuscode.ch>
  18. * @author Luke Policinski <lpolicinski@gmail.com>
  19. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  20. * @author Morris Jobke <hey@morrisjobke.de>
  21. * @author Piotr Filiciak <piotr@filiciak.pl>
  22. * @author Robin Appelman <robin@icewind.nl>
  23. * @author Robin McCorkell <robin@mccorkell.me.uk>
  24. * @author Roeland Jago Douma <roeland@famdouma.nl>
  25. * @author Sam Tuke <mail@samtuke.com>
  26. * @author Scott Dutton <exussum12@users.noreply.github.com>
  27. * @author Thomas Müller <thomas.mueller@tmit.eu>
  28. * @author Thomas Tanghus <thomas@tanghus.net>
  29. * @author Vincent Petry <pvince81@owncloud.com>
  30. *
  31. * @license AGPL-3.0
  32. *
  33. * This code is free software: you can redistribute it and/or modify
  34. * it under the terms of the GNU Affero General Public License, version 3,
  35. * as published by the Free Software Foundation.
  36. *
  37. * This program is distributed in the hope that it will be useful,
  38. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  39. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  40. * GNU Affero General Public License for more details.
  41. *
  42. * You should have received a copy of the GNU Affero General Public License, version 3,
  43. * along with this program. If not, see <http://www.gnu.org/licenses/>
  44. *
  45. */
  46. namespace OC\Files;
  47. use Icewind\Streams\CallbackWrapper;
  48. use OC\Files\Mount\MoveableMount;
  49. use OC\Files\Storage\Storage;
  50. use OC\User\User;
  51. use OCA\Files_Sharing\SharedMount;
  52. use OCP\Constants;
  53. use OCP\Files\Cache\ICacheEntry;
  54. use OCP\Files\EmptyFileNameException;
  55. use OCP\Files\FileNameTooLongException;
  56. use OCP\Files\InvalidCharacterInPathException;
  57. use OCP\Files\InvalidDirectoryException;
  58. use OCP\Files\InvalidPathException;
  59. use OCP\Files\Mount\IMountPoint;
  60. use OCP\Files\NotFoundException;
  61. use OCP\Files\ReservedWordException;
  62. use OCP\Files\Storage\IStorage;
  63. use OCP\ILogger;
  64. use OCP\IUser;
  65. use OCP\Lock\ILockingProvider;
  66. use OCP\Lock\LockedException;
  67. /**
  68. * Class to provide access to ownCloud filesystem via a "view", and methods for
  69. * working with files within that view (e.g. read, write, delete, etc.). Each
  70. * view is restricted to a set of directories via a virtual root. The default view
  71. * uses the currently logged in user's data directory as root (parts of
  72. * OC_Filesystem are merely a wrapper for OC\Files\View).
  73. *
  74. * Apps that need to access files outside of the user data folders (to modify files
  75. * belonging to a user other than the one currently logged in, for example) should
  76. * use this class directly rather than using OC_Filesystem, or making use of PHP's
  77. * built-in file manipulation functions. This will ensure all hooks and proxies
  78. * are triggered correctly.
  79. *
  80. * Filesystem functions are not called directly; they are passed to the correct
  81. * \OC\Files\Storage\Storage object
  82. */
  83. class View {
  84. /** @var string */
  85. private $fakeRoot = '';
  86. /**
  87. * @var \OCP\Lock\ILockingProvider
  88. */
  89. protected $lockingProvider;
  90. private $lockingEnabled;
  91. private $updaterEnabled = true;
  92. /** @var \OC\User\Manager */
  93. private $userManager;
  94. /** @var \OCP\ILogger */
  95. private $logger;
  96. /**
  97. * @param string $root
  98. * @throws \Exception If $root contains an invalid path
  99. */
  100. public function __construct($root = '') {
  101. if (is_null($root)) {
  102. throw new \InvalidArgumentException('Root can\'t be null');
  103. }
  104. if (!Filesystem::isValidPath($root)) {
  105. throw new \Exception();
  106. }
  107. $this->fakeRoot = $root;
  108. $this->lockingProvider = \OC::$server->getLockingProvider();
  109. $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
  110. $this->userManager = \OC::$server->getUserManager();
  111. $this->logger = \OC::$server->getLogger();
  112. }
  113. public function getAbsolutePath($path = '/') {
  114. if ($path === null) {
  115. return null;
  116. }
  117. $this->assertPathLength($path);
  118. if ($path === '') {
  119. $path = '/';
  120. }
  121. if ($path[0] !== '/') {
  122. $path = '/' . $path;
  123. }
  124. return $this->fakeRoot . $path;
  125. }
  126. /**
  127. * change the root to a fake root
  128. *
  129. * @param string $fakeRoot
  130. * @return boolean|null
  131. */
  132. public function chroot($fakeRoot) {
  133. if (!$fakeRoot == '') {
  134. if ($fakeRoot[0] !== '/') {
  135. $fakeRoot = '/' . $fakeRoot;
  136. }
  137. }
  138. $this->fakeRoot = $fakeRoot;
  139. }
  140. /**
  141. * get the fake root
  142. *
  143. * @return string
  144. */
  145. public function getRoot() {
  146. return $this->fakeRoot;
  147. }
  148. /**
  149. * get path relative to the root of the view
  150. *
  151. * @param string $path
  152. * @return string
  153. */
  154. public function getRelativePath($path) {
  155. $this->assertPathLength($path);
  156. if ($this->fakeRoot == '') {
  157. return $path;
  158. }
  159. if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
  160. return '/';
  161. }
  162. // missing slashes can cause wrong matches!
  163. $root = rtrim($this->fakeRoot, '/') . '/';
  164. if (strpos($path, $root) !== 0) {
  165. return null;
  166. } else {
  167. $path = substr($path, strlen($this->fakeRoot));
  168. if (strlen($path) === 0) {
  169. return '/';
  170. } else {
  171. return $path;
  172. }
  173. }
  174. }
  175. /**
  176. * get the mountpoint of the storage object for a path
  177. * ( note: because a storage is not always mounted inside the fakeroot, the
  178. * returned mountpoint is relative to the absolute root of the filesystem
  179. * and does not take the chroot into account )
  180. *
  181. * @param string $path
  182. * @return string
  183. */
  184. public function getMountPoint($path) {
  185. return Filesystem::getMountPoint($this->getAbsolutePath($path));
  186. }
  187. /**
  188. * get the mountpoint of the storage object for a path
  189. * ( note: because a storage is not always mounted inside the fakeroot, the
  190. * returned mountpoint is relative to the absolute root of the filesystem
  191. * and does not take the chroot into account )
  192. *
  193. * @param string $path
  194. * @return \OCP\Files\Mount\IMountPoint
  195. */
  196. public function getMount($path) {
  197. return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
  198. }
  199. /**
  200. * resolve a path to a storage and internal path
  201. *
  202. * @param string $path
  203. * @return array an array consisting of the storage and the internal path
  204. */
  205. public function resolvePath($path) {
  206. $a = $this->getAbsolutePath($path);
  207. $p = Filesystem::normalizePath($a);
  208. return Filesystem::resolvePath($p);
  209. }
  210. /**
  211. * return the path to a local version of the file
  212. * we need this because we can't know if a file is stored local or not from
  213. * outside the filestorage and for some purposes a local file is needed
  214. *
  215. * @param string $path
  216. * @return string
  217. */
  218. public function getLocalFile($path) {
  219. $parent = substr($path, 0, strrpos($path, '/'));
  220. $path = $this->getAbsolutePath($path);
  221. [$storage, $internalPath] = Filesystem::resolvePath($path);
  222. if (Filesystem::isValidPath($parent) and $storage) {
  223. return $storage->getLocalFile($internalPath);
  224. } else {
  225. return null;
  226. }
  227. }
  228. /**
  229. * @param string $path
  230. * @return string
  231. */
  232. public function getLocalFolder($path) {
  233. $parent = substr($path, 0, strrpos($path, '/'));
  234. $path = $this->getAbsolutePath($path);
  235. [$storage, $internalPath] = Filesystem::resolvePath($path);
  236. if (Filesystem::isValidPath($parent) and $storage) {
  237. return $storage->getLocalFolder($internalPath);
  238. } else {
  239. return null;
  240. }
  241. }
  242. /**
  243. * the following functions operate with arguments and return values identical
  244. * to those of their PHP built-in equivalents. Mostly they are merely wrappers
  245. * for \OC\Files\Storage\Storage via basicOperation().
  246. */
  247. public function mkdir($path) {
  248. return $this->basicOperation('mkdir', $path, ['create', 'write']);
  249. }
  250. /**
  251. * remove mount point
  252. *
  253. * @param \OC\Files\Mount\MoveableMount $mount
  254. * @param string $path relative to data/
  255. * @return boolean
  256. */
  257. protected function removeMount($mount, $path) {
  258. if ($mount instanceof MoveableMount) {
  259. // cut of /user/files to get the relative path to data/user/files
  260. $pathParts = explode('/', $path, 4);
  261. $relPath = '/' . $pathParts[3];
  262. $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
  263. \OC_Hook::emit(
  264. Filesystem::CLASSNAME, "umount",
  265. [Filesystem::signal_param_path => $relPath]
  266. );
  267. $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
  268. $result = $mount->removeMount();
  269. $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
  270. if ($result) {
  271. \OC_Hook::emit(
  272. Filesystem::CLASSNAME, "post_umount",
  273. [Filesystem::signal_param_path => $relPath]
  274. );
  275. }
  276. $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
  277. return $result;
  278. } else {
  279. // do not allow deleting the storage's root / the mount point
  280. // because for some storages it might delete the whole contents
  281. // but isn't supposed to work that way
  282. return false;
  283. }
  284. }
  285. public function disableCacheUpdate() {
  286. $this->updaterEnabled = false;
  287. }
  288. public function enableCacheUpdate() {
  289. $this->updaterEnabled = true;
  290. }
  291. protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
  292. if ($this->updaterEnabled) {
  293. if (is_null($time)) {
  294. $time = time();
  295. }
  296. $storage->getUpdater()->update($internalPath, $time);
  297. }
  298. }
  299. protected function removeUpdate(Storage $storage, $internalPath) {
  300. if ($this->updaterEnabled) {
  301. $storage->getUpdater()->remove($internalPath);
  302. }
  303. }
  304. protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
  305. if ($this->updaterEnabled) {
  306. $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  307. }
  308. }
  309. /**
  310. * @param string $path
  311. * @return bool|mixed
  312. */
  313. public function rmdir($path) {
  314. $absolutePath = $this->getAbsolutePath($path);
  315. $mount = Filesystem::getMountManager()->find($absolutePath);
  316. if ($mount->getInternalPath($absolutePath) === '') {
  317. return $this->removeMount($mount, $absolutePath);
  318. }
  319. if ($this->is_dir($path)) {
  320. $result = $this->basicOperation('rmdir', $path, ['delete']);
  321. } else {
  322. $result = false;
  323. }
  324. if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
  325. $storage = $mount->getStorage();
  326. $internalPath = $mount->getInternalPath($absolutePath);
  327. $storage->getUpdater()->remove($internalPath);
  328. }
  329. return $result;
  330. }
  331. /**
  332. * @param string $path
  333. * @return resource
  334. */
  335. public function opendir($path) {
  336. return $this->basicOperation('opendir', $path, ['read']);
  337. }
  338. /**
  339. * @param string $path
  340. * @return bool|mixed
  341. */
  342. public function is_dir($path) {
  343. if ($path == '/') {
  344. return true;
  345. }
  346. return $this->basicOperation('is_dir', $path);
  347. }
  348. /**
  349. * @param string $path
  350. * @return bool|mixed
  351. */
  352. public function is_file($path) {
  353. if ($path == '/') {
  354. return false;
  355. }
  356. return $this->basicOperation('is_file', $path);
  357. }
  358. /**
  359. * @param string $path
  360. * @return mixed
  361. */
  362. public function stat($path) {
  363. return $this->basicOperation('stat', $path);
  364. }
  365. /**
  366. * @param string $path
  367. * @return mixed
  368. */
  369. public function filetype($path) {
  370. return $this->basicOperation('filetype', $path);
  371. }
  372. /**
  373. * @param string $path
  374. * @return mixed
  375. */
  376. public function filesize($path) {
  377. return $this->basicOperation('filesize', $path);
  378. }
  379. /**
  380. * @param string $path
  381. * @return bool|mixed
  382. * @throws \OCP\Files\InvalidPathException
  383. */
  384. public function readfile($path) {
  385. $this->assertPathLength($path);
  386. @ob_end_clean();
  387. $handle = $this->fopen($path, 'rb');
  388. if ($handle) {
  389. $chunkSize = 524288; // 512 kB chunks
  390. while (!feof($handle)) {
  391. echo fread($handle, $chunkSize);
  392. flush();
  393. }
  394. fclose($handle);
  395. return $this->filesize($path);
  396. }
  397. return false;
  398. }
  399. /**
  400. * @param string $path
  401. * @param int $from
  402. * @param int $to
  403. * @return bool|mixed
  404. * @throws \OCP\Files\InvalidPathException
  405. * @throws \OCP\Files\UnseekableException
  406. */
  407. public function readfilePart($path, $from, $to) {
  408. $this->assertPathLength($path);
  409. @ob_end_clean();
  410. $handle = $this->fopen($path, 'rb');
  411. if ($handle) {
  412. $chunkSize = 524288; // 512 kB chunks
  413. $startReading = true;
  414. if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
  415. // forward file handle via chunked fread because fseek seem to have failed
  416. $end = $from + 1;
  417. while (!feof($handle) && ftell($handle) < $end) {
  418. $len = $from - ftell($handle);
  419. if ($len > $chunkSize) {
  420. $len = $chunkSize;
  421. }
  422. $result = fread($handle, $len);
  423. if ($result === false) {
  424. $startReading = false;
  425. break;
  426. }
  427. }
  428. }
  429. if ($startReading) {
  430. $end = $to + 1;
  431. while (!feof($handle) && ftell($handle) < $end) {
  432. $len = $end - ftell($handle);
  433. if ($len > $chunkSize) {
  434. $len = $chunkSize;
  435. }
  436. echo fread($handle, $len);
  437. flush();
  438. }
  439. return ftell($handle) - $from;
  440. }
  441. throw new \OCP\Files\UnseekableException('fseek error');
  442. }
  443. return false;
  444. }
  445. /**
  446. * @param string $path
  447. * @return mixed
  448. */
  449. public function isCreatable($path) {
  450. return $this->basicOperation('isCreatable', $path);
  451. }
  452. /**
  453. * @param string $path
  454. * @return mixed
  455. */
  456. public function isReadable($path) {
  457. return $this->basicOperation('isReadable', $path);
  458. }
  459. /**
  460. * @param string $path
  461. * @return mixed
  462. */
  463. public function isUpdatable($path) {
  464. return $this->basicOperation('isUpdatable', $path);
  465. }
  466. /**
  467. * @param string $path
  468. * @return bool|mixed
  469. */
  470. public function isDeletable($path) {
  471. $absolutePath = $this->getAbsolutePath($path);
  472. $mount = Filesystem::getMountManager()->find($absolutePath);
  473. if ($mount->getInternalPath($absolutePath) === '') {
  474. return $mount instanceof MoveableMount;
  475. }
  476. return $this->basicOperation('isDeletable', $path);
  477. }
  478. /**
  479. * @param string $path
  480. * @return mixed
  481. */
  482. public function isSharable($path) {
  483. return $this->basicOperation('isSharable', $path);
  484. }
  485. /**
  486. * @param string $path
  487. * @return bool|mixed
  488. */
  489. public function file_exists($path) {
  490. if ($path == '/') {
  491. return true;
  492. }
  493. return $this->basicOperation('file_exists', $path);
  494. }
  495. /**
  496. * @param string $path
  497. * @return mixed
  498. */
  499. public function filemtime($path) {
  500. return $this->basicOperation('filemtime', $path);
  501. }
  502. /**
  503. * @param string $path
  504. * @param int|string $mtime
  505. * @return bool
  506. */
  507. public function touch($path, $mtime = null) {
  508. if (!is_null($mtime) and !is_numeric($mtime)) {
  509. $mtime = strtotime($mtime);
  510. }
  511. $hooks = ['touch'];
  512. if (!$this->file_exists($path)) {
  513. $hooks[] = 'create';
  514. $hooks[] = 'write';
  515. }
  516. try {
  517. $result = $this->basicOperation('touch', $path, $hooks, $mtime);
  518. } catch (\Exception $e) {
  519. $this->logger->logException($e, ['level' => ILogger::INFO, 'message' => 'Error while setting modified time']);
  520. $result = false;
  521. }
  522. if (!$result) {
  523. // If create file fails because of permissions on external storage like SMB folders,
  524. // check file exists and return false if not.
  525. if (!$this->file_exists($path)) {
  526. return false;
  527. }
  528. if (is_null($mtime)) {
  529. $mtime = time();
  530. }
  531. //if native touch fails, we emulate it by changing the mtime in the cache
  532. $this->putFileInfo($path, ['mtime' => floor($mtime)]);
  533. }
  534. return true;
  535. }
  536. /**
  537. * @param string $path
  538. * @return mixed
  539. * @throws LockedException
  540. */
  541. public function file_get_contents($path) {
  542. return $this->basicOperation('file_get_contents', $path, ['read']);
  543. }
  544. /**
  545. * @param bool $exists
  546. * @param string $path
  547. * @param bool $run
  548. */
  549. protected function emit_file_hooks_pre($exists, $path, &$run) {
  550. if (!$exists) {
  551. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
  552. Filesystem::signal_param_path => $this->getHookPath($path),
  553. Filesystem::signal_param_run => &$run,
  554. ]);
  555. } else {
  556. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
  557. Filesystem::signal_param_path => $this->getHookPath($path),
  558. Filesystem::signal_param_run => &$run,
  559. ]);
  560. }
  561. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
  562. Filesystem::signal_param_path => $this->getHookPath($path),
  563. Filesystem::signal_param_run => &$run,
  564. ]);
  565. }
  566. /**
  567. * @param bool $exists
  568. * @param string $path
  569. */
  570. protected function emit_file_hooks_post($exists, $path) {
  571. if (!$exists) {
  572. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
  573. Filesystem::signal_param_path => $this->getHookPath($path),
  574. ]);
  575. } else {
  576. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
  577. Filesystem::signal_param_path => $this->getHookPath($path),
  578. ]);
  579. }
  580. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
  581. Filesystem::signal_param_path => $this->getHookPath($path),
  582. ]);
  583. }
  584. /**
  585. * @param string $path
  586. * @param string|resource $data
  587. * @return bool|mixed
  588. * @throws LockedException
  589. */
  590. public function file_put_contents($path, $data) {
  591. if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
  592. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  593. if (Filesystem::isValidPath($path)
  594. and !Filesystem::isFileBlacklisted($path)
  595. ) {
  596. $path = $this->getRelativePath($absolutePath);
  597. $this->lockFile($path, ILockingProvider::LOCK_SHARED);
  598. $exists = $this->file_exists($path);
  599. $run = true;
  600. if ($this->shouldEmitHooks($path)) {
  601. $this->emit_file_hooks_pre($exists, $path, $run);
  602. }
  603. if (!$run) {
  604. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  605. return false;
  606. }
  607. $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
  608. /** @var \OC\Files\Storage\Storage $storage */
  609. [$storage, $internalPath] = $this->resolvePath($path);
  610. $target = $storage->fopen($internalPath, 'w');
  611. if ($target) {
  612. [, $result] = \OC_Helper::streamCopy($data, $target);
  613. fclose($target);
  614. fclose($data);
  615. $this->writeUpdate($storage, $internalPath);
  616. $this->changeLock($path, ILockingProvider::LOCK_SHARED);
  617. if ($this->shouldEmitHooks($path) && $result !== false) {
  618. $this->emit_file_hooks_post($exists, $path);
  619. }
  620. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  621. return $result;
  622. } else {
  623. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  624. return false;
  625. }
  626. } else {
  627. return false;
  628. }
  629. } else {
  630. $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
  631. return $this->basicOperation('file_put_contents', $path, $hooks, $data);
  632. }
  633. }
  634. /**
  635. * @param string $path
  636. * @return bool|mixed
  637. */
  638. public function unlink($path) {
  639. if ($path === '' || $path === '/') {
  640. // do not allow deleting the root
  641. return false;
  642. }
  643. $postFix = (substr($path, -1) === '/') ? '/' : '';
  644. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  645. $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
  646. if ($mount and $mount->getInternalPath($absolutePath) === '') {
  647. return $this->removeMount($mount, $absolutePath);
  648. }
  649. if ($this->is_dir($path)) {
  650. $result = $this->basicOperation('rmdir', $path, ['delete']);
  651. } else {
  652. $result = $this->basicOperation('unlink', $path, ['delete']);
  653. }
  654. if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
  655. $storage = $mount->getStorage();
  656. $internalPath = $mount->getInternalPath($absolutePath);
  657. $storage->getUpdater()->remove($internalPath);
  658. return true;
  659. } else {
  660. return $result;
  661. }
  662. }
  663. /**
  664. * @param string $directory
  665. * @return bool|mixed
  666. */
  667. public function deleteAll($directory) {
  668. return $this->rmdir($directory);
  669. }
  670. /**
  671. * Rename/move a file or folder from the source path to target path.
  672. *
  673. * @param string $path1 source path
  674. * @param string $path2 target path
  675. *
  676. * @return bool|mixed
  677. * @throws LockedException
  678. */
  679. public function rename($path1, $path2) {
  680. $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
  681. $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
  682. $result = false;
  683. if (
  684. Filesystem::isValidPath($path2)
  685. and Filesystem::isValidPath($path1)
  686. and !Filesystem::isFileBlacklisted($path2)
  687. ) {
  688. $path1 = $this->getRelativePath($absolutePath1);
  689. $path2 = $this->getRelativePath($absolutePath2);
  690. $exists = $this->file_exists($path2);
  691. if ($path1 == null or $path2 == null) {
  692. return false;
  693. }
  694. $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
  695. try {
  696. $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
  697. $run = true;
  698. if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
  699. // if it was a rename from a part file to a regular file it was a write and not a rename operation
  700. $this->emit_file_hooks_pre($exists, $path2, $run);
  701. } elseif ($this->shouldEmitHooks($path1)) {
  702. \OC_Hook::emit(
  703. Filesystem::CLASSNAME, Filesystem::signal_rename,
  704. [
  705. Filesystem::signal_param_oldpath => $this->getHookPath($path1),
  706. Filesystem::signal_param_newpath => $this->getHookPath($path2),
  707. Filesystem::signal_param_run => &$run
  708. ]
  709. );
  710. }
  711. if ($run) {
  712. $this->verifyPath(dirname($path2), basename($path2));
  713. $manager = Filesystem::getMountManager();
  714. $mount1 = $this->getMount($path1);
  715. $mount2 = $this->getMount($path2);
  716. $storage1 = $mount1->getStorage();
  717. $storage2 = $mount2->getStorage();
  718. $internalPath1 = $mount1->getInternalPath($absolutePath1);
  719. $internalPath2 = $mount2->getInternalPath($absolutePath2);
  720. $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
  721. try {
  722. $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
  723. if ($internalPath1 === '') {
  724. if ($mount1 instanceof MoveableMount) {
  725. $sourceParentMount = $this->getMount(dirname($path1));
  726. if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
  727. /**
  728. * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
  729. */
  730. $sourceMountPoint = $mount1->getMountPoint();
  731. $result = $mount1->moveMount($absolutePath2);
  732. $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
  733. } else {
  734. $result = false;
  735. }
  736. } else {
  737. $result = false;
  738. }
  739. // moving a file/folder within the same mount point
  740. } elseif ($storage1 === $storage2) {
  741. if ($storage1) {
  742. $result = $storage1->rename($internalPath1, $internalPath2);
  743. } else {
  744. $result = false;
  745. }
  746. // moving a file/folder between storages (from $storage1 to $storage2)
  747. } else {
  748. $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
  749. }
  750. if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
  751. // if it was a rename from a part file to a regular file it was a write and not a rename operation
  752. $this->writeUpdate($storage2, $internalPath2);
  753. } elseif ($result) {
  754. if ($internalPath1 !== '') { // don't do a cache update for moved mounts
  755. $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
  756. }
  757. }
  758. } catch (\Exception $e) {
  759. throw $e;
  760. } finally {
  761. $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
  762. $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
  763. }
  764. if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
  765. if ($this->shouldEmitHooks()) {
  766. $this->emit_file_hooks_post($exists, $path2);
  767. }
  768. } elseif ($result) {
  769. if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
  770. \OC_Hook::emit(
  771. Filesystem::CLASSNAME,
  772. Filesystem::signal_post_rename,
  773. [
  774. Filesystem::signal_param_oldpath => $this->getHookPath($path1),
  775. Filesystem::signal_param_newpath => $this->getHookPath($path2)
  776. ]
  777. );
  778. }
  779. }
  780. }
  781. } catch (\Exception $e) {
  782. throw $e;
  783. } finally {
  784. $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
  785. $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
  786. }
  787. }
  788. return $result;
  789. }
  790. /**
  791. * Copy a file/folder from the source path to target path
  792. *
  793. * @param string $path1 source path
  794. * @param string $path2 target path
  795. * @param bool $preserveMtime whether to preserve mtime on the copy
  796. *
  797. * @return bool|mixed
  798. */
  799. public function copy($path1, $path2, $preserveMtime = false) {
  800. $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
  801. $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
  802. $result = false;
  803. if (
  804. Filesystem::isValidPath($path2)
  805. and Filesystem::isValidPath($path1)
  806. and !Filesystem::isFileBlacklisted($path2)
  807. ) {
  808. $path1 = $this->getRelativePath($absolutePath1);
  809. $path2 = $this->getRelativePath($absolutePath2);
  810. if ($path1 == null or $path2 == null) {
  811. return false;
  812. }
  813. $run = true;
  814. $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
  815. $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
  816. $lockTypePath1 = ILockingProvider::LOCK_SHARED;
  817. $lockTypePath2 = ILockingProvider::LOCK_SHARED;
  818. try {
  819. $exists = $this->file_exists($path2);
  820. if ($this->shouldEmitHooks()) {
  821. \OC_Hook::emit(
  822. Filesystem::CLASSNAME,
  823. Filesystem::signal_copy,
  824. [
  825. Filesystem::signal_param_oldpath => $this->getHookPath($path1),
  826. Filesystem::signal_param_newpath => $this->getHookPath($path2),
  827. Filesystem::signal_param_run => &$run
  828. ]
  829. );
  830. $this->emit_file_hooks_pre($exists, $path2, $run);
  831. }
  832. if ($run) {
  833. $mount1 = $this->getMount($path1);
  834. $mount2 = $this->getMount($path2);
  835. $storage1 = $mount1->getStorage();
  836. $internalPath1 = $mount1->getInternalPath($absolutePath1);
  837. $storage2 = $mount2->getStorage();
  838. $internalPath2 = $mount2->getInternalPath($absolutePath2);
  839. $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
  840. $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
  841. if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
  842. if ($storage1) {
  843. $result = $storage1->copy($internalPath1, $internalPath2);
  844. } else {
  845. $result = false;
  846. }
  847. } else {
  848. $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
  849. }
  850. $this->writeUpdate($storage2, $internalPath2);
  851. $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
  852. $lockTypePath2 = ILockingProvider::LOCK_SHARED;
  853. if ($this->shouldEmitHooks() && $result !== false) {
  854. \OC_Hook::emit(
  855. Filesystem::CLASSNAME,
  856. Filesystem::signal_post_copy,
  857. [
  858. Filesystem::signal_param_oldpath => $this->getHookPath($path1),
  859. Filesystem::signal_param_newpath => $this->getHookPath($path2)
  860. ]
  861. );
  862. $this->emit_file_hooks_post($exists, $path2);
  863. }
  864. }
  865. } catch (\Exception $e) {
  866. $this->unlockFile($path2, $lockTypePath2);
  867. $this->unlockFile($path1, $lockTypePath1);
  868. throw $e;
  869. }
  870. $this->unlockFile($path2, $lockTypePath2);
  871. $this->unlockFile($path1, $lockTypePath1);
  872. }
  873. return $result;
  874. }
  875. /**
  876. * @param string $path
  877. * @param string $mode 'r' or 'w'
  878. * @return resource
  879. * @throws LockedException
  880. */
  881. public function fopen($path, $mode) {
  882. $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
  883. $hooks = [];
  884. switch ($mode) {
  885. case 'r':
  886. $hooks[] = 'read';
  887. break;
  888. case 'r+':
  889. case 'w+':
  890. case 'x+':
  891. case 'a+':
  892. $hooks[] = 'read';
  893. $hooks[] = 'write';
  894. break;
  895. case 'w':
  896. case 'x':
  897. case 'a':
  898. $hooks[] = 'write';
  899. break;
  900. default:
  901. \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, ILogger::ERROR);
  902. }
  903. if ($mode !== 'r' && $mode !== 'w') {
  904. \OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
  905. }
  906. return $this->basicOperation('fopen', $path, $hooks, $mode);
  907. }
  908. /**
  909. * @param string $path
  910. * @return bool|string
  911. * @throws \OCP\Files\InvalidPathException
  912. */
  913. public function toTmpFile($path) {
  914. $this->assertPathLength($path);
  915. if (Filesystem::isValidPath($path)) {
  916. $source = $this->fopen($path, 'r');
  917. if ($source) {
  918. $extension = pathinfo($path, PATHINFO_EXTENSION);
  919. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
  920. file_put_contents($tmpFile, $source);
  921. return $tmpFile;
  922. } else {
  923. return false;
  924. }
  925. } else {
  926. return false;
  927. }
  928. }
  929. /**
  930. * @param string $tmpFile
  931. * @param string $path
  932. * @return bool|mixed
  933. * @throws \OCP\Files\InvalidPathException
  934. */
  935. public function fromTmpFile($tmpFile, $path) {
  936. $this->assertPathLength($path);
  937. if (Filesystem::isValidPath($path)) {
  938. // Get directory that the file is going into
  939. $filePath = dirname($path);
  940. // Create the directories if any
  941. if (!$this->file_exists($filePath)) {
  942. $result = $this->createParentDirectories($filePath);
  943. if ($result === false) {
  944. return false;
  945. }
  946. }
  947. $source = fopen($tmpFile, 'r');
  948. if ($source) {
  949. $result = $this->file_put_contents($path, $source);
  950. // $this->file_put_contents() might have already closed
  951. // the resource, so we check it, before trying to close it
  952. // to avoid messages in the error log.
  953. if (is_resource($source)) {
  954. fclose($source);
  955. }
  956. unlink($tmpFile);
  957. return $result;
  958. } else {
  959. return false;
  960. }
  961. } else {
  962. return false;
  963. }
  964. }
  965. /**
  966. * @param string $path
  967. * @return mixed
  968. * @throws \OCP\Files\InvalidPathException
  969. */
  970. public function getMimeType($path) {
  971. $this->assertPathLength($path);
  972. return $this->basicOperation('getMimeType', $path);
  973. }
  974. /**
  975. * @param string $type
  976. * @param string $path
  977. * @param bool $raw
  978. * @return bool|null|string
  979. */
  980. public function hash($type, $path, $raw = false) {
  981. $postFix = (substr($path, -1) === '/') ? '/' : '';
  982. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  983. if (Filesystem::isValidPath($path)) {
  984. $path = $this->getRelativePath($absolutePath);
  985. if ($path == null) {
  986. return false;
  987. }
  988. if ($this->shouldEmitHooks($path)) {
  989. \OC_Hook::emit(
  990. Filesystem::CLASSNAME,
  991. Filesystem::signal_read,
  992. [Filesystem::signal_param_path => $this->getHookPath($path)]
  993. );
  994. }
  995. [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
  996. if ($storage) {
  997. return $storage->hash($type, $internalPath, $raw);
  998. }
  999. }
  1000. return null;
  1001. }
  1002. /**
  1003. * @param string $path
  1004. * @return mixed
  1005. * @throws \OCP\Files\InvalidPathException
  1006. */
  1007. public function free_space($path = '/') {
  1008. $this->assertPathLength($path);
  1009. $result = $this->basicOperation('free_space', $path);
  1010. if ($result === null) {
  1011. throw new InvalidPathException();
  1012. }
  1013. return $result;
  1014. }
  1015. /**
  1016. * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
  1017. *
  1018. * @param string $operation
  1019. * @param string $path
  1020. * @param array $hooks (optional)
  1021. * @param mixed $extraParam (optional)
  1022. * @return mixed
  1023. * @throws LockedException
  1024. *
  1025. * This method takes requests for basic filesystem functions (e.g. reading & writing
  1026. * files), processes hooks and proxies, sanitises paths, and finally passes them on to
  1027. * \OC\Files\Storage\Storage for delegation to a storage backend for execution
  1028. */
  1029. private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
  1030. $postFix = (substr($path, -1) === '/') ? '/' : '';
  1031. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  1032. if (Filesystem::isValidPath($path)
  1033. and !Filesystem::isFileBlacklisted($path)
  1034. ) {
  1035. $path = $this->getRelativePath($absolutePath);
  1036. if ($path == null) {
  1037. return false;
  1038. }
  1039. if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
  1040. // always a shared lock during pre-hooks so the hook can read the file
  1041. $this->lockFile($path, ILockingProvider::LOCK_SHARED);
  1042. }
  1043. $run = $this->runHooks($hooks, $path);
  1044. /** @var \OC\Files\Storage\Storage $storage */
  1045. [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
  1046. if ($run and $storage) {
  1047. if (in_array('write', $hooks) || in_array('delete', $hooks)) {
  1048. try {
  1049. $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
  1050. } catch (LockedException $e) {
  1051. // release the shared lock we acquired before quiting
  1052. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1053. throw $e;
  1054. }
  1055. }
  1056. try {
  1057. if (!is_null($extraParam)) {
  1058. $result = $storage->$operation($internalPath, $extraParam);
  1059. } else {
  1060. $result = $storage->$operation($internalPath);
  1061. }
  1062. } catch (\Exception $e) {
  1063. if (in_array('write', $hooks) || in_array('delete', $hooks)) {
  1064. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  1065. } elseif (in_array('read', $hooks)) {
  1066. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1067. }
  1068. throw $e;
  1069. }
  1070. if ($result && in_array('delete', $hooks) and $result) {
  1071. $this->removeUpdate($storage, $internalPath);
  1072. }
  1073. if ($result && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
  1074. $this->writeUpdate($storage, $internalPath);
  1075. }
  1076. if ($result && in_array('touch', $hooks)) {
  1077. $this->writeUpdate($storage, $internalPath, $extraParam);
  1078. }
  1079. if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
  1080. $this->changeLock($path, ILockingProvider::LOCK_SHARED);
  1081. }
  1082. $unlockLater = false;
  1083. if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
  1084. $unlockLater = true;
  1085. // make sure our unlocking callback will still be called if connection is aborted
  1086. ignore_user_abort(true);
  1087. $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
  1088. if (in_array('write', $hooks)) {
  1089. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  1090. } elseif (in_array('read', $hooks)) {
  1091. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1092. }
  1093. });
  1094. }
  1095. if ($this->shouldEmitHooks($path) && $result !== false) {
  1096. if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
  1097. $this->runHooks($hooks, $path, true);
  1098. }
  1099. }
  1100. if (!$unlockLater
  1101. && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
  1102. ) {
  1103. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1104. }
  1105. return $result;
  1106. } else {
  1107. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1108. }
  1109. }
  1110. return null;
  1111. }
  1112. /**
  1113. * get the path relative to the default root for hook usage
  1114. *
  1115. * @param string $path
  1116. * @return string
  1117. */
  1118. private function getHookPath($path) {
  1119. if (!Filesystem::getView()) {
  1120. return $path;
  1121. }
  1122. return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
  1123. }
  1124. private function shouldEmitHooks($path = '') {
  1125. if ($path && Cache\Scanner::isPartialFile($path)) {
  1126. return false;
  1127. }
  1128. if (!Filesystem::$loaded) {
  1129. return false;
  1130. }
  1131. $defaultRoot = Filesystem::getRoot();
  1132. if ($defaultRoot === null) {
  1133. return false;
  1134. }
  1135. if ($this->fakeRoot === $defaultRoot) {
  1136. return true;
  1137. }
  1138. $fullPath = $this->getAbsolutePath($path);
  1139. if ($fullPath === $defaultRoot) {
  1140. return true;
  1141. }
  1142. return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
  1143. }
  1144. /**
  1145. * @param string[] $hooks
  1146. * @param string $path
  1147. * @param bool $post
  1148. * @return bool
  1149. */
  1150. private function runHooks($hooks, $path, $post = false) {
  1151. $relativePath = $path;
  1152. $path = $this->getHookPath($path);
  1153. $prefix = $post ? 'post_' : '';
  1154. $run = true;
  1155. if ($this->shouldEmitHooks($relativePath)) {
  1156. foreach ($hooks as $hook) {
  1157. if ($hook != 'read') {
  1158. \OC_Hook::emit(
  1159. Filesystem::CLASSNAME,
  1160. $prefix . $hook,
  1161. [
  1162. Filesystem::signal_param_run => &$run,
  1163. Filesystem::signal_param_path => $path
  1164. ]
  1165. );
  1166. } elseif (!$post) {
  1167. \OC_Hook::emit(
  1168. Filesystem::CLASSNAME,
  1169. $prefix . $hook,
  1170. [
  1171. Filesystem::signal_param_path => $path
  1172. ]
  1173. );
  1174. }
  1175. }
  1176. }
  1177. return $run;
  1178. }
  1179. /**
  1180. * check if a file or folder has been updated since $time
  1181. *
  1182. * @param string $path
  1183. * @param int $time
  1184. * @return bool
  1185. */
  1186. public function hasUpdated($path, $time) {
  1187. return $this->basicOperation('hasUpdated', $path, [], $time);
  1188. }
  1189. /**
  1190. * @param string $ownerId
  1191. * @return \OC\User\User
  1192. */
  1193. private function getUserObjectForOwner($ownerId) {
  1194. $owner = $this->userManager->get($ownerId);
  1195. if ($owner instanceof IUser) {
  1196. return $owner;
  1197. } else {
  1198. return new User($ownerId, null, \OC::$server->getEventDispatcher());
  1199. }
  1200. }
  1201. /**
  1202. * Get file info from cache
  1203. *
  1204. * If the file is not in cached it will be scanned
  1205. * If the file has changed on storage the cache will be updated
  1206. *
  1207. * @param \OC\Files\Storage\Storage $storage
  1208. * @param string $internalPath
  1209. * @param string $relativePath
  1210. * @return ICacheEntry|bool
  1211. */
  1212. private function getCacheEntry($storage, $internalPath, $relativePath) {
  1213. $cache = $storage->getCache($internalPath);
  1214. $data = $cache->get($internalPath);
  1215. $watcher = $storage->getWatcher($internalPath);
  1216. try {
  1217. // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
  1218. if (!$data || $data['size'] === -1) {
  1219. if (!$storage->file_exists($internalPath)) {
  1220. return false;
  1221. }
  1222. // don't need to get a lock here since the scanner does it's own locking
  1223. $scanner = $storage->getScanner($internalPath);
  1224. $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
  1225. $data = $cache->get($internalPath);
  1226. } elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
  1227. $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
  1228. $watcher->update($internalPath, $data);
  1229. $storage->getPropagator()->propagateChange($internalPath, time());
  1230. $data = $cache->get($internalPath);
  1231. $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
  1232. }
  1233. } catch (LockedException $e) {
  1234. // if the file is locked we just use the old cache info
  1235. }
  1236. return $data;
  1237. }
  1238. /**
  1239. * get the filesystem info
  1240. *
  1241. * @param string $path
  1242. * @param boolean|string $includeMountPoints true to add mountpoint sizes,
  1243. * 'ext' to add only ext storage mount point sizes. Defaults to true.
  1244. * defaults to true
  1245. * @return \OC\Files\FileInfo|false False if file does not exist
  1246. */
  1247. public function getFileInfo($path, $includeMountPoints = true) {
  1248. $this->assertPathLength($path);
  1249. if (!Filesystem::isValidPath($path)) {
  1250. return false;
  1251. }
  1252. if (Cache\Scanner::isPartialFile($path)) {
  1253. return $this->getPartFileInfo($path);
  1254. }
  1255. $relativePath = $path;
  1256. $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
  1257. $mount = Filesystem::getMountManager()->find($path);
  1258. if (!$mount) {
  1259. \OC::$server->getLogger()->warning('Mountpoint not found for path: ' . $path);
  1260. return false;
  1261. }
  1262. $storage = $mount->getStorage();
  1263. $internalPath = $mount->getInternalPath($path);
  1264. if ($storage) {
  1265. $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
  1266. if (!$data instanceof ICacheEntry) {
  1267. return false;
  1268. }
  1269. if ($mount instanceof MoveableMount && $internalPath === '') {
  1270. $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
  1271. }
  1272. $ownerId = $storage->getOwner($internalPath);
  1273. $owner = null;
  1274. if ($ownerId !== null && $ownerId !== false) {
  1275. // ownerId might be null if files are accessed with an access token without file system access
  1276. $owner = $this->getUserObjectForOwner($ownerId);
  1277. }
  1278. $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
  1279. if ($data and isset($data['fileid'])) {
  1280. if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
  1281. //add the sizes of other mount points to the folder
  1282. $extOnly = ($includeMountPoints === 'ext');
  1283. $mounts = Filesystem::getMountManager()->findIn($path);
  1284. $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
  1285. $subStorage = $mount->getStorage();
  1286. return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
  1287. }));
  1288. }
  1289. }
  1290. return $info;
  1291. } else {
  1292. \OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
  1293. }
  1294. return false;
  1295. }
  1296. /**
  1297. * get the content of a directory
  1298. *
  1299. * @param string $directory path under datadirectory
  1300. * @param string $mimetype_filter limit returned content to this mimetype or mimepart
  1301. * @return FileInfo[]
  1302. */
  1303. public function getDirectoryContent($directory, $mimetype_filter = '') {
  1304. $this->assertPathLength($directory);
  1305. if (!Filesystem::isValidPath($directory)) {
  1306. return [];
  1307. }
  1308. $path = $this->getAbsolutePath($directory);
  1309. $path = Filesystem::normalizePath($path);
  1310. $mount = $this->getMount($directory);
  1311. if (!$mount) {
  1312. return [];
  1313. }
  1314. $storage = $mount->getStorage();
  1315. $internalPath = $mount->getInternalPath($path);
  1316. if ($storage) {
  1317. $cache = $storage->getCache($internalPath);
  1318. $user = \OC_User::getUser();
  1319. $data = $this->getCacheEntry($storage, $internalPath, $directory);
  1320. if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
  1321. return [];
  1322. }
  1323. $folderId = $data['fileid'];
  1324. $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
  1325. $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
  1326. $fileNames = array_map(function (ICacheEntry $content) {
  1327. return $content->getName();
  1328. }, $contents);
  1329. /**
  1330. * @var \OC\Files\FileInfo[] $fileInfos
  1331. */
  1332. $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
  1333. if ($sharingDisabled) {
  1334. $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
  1335. }
  1336. $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
  1337. return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
  1338. }, $contents);
  1339. $files = array_combine($fileNames, $fileInfos);
  1340. //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
  1341. $mounts = Filesystem::getMountManager()->findIn($path);
  1342. $dirLength = strlen($path);
  1343. foreach ($mounts as $mount) {
  1344. $mountPoint = $mount->getMountPoint();
  1345. $subStorage = $mount->getStorage();
  1346. if ($subStorage) {
  1347. $subCache = $subStorage->getCache('');
  1348. $rootEntry = $subCache->get('');
  1349. if (!$rootEntry) {
  1350. $subScanner = $subStorage->getScanner('');
  1351. try {
  1352. $subScanner->scanFile('');
  1353. } catch (\OCP\Files\StorageNotAvailableException $e) {
  1354. continue;
  1355. } catch (\OCP\Files\StorageInvalidException $e) {
  1356. continue;
  1357. } catch (\Exception $e) {
  1358. // sometimes when the storage is not available it can be any exception
  1359. \OC::$server->getLogger()->logException($e, [
  1360. 'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
  1361. 'level' => ILogger::ERROR,
  1362. 'app' => 'lib',
  1363. ]);
  1364. continue;
  1365. }
  1366. $rootEntry = $subCache->get('');
  1367. }
  1368. if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
  1369. $relativePath = trim(substr($mountPoint, $dirLength), '/');
  1370. if ($pos = strpos($relativePath, '/')) {
  1371. //mountpoint inside subfolder add size to the correct folder
  1372. $entryName = substr($relativePath, 0, $pos);
  1373. foreach ($files as &$entry) {
  1374. if ($entry->getName() === $entryName) {
  1375. $entry->addSubEntry($rootEntry, $mountPoint);
  1376. }
  1377. }
  1378. } else { //mountpoint in this folder, add an entry for it
  1379. $rootEntry['name'] = $relativePath;
  1380. $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
  1381. $permissions = $rootEntry['permissions'];
  1382. // do not allow renaming/deleting the mount point if they are not shared files/folders
  1383. // for shared files/folders we use the permissions given by the owner
  1384. if ($mount instanceof MoveableMount) {
  1385. $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
  1386. } else {
  1387. $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
  1388. }
  1389. $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
  1390. // if sharing was disabled for the user we remove the share permissions
  1391. if (\OCP\Util::isSharingDisabledForUser()) {
  1392. $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
  1393. }
  1394. $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
  1395. $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
  1396. }
  1397. }
  1398. }
  1399. }
  1400. if ($mimetype_filter) {
  1401. $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
  1402. if (strpos($mimetype_filter, '/')) {
  1403. return $file->getMimetype() === $mimetype_filter;
  1404. } else {
  1405. return $file->getMimePart() === $mimetype_filter;
  1406. }
  1407. });
  1408. }
  1409. return array_values($files);
  1410. } else {
  1411. return [];
  1412. }
  1413. }
  1414. /**
  1415. * change file metadata
  1416. *
  1417. * @param string $path
  1418. * @param array|\OCP\Files\FileInfo $data
  1419. * @return int
  1420. *
  1421. * returns the fileid of the updated file
  1422. */
  1423. public function putFileInfo($path, $data) {
  1424. $this->assertPathLength($path);
  1425. if ($data instanceof FileInfo) {
  1426. $data = $data->getData();
  1427. }
  1428. $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
  1429. /**
  1430. * @var \OC\Files\Storage\Storage $storage
  1431. * @var string $internalPath
  1432. */
  1433. [$storage, $internalPath] = Filesystem::resolvePath($path);
  1434. if ($storage) {
  1435. $cache = $storage->getCache($path);
  1436. if (!$cache->inCache($internalPath)) {
  1437. $scanner = $storage->getScanner($internalPath);
  1438. $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
  1439. }
  1440. return $cache->put($internalPath, $data);
  1441. } else {
  1442. return -1;
  1443. }
  1444. }
  1445. /**
  1446. * search for files with the name matching $query
  1447. *
  1448. * @param string $query
  1449. * @return FileInfo[]
  1450. */
  1451. public function search($query) {
  1452. return $this->searchCommon('search', ['%' . $query . '%']);
  1453. }
  1454. /**
  1455. * search for files with the name matching $query
  1456. *
  1457. * @param string $query
  1458. * @return FileInfo[]
  1459. */
  1460. public function searchRaw($query) {
  1461. return $this->searchCommon('search', [$query]);
  1462. }
  1463. /**
  1464. * search for files by mimetype
  1465. *
  1466. * @param string $mimetype
  1467. * @return FileInfo[]
  1468. */
  1469. public function searchByMime($mimetype) {
  1470. return $this->searchCommon('searchByMime', [$mimetype]);
  1471. }
  1472. /**
  1473. * search for files by tag
  1474. *
  1475. * @param string|int $tag name or tag id
  1476. * @param string $userId owner of the tags
  1477. * @return FileInfo[]
  1478. */
  1479. public function searchByTag($tag, $userId) {
  1480. return $this->searchCommon('searchByTag', [$tag, $userId]);
  1481. }
  1482. /**
  1483. * @param string $method cache method
  1484. * @param array $args
  1485. * @return FileInfo[]
  1486. */
  1487. private function searchCommon($method, $args) {
  1488. $files = [];
  1489. $rootLength = strlen($this->fakeRoot);
  1490. $mount = $this->getMount('');
  1491. $mountPoint = $mount->getMountPoint();
  1492. $storage = $mount->getStorage();
  1493. if ($storage) {
  1494. $cache = $storage->getCache('');
  1495. $results = call_user_func_array([$cache, $method], $args);
  1496. foreach ($results as $result) {
  1497. if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
  1498. $internalPath = $result['path'];
  1499. $path = $mountPoint . $result['path'];
  1500. $result['path'] = substr($mountPoint . $result['path'], $rootLength);
  1501. $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
  1502. $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
  1503. }
  1504. }
  1505. $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
  1506. foreach ($mounts as $mount) {
  1507. $mountPoint = $mount->getMountPoint();
  1508. $storage = $mount->getStorage();
  1509. if ($storage) {
  1510. $cache = $storage->getCache('');
  1511. $relativeMountPoint = substr($mountPoint, $rootLength);
  1512. $results = call_user_func_array([$cache, $method], $args);
  1513. if ($results) {
  1514. foreach ($results as $result) {
  1515. $internalPath = $result['path'];
  1516. $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
  1517. $path = rtrim($mountPoint . $internalPath, '/');
  1518. $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
  1519. $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
  1520. }
  1521. }
  1522. }
  1523. }
  1524. }
  1525. return $files;
  1526. }
  1527. /**
  1528. * Get the owner for a file or folder
  1529. *
  1530. * @param string $path
  1531. * @return string the user id of the owner
  1532. * @throws NotFoundException
  1533. */
  1534. public function getOwner($path) {
  1535. $info = $this->getFileInfo($path);
  1536. if (!$info) {
  1537. throw new NotFoundException($path . ' not found while trying to get owner');
  1538. }
  1539. if ($info->getOwner() === null) {
  1540. throw new NotFoundException($path . ' has no owner');
  1541. }
  1542. return $info->getOwner()->getUID();
  1543. }
  1544. /**
  1545. * get the ETag for a file or folder
  1546. *
  1547. * @param string $path
  1548. * @return string
  1549. */
  1550. public function getETag($path) {
  1551. /**
  1552. * @var Storage\Storage $storage
  1553. * @var string $internalPath
  1554. */
  1555. [$storage, $internalPath] = $this->resolvePath($path);
  1556. if ($storage) {
  1557. return $storage->getETag($internalPath);
  1558. } else {
  1559. return null;
  1560. }
  1561. }
  1562. /**
  1563. * Get the path of a file by id, relative to the view
  1564. *
  1565. * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
  1566. *
  1567. * @param int $id
  1568. * @param int|null $storageId
  1569. * @return string
  1570. * @throws NotFoundException
  1571. */
  1572. public function getPath($id, int $storageId = null) {
  1573. $id = (int)$id;
  1574. $manager = Filesystem::getMountManager();
  1575. $mounts = $manager->findIn($this->fakeRoot);
  1576. $mounts[] = $manager->find($this->fakeRoot);
  1577. // reverse the array so we start with the storage this view is in
  1578. // which is the most likely to contain the file we're looking for
  1579. $mounts = array_reverse($mounts);
  1580. // put non shared mounts in front of the shared mount
  1581. // this prevent unneeded recursion into shares
  1582. usort($mounts, function (IMountPoint $a, IMountPoint $b) {
  1583. return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
  1584. });
  1585. if (!is_null($storageId)) {
  1586. $mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
  1587. return $mount->getNumericStorageId() === $storageId;
  1588. });
  1589. }
  1590. foreach ($mounts as $mount) {
  1591. /**
  1592. * @var \OC\Files\Mount\MountPoint $mount
  1593. */
  1594. if ($mount->getStorage()) {
  1595. $cache = $mount->getStorage()->getCache();
  1596. $internalPath = $cache->getPathById($id);
  1597. if (is_string($internalPath)) {
  1598. $fullPath = $mount->getMountPoint() . $internalPath;
  1599. if (!is_null($path = $this->getRelativePath($fullPath))) {
  1600. return $path;
  1601. }
  1602. }
  1603. }
  1604. }
  1605. throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
  1606. }
  1607. /**
  1608. * @param string $path
  1609. * @throws InvalidPathException
  1610. */
  1611. private function assertPathLength($path) {
  1612. $maxLen = min(PHP_MAXPATHLEN, 4000);
  1613. // Check for the string length - performed using isset() instead of strlen()
  1614. // because isset() is about 5x-40x faster.
  1615. if (isset($path[$maxLen])) {
  1616. $pathLen = strlen($path);
  1617. throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
  1618. }
  1619. }
  1620. /**
  1621. * check if it is allowed to move a mount point to a given target.
  1622. * It is not allowed to move a mount point into a different mount point or
  1623. * into an already shared folder
  1624. *
  1625. * @param IStorage $targetStorage
  1626. * @param string $targetInternalPath
  1627. * @return boolean
  1628. */
  1629. private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
  1630. // note: cannot use the view because the target is already locked
  1631. $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
  1632. if ($fileId === -1) {
  1633. // target might not exist, need to check parent instead
  1634. $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
  1635. }
  1636. // check if any of the parents were shared by the current owner (include collections)
  1637. $shares = \OCP\Share::getItemShared(
  1638. 'folder',
  1639. $fileId,
  1640. \OCP\Share::FORMAT_NONE,
  1641. null,
  1642. true
  1643. );
  1644. if (count($shares) > 0) {
  1645. \OCP\Util::writeLog('files',
  1646. 'It is not allowed to move one mount point into a shared folder',
  1647. ILogger::DEBUG);
  1648. return false;
  1649. }
  1650. return true;
  1651. }
  1652. /**
  1653. * Get a fileinfo object for files that are ignored in the cache (part files)
  1654. *
  1655. * @param string $path
  1656. * @return \OCP\Files\FileInfo
  1657. */
  1658. private function getPartFileInfo($path) {
  1659. $mount = $this->getMount($path);
  1660. $storage = $mount->getStorage();
  1661. $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
  1662. $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
  1663. return new FileInfo(
  1664. $this->getAbsolutePath($path),
  1665. $storage,
  1666. $internalPath,
  1667. [
  1668. 'fileid' => null,
  1669. 'mimetype' => $storage->getMimeType($internalPath),
  1670. 'name' => basename($path),
  1671. 'etag' => null,
  1672. 'size' => $storage->filesize($internalPath),
  1673. 'mtime' => $storage->filemtime($internalPath),
  1674. 'encrypted' => false,
  1675. 'permissions' => \OCP\Constants::PERMISSION_ALL
  1676. ],
  1677. $mount,
  1678. $owner
  1679. );
  1680. }
  1681. /**
  1682. * @param string $path
  1683. * @param string $fileName
  1684. * @throws InvalidPathException
  1685. */
  1686. public function verifyPath($path, $fileName) {
  1687. try {
  1688. /** @type \OCP\Files\Storage $storage */
  1689. [$storage, $internalPath] = $this->resolvePath($path);
  1690. $storage->verifyPath($internalPath, $fileName);
  1691. } catch (ReservedWordException $ex) {
  1692. $l = \OC::$server->getL10N('lib');
  1693. throw new InvalidPathException($l->t('File name is a reserved word'));
  1694. } catch (InvalidCharacterInPathException $ex) {
  1695. $l = \OC::$server->getL10N('lib');
  1696. throw new InvalidPathException($l->t('File name contains at least one invalid character'));
  1697. } catch (FileNameTooLongException $ex) {
  1698. $l = \OC::$server->getL10N('lib');
  1699. throw new InvalidPathException($l->t('File name is too long'));
  1700. } catch (InvalidDirectoryException $ex) {
  1701. $l = \OC::$server->getL10N('lib');
  1702. throw new InvalidPathException($l->t('Dot files are not allowed'));
  1703. } catch (EmptyFileNameException $ex) {
  1704. $l = \OC::$server->getL10N('lib');
  1705. throw new InvalidPathException($l->t('Empty filename is not allowed'));
  1706. }
  1707. }
  1708. /**
  1709. * get all parent folders of $path
  1710. *
  1711. * @param string $path
  1712. * @return string[]
  1713. */
  1714. private function getParents($path) {
  1715. $path = trim($path, '/');
  1716. if (!$path) {
  1717. return [];
  1718. }
  1719. $parts = explode('/', $path);
  1720. // remove the single file
  1721. array_pop($parts);
  1722. $result = ['/'];
  1723. $resultPath = '';
  1724. foreach ($parts as $part) {
  1725. if ($part) {
  1726. $resultPath .= '/' . $part;
  1727. $result[] = $resultPath;
  1728. }
  1729. }
  1730. return $result;
  1731. }
  1732. /**
  1733. * Returns the mount point for which to lock
  1734. *
  1735. * @param string $absolutePath absolute path
  1736. * @param bool $useParentMount true to return parent mount instead of whatever
  1737. * is mounted directly on the given path, false otherwise
  1738. * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
  1739. */
  1740. private function getMountForLock($absolutePath, $useParentMount = false) {
  1741. $results = [];
  1742. $mount = Filesystem::getMountManager()->find($absolutePath);
  1743. if (!$mount) {
  1744. return $results;
  1745. }
  1746. if ($useParentMount) {
  1747. // find out if something is mounted directly on the path
  1748. $internalPath = $mount->getInternalPath($absolutePath);
  1749. if ($internalPath === '') {
  1750. // resolve the parent mount instead
  1751. $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
  1752. }
  1753. }
  1754. return $mount;
  1755. }
  1756. /**
  1757. * Lock the given path
  1758. *
  1759. * @param string $path the path of the file to lock, relative to the view
  1760. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1761. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1762. *
  1763. * @return bool False if the path is excluded from locking, true otherwise
  1764. * @throws LockedException if the path is already locked
  1765. */
  1766. private function lockPath($path, $type, $lockMountPoint = false) {
  1767. $absolutePath = $this->getAbsolutePath($path);
  1768. $absolutePath = Filesystem::normalizePath($absolutePath);
  1769. if (!$this->shouldLockFile($absolutePath)) {
  1770. return false;
  1771. }
  1772. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1773. if ($mount) {
  1774. try {
  1775. $storage = $mount->getStorage();
  1776. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1777. $storage->acquireLock(
  1778. $mount->getInternalPath($absolutePath),
  1779. $type,
  1780. $this->lockingProvider
  1781. );
  1782. }
  1783. } catch (LockedException $e) {
  1784. // rethrow with the a human-readable path
  1785. throw new LockedException(
  1786. $this->getPathRelativeToFiles($absolutePath),
  1787. $e,
  1788. $e->getExistingLock()
  1789. );
  1790. }
  1791. }
  1792. return true;
  1793. }
  1794. /**
  1795. * Change the lock type
  1796. *
  1797. * @param string $path the path of the file to lock, relative to the view
  1798. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1799. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1800. *
  1801. * @return bool False if the path is excluded from locking, true otherwise
  1802. * @throws LockedException if the path is already locked
  1803. */
  1804. public function changeLock($path, $type, $lockMountPoint = false) {
  1805. $path = Filesystem::normalizePath($path);
  1806. $absolutePath = $this->getAbsolutePath($path);
  1807. $absolutePath = Filesystem::normalizePath($absolutePath);
  1808. if (!$this->shouldLockFile($absolutePath)) {
  1809. return false;
  1810. }
  1811. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1812. if ($mount) {
  1813. try {
  1814. $storage = $mount->getStorage();
  1815. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1816. $storage->changeLock(
  1817. $mount->getInternalPath($absolutePath),
  1818. $type,
  1819. $this->lockingProvider
  1820. );
  1821. }
  1822. } catch (LockedException $e) {
  1823. try {
  1824. // rethrow with the a human-readable path
  1825. throw new LockedException(
  1826. $this->getPathRelativeToFiles($absolutePath),
  1827. $e,
  1828. $e->getExistingLock()
  1829. );
  1830. } catch (\InvalidArgumentException $ex) {
  1831. throw new LockedException(
  1832. $absolutePath,
  1833. $ex,
  1834. $e->getExistingLock()
  1835. );
  1836. }
  1837. }
  1838. }
  1839. return true;
  1840. }
  1841. /**
  1842. * Unlock the given path
  1843. *
  1844. * @param string $path the path of the file to unlock, relative to the view
  1845. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1846. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1847. *
  1848. * @return bool False if the path is excluded from locking, true otherwise
  1849. * @throws LockedException
  1850. */
  1851. private function unlockPath($path, $type, $lockMountPoint = false) {
  1852. $absolutePath = $this->getAbsolutePath($path);
  1853. $absolutePath = Filesystem::normalizePath($absolutePath);
  1854. if (!$this->shouldLockFile($absolutePath)) {
  1855. return false;
  1856. }
  1857. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1858. if ($mount) {
  1859. $storage = $mount->getStorage();
  1860. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1861. $storage->releaseLock(
  1862. $mount->getInternalPath($absolutePath),
  1863. $type,
  1864. $this->lockingProvider
  1865. );
  1866. }
  1867. }
  1868. return true;
  1869. }
  1870. /**
  1871. * Lock a path and all its parents up to the root of the view
  1872. *
  1873. * @param string $path the path of the file to lock relative to the view
  1874. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1875. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1876. *
  1877. * @return bool False if the path is excluded from locking, true otherwise
  1878. * @throws LockedException
  1879. */
  1880. public function lockFile($path, $type, $lockMountPoint = false) {
  1881. $absolutePath = $this->getAbsolutePath($path);
  1882. $absolutePath = Filesystem::normalizePath($absolutePath);
  1883. if (!$this->shouldLockFile($absolutePath)) {
  1884. return false;
  1885. }
  1886. $this->lockPath($path, $type, $lockMountPoint);
  1887. $parents = $this->getParents($path);
  1888. foreach ($parents as $parent) {
  1889. $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
  1890. }
  1891. return true;
  1892. }
  1893. /**
  1894. * Unlock a path and all its parents up to the root of the view
  1895. *
  1896. * @param string $path the path of the file to lock relative to the view
  1897. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1898. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1899. *
  1900. * @return bool False if the path is excluded from locking, true otherwise
  1901. * @throws LockedException
  1902. */
  1903. public function unlockFile($path, $type, $lockMountPoint = false) {
  1904. $absolutePath = $this->getAbsolutePath($path);
  1905. $absolutePath = Filesystem::normalizePath($absolutePath);
  1906. if (!$this->shouldLockFile($absolutePath)) {
  1907. return false;
  1908. }
  1909. $this->unlockPath($path, $type, $lockMountPoint);
  1910. $parents = $this->getParents($path);
  1911. foreach ($parents as $parent) {
  1912. $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
  1913. }
  1914. return true;
  1915. }
  1916. /**
  1917. * Only lock files in data/user/files/
  1918. *
  1919. * @param string $path Absolute path to the file/folder we try to (un)lock
  1920. * @return bool
  1921. */
  1922. protected function shouldLockFile($path) {
  1923. $path = Filesystem::normalizePath($path);
  1924. $pathSegments = explode('/', $path);
  1925. if (isset($pathSegments[2])) {
  1926. // E.g.: /username/files/path-to-file
  1927. return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
  1928. }
  1929. return strpos($path, '/appdata_') !== 0;
  1930. }
  1931. /**
  1932. * Shortens the given absolute path to be relative to
  1933. * "$user/files".
  1934. *
  1935. * @param string $absolutePath absolute path which is under "files"
  1936. *
  1937. * @return string path relative to "files" with trimmed slashes or null
  1938. * if the path was NOT relative to files
  1939. *
  1940. * @throws \InvalidArgumentException if the given path was not under "files"
  1941. * @since 8.1.0
  1942. */
  1943. public function getPathRelativeToFiles($absolutePath) {
  1944. $path = Filesystem::normalizePath($absolutePath);
  1945. $parts = explode('/', trim($path, '/'), 3);
  1946. // "$user", "files", "path/to/dir"
  1947. if (!isset($parts[1]) || $parts[1] !== 'files') {
  1948. $this->logger->error(
  1949. '$absolutePath must be relative to "files", value is "%s"',
  1950. [
  1951. $absolutePath
  1952. ]
  1953. );
  1954. throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
  1955. }
  1956. if (isset($parts[2])) {
  1957. return $parts[2];
  1958. }
  1959. return '';
  1960. }
  1961. /**
  1962. * @param string $filename
  1963. * @return array
  1964. * @throws \OC\User\NoUserException
  1965. * @throws NotFoundException
  1966. */
  1967. public function getUidAndFilename($filename) {
  1968. $info = $this->getFileInfo($filename);
  1969. if (!$info instanceof \OCP\Files\FileInfo) {
  1970. throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
  1971. }
  1972. $uid = $info->getOwner()->getUID();
  1973. if ($uid != \OCP\User::getUser()) {
  1974. Filesystem::initMountPoints($uid);
  1975. $ownerView = new View('/' . $uid . '/files');
  1976. try {
  1977. $filename = $ownerView->getPath($info['fileid']);
  1978. } catch (NotFoundException $e) {
  1979. throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
  1980. }
  1981. }
  1982. return [$uid, $filename];
  1983. }
  1984. /**
  1985. * Creates parent non-existing folders
  1986. *
  1987. * @param string $filePath
  1988. * @return bool
  1989. */
  1990. private function createParentDirectories($filePath) {
  1991. $directoryParts = explode('/', $filePath);
  1992. $directoryParts = array_filter($directoryParts);
  1993. foreach ($directoryParts as $key => $part) {
  1994. $currentPathElements = array_slice($directoryParts, 0, $key);
  1995. $currentPath = '/' . implode('/', $currentPathElements);
  1996. if ($this->is_file($currentPath)) {
  1997. return false;
  1998. }
  1999. if (!$this->file_exists($currentPath)) {
  2000. $this->mkdir($currentPath);
  2001. }
  2002. }
  2003. return true;
  2004. }
  2005. }