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,177 @@
<?php
/**
* @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @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\Activity;
use OCP\Activity\IEvent;
use OCP\Activity\IEventMerger;
use OCP\Activity\IManager;
use OCP\Activity\IProvider;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\L10N\IFactory;
class FavoriteProvider implements IProvider {
public const SUBJECT_ADDED = 'added_favorite';
public const SUBJECT_REMOVED = 'removed_favorite';
/** @var IFactory */
protected $languageFactory;
/** @var IL10N */
protected $l;
/** @var IURLGenerator */
protected $url;
/** @var IManager */
protected $activityManager;
/** @var IEventMerger */
protected $eventMerger;
/**
* @param IFactory $languageFactory
* @param IURLGenerator $url
* @param IManager $activityManager
* @param IEventMerger $eventMerger
*/
public function __construct(IFactory $languageFactory, IURLGenerator $url, IManager $activityManager, IEventMerger $eventMerger) {
$this->languageFactory = $languageFactory;
$this->url = $url;
$this->activityManager = $activityManager;
$this->eventMerger = $eventMerger;
}
/**
* @param string $language
* @param IEvent $event
* @param IEvent|null $previousEvent
* @return IEvent
* @throws \InvalidArgumentException
* @since 11.0.0
*/
public function parse($language, IEvent $event, IEvent $previousEvent = null) {
if ($event->getApp() !== 'files' || $event->getType() !== 'favorite') {
throw new \InvalidArgumentException();
}
$this->l = $this->languageFactory->get('files', $language);
if ($this->activityManager->isFormattingFilteredObject()) {
try {
return $this->parseShortVersion($event);
} catch (\InvalidArgumentException $e) {
// Ignore and simply use the long version...
}
}
return $this->parseLongVersion($event, $previousEvent);
}
/**
* @param IEvent $event
* @return IEvent
* @throws \InvalidArgumentException
* @since 11.0.0
*/
public function parseShortVersion(IEvent $event) {
if ($event->getSubject() === self::SUBJECT_ADDED) {
$event->setParsedSubject($this->l->t('Added to favorites'));
if ($this->activityManager->getRequirePNG()) {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/starred.png')));
} else {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/starred.svg')));
}
} elseif ($event->getSubject() === self::SUBJECT_REMOVED) {
$event->setType('unfavorite');
$event->setParsedSubject($this->l->t('Removed from favorites'));
if ($this->activityManager->getRequirePNG()) {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/star.png')));
} else {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/star.svg')));
}
} else {
throw new \InvalidArgumentException();
}
return $event;
}
/**
* @param IEvent $event
* @param IEvent|null $previousEvent
* @return IEvent
* @throws \InvalidArgumentException
* @since 11.0.0
*/
public function parseLongVersion(IEvent $event, IEvent $previousEvent = null) {
if ($event->getSubject() === self::SUBJECT_ADDED) {
$subject = $this->l->t('You added {file} to your favorites');
if ($this->activityManager->getRequirePNG()) {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/starred.png')));
} else {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/starred.svg')));
}
} elseif ($event->getSubject() === self::SUBJECT_REMOVED) {
$event->setType('unfavorite');
$subject = $this->l->t('You removed {file} from your favorites');
if ($this->activityManager->getRequirePNG()) {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/star.png')));
} else {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/star.svg')));
}
} else {
throw new \InvalidArgumentException();
}
$this->setSubjects($event, $subject);
$event = $this->eventMerger->mergeEvents('file', $event, $previousEvent);
return $event;
}
/**
* @param IEvent $event
* @param string $subject
*/
protected function setSubjects(IEvent $event, $subject) {
$subjectParams = $event->getSubjectParameters();
if (empty($subjectParams)) {
// Try to fall back to the old way, but this does not work for emails.
// But at least old activities still work.
$subjectParams = [
'id' => $event->getObjectId(),
'path' => $event->getObjectName(),
];
}
$parameter = [
'type' => 'file',
'id' => $subjectParams['id'],
'name' => basename($subjectParams['path']),
'path' => trim($subjectParams['path'], '/'),
'link' => $this->url->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $subjectParams['id']]),
];
$event->setRichSubject($subject, ['file' => $parameter]);
}
}
@@ -0,0 +1,160 @@
<?php
/**
* @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @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\Activity\Filter;
use OCA\Files\Activity\Helper;
use OCP\Activity\IFilter;
use OCP\Activity\IManager;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
use OCP\IL10N;
use OCP\IURLGenerator;
class Favorites implements IFilter {
/** @var IL10N */
protected $l;
/** @var IURLGenerator */
protected $url;
/** @var IManager */
protected $activityManager;
/** @var Helper */
protected $helper;
/** @var IDBConnection */
protected $db;
/**
* @param IL10N $l
* @param IURLGenerator $url
* @param IManager $activityManager
* @param Helper $helper
* @param IDBConnection $db
*/
public function __construct(IL10N $l, IURLGenerator $url, IManager $activityManager, Helper $helper, IDBConnection $db) {
$this->l = $l;
$this->url = $url;
$this->activityManager = $activityManager;
$this->helper = $helper;
$this->db = $db;
}
/**
* @return string Lowercase a-z only identifier
* @since 11.0.0
*/
public function getIdentifier() {
return 'files_favorites';
}
/**
* @return string A translated string
* @since 11.0.0
*/
public function getName() {
return $this->l->t('Favorites');
}
/**
* @return int
* @since 11.0.0
*/
public function getPriority() {
return 10;
}
/**
* @return string Full URL to an icon, empty string when none is given
* @since 11.0.0
*/
public function getIcon() {
return $this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/star-dark.svg'));
}
/**
* @param string[] $types
* @return string[] An array of allowed apps from which activities should be displayed
* @since 11.0.0
*/
public function filterTypes(array $types) {
return array_intersect([
'file_created',
'file_changed',
'file_deleted',
'file_restored',
], $types);
}
/**
* @return string[] An array of allowed apps from which activities should be displayed
* @since 11.0.0
*/
public function allowedApps() {
return ['files'];
}
/**
* @param IQueryBuilder $query
*/
public function filterFavorites(IQueryBuilder $query) {
try {
$user = $this->activityManager->getCurrentUserId();
} catch (\UnexpectedValueException $e) {
return;
}
try {
$favorites = $this->helper->getFavoriteFilePaths($user);
} catch (\RuntimeException $e) {
return;
}
$limitations = [];
if (!empty($favorites['items'])) {
$limitations[] = $query->expr()->in('file', $query->createNamedParameter($favorites['items'], IQueryBuilder::PARAM_STR_ARRAY));
}
foreach ($favorites['folders'] as $favorite) {
$limitations[] = $query->expr()->like('file', $query->createNamedParameter(
$this->db->escapeLikeParameter($favorite . '/') . '%'
));
}
if (empty($limitations)) {
return;
}
$function = $query->createFunction('
CASE
WHEN ' . $query->getColumnName('app') . ' <> ' . $query->createNamedParameter('files') . ' THEN 1
WHEN ' . $query->getColumnName('app') . ' = ' . $query->createNamedParameter('files') . '
AND (' . implode(' OR ', $limitations) . ')
THEN 1
END = 1'
);
$query->andWhere($function);
}
}
@@ -0,0 +1,100 @@
<?php
/**
* @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
*
* @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\Activity\Filter;
use OCP\Activity\IFilter;
use OCP\IL10N;
use OCP\IURLGenerator;
class FileChanges implements IFilter {
/** @var IL10N */
protected $l;
/** @var IURLGenerator */
protected $url;
/**
* @param IL10N $l
* @param IURLGenerator $url
*/
public function __construct(IL10N $l, IURLGenerator $url) {
$this->l = $l;
$this->url = $url;
}
/**
* @return string Lowercase a-z only identifier
* @since 11.0.0
*/
public function getIdentifier() {
return 'files';
}
/**
* @return string A translated string
* @since 11.0.0
*/
public function getName() {
return $this->l->t('File changes');
}
/**
* @return int
* @since 11.0.0
*/
public function getPriority() {
return 30;
}
/**
* @return string Full URL to an icon, empty string when none is given
* @since 11.0.0
*/
public function getIcon() {
return $this->url->getAbsoluteURL($this->url->imagePath('core', 'places/files.svg'));
}
/**
* @param string[] $types
* @return string[] An array of allowed apps from which activities should be displayed
* @since 11.0.0
*/
public function filterTypes(array $types) {
return array_intersect([
'file_created',
'file_changed',
'file_deleted',
'file_restored',
], $types);
}
/**
* @return string[] An array of allowed apps from which activities should be displayed
* @since 11.0.0
*/
public function allowedApps() {
return ['files'];
}
}
@@ -0,0 +1,105 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Ferdinand Thiessen <opensource@fthiessen.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\Activity;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\ITagManager;
class Helper {
/** If a user has a lot of favorites the query might get too slow and long */
public const FAVORITE_LIMIT = 50;
public function __construct(
protected ITagManager $tagManager,
protected IRootFolder $rootFolder,
) {
}
/**
* Return an array with nodes marked as favorites
*
* @param string $user User ID
* @param bool $foldersOnly Only return folders (default false)
* @return Node[]
* @psalm-return ($foldersOnly is true ? Folder[] : Node[])
* @throws \RuntimeException when too many or no favorites where found
*/
public function getFavoriteNodes(string $user, bool $foldersOnly = false): array {
$tags = $this->tagManager->load('files', [], false, $user);
$favorites = $tags->getFavorites();
if (empty($favorites)) {
throw new \RuntimeException('No favorites', 1);
} elseif (isset($favorites[self::FAVORITE_LIMIT])) {
throw new \RuntimeException('Too many favorites', 2);
}
// Can not DI because the user is not known on instantiation
$userFolder = $this->rootFolder->getUserFolder($user);
$favoriteNodes = [];
foreach ($favorites as $favorite) {
$nodes = $userFolder->getById($favorite);
if (!empty($nodes)) {
$node = array_shift($nodes);
if (!$foldersOnly || $node instanceof Folder) {
$favoriteNodes[] = $node;
}
}
}
if (empty($favoriteNodes)) {
throw new \RuntimeException('No favorites', 1);
}
return $favoriteNodes;
}
/**
* Returns an array with the favorites
*
* @param string $user
* @return array
* @throws \RuntimeException when too many or no favorites where found
*/
public function getFavoriteFilePaths(string $user): array {
$userFolder = $this->rootFolder->getUserFolder($user);
$nodes = $this->getFavoriteNodes($user);
$folders = $items = [];
foreach ($nodes as $node) {
$path = $userFolder->getRelativePath($node->getPath());
$items[] = $path;
if ($node instanceof Folder) {
$folders[] = $path;
}
}
return [
'items' => $items,
'folders' => $folders,
];
}
}
@@ -0,0 +1,579 @@
<?php
/**
* @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @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\Activity;
use OCP\Activity\IEvent;
use OCP\Activity\IEventMerger;
use OCP\Activity\IManager;
use OCP\Activity\IProvider;
use OCP\Contacts\IManager as IContactsManager;
use OCP\Federation\ICloudIdManager;
use OCP\Files\Folder;
use OCP\Files\InvalidPathException;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\Files\NotFoundException;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\IUserManager;
use OCP\L10N\IFactory;
class Provider implements IProvider {
/** @var IFactory */
protected $languageFactory;
/** @var IL10N */
protected $l;
/** @var IL10N */
protected $activityLang;
/** @var IURLGenerator */
protected $url;
/** @var IManager */
protected $activityManager;
/** @var IUserManager */
protected $userManager;
/** @var IRootFolder */
protected $rootFolder;
/** @var IEventMerger */
protected $eventMerger;
/** @var ICloudIdManager */
protected $cloudIdManager;
/** @var IContactsManager */
protected $contactsManager;
/** @var string[] cached displayNames - key is the cloud id and value the displayname */
protected $displayNames = [];
protected $fileIsEncrypted = false;
public function __construct(IFactory $languageFactory,
IURLGenerator $url,
IManager $activityManager,
IUserManager $userManager,
IRootFolder $rootFolder,
ICloudIdManager $cloudIdManager,
IContactsManager $contactsManager,
IEventMerger $eventMerger) {
$this->languageFactory = $languageFactory;
$this->url = $url;
$this->activityManager = $activityManager;
$this->userManager = $userManager;
$this->rootFolder = $rootFolder;
$this->cloudIdManager = $cloudIdManager;
$this->contactsManager = $contactsManager;
$this->eventMerger = $eventMerger;
}
/**
* @param string $language
* @param IEvent $event
* @param IEvent|null $previousEvent
* @return IEvent
* @throws \InvalidArgumentException
* @since 11.0.0
*/
public function parse($language, IEvent $event, IEvent $previousEvent = null) {
if ($event->getApp() !== 'files') {
throw new \InvalidArgumentException();
}
$this->l = $this->languageFactory->get('files', $language);
$this->activityLang = $this->languageFactory->get('activity', $language);
if ($this->activityManager->isFormattingFilteredObject()) {
try {
return $this->parseShortVersion($event, $previousEvent);
} catch (\InvalidArgumentException $e) {
// Ignore and simply use the long version...
}
}
return $this->parseLongVersion($event, $previousEvent);
}
protected function setIcon(IEvent $event, string $icon, string $app = 'files') {
if ($this->activityManager->getRequirePNG()) {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath($app, $icon . '.png')));
} else {
$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath($app, $icon . '.svg')));
}
}
/**
* @param IEvent $event
* @param IEvent|null $previousEvent
* @return IEvent
* @throws \InvalidArgumentException
* @since 11.0.0
*/
public function parseShortVersion(IEvent $event, IEvent $previousEvent = null) {
$parsedParameters = $this->getParameters($event);
if ($event->getSubject() === 'created_by') {
$subject = $this->l->t('Created by {user}');
$this->setIcon($event, 'add-color');
} elseif ($event->getSubject() === 'changed_by') {
$subject = $this->l->t('Changed by {user}');
$this->setIcon($event, 'change');
} elseif ($event->getSubject() === 'deleted_by') {
$subject = $this->l->t('Deleted by {user}');
$this->setIcon($event, 'delete-color');
} elseif ($event->getSubject() === 'restored_by') {
$subject = $this->l->t('Restored by {user}');
$this->setIcon($event, 'actions/history', 'core');
} elseif ($event->getSubject() === 'renamed_by') {
$subject = $this->l->t('Renamed by {user}');
$this->setIcon($event, 'change');
} elseif ($event->getSubject() === 'moved_by') {
$subject = $this->l->t('Moved by {user}');
$this->setIcon($event, 'change');
} else {
throw new \InvalidArgumentException();
}
if (!isset($parsedParameters['user'])) {
// External user via public link share
$subject = str_replace('{user}', $this->activityLang->t('"remote user"'), $subject);
}
$this->setSubjects($event, $subject, $parsedParameters);
return $this->eventMerger->mergeEvents('user', $event, $previousEvent);
}
/**
* @param IEvent $event
* @param IEvent|null $previousEvent
* @return IEvent
* @throws \InvalidArgumentException
* @since 11.0.0
*/
public function parseLongVersion(IEvent $event, IEvent $previousEvent = null) {
$this->fileIsEncrypted = false;
$parsedParameters = $this->getParameters($event);
if ($event->getSubject() === 'created_self') {
$subject = $this->l->t('You created {file}');
if ($this->fileIsEncrypted) {
$subject = $this->l->t('You created an encrypted file in {file}');
}
$this->setIcon($event, 'add-color');
} elseif ($event->getSubject() === 'created_by') {
$subject = $this->l->t('{user} created {file}');
if ($this->fileIsEncrypted) {
$subject = $this->l->t('{user} created an encrypted file in {file}');
}
$this->setIcon($event, 'add-color');
} elseif ($event->getSubject() === 'created_public') {
$subject = $this->l->t('{file} was created in a public folder');
$this->setIcon($event, 'add-color');
} elseif ($event->getSubject() === 'changed_self') {
$subject = $this->l->t('You changed {file}');
if ($this->fileIsEncrypted) {
$subject = $this->l->t('You changed an encrypted file in {file}');
}
$this->setIcon($event, 'change');
} elseif ($event->getSubject() === 'changed_by') {
$subject = $this->l->t('{user} changed {file}');
if ($this->fileIsEncrypted) {
$subject = $this->l->t('{user} changed an encrypted file in {file}');
}
$this->setIcon($event, 'change');
} elseif ($event->getSubject() === 'deleted_self') {
$subject = $this->l->t('You deleted {file}');
if ($this->fileIsEncrypted) {
$subject = $this->l->t('You deleted an encrypted file in {file}');
}
$this->setIcon($event, 'delete-color');
} elseif ($event->getSubject() === 'deleted_by') {
$subject = $this->l->t('{user} deleted {file}');
if ($this->fileIsEncrypted) {
$subject = $this->l->t('{user} deleted an encrypted file in {file}');
}
$this->setIcon($event, 'delete-color');
} elseif ($event->getSubject() === 'restored_self') {
$subject = $this->l->t('You restored {file}');
$this->setIcon($event, 'actions/history', 'core');
} elseif ($event->getSubject() === 'restored_by') {
$subject = $this->l->t('{user} restored {file}');
$this->setIcon($event, 'actions/history', 'core');
} elseif ($event->getSubject() === 'renamed_self') {
$oldFileName = $parsedParameters['oldfile']['name'];
$newFileName = $parsedParameters['newfile']['name'];
if ($this->isHiddenFile($oldFileName)) {
if ($this->isHiddenFile($newFileName)) {
$subject = $this->l->t('You renamed {oldfile} (hidden) to {newfile} (hidden)');
} else {
$subject = $this->l->t('You renamed {oldfile} (hidden) to {newfile}');
}
} else {
if ($this->isHiddenFile($newFileName)) {
$subject = $this->l->t('You renamed {oldfile} to {newfile} (hidden)');
} else {
$subject = $this->l->t('You renamed {oldfile} to {newfile}');
}
}
$this->setIcon($event, 'change');
} elseif ($event->getSubject() === 'renamed_by') {
$oldFileName = $parsedParameters['oldfile']['name'];
$newFileName = $parsedParameters['newfile']['name'];
if ($this->isHiddenFile($oldFileName)) {
if ($this->isHiddenFile($newFileName)) {
$subject = $this->l->t('{user} renamed {oldfile} (hidden) to {newfile} (hidden)');
} else {
$subject = $this->l->t('{user} renamed {oldfile} (hidden) to {newfile}');
}
} else {
if ($this->isHiddenFile($newFileName)) {
$subject = $this->l->t('{user} renamed {oldfile} to {newfile} (hidden)');
} else {
$subject = $this->l->t('{user} renamed {oldfile} to {newfile}');
}
}
$this->setIcon($event, 'change');
} elseif ($event->getSubject() === 'moved_self') {
$subject = $this->l->t('You moved {oldfile} to {newfile}');
$this->setIcon($event, 'change');
} elseif ($event->getSubject() === 'moved_by') {
$subject = $this->l->t('{user} moved {oldfile} to {newfile}');
$this->setIcon($event, 'change');
} else {
throw new \InvalidArgumentException();
}
if ($this->fileIsEncrypted) {
$event->setSubject($event->getSubject() . '_enc', $event->getSubjectParameters());
}
if (!isset($parsedParameters['user'])) {
// External user via public link share
$subject = str_replace('{user}', $this->activityLang->t('"remote user"'), $subject);
}
$this->setSubjects($event, $subject, $parsedParameters);
if ($event->getSubject() === 'moved_self' || $event->getSubject() === 'moved_by') {
$event = $this->eventMerger->mergeEvents('oldfile', $event, $previousEvent);
} else {
$event = $this->eventMerger->mergeEvents('file', $event, $previousEvent);
}
if ($event->getChildEvent() === null) {
// Couldn't group by file, maybe we can group by user
$event = $this->eventMerger->mergeEvents('user', $event, $previousEvent);
}
return $event;
}
private function isHiddenFile(string $filename): bool {
return strlen($filename) > 0 && $filename[0] === '.';
}
protected function setSubjects(IEvent $event, string $subject, array $parameters): void {
$event->setRichSubject($subject, $parameters);
}
/**
* @param IEvent $event
* @return array
* @throws \InvalidArgumentException
*/
protected function getParameters(IEvent $event) {
$parameters = $event->getSubjectParameters();
switch ($event->getSubject()) {
case 'created_self':
case 'created_public':
case 'changed_self':
case 'deleted_self':
case 'restored_self':
return [
'file' => $this->getFile($parameters[0], $event),
];
case 'created_by':
case 'changed_by':
case 'deleted_by':
case 'restored_by':
if ($parameters[1] === '') {
// External user via public link share
return [
'file' => $this->getFile($parameters[0], $event),
];
}
return [
'file' => $this->getFile($parameters[0], $event),
'user' => $this->getUser($parameters[1]),
];
case 'renamed_self':
case 'moved_self':
return [
'newfile' => $this->getFile($parameters[0]),
'oldfile' => $this->getFile($parameters[1]),
];
case 'renamed_by':
case 'moved_by':
if ($parameters[1] === '') {
// External user via public link share
return [
'newfile' => $this->getFile($parameters[0]),
'oldfile' => $this->getFile($parameters[2]),
];
}
return [
'newfile' => $this->getFile($parameters[0]),
'user' => $this->getUser($parameters[1]),
'oldfile' => $this->getFile($parameters[2]),
];
}
return [];
}
/**
* @param array|string $parameter
* @param IEvent|null $event
* @return array
* @throws \InvalidArgumentException
*/
protected function getFile($parameter, IEvent $event = null) {
if (is_array($parameter)) {
$path = reset($parameter);
$id = (string) key($parameter);
} elseif ($event !== null) {
// Legacy from before ownCloud 8.2
$path = $parameter;
$id = $event->getObjectId();
} else {
throw new \InvalidArgumentException('Could not generate file parameter');
}
$encryptionContainer = $this->getEndToEndEncryptionContainer($id, $path);
if ($encryptionContainer instanceof Folder) {
$this->fileIsEncrypted = true;
try {
$fullPath = rtrim($encryptionContainer->getPath(), '/');
// Remove /user/files/...
[,,, $path] = explode('/', $fullPath, 4);
if (!$path) {
throw new InvalidPathException('Path could not be split correctly');
}
return [
'type' => 'file',
'id' => $encryptionContainer->getId(),
'name' => $encryptionContainer->getName(),
'path' => $path,
'link' => $this->url->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $encryptionContainer->getId()]),
];
} catch (\Exception $e) {
// fall back to the normal one
$this->fileIsEncrypted = false;
}
}
return [
'type' => 'file',
'id' => $id,
'name' => basename($path),
'path' => trim($path, '/'),
'link' => $this->url->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $id]),
];
}
protected $fileEncrypted = [];
/**
* Check if a file is end2end encrypted
* @param int $fileId
* @param string $path
* @return Folder|null
*/
protected function getEndToEndEncryptionContainer($fileId, $path) {
if (isset($this->fileEncrypted[$fileId])) {
return $this->fileEncrypted[$fileId];
}
$fileName = basename($path);
if (!preg_match('/^[0-9a-fA-F]{32}$/', $fileName)) {
$this->fileEncrypted[$fileId] = false;
return $this->fileEncrypted[$fileId];
}
$userFolder = $this->rootFolder->getUserFolder($this->activityManager->getCurrentUserId());
$files = $userFolder->getById($fileId);
if (empty($files)) {
try {
// Deleted, try with parent
$file = $this->findExistingParent($userFolder, dirname($path));
} catch (NotFoundException $e) {
return null;
}
if (!$file instanceof Folder || !$file->isEncrypted()) {
return null;
}
$this->fileEncrypted[$fileId] = $file;
return $file;
}
$file = array_shift($files);
if ($file instanceof Folder && $file->isEncrypted()) {
// If the folder is encrypted, it is the Container,
// but can be the name is just fine.
$this->fileEncrypted[$fileId] = true;
return null;
}
$this->fileEncrypted[$fileId] = $this->getParentEndToEndEncryptionContainer($userFolder, $file);
return $this->fileEncrypted[$fileId];
}
/**
* @param Folder $userFolder
* @param string $path
* @return Folder
* @throws NotFoundException
*/
protected function findExistingParent(Folder $userFolder, $path) {
if ($path === '/') {
throw new NotFoundException('Reached the root');
}
try {
$folder = $userFolder->get(dirname($path));
} catch (NotFoundException $e) {
return $this->findExistingParent($userFolder, dirname($path));
}
return $folder;
}
/**
* Check all parents until the user's root folder if one is encrypted
*
* @param Folder $userFolder
* @param Node $file
* @return Node|null
*/
protected function getParentEndToEndEncryptionContainer(Folder $userFolder, Node $file) {
try {
$parent = $file->getParent();
if ($userFolder->getId() === $parent->getId()) {
return null;
}
} catch (\Exception $e) {
return null;
}
if ($parent->isEncrypted()) {
return $parent;
}
return $this->getParentEndToEndEncryptionContainer($userFolder, $parent);
}
/**
* @param string $uid
* @return array
*/
protected function getUser($uid) {
// First try local user
$displayName = $this->userManager->getDisplayName($uid);
if ($displayName !== null) {
return [
'type' => 'user',
'id' => $uid,
'name' => $displayName,
];
}
// Then a contact from the addressbook
if ($this->cloudIdManager->isValidCloudId($uid)) {
$cloudId = $this->cloudIdManager->resolveCloudId($uid);
return [
'type' => 'user',
'id' => $cloudId->getUser(),
'name' => $this->getDisplayNameFromAddressBook($cloudId->getDisplayId()),
'server' => $cloudId->getRemote(),
];
}
// Fallback to empty dummy data
return [
'type' => 'user',
'id' => $uid,
'name' => $uid,
];
}
protected function getDisplayNameFromAddressBook(string $search): string {
if (isset($this->displayNames[$search])) {
return $this->displayNames[$search];
}
$addressBookContacts = $this->contactsManager->search($search, ['CLOUD'], [
'limit' => 1,
'enumeration' => false,
'fullmatch' => false,
'strict_search' => true,
]);
foreach ($addressBookContacts as $contact) {
if (isset($contact['isLocalSystemBook'])) {
continue;
}
if (isset($contact['CLOUD'])) {
$cloudIds = $contact['CLOUD'];
if (is_string($cloudIds)) {
$cloudIds = [$cloudIds];
}
$lowerSearch = strtolower($search);
foreach ($cloudIds as $cloudId) {
if (strtolower($cloudId) === $lowerSearch) {
$this->displayNames[$search] = $contact['FN'] . " ($cloudId)";
return $this->displayNames[$search];
}
}
}
}
return $search;
}
}
@@ -0,0 +1,92 @@
<?php
/**
* @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
* @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\Activity\Settings;
class FavoriteAction extends FileActivitySettings {
/**
* @return string Lowercase a-z and underscore only identifier
* @since 11.0.0
*/
public function getIdentifier() {
return 'favorite';
}
/**
* @return string A translated string
* @since 11.0.0
*/
public function getName() {
return $this->l->t('A file has been added to or removed from your <strong>favorites</strong>');
}
/**
* @return int whether the filter should be rather on the top or bottom of
* the admin section. The filters are arranged in ascending order of the
* priority values. It is required to return a value between 0 and 100.
* @since 11.0.0
*/
public function getPriority() {
return 5;
}
/**
* @return bool True when the option can be changed for the stream
* @since 11.0.0
*/
public function canChangeStream() {
return false;
}
/**
* @return bool True when the option can be changed for the stream
* @since 11.0.0
*/
public function isDefaultEnabledStream() {
return true;
}
/**
* @return bool True when the option can be changed for the mail
* @since 11.0.0
*/
public function canChangeMail() {
return false;
}
/**
* @return bool True when the option can be changed for the stream
* @since 11.0.0
*/
public function isDefaultEnabledMail() {
return false;
}
/**
* @return bool True when the option can be changed for the notification
* @since 20.0.0
*/
public function canChangeNotification() {
return false;
}
}
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020 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\Activity\Settings;
use OCP\Activity\ActivitySettings;
use OCP\IL10N;
abstract class FileActivitySettings extends ActivitySettings {
/** @var IL10N */
protected $l;
/**
* @param IL10N $l
*/
public function __construct(IL10N $l) {
$this->l = $l;
}
public function getGroupIdentifier() {
return 'files';
}
public function getGroupName() {
return $this->l->t('Files');
}
}
@@ -0,0 +1,68 @@
<?php
/**
* @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
* @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\Activity\Settings;
class FileChanged extends FileActivitySettings {
/**
* @return string Lowercase a-z and underscore only identifier
* @since 11.0.0
*/
public function getIdentifier() {
return 'file_changed';
}
/**
* @return string A translated string
* @since 11.0.0
*/
public function getName() {
return $this->l->t('A file or folder has been <strong>changed</strong>');
}
/**
* @return int whether the filter should be rather on the top or bottom of
* the admin section. The filters are arranged in ascending order of the
* priority values. It is required to return a value between 0 and 100.
* @since 11.0.0
*/
public function getPriority() {
return 2;
}
public function canChangeMail() {
return true;
}
public function isDefaultEnabledMail() {
return false;
}
public function canChangeNotification() {
return true;
}
public function isDefaultEnabledNotification() {
return false;
}
}
@@ -0,0 +1,92 @@
<?php
/**
* @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
* @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\Activity\Settings;
class FileFavoriteChanged extends FileActivitySettings {
/**
* @return string Lowercase a-z and underscore only identifier
* @since 11.0.0
*/
public function getIdentifier() {
return 'file_favorite_changed';
}
/**
* @return string A translated string
* @since 11.0.0
*/
public function getName() {
return $this->l->t('A favorite file or folder has been <strong>changed</strong>');
}
/**
* @return int whether the filter should be rather on the top or bottom of
* the admin section. The filters are arranged in ascending order of the
* priority values. It is required to return a value between 0 and 100.
* @since 11.0.0
*/
public function getPriority() {
return 1;
}
/**
* @return bool True when the option can be changed for the stream
* @since 11.0.0
*/
public function canChangeStream() {
return true;
}
/**
* @return bool True when the option can be changed for the stream
* @since 11.0.0
*/
public function isDefaultEnabledStream() {
return true;
}
/**
* @return bool True when the option can be changed for the mail
* @since 11.0.0
*/
public function canChangeMail() {
return false;
}
public function canChangeNotification() {
return false;
}
/**
* @return bool True when the option can be changed for the stream
* @since 11.0.0
*/
public function isDefaultEnabledMail() {
return false;
}
public function isDefaultEnabledNotification() {
return false;
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christopher Schäpers <kondou@ts.unde.re>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Vincent Petry <vincent@nextcloud.com>
* @author Carl Schwan <carl@carlschwan.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;
use OC\NavigationManager;
use OCP\App\IAppManager;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\INavigationManager;
use OCP\IURLGenerator;
use OCP\IUserSession;
use OCP\L10N\IFactory;
use OCP\Server;
class App {
private static ?INavigationManager $navigationManager = null;
/**
* Returns the app's navigation manager
*/
public static function getNavigationManager(): INavigationManager {
// TODO: move this into a service in the Application class
if (self::$navigationManager === null) {
self::$navigationManager = new NavigationManager(
Server::get(IAppManager::class),
Server::get(IUrlGenerator::class),
Server::get(IFactory::class),
Server::get(IUserSession::class),
Server::get(IGroupManager::class),
Server::get(IConfig::class)
);
self::$navigationManager->clear(false);
}
return self::$navigationManager;
}
public static function extendJsConfig($settings): void {
$appConfig = json_decode($settings['array']['oc_appconfig'], true);
$maxChunkSize = (int)Server::get(IConfig::class)->getAppValue('files', 'max_chunk_size', (string)(10 * 1024 * 1024));
$appConfig['files'] = [
'max_chunk_size' => $maxChunkSize
];
$settings['array']['oc_appconfig'] = json_encode($appConfig);
}
}
@@ -0,0 +1,164 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Tobias Kaminsky <tobias@kaminsky.me>
* @author Vincent Petry <vincent@nextcloud.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\AppInfo;
use Closure;
use OC\Search\Provider\File;
use OCA\Files\Capabilities;
use OCA\Files\Collaboration\Resources\Listener;
use OCA\Files\Collaboration\Resources\ResourceProvider;
use OCA\Files\Controller\ApiController;
use OCA\Files\DirectEditingCapabilities;
use OCA\Files\Event\LoadSidebar;
use OCA\Files\Listener\LoadSidebarListener;
use OCA\Files\Listener\RenderReferenceEventListener;
use OCA\Files\Listener\SyncLivePhotosListener;
use OCA\Files\Notification\Notifier;
use OCA\Files\Search\FilesSearchProvider;
use OCA\Files\Service\TagService;
use OCA\Files\Service\UserConfig;
use OCA\Files\Service\ViewConfig;
use OCA\Files_Trashbin\Events\BeforeNodeRestoredEvent;
use OCP\Activity\IManager as IActivityManager;
use OCP\AppFramework\App;
use OCP\AppFramework\Bootstrap\IBootContext;
use OCP\AppFramework\Bootstrap\IBootstrap;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
use OCP\Collaboration\Reference\RenderReferenceEvent;
use OCP\Collaboration\Resources\IProviderManager;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\Cache\CacheEntryRemovedEvent;
use OCP\Files\Events\Node\BeforeNodeDeletedEvent;
use OCP\Files\Events\Node\BeforeNodeRenamedEvent;
use OCP\IConfig;
use OCP\IPreview;
use OCP\IRequest;
use OCP\ISearch;
use OCP\IServerContainer;
use OCP\ITagManager;
use OCP\IUserSession;
use OCP\Share\IManager as IShareManager;
use OCP\Util;
use Psr\Container\ContainerInterface;
class Application extends App implements IBootstrap {
public const APP_ID = 'files';
public function __construct(array $urlParams = []) {
parent::__construct(self::APP_ID, $urlParams);
}
public function register(IRegistrationContext $context): void {
/**
* Controllers
*/
$context->registerService('APIController', function (ContainerInterface $c) {
/** @var IServerContainer $server */
$server = $c->get(IServerContainer::class);
return new ApiController(
$c->get('AppName'),
$c->get(IRequest::class),
$c->get(IUserSession::class),
$c->get(TagService::class),
$c->get(IPreview::class),
$c->get(IShareManager::class),
$c->get(IConfig::class),
$server->getUserFolder(),
$c->get(UserConfig::class),
$c->get(ViewConfig::class),
);
});
/**
* Services
*/
$context->registerService(TagService::class, function (ContainerInterface $c) {
/** @var IServerContainer $server */
$server = $c->get(IServerContainer::class);
return new TagService(
$c->get(IUserSession::class),
$c->get(IActivityManager::class),
$c->get(ITagManager::class)->load(self::APP_ID),
$server->getUserFolder(),
$c->get(IEventDispatcher::class),
);
});
/*
* Register capabilities
*/
$context->registerCapability(Capabilities::class);
$context->registerCapability(DirectEditingCapabilities::class);
$context->registerEventListener(LoadSidebar::class, LoadSidebarListener::class);
$context->registerEventListener(RenderReferenceEvent::class, RenderReferenceEventListener::class);
$context->registerEventListener(BeforeNodeRenamedEvent::class, SyncLivePhotosListener::class);
$context->registerEventListener(BeforeNodeDeletedEvent::class, SyncLivePhotosListener::class);
$context->registerEventListener(BeforeNodeRestoredEvent::class, SyncLivePhotosListener::class);
$context->registerEventListener(CacheEntryRemovedEvent::class, SyncLivePhotosListener::class);
$context->registerSearchProvider(FilesSearchProvider::class);
$context->registerNotifierService(Notifier::class);
}
public function boot(IBootContext $context): void {
$context->injectFn(Closure::fromCallable([$this, 'registerCollaboration']));
$context->injectFn([Listener::class, 'register']);
$context->injectFn(Closure::fromCallable([$this, 'registerSearchProvider']));
$this->registerTemplates();
$this->registerHooks();
}
private function registerCollaboration(IProviderManager $providerManager): void {
$providerManager->registerResourceProvider(ResourceProvider::class);
}
private function registerSearchProvider(ISearch $search): void {
$search->registerProvider(File::class, ['apps' => ['files']]);
}
private function registerTemplates(): void {
$templateManager = \OC_Helper::getFileTemplateManager();
$templateManager->registerTemplate('application/vnd.oasis.opendocument.presentation', 'core/templates/filetemplates/template.odp');
$templateManager->registerTemplate('application/vnd.oasis.opendocument.text', 'core/templates/filetemplates/template.odt');
$templateManager->registerTemplate('application/vnd.oasis.opendocument.spreadsheet', 'core/templates/filetemplates/template.ods');
}
private function registerHooks(): void {
Util::connectHook('\OCP\Config', 'js', '\OCA\Files\App', 'extendJsConfig');
}
}
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016 Julius Härtl <jus@bitgrid.net>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Julius Härtl <jus@bitgrid.net>
*
* @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\BackgroundJob;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\TimedJob;
use OCP\DirectEditing\IManager;
class CleanupDirectEditingTokens extends TimedJob {
private const INTERVAL_MINUTES = 15 * 60;
private IManager $manager;
public function __construct(ITimeFactory $time,
IManager $manager) {
parent::__construct($time);
$this->interval = self::INTERVAL_MINUTES;
$this->manager = $manager;
}
/**
* Makes the background job do its work
*
* @param array $argument unused argument
* @throws \Exception
*/
public function run($argument) {
$this->manager->cleanup();
}
}
@@ -0,0 +1,62 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Max Kovalenko <mxss1998@yandex.ru>
* @author Morris Jobke <hey@morrisjobke.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\BackgroundJob;
use OC\Lock\DBLockingProvider;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\TimedJob;
/**
* Clean up all file locks that are expired for the DB file locking provider
*/
class CleanupFileLocks extends TimedJob {
/**
* Default interval in minutes
*
* @var int $defaultIntervalMin
**/
protected $defaultIntervalMin = 5;
/**
* sets the correct interval for this timed job
*/
public function __construct(ITimeFactory $time) {
parent::__construct($time);
$this->interval = $this->defaultIntervalMin * 60;
}
/**
* Makes the background job do its work
*
* @param array $argument unused argument
* @throws \Exception
*/
public function run($argument) {
$lockingProvider = \OC::$server->getLockingProvider();
if ($lockingProvider instanceof DBLockingProvider) {
$lockingProvider->cleanExpiredLocks();
}
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @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\BackgroundJob;
use OCA\Files\Db\OpenLocalEditorMapper;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJob;
use OCP\BackgroundJob\TimedJob;
/**
* Delete all expired "Open local editor" token
*/
class DeleteExpiredOpenLocalEditor extends TimedJob {
protected OpenLocalEditorMapper $mapper;
public function __construct(
ITimeFactory $time,
OpenLocalEditorMapper $mapper
) {
parent::__construct($time);
$this->mapper = $mapper;
// Run every 12h
$this->interval = 12 * 3600;
$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
}
/**
* Makes the background job do its work
*
* @param array $argument unused argument
*/
public function run($argument): void {
$this->mapper->deleteExpiredTokens($this->time->getTime());
}
}
@@ -0,0 +1,146 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Vincent Petry <vincent@nextcloud.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\BackgroundJob;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\TimedJob;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
use Psr\Log\LoggerInterface;
/**
* Delete all share entries that have no matching entries in the file cache table.
*/
class DeleteOrphanedItems extends TimedJob {
public const CHUNK_SIZE = 200;
protected $defaultIntervalMin = 60;
/**
* sets the correct interval for this timed job
*/
public function __construct(
ITimeFactory $time,
protected IDBConnection $connection,
protected LoggerInterface $logger,
) {
parent::__construct($time);
$this->interval = $this->defaultIntervalMin * 60;
}
/**
* Makes the background job do its work
*
* @param array $argument unused argument
*/
public function run($argument) {
$this->cleanSystemTags();
$this->cleanUserTags();
$this->cleanComments();
$this->cleanCommentMarkers();
}
/**
* Deleting orphaned system tag mappings
*
* @param string $table
* @param string $idCol
* @param string $typeCol
* @return int Number of deleted entries
*/
protected function cleanUp($table, $idCol, $typeCol) {
$deletedEntries = 0;
$query = $this->connection->getQueryBuilder();
$query->select('t1.' . $idCol)
->from($table, 't1')
->where($query->expr()->eq($typeCol, $query->expr()->literal('files')))
->andWhere($query->expr()->isNull('t2.fileid'))
->leftJoin('t1', 'filecache', 't2', $query->expr()->eq($query->expr()->castColumn('t1.' . $idCol, IQueryBuilder::PARAM_INT), 't2.fileid'))
->groupBy('t1.' . $idCol)
->setMaxResults(self::CHUNK_SIZE);
$deleteQuery = $this->connection->getQueryBuilder();
$deleteQuery->delete($table)
->where($deleteQuery->expr()->eq($idCol, $deleteQuery->createParameter('objectid')));
$deletedInLastChunk = self::CHUNK_SIZE;
while ($deletedInLastChunk === self::CHUNK_SIZE) {
$result = $query->execute();
$deletedInLastChunk = 0;
while ($row = $result->fetch()) {
$deletedInLastChunk++;
$deletedEntries += $deleteQuery->setParameter('objectid', (int) $row[$idCol])
->execute();
}
$result->closeCursor();
}
return $deletedEntries;
}
/**
* Deleting orphaned system tag mappings
*
* @return int Number of deleted entries
*/
protected function cleanSystemTags() {
$deletedEntries = $this->cleanUp('systemtag_object_mapping', 'objectid', 'objecttype');
$this->logger->debug("$deletedEntries orphaned system tag relations deleted", ['app' => 'DeleteOrphanedItems']);
return $deletedEntries;
}
/**
* Deleting orphaned user tag mappings
*
* @return int Number of deleted entries
*/
protected function cleanUserTags() {
$deletedEntries = $this->cleanUp('vcategory_to_object', 'objid', 'type');
$this->logger->debug("$deletedEntries orphaned user tag relations deleted", ['app' => 'DeleteOrphanedItems']);
return $deletedEntries;
}
/**
* Deleting orphaned comments
*
* @return int Number of deleted entries
*/
protected function cleanComments() {
$deletedEntries = $this->cleanUp('comments', 'object_id', 'object_type');
$this->logger->debug("$deletedEntries orphaned comments deleted", ['app' => 'DeleteOrphanedItems']);
return $deletedEntries;
}
/**
* Deleting orphaned comment read markers
*
* @return int Number of deleted entries
*/
protected function cleanCommentMarkers() {
$deletedEntries = $this->cleanUp('comments_read_markers', 'object_id', 'object_type');
$this->logger->debug("$deletedEntries orphaned comment read marks deleted", ['app' => 'DeleteOrphanedItems']);
return $deletedEntries;
}
}
@@ -0,0 +1,123 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Lukas Reschke <lukas@statuscode.ch>
* @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\BackgroundJob;
use OC\Files\Utils\Scanner;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\TimedJob;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IConfig;
use OCP\IDBConnection;
use Psr\Log\LoggerInterface;
/**
* Class ScanFiles is a background job used to run the file scanner over the user
* accounts to ensure integrity of the file cache.
*
* @package OCA\Files\BackgroundJob
*/
class ScanFiles extends TimedJob {
private IConfig $config;
private IEventDispatcher $dispatcher;
private LoggerInterface $logger;
private IDBConnection $connection;
/** Amount of users that should get scanned per execution */
public const USERS_PER_SESSION = 500;
public function __construct(
IConfig $config,
IEventDispatcher $dispatcher,
LoggerInterface $logger,
IDBConnection $connection,
ITimeFactory $time
) {
parent::__construct($time);
// Run once per 10 minutes
$this->setInterval(60 * 10);
$this->config = $config;
$this->dispatcher = $dispatcher;
$this->logger = $logger;
$this->connection = $connection;
}
protected function runScanner(string $user): void {
try {
$scanner = new Scanner(
$user,
null,
$this->dispatcher,
$this->logger
);
$scanner->backgroundScan('');
} catch (\Exception $e) {
$this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'files']);
}
\OC_Util::tearDownFS();
}
/**
* Find a storage which have unindexed files and return a user with access to the storage
*
* @return string|false
*/
private function getUserToScan() {
$query = $this->connection->getQueryBuilder();
$query->select('user_id')
->from('filecache', 'f')
->innerJoin('f', 'mounts', 'm', $query->expr()->eq('storage_id', 'storage'))
->where($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)))
->andWhere($query->expr()->gt('parent', $query->createNamedParameter(-1, IQueryBuilder::PARAM_INT)))
->setMaxResults(1);
return $query->executeQuery()->fetchOne();
}
/**
* @param $argument
* @throws \Exception
*/
protected function run($argument) {
if ($this->config->getSystemValueBool('files_no_background_scan', false)) {
return;
}
$usersScanned = 0;
$lastUser = '';
$user = $this->getUserToScan();
while ($user && $usersScanned < self::USERS_PER_SESSION && $lastUser !== $user) {
$this->runScanner($user);
$lastUser = $user;
$user = $this->getUserToScan();
$usersScanned += 1;
}
if ($lastUser === $user) {
$this->logger->warning("User $user still has unscanned files after running background scan, background scan might be stopped prematurely");
}
}
}
@@ -0,0 +1,162 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.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\BackgroundJob;
use OCA\Files\AppInfo\Application;
use OCA\Files\Db\TransferOwnership as Transfer;
use OCA\Files\Db\TransferOwnershipMapper;
use OCA\Files\Exception\TransferOwnershipException;
use OCA\Files\Service\OwnershipTransferService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\QueuedJob;
use OCP\Files\IRootFolder;
use OCP\IUser;
use OCP\IUserManager;
use OCP\Notification\IManager as NotificationManager;
use Psr\Log\LoggerInterface;
use function ltrim;
class TransferOwnership extends QueuedJob {
public function __construct(
ITimeFactory $timeFactory,
private IUserManager $userManager,
private OwnershipTransferService $transferService,
private LoggerInterface $logger,
private NotificationManager $notificationManager,
private TransferOwnershipMapper $mapper,
private IRootFolder $rootFolder,
) {
parent::__construct($timeFactory);
}
protected function run($argument) {
$id = $argument['id'];
$transfer = $this->mapper->getById($id);
$sourceUser = $transfer->getSourceUser();
$destinationUser = $transfer->getTargetUser();
$fileId = $transfer->getFileId();
$userFolder = $this->rootFolder->getUserFolder($sourceUser);
$nodes = $userFolder->getById($fileId);
if (empty($nodes)) {
$this->logger->alert('Could not transfer ownership: Node not found');
$this->failedNotication($transfer);
return;
}
$path = $userFolder->getRelativePath($nodes[0]->getPath());
$sourceUserObject = $this->userManager->get($sourceUser);
$destinationUserObject = $this->userManager->get($destinationUser);
if (!$sourceUserObject instanceof IUser) {
$this->logger->alert('Could not transfer ownership: Unknown source user ' . $sourceUser);
$this->failedNotication($transfer);
return;
}
if (!$destinationUserObject instanceof IUser) {
$this->logger->alert("Unknown destination user $destinationUser");
$this->failedNotication($transfer);
return;
}
try {
$this->transferService->transfer(
$sourceUserObject,
$destinationUserObject,
ltrim($path, '/')
);
$this->successNotification($transfer);
} catch (TransferOwnershipException $e) {
$this->logger->error(
$e->getMessage(),
[
'exception' => $e,
],
);
$this->failedNotication($transfer);
}
$this->mapper->delete($transfer);
}
private function failedNotication(Transfer $transfer): void {
// Send notification to source user
$notification = $this->notificationManager->createNotification();
$notification->setUser($transfer->getSourceUser())
->setApp(Application::APP_ID)
->setDateTime($this->time->getDateTime())
->setSubject('transferOwnershipFailedSource', [
'sourceUser' => $transfer->getSourceUser(),
'targetUser' => $transfer->getTargetUser(),
'nodeName' => $transfer->getNodeName(),
])
->setObject('transfer', (string)$transfer->getId());
$this->notificationManager->notify($notification);
// Send notification to source user
$notification = $this->notificationManager->createNotification();
$notification->setUser($transfer->getTargetUser())
->setApp(Application::APP_ID)
->setDateTime($this->time->getDateTime())
->setSubject('transferOwnershipFailedTarget', [
'sourceUser' => $transfer->getSourceUser(),
'targetUser' => $transfer->getTargetUser(),
'nodeName' => $transfer->getNodeName(),
])
->setObject('transfer', (string)$transfer->getId());
$this->notificationManager->notify($notification);
}
private function successNotification(Transfer $transfer): void {
// Send notification to source user
$notification = $this->notificationManager->createNotification();
$notification->setUser($transfer->getSourceUser())
->setApp(Application::APP_ID)
->setDateTime($this->time->getDateTime())
->setSubject('transferOwnershipDoneSource', [
'sourceUser' => $transfer->getSourceUser(),
'targetUser' => $transfer->getTargetUser(),
'nodeName' => $transfer->getNodeName(),
])
->setObject('transfer', (string)$transfer->getId());
$this->notificationManager->notify($notification);
// Send notification to source user
$notification = $this->notificationManager->createNotification();
$notification->setUser($transfer->getTargetUser())
->setApp(Application::APP_ID)
->setDateTime($this->time->getDateTime())
->setSubject('transferOwnershipDoneTarget', [
'sourceUser' => $transfer->getSourceUser(),
'targetUser' => $transfer->getTargetUser(),
'nodeName' => $transfer->getNodeName(),
])
->setObject('transfer', (string)$transfer->getId());
$this->notificationManager->notify($notification);
}
}
@@ -0,0 +1,52 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christopher Schäpers <kondou@ts.unde.re>
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Härtl <jus@bitgrid.net>
* @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;
use OCP\Capabilities\ICapability;
use OCP\IConfig;
class Capabilities implements ICapability {
protected IConfig $config;
public function __construct(IConfig $config) {
$this->config = $config;
}
/**
* Return this classes capabilities
*
* @return array{files: array{bigfilechunking: bool, blacklisted_files: array<mixed>}}
*/
public function getCapabilities() {
return [
'files' => [
'bigfilechunking' => true,
'blacklisted_files' => (array)$this->config->getSystemValue('blacklisted_files', ['.htaccess'])
],
];
}
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @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\Collaboration\Resources;
use OCP\Collaboration\Resources\IManager;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Server;
use OCP\Share\Events\ShareCreatedEvent;
use OCP\Share\Events\ShareDeletedEvent;
use OCP\Share\Events\ShareDeletedFromSelfEvent;
class Listener {
public static function register(IEventDispatcher $dispatcher): void {
$dispatcher->addListener(ShareCreatedEvent::class, [self::class, 'shareModification']);
$dispatcher->addListener(ShareDeletedEvent::class, [self::class, 'shareModification']);
$dispatcher->addListener(ShareDeletedFromSelfEvent::class, [self::class, 'shareModification']);
}
public static function shareModification(): void {
/** @var IManager $resourceManager */
$resourceManager = Server::get(IManager::class);
/** @var ResourceProvider $resourceProvider */
$resourceProvider = Server::get(ResourceProvider::class);
$resourceManager->invalidateAccessCacheForProvider($resourceProvider);
}
}
@@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Härtl <jus@bitgrid.net>
*
* @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\Collaboration\Resources;
use OCP\Collaboration\Resources\IProvider;
use OCP\Collaboration\Resources\IResource;
use OCP\Collaboration\Resources\ResourceException;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\IPreview;
use OCP\IURLGenerator;
use OCP\IUser;
class ResourceProvider implements IProvider {
public const RESOURCE_TYPE = 'file';
/** @var IRootFolder */
protected $rootFolder;
/** @var IPreview */
private $preview;
/** @var IURLGenerator */
private $urlGenerator;
/** @var array */
protected $nodes = [];
public function __construct(IRootFolder $rootFolder,
IPreview $preview,
IURLGenerator $urlGenerator) {
$this->rootFolder = $rootFolder;
$this->preview = $preview;
$this->urlGenerator = $urlGenerator;
}
private function getNode(IResource $resource): ?Node {
if (isset($this->nodes[(int) $resource->getId()])) {
return $this->nodes[(int) $resource->getId()];
}
$nodes = $this->rootFolder->getById((int) $resource->getId());
if (!empty($nodes)) {
$this->nodes[(int) $resource->getId()] = array_shift($nodes);
return $this->nodes[(int) $resource->getId()];
}
return null;
}
/**
* @param IResource $resource
* @return array
* @since 16.0.0
*/
public function getResourceRichObject(IResource $resource): array {
if (isset($this->nodes[(int) $resource->getId()])) {
$node = $this->nodes[(int) $resource->getId()]->getPath();
} else {
$node = $this->getNode($resource);
}
if ($node instanceof Node) {
$link = $this->urlGenerator->linkToRouteAbsolute(
'files.viewcontroller.showFile',
['fileid' => $resource->getId()]
);
return [
'type' => 'file',
'id' => $resource->getId(),
'name' => $node->getName(),
'path' => $node->getInternalPath(),
'link' => $link,
'mimetype' => $node->getMimetype(),
'preview-available' => $this->preview->isAvailable($node),
];
}
throw new ResourceException('File not found');
}
/**
* Can a user/guest access the collection
*
* @param IResource $resource
* @param IUser $user
* @return bool
* @since 16.0.0
*/
public function canAccessResource(IResource $resource, IUser $user = null): bool {
if (!$user instanceof IUser) {
return false;
}
$userFolder = $this->rootFolder->getUserFolder($user->getUID());
$nodes = $userFolder->getById((int) $resource->getId());
if (!empty($nodes)) {
$this->nodes[(int) $resource->getId()] = array_shift($nodes);
return true;
}
return false;
}
/**
* Get the resource type of the provider
*
* @return string
* @since 16.0.0
*/
public function getType(): string {
return self::RESOURCE_TYPE;
}
}
@@ -0,0 +1,132 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 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\Command;
use OC\Core\Command\Info\FileUtils;
use OCP\Files\Folder;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
class Copy extends Command {
private FileUtils $fileUtils;
public function __construct(FileUtils $fileUtils) {
$this->fileUtils = $fileUtils;
parent::__construct();
}
protected function configure(): void {
$this
->setName('files:copy')
->setDescription('Copy a file or folder')
->addArgument('source', InputArgument::REQUIRED, "Source file id or path")
->addArgument('target', InputArgument::REQUIRED, "Target path")
->addOption('force', 'f', InputOption::VALUE_NONE, "Don't ask for confirmation and don't output any warnings")
->addOption('no-target-directory', 'T', InputOption::VALUE_NONE, "When target path is folder, overwrite the folder instead of copying into the folder");
}
public function execute(InputInterface $input, OutputInterface $output): int {
$sourceInput = $input->getArgument('source');
$targetInput = $input->getArgument('target');
$force = $input->getOption('force');
$noTargetDir = $input->getOption('no-target-directory');
$node = $this->fileUtils->getNode($sourceInput);
$targetNode = $this->fileUtils->getNode($targetInput);
if (!$node) {
$output->writeln("<error>file $sourceInput not found</error>");
return 1;
}
$targetParentPath = dirname(rtrim($targetInput, '/'));
$targetParent = $this->fileUtils->getNode($targetParentPath);
if (!$targetParent) {
$output->writeln("<error>Target parent path $targetParentPath doesn't exist</error>");
return 1;
}
$wouldRequireDelete = false;
if ($targetNode) {
if (!$targetNode->isUpdateable()) {
$output->writeln("<error>$targetInput isn't writable</error>");
return 1;
}
if ($targetNode instanceof Folder) {
if ($noTargetDir) {
if (!$force) {
$output->writeln("Warning: <info>$sourceInput</info> is a file, but <info>$targetInput</info> is a folder");
}
$wouldRequireDelete = true;
} else {
$targetInput = $targetNode->getFullPath($node->getName());
$targetNode = $this->fileUtils->getNode($targetInput);
}
} else {
if ($node instanceof Folder) {
if (!$force) {
$output->writeln("Warning: <info>$sourceInput</info> is a folder, but <info>$targetInput</info> is a file");
}
$wouldRequireDelete = true;
}
}
if ($wouldRequireDelete && $targetNode->getInternalPath() === '') {
$output->writeln("<error>Mount root can't be overwritten with a different type</error>");
return 1;
}
if ($wouldRequireDelete && !$targetNode->isDeletable()) {
$output->writeln("<error>$targetInput can't be deleted to be replaced with $sourceInput</error>");
return 1;
}
if (!$force && $targetNode) {
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
$question = new ConfirmationQuestion("<info>" . $targetInput . "</info> already exists, overwrite? [y/N] ", false);
if (!$helper->ask($input, $output, $question)) {
return 1;
}
}
}
if ($wouldRequireDelete && $targetNode) {
$targetNode->delete();
}
$node->copy($targetInput);
return 0;
}
}
@@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 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\Command;
use OC\Core\Command\Info\FileUtils;
use OCA\Files_Sharing\SharedStorage;
use OCP\Files\Folder;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
class Delete extends Command {
public function __construct(
private FileUtils $fileUtils,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('files:delete')
->setDescription('Delete a file or folder')
->addArgument('file', InputArgument::REQUIRED, "File id or path")
->addOption('force', 'f', InputOption::VALUE_NONE, "Don't ask for configuration and don't output any warnings");
}
public function execute(InputInterface $input, OutputInterface $output): int {
$fileInput = $input->getArgument('file');
$inputIsId = is_numeric($fileInput);
$force = $input->getOption('force');
$node = $this->fileUtils->getNode($fileInput);
if (!$node) {
$output->writeln("<error>file $fileInput not found</error>");
return self::FAILURE;
}
$deleteConfirmed = $force;
if (!$deleteConfirmed) {
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
$storage = $node->getStorage();
if (!$inputIsId && $storage->instanceOfStorage(SharedStorage::class) && $node->getInternalPath() === '') {
/** @var SharedStorage $storage */
[,$user] = explode('/', $fileInput, 3);
$question = new ConfirmationQuestion("<info>$fileInput</info> in a shared file, do you want to unshare the file from <info>$user</info> instead of deleting the source file? [Y/n] ", true);
if ($helper->ask($input, $output, $question)) {
$storage->unshareStorage();
return self::SUCCESS;
} else {
$node = $storage->getShare()->getNode();
$output->writeln("");
}
}
$filesByUsers = $this->fileUtils->getFilesByUser($node);
if (count($filesByUsers) > 1) {
$output->writeln("Warning: the provided file is accessible by more than one user");
$output->writeln(" all of the following users will lose access to the file when deleted:");
$output->writeln("");
foreach ($filesByUsers as $user => $filesByUser) {
$output->writeln($user . ":");
foreach($filesByUser as $file) {
$output->writeln(" - " . $file->getPath());
}
}
$output->writeln("");
}
if ($node instanceof Folder) {
$maybeContents = " and all it's contents";
} else {
$maybeContents = "";
}
$question = new ConfirmationQuestion("Delete " . $node->getPath() . $maybeContents . "? [y/N] ", false);
$deleteConfirmed = $helper->ask($input, $output, $question);
}
if ($deleteConfirmed) {
if ($node->isDeletable()) {
$node->delete();
} else {
$output->writeln("<error>File cannot be deleted, insufficient permissions.</error>");
}
}
return self::SUCCESS;
}
}
@@ -0,0 +1,112 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Morris Jobke <hey@morrisjobke.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\Command;
use OCP\IDBConnection;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Delete all file entries that have no matching entries in the storage table.
*/
class DeleteOrphanedFiles extends Command {
public const CHUNK_SIZE = 200;
public function __construct(
protected IDBConnection $connection,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('files:cleanup')
->setDescription('cleanup filecache');
}
public function execute(InputInterface $input, OutputInterface $output): int {
$deletedEntries = 0;
$query = $this->connection->getQueryBuilder();
$query->select('fc.fileid')
->from('filecache', 'fc')
->where($query->expr()->isNull('s.numeric_id'))
->leftJoin('fc', 'storages', 's', $query->expr()->eq('fc.storage', 's.numeric_id'))
->setMaxResults(self::CHUNK_SIZE);
$deleteQuery = $this->connection->getQueryBuilder();
$deleteQuery->delete('filecache')
->where($deleteQuery->expr()->eq('fileid', $deleteQuery->createParameter('objectid')));
$deletedInLastChunk = self::CHUNK_SIZE;
while ($deletedInLastChunk === self::CHUNK_SIZE) {
$deletedInLastChunk = 0;
$result = $query->execute();
while ($row = $result->fetch()) {
$deletedInLastChunk++;
$deletedEntries += $deleteQuery->setParameter('objectid', (int) $row['fileid'])
->execute();
}
$result->closeCursor();
}
$output->writeln("$deletedEntries orphaned file cache entries deleted");
$deletedMounts = $this->cleanupOrphanedMounts();
$output->writeln("$deletedMounts orphaned mount entries deleted");
return self::SUCCESS;
}
private function cleanupOrphanedMounts(): int {
$deletedEntries = 0;
$query = $this->connection->getQueryBuilder();
$query->select('m.storage_id')
->from('mounts', 'm')
->where($query->expr()->isNull('s.numeric_id'))
->leftJoin('m', 'storages', 's', $query->expr()->eq('m.storage_id', 's.numeric_id'))
->groupBy('storage_id')
->setMaxResults(self::CHUNK_SIZE);
$deleteQuery = $this->connection->getQueryBuilder();
$deleteQuery->delete('mounts')
->where($deleteQuery->expr()->eq('storage_id', $deleteQuery->createParameter('storageid')));
$deletedInLastChunk = self::CHUNK_SIZE;
while ($deletedInLastChunk === self::CHUNK_SIZE) {
$deletedInLastChunk = 0;
$result = $query->execute();
while ($row = $result->fetch()) {
$deletedInLastChunk++;
$deletedEntries += $deleteQuery->setParameter('storageid', (int) $row['storage_id'])
->execute();
}
$result->closeCursor();
}
return $deletedEntries;
}
}
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 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\Command;
use OC\Core\Command\Info\FileUtils;
use OCP\Files\File;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Get extends Command {
public function __construct(
private FileUtils $fileUtils,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('files:get')
->setDescription('Get the contents of a file')
->addArgument('file', InputArgument::REQUIRED, "Source file id or Nextcloud path")
->addArgument('output', InputArgument::OPTIONAL, "Target local file to output to, defaults to STDOUT");
}
public function execute(InputInterface $input, OutputInterface $output): int {
$fileInput = $input->getArgument('file');
$outputName = $input->getArgument('output');
$node = $this->fileUtils->getNode($fileInput);
if (!$node) {
$output->writeln("<error>file $fileInput not found</error>");
return self::FAILURE;
}
if (!($node instanceof File)) {
$output->writeln("<error>$fileInput is a directory</error>");
return self::FAILURE;
}
$isTTY = stream_isatty(STDOUT);
if ($outputName === null && $isTTY && $node->getMimePart() !== 'text') {
$output->writeln([
"<error>Warning: Binary output can mess up your terminal</error>",
" Use <info>occ files:get $fileInput -</info> to output it to the terminal anyway",
" Or <info>occ files:get $fileInput <FILE></info> to save to a file instead"
]);
return self::FAILURE;
}
$source = $node->fopen('r');
if (!$source) {
$output->writeln("<error>Failed to open $fileInput for reading</error>");
return self::FAILURE;
}
$target = ($outputName === null || $outputName === '-') ? STDOUT : fopen($outputName, 'w');
if (!$target) {
$output->writeln("<error>Failed to open $outputName for reading</error>");
return self::FAILURE;
}
stream_copy_to_stream($source, $target);
return self::SUCCESS;
}
}
@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 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\Command;
use OC\Core\Command\Info\FileUtils;
use OCP\Files\File;
use OCP\Files\Folder;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
class Move extends Command {
private FileUtils $fileUtils;
public function __construct(FileUtils $fileUtils) {
$this->fileUtils = $fileUtils;
parent::__construct();
}
protected function configure(): void {
$this
->setName('files:move')
->setDescription('Move a file or folder')
->addArgument('source', InputArgument::REQUIRED, "Source file id or path")
->addArgument('target', InputArgument::REQUIRED, "Target path")
->addOption('force', 'f', InputOption::VALUE_NONE, "Don't ask for configuration and don't output any warnings");
}
public function execute(InputInterface $input, OutputInterface $output): int {
$sourceInput = $input->getArgument('source');
$targetInput = $input->getArgument('target');
$force = $input->getOption('force');
$node = $this->fileUtils->getNode($sourceInput);
$targetNode = $this->fileUtils->getNode($targetInput);
if (!$node) {
$output->writeln("<error>file $sourceInput not found</error>");
return 1;
}
$targetParentPath = dirname(rtrim($targetInput, '/'));
$targetParent = $this->fileUtils->getNode($targetParentPath);
if (!$targetParent) {
$output->writeln("<error>Target parent path $targetParentPath doesn't exist</error>");
return 1;
}
$wouldRequireDelete = false;
if ($targetNode) {
if (!$targetNode->isUpdateable()) {
$output->writeln("<error>$targetInput already exists and isn't writable</error>");
return 1;
}
if ($node instanceof Folder && $targetNode instanceof File) {
$output->writeln("Warning: <info>$sourceInput</info> is a folder, but <info>$targetInput</info> is a file");
$wouldRequireDelete = true;
}
if ($node instanceof File && $targetNode instanceof Folder) {
$output->writeln("Warning: <info>$sourceInput</info> is a file, but <info>$targetInput</info> is a folder");
$wouldRequireDelete = true;
}
if ($wouldRequireDelete && $targetNode->getInternalPath() === '') {
$output->writeln("<error>Mount root can't be overwritten with a different type</error>");
return 1;
}
if ($wouldRequireDelete && !$targetNode->isDeletable()) {
$output->writeln("<error>$targetInput can't be deleted to be replaced with $sourceInput</error>");
return 1;
}
if (!$force) {
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
$question = new ConfirmationQuestion("<info>" . $targetInput . "</info> already exists, overwrite? [y/N] ", false);
if (!$helper->ask($input, $output, $question)) {
return 1;
}
}
}
if ($wouldRequireDelete && $targetNode) {
$targetNode->delete();
}
$node->move($targetInput);
return 0;
}
}
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 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\Command\Object;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
class Delete extends Command {
public function __construct(
private ObjectUtil $objectUtils,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('files:object:delete')
->setDescription('Delete an object from the object store')
->addArgument('object', InputArgument::REQUIRED, "Object to delete")
->addOption('bucket', 'b', InputOption::VALUE_REQUIRED, "Bucket to delete the object from, only required in cases where it can't be determined from the config");
}
public function execute(InputInterface $input, OutputInterface $output): int {
$object = $input->getArgument('object');
$objectStore = $this->objectUtils->getObjectStore($input->getOption("bucket"), $output);
if (!$objectStore) {
return -1;
}
if ($fileId = $this->objectUtils->objectExistsInDb($object)) {
$output->writeln("<error>Warning, object $object belongs to an existing file, deleting the object will lead to unexpected behavior if not replaced</error>");
$output->writeln(" Note: use <info>occ files:delete $fileId</info> to delete the file cleanly or <info>occ info:file $fileId</info> for more information about the file");
$output->writeln("");
}
if (!$objectStore->objectExists($object)) {
$output->writeln("<error>Object $object does not exist</error>");
return -1;
}
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
$question = new ConfirmationQuestion("Delete $object? [y/N] ", false);
if ($helper->ask($input, $output, $question)) {
$objectStore->deleteObject($object);
}
return self::SUCCESS;
}
}
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 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\Command\Object;
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 Get extends Command {
public function __construct(
private ObjectUtil $objectUtils,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('files:object:get')
->setDescription('Get the contents of an object')
->addArgument('object', InputArgument::REQUIRED, "Object to get")
->addArgument('output', InputArgument::REQUIRED, "Target local file to output to, use - for STDOUT")
->addOption('bucket', 'b', InputOption::VALUE_REQUIRED, "Bucket to get the object from, only required in cases where it can't be determined from the config");
}
public function execute(InputInterface $input, OutputInterface $output): int {
$object = $input->getArgument('object');
$outputName = $input->getArgument('output');
$objectStore = $this->objectUtils->getObjectStore($input->getOption("bucket"), $output);
if (!$objectStore) {
return self::FAILURE;
}
if (!$objectStore->objectExists($object)) {
$output->writeln("<error>Object $object does not exist</error>");
return self::FAILURE;
}
try {
$source = $objectStore->readObject($object);
} catch (\Exception $e) {
$msg = $e->getMessage();
$output->writeln("<error>Failed to read $object from object store: $msg</error>");
return self::FAILURE;
}
$target = $outputName === '-' ? STDOUT : fopen($outputName, 'w');
if (!$target) {
$output->writeln("<error>Failed to open $outputName for writing</error>");
return self::FAILURE;
}
stream_copy_to_stream($source, $target);
return self::SUCCESS;
}
}
@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 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\Command\Object;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\Files\ObjectStore\IObjectStore;
use OCP\IConfig;
use OCP\IDBConnection;
use Symfony\Component\Console\Output\OutputInterface;
class ObjectUtil {
public function __construct(
private IConfig $config,
private IDBConnection $connection,
) {
}
private function getObjectStoreConfig(): ?array {
$config = $this->config->getSystemValue('objectstore_multibucket');
if (is_array($config)) {
$config['multibucket'] = true;
return $config;
}
$config = $this->config->getSystemValue('objectstore');
if (is_array($config)) {
if (!isset($config['multibucket'])) {
$config['multibucket'] = false;
}
return $config;
}
return null;
}
public function getObjectStore(?string $bucket, OutputInterface $output): ?IObjectStore {
$config = $this->getObjectStoreConfig();
if (!$config) {
$output->writeln("<error>Instance is not using primary object store</error>");
return null;
}
if ($config['multibucket'] && !$bucket) {
$output->writeln("<error>--bucket option required</error> because <info>multi bucket</info> is enabled.");
return null;
}
if (!isset($config['arguments'])) {
throw new \Exception("no arguments configured for object store configuration");
}
if (!isset($config['class'])) {
throw new \Exception("no class configured for object store configuration");
}
if ($bucket) {
// s3, swift
$config['arguments']['bucket'] = $bucket;
// azure
$config['arguments']['container'] = $bucket;
}
$store = new $config['class']($config['arguments']);
if (!$store instanceof IObjectStore) {
throw new \Exception("configured object store class is not an object store implementation");
}
return $store;
}
/**
* Check if an object is referenced in the database
*/
public function objectExistsInDb(string $object): int|false {
if (!str_starts_with($object, 'urn:oid:')) {
return false;
}
$fileId = (int)substr($object, strlen('urn:oid:'));
$query = $this->connection->getQueryBuilder();
$query->select('fileid')
->from('filecache')
->where($query->expr()->eq('fileid', $query->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
$result = $query->executeQuery();
if ($result->fetchOne() === false) {
return false;
}
return $fileId;
}
}
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 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\Command\Object;
use OCP\Files\IMimeTypeDetector;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
class Put extends Command {
public function __construct(
private ObjectUtil $objectUtils,
private IMimeTypeDetector $mimeTypeDetector,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('files:object:put')
->setDescription('Write a file to the object store')
->addArgument('input', InputArgument::REQUIRED, "Source local path, use - to read from STDIN")
->addArgument('object', InputArgument::REQUIRED, "Object to write")
->addOption('bucket', 'b', InputOption::VALUE_REQUIRED, "Bucket where to store the object, only required in cases where it can't be determined from the config");
;
}
public function execute(InputInterface $input, OutputInterface $output): int {
$object = $input->getArgument('object');
$inputName = (string)$input->getArgument('input');
$objectStore = $this->objectUtils->getObjectStore($input->getOption("bucket"), $output);
if (!$objectStore) {
return -1;
}
if ($fileId = $this->objectUtils->objectExistsInDb($object)) {
$output->writeln("<error>Warning, object $object belongs to an existing file, overwriting the object contents can lead to unexpected behavior.</error>");
$output->writeln("You can use <info>occ files:put $inputName $fileId</info> to write to the file safely.");
$output->writeln("");
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
$question = new ConfirmationQuestion("Write to the object anyway? [y/N] ", false);
if (!$helper->ask($input, $output, $question)) {
return -1;
}
}
$source = $inputName === '-' ? STDIN : fopen($inputName, 'r');
if (!$source) {
$output->writeln("<error>Failed to open $inputName</error>");
return self::FAILURE;
}
$objectStore->writeObject($object, $source, $this->mimeTypeDetector->detectPath($inputName));
return self::SUCCESS;
}
}
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 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\Command;
use OC\Core\Command\Info\FileUtils;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Put extends Command {
public function __construct(
private FileUtils $fileUtils,
private IRootFolder $rootFolder,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('files:put')
->setDescription('Write contents of a file')
->addArgument('input', InputArgument::REQUIRED, "Source local path, use - to read from STDIN")
->addArgument('file', InputArgument::REQUIRED, "Target Nextcloud file path to write to or fileid of existing file");
}
public function execute(InputInterface $input, OutputInterface $output): int {
$fileOutput = $input->getArgument('file');
$inputName = $input->getArgument('input');
$node = $this->fileUtils->getNode($fileOutput);
if ($node instanceof Folder) {
$output->writeln("<error>$fileOutput is a folder</error>");
return self::FAILURE;
}
if (!$node and is_numeric($fileOutput)) {
$output->writeln("<error>$fileOutput not found</error>");
return self::FAILURE;
}
$source = ($inputName === null || $inputName === '-') ? STDIN : fopen($inputName, 'r');
if (!$source) {
$output->writeln("<error>Failed to open $inputName</error>");
return self::FAILURE;
}
if ($node instanceof File) {
$target = $node->fopen('w');
if (!$target) {
$output->writeln("<error>Failed to open $fileOutput</error>");
return self::FAILURE;
}
stream_copy_to_stream($source, $target);
} else {
$this->rootFolder->newFile($fileOutput, $source);
}
return self::SUCCESS;
}
}
@@ -0,0 +1,130 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2021 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\Command;
use OCP\IDBConnection;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class RepairTree extends Command {
public const CHUNK_SIZE = 200;
public function __construct(
protected IDBConnection $connection,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('files:repair-tree')
->setDescription('Try and repair malformed filesystem tree structures')
->addOption('dry-run');
}
public function execute(InputInterface $input, OutputInterface $output): int {
$rows = $this->findBrokenTreeBits();
$fix = !$input->getOption('dry-run');
$output->writeln("Found " . count($rows) . " file entries with an invalid path");
if ($fix) {
$this->connection->beginTransaction();
}
$query = $this->connection->getQueryBuilder();
$query->update('filecache')
->set('path', $query->createParameter('path'))
->set('path_hash', $query->func()->md5($query->createParameter('path')))
->set('storage', $query->createParameter('storage'))
->where($query->expr()->eq('fileid', $query->createParameter('fileid')));
foreach ($rows as $row) {
$output->writeln("Path of file {$row['fileid']} is {$row['path']} but should be {$row['parent_path']}/{$row['name']} based on its parent", OutputInterface::VERBOSITY_VERBOSE);
if ($fix) {
$fileId = $this->getFileId((int)$row['parent_storage'], $row['parent_path'] . '/' . $row['name']);
if ($fileId > 0) {
$output->writeln("Cache entry has already be recreated with id $fileId, deleting instead");
$this->deleteById((int)$row['fileid']);
} else {
$query->setParameters([
'fileid' => $row['fileid'],
'path' => $row['parent_path'] . '/' . $row['name'],
'storage' => $row['parent_storage'],
]);
$query->execute();
}
}
}
if ($fix) {
$this->connection->commit();
}
return self::SUCCESS;
}
private function getFileId(int $storage, string $path) {
$query = $this->connection->getQueryBuilder();
$query->select('fileid')
->from('filecache')
->where($query->expr()->eq('storage', $query->createNamedParameter($storage)))
->andWhere($query->expr()->eq('path_hash', $query->createNamedParameter(md5($path))));
return $query->execute()->fetch(\PDO::FETCH_COLUMN);
}
private function deleteById(int $fileId): void {
$query = $this->connection->getQueryBuilder();
$query->delete('filecache')
->where($query->expr()->eq('fileid', $query->createNamedParameter($fileId)));
$query->execute();
}
private function findBrokenTreeBits(): array {
$query = $this->connection->getQueryBuilder();
$query->select('f.fileid', 'f.path', 'f.parent', 'f.name')
->selectAlias('p.path', 'parent_path')
->selectAlias('p.storage', 'parent_storage')
->from('filecache', 'f')
->innerJoin('f', 'filecache', 'p', $query->expr()->eq('f.parent', 'p.fileid'))
->where($query->expr()->orX(
$query->expr()->andX(
$query->expr()->neq('p.path_hash', $query->createNamedParameter(md5(''))),
$query->expr()->neq('f.path', $query->func()->concat('p.path', $query->func()->concat($query->createNamedParameter('/'), 'f.name')))
),
$query->expr()->andX(
$query->expr()->eq('p.path_hash', $query->createNamedParameter(md5(''))),
$query->expr()->neq('f.path', 'f.name')
),
$query->expr()->neq('f.storage', 'p.storage')
));
return $query->execute()->fetchAll();
}
}
@@ -0,0 +1,355 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bart Visscher <bartv@thisnet.nl>
* @author Blaok <i@blaok.me>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author J0WI <J0WI@users.noreply.github.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Joel S <joel.devbox@protonmail.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author martin.mattel@diemattels.at <martin.mattel@diemattels.at>
* @author Maxence Lange <maxence@artificial-owl.com>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Vincent Petry <vincent@nextcloud.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\Command;
use OC\Core\Command\Base;
use OC\Core\Command\InterruptedException;
use OC\DB\Connection;
use OC\DB\ConnectionAdapter;
use OC\FilesMetadata\FilesMetadataManager;
use OC\ForbiddenException;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\Events\FileCacheUpdated;
use OCP\Files\Events\NodeAddedToCache;
use OCP\Files\Events\NodeRemovedFromCache;
use OCP\Files\IRootFolder;
use OCP\Files\Mount\IMountPoint;
use OCP\Files\NotFoundException;
use OCP\Files\StorageNotAvailableException;
use OCP\FilesMetadata\IFilesMetadataManager;
use OCP\IUserManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Helper\Table;
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 Scan extends Base {
protected float $execTime = 0;
protected int $foldersCounter = 0;
protected int $filesCounter = 0;
protected int $errorsCounter = 0;
protected int $newCounter = 0;
protected int $updatedCounter = 0;
protected int $removedCounter = 0;
public function __construct(
private IUserManager $userManager,
private IRootFolder $rootFolder,
private FilesMetadataManager $filesMetadataManager,
private IEventDispatcher $eventDispatcher,
private LoggerInterface $logger,
) {
parent::__construct();
}
protected function configure(): void {
parent::configure();
$this
->setName('files:scan')
->setDescription('rescan filesystem')
->addArgument(
'user_id',
InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
'will rescan all files of the given user(s)'
)
->addOption(
'path',
'p',
InputArgument::OPTIONAL,
'limit rescan to this path, eg. --path="/alice/files/Music", the user_id is determined by the path and the user_id parameter and --all are ignored'
)
->addOption(
'generate-metadata',
null,
InputOption::VALUE_OPTIONAL,
'Generate metadata for all scanned files; if specified only generate for named value',
''
)
->addOption(
'all',
null,
InputOption::VALUE_NONE,
'will rescan all files of all known users'
)->addOption(
'unscanned',
null,
InputOption::VALUE_NONE,
'only scan files which are marked as not fully scanned'
)->addOption(
'shallow',
null,
InputOption::VALUE_NONE,
'do not scan folders recursively'
)->addOption(
'home-only',
null,
InputOption::VALUE_NONE,
'only scan the home storage, ignoring any mounted external storage or share'
);
}
protected function scanFiles(string $user, string $path, ?string $scanMetadata, OutputInterface $output, bool $backgroundScan = false, bool $recursive = true, bool $homeOnly = false): void {
$connection = $this->reconnectToDatabase($output);
$scanner = new \OC\Files\Utils\Scanner(
$user,
new ConnectionAdapter($connection),
\OC::$server->get(IEventDispatcher::class),
\OC::$server->get(LoggerInterface::class)
);
# check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function (string $path) use ($output, $scanMetadata) {
$output->writeln("\tFile\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
++$this->filesCounter;
$this->abortIfInterrupted();
if ($scanMetadata !== null) {
$node = $this->rootFolder->get($path);
$this->filesMetadataManager->refreshMetadata(
$node,
($scanMetadata !== '') ? IFilesMetadataManager::PROCESS_NAMED : IFilesMetadataManager::PROCESS_LIVE | IFilesMetadataManager::PROCESS_BACKGROUND,
$scanMetadata
);
}
});
$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
$output->writeln("\tFolder\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
++$this->foldersCounter;
$this->abortIfInterrupted();
});
$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
$output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
++$this->errorsCounter;
});
$scanner->listen('\OC\Files\Utils\Scanner', 'normalizedNameMismatch', function ($fullPath) use ($output) {
$output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
++$this->errorsCounter;
});
$this->eventDispatcher->addListener(NodeAddedToCache::class, function () {
++$this->newCounter;
});
$this->eventDispatcher->addListener(FileCacheUpdated::class, function () {
++$this->updatedCounter;
});
$this->eventDispatcher->addListener(NodeRemovedFromCache::class, function () {
++$this->removedCounter;
});
try {
if ($backgroundScan) {
$scanner->backgroundScan($path);
} else {
$scanner->scan($path, $recursive, $homeOnly ? [$this, 'filterHomeMount'] : null);
}
} catch (ForbiddenException $e) {
$output->writeln("<error>Home storage for user $user not writable or 'files' subdirectory missing</error>");
$output->writeln(' ' . $e->getMessage());
$output->writeln('Make sure you\'re running the scan command only as the user the web server runs as');
++$this->errorsCounter;
} catch (InterruptedException $e) {
# exit the function if ctrl-c has been pressed
$output->writeln('Interrupted by user');
} catch (NotFoundException $e) {
$output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
++$this->errorsCounter;
} catch (\Exception $e) {
$output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
$output->writeln('<error>' . $e->getTraceAsString() . '</error>');
++$this->errorsCounter;
}
}
public function filterHomeMount(IMountPoint $mountPoint): bool {
// any mountpoint inside '/$user/files/'
return substr_count($mountPoint->getMountPoint(), '/') <= 3;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$inputPath = $input->getOption('path');
if ($inputPath) {
$inputPath = '/' . trim($inputPath, '/');
[, $user,] = explode('/', $inputPath, 3);
$users = [$user];
} elseif ($input->getOption('all')) {
$users = $this->userManager->search('');
} else {
$users = $input->getArgument('user_id');
}
# check quantity of users to be process and show it on the command line
$users_total = count($users);
if ($users_total === 0) {
$output->writeln('<error>Please specify the user id to scan, --all to scan for all users or --path=...</error>');
return self::FAILURE;
}
$this->initTools($output);
// getOption() logic on VALUE_OPTIONAL
$metadata = null; // null if --generate-metadata is not set, empty if option have no value, value if set
if ($input->getOption('generate-metadata') !== '') {
$metadata = $input->getOption('generate-metadata') ?? '';
}
$user_count = 0;
foreach ($users as $user) {
if (is_object($user)) {
$user = $user->getUID();
}
$path = $inputPath ?: '/' . $user;
++$user_count;
if ($this->userManager->userExists($user)) {
$output->writeln("Starting scan for user $user_count out of $users_total ($user)");
$this->scanFiles($user, $path, $metadata, $output, $input->getOption('unscanned'), !$input->getOption('shallow'), $input->getOption('home-only'));
$output->writeln('', OutputInterface::VERBOSITY_VERBOSE);
} else {
$output->writeln("<error>Unknown user $user_count $user</error>");
$output->writeln('', OutputInterface::VERBOSITY_VERBOSE);
}
try {
$this->abortIfInterrupted();
} catch (InterruptedException $e) {
break;
}
}
$this->presentStats($output);
return self::SUCCESS;
}
/**
* Initialises some useful tools for the Command
*/
protected function initTools(OutputInterface $output): void {
// Start the timer
$this->execTime = -microtime(true);
// Convert PHP errors to exceptions
set_error_handler(
fn (int $severity, string $message, string $file, int $line): bool =>
$this->exceptionErrorHandler($output, $severity, $message, $file, $line),
E_ALL
);
}
/**
* Processes PHP errors in order to be able to show them in the output
*
* @see https://www.php.net/manual/en/function.set-error-handler.php
*
* @param int $severity the level of the error raised
* @param string $message
* @param string $file the filename that the error was raised in
* @param int $line the line number the error was raised
*/
public function exceptionErrorHandler(OutputInterface $output, int $severity, string $message, string $file, int $line): bool {
if (($severity === E_DEPRECATED) || ($severity === E_USER_DEPRECATED)) {
// Do not show deprecation warnings
return false;
}
$e = new \ErrorException($message, 0, $severity, $file, $line);
$output->writeln('<error>Error during scan: ' . $e->getMessage() . '</error>');
$output->writeln('<error>' . $e->getTraceAsString() . '</error>', OutputInterface::VERBOSITY_VERY_VERBOSE);
++$this->errorsCounter;
return true;
}
protected function presentStats(OutputInterface $output): void {
// Stop the timer
$this->execTime += microtime(true);
$this->logger->info("Completed scan of {$this->filesCounter} files in {$this->foldersCounter} folder. Found {$this->newCounter} new, {$this->updatedCounter} updated and {$this->removedCounter} removed items");
$headers = [
'Folders',
'Files',
'New',
'Updated',
'Removed',
'Errors',
'Elapsed time',
];
$niceDate = $this->formatExecTime();
$rows = [
$this->foldersCounter,
$this->filesCounter,
$this->newCounter,
$this->updatedCounter,
$this->removedCounter,
$this->errorsCounter,
$niceDate,
];
$table = new Table($output);
$table
->setHeaders($headers)
->setRows([$rows]);
$table->render();
}
/**
* Formats microtime into a human-readable format
*/
protected function formatExecTime(): string {
$secs = (int)round($this->execTime);
# convert seconds into HH:MM:SS form
return sprintf('%02d:%02d:%02d', (int)($secs / 3600), ((int)($secs / 60) % 60), $secs % 60);
}
protected function reconnectToDatabase(OutputInterface $output): Connection {
/** @var Connection $connection */
$connection = \OC::$server->get(Connection::class);
try {
$connection->close();
} catch (\Exception $ex) {
$output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
}
while (!$connection->isConnected()) {
try {
$connection->connect();
} catch (\Exception $ex) {
$output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
sleep(60);
}
}
return $connection;
}
}
@@ -0,0 +1,267 @@
<?php
/**
* @copyright Copyright (c) 2016 Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author J0WI <J0WI@users.noreply.github.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Joel S <joel.devbox@protonmail.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Erik Wouters <6179932+EWouters@users.noreply.github.com>
*
* @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\Command;
use OC\Core\Command\Base;
use OC\Core\Command\InterruptedException;
use OC\DB\Connection;
use OC\DB\ConnectionAdapter;
use OC\ForbiddenException;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\Files\NotFoundException;
use OCP\Files\StorageNotAvailableException;
use OCP\IConfig;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ScanAppData extends Base {
protected float $execTime = 0;
protected int $foldersCounter = 0;
protected int $filesCounter = 0;
public function __construct(
protected IRootFolder $rootFolder,
protected IConfig $config,
) {
parent::__construct();
}
protected function configure(): void {
parent::configure();
$this
->setName('files:scan-app-data')
->setDescription('rescan the AppData folder');
$this->addArgument('folder', InputArgument::OPTIONAL, 'The appdata subfolder to scan', '');
}
protected function scanFiles(OutputInterface $output, string $folder): int {
try {
/** @var \OCP\Files\Folder $appData */
$appData = $this->getAppDataFolder();
} catch (NotFoundException $e) {
$output->writeln('<error>NoAppData folder found</error>');
return self::FAILURE;
}
if ($folder !== '') {
try {
$appData = $appData->get($folder);
} catch (NotFoundException $e) {
$output->writeln('<error>Could not find folder: ' . $folder . '</error>');
return self::FAILURE;
}
}
$connection = $this->reconnectToDatabase($output);
$scanner = new \OC\Files\Utils\Scanner(
null,
new ConnectionAdapter($connection),
\OC::$server->query(IEventDispatcher::class),
\OC::$server->get(LoggerInterface::class)
);
# check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
$output->writeln("\tFile <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
++$this->filesCounter;
$this->abortIfInterrupted();
});
$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
$output->writeln("\tFolder <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
++$this->foldersCounter;
$this->abortIfInterrupted();
});
$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
$output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
});
$scanner->listen('\OC\Files\Utils\Scanner', 'normalizedNameMismatch', function ($fullPath) use ($output) {
$output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
});
try {
$scanner->scan($appData->getPath());
} catch (ForbiddenException $e) {
$output->writeln('<error>Storage not writable</error>');
$output->writeln('<info>Make sure you\'re running the scan command only as the user the web server runs as</info>');
return self::FAILURE;
} catch (InterruptedException $e) {
# exit the function if ctrl-c has been pressed
$output->writeln('<info>Interrupted by user</info>');
return self::FAILURE;
} catch (NotFoundException $e) {
$output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
return self::FAILURE;
} catch (\Exception $e) {
$output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
$output->writeln('<error>' . $e->getTraceAsString() . '</error>');
return self::FAILURE;
}
return self::SUCCESS;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
# restrict the verbosity level to VERBOSITY_VERBOSE
if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
$output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
}
$output->writeln('Scanning AppData for files');
$output->writeln('');
$folder = $input->getArgument('folder');
$this->initTools();
$exitCode = $this->scanFiles($output, $folder);
if ($exitCode === 0) {
$this->presentStats($output);
}
return $exitCode;
}
/**
* Initialises some useful tools for the Command
*/
protected function initTools(): void {
// Start the timer
$this->execTime = -microtime(true);
// Convert PHP errors to exceptions
set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
}
/**
* Processes PHP errors as exceptions in order to be able to keep track of problems
*
* @see https://www.php.net/manual/en/function.set-error-handler.php
*
* @param int $severity the level of the error raised
* @param string $message
* @param string $file the filename that the error was raised in
* @param int $line the line number the error was raised
*
* @throws \ErrorException
*/
public function exceptionErrorHandler($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
// This error code is not included in error_reporting
return;
}
throw new \ErrorException($message, 0, $severity, $file, $line);
}
protected function presentStats(OutputInterface $output): void {
// Stop the timer
$this->execTime += microtime(true);
$headers = [
'Folders', 'Files', 'Elapsed time'
];
$this->showSummary($headers, null, $output);
}
/**
* Shows a summary of operations
*
* @param string[] $headers
* @param string[] $rows
*/
protected function showSummary($headers, $rows, OutputInterface $output): void {
$niceDate = $this->formatExecTime();
if (!$rows) {
$rows = [
$this->foldersCounter,
$this->filesCounter,
$niceDate,
];
}
$table = new Table($output);
$table
->setHeaders($headers)
->setRows([$rows]);
$table->render();
}
/**
* Formats microtime into a human-readable format
*/
protected function formatExecTime(): string {
$secs = round($this->execTime);
# convert seconds into HH:MM:SS form
return sprintf('%02d:%02d:%02d', (int)($secs / 3600), ((int)($secs / 60) % 60), (int)$secs % 60);
}
protected function reconnectToDatabase(OutputInterface $output): Connection {
/** @var Connection $connection*/
$connection = \OC::$server->get(Connection::class);
try {
$connection->close();
} catch (\Exception $ex) {
$output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
}
while (!$connection->isConnected()) {
try {
$connection->connect();
} catch (\Exception $ex) {
$output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
sleep(60);
}
}
return $connection;
}
/**
* @throws NotFoundException
*/
private function getAppDataFolder(): Node {
$instanceId = $this->config->getSystemValue('instanceid', null);
if ($instanceId === null) {
throw new NotFoundException();
}
return $this->rootFolder->get('appdata_'.$instanceId);
}
}
@@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Carla Schroder <carla@owncloud.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Sujith Haridasan <sujith.h@gmail.com>
* @author Sujith H <sharidasan@owncloud.com>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Tobia De Koninck <LEDfan@users.noreply.github.com>
* @author Vincent Petry <vincent@nextcloud.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\Command;
use OCA\Files\Exception\TransferOwnershipException;
use OCA\Files\Service\OwnershipTransferService;
use OCP\IConfig;
use OCP\IUser;
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 TransferOwnership extends Command {
public function __construct(
private IUserManager $userManager,
private OwnershipTransferService $transferService,
private IConfig $config,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('files:transfer-ownership')
->setDescription('All files and folders are moved to another user - outgoing shares and incoming user file shares (optionally) are moved as well.')
->addArgument(
'source-user',
InputArgument::REQUIRED,
'owner of files which shall be moved'
)
->addArgument(
'destination-user',
InputArgument::REQUIRED,
'user who will be the new owner of the files'
)
->addOption(
'path',
null,
InputOption::VALUE_REQUIRED,
'selectively provide the path to transfer. For example --path="folder_name"',
''
)->addOption(
'move',
null,
InputOption::VALUE_NONE,
'move data from source user to root directory of destination user, which must be empty'
)->addOption(
'transfer-incoming-shares',
null,
InputOption::VALUE_OPTIONAL,
'transfer incoming user file shares to destination user. Usage: --transfer-incoming-shares=1 (value required)',
'2'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
/**
* Check if source and destination users are same. If they are same then just ignore the transfer.
*/
if ($input->getArgument(('source-user')) === $input->getArgument('destination-user')) {
$output->writeln("<error>Ownership can't be transferred when Source and Destination users are the same user. Please check your input.</error>");
return self::FAILURE;
}
$sourceUserObject = $this->userManager->get($input->getArgument('source-user'));
$destinationUserObject = $this->userManager->get($input->getArgument('destination-user'));
if (!$sourceUserObject instanceof IUser) {
$output->writeln("<error>Unknown source user " . $input->getArgument('source-user') . "</error>");
return self::FAILURE;
}
if (!$destinationUserObject instanceof IUser) {
$output->writeln("<error>Unknown destination user " . $input->getArgument('destination-user') . "</error>");
return self::FAILURE;
}
try {
$includeIncomingArgument = $input->getOption('transfer-incoming-shares');
switch ($includeIncomingArgument) {
case '0':
$includeIncoming = false;
break;
case '1':
$includeIncoming = true;
break;
case '2':
$includeIncoming = $this->config->getSystemValue('transferIncomingShares', false);
if (gettype($includeIncoming) !== 'boolean') {
$output->writeln("<error> config.php: 'transfer-incoming-shares': wrong usage. Transfer aborted.</error>");
return self::FAILURE;
}
break;
default:
$output->writeln("<error>Option --transfer-incoming-shares: wrong usage. Transfer aborted.</error>");
return self::FAILURE;
}
$this->transferService->transfer(
$sourceUserObject,
$destinationUserObject,
ltrim($input->getOption('path'), '/'),
$output,
$input->getOption('move') === true,
false,
$includeIncoming
);
} catch (TransferOwnershipException $e) {
$output->writeln("<error>" . $e->getMessage() . "</error>");
return $e->getCode() !== 0 ? $e->getCode() : self::FAILURE;
}
return self::SUCCESS;
}
}
@@ -0,0 +1,408 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Felix Nüsse <Felix.nuesse@t-online.de>
* @author fnuesse <felix.nuesse@t-online.de>
* @author fnuesse <fnuesse@techfak.uni-bielefeld.de>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Max Kovalenko <mxss1998@yandex.ru>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Nina Pypchenko <22447785+nina-py@users.noreply.github.com>
* @author Richard Steinmetz <richard@steinmetz.cloud>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Tobias Kaminsky <tobias@kaminsky.me>
* @author Vincent Petry <vincent@nextcloud.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\Controller;
use OC\Files\Node\Node;
use OCA\Files\Service\TagService;
use OCA\Files\Service\UserConfig;
use OCA\Files\Service\ViewConfig;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\OpenAPI;
use OCP\AppFramework\Http\ContentSecurityPolicy;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\FileDisplayResponse;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http\StreamResponse;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\NotFoundException;
use OCP\IConfig;
use OCP\IPreview;
use OCP\IRequest;
use OCP\IUserSession;
use OCP\Share\IManager;
use OCP\Share\IShare;
/**
* @package OCA\Files\Controller
*/
class ApiController extends Controller {
private TagService $tagService;
private IManager $shareManager;
private IPreview $previewManager;
private IUserSession $userSession;
private IConfig $config;
private ?Folder $userFolder;
private UserConfig $userConfig;
private ViewConfig $viewConfig;
public function __construct(string $appName,
IRequest $request,
IUserSession $userSession,
TagService $tagService,
IPreview $previewManager,
IManager $shareManager,
IConfig $config,
?Folder $userFolder,
UserConfig $userConfig,
ViewConfig $viewConfig) {
parent::__construct($appName, $request);
$this->userSession = $userSession;
$this->tagService = $tagService;
$this->previewManager = $previewManager;
$this->shareManager = $shareManager;
$this->config = $config;
$this->userFolder = $userFolder;
$this->userConfig = $userConfig;
$this->viewConfig = $viewConfig;
}
/**
* Gets a thumbnail of the specified file
*
* @since API version 1.0
*
* @NoAdminRequired
* @NoCSRFRequired
* @StrictCookieRequired
*
* @param int $x Width of the thumbnail
* @param int $y Height of the thumbnail
* @param string $file URL-encoded filename
* @return FileDisplayResponse<Http::STATUS_OK, array{Content-Type: string}>|DataResponse<Http::STATUS_BAD_REQUEST|Http::STATUS_NOT_FOUND, array{message?: string}, array{}>
*
* 200: Thumbnail returned
* 400: Getting thumbnail is not possible
* 404: File not found
*/
public function getThumbnail($x, $y, $file) {
if ($x < 1 || $y < 1) {
return new DataResponse(['message' => 'Requested size must be numeric and a positive value.'], Http::STATUS_BAD_REQUEST);
}
try {
$file = $this->userFolder->get($file);
if ($file instanceof Folder) {
throw new NotFoundException();
}
/** @var File $file */
$preview = $this->previewManager->getPreview($file, $x, $y, true);
return new FileDisplayResponse($preview, Http::STATUS_OK, ['Content-Type' => $preview->getMimeType()]);
} catch (NotFoundException $e) {
return new DataResponse(['message' => 'File not found.'], Http::STATUS_NOT_FOUND);
} catch (\Exception $e) {
return new DataResponse([], Http::STATUS_BAD_REQUEST);
}
}
/**
* Updates the info of the specified file path
* The passed tags are absolute, which means they will
* replace the actual tag selection.
*
* @NoAdminRequired
*
* @param string $path path
* @param array|string $tags array of tags
* @return DataResponse
*/
public function updateFileTags($path, $tags = null) {
$result = [];
// if tags specified or empty array, update tags
if (!is_null($tags)) {
try {
$this->tagService->updateFileTags($path, $tags);
} catch (\OCP\Files\NotFoundException $e) {
return new DataResponse([
'message' => $e->getMessage()
], Http::STATUS_NOT_FOUND);
} catch (\OCP\Files\StorageNotAvailableException $e) {
return new DataResponse([
'message' => $e->getMessage()
], Http::STATUS_SERVICE_UNAVAILABLE);
} catch (\Exception $e) {
return new DataResponse([
'message' => $e->getMessage()
], Http::STATUS_NOT_FOUND);
}
$result['tags'] = $tags;
}
return new DataResponse($result);
}
/**
* @param \OCP\Files\Node[] $nodes
* @return array
*/
private function formatNodes(array $nodes) {
$shareTypesForNodes = $this->getShareTypesForNodes($nodes);
return array_values(array_map(function (Node $node) use ($shareTypesForNodes) {
$shareTypes = $shareTypesForNodes[$node->getId()] ?? [];
$file = \OCA\Files\Helper::formatFileInfo($node->getFileInfo());
$file['hasPreview'] = $this->previewManager->isAvailable($node);
$parts = explode('/', dirname($node->getPath()), 4);
if (isset($parts[3])) {
$file['path'] = '/' . $parts[3];
} else {
$file['path'] = '/';
}
if (!empty($shareTypes)) {
$file['shareTypes'] = $shareTypes;
}
return $file;
}, $nodes));
}
/**
* Get the share types for each node
*
* @param \OCP\Files\Node[] $nodes
* @return array<int, int[]> list of share types for each fileid
*/
private function getShareTypesForNodes(array $nodes): array {
$userId = $this->userSession->getUser()->getUID();
$requestedShareTypes = [
IShare::TYPE_USER,
IShare::TYPE_GROUP,
IShare::TYPE_LINK,
IShare::TYPE_REMOTE,
IShare::TYPE_EMAIL,
IShare::TYPE_ROOM,
IShare::TYPE_DECK,
IShare::TYPE_SCIENCEMESH,
];
$shareTypes = [];
$nodeIds = array_map(function (Node $node) {
return $node->getId();
}, $nodes);
foreach ($requestedShareTypes as $shareType) {
$nodesLeft = array_combine($nodeIds, array_fill(0, count($nodeIds), true));
$offset = 0;
// fetch shares until we've either found shares for all nodes or there are no more shares left
while (count($nodesLeft) > 0) {
$shares = $this->shareManager->getSharesBy($userId, $shareType, null, false, 100, $offset);
foreach ($shares as $share) {
$fileId = $share->getNodeId();
if (isset($nodesLeft[$fileId])) {
if (!isset($shareTypes[$fileId])) {
$shareTypes[$fileId] = [];
}
$shareTypes[$fileId][] = $shareType;
unset($nodesLeft[$fileId]);
}
}
if (count($shares) < 100) {
break;
} else {
$offset += count($shares);
}
}
}
return $shareTypes;
}
/**
* Returns a list of recently modified files.
*
* @NoAdminRequired
*
* @return DataResponse
*/
public function getRecentFiles() {
$nodes = $this->userFolder->getRecent(100);
$files = $this->formatNodes($nodes);
return new DataResponse(['files' => $files]);
}
/**
* Returns the current logged-in user's storage stats.
*
* @NoAdminRequired
*
* @param ?string $dir the directory to get the storage stats from
* @return JSONResponse
*/
public function getStorageStats($dir = '/'): JSONResponse {
$storageInfo = \OC_Helper::getStorageInfo($dir ?: '/');
return new JSONResponse(['message' => 'ok', 'data' => $storageInfo]);
}
/**
* Set a user view config
*
* @NoAdminRequired
*
* @param string $view
* @param string $key
* @param string|bool $value
* @return JSONResponse
*/
public function setViewConfig(string $view, string $key, $value): JSONResponse {
try {
$this->viewConfig->setConfig($view, $key, (string)$value);
} catch (\InvalidArgumentException $e) {
return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
}
return new JSONResponse(['message' => 'ok', 'data' => $this->viewConfig->getConfig($view)]);
}
/**
* Get the user view config
*
* @NoAdminRequired
*
* @return JSONResponse
*/
public function getViewConfigs(): JSONResponse {
return new JSONResponse(['message' => 'ok', 'data' => $this->viewConfig->getConfigs()]);
}
/**
* Set a user config
*
* @NoAdminRequired
*
* @param string $key
* @param string|bool $value
* @return JSONResponse
*/
public function setConfig(string $key, $value): JSONResponse {
try {
$this->userConfig->setConfig($key, (string)$value);
} catch (\InvalidArgumentException $e) {
return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
}
return new JSONResponse(['message' => 'ok', 'data' => ['key' => $key, 'value' => $value]]);
}
/**
* Get the user config
*
* @NoAdminRequired
*
* @return JSONResponse
*/
public function getConfigs(): JSONResponse {
return new JSONResponse(['message' => 'ok', 'data' => $this->userConfig->getConfigs()]);
}
/**
* Toggle default for showing/hiding hidden files
*
* @NoAdminRequired
*
* @param bool $value
* @return Response
* @throws \OCP\PreConditionNotMetException
*/
public function showHiddenFiles(bool $value): Response {
$this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', $value ? '1' : '0');
return new Response();
}
/**
* Toggle default for cropping preview images
*
* @NoAdminRequired
*
* @param bool $value
* @return Response
* @throws \OCP\PreConditionNotMetException
*/
public function cropImagePreviews(bool $value): Response {
$this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'crop_image_previews', $value ? '1' : '0');
return new Response();
}
/**
* Toggle default for files grid view
*
* @NoAdminRequired
*
* @param bool $show
* @return Response
* @throws \OCP\PreConditionNotMetException
*/
public function showGridView(bool $show): Response {
$this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', $show ? '1' : '0');
return new Response();
}
/**
* Get default settings for the grid view
*
* @NoAdminRequired
*/
public function getGridView() {
$status = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', '0') === '1';
return new JSONResponse(['gridview' => $status]);
}
/**
* @NoAdminRequired
* @NoCSRFRequired
* @PublicPage
*/
#[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
public function serviceWorker(): StreamResponse {
$response = new StreamResponse(__DIR__ . '/../../../../dist/preview-service-worker.js');
$response->setHeaders([
'Content-Type' => 'application/javascript',
'Service-Worker-Allowed' => '/'
]);
$policy = new ContentSecurityPolicy();
$policy->addAllowedWorkerSrcDomain("'self'");
$policy->addAllowedScriptDomain("'self'");
$policy->addAllowedConnectDomain("'self'");
$response->setContentSecurityPolicy($policy);
return $response;
}
}
@@ -0,0 +1,172 @@
<?php
/**
* @copyright Copyright (c) 2019 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
*
* @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\Controller;
use Exception;
use OCA\Files\Service\DirectEditingService;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCSController;
use OCP\DirectEditing\IManager;
use OCP\DirectEditing\RegisterDirectEditorEvent;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IRequest;
use OCP\IURLGenerator;
use Psr\Log\LoggerInterface;
class DirectEditingController extends OCSController {
public function __construct(
string $appName,
IRequest $request,
string $corsMethods,
string $corsAllowedHeaders,
int $corsMaxAge,
private IEventDispatcher $eventDispatcher,
private IURLGenerator $urlGenerator,
private IManager $directEditingManager,
private DirectEditingService $directEditingService,
private LoggerInterface $logger
) {
parent::__construct($appName, $request, $corsMethods, $corsAllowedHeaders, $corsMaxAge);
}
/**
* @NoAdminRequired
*
* Get the direct editing capabilities
* @return DataResponse<Http::STATUS_OK, array{editors: array<string, array{id: string, name: string, mimetypes: string[], optionalMimetypes: string[], secure: bool}>, creators: array<string, array{id: string, editor: string, name: string, extension: string, templates: bool, mimetypes: string[]}>}, array{}>
*
* 200: Direct editing capabilities returned
*/
public function info(): DataResponse {
$response = new DataResponse($this->directEditingService->getDirectEditingCapabilitites());
$response->setETag($this->directEditingService->getDirectEditingETag());
return $response;
}
/**
* @NoAdminRequired
*
* Create a file for direct editing
*
* @param string $path Path of the file
* @param string $editorId ID of the editor
* @param string $creatorId ID of the creator
* @param ?string $templateId ID of the template
*
* @return DataResponse<Http::STATUS_OK, array{url: string}, array{}>|DataResponse<Http::STATUS_FORBIDDEN|Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
*
* 200: URL for direct editing returned
* 403: Opening file is not allowed
*/
public function create(string $path, string $editorId, string $creatorId, string $templateId = null): DataResponse {
if (!$this->directEditingManager->isEnabled()) {
return new DataResponse(['message' => 'Direct editing is not enabled'], Http::STATUS_INTERNAL_SERVER_ERROR);
}
$this->eventDispatcher->dispatchTyped(new RegisterDirectEditorEvent($this->directEditingManager));
try {
$token = $this->directEditingManager->create($path, $editorId, $creatorId, $templateId);
return new DataResponse([
'url' => $this->urlGenerator->linkToRouteAbsolute('files.DirectEditingView.edit', ['token' => $token])
]);
} catch (Exception $e) {
$this->logger->error(
'Exception when creating a new file through direct editing',
[
'exception' => $e
],
);
return new DataResponse(['message' => 'Failed to create file: ' . $e->getMessage()], Http::STATUS_FORBIDDEN);
}
}
/**
* @NoAdminRequired
*
* Open a file for direct editing
*
* @param string $path Path of the file
* @param ?string $editorId ID of the editor
* @param ?int $fileId ID of the file
*
* @return DataResponse<Http::STATUS_OK, array{url: string}, array{}>|DataResponse<Http::STATUS_FORBIDDEN|Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
*
* 200: URL for direct editing returned
* 403: Opening file is not allowed
*/
public function open(string $path, string $editorId = null, ?int $fileId = null): DataResponse {
if (!$this->directEditingManager->isEnabled()) {
return new DataResponse(['message' => 'Direct editing is not enabled'], Http::STATUS_INTERNAL_SERVER_ERROR);
}
$this->eventDispatcher->dispatchTyped(new RegisterDirectEditorEvent($this->directEditingManager));
try {
$token = $this->directEditingManager->open($path, $editorId, $fileId);
return new DataResponse([
'url' => $this->urlGenerator->linkToRouteAbsolute('files.DirectEditingView.edit', ['token' => $token])
]);
} catch (Exception $e) {
$this->logger->error(
'Exception when opening a file through direct editing',
[
'exception' => $e
],
);
return new DataResponse(['message' => 'Failed to open file: ' . $e->getMessage()], Http::STATUS_FORBIDDEN);
}
}
/**
* @NoAdminRequired
*
* Get the templates for direct editing
*
* @param string $editorId ID of the editor
* @param string $creatorId ID of the creator
*
* @return DataResponse<Http::STATUS_OK, array{templates: array<string, array{id: string, title: string, preview: ?string, extension: string, mimetype: string}>}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
*
* 200: Templates returned
*/
public function templates(string $editorId, string $creatorId): DataResponse {
if (!$this->directEditingManager->isEnabled()) {
return new DataResponse(['message' => 'Direct editing is not enabled'], Http::STATUS_INTERNAL_SERVER_ERROR);
}
$this->eventDispatcher->dispatchTyped(new RegisterDirectEditorEvent($this->directEditingManager));
try {
return new DataResponse($this->directEditingManager->getTemplates($editorId, $creatorId));
} catch (Exception $e) {
$this->logger->error(
$e->getMessage(),
[
'exception' => $e
],
);
return new DataResponse(['message' => 'Failed to obtain template list: ' . $e->getMessage()], Http::STATUS_INTERNAL_SERVER_ERROR);
}
}
}
@@ -0,0 +1,65 @@
<?php
/**
* @copyright Copyright (c) 2019 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
*
* @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\Controller;
use Exception;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\Attribute\OpenAPI;
use OCP\AppFramework\Http\NotFoundResponse;
use OCP\AppFramework\Http\Response;
use OCP\DirectEditing\IManager;
use OCP\DirectEditing\RegisterDirectEditorEvent;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IRequest;
use Psr\Log\LoggerInterface;
#[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
class DirectEditingViewController extends Controller {
public function __construct(
$appName,
IRequest $request,
private IEventDispatcher $eventDispatcher,
private IManager $directEditingManager,
private LoggerInterface $logger,
) {
parent::__construct($appName, $request);
}
/**
* @PublicPage
* @NoCSRFRequired
* @UseSession
*
* @param string $token
* @return Response
*/
public function edit(string $token): Response {
$this->eventDispatcher->dispatchTyped(new RegisterDirectEditorEvent($this->directEditingManager));
try {
return $this->directEditingManager->edit($token);
} catch (Exception $e) {
$this->logger->error($e->getMessage(), ['exception' => $e]);
return new NotFoundResponse();
}
}
}
@@ -0,0 +1,156 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @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\Controller;
use OCA\Files\Db\OpenLocalEditor;
use OCA\Files\Db\OpenLocalEditorMapper;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCSController;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\DB\Exception;
use OCP\IRequest;
use OCP\Security\ISecureRandom;
use Psr\Log\LoggerInterface;
class OpenLocalEditorController extends OCSController {
public const TOKEN_LENGTH = 128;
public const TOKEN_DURATION = 600; // 10 Minutes
public const TOKEN_RETRIES = 50;
protected ITimeFactory $timeFactory;
protected OpenLocalEditorMapper $mapper;
protected ISecureRandom $secureRandom;
protected LoggerInterface $logger;
protected ?string $userId;
public function __construct(
string $appName,
IRequest $request,
ITimeFactory $timeFactory,
OpenLocalEditorMapper $mapper,
ISecureRandom $secureRandom,
LoggerInterface $logger,
?string $userId
) {
parent::__construct($appName, $request);
$this->timeFactory = $timeFactory;
$this->mapper = $mapper;
$this->secureRandom = $secureRandom;
$this->logger = $logger;
$this->userId = $userId;
}
/**
* @NoAdminRequired
* @UserRateThrottle(limit=10, period=120)
*
* Create a local editor
*
* @param string $path Path of the file
*
* @return DataResponse<Http::STATUS_OK, array{userId: ?string, pathHash: string, expirationTime: int, token: string}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR, array<empty>, array{}>
*
* 200: Local editor returned
*/
public function create(string $path): DataResponse {
$pathHash = sha1($path);
$entity = new OpenLocalEditor();
$entity->setUserId($this->userId);
$entity->setPathHash($pathHash);
$entity->setExpirationTime($this->timeFactory->getTime() + self::TOKEN_DURATION); // Expire in 10 minutes
for ($i = 1; $i <= self::TOKEN_RETRIES; $i++) {
$token = $this->secureRandom->generate(self::TOKEN_LENGTH, ISecureRandom::CHAR_ALPHANUMERIC);
$entity->setToken($token);
try {
$this->mapper->insert($entity);
return new DataResponse([
'userId' => $this->userId,
'pathHash' => $pathHash,
'expirationTime' => $entity->getExpirationTime(),
'token' => $entity->getToken(),
]);
} catch (Exception $e) {
if ($e->getCode() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
// Only retry on unique constraint violation
throw $e;
}
}
}
$this->logger->error('Giving up after ' . self::TOKEN_RETRIES . ' retries to generate a unique local editor token for path hash: ' . $pathHash);
return new DataResponse([], Http::STATUS_INTERNAL_SERVER_ERROR);
}
/**
* @NoAdminRequired
* @BruteForceProtection(action=openLocalEditor)
*
* Validate a local editor
*
* @param string $path Path of the file
* @param string $token Token of the local editor
*
* @return DataResponse<Http::STATUS_OK, array{userId: string, pathHash: string, expirationTime: int, token: string}, array{}>|DataResponse<Http::STATUS_NOT_FOUND, array<empty>, array{}>
*
* 200: Local editor validated successfully
* 404: Local editor not found
*/
public function validate(string $path, string $token): DataResponse {
$pathHash = sha1($path);
try {
$entity = $this->mapper->verifyToken($this->userId, $pathHash, $token);
} catch (DoesNotExistException $e) {
$response = new DataResponse([], Http::STATUS_NOT_FOUND);
$response->throttle(['userId' => $this->userId, 'pathHash' => $pathHash]);
return $response;
}
$this->mapper->delete($entity);
if ($entity->getExpirationTime() <= $this->timeFactory->getTime()) {
$response = new DataResponse([], Http::STATUS_NOT_FOUND);
$response->throttle(['userId' => $this->userId, 'pathHash' => $pathHash]);
return $response;
}
return new DataResponse([
'userId' => $this->userId,
'pathHash' => $pathHash,
'expirationTime' => $entity->getExpirationTime(),
'token' => $entity->getToken(),
]);
}
}
@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2021 Julius Härtl <jus@bitgrid.net>
*
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Julius Härtl <jus@bitgrid.net>
*
* @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\Controller;
use OCA\Files\ResponseDefinitions;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCS\OCSForbiddenException;
use OCP\AppFramework\OCSController;
use OCP\Files\GenericFileException;
use OCP\Files\Template\ITemplateManager;
use OCP\Files\Template\TemplateFileCreator;
use OCP\IRequest;
/**
* @psalm-import-type FilesTemplateFile from ResponseDefinitions
* @psalm-import-type FilesTemplateFileCreator from ResponseDefinitions
*/
class TemplateController extends OCSController {
protected $templateManager;
public function __construct($appName, IRequest $request, ITemplateManager $templateManager) {
parent::__construct($appName, $request);
$this->templateManager = $templateManager;
}
/**
* @NoAdminRequired
*
* List the available templates
*
* @return DataResponse<Http::STATUS_OK, array<FilesTemplateFileCreator>, array{}>
*
* 200: Available templates returned
*/
public function list(): DataResponse {
return new DataResponse($this->templateManager->listTemplates());
}
/**
* @NoAdminRequired
*
* Create a template
*
* @param string $filePath Path of the file
* @param string $templatePath Name of the template
* @param string $templateType Type of the template
*
* @return DataResponse<Http::STATUS_OK, FilesTemplateFile, array{}>
* @throws OCSForbiddenException Creating template is not allowed
*
* 200: Template created successfully
*/
public function create(string $filePath, string $templatePath = '', string $templateType = 'user'): DataResponse {
try {
return new DataResponse($this->templateManager->createFromTemplate($filePath, $templatePath, $templateType));
} catch (GenericFileException $e) {
throw new OCSForbiddenException($e->getMessage());
}
}
/**
* @NoAdminRequired
*
* Initialize the template directory
*
* @param string $templatePath Path of the template directory
* @param bool $copySystemTemplates Whether to copy the system templates to the template directory
*
* @return DataResponse<Http::STATUS_OK, array{template_path: string, templates: FilesTemplateFileCreator[]}, array{}>
* @throws OCSForbiddenException Initializing the template directory is not allowed
*
* 200: Template directory initialized successfully
*/
public function path(string $templatePath = '', bool $copySystemTemplates = false) {
try {
/** @var string $templatePath */
$templatePath = $this->templateManager->initializeTemplateDirectory($templatePath, null, $copySystemTemplates);
return new DataResponse([
'template_path' => $templatePath,
'templates' => array_map(fn (TemplateFileCreator $creator) => $creator->jsonSerialize(), $this->templateManager->listCreators()),
]);
} catch (\Exception $e) {
throw new OCSForbiddenException($e->getMessage());
}
}
}
@@ -0,0 +1,227 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Julius Härtl <jus@bitgrid.net>
* @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\Controller;
use OCA\Files\BackgroundJob\TransferOwnership;
use OCA\Files\Db\TransferOwnership as TransferOwnershipEntity;
use OCA\Files\Db\TransferOwnershipMapper;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCSController;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\Files\IHomeStorage;
use OCP\Files\IRootFolder;
use OCP\IRequest;
use OCP\IUserManager;
use OCP\Notification\IManager as NotificationManager;
class TransferOwnershipController extends OCSController {
/** @var string */
private $userId;
/** @var NotificationManager */
private $notificationManager;
/** @var ITimeFactory */
private $timeFactory;
/** @var IJobList */
private $jobList;
/** @var TransferOwnershipMapper */
private $mapper;
/** @var IUserManager */
private $userManager;
/** @var IRootFolder */
private $rootFolder;
public function __construct(string $appName,
IRequest $request,
string $userId,
NotificationManager $notificationManager,
ITimeFactory $timeFactory,
IJobList $jobList,
TransferOwnershipMapper $mapper,
IUserManager $userManager,
IRootFolder $rootFolder) {
parent::__construct($appName, $request);
$this->userId = $userId;
$this->notificationManager = $notificationManager;
$this->timeFactory = $timeFactory;
$this->jobList = $jobList;
$this->mapper = $mapper;
$this->userManager = $userManager;
$this->rootFolder = $rootFolder;
}
/**
* @NoAdminRequired
*
* Transfer the ownership to another user
*
* @param string $recipient Username of the recipient
* @param string $path Path of the file
*
* @return DataResponse<Http::STATUS_OK|Http::STATUS_BAD_REQUEST|Http::STATUS_FORBIDDEN, array<empty>, array{}>
*
* 200: Ownership transferred successfully
* 400: Transferring ownership is not possible
* 403: Transferring ownership is not allowed
*/
public function transfer(string $recipient, string $path): DataResponse {
$recipientUser = $this->userManager->get($recipient);
if ($recipientUser === null) {
return new DataResponse([], Http::STATUS_BAD_REQUEST);
}
$userRoot = $this->rootFolder->getUserFolder($this->userId);
try {
$node = $userRoot->get($path);
} catch (\Exception $e) {
return new DataResponse([], Http::STATUS_BAD_REQUEST);
}
if ($node->getOwner()->getUID() !== $this->userId || !$node->getStorage()->instanceOfStorage(IHomeStorage::class)) {
return new DataResponse([], Http::STATUS_FORBIDDEN);
}
$transferOwnership = new TransferOwnershipEntity();
$transferOwnership->setSourceUser($this->userId);
$transferOwnership->setTargetUser($recipient);
$transferOwnership->setFileId($node->getId());
$transferOwnership->setNodeName($node->getName());
$transferOwnership = $this->mapper->insert($transferOwnership);
$notification = $this->notificationManager->createNotification();
$notification->setUser($recipient)
->setApp($this->appName)
->setDateTime($this->timeFactory->getDateTime())
->setSubject('transferownershipRequest', [
'sourceUser' => $this->userId,
'targetUser' => $recipient,
'nodeName' => $node->getName(),
])
->setObject('transfer', (string)$transferOwnership->getId());
$this->notificationManager->notify($notification);
return new DataResponse([]);
}
/**
* @NoAdminRequired
*
* Accept an ownership transfer
*
* @param int $id ID of the ownership transfer
*
* @return DataResponse<Http::STATUS_OK|Http::STATUS_FORBIDDEN|Http::STATUS_NOT_FOUND, array<empty>, array{}>
*
* 200: Ownership transfer accepted successfully
* 403: Accepting ownership transfer is not allowed
* 404: Ownership transfer not found
*/
public function accept(int $id): DataResponse {
try {
$transferOwnership = $this->mapper->getById($id);
} catch (DoesNotExistException $e) {
return new DataResponse([], Http::STATUS_NOT_FOUND);
}
if ($transferOwnership->getTargetUser() !== $this->userId) {
return new DataResponse([], Http::STATUS_FORBIDDEN);
}
$notification = $this->notificationManager->createNotification();
$notification->setApp('files')
->setObject('transfer', (string)$id);
$this->notificationManager->markProcessed($notification);
$newTransferOwnership = new TransferOwnershipEntity();
$newTransferOwnership->setNodeName($transferOwnership->getNodeName());
$newTransferOwnership->setFileId($transferOwnership->getFileId());
$newTransferOwnership->setSourceUser($transferOwnership->getSourceUser());
$newTransferOwnership->setTargetUser($transferOwnership->getTargetUser());
$this->mapper->insert($newTransferOwnership);
$this->jobList->add(TransferOwnership::class, [
'id' => $newTransferOwnership->getId(),
]);
return new DataResponse([], Http::STATUS_OK);
}
/**
* @NoAdminRequired
*
* Reject an ownership transfer
*
* @param int $id ID of the ownership transfer
*
* @return DataResponse<Http::STATUS_OK|Http::STATUS_FORBIDDEN|Http::STATUS_NOT_FOUND, array<empty>, array{}>
*
* 200: Ownership transfer rejected successfully
* 403: Rejecting ownership transfer is not allowed
* 404: Ownership transfer not found
*/
public function reject(int $id): DataResponse {
try {
$transferOwnership = $this->mapper->getById($id);
} catch (DoesNotExistException $e) {
return new DataResponse([], Http::STATUS_NOT_FOUND);
}
if ($transferOwnership->getTargetUser() !== $this->userId) {
return new DataResponse([], Http::STATUS_FORBIDDEN);
}
$notification = $this->notificationManager->createNotification();
$notification->setApp('files')
->setObject('transfer', (string)$id);
$this->notificationManager->markProcessed($notification);
$notification = $this->notificationManager->createNotification();
$notification->setUser($transferOwnership->getSourceUser())
->setApp($this->appName)
->setDateTime($this->timeFactory->getDateTime())
->setSubject('transferownershipRequestDenied', [
'sourceUser' => $transferOwnership->getSourceUser(),
'targetUser' => $transferOwnership->getTargetUser(),
'nodeName' => $transferOwnership->getNodeName()
])
->setObject('transfer', (string)$transferOwnership->getId());
$this->notificationManager->notify($notification);
$this->mapper->delete($transferOwnership);
return new DataResponse([], Http::STATUS_OK);
}
}
@@ -0,0 +1,424 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author fnuesse <felix.nuesse@t-online.de>
* @author fnuesse <fnuesse@techfak.uni-bielefeld.de>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Max Kovalenko <mxss1998@yandex.ru>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Nina Pypchenko <22447785+nina-py@users.noreply.github.com>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Vincent Petry <vincent@nextcloud.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\Controller;
use OCA\Files\Activity\Helper;
use OCA\Files\AppInfo\Application;
use OCA\Files\Event\LoadAdditionalScriptsEvent;
use OCA\Files\Event\LoadSidebar;
use OCA\Files\Service\UserConfig;
use OCA\Files\Service\ViewConfig;
use OCA\Viewer\Event\LoadViewer;
use OCP\App\IAppManager;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\Attribute\OpenAPI;
use OCP\AppFramework\Http\ContentSecurityPolicy;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Services\IInitialState;
use OCP\Collaboration\Resources\LoadAdditionalScriptsEvent as ResourcesLoadAdditionalScriptsEvent;
use OCP\Constants;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\Files\Template\ITemplateManager;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\IUserSession;
use OCP\Share\IManager;
/**
* @package OCA\Files\Controller
*/
#[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
class ViewController extends Controller {
private IURLGenerator $urlGenerator;
private IL10N $l10n;
private IConfig $config;
private IEventDispatcher $eventDispatcher;
private IUserSession $userSession;
private IAppManager $appManager;
private IRootFolder $rootFolder;
private Helper $activityHelper;
private IInitialState $initialState;
private ITemplateManager $templateManager;
private IManager $shareManager;
private UserConfig $userConfig;
private ViewConfig $viewConfig;
public function __construct(string $appName,
IRequest $request,
IURLGenerator $urlGenerator,
IL10N $l10n,
IConfig $config,
IEventDispatcher $eventDispatcher,
IUserSession $userSession,
IAppManager $appManager,
IRootFolder $rootFolder,
Helper $activityHelper,
IInitialState $initialState,
ITemplateManager $templateManager,
IManager $shareManager,
UserConfig $userConfig,
ViewConfig $viewConfig
) {
parent::__construct($appName, $request);
$this->urlGenerator = $urlGenerator;
$this->l10n = $l10n;
$this->config = $config;
$this->eventDispatcher = $eventDispatcher;
$this->userSession = $userSession;
$this->appManager = $appManager;
$this->rootFolder = $rootFolder;
$this->activityHelper = $activityHelper;
$this->initialState = $initialState;
$this->templateManager = $templateManager;
$this->shareManager = $shareManager;
$this->userConfig = $userConfig;
$this->viewConfig = $viewConfig;
}
/**
* @param string $appName
* @param string $scriptName
* @return string
*/
protected function renderScript($appName, $scriptName) {
$content = '';
$appPath = \OC_App::getAppPath($appName);
$scriptPath = $appPath . '/' . $scriptName;
if (file_exists($scriptPath)) {
// TODO: sanitize path / script name ?
ob_start();
include $scriptPath;
$content = ob_get_contents();
@ob_end_clean();
}
return $content;
}
/**
* FIXME: Replace with non static code
*
* @return array
* @throws \OCP\Files\NotFoundException
*/
protected function getStorageInfo(string $dir = '/') {
$rootInfo = \OC\Files\Filesystem::getFileInfo('/', false);
return \OC_Helper::getStorageInfo($dir, $rootInfo ?: null);
}
/**
* @NoCSRFRequired
* @NoAdminRequired
*
* @param string $fileid
* @return TemplateResponse|RedirectResponse
*/
public function showFile(string $fileid = null): Response {
if (!$fileid) {
return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
}
// This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
try {
return $this->redirectToFile((int) $fileid);
} catch (NotFoundException $e) {
return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
}
}
/**
* @NoCSRFRequired
* @NoAdminRequired
* @UseSession
*
* @param string $dir
* @param string $view
* @param string $fileid
* @param bool $fileNotFound
* @return TemplateResponse|RedirectResponse
*/
public function indexView($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
return $this->index($dir, $view, $fileid, $fileNotFound);
}
/**
* @NoCSRFRequired
* @NoAdminRequired
* @UseSession
*
* @param string $dir
* @param string $view
* @param string $fileid
* @param bool $fileNotFound
* @return TemplateResponse|RedirectResponse
*/
public function indexViewFileid($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
return $this->index($dir, $view, $fileid, $fileNotFound);
}
/**
* @NoCSRFRequired
* @NoAdminRequired
* @UseSession
*
* @param string $dir
* @param string $view
* @param string $fileid
* @param bool $fileNotFound
* @return TemplateResponse|RedirectResponse
*/
public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
if ($fileid !== null && $view !== 'trashbin') {
try {
return $this->redirectToFileIfInTrashbin((int) $fileid);
} catch (NotFoundException $e) {
}
}
// Load the files we need
\OCP\Util::addInitScript('files', 'init');
\OCP\Util::addStyle('files', 'merged');
\OCP\Util::addScript('files', 'main');
$userId = $this->userSession->getUser()->getUID();
// Get all the user favorites to create a submenu
try {
$userFolder = $this->rootFolder->getUserFolder($userId);
$favElements = $this->activityHelper->getFavoriteNodes($userId, true);
$favElements = array_map(fn (Folder $node) => [
'fileid' => $node->getId(),
'path' => $userFolder->getRelativePath($node->getPath()),
], $favElements);
} catch (\RuntimeException $e) {
$favElements = [];
}
// If the file doesn't exists in the folder and
// exists in only one occurrence, redirect to that file
// in the correct folder
if ($fileid && $dir !== '') {
$baseFolder = $this->rootFolder->getUserFolder($userId);
$nodes = $baseFolder->getById((int) $fileid);
if (!empty($nodes)) {
$nodePath = $baseFolder->getRelativePath($nodes[0]->getPath());
$relativePath = $nodePath ? dirname($nodePath) : '';
// If the requested path does not contain the file id
// or if the requested path is not the file id itself
if (count($nodes) === 1 && $relativePath !== $dir && $nodePath !== $dir) {
return $this->redirectToFile((int) $fileid);
}
} else { // fileid does not exist anywhere
$fileNotFound = true;
}
}
try {
// If view is files, we use the directory, otherwise we use the root storage
$storageInfo = $this->getStorageInfo(($view === 'files' && $dir) ? $dir : '/');
} catch(\Exception $e) {
$storageInfo = $this->getStorageInfo();
}
$this->initialState->provideInitialState('storageStats', $storageInfo);
$this->initialState->provideInitialState('config', $this->userConfig->getConfigs());
$this->initialState->provideInitialState('viewConfigs', $this->viewConfig->getConfigs());
$this->initialState->provideInitialState('favoriteFolders', $favElements);
// File sorting user config
$filesSortingConfig = json_decode($this->config->getUserValue($userId, 'files', 'files_sorting_configs', '{}'), true);
$this->initialState->provideInitialState('filesSortingConfig', $filesSortingConfig);
// Forbidden file characters
/** @var string[] */
$forbiddenCharacters = $this->config->getSystemValue('forbidden_chars', []);
$this->initialState->provideInitialState('forbiddenCharacters', Constants::FILENAME_INVALID_CHARS . implode('', $forbiddenCharacters));
$event = new LoadAdditionalScriptsEvent();
$this->eventDispatcher->dispatchTyped($event);
$this->eventDispatcher->dispatchTyped(new ResourcesLoadAdditionalScriptsEvent());
$this->eventDispatcher->dispatchTyped(new LoadSidebar());
// Load Viewer scripts
if (class_exists(LoadViewer::class)) {
$this->eventDispatcher->dispatchTyped(new LoadViewer());
}
$this->initialState->provideInitialState('templates_path', $this->templateManager->hasTemplateDirectory() ? $this->templateManager->getTemplatePath() : false);
$this->initialState->provideInitialState('templates', $this->templateManager->listCreators());
$response = new TemplateResponse(
Application::APP_ID,
'index',
);
$policy = new ContentSecurityPolicy();
$policy->addAllowedFrameDomain('\'self\'');
// Allow preview service worker
$policy->addAllowedWorkerSrcDomain('\'self\'');
$response->setContentSecurityPolicy($policy);
$this->provideInitialState($dir, $fileid);
return $response;
}
/**
* Add openFileInfo in initialState.
* @param string $dir - the ?dir= URL param
* @param string $fileid - the fileid URL param
* @return void
*/
private function provideInitialState(string $dir, ?string $fileid): void {
if ($fileid === null) {
return;
}
$user = $this->userSession->getUser();
if ($user === null) {
return;
}
$uid = $user->getUID();
$userFolder = $this->rootFolder->getUserFolder($uid);
$nodes = $userFolder->getById((int) $fileid);
$node = array_shift($nodes);
if ($node === null) {
return;
}
// properly format full path and make sure
// we're relative to the user home folder
$isRoot = $node === $userFolder;
$path = $userFolder->getRelativePath($node->getPath());
$directory = $userFolder->getRelativePath($node->getParent()->getPath());
// Prevent opening a file from another folder.
if ($dir !== $directory) {
return;
}
$this->initialState->provideInitialState(
'openFileInfo', [
'id' => $node->getId(),
'name' => $isRoot ? '' : $node->getName(),
'path' => $path,
'directory' => $directory,
'mime' => $node->getMimetype(),
'type' => $node->getType(),
'permissions' => $node->getPermissions(),
]
);
}
/**
* Redirects to the trashbin file list and highlight the given file id
*
* @param int $fileId file id to show
* @return RedirectResponse redirect response or not found response
* @throws NotFoundException
*/
private function redirectToFileIfInTrashbin($fileId): RedirectResponse {
$uid = $this->userSession->getUser()->getUID();
$baseFolder = $this->rootFolder->getUserFolder($uid);
$nodes = $baseFolder->getById($fileId);
$params = [];
if (empty($nodes) && $this->appManager->isEnabledForUser('files_trashbin')) {
/** @var Folder */
$baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
$nodes = $baseFolder->getById($fileId);
$params['view'] = 'trashbin';
if (!empty($nodes)) {
$node = current($nodes);
$params['fileid'] = $fileId;
if ($node instanceof Folder) {
// set the full path to enter the folder
$params['dir'] = $baseFolder->getRelativePath($node->getPath());
} else {
// set parent path as dir
$params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
}
return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
}
}
throw new NotFoundException();
}
/**
* Redirects to the file list and highlight the given file id
*
* @param int $fileId file id to show
* @return RedirectResponse redirect response or not found response
* @throws NotFoundException
*/
private function redirectToFile(int $fileId) {
$uid = $this->userSession->getUser()->getUID();
$baseFolder = $this->rootFolder->getUserFolder($uid);
$nodes = $baseFolder->getById($fileId);
$params = ['view' => 'files'];
try {
$this->redirectToFileIfInTrashbin($fileId);
} catch (NotFoundException $e) {
}
if (!empty($nodes)) {
$node = current($nodes);
$params['fileid'] = $fileId;
if ($node instanceof Folder) {
// set the full path to enter the folder
$params['dir'] = $baseFolder->getRelativePath($node->getPath());
} else {
// set parent path as dir
$params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
}
return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
}
throw new NotFoundException();
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @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\Db;
use OCP\AppFramework\Db\Entity;
/**
* @method void setUserId(string $userId)
* @method string getUserId()
* @method void setPathHash(string $pathHash)
* @method string getPathHash()
* @method void setExpirationTime(int $expirationTime)
* @method int getExpirationTime()
* @method void setToken(string $token)
* @method string getToken()
*/
class OpenLocalEditor extends Entity {
/** @var string */
protected $userId;
/** @var string */
protected $pathHash;
/** @var int */
protected $expirationTime;
/** @var string */
protected $token;
public function __construct() {
$this->addType('userId', 'string');
$this->addType('pathHash', 'string');
$this->addType('expirationTime', 'integer');
$this->addType('token', 'string');
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @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\Db;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\AppFramework\Db\QBMapper;
use OCP\DB\Exception;
use OCP\IDBConnection;
/**
* @template-extends QBMapper<OpenLocalEditor>
*/
class OpenLocalEditorMapper extends QBMapper {
public function __construct(IDBConnection $db) {
parent::__construct($db, 'open_local_editor', OpenLocalEditor::class);
}
/**
* @throws DoesNotExistException
* @throws MultipleObjectsReturnedException
* @throws Exception
*/
public function verifyToken(string $userId, string $pathHash, string $token): OpenLocalEditor {
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from($this->getTableName())
->where($qb->expr()->eq('user_id', $qb->createNamedParameter($userId)))
->andWhere($qb->expr()->eq('path_hash', $qb->createNamedParameter($pathHash)))
->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)));
return $this->findEntity($qb);
}
public function deleteExpiredTokens(int $time): void {
$qb = $this->db->getQueryBuilder();
$qb->delete($this->getTableName())
->where($qb->expr()->lt('expiration_time', $qb->createNamedParameter($time)));
$qb->executeStatement();
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.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\Db;
use OCP\AppFramework\Db\Entity;
/**
* @method void setSourceUser(string $uid)
* @method string getSourceUser()
* @method void setTargetUser(string $uid)
* @method string getTargetUser()
* @method void setFileId(int $fileId)
* @method int getFileId()
* @method void setNodeName(string $name)
* @method string getNodeName()
*/
class TransferOwnership extends Entity {
/** @var string */
protected $sourceUser;
/** @var string */
protected $targetUser;
/** @var integer */
protected $fileId;
/** @var string */
protected $nodeName;
public function __construct() {
$this->addType('sourceUser', 'string');
$this->addType('targetUser', 'string');
$this->addType('fileId', 'integer');
$this->addType('nodeName', 'string');
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Joas Schilling <coding@schilljs.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\Db;
use OCP\AppFramework\Db\QBMapper;
use OCP\IDBConnection;
/**
* @template-extends QBMapper<TransferOwnership>
*/
class TransferOwnershipMapper extends QBMapper {
public function __construct(IDBConnection $db) {
parent::__construct($db, 'user_transfer_owner', TransferOwnership::class);
}
public function getById(int $id): TransferOwnership {
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from($this->getTableName())
->where(
$qb->expr()->eq('id', $qb->createNamedParameter($id))
);
return $this->findEntity($qb);
}
}
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
*
* @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;
use OCA\Files\Service\DirectEditingService;
use OCP\Capabilities\ICapability;
use OCP\Capabilities\IInitialStateExcludedCapability;
use OCP\IURLGenerator;
class DirectEditingCapabilities implements ICapability, IInitialStateExcludedCapability {
protected DirectEditingService $directEditingService;
protected IURLGenerator $urlGenerator;
public function __construct(DirectEditingService $directEditingService, IURLGenerator $urlGenerator) {
$this->directEditingService = $directEditingService;
$this->urlGenerator = $urlGenerator;
}
/**
* @return array{files: array{directEditing: array{url: string, etag: string, supportsFileId: bool}}}
*/
public function getCapabilities() {
return [
'files' => [
'directEditing' => [
'url' => $this->urlGenerator->linkToOCSRouteAbsolute('files.DirectEditing.info'),
'etag' => $this->directEditingService->getDirectEditingETag(),
'supportsFileId' => true,
]
],
];
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @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\Event;
use OCP\EventDispatcher\Event;
/**
* This event is triggered when the files app is rendered.
*
* @since 17.0.0
*/
class LoadAdditionalScriptsEvent extends Event {
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author John Molakvoæ <skjnldsv@protonmail.com>
*
* @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\Event;
use OCP\EventDispatcher\Event;
class LoadSidebar extends Event {
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
/**
* @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @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\Exception;
use Exception;
class TransferOwnershipException extends Exception {
}
+273
View File
@@ -0,0 +1,273 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Björn Schießle <bjoern@schiessle.org>
* @author brumsel <brumsel@losecatcher.de>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Michael Jobst <mjobst+github@tecratech.de>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Robin McCorkell <robin@mccorkell.me.uk>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Vincent Petry <vincent@nextcloud.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;
use OCP\Files\FileInfo;
use OCP\ITagManager;
/**
* Helper class for manipulating file information
*/
class Helper {
/**
* @param string $dir
* @return array
* @throws \OCP\Files\NotFoundException
*/
public static function buildFileStorageStatistics($dir) {
// information about storage capacities
$storageInfo = \OC_Helper::getStorageInfo($dir);
$l = \OC::$server->getL10N('files');
$maxUploadFileSize = \OCP\Util::maxUploadFilesize($dir, $storageInfo['free']);
$maxHumanFileSize = \OCP\Util::humanFileSize($maxUploadFileSize);
$maxHumanFileSize = $l->t('Upload (max. %s)', [$maxHumanFileSize]);
return [
'uploadMaxFilesize' => $maxUploadFileSize,
'maxHumanFilesize' => $maxHumanFileSize,
'freeSpace' => $storageInfo['free'],
'quota' => $storageInfo['quota'],
'total' => $storageInfo['total'],
'used' => $storageInfo['used'],
'usedSpacePercent' => $storageInfo['relative'],
'owner' => $storageInfo['owner'],
'ownerDisplayName' => $storageInfo['ownerDisplayName'],
'mountType' => $storageInfo['mountType'],
'mountPoint' => $storageInfo['mountPoint'],
];
}
/**
* Determine icon for a given file
*
* @param \OCP\Files\FileInfo $file file info
* @return string icon URL
*/
public static function determineIcon($file) {
if ($file['type'] === 'dir') {
$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir');
// TODO: move this part to the client side, using mountType
if ($file->isShared()) {
$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-shared');
} elseif ($file->isMounted()) {
$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-external');
}
} else {
$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($file->getMimetype());
}
return substr($icon, 0, -3) . 'svg';
}
/**
* Comparator function to sort files alphabetically and have
* the directories appear first
*
* @param \OCP\Files\FileInfo $a file
* @param \OCP\Files\FileInfo $b file
* @return int -1 if $a must come before $b, 1 otherwise
*/
public static function compareFileNames(FileInfo $a, FileInfo $b) {
$aType = $a->getType();
$bType = $b->getType();
if ($aType === 'dir' and $bType !== 'dir') {
return -1;
} elseif ($aType !== 'dir' and $bType === 'dir') {
return 1;
} else {
return \OCP\Util::naturalSortCompare($a->getName(), $b->getName());
}
}
/**
* Comparator function to sort files by date
*
* @param \OCP\Files\FileInfo $a file
* @param \OCP\Files\FileInfo $b file
* @return int -1 if $a must come before $b, 1 otherwise
*/
public static function compareTimestamp(FileInfo $a, FileInfo $b) {
$aTime = $a->getMTime();
$bTime = $b->getMTime();
return ($aTime < $bTime) ? -1 : 1;
}
/**
* Comparator function to sort files by size
*
* @param \OCP\Files\FileInfo $a file
* @param \OCP\Files\FileInfo $b file
* @return int -1 if $a must come before $b, 1 otherwise
*/
public static function compareSize(FileInfo $a, FileInfo $b) {
$aSize = $a->getSize();
$bSize = $b->getSize();
return ($aSize < $bSize) ? -1 : 1;
}
/**
* Formats the file info to be returned as JSON to the client.
*
* @param \OCP\Files\FileInfo $i
* @return array formatted file info
*/
public static function formatFileInfo(FileInfo $i) {
$entry = [];
$entry['id'] = $i['fileid'];
$entry['parentId'] = $i['parent'];
$entry['mtime'] = $i['mtime'] * 1000;
// only pick out the needed attributes
$entry['name'] = $i->getName();
$entry['permissions'] = $i['permissions'];
$entry['mimetype'] = $i['mimetype'];
$entry['size'] = $i['size'];
$entry['type'] = $i['type'];
$entry['etag'] = $i['etag'];
if (isset($i['tags'])) {
$entry['tags'] = $i['tags'];
}
if (isset($i['displayname_owner'])) {
$entry['shareOwner'] = $i['displayname_owner'];
}
if (isset($i['is_share_mount_point'])) {
$entry['isShareMountPoint'] = $i['is_share_mount_point'];
}
$mountType = null;
$mount = $i->getMountPoint();
$mountType = $mount->getMountType();
if ($mountType !== '') {
if ($i->getInternalPath() === '') {
$mountType .= '-root';
}
$entry['mountType'] = $mountType;
}
if (isset($i['extraData'])) {
$entry['extraData'] = $i['extraData'];
}
return $entry;
}
/**
* Format file info for JSON
* @param \OCP\Files\FileInfo[] $fileInfos file infos
* @return array
*/
public static function formatFileInfos($fileInfos) {
$files = [];
foreach ($fileInfos as $i) {
$files[] = self::formatFileInfo($i);
}
return $files;
}
/**
* Retrieves the contents of the given directory and
* returns it as a sorted array of FileInfo.
*
* @param string $dir path to the directory
* @param string $sortAttribute attribute to sort on
* @param bool $sortDescending true for descending sort, false otherwise
* @param string $mimetypeFilter limit returned content to this mimetype or mimepart
* @return \OCP\Files\FileInfo[] files
*/
public static function getFiles($dir, $sortAttribute = 'name', $sortDescending = false, $mimetypeFilter = '') {
$content = \OC\Files\Filesystem::getDirectoryContent($dir, $mimetypeFilter);
return self::sortFiles($content, $sortAttribute, $sortDescending);
}
/**
* Populate the result set with file tags
*
* @param array $fileList
* @param string $fileIdentifier identifier attribute name for values in $fileList
* @param ITagManager $tagManager
* @return array file list populated with tags
*/
public static function populateTags(array $fileList, $fileIdentifier, ITagManager $tagManager) {
$ids = [];
foreach ($fileList as $fileData) {
$ids[] = $fileData[$fileIdentifier];
}
$tagger = $tagManager->load('files');
$tags = $tagger->getTagsForObjects($ids);
if (!is_array($tags)) {
throw new \UnexpectedValueException('$tags must be an array');
}
// Set empty tag array
foreach ($fileList as $key => $fileData) {
$fileList[$key]['tags'] = [];
}
if (!empty($tags)) {
foreach ($tags as $fileId => $fileTags) {
foreach ($fileList as $key => $fileData) {
if ($fileId !== $fileData[$fileIdentifier]) {
continue;
}
$fileList[$key]['tags'] = $fileTags;
}
}
}
return $fileList;
}
/**
* Sort the given file info array
*
* @param \OCP\Files\FileInfo[] $files files to sort
* @param string $sortAttribute attribute to sort on
* @param bool $sortDescending true for descending sort, false otherwise
* @return \OCP\Files\FileInfo[] sorted files
*/
public static function sortFiles($files, $sortAttribute = 'name', $sortDescending = false) {
$sortFunc = 'compareFileNames';
if ($sortAttribute === 'mtime') {
$sortFunc = 'compareTimestamp';
} elseif ($sortAttribute === 'size') {
$sortFunc = 'compareSize';
}
usort($files, [Helper::class, $sortFunc]);
if ($sortDescending) {
$files = array_reverse($files);
}
return $files;
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, John Molakvoæ <skjnldsv@protonmail.com>
*
* @author John Molakvoæ <skjnldsv@protonmail.com>
*
* @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\Listener;
use OCA\Files\AppInfo\Application;
use OCA\Files\Event\LoadSidebar;
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;
}
Util::addScript(Application::APP_ID, 'sidebar');
// needed by the Sidebar legacy tabs
// TODO: remove when all tabs migrated to the new api
Util::addScript('files', 'fileinfomodel');
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
*
* @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\Listener;
use OCP\Collaboration\Reference\RenderReferenceEvent;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
class RenderReferenceEventListener implements IEventListener {
public function handle(Event $event): void {
if (!$event instanceof RenderReferenceEvent) {
return;
}
\OCP\Util::addScript('files', 'reference-files');
}
}
@@ -0,0 +1,277 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Louis Chemineau <louis@chmn.me>
*
* @author Louis Chemineau <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\Listener;
use OCA\Files_Trashbin\Events\BeforeNodeRestoredEvent;
use OCA\Files_Trashbin\Trash\ITrashItem;
use OCA\Files_Trashbin\Trash\ITrashManager;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Files\Cache\CacheEntryRemovedEvent;
use OCP\Files\Events\Node\BeforeNodeDeletedEvent;
use OCP\Files\Events\Node\BeforeNodeRenamedEvent;
use OCP\Files\Folder;
use OCP\Files\Node;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\FilesMetadata\Exceptions\FilesMetadataNotFoundException;
use OCP\FilesMetadata\IFilesMetadataManager;
use OCP\IUserSession;
/**
* @template-implements IEventListener<Event>
*/
class SyncLivePhotosListener implements IEventListener {
/** @var Array<int, string> */
private array $pendingRenames = [];
/** @var Array<int, bool> */
private array $pendingDeletion = [];
/** @var Array<int, bool> */
private array $pendingRestores = [];
public function __construct(
private ?Folder $userFolder,
private ?IUserSession $userSession,
private ITrashManager $trashManager,
private IFilesMetadataManager $filesMetadataManager,
) {
}
public function handle(Event $event): void {
if ($this->userFolder === null || $this->userSession === null) {
return;
}
$peerFile = null;
if ($event instanceof BeforeNodeRenamedEvent) {
$peerFile = $this->getLivePhotoPeer($event->getSource()->getId());
} elseif ($event instanceof BeforeNodeRestoredEvent) {
$peerFile = $this->getLivePhotoPeer($event->getSource()->getId());
} elseif ($event instanceof BeforeNodeDeletedEvent) {
$peerFile = $this->getLivePhotoPeer($event->getNode()->getId());
} elseif ($event instanceof CacheEntryRemovedEvent) {
$peerFile = $this->getLivePhotoPeer($event->getFileId());
}
if ($peerFile === null) {
return; // not a Live Photo
}
if ($event instanceof BeforeNodeRenamedEvent) {
$this->handleMove($event, $peerFile);
} elseif ($event instanceof BeforeNodeDeletedEvent) {
$this->handleDeletion($event, $peerFile);
} elseif ($event instanceof CacheEntryRemovedEvent) {
$peerFile->delete();
} elseif ($event instanceof BeforeNodeRestoredEvent) {
$this->handleRestore($event, $peerFile);
}
}
/**
* During rename events, which also include move operations,
* we rename the peer file using the same name.
* The event listener being singleton, we can store the current state
* of pending renames inside the 'pendingRenames' property,
* to prevent infinite recursive.
*/
private function handleMove(BeforeNodeRenamedEvent $event, Node $peerFile): void {
$sourceFile = $event->getSource();
$targetFile = $event->getTarget();
$targetParent = $targetFile->getParent();
$sourceExtension = $sourceFile->getExtension();
$peerFileExtension = $peerFile->getExtension();
$targetName = $targetFile->getName();
$targetPath = $targetFile->getPath();
if (!str_ends_with($targetName, ".".$sourceExtension)) {
$event->abortOperation(new NotPermittedException("Cannot change the extension of a Live Photo"));
}
try {
$targetParent->get($targetName);
$event->abortOperation(new NotPermittedException("A file already exist at destination path of the Live Photo"));
} catch (NotFoundException $ex) {
}
$peerTargetName = substr($targetName, 0, -strlen($sourceExtension)) . $peerFileExtension;
try {
$targetParent->get($peerTargetName);
$event->abortOperation(new NotPermittedException("A file already exist at destination path of the Live Photo"));
} catch (NotFoundException $ex) {
}
// in case the rename was initiated from this listener, we stop right now
if (array_key_exists($peerFile->getId(), $this->pendingRenames)) {
return;
}
$this->pendingRenames[$sourceFile->getId()] = $targetPath;
try {
$peerFile->move($targetParent->getPath() . '/' . $peerTargetName);
} catch (\Throwable $ex) {
$event->abortOperation($ex);
}
unset($this->pendingRenames[$sourceFile->getId()]);
}
/**
* During deletion event, we trigger another recursive delete on the peer file.
* Delete operations on the .mov file directly are currently blocked.
* The event listener being singleton, we can store the current state
* of pending deletions inside the 'pendingDeletions' property,
* to prevent infinite recursivity.
*/
private function handleDeletion(BeforeNodeDeletedEvent $event, Node $peerFile): void {
$deletedFile = $event->getNode();
if ($deletedFile->getMimetype() === 'video/quicktime') {
if (isset($this->pendingDeletion[$peerFile->getId()])) {
unset($this->pendingDeletion[$peerFile->getId()]);
return;
} else {
$event->abortOperation(new NotPermittedException("Cannot delete the video part of a live photo"));
}
} else {
$this->pendingDeletion[$deletedFile->getId()] = true;
try {
$peerFile->delete();
} catch (\Throwable $ex) {
$event->abortOperation($ex);
}
}
return;
}
/**
* During restore event, we trigger another recursive restore on the peer file.
* Restore operations on the .mov file directly are currently blocked.
* The event listener being singleton, we can store the current state
* of pending restores inside the 'pendingRestores' property,
* to prevent infinite recursivity.
*/
private function handleRestore(BeforeNodeRestoredEvent $event, Node $peerFile): void {
$sourceFile = $event->getSource();
if ($sourceFile->getMimetype() === 'video/quicktime') {
if (isset($this->pendingRestores[$peerFile->getId()])) {
unset($this->pendingRestores[$peerFile->getId()]);
return;
} else {
$event->abortOperation(new NotPermittedException("Cannot restore the video part of a live photo"));
}
} else {
$user = $this->userSession->getUser();
if ($user === null) {
return;
}
$peerTrashItem = $this->trashManager->getTrashNodeById($user, $peerFile->getId());
// Peer file is not in the bin, no need to restore it.
if ($peerTrashItem === null) {
return;
}
$trashRoot = $this->trashManager->listTrashRoot($user);
$trashItem = $this->getTrashItem($trashRoot, $peerFile->getInternalPath());
if ($trashItem === null) {
$event->abortOperation(new NotFoundException("Couldn't find peer file in trashbin"));
}
$this->pendingRestores[$sourceFile->getId()] = true;
try {
$this->trashManager->restoreItem($trashItem);
} catch (\Throwable $ex) {
$event->abortOperation($ex);
}
}
}
/**
* Helper method to get the associated live photo file.
* We first look for it in the user folder, and if we
* cannot find it here, we look for it in the user's trashbin.
*/
private function getLivePhotoPeer(int $nodeId): ?Node {
if ($this->userFolder === null || $this->userSession === null) {
return null;
}
try {
$metadata = $this->filesMetadataManager->getMetadata($nodeId);
} catch (FilesMetadataNotFoundException $ex) {
return null;
}
if (!$metadata->hasKey('files-live-photo')) {
return null;
}
$peerFileId = (int)$metadata->getString('files-live-photo');
// Check the user's folder.
$nodes = $this->userFolder->getById($peerFileId);
if (count($nodes) !== 0) {
return $nodes[0];
}
// Check the user's trashbin.
$user = $this->userSession->getUser();
if ($user !== null) {
$peerFile = $this->trashManager->getTrashNodeById($user, $peerFileId);
if ($peerFile !== null) {
return $peerFile;
}
}
$metadata->unset('files-live-photo');
return null;
}
/**
* There is currently no method to restore a file based on its fileId or path.
* So we have to manually find a ITrashItem from the trash item list.
* TODO: This should be replaced by a proper method in the TrashManager.
*/
private function getTrashItem(array $trashFolder, string $path): ?ITrashItem {
foreach($trashFolder as $trashItem) {
if (str_starts_with($path, "files_trashbin/files".$trashItem->getTrashPath())) {
if ($path === "files_trashbin/files".$trashItem->getTrashPath()) {
return $trashItem;
}
if ($trashItem instanceof Folder) {
$node = $this->getTrashItem($trashItem->getDirectoryListing(), $path);
if ($node !== null) {
return $node;
}
}
}
}
return null;
}
}
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Joas Schilling <coding@schilljs.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\Migration;
use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
class Version11301Date20191205150729 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) {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();
$table = $schema->createTable('user_transfer_owner');
$table->addColumn('id', 'bigint', [
'autoincrement' => true,
'notnull' => true,
'length' => 20,
'unsigned' => true,
]);
$table->addColumn('source_user', 'string', [
'notnull' => true,
'length' => 64,
]);
$table->addColumn('target_user', 'string', [
'notnull' => true,
'length' => 64,
]);
$table->addColumn('file_id', 'bigint', [
'notnull' => true,
'length' => 20,
]);
$table->addColumn('node_name', 'string', [
'notnull' => true,
'length' => 255,
]);
$table->setPrimaryKey(['id']);
// Quite radical, we just assume no one updates cross beta with a pending request.
// Do not try this at home
if ($schema->hasTable('user_transfer_ownership')) {
$schema->dropTable('user_transfer_ownership');
}
return $schema;
}
}
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @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\Migration;
use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
class Version12101Date20221011153334 extends SimpleMigrationStep {
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();
$table = $schema->createTable('open_local_editor');
$table->addColumn('id', Types::BIGINT, [
'autoincrement' => true,
'notnull' => true,
'length' => 20,
'unsigned' => true,
]);
$table->addColumn('user_id', Types::STRING, [
'notnull' => true,
'length' => 64,
]);
$table->addColumn('path_hash', Types::STRING, [
'notnull' => true,
'length' => 64,
]);
$table->addColumn('expiration_time', Types::BIGINT, [
'notnull' => true,
'unsigned' => true,
]);
$table->addColumn('token', Types::STRING, [
'notnull' => true,
'length' => 128,
]);
$table->setPrimaryKey(['id']);
$table->addUniqueIndex(['user_id', 'path_hash', 'token'], 'openlocal_user_path_token');
return $schema;
}
}
@@ -0,0 +1,295 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Joas Schilling <coding@schilljs.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Sascha Wiswedel <sascha.wiswedel@nextcloud.com>
*
* @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\Notification;
use OCA\Files\Db\TransferOwnershipMapper;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
use OCP\L10N\IFactory;
use OCP\Notification\IAction;
use OCP\Notification\IDismissableNotifier;
use OCP\Notification\IManager;
use OCP\Notification\INotification;
use OCP\Notification\INotifier;
class Notifier implements INotifier, IDismissableNotifier {
/** @var IFactory */
protected $l10nFactory;
/** @var IURLGenerator */
protected $urlGenerator;
/** @var TransferOwnershipMapper */
private $mapper;
/** @var IManager */
private $notificationManager;
/** @var IUserManager */
private $userManager;
/** @var ITimeFactory */
private $timeFactory;
public function __construct(IFactory $l10nFactory,
IURLGenerator $urlGenerator,
TransferOwnershipMapper $mapper,
IManager $notificationManager,
IUserManager $userManager,
ITimeFactory $timeFactory) {
$this->l10nFactory = $l10nFactory;
$this->urlGenerator = $urlGenerator;
$this->mapper = $mapper;
$this->notificationManager = $notificationManager;
$this->userManager = $userManager;
$this->timeFactory = $timeFactory;
}
public function getID(): string {
return 'files';
}
public function getName(): string {
return $this->l10nFactory->get('files')->t('Files');
}
/**
* @param INotification $notification
* @param string $languageCode The code of the language that should be used to prepare the notification
* @return INotification
* @throws \InvalidArgumentException When the notification was not prepared by a notifier
*/
public function prepare(INotification $notification, string $languageCode): INotification {
if ($notification->getApp() !== 'files') {
throw new \InvalidArgumentException('Unhandled app');
}
if ($notification->getSubject() === 'transferownershipRequest') {
return $this->handleTransferownershipRequest($notification, $languageCode);
}
if ($notification->getSubject() === 'transferOwnershipFailedSource') {
return $this->handleTransferOwnershipFailedSource($notification, $languageCode);
}
if ($notification->getSubject() === 'transferOwnershipFailedTarget') {
return $this->handleTransferOwnershipFailedTarget($notification, $languageCode);
}
if ($notification->getSubject() === 'transferOwnershipDoneSource') {
return $this->handleTransferOwnershipDoneSource($notification, $languageCode);
}
if ($notification->getSubject() === 'transferOwnershipDoneTarget') {
return $this->handleTransferOwnershipDoneTarget($notification, $languageCode);
}
throw new \InvalidArgumentException('Unhandled subject');
}
public function handleTransferownershipRequest(INotification $notification, string $languageCode): INotification {
$l = $this->l10nFactory->get('files', $languageCode);
$id = $notification->getObjectId();
$param = $notification->getSubjectParameters();
$approveAction = $notification->createAction()
->setParsedLabel($l->t('Accept'))
->setPrimary(true)
->setLink(
$this->urlGenerator->getAbsoluteURL(
$this->urlGenerator->linkTo(
'',
'ocs/v2.php/apps/files/api/v1/transferownership/' . $id
)
),
IAction::TYPE_POST
);
$disapproveAction = $notification->createAction()
->setParsedLabel($l->t('Reject'))
->setPrimary(false)
->setLink(
$this->urlGenerator->getAbsoluteURL(
$this->urlGenerator->linkTo(
'',
'ocs/v2.php/apps/files/api/v1/transferownership/' . $id
)
),
IAction::TYPE_DELETE
);
$sourceUser = $this->getUser($param['sourceUser']);
$notification->addParsedAction($approveAction)
->addParsedAction($disapproveAction)
->setRichSubject(
$l->t('Incoming ownership transfer from {user}'),
[
'user' => [
'type' => 'user',
'id' => $sourceUser->getUID(),
'name' => $sourceUser->getDisplayName(),
],
])
->setRichMessage(
$l->t("Do you want to accept {path}?\n\nNote: The transfer process after accepting may take up to 1 hour."),
[
'path' => [
'type' => 'highlight',
'id' => $param['targetUser'] . '::' . $param['nodeName'],
'name' => $param['nodeName'],
]
]);
return $notification;
}
public function handleTransferOwnershipFailedSource(INotification $notification, string $languageCode): INotification {
$l = $this->l10nFactory->get('files', $languageCode);
$param = $notification->getSubjectParameters();
$targetUser = $this->getUser($param['targetUser']);
$notification->setRichSubject($l->t('Ownership transfer failed'))
->setRichMessage(
$l->t('Your ownership transfer of {path} to {user} failed.'),
[
'path' => [
'type' => 'highlight',
'id' => $param['targetUser'] . '::' . $param['nodeName'],
'name' => $param['nodeName'],
],
'user' => [
'type' => 'user',
'id' => $targetUser->getUID(),
'name' => $targetUser->getDisplayName(),
],
]);
return $notification;
}
public function handleTransferOwnershipFailedTarget(INotification $notification, string $languageCode): INotification {
$l = $this->l10nFactory->get('files', $languageCode);
$param = $notification->getSubjectParameters();
$sourceUser = $this->getUser($param['sourceUser']);
$notification->setRichSubject($l->t('Ownership transfer failed'))
->setRichMessage(
$l->t('The ownership transfer of {path} from {user} failed.'),
[
'path' => [
'type' => 'highlight',
'id' => $param['sourceUser'] . '::' . $param['nodeName'],
'name' => $param['nodeName'],
],
'user' => [
'type' => 'user',
'id' => $sourceUser->getUID(),
'name' => $sourceUser->getDisplayName(),
],
]);
return $notification;
}
public function handleTransferOwnershipDoneSource(INotification $notification, string $languageCode): INotification {
$l = $this->l10nFactory->get('files', $languageCode);
$param = $notification->getSubjectParameters();
$targetUser = $this->getUser($param['targetUser']);
$notification->setRichSubject($l->t('Ownership transfer done'))
->setRichMessage(
$l->t('Your ownership transfer of {path} to {user} has completed.'),
[
'path' => [
'type' => 'highlight',
'id' => $param['targetUser'] . '::' . $param['nodeName'],
'name' => $param['nodeName'],
],
'user' => [
'type' => 'user',
'id' => $targetUser->getUID(),
'name' => $targetUser->getDisplayName(),
],
]);
return $notification;
}
public function handleTransferOwnershipDoneTarget(INotification $notification, string $languageCode): INotification {
$l = $this->l10nFactory->get('files', $languageCode);
$param = $notification->getSubjectParameters();
$sourceUser = $this->getUser($param['sourceUser']);
$notification->setRichSubject($l->t('Ownership transfer done'))
->setRichMessage(
$l->t('The ownership transfer of {path} from {user} has completed.'),
[
'path' => [
'type' => 'highlight',
'id' => $param['sourceUser'] . '::' . $param['nodeName'],
'name' => $param['nodeName'],
],
'user' => [
'type' => 'user',
'id' => $sourceUser->getUID(),
'name' => $sourceUser->getDisplayName(),
],
]);
return $notification;
}
public function dismissNotification(INotification $notification): void {
if ($notification->getApp() !== 'files') {
throw new \InvalidArgumentException('Unhandled app');
}
// TODO: This should all be moved to a service that also the transferownershipController uses.
try {
$transferOwnership = $this->mapper->getById((int)$notification->getObjectId());
} catch (DoesNotExistException $e) {
return;
}
$notification = $this->notificationManager->createNotification();
$notification->setUser($transferOwnership->getSourceUser())
->setApp('files')
->setDateTime($this->timeFactory->getDateTime())
->setSubject('transferownershipRequestDenied', [
'sourceUser' => $transferOwnership->getSourceUser(),
'targetUser' => $transferOwnership->getTargetUser(),
'nodeName' => $transferOwnership->getNodeName()
])
->setObject('transfer', (string)$transferOwnership->getId());
$this->notificationManager->notify($notification);
$this->mapper->delete($transferOwnership);
}
protected function getUser(string $userId): IUser {
$user = $this->userManager->get($userId);
if ($user instanceof IUser) {
return $user;
}
throw new \InvalidArgumentException('User not found');
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Kate Döen <kate.doeen@nextcloud.com>
*
* @author Kate Döen <kate.doeen@nextcloud.com>
*
* @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;
/**
* @psalm-type FilesTemplateFile = array{
* basename: string,
* etag: string,
* fileid: int,
* filename: ?string,
* lastmod: int,
* mime: string,
* size: int,
* type: string,
* hasPreview: bool,
* }
*
* @psalm-type FilesTemplateFileCreator = array{
* app: string,
* label: string,
* extension: string,
* iconClass: ?string,
* mimetypes: string[],
* ratio: ?float,
* actionLabel: string,
* }
*/
class ResponseDefinitions {
}
@@ -0,0 +1,236 @@
<?php
declare(strict_types=1);
/**
* @copyright 2020 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @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\Search;
use InvalidArgumentException;
use OC\Files\Search\SearchBinaryOperator;
use OC\Files\Search\SearchComparison;
use OC\Files\Search\SearchOrder;
use OC\Files\Search\SearchQuery;
use OC\Search\Filter\GroupFilter;
use OC\Search\Filter\UserFilter;
use OCP\Files\FileInfo;
use OCP\Files\IMimeTypeDetector;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\Files\Search\ISearchComparison;
use OCP\Files\Search\ISearchOperator;
use OCP\Files\Search\ISearchOrder;
use OCP\IL10N;
use OCP\IPreview;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\Search\FilterDefinition;
use OCP\Search\IFilter;
use OCP\Search\IFilteringProvider;
use OCP\Search\ISearchQuery;
use OCP\Search\SearchResult;
use OCP\Search\SearchResultEntry;
use OCP\Share\IShare;
class FilesSearchProvider implements IFilteringProvider {
/** @var IL10N */
private $l10n;
/** @var IURLGenerator */
private $urlGenerator;
/** @var IMimeTypeDetector */
private $mimeTypeDetector;
/** @var IRootFolder */
private $rootFolder;
public function __construct(
IL10N $l10n,
IURLGenerator $urlGenerator,
IMimeTypeDetector $mimeTypeDetector,
IRootFolder $rootFolder,
private IPreview $previewManager,
) {
$this->l10n = $l10n;
$this->urlGenerator = $urlGenerator;
$this->mimeTypeDetector = $mimeTypeDetector;
$this->rootFolder = $rootFolder;
}
/**
* @inheritDoc
*/
public function getId(): string {
return 'files';
}
/**
* @inheritDoc
*/
public function getName(): string {
return $this->l10n->t('Files');
}
/**
* @inheritDoc
*/
public function getOrder(string $route, array $routeParameters): int {
if ($route === 'files.View.index') {
// Before comments
return -5;
}
return 5;
}
public function getSupportedFilters(): array {
return [
'term',
'since',
'until',
'person',
'min-size',
'max-size',
'mime',
'type',
'is-favorite',
'title-only',
];
}
public function getAlternateIds(): array {
return [];
}
public function getCustomFilters(): array {
return [
new FilterDefinition('min-size', FilterDefinition::TYPE_INT),
new FilterDefinition('max-size', FilterDefinition::TYPE_INT),
new FilterDefinition('mime', FilterDefinition::TYPE_STRING),
new FilterDefinition('type', FilterDefinition::TYPE_STRING),
new FilterDefinition('is-favorite', FilterDefinition::TYPE_BOOL),
];
}
public function search(IUser $user, ISearchQuery $query): SearchResult {
$userFolder = $this->rootFolder->getUserFolder($user->getUID());
$fileQuery = $this->buildSearchQuery($query, $user);
return SearchResult::paginated(
$this->l10n->t('Files'),
array_map(function (Node $result) use ($userFolder) {
$thumbnailUrl = $this->previewManager->isMimeSupported($result->getMimetype())
? $this->urlGenerator->linkToRouteAbsolute('core.Preview.getPreviewByFileId', ['x' => 32, 'y' => 32, 'fileId' => $result->getId()])
: '';
$icon = $result->getMimetype() === FileInfo::MIMETYPE_FOLDER
? 'icon-folder'
: $this->mimeTypeDetector->mimeTypeIcon($result->getMimetype());
$path = $userFolder->getRelativePath($result->getPath());
// Use shortened link to centralize the various
// files/folder url redirection in files.View.showFile
$link = $this->urlGenerator->linkToRoute(
'files.View.showFile',
['fileid' => $result->getId()]
);
$searchResultEntry = new SearchResultEntry(
$thumbnailUrl,
$result->getName(),
$this->formatSubline($path),
$this->urlGenerator->getAbsoluteURL($link),
$icon,
);
$searchResultEntry->addAttribute('fileId', (string)$result->getId());
$searchResultEntry->addAttribute('path', $path);
return $searchResultEntry;
}, $userFolder->search($fileQuery)),
$query->getCursor() + $query->getLimit()
);
}
private function buildSearchQuery(ISearchQuery $query, IUser $user): SearchQuery {
$comparisons = [];
foreach ($query->getFilters() as $name => $filter) {
$comparisons[] = match ($name) {
'term' => new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', '%' . $filter->get() . '%'),
'since' => new SearchComparison(ISearchComparison::COMPARE_GREATER_THAN_EQUAL, 'mtime', $filter->get()->getTimestamp()),
'until' => new SearchComparison(ISearchComparison::COMPARE_LESS_THAN_EQUAL, 'mtime', $filter->get()->getTimestamp()),
'min-size' => new SearchComparison(ISearchComparison::COMPARE_GREATER_THAN_EQUAL, 'size', $filter->get()),
'max-size' => new SearchComparison(ISearchComparison::COMPARE_LESS_THAN_EQUAL, 'size', $filter->get()),
'mime' => new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', $filter->get()),
'type' => new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', $filter->get() . '/%'),
'person' => $this->buildPersonSearchQuery($filter),
default => throw new InvalidArgumentException('Unsupported comparison'),
};
}
return new SearchQuery(
new SearchBinaryOperator(SearchBinaryOperator::OPERATOR_AND, $comparisons),
$query->getLimit(),
(int) $query->getCursor(),
$query->getSortOrder() === ISearchQuery::SORT_DATE_DESC
? [new SearchOrder(ISearchOrder::DIRECTION_DESCENDING, 'mtime')]
: [],
$user
);
}
private function buildPersonSearchQuery(IFilter $person): ISearchOperator {
if ($person instanceof UserFilter) {
return new SearchBinaryOperator(SearchBinaryOperator::OPERATOR_OR, [
new SearchBinaryOperator(SearchBinaryOperator::OPERATOR_AND, [
new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'share_with', $person->get()->getUID()),
new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'share_type', IShare::TYPE_USER),
]),
new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'owner', $person->get()->getUID()),
]);
}
if ($person instanceof GroupFilter) {
return new SearchBinaryOperator(SearchBinaryOperator::OPERATOR_AND, [
new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'share_with', $person->get()->getGID()),
new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'share_type', IShare::TYPE_GROUP),
]);
}
throw new InvalidArgumentException('Unsupported filter type');
}
/**
* Format subline for files
*
* @param string $path
* @return string
*/
private function formatSubline(string $path): string {
// Do not show the location if the file is in root
if (strrpos($path, '/') > 0) {
$path = ltrim(dirname($path), '/');
return $this->l10n->t('in %s', [$path]);
} else {
return '';
}
}
}
@@ -0,0 +1,88 @@
<?php
/**
* @copyright Copyright (c) 2019 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
* @author Tobias Kaminsky <tobias@kaminsky.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\Service;
use OCP\DirectEditing\ACreateEmpty;
use OCP\DirectEditing\ACreateFromTemplate;
use OCP\DirectEditing\IEditor;
use OCP\DirectEditing\IManager;
use OCP\DirectEditing\RegisterDirectEditorEvent;
use OCP\EventDispatcher\IEventDispatcher;
class DirectEditingService {
/** @var IManager */
private $directEditingManager;
/** @var IEventDispatcher */
private $eventDispatcher;
public function __construct(IEventDispatcher $eventDispatcher, IManager $directEditingManager) {
$this->directEditingManager = $directEditingManager;
$this->eventDispatcher = $eventDispatcher;
}
public function getDirectEditingETag(): string {
return \md5(\json_encode($this->getDirectEditingCapabilitites()));
}
public function getDirectEditingCapabilitites(): array {
$this->eventDispatcher->dispatchTyped(new RegisterDirectEditorEvent($this->directEditingManager));
$capabilities = [
'editors' => [],
'creators' => []
];
if (!$this->directEditingManager->isEnabled()) {
return $capabilities;
}
/**
* @var string $id
* @var IEditor $editor
*/
foreach ($this->directEditingManager->getEditors() as $id => $editor) {
$capabilities['editors'][$id] = [
'id' => $editor->getId(),
'name' => $editor->getName(),
'mimetypes' => $editor->getMimetypes(),
'optionalMimetypes' => $editor->getMimetypesOptional(),
'secure' => $editor->isSecure(),
];
/** @var ACreateEmpty|ACreateFromTemplate $creator */
foreach ($editor->getCreators() as $creator) {
$id = $creator->getId();
$capabilities['creators'][$id] = [
'id' => $id,
'editor' => $editor->getId(),
'name' => $creator->getName(),
'extension' => $creator->getExtension(),
'templates' => $creator instanceof ACreateFromTemplate,
'mimetype' => $creator->getMimetype()
];
}
}
return $capabilities;
}
}
@@ -0,0 +1,517 @@
<?php
declare(strict_types=1);
/**
* @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Sascha Wiswedel <sascha.wiswedel@nextcloud.com>
* @author Tobia De Koninck <LEDfan@users.noreply.github.com>
*
* @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\Service;
use Closure;
use OC\Files\Filesystem;
use OC\Files\View;
use OCA\Files\Exception\TransferOwnershipException;
use OCP\Encryption\IManager as IEncryptionManager;
use OCP\Files\Config\IUserMountCache;
use OCP\Files\FileInfo;
use OCP\Files\IHomeStorage;
use OCP\Files\InvalidPathException;
use OCP\Files\Mount\IMountManager;
use OCP\IUser;
use OCP\IUserManager;
use OCP\Share\IManager as IShareManager;
use OCP\Share\IShare;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Output\OutputInterface;
use function array_merge;
use function basename;
use function count;
use function date;
use function is_dir;
use function rtrim;
class OwnershipTransferService {
/** @var IEncryptionManager */
private $encryptionManager;
/** @var IShareManager */
private $shareManager;
/** @var IMountManager */
private $mountManager;
/** @var IUserMountCache */
private $userMountCache;
/** @var IUserManager */
private $userManager;
public function __construct(IEncryptionManager $manager,
IShareManager $shareManager,
IMountManager $mountManager,
IUserMountCache $userMountCache,
IUserManager $userManager) {
$this->encryptionManager = $manager;
$this->shareManager = $shareManager;
$this->mountManager = $mountManager;
$this->userMountCache = $userMountCache;
$this->userManager = $userManager;
}
/**
* @param IUser $sourceUser
* @param IUser $destinationUser
* @param string $path
*
* @param OutputInterface|null $output
* @param bool $move
* @throws TransferOwnershipException
* @throws \OC\User\NoUserException
*/
public function transfer(IUser $sourceUser,
IUser $destinationUser,
string $path,
?OutputInterface $output = null,
bool $move = false,
bool $firstLogin = false,
bool $transferIncomingShares = false): void {
$output = $output ?? new NullOutput();
$sourceUid = $sourceUser->getUID();
$destinationUid = $destinationUser->getUID();
$sourcePath = rtrim($sourceUid . '/files/' . $path, '/');
// If encryption is on we have to ensure the user has logged in before and that all encryption modules are ready
if (($this->encryptionManager->isEnabled() && $destinationUser->getLastLogin() === 0)
|| !$this->encryptionManager->isReadyForUser($destinationUid)) {
throw new TransferOwnershipException("The target user is not ready to accept files. The user has at least to have logged in once.", 2);
}
// setup filesystem
// Requesting the user folder will set it up if the user hasn't logged in before
// We need a setupFS for the full filesystem setup before as otherwise we will just return
// a lazy root folder which does not create the destination users folder
\OC_Util::setupFS($destinationUser->getUID());
\OC::$server->getUserFolder($destinationUser->getUID());
Filesystem::initMountPoints($sourceUid);
Filesystem::initMountPoints($destinationUid);
$view = new View();
if ($move) {
$finalTarget = "$destinationUid/files/";
} else {
$date = date('Y-m-d H-i-s');
// Remove some characters which are prone to cause errors
$cleanUserName = str_replace(['\\', '/', ':', '.', '?', '#', '\'', '"'], '-', $sourceUser->getDisplayName());
// Replace multiple dashes with one dash
$cleanUserName = preg_replace('/-{2,}/s', '-', $cleanUserName);
$cleanUserName = $cleanUserName ?: $sourceUid;
$finalTarget = "$destinationUid/files/transferred from $cleanUserName on $date";
try {
$view->verifyPath(dirname($finalTarget), basename($finalTarget));
} catch (InvalidPathException $e) {
$finalTarget = "$destinationUid/files/transferred from $sourceUid on $date";
}
}
if (!($view->is_dir($sourcePath) || $view->is_file($sourcePath))) {
throw new TransferOwnershipException("Unknown path provided: $path", 1);
}
if ($move && !$view->is_dir($finalTarget)) {
// Initialize storage
\OC_Util::setupFS($destinationUser->getUID());
}
if ($move && !$firstLogin && count($view->getDirectoryContent($finalTarget)) > 0) {
throw new TransferOwnershipException("Destination path does not exists or is not empty", 1);
}
// analyse source folder
$this->analyse(
$sourceUid,
$destinationUid,
$sourcePath,
$view,
$output
);
// collect all the shares
$shares = $this->collectUsersShares(
$sourceUid,
$output,
$view,
$sourcePath
);
// transfer the files
$this->transferFiles(
$sourceUid,
$sourcePath,
$finalTarget,
$view,
$output
);
// restore the shares
$this->restoreShares(
$sourceUid,
$destinationUid,
$shares,
$output
);
// transfer the incoming shares
if ($transferIncomingShares === true) {
$sourceShares = $this->collectIncomingShares(
$sourceUid,
$output,
$view
);
$destinationShares = $this->collectIncomingShares(
$destinationUid,
$output,
$view,
true
);
$this->transferIncomingShares(
$sourceUid,
$destinationUid,
$sourceShares,
$destinationShares,
$output,
$path,
$finalTarget,
$move
);
}
}
private function walkFiles(View $view, $path, Closure $callBack) {
foreach ($view->getDirectoryContent($path) as $fileInfo) {
if (!$callBack($fileInfo)) {
return;
}
if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
$this->walkFiles($view, $fileInfo->getPath(), $callBack);
}
}
}
/**
* @param OutputInterface $output
*
* @throws \Exception
*/
protected function analyse(string $sourceUid,
string $destinationUid,
string $sourcePath,
View $view,
OutputInterface $output): void {
$output->writeln('Validating quota');
$size = $view->getFileInfo($sourcePath, false)->getSize(false);
$freeSpace = $view->free_space($destinationUid . '/files/');
if ($size > $freeSpace && $freeSpace !== FileInfo::SPACE_UNKNOWN) {
$output->writeln('<error>Target user does not have enough free space available.</error>');
throw new \Exception('Execution terminated.');
}
$output->writeln("Analysing files of $sourceUid ...");
$progress = new ProgressBar($output);
$progress->start();
$encryptedFiles = [];
$this->walkFiles($view, $sourcePath,
function (FileInfo $fileInfo) use ($progress) {
if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
// only analyze into folders from main storage,
if (!$fileInfo->getStorage()->instanceOfStorage(IHomeStorage::class)) {
return false;
}
return true;
}
$progress->advance();
if ($fileInfo->isEncrypted()) {
$encryptedFiles[] = $fileInfo;
}
return true;
});
$progress->finish();
$output->writeln('');
// no file is allowed to be encrypted
if (!empty($encryptedFiles)) {
$output->writeln("<error>Some files are encrypted - please decrypt them first.</error>");
foreach ($encryptedFiles as $encryptedFile) {
/** @var FileInfo $encryptedFile */
$output->writeln(" " . $encryptedFile->getPath());
}
throw new \Exception('Execution terminated.');
}
}
private function collectUsersShares(string $sourceUid,
OutputInterface $output,
View $view,
string $path): array {
$output->writeln("Collecting all share information for files and folders of $sourceUid ...");
$shares = [];
$progress = new ProgressBar($output);
foreach ([IShare::TYPE_GROUP, IShare::TYPE_USER, IShare::TYPE_LINK, IShare::TYPE_REMOTE, IShare::TYPE_ROOM, IShare::TYPE_EMAIL, IShare::TYPE_CIRCLE, IShare::TYPE_DECK, IShare::TYPE_SCIENCEMESH] as $shareType) {
$offset = 0;
while (true) {
$sharePage = $this->shareManager->getSharesBy($sourceUid, $shareType, null, true, 50, $offset);
$progress->advance(count($sharePage));
if (empty($sharePage)) {
break;
}
if ($path !== "$sourceUid/files") {
$sharePage = array_filter($sharePage, function (IShare $share) use ($view, $path) {
try {
$relativePath = $view->getPath($share->getNodeId());
$singleFileTranfer = $view->is_file($path);
if ($singleFileTranfer) {
return Filesystem::normalizePath($relativePath) === Filesystem::normalizePath($path);
}
return mb_strpos(
Filesystem::normalizePath($relativePath . '/', false),
Filesystem::normalizePath($path . '/', false)) === 0;
} catch (\Exception $e) {
return false;
}
});
}
$shares = array_merge($shares, $sharePage);
$offset += 50;
}
}
$progress->finish();
$output->writeln('');
return $shares;
}
private function collectIncomingShares(string $sourceUid,
OutputInterface $output,
View $view,
bool $addKeys = false): array {
$output->writeln("Collecting all incoming share information for files and folders of $sourceUid ...");
$shares = [];
$progress = new ProgressBar($output);
$offset = 0;
while (true) {
$sharePage = $this->shareManager->getSharedWith($sourceUid, IShare::TYPE_USER, null, 50, $offset);
$progress->advance(count($sharePage));
if (empty($sharePage)) {
break;
}
if ($addKeys) {
foreach ($sharePage as $singleShare) {
$shares[$singleShare->getNodeId()] = $singleShare;
}
} else {
foreach ($sharePage as $singleShare) {
$shares[] = $singleShare;
}
}
$offset += 50;
}
$progress->finish();
$output->writeln('');
return $shares;
}
/**
* @throws TransferOwnershipException
*/
protected function transferFiles(string $sourceUid,
string $sourcePath,
string $finalTarget,
View $view,
OutputInterface $output): void {
$output->writeln("Transferring files to $finalTarget ...");
// This change will help user to transfer the folder specified using --path option.
// Else only the content inside folder is transferred which is not correct.
if ($sourcePath !== "$sourceUid/files") {
$view->mkdir($finalTarget);
$finalTarget = $finalTarget . '/' . basename($sourcePath);
}
if ($view->rename($sourcePath, $finalTarget) === false) {
throw new TransferOwnershipException("Could not transfer files.", 1);
}
if (!is_dir("$sourceUid/files")) {
// because the files folder is moved away we need to recreate it
$view->mkdir("$sourceUid/files");
}
}
private function restoreShares(string $sourceUid,
string $destinationUid,
array $shares,
OutputInterface $output) {
$output->writeln("Restoring shares ...");
$progress = new ProgressBar($output, count($shares));
foreach ($shares as $share) {
try {
if ($share->getShareType() === IShare::TYPE_USER &&
$share->getSharedWith() === $destinationUid) {
// Unmount the shares before deleting, so we don't try to get the storage later on.
$shareMountPoint = $this->mountManager->find('/' . $destinationUid . '/files' . $share->getTarget());
if ($shareMountPoint) {
$this->mountManager->removeMount($shareMountPoint->getMountPoint());
}
$this->shareManager->deleteShare($share);
} else {
if ($share->getShareOwner() === $sourceUid) {
$share->setShareOwner($destinationUid);
}
if ($share->getSharedBy() === $sourceUid) {
$share->setSharedBy($destinationUid);
}
if ($share->getShareType() === IShare::TYPE_USER &&
!$this->userManager->userExists($share->getSharedWith())) {
// stray share with deleted user
$output->writeln('<error>Share with id ' . $share->getId() . ' points at deleted user "' . $share->getSharedWith() . '", deleting</error>');
$this->shareManager->deleteShare($share);
continue;
} else {
// trigger refetching of the node so that the new owner and mountpoint are taken into account
// otherwise the checks on the share update will fail due to the original node not being available in the new user scope
$this->userMountCache->clear();
$share->setNodeId($share->getNode()->getId());
$this->shareManager->updateShare($share);
}
}
} catch (\OCP\Files\NotFoundException $e) {
$output->writeln('<error>Share with id ' . $share->getId() . ' points at deleted file, skipping</error>');
} catch (\Throwable $e) {
$output->writeln('<error>Could not restore share with id ' . $share->getId() . ':' . $e->getMessage() . ' : ' . $e->getTraceAsString() . '</error>');
}
$progress->advance();
}
$progress->finish();
$output->writeln('');
}
private function transferIncomingShares(string $sourceUid,
string $destinationUid,
array $sourceShares,
array $destinationShares,
OutputInterface $output,
string $path,
string $finalTarget,
bool $move): void {
$output->writeln("Restoring incoming shares ...");
$progress = new ProgressBar($output, count($sourceShares));
$prefix = "$destinationUid/files";
$finalShareTarget = '';
if (substr($finalTarget, 0, strlen($prefix)) === $prefix) {
$finalShareTarget = substr($finalTarget, strlen($prefix));
}
foreach ($sourceShares as $share) {
try {
// Only restore if share is in given path.
$pathToCheck = '/';
if (trim($path, '/') !== '') {
$pathToCheck = '/' . trim($path) . '/';
}
if (substr($share->getTarget(), 0, strlen($pathToCheck)) !== $pathToCheck) {
continue;
}
$shareTarget = $share->getTarget();
$shareTarget = $finalShareTarget . $shareTarget;
if ($share->getShareType() === IShare::TYPE_USER &&
$share->getSharedBy() === $destinationUid) {
$this->shareManager->deleteShare($share);
} elseif (isset($destinationShares[$share->getNodeId()])) {
$destinationShare = $destinationShares[$share->getNodeId()];
// Keep the share which has the most permissions and discard the other one.
if ($destinationShare->getPermissions() < $share->getPermissions()) {
$this->shareManager->deleteShare($destinationShare);
$share->setSharedWith($destinationUid);
// trigger refetching of the node so that the new owner and mountpoint are taken into account
// otherwise the checks on the share update will fail due to the original node not being available in the new user scope
$this->userMountCache->clear();
$share->setNodeId($share->getNode()->getId());
$this->shareManager->updateShare($share);
// The share is already transferred.
$progress->advance();
if ($move) {
continue;
}
$share->setTarget($shareTarget);
$this->shareManager->moveShare($share, $destinationUid);
continue;
}
$this->shareManager->deleteShare($share);
} elseif ($share->getShareOwner() === $destinationUid) {
$this->shareManager->deleteShare($share);
} else {
$share->setSharedWith($destinationUid);
$share->setNodeId($share->getNode()->getId());
$this->shareManager->updateShare($share);
// trigger refetching of the node so that the new owner and mountpoint are taken into account
// otherwise the checks on the share update will fail due to the original node not being available in the new user scope
$this->userMountCache->clear();
// The share is already transferred.
$progress->advance();
if ($move) {
continue;
}
$share->setTarget($shareTarget);
$this->shareManager->moveShare($share, $destinationUid);
continue;
}
} catch (\OCP\Files\NotFoundException $e) {
$output->writeln('<error>Share with id ' . $share->getId() . ' points at deleted file, skipping</error>');
} catch (\Throwable $e) {
$output->writeln('<error>Could not restore share with id ' . $share->getId() . ':' . $e->getTraceAsString() . '</error>');
}
$progress->advance();
}
$progress->finish();
$output->writeln('');
}
}
@@ -0,0 +1,148 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Joas Schilling <coding@schilljs.com>
* @author Vincent Petry <vincent@nextcloud.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\Service;
use OCA\Files\Activity\FavoriteProvider;
use OCP\Activity\IManager;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\Events\NodeAddedToFavorite;
use OCP\Files\Events\NodeRemovedFromFavorite;
use OCP\Files\Folder;
use OCP\ITags;
use OCP\IUser;
use OCP\IUserSession;
/**
* Service class to manage tags on files.
*/
class TagService {
/** @var IUserSession */
private $userSession;
/** @var IManager */
private $activityManager;
/** @var ITags|null */
private $tagger;
/** @var Folder|null */
private $homeFolder;
/** @var IEventDispatcher */
private $dispatcher;
public function __construct(
IUserSession $userSession,
IManager $activityManager,
?ITags $tagger,
?Folder $homeFolder,
IEventDispatcher $dispatcher,
) {
$this->userSession = $userSession;
$this->activityManager = $activityManager;
$this->tagger = $tagger;
$this->homeFolder = $homeFolder;
$this->dispatcher = $dispatcher;
}
/**
* Updates the tags of the specified file path.
* The passed tags are absolute, which means they will
* replace the actual tag selection.
*
* @param string $path path
* @param array $tags array of tags
* @return array list of tags
* @throws \OCP\Files\NotFoundException if the file does not exist
*/
public function updateFileTags($path, $tags) {
if ($this->tagger === null) {
throw new \RuntimeException('No tagger set');
}
if ($this->homeFolder === null) {
throw new \RuntimeException('No homeFolder set');
}
$fileId = $this->homeFolder->get($path)->getId();
$currentTags = $this->tagger->getTagsForObjects([$fileId]);
if (!empty($currentTags)) {
$currentTags = current($currentTags);
}
$newTags = array_diff($tags, $currentTags);
foreach ($newTags as $tag) {
if ($tag === ITags::TAG_FAVORITE) {
$this->addActivity(true, $fileId, $path);
}
$this->tagger->tagAs($fileId, $tag);
}
$deletedTags = array_diff($currentTags, $tags);
foreach ($deletedTags as $tag) {
if ($tag === ITags::TAG_FAVORITE) {
$this->addActivity(false, $fileId, $path);
}
$this->tagger->unTag($fileId, $tag);
}
// TODO: re-read from tagger to make sure the
// list is up to date, in case of concurrent changes ?
return $tags;
}
/**
* @param bool $addToFavorite
* @param int $fileId
* @param string $path
*/
protected function addActivity($addToFavorite, $fileId, $path) {
$user = $this->userSession->getUser();
if (!$user instanceof IUser) {
return;
}
if ($addToFavorite) {
$event = new NodeAddedToFavorite($user, $fileId, $path);
} else {
$event = new NodeRemovedFromFavorite($user, $fileId, $path);
}
$this->dispatcher->dispatchTyped($event);
$event = $this->activityManager->generateEvent();
try {
$event->setApp('files')
->setObject('files', $fileId, $path)
->setType('favorite')
->setAuthor($user->getUID())
->setAffectedUser($user->getUID())
->setTimestamp(time())
->setSubject(
$addToFavorite ? FavoriteProvider::SUBJECT_ADDED : FavoriteProvider::SUBJECT_REMOVED,
['id' => $fileId, 'path' => $path]
);
$this->activityManager->publish($event);
} catch (\InvalidArgumentException $e) {
} catch (\BadMethodCallException $e) {
}
}
}
@@ -0,0 +1,162 @@
<?php
/**
* @copyright Copyright (c) 2022 John Molakvoæ <skjnldsv@protonmail.com>
*
* @author John Molakvoæ <skjnldsv@protonmail.com>
*
* @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\Service;
use OCA\Files\AppInfo\Application;
use OCP\IConfig;
use OCP\IUser;
use OCP\IUserSession;
class UserConfig {
public const ALLOWED_CONFIGS = [
[
// Whether to crop the files previews or not in the files list
'key' => 'crop_image_previews',
'default' => true,
'allowed' => [true, false],
],
[
// Whether to show the hidden files or not in the files list
'key' => 'show_hidden',
'default' => false,
'allowed' => [true, false],
],
[
// Whether to sort favorites first in the list or not
'key' => 'sort_favorites_first',
'default' => true,
'allowed' => [true, false],
],
[
// Whether to sort folders before files in the list or not
'key' => 'sort_folders_first',
'default' => true,
'allowed' => [true, false],
],
[
// Whether to show the files list in grid view or not
'key' => 'grid_view',
'default' => false,
'allowed' => [true, false],
],
];
protected IConfig $config;
protected ?IUser $user = null;
public function __construct(IConfig $config, IUserSession $userSession) {
$this->config = $config;
$this->user = $userSession->getUser();
}
/**
* Get the list of all allowed user config keys
* @return string[]
*/
public function getAllowedConfigKeys(): array {
return array_map(function ($config) {
return $config['key'];
}, self::ALLOWED_CONFIGS);
}
/**
* Get the list of allowed config values for a given key
*
* @param string $key a valid config key
* @return array
*/
private function getAllowedConfigValues(string $key): array {
foreach (self::ALLOWED_CONFIGS as $config) {
if ($config['key'] === $key) {
return $config['allowed'];
}
}
return [];
}
/**
* Get the default config value for a given key
*
* @param string $key a valid config key
* @return string|bool
*/
private function getDefaultConfigValue(string $key) {
foreach (self::ALLOWED_CONFIGS as $config) {
if ($config['key'] === $key) {
return $config['default'];
}
}
return '';
}
/**
* Set a user config
*
* @param string $key
* @param string|bool $value
* @throws \Exception
* @throws \InvalidArgumentException
*/
public function setConfig(string $key, $value): void {
if ($this->user === null) {
throw new \Exception('No user logged in');
}
if (!in_array($key, $this->getAllowedConfigKeys())) {
throw new \InvalidArgumentException('Unknown config key');
}
if (!in_array($value, $this->getAllowedConfigValues($key))) {
throw new \InvalidArgumentException('Invalid config value');
}
if (is_bool($value)) {
$value = $value ? '1' : '0';
}
$this->config->setUserValue($this->user->getUID(), Application::APP_ID, $key, $value);
}
/**
* Get the current user configs array
*
* @return array
*/
public function getConfigs(): array {
if ($this->user === null) {
throw new \Exception('No user logged in');
}
$userId = $this->user->getUID();
$userConfigs = array_map(function (string $key) use ($userId) {
$value = $this->config->getUserValue($userId, Application::APP_ID, $key, $this->getDefaultConfigValue($key));
// If the default is expected to be a boolean, we need to cast the value
if (is_bool($this->getDefaultConfigValue($key)) && is_string($value)) {
return $value === '1';
}
return $value;
}, $this->getAllowedConfigKeys());
return array_combine($this->getAllowedConfigKeys(), $userConfigs);
}
}
@@ -0,0 +1,184 @@
<?php
/**
* @copyright Copyright (c) 2023 John Molakvoæ <skjnldsv@protonmail.com>
*
* @author John Molakvoæ <skjnldsv@protonmail.com>
*
* @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\Service;
use OCA\Files\AppInfo\Application;
use OCP\IConfig;
use OCP\IUser;
use OCP\IUserSession;
class ViewConfig {
public const CONFIG_KEY = 'files_views_configs';
public const ALLOWED_CONFIGS = [
[
// The default sorting key for the files list view
'key' => 'sorting_mode',
// null by default as views can provide default sorting key
// and will fallback to it if user hasn't change it
'default' => null,
],
[
// The default sorting direction for the files list view
'key' => 'sorting_direction',
'default' => 'asc',
'allowed' => ['asc', 'desc'],
],
[
// If the navigation entry for this view is expanded or not
'key' => 'expanded',
'default' => true,
'allowed' => [true, false],
],
];
protected IConfig $config;
protected ?IUser $user = null;
public function __construct(IConfig $config, IUserSession $userSession) {
$this->config = $config;
$this->user = $userSession->getUser();
}
/**
* Get the list of all allowed user config keys
* @return string[]
*/
public function getAllowedConfigKeys(): array {
return array_map(function ($config) {
return $config['key'];
}, self::ALLOWED_CONFIGS);
}
/**
* Get the list of allowed config values for a given key
*
* @param string $key a valid config key
* @return array
*/
private function getAllowedConfigValues(string $key): array {
foreach (self::ALLOWED_CONFIGS as $config) {
if ($config['key'] === $key) {
return $config['allowed'] ?? [];
}
}
return [];
}
/**
* Get the default config value for a given key
*
* @param string $key a valid config key
* @return string|bool|null
*/
private function getDefaultConfigValue(string $key) {
foreach (self::ALLOWED_CONFIGS as $config) {
if ($config['key'] === $key) {
return $config['default'];
}
}
return '';
}
/**
* Set a user config
*
* @param string $view
* @param string $key
* @param string|bool $value
* @throws \Exception
* @throws \InvalidArgumentException
*/
public function setConfig(string $view, string $key, $value): void {
if ($this->user === null) {
throw new \Exception('No user logged in');
}
if (!$view) {
throw new \Exception('Unknown view');
}
if (!in_array($key, $this->getAllowedConfigKeys())) {
throw new \InvalidArgumentException('Unknown config key');
}
if (!in_array($value, $this->getAllowedConfigValues($key))
&& !empty($this->getAllowedConfigValues($key))) {
throw new \InvalidArgumentException('Invalid config value');
}
// Cast boolean values
if (is_bool($this->getDefaultConfigValue($key))) {
$value = $value === '1';
}
$config = $this->getConfigs();
$config[$view][$key] = $value;
$this->config->setUserValue($this->user->getUID(), Application::APP_ID, self::CONFIG_KEY, json_encode($config));
}
/**
* Get the current user configs array for a given view
*
* @return array
*/
public function getConfig(string $view): array {
if ($this->user === null) {
throw new \Exception('No user logged in');
}
$userId = $this->user->getUID();
$configs = json_decode($this->config->getUserValue($userId, Application::APP_ID, self::CONFIG_KEY, '[]'), true);
if (!isset($configs[$view])) {
$configs[$view] = [];
}
// Extend undefined values with defaults
return array_reduce(self::ALLOWED_CONFIGS, function ($carry, $config) use ($view, $configs) {
$key = $config['key'];
$carry[$key] = $configs[$view][$key] ?? $this->getDefaultConfigValue($key);
return $carry;
}, []);
}
/**
* Get the current user configs array
*
* @return array
*/
public function getConfigs(): array {
if ($this->user === null) {
throw new \Exception('No user logged in');
}
$userId = $this->user->getUID();
$configs = json_decode($this->config->getUserValue($userId, Application::APP_ID, self::CONFIG_KEY, '[]'), true);
$views = array_keys($configs);
return array_reduce($views, function ($carry, $view) use ($configs) {
$carry[$view] = $this->getConfig($view);
return $carry;
}, []);
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
/**
* @copyright 2019 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\Settings;
use OCA\Files\AppInfo\Application;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\Settings\ISettings;
class PersonalSettings implements ISettings {
public function getForm(): TemplateResponse {
return new TemplateResponse(Application::APP_ID, 'settings-personal');
}
public function getSection(): string {
return 'sharing';
}
public function getPriority(): int {
return 90;
}
}