migrate therinaldos.com data
Build & Deploy to DigitalOcean Space / build (push) Failing after 2m38s

This commit is contained in:
2024-05-05 15:50:45 -04:00
commit ef1ff240d4
23182 changed files with 3801898 additions and 0 deletions
@@ -0,0 +1,158 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Victor Dubiniuk <dubiniuk@owncloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Files_Versions\AppInfo;
use OC\KnownUser\KnownUserService;
use OCA\DAV\CalDAV\Proxy\ProxyMapper;
use OCA\DAV\Connector\Sabre\Principal;
use OCA\Files\Event\LoadAdditionalScriptsEvent;
use OCA\Files\Event\LoadSidebar;
use OCA\Files_Versions\Capabilities;
use OCA\Files_Versions\Listener\FileEventsListener;
use OCA\Files_Versions\Listener\LoadAdditionalListener;
use OCA\Files_Versions\Listener\LoadSidebarListener;
use OCA\Files_Versions\Versions\IVersionManager;
use OCA\Files_Versions\Versions\VersionManager;
use OCP\Accounts\IAccountManager;
use OCP\App\IAppManager;
use OCP\AppFramework\App;
use OCP\AppFramework\Bootstrap\IBootContext;
use OCP\AppFramework\Bootstrap\IBootstrap;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
use OCP\Files\Events\Node\BeforeNodeCopiedEvent;
use OCP\Files\Events\Node\BeforeNodeDeletedEvent;
use OCP\Files\Events\Node\BeforeNodeRenamedEvent;
use OCP\Files\Events\Node\BeforeNodeTouchedEvent;
use OCP\Files\Events\Node\BeforeNodeWrittenEvent;
use OCP\Files\Events\Node\NodeCopiedEvent;
use OCP\Files\Events\Node\NodeCreatedEvent;
use OCP\Files\Events\Node\NodeDeletedEvent;
use OCP\Files\Events\Node\NodeRenamedEvent;
use OCP\Files\Events\Node\NodeTouchedEvent;
use OCP\Files\Events\Node\NodeWrittenEvent;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\IServerContainer;
use OCP\IUserManager;
use OCP\IUserSession;
use OCP\L10N\IFactory;
use OCP\Share\IManager as IShareManager;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
class Application extends App implements IBootstrap {
public const APP_ID = 'files_versions';
public function __construct(array $urlParams = []) {
parent::__construct(self::APP_ID, $urlParams);
}
public function register(IRegistrationContext $context): void {
/**
* Register capabilities
*/
$context->registerCapability(Capabilities::class);
/**
* Register $principalBackend for the DAV collection
*/
$context->registerService('principalBackend', function (ContainerInterface $c) {
/** @var IServerContainer $server */
$server = $c->get(IServerContainer::class);
return new Principal(
$server->get(IUserManager::class),
$server->get(IGroupManager::class),
\OC::$server->get(IAccountManager::class),
$server->get(IShareManager::class),
$server->get(IUserSession::class),
$server->get(IAppManager::class),
$server->get(ProxyMapper::class),
$server->get(KnownUserService::class),
$server->get(IConfig::class),
$server->get(IFactory::class),
);
});
$context->registerService(IVersionManager::class, function () {
return new VersionManager();
});
/**
* Register Events
*/
$context->registerEventListener(LoadAdditionalScriptsEvent::class, LoadAdditionalListener::class);
$context->registerEventListener(LoadSidebar::class, LoadSidebarListener::class);
$context->registerEventListener(NodeCreatedEvent::class, FileEventsListener::class);
$context->registerEventListener(BeforeNodeTouchedEvent::class, FileEventsListener::class);
$context->registerEventListener(NodeTouchedEvent::class, FileEventsListener::class);
$context->registerEventListener(BeforeNodeWrittenEvent::class, FileEventsListener::class);
$context->registerEventListener(NodeWrittenEvent::class, FileEventsListener::class);
$context->registerEventListener(BeforeNodeDeletedEvent::class, FileEventsListener::class);
$context->registerEventListener(NodeDeletedEvent::class, FileEventsListener::class);
$context->registerEventListener(NodeRenamedEvent::class, FileEventsListener::class);
$context->registerEventListener(NodeCopiedEvent::class, FileEventsListener::class);
$context->registerEventListener(BeforeNodeRenamedEvent::class, FileEventsListener::class);
$context->registerEventListener(BeforeNodeCopiedEvent::class, FileEventsListener::class);
}
public function boot(IBootContext $context): void {
$context->injectFn(\Closure::fromCallable([$this, 'registerVersionBackends']));
}
public function registerVersionBackends(ContainerInterface $container, IAppManager $appManager, LoggerInterface $logger): void {
foreach ($appManager->getInstalledApps() as $app) {
$appInfo = $appManager->getAppInfo($app);
if (isset($appInfo['versions'])) {
$backends = $appInfo['versions'];
foreach ($backends as $backend) {
if (isset($backend['@value'])) {
$this->loadBackend($backend, $container, $logger);
} else {
foreach ($backend as $singleBackend) {
$this->loadBackend($singleBackend, $container, $logger);
}
}
}
}
}
}
private function loadBackend(array $backend, ContainerInterface $container, LoggerInterface $logger): void {
/** @var IVersionManager $versionManager */
$versionManager = $container->get(IVersionManager::class);
$class = $backend['@value'];
$for = $backend['@attributes']['for'];
try {
$backendObject = $container->get($class);
$versionManager->registerBackend($for, $backendObject);
} catch (\Exception $e) {
$logger->error($e->getMessage(), ['exception' => $e]);
}
}
}
@@ -0,0 +1,88 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Victor Dubiniuk <dubiniuk@owncloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Files_Versions\BackgroundJob;
use OCA\Files_Versions\Expiration;
use OCA\Files_Versions\Storage;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\TimedJob;
use OCP\IConfig;
use OCP\IUser;
use OCP\IUserManager;
class ExpireVersions extends TimedJob {
public const ITEMS_PER_SESSION = 1000;
private IConfig $config;
private Expiration $expiration;
private IUserManager $userManager;
public function __construct(IConfig $config, IUserManager $userManager, Expiration $expiration, ITimeFactory $time) {
parent::__construct($time);
// Run once per 30 minutes
$this->setInterval(60 * 30);
$this->config = $config;
$this->expiration = $expiration;
$this->userManager = $userManager;
}
public function run($argument) {
$backgroundJob = $this->config->getAppValue('files_versions', 'background_job_expire_versions', 'yes');
if ($backgroundJob === 'no') {
return;
}
$maxAge = $this->expiration->getMaxAgeAsTimestamp();
if (!$maxAge) {
return;
}
$this->userManager->callForSeenUsers(function (IUser $user) {
$uid = $user->getUID();
if (!$this->setupFS($uid)) {
return;
}
Storage::expireOlderThanMaxForUser($uid);
});
}
/**
* Act on behalf on trash item owner
*/
protected function setupFS(string $user): bool {
\OC_Util::tearDownFS();
\OC_Util::setupFS($user);
// Check if this user has a versions directory
$view = new \OC\Files\View('/' . $user);
if (!$view->is_dir('/files_versions')) {
return false;
}
return true;
}
}
@@ -0,0 +1,57 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christopher Schäpers <kondou@ts.unde.re>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Tom Needham <tom@owncloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Files_Versions;
use OCP\App\IAppManager;
use OCP\Capabilities\ICapability;
use OCP\IConfig;
class Capabilities implements ICapability {
private IConfig $config;
private IAppManager $appManager;
public function __construct(
IConfig $config,
IAppManager $appManager
) {
$this->config = $config;
$this->appManager = $appManager;
}
/**
* Return this classes capabilities
*
* @return array{files: array{versioning: bool, version_labeling: bool, version_deletion: bool}}
*/
public function getCapabilities() {
return [
'files' => [
'versioning' => true,
'version_labeling' => $this->config->getSystemValueBool('enable_version_labeling', true),
'version_deletion' => $this->config->getSystemValueBool('enable_version_deletion', true),
]
];
}
}
@@ -0,0 +1,127 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Daniel Rudolf <nextcloud.com@daniel-rudolf.de>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Files_Versions\Command;
use OCP\Files\IRootFolder;
use OCP\IUserBackend;
use OCP\IUserManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class CleanUp extends Command {
public function __construct(
protected IRootFolder $rootFolder,
protected IUserManager $userManager,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('versions:cleanup')
->setDescription('Delete versions')
->addArgument(
'user_id',
InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
'delete versions of the given user(s), if no user is given all versions will be deleted'
)
->addOption(
'path',
'p',
InputOption::VALUE_REQUIRED,
'only delete versions of this path, e.g. --path="/alice/files/Music"'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$users = $input->getArgument('user_id');
$path = $input->getOption('path');
if ($path) {
if (!preg_match('#^/([^/]+)/files(/.*)?$#', $path, $pathMatches)) {
$output->writeln("<error>Invalid path given</error>");
return self::FAILURE;
}
$users = [ $pathMatches[1] ];
$path = trim($pathMatches[2], '/');
}
if (!empty($users)) {
foreach ($users as $user) {
if (!$this->userManager->userExists($user)) {
$output->writeln("<error>Unknown user $user</error>");
return self::FAILURE;
}
$output->writeln("Delete versions of <info>$user</info>");
$this->deleteVersions($user, $path);
}
return self::SUCCESS;
}
$output->writeln('Delete all versions');
foreach ($this->userManager->getBackends() as $backend) {
$name = get_class($backend);
if ($backend instanceof IUserBackend) {
$name = $backend->getBackendName();
}
$output->writeln("Delete versions for users on backend <info>$name</info>");
$limit = 500;
$offset = 0;
do {
$users = $backend->getUsers('', $limit, $offset);
foreach ($users as $user) {
$output->writeln(" <info>$user</info>");
$this->deleteVersions($user);
}
$offset += $limit;
} while (count($users) >= $limit);
}
return self::SUCCESS;
}
/**
* delete versions for the given user
*/
protected function deleteVersions(string $user, ?string $path = null): void {
\OC_Util::tearDownFS();
\OC_Util::setupFS($user);
$fullPath = '/' . $user . '/files_versions' . ($path ? '/' . $path : '');
if ($this->rootFolder->nodeExists($fullPath)) {
$this->rootFolder->get($fullPath)->delete();
}
}
}
@@ -0,0 +1,64 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Robin Appelman <robin@icewind.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Files_Versions\Command;
use OC\Command\FileAccess;
use OCA\Files_Versions\Storage;
use OCP\Command\ICommand;
use OCP\Files\StorageNotAvailableException;
use OCP\IUserManager;
use Psr\Log\LoggerInterface;
class Expire implements ICommand {
use FileAccess;
public function __construct(
private string $user,
private string $fileName,
) {
}
public function handle(): void {
/** @var IUserManager $userManager */
$userManager = \OC::$server->get(IUserManager::class);
if (!$userManager->userExists($this->user)) {
// User has been deleted already
return;
}
try {
Storage::expire($this->fileName, $this->user);
} catch (StorageNotAvailableException $e) {
// In case of external storage and session credentials, the expiration
// fails because the command does not have those credentials
$logger = \OC::$server->get(LoggerInterface::class);
$logger->warning($e->getMessage(), [
'exception' => $e,
'uid' => $this->user,
'fileName' => $this->fileName,
]);
}
}
}
@@ -0,0 +1,113 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud GmbH.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Files_Versions\Command;
use OCA\Files_Versions\Expiration;
use OCA\Files_Versions\Storage;
use OCP\IUser;
use OCP\IUserManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ExpireVersions extends Command {
public function __construct(
private IUserManager $userManager,
private Expiration $expiration,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('versions:expire')
->setDescription('Expires the users file versions')
->addArgument(
'user_id',
InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
'expire file versions of the given user(s), if no user is given file versions for all users will be expired.'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$maxAge = $this->expiration->getMaxAgeAsTimestamp();
if (!$maxAge) {
$output->writeln("Auto expiration is configured - expiration will be handled automatically according to the expiration patterns detailed at the following link https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/file_versioning.html.");
return self::FAILURE;
}
$users = $input->getArgument('user_id');
if (!empty($users)) {
foreach ($users as $user) {
if (!$this->userManager->userExists($user)) {
$output->writeln("<error>Unknown user $user</error>");
return self::FAILURE;
}
$output->writeln("Remove deleted files of <info>$user</info>");
$userObject = $this->userManager->get($user);
$this->expireVersionsForUser($userObject);
}
return self::SUCCESS;
}
$p = new ProgressBar($output);
$p->start();
$this->userManager->callForSeenUsers(function (IUser $user) use ($p) {
$p->advance();
$this->expireVersionsForUser($user);
});
$p->finish();
$output->writeln('');
return self::SUCCESS;
}
public function expireVersionsForUser(IUser $user): void {
$uid = $user->getUID();
if (!$this->setupFS($uid)) {
return;
}
Storage::expireOlderThanMaxForUser($uid);
}
/**
* Act on behalf on versions item owner
*/
protected function setupFS(string $user): bool {
\OC_Util::tearDownFS();
\OC_Util::setupFS($user);
// Check if this user has a version directory
$view = new \OC\Files\View('/' . $user);
if (!$view->is_dir('/files_versions')) {
return false;
}
return true;
}
}
@@ -0,0 +1,107 @@
<?php
/**
* @copyright Copyright (c) 2016, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Controller;
use OCA\Files_Versions\Versions\IVersionManager;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\FileDisplayResponse;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\IPreview;
use OCP\IRequest;
use OCP\IUserSession;
class PreviewController extends Controller {
/** @var IRootFolder */
private $rootFolder;
/** @var IUserSession */
private $userSession;
/** @var IVersionManager */
private $versionManager;
/** @var IPreview */
private $previewManager;
public function __construct(
string $appName,
IRequest $request,
IRootFolder $rootFolder,
IUserSession $userSession,
IVersionManager $versionManager,
IPreview $previewManager
) {
parent::__construct($appName, $request);
$this->rootFolder = $rootFolder;
$this->userSession = $userSession;
$this->versionManager = $versionManager;
$this->previewManager = $previewManager;
}
/**
* @NoAdminRequired
* @NoCSRFRequired
*
* Get the preview for a file version
*
* @param string $file Path of the file
* @param int $x Width of the preview
* @param int $y Height of the preview
* @param string $version Version of the file to get the preview for
* @return FileDisplayResponse<Http::STATUS_OK, array{Content-Type: string}>|DataResponse<Http::STATUS_BAD_REQUEST|Http::STATUS_NOT_FOUND, array<empty>, array{}>
*
* 200: Preview returned
* 400: Getting preview is not possible
* 404: Preview not found
*/
public function getPreview(
string $file = '',
int $x = 44,
int $y = 44,
string $version = ''
) {
if ($file === '' || $version === '' || $x === 0 || $y === 0) {
return new DataResponse([], Http::STATUS_BAD_REQUEST);
}
try {
$user = $this->userSession->getUser();
$userFolder = $this->rootFolder->getUserFolder($user->getUID());
$file = $userFolder->get($file);
$versionFile = $this->versionManager->getVersionFile($user, $file, $version);
$preview = $this->previewManager->getPreview($versionFile, $x, $y, true, IPreview::MODE_FILL, $versionFile->getMimetype());
return new FileDisplayResponse($preview, Http::STATUS_OK, ['Content-Type' => $preview->getMimeType()]);
} catch (NotFoundException $e) {
return new DataResponse([], Http::STATUS_NOT_FOUND);
} catch (\InvalidArgumentException $e) {
return new DataResponse([], Http::STATUS_BAD_REQUEST);
}
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Louis Chmn <louis@chmn.me>
*
* @author Louis Chmn <louis@chmn.me>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Db;
use JsonSerializable;
use OCP\AppFramework\Db\Entity;
use OCP\DB\Types;
/**
* @method int getFileId()
* @method void setFileId(int $fileId)
* @method int getTimestamp()
* @method void setTimestamp(int $timestamp)
* @method int|float getSize()
* @method void setSize(int|float $size)
* @method int getMimetype()
* @method void setMimetype(int $mimetype)
* @method array|null getMetadata()
* @method void setMetadata(array $metadata)
*/
class VersionEntity extends Entity implements JsonSerializable {
protected ?int $fileId = null;
protected ?int $timestamp = null;
protected ?int $size = null;
protected ?int $mimetype = null;
protected ?array $metadata = null;
public function __construct() {
$this->addType('id', Types::INTEGER);
$this->addType('file_id', Types::INTEGER);
$this->addType('timestamp', Types::INTEGER);
$this->addType('size', Types::INTEGER);
$this->addType('mimetype', Types::INTEGER);
$this->addType('metadata', Types::JSON);
}
public function jsonSerialize(): array {
return [
'id' => $this->id,
'file_id' => $this->fileId,
'timestamp' => $this->timestamp,
'size' => $this->size,
'mimetype' => $this->mimetype,
'metadata' => $this->metadata,
];
}
public function getLabel(): string {
return $this->metadata['label'] ?? '';
}
public function setLabel(string $label): void {
$this->metadata['label'] = $label;
$this->markFieldUpdated('metadata');
}
}
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Louis Chmn <louis@chmn.me>
*
* @author Louis Chmn <louis@chmn.me>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Db;
use OCP\AppFramework\Db\QBMapper;
use OCP\IDBConnection;
/**
* @extends QBMapper<VersionEntity>
*/
class VersionsMapper extends QBMapper {
public function __construct(IDBConnection $db) {
parent::__construct($db, 'files_versions', VersionEntity::class);
}
/**
* @return VersionEntity[]
*/
public function findAllVersionsForFileId(int $fileId): array {
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from($this->getTableName())
->where($qb->expr()->eq('file_id', $qb->createNamedParameter($fileId)));
return $this->findEntities($qb);
}
/**
* @return VersionEntity
*/
public function findCurrentVersionForFileId(int $fileId): VersionEntity {
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from($this->getTableName())
->where($qb->expr()->eq('file_id', $qb->createNamedParameter($fileId)))
->orderBy('timestamp', 'DESC')
->setMaxResults(1);
return $this->findEntity($qb);
}
public function findVersionForFileId(int $fileId, int $timestamp): VersionEntity {
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from($this->getTableName())
->where($qb->expr()->eq('file_id', $qb->createNamedParameter($fileId)))
->andWhere($qb->expr()->eq('timestamp', $qb->createNamedParameter($timestamp)));
return $this->findEntity($qb);
}
public function deleteAllVersionsForFileId(int $fileId): int {
$qb = $this->db->getQueryBuilder();
return $qb->delete($this->getTableName())
->where($qb->expr()->eq('file_id', $qb->createNamedParameter($fileId)))
->executeStatement();
}
}
@@ -0,0 +1,80 @@
<?php
/**
* @copyright Copyright (c) 2017 Bjoern Schiessle <bjoern@schiessle.org>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Events;
use OCP\EventDispatcher\Event;
use OCP\Files\Node;
/**
* Class CreateVersionEvent
*
* Event to allow other apps to disable versions for specific files
*
* @package OCA\Files_Versions
*/
class CreateVersionEvent extends Event {
/** @var bool */
private $createVersion;
/** @var Node */
private $node;
/**
* CreateVersionEvent constructor.
*
* @param Node $node
*/
public function __construct(Node $node) {
$this->createVersion = true;
$this->node = $node;
}
/**
* get Node of the file which should be versioned
*
* @return Node
*/
public function getNode(): Node {
return $this->node;
}
/**
* disable versions for this file
*/
public function disableVersions(): void {
$this->createVersion = false;
}
/**
* should a version be created for this file?
*
* @return bool
*/
public function shouldCreateVersion(): bool {
return $this->createVersion;
}
}
@@ -0,0 +1,207 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Victor Dubiniuk <dubiniuk@owncloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Files_Versions;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IConfig;
use Psr\Log\LoggerInterface;
class Expiration {
// how long do we keep files a version if no other value is defined in the config file (unit: days)
public const NO_OBLIGATION = -1;
/** @var ITimeFactory */
private $timeFactory;
/** @var string */
private $retentionObligation;
/** @var int */
private $minAge;
/** @var int */
private $maxAge;
/** @var bool */
private $canPurgeToSaveSpace;
/** @var LoggerInterface */
private $logger;
public function __construct(IConfig $config, ITimeFactory $timeFactory, LoggerInterface $logger) {
$this->timeFactory = $timeFactory;
$this->logger = $logger;
$this->retentionObligation = $config->getSystemValue('versions_retention_obligation', 'auto');
if ($this->retentionObligation !== 'disabled') {
$this->parseRetentionObligation();
}
}
/**
* Is versions expiration enabled
* @return bool
*/
public function isEnabled(): bool {
return $this->retentionObligation !== 'disabled';
}
/**
* Is default expiration active
*/
public function shouldAutoExpire(): bool {
return $this->minAge === self::NO_OBLIGATION
|| $this->maxAge === self::NO_OBLIGATION;
}
/**
* Check if given timestamp in expiration range
* @param int $timestamp
* @param bool $quotaExceeded
* @return bool
*/
public function isExpired(int $timestamp, bool $quotaExceeded = false): bool {
// No expiration if disabled
if (!$this->isEnabled()) {
return false;
}
// Purge to save space (if allowed)
if ($quotaExceeded && $this->canPurgeToSaveSpace) {
return true;
}
$time = $this->timeFactory->getTime();
// Never expire dates in future e.g. misconfiguration or negative time
// adjustment
if ($time < $timestamp) {
return false;
}
// Purge as too old
if ($this->maxAge !== self::NO_OBLIGATION) {
$maxTimestamp = $time - ($this->maxAge * 86400);
$isOlderThanMax = $timestamp < $maxTimestamp;
} else {
$isOlderThanMax = false;
}
if ($this->minAge !== self::NO_OBLIGATION) {
// older than Min obligation and we are running out of quota?
$minTimestamp = $time - ($this->minAge * 86400);
$isMinReached = ($timestamp < $minTimestamp) && $quotaExceeded;
} else {
$isMinReached = false;
}
return $isOlderThanMax || $isMinReached;
}
/**
* Get maximal retention obligation as a timestamp
*
* @return int|false
*/
public function getMaxAgeAsTimestamp() {
$maxAge = false;
if ($this->isEnabled() && $this->maxAge !== self::NO_OBLIGATION) {
$time = $this->timeFactory->getTime();
$maxAge = $time - ($this->maxAge * 86400);
}
return $maxAge;
}
/**
* Read versions_retention_obligation, validate it
* and set private members accordingly
*/
private function parseRetentionObligation(): void {
$splitValues = explode(',', $this->retentionObligation);
if (!isset($splitValues[0])) {
$minValue = 'auto';
} else {
$minValue = trim($splitValues[0]);
}
if (!isset($splitValues[1])) {
$maxValue = 'auto';
} else {
$maxValue = trim($splitValues[1]);
}
$isValid = true;
// Validate
if (!ctype_digit($minValue) && $minValue !== 'auto') {
$isValid = false;
$this->logger->warning(
$minValue . ' is not a valid value for minimal versions retention obligation. Check versions_retention_obligation in your config.php. Falling back to auto.',
['app' => 'files_versions']
);
}
if (!ctype_digit($maxValue) && $maxValue !== 'auto') {
$isValid = false;
$this->logger->warning(
$maxValue . ' is not a valid value for maximal versions retention obligation. Check versions_retention_obligation in your config.php. Falling back to auto.',
['app' => 'files_versions']
);
}
if (!$isValid) {
$minValue = 'auto';
$maxValue = 'auto';
}
if ($minValue === 'auto' && $maxValue === 'auto') {
// Default: Delete anytime if space needed
$this->minAge = self::NO_OBLIGATION;
$this->maxAge = self::NO_OBLIGATION;
$this->canPurgeToSaveSpace = true;
} elseif ($minValue !== 'auto' && $maxValue === 'auto') {
// Keep for X days but delete anytime if space needed
$this->minAge = (int)$minValue;
$this->maxAge = self::NO_OBLIGATION;
$this->canPurgeToSaveSpace = true;
} elseif ($minValue === 'auto' && $maxValue !== 'auto') {
// Delete anytime if space needed, Delete all older than max automatically
$this->minAge = self::NO_OBLIGATION;
$this->maxAge = (int)$maxValue;
$this->canPurgeToSaveSpace = true;
} elseif ($minValue !== 'auto' && $maxValue !== 'auto') {
// Delete all older than max OR older than min if space needed
// Max < Min as per https://github.com/owncloud/core/issues/16301
if ($maxValue < $minValue) {
$maxValue = $minValue;
}
$this->minAge = (int)$minValue;
$this->maxAge = (int)$maxValue;
$this->canPurgeToSaveSpace = false;
}
}
}
@@ -0,0 +1,375 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bart Visscher <bartv@thisnet.nl>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Robin McCorkell <robin@mccorkell.me.uk>
* @author Sam Tuke <mail@samtuke.com>
* @author Louis Chmn <louis@chmn.me>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Files_Versions\Listener;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use OC\DB\Exceptions\DbalException;
use OC\Files\Filesystem;
use OC\Files\Mount\MoveableMount;
use OC\Files\Node\NonExistingFile;
use OC\Files\View;
use OCA\Files_Versions\Storage;
use OCA\Files_Versions\Versions\INeedSyncVersionBackend;
use OCA\Files_Versions\Versions\IVersionManager;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\DB\Exception;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Files\Events\Node\BeforeNodeCopiedEvent;
use OCP\Files\Events\Node\BeforeNodeDeletedEvent;
use OCP\Files\Events\Node\BeforeNodeRenamedEvent;
use OCP\Files\Events\Node\BeforeNodeTouchedEvent;
use OCP\Files\Events\Node\BeforeNodeWrittenEvent;
use OCP\Files\Events\Node\NodeCopiedEvent;
use OCP\Files\Events\Node\NodeCreatedEvent;
use OCP\Files\Events\Node\NodeDeletedEvent;
use OCP\Files\Events\Node\NodeRenamedEvent;
use OCP\Files\Events\Node\NodeTouchedEvent;
use OCP\Files\Events\Node\NodeWrittenEvent;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\IMimeTypeLoader;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\IUserSession;
use Psr\Log\LoggerInterface;
class FileEventsListener implements IEventListener {
/**
* @var array<int, array>
*/
private array $writeHookInfo = [];
/**
* @var array<int, Node>
*/
private array $nodesTouched = [];
/**
* @var array<string, Node>
*/
private array $versionsDeleted = [];
public function __construct(
private IRootFolder $rootFolder,
private IVersionManager $versionManager,
private IMimeTypeLoader $mimeTypeLoader,
private IUserSession $userSession,
private LoggerInterface $logger,
) {
}
public function handle(Event $event): void {
if ($event instanceof NodeCreatedEvent) {
$this->created($event->getNode());
}
if ($event instanceof BeforeNodeTouchedEvent) {
$this->pre_touch_hook($event->getNode());
}
if ($event instanceof NodeTouchedEvent) {
$this->touch_hook($event->getNode());
}
if ($event instanceof BeforeNodeWrittenEvent) {
$this->write_hook($event->getNode());
}
if ($event instanceof NodeWrittenEvent) {
$this->post_write_hook($event->getNode());
}
if ($event instanceof BeforeNodeDeletedEvent) {
$this->pre_remove_hook($event->getNode());
}
if ($event instanceof NodeDeletedEvent) {
$this->remove_hook($event->getNode());
}
if ($event instanceof NodeRenamedEvent) {
$this->rename_hook($event->getSource(), $event->getTarget());
}
if ($event instanceof NodeCopiedEvent) {
$this->copy_hook($event->getSource(), $event->getTarget());
}
if ($event instanceof BeforeNodeRenamedEvent) {
$this->pre_renameOrCopy_hook($event->getSource(), $event->getTarget());
}
if ($event instanceof BeforeNodeCopiedEvent) {
$this->pre_renameOrCopy_hook($event->getSource(), $event->getTarget());
}
}
public function pre_touch_hook(Node $node): void {
// Do not handle folders.
if ($node instanceof Folder) {
return;
}
// $node is a non-existing on file creation.
if ($node instanceof NonExistingFile) {
return;
}
$this->nodesTouched[$node->getId()] = $node;
}
public function touch_hook(Node $node): void {
$previousNode = $this->nodesTouched[$node->getId()] ?? null;
if ($previousNode === null) {
return;
}
unset($this->nodesTouched[$node->getId()]);
try {
if ($node instanceof File && $this->versionManager instanceof INeedSyncVersionBackend) {
// We update the timestamp of the version entity associated with the previousNode.
$this->versionManager->updateVersionEntity($node, $previousNode->getMTime(), ['timestamp' => $node->getMTime()]);
}
} catch (DbalException $ex) {
// Ignore UniqueConstraintViolationException, as we are probably in the middle of a rollback
// Where the previous node would temporary have the mtime of the old version, so the rollback touches it to fix it.
if (!($ex->getPrevious() instanceof UniqueConstraintViolationException)) {
throw $ex;
}
} catch (DoesNotExistException $ex) {
// Ignore DoesNotExistException, as we are probably in the middle of a rollback
// Where the previous node would temporary have a wrong mtime, so the rollback touches it to fix it.
}
}
public function created(Node $node): void {
// Do not handle folders.
if ($node instanceof File && $this->versionManager instanceof INeedSyncVersionBackend) {
$this->versionManager->createVersionEntity($node);
}
}
/**
* listen to write event.
*/
public function write_hook(Node $node): void {
// Do not handle folders.
if ($node instanceof Folder) {
return;
}
// $node is a non-existing on file creation.
if ($node instanceof NonExistingFile) {
return;
}
$path = $this->getPathForNode($node);
$result = Storage::store($path);
// Store the result of the version creation so it can be used in post_write_hook.
$this->writeHookInfo[$node->getId()] = [
'previousNode' => $node,
'versionCreated' => $result !== false
];
}
/**
* listen to post_write event.
*/
public function post_write_hook(Node $node): void {
// Do not handle folders.
if ($node instanceof Folder) {
return;
}
$writeHookInfo = $this->writeHookInfo[$node->getId()] ?? null;
if ($writeHookInfo === null) {
return;
}
if (
($writeHookInfo['versionCreated'] || $writeHookInfo['previousNode']->getSize() === 0) &&
$node->getMTime() !== $writeHookInfo['previousNode']->getMTime()
) {
// If a new version was created, insert a version in the DB for the current content.
// Unless both versions have the same mtime.
$this->created($node);
} else {
try {
// If no new version was stored in the FS, no new version should be added in the DB.
// So we simply update the associated version.
if ($node instanceof File && $this->versionManager instanceof INeedSyncVersionBackend) {
$this->versionManager->updateVersionEntity(
$node,
$writeHookInfo['previousNode']->getMtime(),
[
'timestamp' => $node->getMTime(),
'size' => $node->getSize(),
'mimetype' => $this->mimeTypeLoader->getId($node->getMimetype()),
],
);
}
} catch (Exception $e) {
$this->logger->error('Failed to update existing version for ' . $node->getPath(), [
'exception' => $e,
'versionCreated' => $writeHookInfo['versionCreated'],
'previousNode' => [
'size' => $writeHookInfo['previousNode']->getSize(),
'mtime' => $writeHookInfo['previousNode']->getMTime(),
],
'node' => [
'size' => $node->getSize(),
'mtime' => $node->getMTime(),
]
]);
throw $e;
}
}
unset($this->writeHookInfo[$node->getId()]);
}
/**
* Erase versions of deleted file
*
* This function is connected to the delete signal of OC_Filesystem
* cleanup the versions directory if the actual file gets deleted
*/
public function remove_hook(Node $node): void {
// Need to normalize the path as there is an issue with path concatenation in View.php::getAbsolutePath.
$path = Filesystem::normalizePath($node->getPath());
if (!array_key_exists($path, $this->versionsDeleted)) {
return;
}
$node = $this->versionsDeleted[$path];
$relativePath = $this->getPathForNode($node);
unset($this->versionsDeleted[$path]);
Storage::delete($relativePath);
// If no new version was stored in the FS, no new version should be added in the DB.
// So we simply update the associated version.
if ($node instanceof File && $this->versionManager instanceof INeedSyncVersionBackend) {
$this->versionManager->deleteVersionsEntity($node);
}
}
/**
* mark file as "deleted" so that we can clean up the versions if the file is gone
*/
public function pre_remove_hook(Node $node): void {
$path = $this->getPathForNode($node);
Storage::markDeletedFile($path);
$this->versionsDeleted[$node->getPath()] = $node;
}
/**
* rename/move versions of renamed/moved files
*
* This function is connected to the rename signal of OC_Filesystem and adjust the name and location
* of the stored versions along the actual file
*/
public function rename_hook(Node $source, Node $target): void {
$oldPath = $this->getPathForNode($source);
$newPath = $this->getPathForNode($target);
Storage::renameOrCopy($oldPath, $newPath, 'rename');
}
/**
* copy versions of copied files
*
* This function is connected to the copy signal of OC_Filesystem and copies the
* the stored versions to the new location
*/
public function copy_hook(Node $source, Node $target): void {
$oldPath = $this->getPathForNode($source);
$newPath = $this->getPathForNode($target);
Storage::renameOrCopy($oldPath, $newPath, 'copy');
}
/**
* Remember owner and the owner path of the source file.
* If the file already exists, then it was a upload of a existing file
* over the web interface and we call Storage::store() directly
*
*
*/
public function pre_renameOrCopy_hook(Node $source, Node $target): void {
// if we rename a movable mount point, then the versions don't have
// to be renamed
$oldPath = $this->getPathForNode($source);
$newPath = $this->getPathForNode($target);
$absOldPath = Filesystem::normalizePath('/' . \OC_User::getUser() . '/files' . $oldPath);
$manager = Filesystem::getMountManager();
$mount = $manager->find($absOldPath);
$internalPath = $mount->getInternalPath($absOldPath);
if ($internalPath === '' and $mount instanceof MoveableMount) {
return;
}
$view = new View(\OC_User::getUser() . '/files');
if ($view->file_exists($newPath)) {
Storage::store($newPath);
} else {
Storage::setSourcePathAndUser($oldPath);
}
}
/**
* Retrieve the path relative to the current user root folder.
* If no user is connected, try to use the node's owner.
*/
private function getPathForNode(Node $node): ?string {
$user = $this->userSession->getUser()?->getUID();
if ($user) {
$path = $this->rootFolder
->getUserFolder($user)
->getRelativePath($node->getPath());
if ($path !== null) {
return $path;
}
}
$owner = $node->getOwner()?->getUid();
if ($owner) {
$path = $this->rootFolder
->getUserFolder($owner)
->getRelativePath($node->getPath());
if ($path !== null) {
return $path;
}
}
return null;
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Listener;
use OCA\Files\Event\LoadAdditionalScriptsEvent;
use OCA\Files_Versions\AppInfo\Application;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Util;
class LoadAdditionalListener implements IEventListener {
public function handle(Event $event): void {
if (!($event instanceof LoadAdditionalScriptsEvent)) {
return;
}
// TODO: make sure to only include the sidebar script when
// we properly split it between files list and sidebar
Util::addScript(Application::APP_ID, 'files_versions');
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Listener;
use OCA\Files\Event\LoadSidebar;
use OCA\Files_Versions\AppInfo\Application;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Util;
class LoadSidebarListener implements IEventListener {
public function handle(Event $event): void {
if (!($event instanceof LoadSidebar)) {
return;
}
// TODO: make sure to only include the sidebar script when
// we properly split it between files list and sidebar
Util::addScript(Application::APP_ID, 'files_versions');
}
}
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Louis Chmn <louis@chmn.me>
*
* @author Louis Chmn <louis@chmn.me>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Migration;
use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
/**
* Auto-generated migration step: Please modify to your needs!
*/
class Version1020Date20221114144058 extends SimpleMigrationStep {
/**
* @param IOutput $output
* @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
* @param array $options
* @return null|ISchemaWrapper
*/
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();
if ($schema->hasTable("files_versions")) {
return null;
}
$table = $schema->createTable("files_versions");
$table->addColumn('id', Types::BIGINT, [
'autoincrement' => true,
'notnull' => true,
'length' => 20,
]);
$table->addColumn('file_id', Types::BIGINT, [
'notnull' => true,
'length' => 20,
]);
$table->addColumn('timestamp', Types::BIGINT, [
'notnull' => true,
'length' => 20,
]);
$table->addColumn('size', Types::BIGINT, [
'notnull' => true,
'length' => 20,
]);
$table->addColumn('mimetype', Types::BIGINT, [
'notnull' => true,
'length' => 20,
]);
$table->addColumn('metadata', Types::JSON, [
'notnull' => true,
]);
$table->setPrimaryKey(['id']);
$table->addUniqueIndex(['file_id', 'timestamp'], 'files_versions_uniq_index');
return $schema;
}
}
@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Sabre;
use OC\AppFramework\Http\Request;
use OCA\DAV\Connector\Sabre\FilesPlugin;
use OCP\IPreview;
use OCP\IRequest;
use Sabre\DAV\Exception\NotFound;
use Sabre\DAV\INode;
use Sabre\DAV\PropFind;
use Sabre\DAV\PropPatch;
use Sabre\DAV\Server;
use Sabre\DAV\ServerPlugin;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
class Plugin extends ServerPlugin {
private Server $server;
public const VERSION_LABEL = '{http://nextcloud.org/ns}version-label';
public function __construct(
private IRequest $request,
private IPreview $previewManager,
) {
$this->request = $request;
}
public function initialize(Server $server) {
$this->server = $server;
$server->on('afterMethod:GET', [$this, 'afterGet']);
$server->on('propFind', [$this, 'propFind']);
$server->on('propPatch', [$this, 'propPatch']);
}
public function afterGet(RequestInterface $request, ResponseInterface $response) {
$path = $request->getPath();
if (!str_starts_with($path, 'versions')) {
return;
}
try {
$node = $this->server->tree->getNodeForPath($path);
} catch (NotFound $e) {
return;
}
if (!($node instanceof VersionFile)) {
return;
}
$filename = $node->getVersion()->getSourceFileName();
if ($this->request->isUserAgent(
[
Request::USER_AGENT_IE,
Request::USER_AGENT_ANDROID_MOBILE_CHROME,
Request::USER_AGENT_FREEBOX,
])) {
$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
} else {
$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
. '; filename="' . rawurlencode($filename) . '"');
}
}
public function propFind(PropFind $propFind, INode $node): void {
if ($node instanceof VersionFile) {
$propFind->handle(self::VERSION_LABEL, fn () => $node->getLabel());
$propFind->handle(FilesPlugin::HAS_PREVIEW_PROPERTYNAME, fn () => $this->previewManager->isMimeSupported($node->getContentType()));
}
}
public function propPatch($path, PropPatch $propPatch): void {
$node = $this->server->tree->getNodeForPath($path);
if ($node instanceof VersionFile) {
$propPatch->handle(self::VERSION_LABEL, fn ($label) => $node->setLabel($label));
}
}
}
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Sabre;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\ICollection;
use Sabre\DAV\IMoveTarget;
use Sabre\DAV\INode;
class RestoreFolder implements ICollection, IMoveTarget {
public function createFile($name, $data = null) {
throw new Forbidden();
}
public function createDirectory($name) {
throw new Forbidden();
}
public function getChild($name) {
return null;
}
public function delete() {
throw new Forbidden();
}
public function getName() {
return 'restore';
}
public function setName($name) {
throw new Forbidden();
}
public function getLastModified(): int {
return 0;
}
public function getChildren(): array {
return [];
}
public function childExists($name): bool {
return false;
}
public function moveInto($targetName, $sourcePath, INode $sourceNode): bool {
if (!($sourceNode instanceof VersionFile)) {
return false;
}
$sourceNode->rollBack();
return true;
}
}
@@ -0,0 +1,89 @@
<?php
/**
* @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Sabre;
use OCA\Files_Versions\Versions\IVersionManager;
use OCP\Files\IRootFolder;
use OCP\IConfig;
use OCP\IUserManager;
use OCP\IUserSession;
use Sabre\DAV\INode;
use Sabre\DAVACL\AbstractPrincipalCollection;
use Sabre\DAVACL\PrincipalBackend;
class RootCollection extends AbstractPrincipalCollection {
/** @var IRootFolder */
private $rootFolder;
/** @var IUserManager */
private $userManager;
/** @var IVersionManager */
private $versionManager;
/** @var IUserSession */
private $userSession;
public function __construct(
PrincipalBackend\BackendInterface $principalBackend,
IRootFolder $rootFolder,
IConfig $config,
IUserManager $userManager,
IVersionManager $versionManager,
IUserSession $userSession
) {
parent::__construct($principalBackend, 'principals/users');
$this->rootFolder = $rootFolder;
$this->userManager = $userManager;
$this->versionManager = $versionManager;
$this->userSession = $userSession;
$this->disableListing = !$config->getSystemValue('debug', false);
}
/**
* This method returns a node for a principal.
*
* The passed array contains principal information, and is guaranteed to
* at least contain a uri item. Other properties may or may not be
* supplied by the authentication backend.
*
* @param array $principalInfo
* @return INode
*/
public function getChildForPrincipal(array $principalInfo) {
[, $name] = \Sabre\Uri\split($principalInfo['uri']);
$user = $this->userSession->getUser();
if (is_null($user) || $name !== $user->getUID()) {
throw new \Sabre\DAV\Exception\Forbidden();
}
return new VersionHome($principalInfo, $this->rootFolder, $this->userManager, $this->versionManager);
}
public function getName() {
return 'versions';
}
}
@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Sabre;
use OCA\Files_Versions\Versions\IVersion;
use OCA\Files_Versions\Versions\IVersionManager;
use OCP\Files\File;
use OCP\IUser;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\Exception\NotFound;
use Sabre\DAV\ICollection;
class VersionCollection implements ICollection {
/** @var File */
private $file;
/** @var IUser */
private $user;
/** @var IVersionManager */
private $versionManager;
public function __construct(File $file, IUser $user, IVersionManager $versionManager) {
$this->file = $file;
$this->user = $user;
$this->versionManager = $versionManager;
}
public function createFile($name, $data = null) {
throw new Forbidden();
}
public function createDirectory($name) {
throw new Forbidden();
}
public function getChild($name) {
/** @var VersionFile[] $versions */
$versions = $this->getChildren();
foreach ($versions as $version) {
if ($version->getName() === $name) {
return $version;
}
}
throw new NotFound();
}
public function getChildren(): array {
$versions = $this->versionManager->getVersionsForFile($this->user, $this->file);
return array_map(function (IVersion $version) {
return new VersionFile($version, $this->versionManager);
}, $versions);
}
public function childExists($name): bool {
try {
$this->getChild($name);
return true;
} catch (NotFound $e) {
return false;
}
}
public function delete() {
throw new Forbidden();
}
public function getName(): string {
return (string)$this->file->getId();
}
public function setName($name) {
throw new Forbidden();
}
public function getLastModified(): int {
return 0;
}
}
@@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Sabre;
use OCA\Files_Versions\Versions\IDeletableVersionBackend;
use OCA\Files_Versions\Versions\INameableVersion;
use OCA\Files_Versions\Versions\INameableVersionBackend;
use OCA\Files_Versions\Versions\IVersion;
use OCA\Files_Versions\Versions\IVersionManager;
use OCP\Files\NotFoundException;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\Exception\NotFound;
use Sabre\DAV\IFile;
class VersionFile implements IFile {
/** @var IVersion */
private $version;
/** @var IVersionManager */
private $versionManager;
public function __construct(IVersion $version, IVersionManager $versionManager) {
$this->version = $version;
$this->versionManager = $versionManager;
}
public function put($data) {
throw new Forbidden();
}
public function get() {
try {
return $this->versionManager->read($this->version);
} catch (NotFoundException $e) {
throw new NotFound();
}
}
public function getContentType(): string {
return $this->version->getMimeType();
}
public function getETag(): string {
return (string)$this->version->getRevisionId();
}
/**
* @psalm-suppress ImplementedReturnTypeMismatch \Sabre\DAV\IFile::getSize signature does not support 32bit
* @return int|float
*/
public function getSize(): int|float {
return $this->version->getSize();
}
public function delete() {
if ($this->versionManager instanceof IDeletableVersionBackend) {
$this->versionManager->deleteVersion($this->version);
} else {
throw new Forbidden();
}
}
public function getName(): string {
return (string)$this->version->getRevisionId();
}
public function setName($name) {
throw new Forbidden();
}
public function getLabel(): ?string {
if ($this->version instanceof INameableVersion && $this->version->getSourceFile()->getSize() > 0) {
return $this->version->getLabel();
} else {
return null;
}
}
public function setLabel($label): bool {
if ($this->versionManager instanceof INameableVersionBackend) {
$this->versionManager->setVersionLabel($this->version, $label);
return true;
} else {
return false;
}
}
public function getLastModified(): int {
return $this->version->getTimestamp();
}
public function rollBack() {
$this->versionManager->rollback($this->version);
}
public function getVersion(): IVersion {
return $this->version;
}
}
@@ -0,0 +1,110 @@
<?php
/**
* @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Sabre;
use OC\User\NoUserException;
use OCA\Files_Versions\Versions\IVersionManager;
use OCP\Files\IRootFolder;
use OCP\IUserManager;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\ICollection;
class VersionHome implements ICollection {
/** @var array */
private $principalInfo;
/** @var IRootFolder */
private $rootFolder;
/** @var IUserManager */
private $userManager;
/** @var IVersionManager */
private $versionManager;
public function __construct(array $principalInfo, IRootFolder $rootFolder, IUserManager $userManager, IVersionManager $versionManager) {
$this->principalInfo = $principalInfo;
$this->rootFolder = $rootFolder;
$this->userManager = $userManager;
$this->versionManager = $versionManager;
}
private function getUser() {
[, $name] = \Sabre\Uri\split($this->principalInfo['uri']);
$user = $this->userManager->get($name);
if (!$user) {
throw new NoUserException();
}
return $user;
}
public function delete() {
throw new Forbidden();
}
public function getName(): string {
return $this->getUser()->getUID();
}
public function setName($name) {
throw new Forbidden();
}
public function createFile($name, $data = null) {
throw new Forbidden();
}
public function createDirectory($name) {
throw new Forbidden();
}
public function getChild($name) {
$user = $this->getUser();
if ($name === 'versions') {
return new VersionRoot($user, $this->rootFolder, $this->versionManager);
}
if ($name === 'restore') {
return new RestoreFolder();
}
}
public function getChildren() {
$user = $this->getUser();
return [
new VersionRoot($user, $this->rootFolder, $this->versionManager),
new RestoreFolder(),
];
}
public function childExists($name) {
return $name === 'versions' || $name === 'restore';
}
public function getLastModified() {
return 0;
}
}
@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Sabre;
use OCA\Files_Versions\Versions\IVersionManager;
use OCP\Files\File;
use OCP\Files\IRootFolder;
use OCP\IUser;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\Exception\NotFound;
use Sabre\DAV\ICollection;
class VersionRoot implements ICollection {
/** @var IUser */
private $user;
/** @var IRootFolder */
private $rootFolder;
/** @var IVersionManager */
private $versionManager;
public function __construct(IUser $user, IRootFolder $rootFolder, IVersionManager $versionManager) {
$this->user = $user;
$this->rootFolder = $rootFolder;
$this->versionManager = $versionManager;
}
public function delete() {
throw new Forbidden();
}
public function getName(): string {
return 'versions';
}
public function setName($name) {
throw new Forbidden();
}
public function createFile($name, $data = null) {
throw new Forbidden();
}
public function createDirectory($name) {
throw new Forbidden();
}
public function getChild($name) {
$userFolder = $this->rootFolder->getUserFolder($this->user->getUID());
$fileId = (int)$name;
$nodes = $userFolder->getById($fileId);
if ($nodes === []) {
throw new NotFound();
}
$node = array_pop($nodes);
if (!$node instanceof File) {
throw new NotFound();
}
return new VersionCollection($node, $this->user, $this->versionManager);
}
public function getChildren(): array {
return [];
}
public function childExists($name): bool {
try {
$this->getChild($name);
return true;
} catch (NotFound $e) {
return false;
}
}
public function getLastModified(): int {
return 0;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,26 @@
<?php
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @author Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Versions;
class BackendNotFoundException extends \Exception {
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Louis Chmn <louis@chmn.me>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Versions;
/**
* @since 26.0.0
*/
interface IDeletableVersionBackend {
/**
* Delete a version.
*
* @since 26.0.0
*/
public function deleteVersion(IVersion $version): void;
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Louis Chmn <louis@chmn.me>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Versions;
/**
* @since 26.0.0
*/
interface INameableVersion {
/**
* Get the user created label
*
* @return string
* @since 26.0.0
*/
public function getLabel(): string;
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Louis Chmn <louis@chmn.me>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Versions;
/**
* @since 26.0.0
*/
interface INameableVersionBackend {
/**
* Set the label for a version.
*
* @since 26.0.0
*/
public function setVersionLabel(IVersion $version, string $label): void;
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Louis Chmn <louis@chmn.me>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Versions;
use OCP\Files\File;
/**
* @since 28.0.0
*/
interface INeedSyncVersionBackend {
public function createVersionEntity(File $file): void;
public function updateVersionEntity(File $sourceFile, int $revision, array $properties): void;
public function deleteVersionsEntity(File $file): void;
}
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @author Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Versions;
use OCP\Files\FileInfo;
use OCP\IUser;
/**
* @since 15.0.0
*/
interface IVersion {
/**
* @return IVersionBackend
* @since 15.0.0
*/
public function getBackend(): IVersionBackend;
/**
* Get the file info of the source file
*
* @return FileInfo
* @since 15.0.0
*/
public function getSourceFile(): FileInfo;
/**
* Get the id of the revision for the file
*
* @return int|string
* @since 15.0.0
*/
public function getRevisionId();
/**
* Get the timestamp this version was created
*
* @return int
* @since 15.0.0
*/
public function getTimestamp(): int;
/**
* Get the size of this version
*
* @return int|float
* @since 15.0.0
*/
public function getSize(): int|float;
/**
* Get the name of the source file at the time of making this version
*
* @return string
* @since 15.0.0
*/
public function getSourceFileName(): string;
/**
* Get the mimetype of this version
*
* @return string
* @since 15.0.0
*/
public function getMimeType(): string;
/**
* Get the path of this version
*
* @return string
* @since 15.0.0
*/
public function getVersionPath(): string;
/**
* @return IUser
* @since 15.0.0
*/
public function getUser(): IUser;
}
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Versions;
use OCP\Files\File;
use OCP\Files\FileInfo;
use OCP\Files\NotFoundException;
use OCP\Files\Storage\IStorage;
use OCP\IUser;
/**
* @since 15.0.0
*/
interface IVersionBackend {
/**
* Whether or not this version backend should be used for a storage
*
* If false is returned then the next applicable backend will be used
*
* @param IStorage $storage
* @return bool
* @since 17.0.0
*/
public function useBackendForStorage(IStorage $storage): bool;
/**
* Get all versions for a file
*
* @param IUser $user
* @param FileInfo $file
* @return IVersion[]
* @since 15.0.0
*/
public function getVersionsForFile(IUser $user, FileInfo $file): array;
/**
* Create a new version for a file
*
* @param IUser $user
* @param FileInfo $file
* @since 15.0.0
*/
public function createVersion(IUser $user, FileInfo $file);
/**
* Restore this version
*
* @param IVersion $version
* @since 15.0.0
*/
public function rollback(IVersion $version);
/**
* Open the file for reading
*
* @param IVersion $version
* @return resource|false
* @throws NotFoundException
* @since 15.0.0
*/
public function read(IVersion $version);
/**
* Get the preview for a specific version of a file
*
* @param IUser $user
* @param FileInfo $sourceFile
* @param int|string $revision
*
* @return File
*
* @since 15.0.0
*/
public function getVersionFile(IUser $user, FileInfo $sourceFile, $revision): File;
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @author Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Versions;
/**
* @since 15.0.0
*/
interface IVersionManager extends IVersionBackend {
/**
* Register a new backend
*
* @param string $storageType
* @param IVersionBackend $backend
* @since 15.0.0
*/
public function registerBackend(string $storageType, IVersionBackend $backend);
}
@@ -0,0 +1,309 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Versions;
use OC\Files\View;
use OCA\DAV\Connector\Sabre\Exception\Forbidden;
use OCA\Files_Sharing\ISharedStorage;
use OCA\Files_Sharing\SharedStorage;
use OCA\Files_Versions\Db\VersionEntity;
use OCA\Files_Versions\Db\VersionsMapper;
use OCA\Files_Versions\Storage;
use OCP\Files\File;
use OCP\Files\FileInfo;
use OCP\Files\Folder;
use OCP\Files\IMimeTypeLoader;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\Files\Storage\IStorage;
use OCP\IUser;
use OCP\IUserManager;
use OCP\IUserSession;
class LegacyVersionsBackend implements IVersionBackend, INameableVersionBackend, IDeletableVersionBackend, INeedSyncVersionBackend {
private IRootFolder $rootFolder;
private IUserManager $userManager;
private VersionsMapper $versionsMapper;
private IMimeTypeLoader $mimeTypeLoader;
private IUserSession $userSession;
public function __construct(
IRootFolder $rootFolder,
IUserManager $userManager,
VersionsMapper $versionsMapper,
IMimeTypeLoader $mimeTypeLoader,
IUserSession $userSession,
) {
$this->rootFolder = $rootFolder;
$this->userManager = $userManager;
$this->versionsMapper = $versionsMapper;
$this->mimeTypeLoader = $mimeTypeLoader;
$this->userSession = $userSession;
}
public function useBackendForStorage(IStorage $storage): bool {
return true;
}
public function getVersionsForFile(IUser $user, FileInfo $file): array {
$storage = $file->getStorage();
if ($storage->instanceOfStorage(SharedStorage::class)) {
$owner = $storage->getOwner('');
$user = $this->userManager->get($owner);
$fileId = $file->getId();
if ($fileId === null) {
throw new NotFoundException("File not found ($fileId)");
}
if ($user === null) {
throw new NotFoundException("User $owner not found for $fileId");
}
$userFolder = $this->rootFolder->getUserFolder($user->getUID());
$nodes = $userFolder->getById($fileId);
$file = array_pop($nodes);
if (!$file) {
throw new NotFoundException("version file not found for share owner");
}
} else {
$userFolder = $this->rootFolder->getUserFolder($user->getUID());
}
$fileId = $file->getId();
if ($fileId === null) {
throw new NotFoundException("File not found ($fileId)");
}
$versions = $this->getVersionsForFileFromDB($file, $user);
// Early exit if we find any version in the database.
// Else we continue to populate the DB from what's on disk.
if (count($versions) > 0) {
return $versions;
}
// Insert the entry in the DB for the current version.
$versionEntity = new VersionEntity();
$versionEntity->setFileId($fileId);
$versionEntity->setTimestamp($file->getMTime());
$versionEntity->setSize($file->getSize());
$versionEntity->setMimetype($this->mimeTypeLoader->getId($file->getMimetype()));
$versionEntity->setMetadata([]);
$this->versionsMapper->insert($versionEntity);
// Insert entries in the DB for existing versions.
$relativePath = $userFolder->getRelativePath($file->getPath());
if ($relativePath === null) {
throw new NotFoundException("Relative path not found for file $fileId (" . $file->getPath() . ')');
}
$versionsOnFS = Storage::getVersions($user->getUID(), $relativePath);
foreach ($versionsOnFS as $version) {
$versionEntity = new VersionEntity();
$versionEntity->setFileId($fileId);
$versionEntity->setTimestamp((int)$version['version']);
$versionEntity->setSize((int)$version['size']);
$versionEntity->setMimetype($this->mimeTypeLoader->getId($version['mimetype']));
$versionEntity->setMetadata([]);
$this->versionsMapper->insert($versionEntity);
}
return $this->getVersionsForFileFromDB($file, $user);
}
/**
* @return IVersion[]
*/
private function getVersionsForFileFromDB(FileInfo $file, IUser $user): array {
$userFolder = $this->rootFolder->getUserFolder($user->getUID());
return array_map(
fn (VersionEntity $versionEntity) => new Version(
$versionEntity->getTimestamp(),
$versionEntity->getTimestamp(),
$file->getName(),
$versionEntity->getSize(),
$this->mimeTypeLoader->getMimetypeById($versionEntity->getMimetype()),
$userFolder->getRelativePath($file->getPath()),
$file,
$this,
$user,
$versionEntity->getLabel(),
),
$this->versionsMapper->findAllVersionsForFileId($file->getId())
);
}
public function createVersion(IUser $user, FileInfo $file) {
$userFolder = $this->rootFolder->getUserFolder($user->getUID());
$relativePath = $userFolder->getRelativePath($file->getPath());
$userView = new View('/' . $user->getUID());
// create all parent folders
Storage::createMissingDirectories($relativePath, $userView);
Storage::scheduleExpire($user->getUID(), $relativePath);
// store a new version of a file
$userView->copy('files/' . $relativePath, 'files_versions/' . $relativePath . '.v' . $file->getMtime());
// ensure the file is scanned
$userView->getFileInfo('files_versions/' . $relativePath . '.v' . $file->getMtime());
}
public function rollback(IVersion $version) {
if (!$this->currentUserHasPermissions($version, \OCP\Constants::PERMISSION_UPDATE)) {
throw new Forbidden('You cannot restore this version because you do not have update permissions on the source file.');
}
return Storage::rollback($version->getVersionPath(), $version->getRevisionId(), $version->getUser());
}
private function getVersionFolder(IUser $user): Folder {
$userRoot = $this->rootFolder->getUserFolder($user->getUID())
->getParent();
try {
/** @var Folder $folder */
$folder = $userRoot->get('files_versions');
return $folder;
} catch (NotFoundException $e) {
return $userRoot->newFolder('files_versions');
}
}
public function read(IVersion $version) {
$versions = $this->getVersionFolder($version->getUser());
/** @var File $file */
$file = $versions->get($version->getVersionPath() . '.v' . $version->getRevisionId());
return $file->fopen('r');
}
public function getVersionFile(IUser $user, FileInfo $sourceFile, $revision): File {
$userFolder = $this->rootFolder->getUserFolder($user->getUID());
$owner = $sourceFile->getOwner();
$storage = $sourceFile->getStorage();
// Shared files have their versions in the owners root folder so we need to obtain them from there
if ($storage->instanceOfStorage(ISharedStorage::class) && $owner) {
/** @var SharedStorage $storage */
$userFolder = $this->rootFolder->getUserFolder($owner->getUID());
$user = $owner;
$ownerPathInStorage = $sourceFile->getInternalPath();
$sourceFile = $storage->getShare()->getNode();
if ($sourceFile instanceof Folder) {
$sourceFile = $sourceFile->get($ownerPathInStorage);
}
}
$versionFolder = $this->getVersionFolder($user);
/** @var File $file */
$file = $versionFolder->get($userFolder->getRelativePath($sourceFile->getPath()) . '.v' . $revision);
return $file;
}
public function setVersionLabel(IVersion $version, string $label): void {
if (!$this->currentUserHasPermissions($version, \OCP\Constants::PERMISSION_UPDATE)) {
throw new Forbidden('You cannot label this version because you do not have update permissions on the source file.');
}
$versionEntity = $this->versionsMapper->findVersionForFileId(
$version->getSourceFile()->getId(),
$version->getTimestamp(),
);
if (trim($label) === '') {
$label = null;
}
$versionEntity->setLabel($label ?? '');
$this->versionsMapper->update($versionEntity);
}
public function deleteVersion(IVersion $version): void {
if (!$this->currentUserHasPermissions($version, \OCP\Constants::PERMISSION_DELETE)) {
throw new Forbidden('You cannot delete this version because you do not have delete permissions on the source file.');
}
Storage::deleteRevision($version->getVersionPath(), $version->getRevisionId());
$versionEntity = $this->versionsMapper->findVersionForFileId(
$version->getSourceFile()->getId(),
$version->getTimestamp(),
);
$this->versionsMapper->delete($versionEntity);
}
public function createVersionEntity(File $file): void {
$versionEntity = new VersionEntity();
$versionEntity->setFileId($file->getId());
$versionEntity->setTimestamp($file->getMTime());
$versionEntity->setSize($file->getSize());
$versionEntity->setMimetype($this->mimeTypeLoader->getId($file->getMimetype()));
$versionEntity->setMetadata([]);
$this->versionsMapper->insert($versionEntity);
}
public function updateVersionEntity(File $sourceFile, int $revision, array $properties): void {
$versionEntity = $this->versionsMapper->findVersionForFileId($sourceFile->getId(), $revision);
if (isset($properties['timestamp'])) {
$versionEntity->setTimestamp($properties['timestamp']);
}
if (isset($properties['size'])) {
$versionEntity->setSize($properties['size']);
}
if (isset($properties['mimetype'])) {
$versionEntity->setMimetype($properties['mimetype']);
}
$this->versionsMapper->update($versionEntity);
}
public function deleteVersionsEntity(File $file): void {
$this->versionsMapper->deleteAllVersionsForFileId($file->getId());
}
private function currentUserHasPermissions(IVersion $version, int $permissions): bool {
$sourceFile = $version->getSourceFile();
$currentUserId = $this->userSession->getUser()?->getUID();
if ($currentUserId === null) {
throw new NotFoundException("No user logged in");
}
if ($sourceFile->getOwner()?->getUID() !== $currentUserId) {
$nodes = $this->rootFolder->getUserFolder($currentUserId)->getById($sourceFile->getId());
$sourceFile = array_pop($nodes);
if (!$sourceFile) {
throw new NotFoundException("Version file not accessible by current user");
}
}
return ($sourceFile->getPermissions() & $permissions) === $permissions;
}
}
@@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @author Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Versions;
use OCP\Files\FileInfo;
use OCP\IUser;
class Version implements IVersion, INameableVersion {
/** @var int */
private $timestamp;
/** @var int|string */
private $revisionId;
/** @var string */
private $name;
private string $label;
/** @var int|float */
private $size;
/** @var string */
private $mimetype;
/** @var string */
private $path;
/** @var FileInfo */
private $sourceFileInfo;
/** @var IVersionBackend */
private $backend;
/** @var IUser */
private $user;
public function __construct(
int $timestamp,
$revisionId,
string $name,
int|float $size,
string $mimetype,
string $path,
FileInfo $sourceFileInfo,
IVersionBackend $backend,
IUser $user,
string $label = ''
) {
$this->timestamp = $timestamp;
$this->revisionId = $revisionId;
$this->name = $name;
$this->label = $label;
$this->size = $size;
$this->mimetype = $mimetype;
$this->path = $path;
$this->sourceFileInfo = $sourceFileInfo;
$this->backend = $backend;
$this->user = $user;
}
public function getBackend(): IVersionBackend {
return $this->backend;
}
public function getSourceFile(): FileInfo {
return $this->sourceFileInfo;
}
public function getRevisionId() {
return $this->revisionId;
}
public function getTimestamp(): int {
return $this->timestamp;
}
public function getSize(): int|float {
return $this->size;
}
public function getSourceFileName(): string {
return $this->name;
}
public function getLabel(): string {
return $this->label;
}
public function getMimeType(): string {
return $this->mimetype;
}
public function getVersionPath(): string {
return $this->path;
}
public function getUser(): IUser {
return $this->user;
}
}
@@ -0,0 +1,206 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl>
*
* @author Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Versions\Versions;
use OCP\Files\File;
use OCP\Files\FileInfo;
use OCP\Files\IRootFolder;
use OCP\Files\Lock\ILock;
use OCP\Files\Lock\ILockManager;
use OCP\Files\Lock\LockContext;
use OCP\Files\Storage\IStorage;
use OCP\IUser;
use OCP\Lock\ManuallyLockedException;
class VersionManager implements IVersionManager, INameableVersionBackend, IDeletableVersionBackend, INeedSyncVersionBackend {
/** @var (IVersionBackend[])[] */
private $backends = [];
public function registerBackend(string $storageType, IVersionBackend $backend) {
if (!isset($this->backends[$storageType])) {
$this->backends[$storageType] = [];
}
$this->backends[$storageType][] = $backend;
}
/**
* @return (IVersionBackend[])[]
*/
private function getBackends(): array {
return $this->backends;
}
/**
* @param IStorage $storage
* @return IVersionBackend
* @throws BackendNotFoundException
*/
public function getBackendForStorage(IStorage $storage): IVersionBackend {
$fullType = get_class($storage);
$backends = $this->getBackends();
$foundType = '';
$foundBackend = null;
foreach ($backends as $type => $backendsForType) {
if (
$storage->instanceOfStorage($type) &&
($foundType === '' || is_subclass_of($type, $foundType))
) {
foreach ($backendsForType as $backend) {
/** @var IVersionBackend $backend */
if ($backend->useBackendForStorage($storage)) {
$foundBackend = $backend;
$foundType = $type;
}
}
}
}
if ($foundType === '' || $foundBackend === null) {
throw new BackendNotFoundException("Version backend for $fullType not found");
} else {
return $foundBackend;
}
}
public function getVersionsForFile(IUser $user, FileInfo $file): array {
$backend = $this->getBackendForStorage($file->getStorage());
return $backend->getVersionsForFile($user, $file);
}
public function createVersion(IUser $user, FileInfo $file) {
$backend = $this->getBackendForStorage($file->getStorage());
$backend->createVersion($user, $file);
}
public function rollback(IVersion $version) {
$backend = $version->getBackend();
$result = self::handleAppLocks(fn (): ?bool => $backend->rollback($version));
// rollback doesn't have a return type yet and some implementations don't return anything
if ($result === null || $result === true) {
\OC_Hook::emit('\OCP\Versions', 'rollback', [
'path' => $version->getVersionPath(),
'revision' => $version->getRevisionId(),
'node' => $version->getSourceFile(),
]);
}
return $result;
}
public function read(IVersion $version) {
$backend = $version->getBackend();
return $backend->read($version);
}
public function getVersionFile(IUser $user, FileInfo $sourceFile, $revision): File {
$backend = $this->getBackendForStorage($sourceFile->getStorage());
return $backend->getVersionFile($user, $sourceFile, $revision);
}
public function useBackendForStorage(IStorage $storage): bool {
return false;
}
public function setVersionLabel(IVersion $version, string $label): void {
$backend = $this->getBackendForStorage($version->getSourceFile()->getStorage());
if ($backend instanceof INameableVersionBackend) {
$backend->setVersionLabel($version, $label);
}
}
public function deleteVersion(IVersion $version): void {
$backend = $this->getBackendForStorage($version->getSourceFile()->getStorage());
if ($backend instanceof IDeletableVersionBackend) {
$backend->deleteVersion($version);
}
}
public function createVersionEntity(File $file): void {
$backend = $this->getBackendForStorage($file->getStorage());
if ($backend instanceof INeedSyncVersionBackend) {
$backend->createVersionEntity($file);
}
}
public function updateVersionEntity(File $sourceFile, int $revision, array $properties): void {
$backend = $this->getBackendForStorage($sourceFile->getStorage());
if ($backend instanceof INeedSyncVersionBackend) {
$backend->updateVersionEntity($sourceFile, $revision, $properties);
}
}
public function deleteVersionsEntity(File $file): void {
$backend = $this->getBackendForStorage($file->getStorage());
if ($backend instanceof INeedSyncVersionBackend) {
$backend->deleteVersionsEntity($file);
}
}
/**
* Catch ManuallyLockedException and retry in app context if possible.
*
* Allow users to go back to old versions via the versions tab in the sidebar
* even when the file is opened in the viewer next to it.
*
* Context: If a file is currently opened for editing
* the files_lock app will throw ManuallyLockedExceptions.
* This prevented the user from rolling an opened file back to a previous version.
*
* Text and Richdocuments can handle changes of open files.
* So we execute the rollback under their lock context
* to let them handle the conflict.
*
* @param callable $callback function to run with app locks handled
* @return bool|null
* @throws ManuallyLockedException
*
*/
private static function handleAppLocks(callable $callback): ?bool {
try {
return $callback();
} catch (ManuallyLockedException $e) {
$owner = (string) $e->getOwner();
$appsThatHandleUpdates = array("text", "richdocuments");
if (!in_array($owner, $appsThatHandleUpdates)) {
throw $e;
}
// The LockWrapper in the files_lock app only compares the lock type and owner
// when checking the lock against the current scope.
// So we do not need to get the actual node here
// and use the root node instead.
$root = \OC::$server->get(IRootFolder::class);
$lockContext = new LockContext($root, ILock::TYPE_APP, $owner);
$lockManager = \OC::$server->get(ILockManager::class);
$result = null;
$lockManager->runInScope($lockContext, function () use ($callback, &$result) {
$result = $callback();
});
return $result;
}
}
}