Trashbin.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Bastien Ho <bastienho@urbancube.fr>
  7. * @author Bjoern Schiessle <bjoern@schiessle.org>
  8. * @author Björn Schießle <bjoern@schiessle.org>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  11. * @author Florin Peter <github@florin-peter.de>
  12. * @author Georg Ehrke <oc.list@georgehrke.com>
  13. * @author Joas Schilling <coding@schilljs.com>
  14. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  15. * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
  16. * @author Julius Härtl <jus@bitgrid.net>
  17. * @author Lars Knickrehm <mail@lars-sh.de>
  18. * @author Lukas Reschke <lukas@statuscode.ch>
  19. * @author Morris Jobke <hey@morrisjobke.de>
  20. * @author Qingping Hou <dave2008713@gmail.com>
  21. * @author Robin Appelman <robin@icewind.nl>
  22. * @author Robin McCorkell <robin@mccorkell.me.uk>
  23. * @author Roeland Jago Douma <roeland@famdouma.nl>
  24. * @author Sjors van der Pluijm <sjors@desjors.nl>
  25. * @author Steven Bühner <buehner@me.com>
  26. * @author Thomas Müller <thomas.mueller@tmit.eu>
  27. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  28. * @author Vincent Petry <vincent@nextcloud.com>
  29. *
  30. * @license AGPL-3.0
  31. *
  32. * This code is free software: you can redistribute it and/or modify
  33. * it under the terms of the GNU Affero General Public License, version 3,
  34. * as published by the Free Software Foundation.
  35. *
  36. * This program is distributed in the hope that it will be useful,
  37. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  38. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  39. * GNU Affero General Public License for more details.
  40. *
  41. * You should have received a copy of the GNU Affero General Public License, version 3,
  42. * along with this program. If not, see <http://www.gnu.org/licenses/>
  43. *
  44. */
  45. namespace OCA\Files_Trashbin;
  46. use Exception;
  47. use OC\Files\Cache\Cache;
  48. use OC\Files\Cache\CacheEntry;
  49. use OC\Files\Cache\CacheQueryBuilder;
  50. use OC\Files\Filesystem;
  51. use OC\Files\Node\File;
  52. use OC\Files\Node\Folder;
  53. use OC\Files\Node\NonExistingFile;
  54. use OC\Files\Node\NonExistingFolder;
  55. use OC\Files\View;
  56. use OC_User;
  57. use OCA\Files_Trashbin\AppInfo\Application;
  58. use OCA\Files_Trashbin\Command\Expire;
  59. use OCA\Files_Trashbin\Events\BeforeNodeRestoredEvent;
  60. use OCA\Files_Trashbin\Events\NodeRestoredEvent;
  61. use OCP\App\IAppManager;
  62. use OCP\AppFramework\Utility\ITimeFactory;
  63. use OCP\EventDispatcher\IEventDispatcher;
  64. use OCP\Files\IRootFolder;
  65. use OCP\Files\Node;
  66. use OCP\Files\NotFoundException;
  67. use OCP\Files\NotPermittedException;
  68. use OCP\Files\Storage\ILockingStorage;
  69. use OCP\FilesMetadata\IFilesMetadataManager;
  70. use OCP\IConfig;
  71. use OCP\Lock\ILockingProvider;
  72. use OCP\Lock\LockedException;
  73. use Psr\Log\LoggerInterface;
  74. class Trashbin {
  75. // unit: percentage; 50% of available disk space/quota
  76. public const DEFAULTMAXSIZE = 50;
  77. /**
  78. * Ensure we don't need to scan the file during the move to trash
  79. * by triggering the scan in the pre-hook
  80. *
  81. * @param array $params
  82. */
  83. public static function ensureFileScannedHook($params) {
  84. try {
  85. self::getUidAndFilename($params['path']);
  86. } catch (NotFoundException $e) {
  87. // nothing to scan for non existing files
  88. }
  89. }
  90. /**
  91. * get the UID of the owner of the file and the path to the file relative to
  92. * owners files folder
  93. *
  94. * @param string $filename
  95. * @return array
  96. * @throws \OC\User\NoUserException
  97. */
  98. public static function getUidAndFilename($filename) {
  99. $uid = Filesystem::getOwner($filename);
  100. $userManager = \OC::$server->getUserManager();
  101. // if the user with the UID doesn't exists, e.g. because the UID points
  102. // to a remote user with a federated cloud ID we use the current logged-in
  103. // user. We need a valid local user to move the file to the right trash bin
  104. if (!$userManager->userExists($uid)) {
  105. $uid = OC_User::getUser();
  106. }
  107. if (!$uid) {
  108. // no owner, usually because of share link from ext storage
  109. return [null, null];
  110. }
  111. Filesystem::initMountPoints($uid);
  112. if ($uid !== OC_User::getUser()) {
  113. $info = Filesystem::getFileInfo($filename);
  114. $ownerView = new View('/' . $uid . '/files');
  115. try {
  116. $filename = $ownerView->getPath($info['fileid']);
  117. } catch (NotFoundException $e) {
  118. $filename = null;
  119. }
  120. }
  121. return [$uid, $filename];
  122. }
  123. /**
  124. * get original location of files for user
  125. *
  126. * @param string $user
  127. * @return array (filename => array (timestamp => original location))
  128. */
  129. public static function getLocations($user) {
  130. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  131. $query->select('id', 'timestamp', 'location')
  132. ->from('files_trash')
  133. ->where($query->expr()->eq('user', $query->createNamedParameter($user)));
  134. $result = $query->executeQuery();
  135. $array = [];
  136. while ($row = $result->fetch()) {
  137. if (isset($array[$row['id']])) {
  138. $array[$row['id']][$row['timestamp']] = $row['location'];
  139. } else {
  140. $array[$row['id']] = [$row['timestamp'] => $row['location']];
  141. }
  142. }
  143. $result->closeCursor();
  144. return $array;
  145. }
  146. /**
  147. * get original location of file
  148. *
  149. * @param string $user
  150. * @param string $filename
  151. * @param string $timestamp
  152. * @return string original location
  153. */
  154. public static function getLocation($user, $filename, $timestamp) {
  155. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  156. $query->select('location')
  157. ->from('files_trash')
  158. ->where($query->expr()->eq('user', $query->createNamedParameter($user)))
  159. ->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
  160. ->andWhere($query->expr()->eq('timestamp', $query->createNamedParameter($timestamp)));
  161. $result = $query->executeQuery();
  162. $row = $result->fetch();
  163. $result->closeCursor();
  164. if (isset($row['location'])) {
  165. return $row['location'];
  166. } else {
  167. return false;
  168. }
  169. }
  170. private static function setUpTrash($user) {
  171. $view = new View('/' . $user);
  172. if (!$view->is_dir('files_trashbin')) {
  173. $view->mkdir('files_trashbin');
  174. }
  175. if (!$view->is_dir('files_trashbin/files')) {
  176. $view->mkdir('files_trashbin/files');
  177. }
  178. if (!$view->is_dir('files_trashbin/versions')) {
  179. $view->mkdir('files_trashbin/versions');
  180. }
  181. if (!$view->is_dir('files_trashbin/keys')) {
  182. $view->mkdir('files_trashbin/keys');
  183. }
  184. }
  185. /**
  186. * copy file to owners trash
  187. *
  188. * @param string $sourcePath
  189. * @param string $owner
  190. * @param string $targetPath
  191. * @param $user
  192. * @param int $timestamp
  193. */
  194. private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) {
  195. self::setUpTrash($owner);
  196. $targetFilename = basename($targetPath);
  197. $targetLocation = dirname($targetPath);
  198. $sourceFilename = basename($sourcePath);
  199. $view = new View('/');
  200. $target = $user . '/files_trashbin/files/' . static::getTrashFilename($targetFilename, $timestamp);
  201. $source = $owner . '/files_trashbin/files/' . static::getTrashFilename($sourceFilename, $timestamp);
  202. $free = $view->free_space($target);
  203. $isUnknownOrUnlimitedFreeSpace = $free < 0;
  204. $isEnoughFreeSpaceLeft = $view->filesize($source) < $free;
  205. if ($isUnknownOrUnlimitedFreeSpace || $isEnoughFreeSpaceLeft) {
  206. self::copy_recursive($source, $target, $view);
  207. }
  208. if ($view->file_exists($target)) {
  209. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  210. $query->insert('files_trash')
  211. ->setValue('id', $query->createNamedParameter($targetFilename))
  212. ->setValue('timestamp', $query->createNamedParameter($timestamp))
  213. ->setValue('location', $query->createNamedParameter($targetLocation))
  214. ->setValue('user', $query->createNamedParameter($user));
  215. $result = $query->executeStatement();
  216. if (!$result) {
  217. \OC::$server->get(LoggerInterface::class)->error('trash bin database couldn\'t be updated for the files owner', ['app' => 'files_trashbin']);
  218. }
  219. }
  220. }
  221. /**
  222. * move file to the trash bin
  223. *
  224. * @param string $file_path path to the deleted file/directory relative to the files root directory
  225. * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
  226. *
  227. * @return bool
  228. */
  229. public static function move2trash($file_path, $ownerOnly = false) {
  230. // get the user for which the filesystem is setup
  231. $root = Filesystem::getRoot();
  232. [, $user] = explode('/', $root);
  233. [$owner, $ownerPath] = self::getUidAndFilename($file_path);
  234. // if no owner found (ex: ext storage + share link), will use the current user's trashbin then
  235. if (is_null($owner)) {
  236. $owner = $user;
  237. $ownerPath = $file_path;
  238. }
  239. $ownerView = new View('/' . $owner);
  240. // file has been deleted in between
  241. if (is_null($ownerPath) || $ownerPath === '') {
  242. return true;
  243. }
  244. $sourceInfo = $ownerView->getFileInfo('/files/' . $ownerPath);
  245. if ($sourceInfo === false) {
  246. return true;
  247. }
  248. self::setUpTrash($user);
  249. if ($owner !== $user) {
  250. // also setup for owner
  251. self::setUpTrash($owner);
  252. }
  253. $path_parts = pathinfo($ownerPath);
  254. $filename = $path_parts['basename'];
  255. $location = $path_parts['dirname'];
  256. /** @var ITimeFactory $timeFactory */
  257. $timeFactory = \OC::$server->query(ITimeFactory::class);
  258. $timestamp = $timeFactory->getTime();
  259. $lockingProvider = \OC::$server->getLockingProvider();
  260. // disable proxy to prevent recursive calls
  261. $trashPath = '/files_trashbin/files/' . static::getTrashFilename($filename, $timestamp);
  262. $gotLock = false;
  263. do {
  264. /** @var ILockingStorage & Storage $trashStorage */
  265. [$trashStorage, $trashInternalPath] = $ownerView->resolvePath($trashPath);
  266. try {
  267. $trashStorage->acquireLock($trashInternalPath, ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  268. $gotLock = true;
  269. } catch (LockedException $e) {
  270. // a file with the same name is being deleted concurrently
  271. // nudge the timestamp a bit to resolve the conflict
  272. $timestamp = $timestamp + 1;
  273. $trashPath = '/files_trashbin/files/' . static::getTrashFilename($filename, $timestamp);
  274. }
  275. } while (!$gotLock);
  276. $sourceStorage = $sourceInfo->getStorage();
  277. $sourceInternalPath = $sourceInfo->getInternalPath();
  278. if ($trashStorage->file_exists($trashInternalPath)) {
  279. $trashStorage->unlink($trashInternalPath);
  280. }
  281. $configuredTrashbinSize = static::getConfiguredTrashbinSize($owner);
  282. if ($configuredTrashbinSize >= 0 && $sourceInfo->getSize() >= $configuredTrashbinSize) {
  283. return false;
  284. }
  285. try {
  286. $moveSuccessful = true;
  287. $trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
  288. if ($sourceStorage->getCache()->inCache($sourceInternalPath)) {
  289. $trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
  290. }
  291. } catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) {
  292. $moveSuccessful = false;
  293. if ($trashStorage->file_exists($trashInternalPath)) {
  294. $trashStorage->unlink($trashInternalPath);
  295. }
  296. \OC::$server->get(LoggerInterface::class)->error('Couldn\'t move ' . $file_path . ' to the trash bin', ['app' => 'files_trashbin']);
  297. }
  298. if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
  299. if ($sourceStorage->is_dir($sourceInternalPath)) {
  300. $sourceStorage->rmdir($sourceInternalPath);
  301. } else {
  302. $sourceStorage->unlink($sourceInternalPath);
  303. }
  304. if ($sourceStorage->file_exists($sourceInternalPath)) {
  305. // undo the cache move
  306. $sourceStorage->getUpdater()->renameFromStorage($trashStorage, $trashInternalPath, $sourceInternalPath);
  307. } else {
  308. $trashStorage->getUpdater()->remove($trashInternalPath);
  309. }
  310. return false;
  311. }
  312. if ($moveSuccessful) {
  313. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  314. $query->insert('files_trash')
  315. ->setValue('id', $query->createNamedParameter($filename))
  316. ->setValue('timestamp', $query->createNamedParameter($timestamp))
  317. ->setValue('location', $query->createNamedParameter($location))
  318. ->setValue('user', $query->createNamedParameter($owner));
  319. $result = $query->executeStatement();
  320. if (!$result) {
  321. \OC::$server->get(LoggerInterface::class)->error('trash bin database couldn\'t be updated', ['app' => 'files_trashbin']);
  322. }
  323. \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', ['filePath' => Filesystem::normalizePath($file_path),
  324. 'trashPath' => Filesystem::normalizePath(static::getTrashFilename($filename, $timestamp))]);
  325. self::retainVersions($filename, $owner, $ownerPath, $timestamp);
  326. // if owner !== user we need to also add a copy to the users trash
  327. if ($user !== $owner && $ownerOnly === false) {
  328. self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp);
  329. }
  330. }
  331. $trashStorage->releaseLock($trashInternalPath, ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  332. self::scheduleExpire($user);
  333. // if owner !== user we also need to update the owners trash size
  334. if ($owner !== $user) {
  335. self::scheduleExpire($owner);
  336. }
  337. return $moveSuccessful;
  338. }
  339. private static function getConfiguredTrashbinSize(string $user): int|float {
  340. $config = \OC::$server->get(IConfig::class);
  341. $userTrashbinSize = $config->getUserValue($user, 'files_trashbin', 'trashbin_size', '-1');
  342. if (is_numeric($userTrashbinSize) && ($userTrashbinSize > -1)) {
  343. return \OCP\Util::numericToNumber($userTrashbinSize);
  344. }
  345. $systemTrashbinSize = $config->getAppValue('files_trashbin', 'trashbin_size', '-1');
  346. if (is_numeric($systemTrashbinSize)) {
  347. return \OCP\Util::numericToNumber($systemTrashbinSize);
  348. }
  349. return -1;
  350. }
  351. /**
  352. * Move file versions to trash so that they can be restored later
  353. *
  354. * @param string $filename of deleted file
  355. * @param string $owner owner user id
  356. * @param string $ownerPath path relative to the owner's home storage
  357. * @param int $timestamp when the file was deleted
  358. */
  359. private static function retainVersions($filename, $owner, $ownerPath, $timestamp) {
  360. if (\OCP\Server::get(IAppManager::class)->isEnabledForUser('files_versions') && !empty($ownerPath)) {
  361. $user = OC_User::getUser();
  362. $rootView = new View('/');
  363. if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
  364. if ($owner !== $user) {
  365. self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . static::getTrashFilename(basename($ownerPath), $timestamp), $rootView);
  366. }
  367. self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . static::getTrashFilename($filename, $timestamp));
  368. } elseif ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
  369. foreach ($versions as $v) {
  370. if ($owner !== $user) {
  371. self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . static::getTrashFilename($v['name'] . '.v' . $v['version'], $timestamp));
  372. }
  373. self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . static::getTrashFilename($filename . '.v' . $v['version'], $timestamp));
  374. }
  375. }
  376. }
  377. }
  378. /**
  379. * Move a file or folder on storage level
  380. *
  381. * @param View $view
  382. * @param string $source
  383. * @param string $target
  384. * @return bool
  385. */
  386. private static function move(View $view, $source, $target) {
  387. /** @var \OC\Files\Storage\Storage $sourceStorage */
  388. [$sourceStorage, $sourceInternalPath] = $view->resolvePath($source);
  389. /** @var \OC\Files\Storage\Storage $targetStorage */
  390. [$targetStorage, $targetInternalPath] = $view->resolvePath($target);
  391. /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
  392. $result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  393. if ($result) {
  394. $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  395. }
  396. return $result;
  397. }
  398. /**
  399. * Copy a file or folder on storage level
  400. *
  401. * @param View $view
  402. * @param string $source
  403. * @param string $target
  404. * @return bool
  405. */
  406. private static function copy(View $view, $source, $target) {
  407. /** @var \OC\Files\Storage\Storage $sourceStorage */
  408. [$sourceStorage, $sourceInternalPath] = $view->resolvePath($source);
  409. /** @var \OC\Files\Storage\Storage $targetStorage */
  410. [$targetStorage, $targetInternalPath] = $view->resolvePath($target);
  411. /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
  412. $result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  413. if ($result) {
  414. $targetStorage->getUpdater()->update($targetInternalPath);
  415. }
  416. return $result;
  417. }
  418. /**
  419. * Restore a file or folder from trash bin
  420. *
  421. * @param string $file path to the deleted file/folder relative to "files_trashbin/files/",
  422. * including the timestamp suffix ".d12345678"
  423. * @param string $filename name of the file/folder
  424. * @param int $timestamp time when the file/folder was deleted
  425. *
  426. * @return bool true on success, false otherwise
  427. */
  428. public static function restore($file, $filename, $timestamp) {
  429. $user = OC_User::getUser();
  430. $view = new View('/' . $user);
  431. $location = '';
  432. if ($timestamp) {
  433. $location = self::getLocation($user, $filename, $timestamp);
  434. if ($location === false) {
  435. \OC::$server->get(LoggerInterface::class)->error('trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']);
  436. } else {
  437. // if location no longer exists, restore file in the root directory
  438. if ($location !== '/' &&
  439. (!$view->is_dir('files/' . $location) ||
  440. !$view->isCreatable('files/' . $location))
  441. ) {
  442. $location = '';
  443. }
  444. }
  445. }
  446. // we need a extension in case a file/dir with the same name already exists
  447. $uniqueFilename = self::getUniqueFilename($location, $filename, $view);
  448. $source = Filesystem::normalizePath('files_trashbin/files/' . $file);
  449. $target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
  450. if (!$view->file_exists($source)) {
  451. return false;
  452. }
  453. $mtime = $view->filemtime($source);
  454. // restore file
  455. if (!$view->isCreatable(dirname($target))) {
  456. throw new NotPermittedException("Can't restore trash item because the target folder is not writable");
  457. }
  458. $sourcePath = Filesystem::normalizePath($file);
  459. $targetPath = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
  460. $sourceNode = self::getNodeForPath($sourcePath);
  461. $targetNode = self::getNodeForPath($targetPath);
  462. $run = true;
  463. $event = new BeforeNodeRestoredEvent($sourceNode, $targetNode, $run);
  464. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  465. $dispatcher->dispatchTyped($event);
  466. if (!$run) {
  467. return false;
  468. }
  469. $restoreResult = $view->rename($source, $target);
  470. // handle the restore result
  471. if ($restoreResult) {
  472. $fakeRoot = $view->getRoot();
  473. $view->chroot('/' . $user . '/files');
  474. $view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
  475. $view->chroot($fakeRoot);
  476. \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', ['filePath' => $targetPath, 'trashPath' => $sourcePath]);
  477. $sourceNode = self::getNodeForPath($sourcePath);
  478. $targetNode = self::getNodeForPath($targetPath);
  479. $event = new NodeRestoredEvent($sourceNode, $targetNode);
  480. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  481. $dispatcher->dispatchTyped($event);
  482. self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
  483. if ($timestamp) {
  484. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  485. $query->delete('files_trash')
  486. ->where($query->expr()->eq('user', $query->createNamedParameter($user)))
  487. ->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
  488. ->andWhere($query->expr()->eq('timestamp', $query->createNamedParameter($timestamp)));
  489. $query->executeStatement();
  490. }
  491. return true;
  492. }
  493. return false;
  494. }
  495. /**
  496. * restore versions from trash bin
  497. *
  498. * @param View $view file view
  499. * @param string $file complete path to file
  500. * @param string $filename name of file once it was deleted
  501. * @param string $uniqueFilename new file name to restore the file without overwriting existing files
  502. * @param string $location location if file
  503. * @param int $timestamp deletion time
  504. * @return false|null
  505. */
  506. private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) {
  507. if (\OCP\Server::get(IAppManager::class)->isEnabledForUser('files_versions')) {
  508. $user = OC_User::getUser();
  509. $rootView = new View('/');
  510. $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
  511. [$owner, $ownerPath] = self::getUidAndFilename($target);
  512. // file has been deleted in between
  513. if (empty($ownerPath)) {
  514. return false;
  515. }
  516. if ($timestamp) {
  517. $versionedFile = $filename;
  518. } else {
  519. $versionedFile = $file;
  520. }
  521. if ($view->is_dir('/files_trashbin/versions/' . $file)) {
  522. $rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
  523. } elseif ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
  524. foreach ($versions as $v) {
  525. if ($timestamp) {
  526. $rootView->rename($user . '/files_trashbin/versions/' . static::getTrashFilename($versionedFile . '.v' . $v, $timestamp), $owner . '/files_versions/' . $ownerPath . '.v' . $v);
  527. } else {
  528. $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
  529. }
  530. }
  531. }
  532. }
  533. }
  534. /**
  535. * delete all files from the trash
  536. */
  537. public static function deleteAll() {
  538. $user = OC_User::getUser();
  539. $userRoot = \OC::$server->getUserFolder($user)->getParent();
  540. $view = new View('/' . $user);
  541. $fileInfos = $view->getDirectoryContent('files_trashbin/files');
  542. try {
  543. $trash = $userRoot->get('files_trashbin');
  544. } catch (NotFoundException $e) {
  545. return false;
  546. }
  547. // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
  548. $filePaths = [];
  549. foreach ($fileInfos as $fileInfo) {
  550. $filePaths[] = $view->getRelativePath($fileInfo->getPath());
  551. }
  552. unset($fileInfos); // save memory
  553. // Bulk PreDelete-Hook
  554. \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', ['paths' => $filePaths]);
  555. // Single-File Hooks
  556. foreach ($filePaths as $path) {
  557. self::emitTrashbinPreDelete($path);
  558. }
  559. // actual file deletion
  560. $trash->delete();
  561. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  562. $query->delete('files_trash')
  563. ->where($query->expr()->eq('user', $query->createNamedParameter($user)));
  564. $query->executeStatement();
  565. // Bulk PostDelete-Hook
  566. \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', ['paths' => $filePaths]);
  567. // Single-File Hooks
  568. foreach ($filePaths as $path) {
  569. self::emitTrashbinPostDelete($path);
  570. }
  571. $trash = $userRoot->newFolder('files_trashbin');
  572. $trash->newFolder('files');
  573. return true;
  574. }
  575. /**
  576. * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
  577. *
  578. * @param string $path
  579. */
  580. protected static function emitTrashbinPreDelete($path) {
  581. \OC_Hook::emit('\OCP\Trashbin', 'preDelete', ['path' => $path]);
  582. }
  583. /**
  584. * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
  585. *
  586. * @param string $path
  587. */
  588. protected static function emitTrashbinPostDelete($path) {
  589. \OC_Hook::emit('\OCP\Trashbin', 'delete', ['path' => $path]);
  590. }
  591. /**
  592. * delete file from trash bin permanently
  593. *
  594. * @param string $filename path to the file
  595. * @param string $user
  596. * @param int $timestamp of deletion time
  597. *
  598. * @return int|float size of deleted files
  599. */
  600. public static function delete($filename, $user, $timestamp = null) {
  601. $userRoot = \OC::$server->getUserFolder($user)->getParent();
  602. $view = new View('/' . $user);
  603. $size = 0;
  604. if ($timestamp) {
  605. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  606. $query->delete('files_trash')
  607. ->where($query->expr()->eq('user', $query->createNamedParameter($user)))
  608. ->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
  609. ->andWhere($query->expr()->eq('timestamp', $query->createNamedParameter($timestamp)));
  610. $query->executeStatement();
  611. $file = static::getTrashFilename($filename, $timestamp);
  612. } else {
  613. $file = $filename;
  614. }
  615. $size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
  616. try {
  617. $node = $userRoot->get('/files_trashbin/files/' . $file);
  618. } catch (NotFoundException $e) {
  619. return $size;
  620. }
  621. if ($node instanceof Folder) {
  622. $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
  623. } elseif ($node instanceof File) {
  624. $size += $view->filesize('/files_trashbin/files/' . $file);
  625. }
  626. self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
  627. $node->delete();
  628. self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
  629. return $size;
  630. }
  631. /**
  632. * @param string $file
  633. * @param string $filename
  634. * @param ?int $timestamp
  635. */
  636. private static function deleteVersions(View $view, $file, $filename, $timestamp, string $user): int|float {
  637. $size = 0;
  638. if (\OCP\Server::get(IAppManager::class)->isEnabledForUser('files_versions')) {
  639. if ($view->is_dir('files_trashbin/versions/' . $file)) {
  640. $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
  641. $view->unlink('files_trashbin/versions/' . $file);
  642. } elseif ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
  643. foreach ($versions as $v) {
  644. if ($timestamp) {
  645. $size += $view->filesize('/files_trashbin/versions/' . static::getTrashFilename($filename . '.v' . $v, $timestamp));
  646. $view->unlink('/files_trashbin/versions/' . static::getTrashFilename($filename . '.v' . $v, $timestamp));
  647. } else {
  648. $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
  649. $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
  650. }
  651. }
  652. }
  653. }
  654. return $size;
  655. }
  656. /**
  657. * check to see whether a file exists in trashbin
  658. *
  659. * @param string $filename path to the file
  660. * @param int $timestamp of deletion time
  661. * @return bool true if file exists, otherwise false
  662. */
  663. public static function file_exists($filename, $timestamp = null) {
  664. $user = OC_User::getUser();
  665. $view = new View('/' . $user);
  666. if ($timestamp) {
  667. $filename = static::getTrashFilename($filename, $timestamp);
  668. }
  669. $target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
  670. return $view->file_exists($target);
  671. }
  672. /**
  673. * deletes used space for trash bin in db if user was deleted
  674. *
  675. * @param string $uid id of deleted user
  676. * @return bool result of db delete operation
  677. */
  678. public static function deleteUser($uid) {
  679. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  680. $query->delete('files_trash')
  681. ->where($query->expr()->eq('user', $query->createNamedParameter($uid)));
  682. return (bool) $query->executeStatement();
  683. }
  684. /**
  685. * calculate remaining free space for trash bin
  686. *
  687. * @param int|float $trashbinSize current size of the trash bin
  688. * @param string $user
  689. * @return int|float available free space for trash bin
  690. */
  691. private static function calculateFreeSpace(int|float $trashbinSize, string $user): int|float {
  692. $configuredTrashbinSize = static::getConfiguredTrashbinSize($user);
  693. if ($configuredTrashbinSize > -1) {
  694. return $configuredTrashbinSize - $trashbinSize;
  695. }
  696. $userObject = \OC::$server->getUserManager()->get($user);
  697. if (is_null($userObject)) {
  698. return 0;
  699. }
  700. $softQuota = true;
  701. $quota = $userObject->getQuota();
  702. if ($quota === null || $quota === 'none') {
  703. $quota = Filesystem::free_space('/');
  704. $softQuota = false;
  705. // inf or unknown free space
  706. if ($quota < 0) {
  707. $quota = PHP_INT_MAX;
  708. }
  709. } else {
  710. $quota = \OCP\Util::computerFileSize($quota);
  711. // invalid quota
  712. if ($quota === false) {
  713. $quota = PHP_INT_MAX;
  714. }
  715. }
  716. // calculate available space for trash bin
  717. // subtract size of files and current trash bin size from quota
  718. if ($softQuota) {
  719. $userFolder = \OC::$server->getUserFolder($user);
  720. if (is_null($userFolder)) {
  721. return 0;
  722. }
  723. $free = $quota - $userFolder->getSize(false); // remaining free space for user
  724. if ($free > 0) {
  725. $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
  726. } else {
  727. $availableSpace = $free - $trashbinSize;
  728. }
  729. } else {
  730. $availableSpace = $quota;
  731. }
  732. return \OCP\Util::numericToNumber($availableSpace);
  733. }
  734. /**
  735. * resize trash bin if necessary after a new file was added to Nextcloud
  736. *
  737. * @param string $user user id
  738. */
  739. public static function resizeTrash($user) {
  740. $size = self::getTrashbinSize($user);
  741. $freeSpace = self::calculateFreeSpace($size, $user);
  742. if ($freeSpace < 0) {
  743. self::scheduleExpire($user);
  744. }
  745. }
  746. /**
  747. * clean up the trash bin
  748. *
  749. * @param string $user
  750. */
  751. public static function expire($user) {
  752. $trashBinSize = self::getTrashbinSize($user);
  753. $availableSpace = self::calculateFreeSpace($trashBinSize, $user);
  754. $dirContent = Helper::getTrashFiles('/', $user, 'mtime');
  755. // delete all files older then $retention_obligation
  756. [$delSize, $count] = self::deleteExpiredFiles($dirContent, $user);
  757. $availableSpace += $delSize;
  758. // delete files from trash until we meet the trash bin size limit again
  759. self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
  760. }
  761. /**
  762. * @param string $user
  763. */
  764. private static function scheduleExpire($user) {
  765. // let the admin disable auto expire
  766. /** @var Application $application */
  767. $application = \OC::$server->query(Application::class);
  768. $expiration = $application->getContainer()->query('Expiration');
  769. if ($expiration->isEnabled()) {
  770. \OC::$server->getCommandBus()->push(new Expire($user));
  771. }
  772. }
  773. /**
  774. * if the size limit for the trash bin is reached, we delete the oldest
  775. * files in the trash bin until we meet the limit again
  776. *
  777. * @param array $files
  778. * @param string $user
  779. * @param int|float $availableSpace available disc space
  780. * @return int|float size of deleted files
  781. */
  782. protected static function deleteFiles(array $files, string $user, int|float $availableSpace): int|float {
  783. /** @var Application $application */
  784. $application = \OC::$server->query(Application::class);
  785. $expiration = $application->getContainer()->query('Expiration');
  786. $size = 0;
  787. if ($availableSpace < 0) {
  788. foreach ($files as $file) {
  789. if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
  790. $tmp = self::delete($file['name'], $user, $file['mtime']);
  791. \OC::$server->get(LoggerInterface::class)->info('remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', ['app' => 'files_trashbin']);
  792. $availableSpace += $tmp;
  793. $size += $tmp;
  794. } else {
  795. break;
  796. }
  797. }
  798. }
  799. return $size;
  800. }
  801. /**
  802. * delete files older then max storage time
  803. *
  804. * @param array $files list of files sorted by mtime
  805. * @param string $user
  806. * @return array{int|float, int} size of deleted files and number of deleted files
  807. */
  808. public static function deleteExpiredFiles($files, $user) {
  809. /** @var Expiration $expiration */
  810. $expiration = \OC::$server->query(Expiration::class);
  811. $size = 0;
  812. $count = 0;
  813. foreach ($files as $file) {
  814. $timestamp = $file['mtime'];
  815. $filename = $file['name'];
  816. if ($expiration->isExpired($timestamp)) {
  817. try {
  818. $size += self::delete($filename, $user, $timestamp);
  819. $count++;
  820. } catch (\OCP\Files\NotPermittedException $e) {
  821. \OC::$server->get(LoggerInterface::class)->warning('Removing "' . $filename . '" from trashbin failed.',
  822. [
  823. 'exception' => $e,
  824. 'app' => 'files_trashbin',
  825. ]
  826. );
  827. }
  828. \OC::$server->get(LoggerInterface::class)->info(
  829. 'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
  830. ['app' => 'files_trashbin']
  831. );
  832. } else {
  833. break;
  834. }
  835. }
  836. return [$size, $count];
  837. }
  838. /**
  839. * recursive copy to copy a whole directory
  840. *
  841. * @param string $source source path, relative to the users files directory
  842. * @param string $destination destination path relative to the users root directory
  843. * @param View $view file view for the users root directory
  844. * @return int|float
  845. * @throws Exceptions\CopyRecursiveException
  846. */
  847. private static function copy_recursive($source, $destination, View $view): int|float {
  848. $size = 0;
  849. if ($view->is_dir($source)) {
  850. $view->mkdir($destination);
  851. $view->touch($destination, $view->filemtime($source));
  852. foreach ($view->getDirectoryContent($source) as $i) {
  853. $pathDir = $source . '/' . $i['name'];
  854. if ($view->is_dir($pathDir)) {
  855. $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
  856. } else {
  857. $size += $view->filesize($pathDir);
  858. $result = $view->copy($pathDir, $destination . '/' . $i['name']);
  859. if (!$result) {
  860. throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
  861. }
  862. $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
  863. }
  864. }
  865. } else {
  866. $size += $view->filesize($source);
  867. $result = $view->copy($source, $destination);
  868. if (!$result) {
  869. throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
  870. }
  871. $view->touch($destination, $view->filemtime($source));
  872. }
  873. return $size;
  874. }
  875. /**
  876. * find all versions which belong to the file we want to restore
  877. *
  878. * @param string $filename name of the file which should be restored
  879. * @param int $timestamp timestamp when the file was deleted
  880. */
  881. private static function getVersionsFromTrash($filename, $timestamp, string $user): array {
  882. $view = new View('/' . $user . '/files_trashbin/versions');
  883. $versions = [];
  884. /** @var \OC\Files\Storage\Storage $storage */
  885. [$storage,] = $view->resolvePath('/');
  886. $pattern = \OC::$server->getDatabaseConnection()->escapeLikeParameter(basename($filename));
  887. if ($timestamp) {
  888. // fetch for old versions
  889. $escapedTimestamp = \OC::$server->getDatabaseConnection()->escapeLikeParameter($timestamp);
  890. $pattern .= '.v%.d' . $escapedTimestamp;
  891. $offset = -strlen($escapedTimestamp) - 2;
  892. } else {
  893. $pattern .= '.v%';
  894. }
  895. // Manually fetch all versions from the file cache to be able to filter them by their parent
  896. $cache = $storage->getCache('');
  897. $query = new CacheQueryBuilder(
  898. \OC::$server->getDatabaseConnection(),
  899. \OC::$server->getSystemConfig(),
  900. \OC::$server->get(LoggerInterface::class),
  901. \OC::$server->get(IFilesMetadataManager::class),
  902. );
  903. $normalizedParentPath = ltrim(Filesystem::normalizePath(dirname('files_trashbin/versions/'. $filename)), '/');
  904. $parentId = $cache->getId($normalizedParentPath);
  905. if ($parentId === -1) {
  906. return [];
  907. }
  908. $query->selectFileCache()
  909. ->whereStorageId($cache->getNumericStorageId())
  910. ->andWhere($query->expr()->eq('parent', $query->createNamedParameter($parentId)))
  911. ->andWhere($query->expr()->iLike('name', $query->createNamedParameter($pattern)));
  912. $result = $query->executeQuery();
  913. $entries = $result->fetchAll();
  914. $result->closeCursor();
  915. /** @var CacheEntry[] $matches */
  916. $matches = array_map(function (array $data) {
  917. return Cache::cacheEntryFromData($data, \OC::$server->getMimeTypeLoader());
  918. }, $entries);
  919. foreach ($matches as $ma) {
  920. if ($timestamp) {
  921. $parts = explode('.v', substr($ma['path'], 0, $offset));
  922. $versions[] = end($parts);
  923. } else {
  924. $parts = explode('.v', $ma['path']);
  925. $versions[] = end($parts);
  926. }
  927. }
  928. return $versions;
  929. }
  930. /**
  931. * find unique extension for restored file if a file with the same name already exists
  932. *
  933. * @param string $location where the file should be restored
  934. * @param string $filename name of the file
  935. * @param View $view filesystem view relative to users root directory
  936. * @return string with unique extension
  937. */
  938. private static function getUniqueFilename($location, $filename, View $view) {
  939. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  940. $name = pathinfo($filename, PATHINFO_FILENAME);
  941. $l = \OCP\Util::getL10N('files_trashbin');
  942. $location = '/' . trim($location, '/');
  943. // if extension is not empty we set a dot in front of it
  944. if ($ext !== '') {
  945. $ext = '.' . $ext;
  946. }
  947. if ($view->file_exists('files' . $location . '/' . $filename)) {
  948. $i = 2;
  949. $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
  950. while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
  951. $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
  952. $i++;
  953. }
  954. return $uniqueName;
  955. }
  956. return $filename;
  957. }
  958. /**
  959. * get the size from a given root folder
  960. *
  961. * @param View $view file view on the root folder
  962. * @return int|float size of the folder
  963. */
  964. private static function calculateSize(View $view): int|float {
  965. $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
  966. if (!file_exists($root)) {
  967. return 0;
  968. }
  969. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
  970. $size = 0;
  971. /**
  972. * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
  973. * This bug is fixed in PHP 5.5.9 or before
  974. * See #8376
  975. */
  976. $iterator->rewind();
  977. while ($iterator->valid()) {
  978. $path = $iterator->current();
  979. $relpath = substr($path, strlen($root) - 1);
  980. if (!$view->is_dir($relpath)) {
  981. $size += $view->filesize($relpath);
  982. }
  983. $iterator->next();
  984. }
  985. return $size;
  986. }
  987. /**
  988. * get current size of trash bin from a given user
  989. *
  990. * @param string $user user who owns the trash bin
  991. * @return int|float trash bin size
  992. */
  993. private static function getTrashbinSize(string $user): int|float {
  994. $view = new View('/' . $user);
  995. $fileInfo = $view->getFileInfo('/files_trashbin');
  996. return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
  997. }
  998. /**
  999. * check if trash bin is empty for a given user
  1000. *
  1001. * @param string $user
  1002. * @return bool
  1003. */
  1004. public static function isEmpty($user) {
  1005. $view = new View('/' . $user . '/files_trashbin');
  1006. if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
  1007. while (($file = readdir($dh)) !== false) {
  1008. if (!Filesystem::isIgnoredDir($file)) {
  1009. return false;
  1010. }
  1011. }
  1012. }
  1013. return true;
  1014. }
  1015. /**
  1016. * @param $path
  1017. * @return string
  1018. */
  1019. public static function preview_icon($path) {
  1020. return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_trashbin_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
  1021. }
  1022. /**
  1023. * Return the filename used in the trash bin
  1024. */
  1025. public static function getTrashFilename(string $filename, int $timestamp): string {
  1026. $trashFilename = $filename . '.d' . $timestamp;
  1027. $length = strlen($trashFilename);
  1028. // oc_filecache `name` column has a limit of 250 chars
  1029. $maxLength = 250;
  1030. if ($length > $maxLength) {
  1031. $trashFilename = substr_replace(
  1032. $trashFilename,
  1033. '',
  1034. $maxLength / 2,
  1035. $length - $maxLength
  1036. );
  1037. }
  1038. return $trashFilename;
  1039. }
  1040. private static function getNodeForPath(string $path): Node {
  1041. $user = OC_User::getUser();
  1042. $rootFolder = \OC::$server->get(IRootFolder::class);
  1043. if ($user !== false) {
  1044. $userFolder = $rootFolder->getUserFolder($user);
  1045. /** @var Folder */
  1046. $trashFolder = $userFolder->getParent()->get('files_trashbin/files');
  1047. try {
  1048. return $trashFolder->get($path);
  1049. } catch (NotFoundException $ex) {
  1050. }
  1051. }
  1052. $view = \OC::$server->get(View::class);
  1053. $fsView = Filesystem::getView();
  1054. if ($fsView === null) {
  1055. throw new Exception('View should not be null');
  1056. }
  1057. $fullPath = $fsView->getAbsolutePath($path);
  1058. if (Filesystem::is_dir($path)) {
  1059. return new NonExistingFolder($rootFolder, $view, $fullPath);
  1060. } else {
  1061. return new NonExistingFile($rootFolder, $view, $fullPath);
  1062. }
  1063. }
  1064. }