Trashbin.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  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\ObjectStore\ObjectStoreStorage;
  56. use OC\Files\View;
  57. use OC_User;
  58. use OCA\Files_Trashbin\AppInfo\Application;
  59. use OCA\Files_Trashbin\Command\Expire;
  60. use OCA\Files_Trashbin\Events\BeforeNodeRestoredEvent;
  61. use OCA\Files_Trashbin\Events\NodeRestoredEvent;
  62. use OCP\App\IAppManager;
  63. use OCP\AppFramework\Utility\ITimeFactory;
  64. use OCP\EventDispatcher\IEventDispatcher;
  65. use OCP\Files\IRootFolder;
  66. use OCP\Files\Node;
  67. use OCP\Files\NotFoundException;
  68. use OCP\Files\NotPermittedException;
  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. while (!$gotLock) {
  264. try {
  265. /** @var \OC\Files\Storage\Storage $trashStorage */
  266. [$trashStorage, $trashInternalPath] = $ownerView->resolvePath($trashPath);
  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. }
  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. $trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
  286. try {
  287. $moveSuccessful = true;
  288. // when moving within the same object store, the cache update done above is enough to move the file
  289. if (!($trashStorage->instanceOfStorage(ObjectStoreStorage::class) && $trashStorage->getId() === $sourceStorage->getId())) {
  290. $trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
  291. }
  292. } catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) {
  293. $moveSuccessful = false;
  294. if ($trashStorage->file_exists($trashInternalPath)) {
  295. $trashStorage->unlink($trashInternalPath);
  296. }
  297. \OC::$server->get(LoggerInterface::class)->error('Couldn\'t move ' . $file_path . ' to the trash bin', ['app' => 'files_trashbin']);
  298. }
  299. if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
  300. if ($sourceStorage->is_dir($sourceInternalPath)) {
  301. $sourceStorage->rmdir($sourceInternalPath);
  302. } else {
  303. $sourceStorage->unlink($sourceInternalPath);
  304. }
  305. if ($sourceStorage->file_exists($sourceInternalPath)) {
  306. // undo the cache move
  307. $sourceStorage->getUpdater()->renameFromStorage($trashStorage, $trashInternalPath, $sourceInternalPath);
  308. } else {
  309. $trashStorage->getUpdater()->remove($trashInternalPath);
  310. }
  311. return false;
  312. }
  313. if ($moveSuccessful) {
  314. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  315. $query->insert('files_trash')
  316. ->setValue('id', $query->createNamedParameter($filename))
  317. ->setValue('timestamp', $query->createNamedParameter($timestamp))
  318. ->setValue('location', $query->createNamedParameter($location))
  319. ->setValue('user', $query->createNamedParameter($owner));
  320. $result = $query->executeStatement();
  321. if (!$result) {
  322. \OC::$server->get(LoggerInterface::class)->error('trash bin database couldn\'t be updated', ['app' => 'files_trashbin']);
  323. }
  324. \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', ['filePath' => Filesystem::normalizePath($file_path),
  325. 'trashPath' => Filesystem::normalizePath(static::getTrashFilename($filename, $timestamp))]);
  326. self::retainVersions($filename, $owner, $ownerPath, $timestamp);
  327. // if owner !== user we need to also add a copy to the users trash
  328. if ($user !== $owner && $ownerOnly === false) {
  329. self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp);
  330. }
  331. }
  332. $trashStorage->releaseLock($trashInternalPath, ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  333. self::scheduleExpire($user);
  334. // if owner !== user we also need to update the owners trash size
  335. if ($owner !== $user) {
  336. self::scheduleExpire($owner);
  337. }
  338. return $moveSuccessful;
  339. }
  340. private static function getConfiguredTrashbinSize(string $user): int|float {
  341. $config = \OC::$server->get(IConfig::class);
  342. $userTrashbinSize = $config->getUserValue($user, 'files_trashbin', 'trashbin_size', '-1');
  343. if (is_numeric($userTrashbinSize) && ($userTrashbinSize > -1)) {
  344. return \OCP\Util::numericToNumber($userTrashbinSize);
  345. }
  346. $systemTrashbinSize = $config->getAppValue('files_trashbin', 'trashbin_size', '-1');
  347. if (is_numeric($systemTrashbinSize)) {
  348. return \OCP\Util::numericToNumber($systemTrashbinSize);
  349. }
  350. return -1;
  351. }
  352. /**
  353. * Move file versions to trash so that they can be restored later
  354. *
  355. * @param string $filename of deleted file
  356. * @param string $owner owner user id
  357. * @param string $ownerPath path relative to the owner's home storage
  358. * @param int $timestamp when the file was deleted
  359. */
  360. private static function retainVersions($filename, $owner, $ownerPath, $timestamp) {
  361. if (\OCP\Server::get(IAppManager::class)->isEnabledForUser('files_versions') && !empty($ownerPath)) {
  362. $user = OC_User::getUser();
  363. $rootView = new View('/');
  364. if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
  365. if ($owner !== $user) {
  366. self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . static::getTrashFilename(basename($ownerPath), $timestamp), $rootView);
  367. }
  368. self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . static::getTrashFilename($filename, $timestamp));
  369. } elseif ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
  370. foreach ($versions as $v) {
  371. if ($owner !== $user) {
  372. self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . static::getTrashFilename($v['name'] . '.v' . $v['version'], $timestamp));
  373. }
  374. self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . static::getTrashFilename($filename . '.v' . $v['version'], $timestamp));
  375. }
  376. }
  377. }
  378. }
  379. /**
  380. * Move a file or folder on storage level
  381. *
  382. * @param View $view
  383. * @param string $source
  384. * @param string $target
  385. * @return bool
  386. */
  387. private static function move(View $view, $source, $target) {
  388. /** @var \OC\Files\Storage\Storage $sourceStorage */
  389. [$sourceStorage, $sourceInternalPath] = $view->resolvePath($source);
  390. /** @var \OC\Files\Storage\Storage $targetStorage */
  391. [$targetStorage, $targetInternalPath] = $view->resolvePath($target);
  392. /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
  393. $result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  394. if ($result) {
  395. $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  396. }
  397. return $result;
  398. }
  399. /**
  400. * Copy a file or folder on storage level
  401. *
  402. * @param View $view
  403. * @param string $source
  404. * @param string $target
  405. * @return bool
  406. */
  407. private static function copy(View $view, $source, $target) {
  408. /** @var \OC\Files\Storage\Storage $sourceStorage */
  409. [$sourceStorage, $sourceInternalPath] = $view->resolvePath($source);
  410. /** @var \OC\Files\Storage\Storage $targetStorage */
  411. [$targetStorage, $targetInternalPath] = $view->resolvePath($target);
  412. /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
  413. $result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  414. if ($result) {
  415. $targetStorage->getUpdater()->update($targetInternalPath);
  416. }
  417. return $result;
  418. }
  419. /**
  420. * Restore a file or folder from trash bin
  421. *
  422. * @param string $file path to the deleted file/folder relative to "files_trashbin/files/",
  423. * including the timestamp suffix ".d12345678"
  424. * @param string $filename name of the file/folder
  425. * @param int $timestamp time when the file/folder was deleted
  426. *
  427. * @return bool true on success, false otherwise
  428. */
  429. public static function restore($file, $filename, $timestamp) {
  430. $user = OC_User::getUser();
  431. $view = new View('/' . $user);
  432. $location = '';
  433. if ($timestamp) {
  434. $location = self::getLocation($user, $filename, $timestamp);
  435. if ($location === false) {
  436. \OC::$server->get(LoggerInterface::class)->error('trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']);
  437. } else {
  438. // if location no longer exists, restore file in the root directory
  439. if ($location !== '/' &&
  440. (!$view->is_dir('files/' . $location) ||
  441. !$view->isCreatable('files/' . $location))
  442. ) {
  443. $location = '';
  444. }
  445. }
  446. }
  447. // we need a extension in case a file/dir with the same name already exists
  448. $uniqueFilename = self::getUniqueFilename($location, $filename, $view);
  449. $source = Filesystem::normalizePath('files_trashbin/files/' . $file);
  450. $target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
  451. if (!$view->file_exists($source)) {
  452. return false;
  453. }
  454. $mtime = $view->filemtime($source);
  455. // restore file
  456. if (!$view->isCreatable(dirname($target))) {
  457. throw new NotPermittedException("Can't restore trash item because the target folder is not writable");
  458. }
  459. $sourcePath = Filesystem::normalizePath($file);
  460. $targetPath = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
  461. $sourceNode = self::getNodeForPath($sourcePath);
  462. $targetNode = self::getNodeForPath($targetPath);
  463. $run = true;
  464. $event = new BeforeNodeRestoredEvent($sourceNode, $targetNode, $run);
  465. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  466. $dispatcher->dispatchTyped($event);
  467. if (!$run) {
  468. return false;
  469. }
  470. $restoreResult = $view->rename($source, $target);
  471. // handle the restore result
  472. if ($restoreResult) {
  473. $fakeRoot = $view->getRoot();
  474. $view->chroot('/' . $user . '/files');
  475. $view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
  476. $view->chroot($fakeRoot);
  477. \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', ['filePath' => $targetPath, 'trashPath' => $sourcePath]);
  478. $sourceNode = self::getNodeForPath($sourcePath);
  479. $targetNode = self::getNodeForPath($targetPath);
  480. $event = new NodeRestoredEvent($sourceNode, $targetNode);
  481. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  482. $dispatcher->dispatchTyped($event);
  483. self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
  484. if ($timestamp) {
  485. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  486. $query->delete('files_trash')
  487. ->where($query->expr()->eq('user', $query->createNamedParameter($user)))
  488. ->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
  489. ->andWhere($query->expr()->eq('timestamp', $query->createNamedParameter($timestamp)));
  490. $query->executeStatement();
  491. }
  492. return true;
  493. }
  494. return false;
  495. }
  496. /**
  497. * restore versions from trash bin
  498. *
  499. * @param View $view file view
  500. * @param string $file complete path to file
  501. * @param string $filename name of file once it was deleted
  502. * @param string $uniqueFilename new file name to restore the file without overwriting existing files
  503. * @param string $location location if file
  504. * @param int $timestamp deletion time
  505. * @return false|null
  506. */
  507. private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) {
  508. if (\OCP\Server::get(IAppManager::class)->isEnabledForUser('files_versions')) {
  509. $user = OC_User::getUser();
  510. $rootView = new View('/');
  511. $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
  512. [$owner, $ownerPath] = self::getUidAndFilename($target);
  513. // file has been deleted in between
  514. if (empty($ownerPath)) {
  515. return false;
  516. }
  517. if ($timestamp) {
  518. $versionedFile = $filename;
  519. } else {
  520. $versionedFile = $file;
  521. }
  522. if ($view->is_dir('/files_trashbin/versions/' . $file)) {
  523. $rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
  524. } elseif ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
  525. foreach ($versions as $v) {
  526. if ($timestamp) {
  527. $rootView->rename($user . '/files_trashbin/versions/' . static::getTrashFilename($versionedFile . '.v' . $v, $timestamp), $owner . '/files_versions/' . $ownerPath . '.v' . $v);
  528. } else {
  529. $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
  530. }
  531. }
  532. }
  533. }
  534. }
  535. /**
  536. * delete all files from the trash
  537. */
  538. public static function deleteAll() {
  539. $user = OC_User::getUser();
  540. $userRoot = \OC::$server->getUserFolder($user)->getParent();
  541. $view = new View('/' . $user);
  542. $fileInfos = $view->getDirectoryContent('files_trashbin/files');
  543. try {
  544. $trash = $userRoot->get('files_trashbin');
  545. } catch (NotFoundException $e) {
  546. return false;
  547. }
  548. // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
  549. $filePaths = [];
  550. foreach ($fileInfos as $fileInfo) {
  551. $filePaths[] = $view->getRelativePath($fileInfo->getPath());
  552. }
  553. unset($fileInfos); // save memory
  554. // Bulk PreDelete-Hook
  555. \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', ['paths' => $filePaths]);
  556. // Single-File Hooks
  557. foreach ($filePaths as $path) {
  558. self::emitTrashbinPreDelete($path);
  559. }
  560. // actual file deletion
  561. $trash->delete();
  562. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  563. $query->delete('files_trash')
  564. ->where($query->expr()->eq('user', $query->createNamedParameter($user)));
  565. $query->executeStatement();
  566. // Bulk PostDelete-Hook
  567. \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', ['paths' => $filePaths]);
  568. // Single-File Hooks
  569. foreach ($filePaths as $path) {
  570. self::emitTrashbinPostDelete($path);
  571. }
  572. $trash = $userRoot->newFolder('files_trashbin');
  573. $trash->newFolder('files');
  574. return true;
  575. }
  576. /**
  577. * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
  578. *
  579. * @param string $path
  580. */
  581. protected static function emitTrashbinPreDelete($path) {
  582. \OC_Hook::emit('\OCP\Trashbin', 'preDelete', ['path' => $path]);
  583. }
  584. /**
  585. * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
  586. *
  587. * @param string $path
  588. */
  589. protected static function emitTrashbinPostDelete($path) {
  590. \OC_Hook::emit('\OCP\Trashbin', 'delete', ['path' => $path]);
  591. }
  592. /**
  593. * delete file from trash bin permanently
  594. *
  595. * @param string $filename path to the file
  596. * @param string $user
  597. * @param int $timestamp of deletion time
  598. *
  599. * @return int|float size of deleted files
  600. */
  601. public static function delete($filename, $user, $timestamp = null) {
  602. $userRoot = \OC::$server->getUserFolder($user)->getParent();
  603. $view = new View('/' . $user);
  604. $size = 0;
  605. if ($timestamp) {
  606. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  607. $query->delete('files_trash')
  608. ->where($query->expr()->eq('user', $query->createNamedParameter($user)))
  609. ->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
  610. ->andWhere($query->expr()->eq('timestamp', $query->createNamedParameter($timestamp)));
  611. $query->executeStatement();
  612. $file = static::getTrashFilename($filename, $timestamp);
  613. } else {
  614. $file = $filename;
  615. }
  616. $size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
  617. try {
  618. $node = $userRoot->get('/files_trashbin/files/' . $file);
  619. } catch (NotFoundException $e) {
  620. return $size;
  621. }
  622. if ($node instanceof Folder) {
  623. $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
  624. } elseif ($node instanceof File) {
  625. $size += $view->filesize('/files_trashbin/files/' . $file);
  626. }
  627. self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
  628. $node->delete();
  629. self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
  630. return $size;
  631. }
  632. /**
  633. * @param string $file
  634. * @param string $filename
  635. * @param ?int $timestamp
  636. */
  637. private static function deleteVersions(View $view, $file, $filename, $timestamp, string $user): int|float {
  638. $size = 0;
  639. if (\OCP\Server::get(IAppManager::class)->isEnabledForUser('files_versions')) {
  640. if ($view->is_dir('files_trashbin/versions/' . $file)) {
  641. $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
  642. $view->unlink('files_trashbin/versions/' . $file);
  643. } elseif ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
  644. foreach ($versions as $v) {
  645. if ($timestamp) {
  646. $size += $view->filesize('/files_trashbin/versions/' . static::getTrashFilename($filename . '.v' . $v, $timestamp));
  647. $view->unlink('/files_trashbin/versions/' . static::getTrashFilename($filename . '.v' . $v, $timestamp));
  648. } else {
  649. $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
  650. $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
  651. }
  652. }
  653. }
  654. }
  655. return $size;
  656. }
  657. /**
  658. * check to see whether a file exists in trashbin
  659. *
  660. * @param string $filename path to the file
  661. * @param int $timestamp of deletion time
  662. * @return bool true if file exists, otherwise false
  663. */
  664. public static function file_exists($filename, $timestamp = null) {
  665. $user = OC_User::getUser();
  666. $view = new View('/' . $user);
  667. if ($timestamp) {
  668. $filename = static::getTrashFilename($filename, $timestamp);
  669. }
  670. $target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
  671. return $view->file_exists($target);
  672. }
  673. /**
  674. * deletes used space for trash bin in db if user was deleted
  675. *
  676. * @param string $uid id of deleted user
  677. * @return bool result of db delete operation
  678. */
  679. public static function deleteUser($uid) {
  680. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  681. $query->delete('files_trash')
  682. ->where($query->expr()->eq('user', $query->createNamedParameter($uid)));
  683. return (bool) $query->executeStatement();
  684. }
  685. /**
  686. * calculate remaining free space for trash bin
  687. *
  688. * @param int|float $trashbinSize current size of the trash bin
  689. * @param string $user
  690. * @return int|float available free space for trash bin
  691. */
  692. private static function calculateFreeSpace(int|float $trashbinSize, string $user): int|float {
  693. $configuredTrashbinSize = static::getConfiguredTrashbinSize($user);
  694. if ($configuredTrashbinSize > -1) {
  695. return $configuredTrashbinSize - $trashbinSize;
  696. }
  697. $userObject = \OC::$server->getUserManager()->get($user);
  698. if (is_null($userObject)) {
  699. return 0;
  700. }
  701. $softQuota = true;
  702. $quota = $userObject->getQuota();
  703. if ($quota === null || $quota === 'none') {
  704. $quota = Filesystem::free_space('/');
  705. $softQuota = false;
  706. // inf or unknown free space
  707. if ($quota < 0) {
  708. $quota = PHP_INT_MAX;
  709. }
  710. } else {
  711. $quota = \OCP\Util::computerFileSize($quota);
  712. // invalid quota
  713. if ($quota === false) {
  714. $quota = PHP_INT_MAX;
  715. }
  716. }
  717. // calculate available space for trash bin
  718. // subtract size of files and current trash bin size from quota
  719. if ($softQuota) {
  720. $userFolder = \OC::$server->getUserFolder($user);
  721. if (is_null($userFolder)) {
  722. return 0;
  723. }
  724. $free = $quota - $userFolder->getSize(false); // remaining free space for user
  725. if ($free > 0) {
  726. $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
  727. } else {
  728. $availableSpace = $free - $trashbinSize;
  729. }
  730. } else {
  731. $availableSpace = $quota;
  732. }
  733. return \OCP\Util::numericToNumber($availableSpace);
  734. }
  735. /**
  736. * resize trash bin if necessary after a new file was added to Nextcloud
  737. *
  738. * @param string $user user id
  739. */
  740. public static function resizeTrash($user) {
  741. $size = self::getTrashbinSize($user);
  742. $freeSpace = self::calculateFreeSpace($size, $user);
  743. if ($freeSpace < 0) {
  744. self::scheduleExpire($user);
  745. }
  746. }
  747. /**
  748. * clean up the trash bin
  749. *
  750. * @param string $user
  751. */
  752. public static function expire($user) {
  753. $trashBinSize = self::getTrashbinSize($user);
  754. $availableSpace = self::calculateFreeSpace($trashBinSize, $user);
  755. $dirContent = Helper::getTrashFiles('/', $user, 'mtime');
  756. // delete all files older then $retention_obligation
  757. [$delSize, $count] = self::deleteExpiredFiles($dirContent, $user);
  758. $availableSpace += $delSize;
  759. // delete files from trash until we meet the trash bin size limit again
  760. self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
  761. }
  762. /**
  763. * @param string $user
  764. */
  765. private static function scheduleExpire($user) {
  766. // let the admin disable auto expire
  767. /** @var Application $application */
  768. $application = \OC::$server->query(Application::class);
  769. $expiration = $application->getContainer()->query('Expiration');
  770. if ($expiration->isEnabled()) {
  771. \OC::$server->getCommandBus()->push(new Expire($user));
  772. }
  773. }
  774. /**
  775. * if the size limit for the trash bin is reached, we delete the oldest
  776. * files in the trash bin until we meet the limit again
  777. *
  778. * @param array $files
  779. * @param string $user
  780. * @param int|float $availableSpace available disc space
  781. * @return int|float size of deleted files
  782. */
  783. protected static function deleteFiles(array $files, string $user, int|float $availableSpace): int|float {
  784. /** @var Application $application */
  785. $application = \OC::$server->query(Application::class);
  786. $expiration = $application->getContainer()->query('Expiration');
  787. $size = 0;
  788. if ($availableSpace < 0) {
  789. foreach ($files as $file) {
  790. if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
  791. $tmp = self::delete($file['name'], $user, $file['mtime']);
  792. \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']);
  793. $availableSpace += $tmp;
  794. $size += $tmp;
  795. } else {
  796. break;
  797. }
  798. }
  799. }
  800. return $size;
  801. }
  802. /**
  803. * delete files older then max storage time
  804. *
  805. * @param array $files list of files sorted by mtime
  806. * @param string $user
  807. * @return array{int|float, int} size of deleted files and number of deleted files
  808. */
  809. public static function deleteExpiredFiles($files, $user) {
  810. /** @var Expiration $expiration */
  811. $expiration = \OC::$server->query(Expiration::class);
  812. $size = 0;
  813. $count = 0;
  814. foreach ($files as $file) {
  815. $timestamp = $file['mtime'];
  816. $filename = $file['name'];
  817. if ($expiration->isExpired($timestamp)) {
  818. try {
  819. $size += self::delete($filename, $user, $timestamp);
  820. $count++;
  821. } catch (\OCP\Files\NotPermittedException $e) {
  822. \OC::$server->get(LoggerInterface::class)->warning('Removing "' . $filename . '" from trashbin failed.',
  823. [
  824. 'exception' => $e,
  825. 'app' => 'files_trashbin',
  826. ]
  827. );
  828. }
  829. \OC::$server->get(LoggerInterface::class)->info(
  830. 'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
  831. ['app' => 'files_trashbin']
  832. );
  833. } else {
  834. break;
  835. }
  836. }
  837. return [$size, $count];
  838. }
  839. /**
  840. * recursive copy to copy a whole directory
  841. *
  842. * @param string $source source path, relative to the users files directory
  843. * @param string $destination destination path relative to the users root directory
  844. * @param View $view file view for the users root directory
  845. * @return int|float
  846. * @throws Exceptions\CopyRecursiveException
  847. */
  848. private static function copy_recursive($source, $destination, View $view): int|float {
  849. $size = 0;
  850. if ($view->is_dir($source)) {
  851. $view->mkdir($destination);
  852. $view->touch($destination, $view->filemtime($source));
  853. foreach ($view->getDirectoryContent($source) as $i) {
  854. $pathDir = $source . '/' . $i['name'];
  855. if ($view->is_dir($pathDir)) {
  856. $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
  857. } else {
  858. $size += $view->filesize($pathDir);
  859. $result = $view->copy($pathDir, $destination . '/' . $i['name']);
  860. if (!$result) {
  861. throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
  862. }
  863. $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
  864. }
  865. }
  866. } else {
  867. $size += $view->filesize($source);
  868. $result = $view->copy($source, $destination);
  869. if (!$result) {
  870. throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
  871. }
  872. $view->touch($destination, $view->filemtime($source));
  873. }
  874. return $size;
  875. }
  876. /**
  877. * find all versions which belong to the file we want to restore
  878. *
  879. * @param string $filename name of the file which should be restored
  880. * @param int $timestamp timestamp when the file was deleted
  881. */
  882. private static function getVersionsFromTrash($filename, $timestamp, string $user): array {
  883. $view = new View('/' . $user . '/files_trashbin/versions');
  884. $versions = [];
  885. /** @var \OC\Files\Storage\Storage $storage */
  886. [$storage,] = $view->resolvePath('/');
  887. $pattern = \OC::$server->getDatabaseConnection()->escapeLikeParameter(basename($filename));
  888. if ($timestamp) {
  889. // fetch for old versions
  890. $escapedTimestamp = \OC::$server->getDatabaseConnection()->escapeLikeParameter($timestamp);
  891. $pattern .= '.v%.d' . $escapedTimestamp;
  892. $offset = -strlen($escapedTimestamp) - 2;
  893. } else {
  894. $pattern .= '.v%';
  895. }
  896. // Manually fetch all versions from the file cache to be able to filter them by their parent
  897. $cache = $storage->getCache('');
  898. $query = new CacheQueryBuilder(
  899. \OC::$server->getDatabaseConnection(),
  900. \OC::$server->getSystemConfig(),
  901. \OC::$server->get(LoggerInterface::class),
  902. \OC::$server->get(IFilesMetadataManager::class),
  903. );
  904. $normalizedParentPath = ltrim(Filesystem::normalizePath(dirname('files_trashbin/versions/'. $filename)), '/');
  905. $parentId = $cache->getId($normalizedParentPath);
  906. if ($parentId === -1) {
  907. return [];
  908. }
  909. $query->selectFileCache()
  910. ->whereStorageId($cache->getNumericStorageId())
  911. ->andWhere($query->expr()->eq('parent', $query->createNamedParameter($parentId)))
  912. ->andWhere($query->expr()->iLike('name', $query->createNamedParameter($pattern)));
  913. $result = $query->executeQuery();
  914. $entries = $result->fetchAll();
  915. $result->closeCursor();
  916. /** @var CacheEntry[] $matches */
  917. $matches = array_map(function (array $data) {
  918. return Cache::cacheEntryFromData($data, \OC::$server->getMimeTypeLoader());
  919. }, $entries);
  920. foreach ($matches as $ma) {
  921. if ($timestamp) {
  922. $parts = explode('.v', substr($ma['path'], 0, $offset));
  923. $versions[] = end($parts);
  924. } else {
  925. $parts = explode('.v', $ma['path']);
  926. $versions[] = end($parts);
  927. }
  928. }
  929. return $versions;
  930. }
  931. /**
  932. * find unique extension for restored file if a file with the same name already exists
  933. *
  934. * @param string $location where the file should be restored
  935. * @param string $filename name of the file
  936. * @param View $view filesystem view relative to users root directory
  937. * @return string with unique extension
  938. */
  939. private static function getUniqueFilename($location, $filename, View $view) {
  940. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  941. $name = pathinfo($filename, PATHINFO_FILENAME);
  942. $l = \OCP\Util::getL10N('files_trashbin');
  943. $location = '/' . trim($location, '/');
  944. // if extension is not empty we set a dot in front of it
  945. if ($ext !== '') {
  946. $ext = '.' . $ext;
  947. }
  948. if ($view->file_exists('files' . $location . '/' . $filename)) {
  949. $i = 2;
  950. $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
  951. while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
  952. $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
  953. $i++;
  954. }
  955. return $uniqueName;
  956. }
  957. return $filename;
  958. }
  959. /**
  960. * get the size from a given root folder
  961. *
  962. * @param View $view file view on the root folder
  963. * @return int|float size of the folder
  964. */
  965. private static function calculateSize(View $view): int|float {
  966. $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
  967. if (!file_exists($root)) {
  968. return 0;
  969. }
  970. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
  971. $size = 0;
  972. /**
  973. * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
  974. * This bug is fixed in PHP 5.5.9 or before
  975. * See #8376
  976. */
  977. $iterator->rewind();
  978. while ($iterator->valid()) {
  979. $path = $iterator->current();
  980. $relpath = substr($path, strlen($root) - 1);
  981. if (!$view->is_dir($relpath)) {
  982. $size += $view->filesize($relpath);
  983. }
  984. $iterator->next();
  985. }
  986. return $size;
  987. }
  988. /**
  989. * get current size of trash bin from a given user
  990. *
  991. * @param string $user user who owns the trash bin
  992. * @return int|float trash bin size
  993. */
  994. private static function getTrashbinSize(string $user): int|float {
  995. $view = new View('/' . $user);
  996. $fileInfo = $view->getFileInfo('/files_trashbin');
  997. return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
  998. }
  999. /**
  1000. * check if trash bin is empty for a given user
  1001. *
  1002. * @param string $user
  1003. * @return bool
  1004. */
  1005. public static function isEmpty($user) {
  1006. $view = new View('/' . $user . '/files_trashbin');
  1007. if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
  1008. while ($file = readdir($dh)) {
  1009. if (!Filesystem::isIgnoredDir($file)) {
  1010. return false;
  1011. }
  1012. }
  1013. }
  1014. return true;
  1015. }
  1016. /**
  1017. * @param $path
  1018. * @return string
  1019. */
  1020. public static function preview_icon($path) {
  1021. return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_trashbin_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
  1022. }
  1023. /**
  1024. * Return the filename used in the trash bin
  1025. */
  1026. public static function getTrashFilename(string $filename, int $timestamp): string {
  1027. $trashFilename = $filename . '.d' . $timestamp;
  1028. $length = strlen($trashFilename);
  1029. // oc_filecache `name` column has a limit of 250 chars
  1030. $maxLength = 250;
  1031. if ($length > $maxLength) {
  1032. $trashFilename = substr_replace(
  1033. $trashFilename,
  1034. '',
  1035. $maxLength / 2,
  1036. $length - $maxLength
  1037. );
  1038. }
  1039. return $trashFilename;
  1040. }
  1041. private static function getNodeForPath(string $path): Node {
  1042. $user = OC_User::getUser();
  1043. $rootFolder = \OC::$server->get(IRootFolder::class);
  1044. if ($user !== false) {
  1045. $userFolder = $rootFolder->getUserFolder($user);
  1046. /** @var Folder */
  1047. $trashFolder = $userFolder->getParent()->get('files_trashbin/files');
  1048. try {
  1049. return $trashFolder->get($path);
  1050. } catch (NotFoundException $ex) {
  1051. }
  1052. }
  1053. $view = \OC::$server->get(View::class);
  1054. $fsView = Filesystem::getView();
  1055. if ($fsView === null) {
  1056. throw new Exception('View should not be null');
  1057. }
  1058. $fullPath = $fsView->getAbsolutePath($path);
  1059. if (Filesystem::is_dir($path)) {
  1060. return new NonExistingFolder($rootFolder, $view, $fullPath);
  1061. } else {
  1062. return new NonExistingFile($rootFolder, $view, $fullPath);
  1063. }
  1064. }
  1065. }