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