1
0

Trashbin.php 40 KB

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