Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(trashbin): Move to OCP classes #50717

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 56 additions & 51 deletions apps/files_trashbin/lib/Trashbin.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
use OCP\FilesMetadata\IFilesMetadataManager;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IUserManager;
use OCP\IUserSession;
use OCP\Lock\ILockingProvider;
use OCP\Lock\LockedException;
use OCP\Server;
Expand Down Expand Up @@ -72,19 +74,20 @@ public static function ensureFileScannedHook(Node $node): void {
*/
public static function getUidAndFilename($filename) {
$uid = Filesystem::getOwner($filename);
$userManager = \OC::$server->getUserManager();
$userManager = Server::get(IUserManager::class);
$userSession = Server::get(IUserSession::class);
// if the user with the UID doesn't exists, e.g. because the UID points
// to a remote user with a federated cloud ID we use the current logged-in
// user. We need a valid local user to move the file to the right trash bin
if (!$userManager->userExists($uid)) {
$uid = OC_User::getUser();
$uid = $userSession->getUser()->getUID();
}
if (!$uid) {
// no owner, usually because of share link from ext storage
return [null, null];
}
Filesystem::initMountPoints($uid);
if ($uid !== OC_User::getUser()) {
if ($uid !== $userSession->getUser()) {
$info = Filesystem::getFileInfo($filename);
$ownerView = new View('/' . $uid . '/files');
try {
Expand All @@ -103,7 +106,7 @@ public static function getUidAndFilename($filename) {
* @return array<string, array<string, array{location: string, deletedBy: string}>>
*/
public static function getExtraData($user) {
$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$query = Server::get(IDBConnection::class)->getQueryBuilder();
$query->select('id', 'timestamp', 'location', 'deleted_by')
->from('files_trash')
->where($query->expr()->eq('user', $query->createNamedParameter($user)));
Expand All @@ -128,7 +131,7 @@ public static function getExtraData($user) {
* @return string|false original location
*/
public static function getLocation($user, $filename, $timestamp) {
$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$query = Server::get(IDBConnection::class)->getQueryBuilder();
$query->select('location')
->from('files_trash')
->where($query->expr()->eq('user', $query->createNamedParameter($user)))
Expand Down Expand Up @@ -194,7 +197,7 @@ private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user,


if ($view->file_exists($target)) {
$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$query = Server::get(IDBConnection::class)->getQueryBuilder();
$query->insert('files_trash')
->setValue('id', $query->createNamedParameter($targetFilename))
->setValue('timestamp', $query->createNamedParameter($timestamp))
Expand All @@ -203,7 +206,7 @@ private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user,
->setValue('deleted_by', $query->createNamedParameter($user));
$result = $query->executeStatement();
if (!$result) {
\OC::$server->get(LoggerInterface::class)->error('trash bin database couldn\'t be updated for the files owner', ['app' => 'files_trashbin']);
Server::get(LoggerInterface::class)->error('trash bin database couldn\'t be updated for the files owner', ['app' => 'files_trashbin']);
}
}
}
Expand Down Expand Up @@ -253,10 +256,10 @@ public static function move2trash($file_path, $ownerOnly = false) {
$filename = $path_parts['basename'];
$location = $path_parts['dirname'];
/** @var ITimeFactory $timeFactory */
$timeFactory = \OC::$server->query(ITimeFactory::class);
$timeFactory = Server::get(ITimeFactory::class);
$timestamp = $timeFactory->getTime();

$lockingProvider = \OC::$server->getLockingProvider();
$lockingProvider = Server::get(ILockingProvider::class);

// disable proxy to prevent recursive calls
$trashPath = '/files_trashbin/files/' . static::getTrashFilename($filename, $timestamp);
Expand Down Expand Up @@ -302,7 +305,7 @@ public static function move2trash($file_path, $ownerOnly = false) {
if ($trashStorage->file_exists($trashInternalPath)) {
$trashStorage->unlink($trashInternalPath);
}
\OC::$server->get(LoggerInterface::class)->error('Couldn\'t move ' . $file_path . ' to the trash bin', ['app' => 'files_trashbin']);
Server::get(LoggerInterface::class)->error('Couldn\'t move ' . $file_path . ' to the trash bin', ['app' => 'files_trashbin']);
}

if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
Expand All @@ -322,7 +325,7 @@ public static function move2trash($file_path, $ownerOnly = false) {
}

if ($moveSuccessful) {
$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$query = Server::get(IDBConnection::class)->getQueryBuilder();
$query->insert('files_trash')
->setValue('id', $query->createNamedParameter($filename))
->setValue('timestamp', $query->createNamedParameter($timestamp))
Expand All @@ -331,7 +334,7 @@ public static function move2trash($file_path, $ownerOnly = false) {
->setValue('deleted_by', $query->createNamedParameter($user));
$result = $query->executeStatement();
if (!$result) {
\OC::$server->get(LoggerInterface::class)->error('trash bin database couldn\'t be updated', ['app' => 'files_trashbin']);
Server::get(LoggerInterface::class)->error('trash bin database couldn\'t be updated', ['app' => 'files_trashbin']);
}
Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', ['filePath' => Filesystem::normalizePath($file_path),
'trashPath' => Filesystem::normalizePath(static::getTrashFilename($filename, $timestamp))]);
Expand All @@ -357,7 +360,7 @@ public static function move2trash($file_path, $ownerOnly = false) {
}

private static function getConfiguredTrashbinSize(string $user): int|float {
$config = \OC::$server->get(IConfig::class);
$config = Server::get(IConfig::class);
$userTrashbinSize = $config->getUserValue($user, 'files_trashbin', 'trashbin_size', '-1');
if (is_numeric($userTrashbinSize) && ($userTrashbinSize > -1)) {
return Util::numericToNumber($userTrashbinSize);
Expand All @@ -379,7 +382,7 @@ private static function getConfiguredTrashbinSize(string $user): int|float {
*/
private static function retainVersions($filename, $owner, $ownerPath, $timestamp) {
if (Server::get(IAppManager::class)->isEnabledForUser('files_versions') && !empty($ownerPath)) {
$user = OC_User::getUser();
$user = Server::get(IUserSession::class)->getUser()->getUID();
$rootView = new View('/');

if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
Expand Down Expand Up @@ -453,14 +456,14 @@ private static function copy(View $view, $source, $target) {
* @return bool true on success, false otherwise
*/
public static function restore($file, $filename, $timestamp) {
$user = OC_User::getUser();
$user = Server::get(IUserSession::class)->getUser()->getUID();
$view = new View('/' . $user);

$location = '';
if ($timestamp) {
$location = self::getLocation($user, $filename, $timestamp);
if ($location === false) {
\OC::$server->get(LoggerInterface::class)->error('trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']);
Server::get(LoggerInterface::class)->error('trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']);
} else {
// if location no longer exists, restore file in the root directory
if ($location !== '/' &&
Expand Down Expand Up @@ -494,7 +497,7 @@ public static function restore($file, $filename, $timestamp) {
$targetNode = self::getNodeForPath($targetPath);
$run = true;
$event = new BeforeNodeRestoredEvent($sourceNode, $targetNode, $run);
$dispatcher = \OC::$server->get(IEventDispatcher::class);
$dispatcher = Server::get(IEventDispatcher::class);
$dispatcher->dispatchTyped($event);

if (!$run) {
Expand All @@ -514,13 +517,13 @@ public static function restore($file, $filename, $timestamp) {
$sourceNode = self::getNodeForPath($sourcePath);
$targetNode = self::getNodeForPath($targetPath);
$event = new NodeRestoredEvent($sourceNode, $targetNode);
$dispatcher = \OC::$server->get(IEventDispatcher::class);
$dispatcher = Server::get(IEventDispatcher::class);
$dispatcher->dispatchTyped($event);

self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);

if ($timestamp) {
$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$query = Server::get(IDBConnection::class)->getQueryBuilder();
$query->delete('files_trash')
->where($query->expr()->eq('user', $query->createNamedParameter($user)))
->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
Expand All @@ -547,7 +550,7 @@ public static function restore($file, $filename, $timestamp) {
*/
private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) {
if (Server::get(IAppManager::class)->isEnabledForUser('files_versions')) {
$user = OC_User::getUser();
$user = Server::get(IUserSession::class)->getUser()->getUID();
$rootView = new View('/');

$target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
Expand All @@ -559,12 +562,7 @@ private static function restoreVersions(View $view, $file, $filename, $uniqueFil
return false;
}

if ($timestamp) {
$versionedFile = $filename;
} else {
$versionedFile = $file;
}

$versionedFile = $timestamp ? $filename : $file;
if ($view->is_dir('/files_trashbin/versions/' . $file)) {
$rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
} elseif ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
Expand All @@ -583,8 +581,9 @@ private static function restoreVersions(View $view, $file, $filename, $uniqueFil
* delete all files from the trash
*/
public static function deleteAll() {
$user = OC_User::getUser();
$userRoot = \OC::$server->getUserFolder($user)->getParent();
$user = Server::get(IUserSession::class)->getUser()->getUID();
$rootFolder = Server::get(IRootFolder::class);
$userRoot = $rootFolder->getUserFolder($user)->getParent();
$view = new View('/' . $user);
$fileInfos = $view->getDirectoryContent('files_trashbin/files');

Expand Down Expand Up @@ -612,7 +611,7 @@ public static function deleteAll() {
// actual file deletion
$trash->delete();

$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$query = Server::get(IDBConnection::class)->getQueryBuilder();
$query->delete('files_trash')
->where($query->expr()->eq('user', $query->createNamedParameter($user)));
$query->executeStatement();
Expand Down Expand Up @@ -659,12 +658,13 @@ protected static function emitTrashbinPostDelete($path) {
* @return int|float size of deleted files
*/
public static function delete($filename, $user, $timestamp = null) {
$userRoot = \OC::$server->getUserFolder($user)->getParent();
$rootFolder = Server::get(IRootFolder::class);
$userRoot = $rootFolder->getUserFolder($user)->getParent();
$view = new View('/' . $user);
$size = 0;

if ($timestamp) {
$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$query = Server::get(IDBConnection::class)->getQueryBuilder();
$query->delete('files_trash')
->where($query->expr()->eq('user', $query->createNamedParameter($user)))
->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
Expand Down Expand Up @@ -731,7 +731,7 @@ private static function deleteVersions(View $view, $file, $filename, $timestamp,
* @return bool true if file exists, otherwise false
*/
public static function file_exists($filename, $timestamp = null) {
$user = OC_User::getUser();
$user = Server::get(IUserSession::class)->getUser()->getUID();
$view = new View('/' . $user);

if ($timestamp) {
Expand All @@ -749,7 +749,7 @@ public static function file_exists($filename, $timestamp = null) {
* @return bool result of db delete operation
*/
public static function deleteUser($uid) {
$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$query = Server::get(IDBConnection::class)->getQueryBuilder();
$query->delete('files_trash')
->where($query->expr()->eq('user', $query->createNamedParameter($uid)));
return (bool)$query->executeStatement();
Expand All @@ -768,7 +768,8 @@ private static function calculateFreeSpace(int|float $trashbinSize, string $user
return $configuredTrashbinSize - $trashbinSize;
}

$userObject = \OC::$server->getUserManager()->get($user);
$userManager = Server::get(IUserManager::class);
$userObject = $userManager->get($user);
if (is_null($userObject)) {
return 0;
}
Expand All @@ -792,7 +793,8 @@ private static function calculateFreeSpace(int|float $trashbinSize, string $user
// calculate available space for trash bin
// subtract size of files and current trash bin size from quota
if ($softQuota) {
$userFolder = \OC::$server->getUserFolder($user);
$rootFolder = Server::get(IRootFolder::class);
$userFolder = $rootFolder->getUserFolder($user);
if (is_null($userFolder)) {
return 0;
}
Expand Down Expand Up @@ -850,10 +852,10 @@ public static function expire($user) {
private static function scheduleExpire($user) {
// let the admin disable auto expire
/** @var Application $application */
$application = \OC::$server->query(Application::class);
$application = Server::get(Application::class);
$expiration = $application->getContainer()->query('Expiration');
if ($expiration->isEnabled()) {
\OC::$server->getCommandBus()->push(new Expire($user));
Server::get(\OCP\Command\IBus::class)->push(new Expire($user));
}
}

Expand All @@ -868,15 +870,15 @@ private static function scheduleExpire($user) {
*/
protected static function deleteFiles(array $files, string $user, int|float $availableSpace): int|float {
/** @var Application $application */
$application = \OC::$server->query(Application::class);
$application = Server::get(Application::class);
$expiration = $application->getContainer()->query('Expiration');
$size = 0;

if ($availableSpace < 0) {
foreach ($files as $file) {
if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
$tmp = self::delete($file['name'], $user, $file['mtime']);
\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']);
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']);
$availableSpace += $tmp;
$size += $tmp;
} else {
Expand All @@ -896,7 +898,7 @@ protected static function deleteFiles(array $files, string $user, int|float $ava
*/
public static function deleteExpiredFiles($files, $user) {
/** @var Expiration $expiration */
$expiration = \OC::$server->query(Expiration::class);
$expiration = Server::get(Expiration::class);
$size = 0;
$count = 0;
foreach ($files as $file) {
Expand All @@ -907,14 +909,14 @@ public static function deleteExpiredFiles($files, $user) {
$size += self::delete($filename, $user, $timestamp);
$count++;
} catch (NotPermittedException $e) {
\OC::$server->get(LoggerInterface::class)->warning('Removing "' . $filename . '" from trashbin failed.',
Server::get(LoggerInterface::class)->warning('Removing "' . $filename . '" from trashbin failed.',
[
'exception' => $e,
'app' => 'files_trashbin',
]
);
}
\OC::$server->get(LoggerInterface::class)->info(
Server::get(LoggerInterface::class)->info(
'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
['app' => 'files_trashbin']
);
Expand Down Expand Up @@ -977,10 +979,11 @@ private static function getVersionsFromTrash($filename, $timestamp, string $user
/** @var \OC\Files\Storage\Storage $storage */
[$storage,] = $view->resolvePath('/');

$pattern = \OC::$server->getDatabaseConnection()->escapeLikeParameter(basename($filename));
$db = Server::get(IDBConnection::class);
$pattern = $db->escapeLikeParameter(basename($filename));
if ($timestamp) {
// fetch for old versions
$escapedTimestamp = \OC::$server->getDatabaseConnection()->escapeLikeParameter((string)$timestamp);
$escapedTimestamp = $db->escapeLikeParameter((string)$timestamp);
$pattern .= '.v%.d' . $escapedTimestamp;
$offset = -strlen($escapedTimestamp) - 2;
} else {
Expand All @@ -990,7 +993,7 @@ private static function getVersionsFromTrash($filename, $timestamp, string $user
// Manually fetch all versions from the file cache to be able to filter them by their parent
$cache = $storage->getCache('');
$query = new CacheQueryBuilder(
Server::get(IDBConnection::class)->getQueryBuilder(),
$db->getQueryBuilder(),
Server::get(IFilesMetadataManager::class),
);
$normalizedParentPath = ltrim(Filesystem::normalizePath(dirname('files_trashbin/versions/' . $filename)), '/');
Expand All @@ -1010,7 +1013,7 @@ private static function getVersionsFromTrash($filename, $timestamp, string $user

/** @var CacheEntry[] $matches */
$matches = array_map(function (array $data) {
return Cache::cacheEntryFromData($data, \OC::$server->getMimeTypeLoader());
return Cache::cacheEntryFromData($data, Server::get(\OCP\Files\IMimeTypeLoader::class));
}, $entries);

foreach ($matches as $ma) {
Expand Down Expand Up @@ -1067,7 +1070,8 @@ private static function getUniqueFilename($location, $filename, View $view) {
* @return int|float size of the folder
*/
private static function calculateSize(View $view): int|float {
$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
$config = Server::get(IConfig::class);
$root = $config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
if (!file_exists($root)) {
return 0;
}
Expand Down Expand Up @@ -1126,7 +1130,8 @@ public static function isEmpty($user) {
* @return string
*/
public static function preview_icon($path) {
return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_trashbin_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
$urlGenerator = Server::get(\OCP\IURLGenerator::class);
return $urlGenerator->linkToRoute('core_ajax_trashbin_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
}

/**
Expand All @@ -1149,8 +1154,8 @@ public static function getTrashFilename(string $filename, int $timestamp): strin
}

private static function getNodeForPath(string $path): Node {
$user = OC_User::getUser();
$rootFolder = \OC::$server->get(IRootFolder::class);
$user = Server::get(IUserSession::class)->getUser()->getUID();
$rootFolder = Server::get(IRootFolder::class);

if ($user !== false) {
$userFolder = $rootFolder->getUserFolder($user);
Expand All @@ -1162,7 +1167,7 @@ private static function getNodeForPath(string $path): Node {
}
}

$view = \OC::$server->get(View::class);
$view = Server::get(View::class);
$fsView = Filesystem::getView();
if ($fsView === null) {
throw new Exception('View should not be null');
Expand Down
Loading