diff --git a/apps/dav/lib/Connector/Sabre/TagsPlugin.php b/apps/dav/lib/Connector/Sabre/TagsPlugin.php index 7baf1742d61..a45f6c12e8a 100644 --- a/apps/dav/lib/Connector/Sabre/TagsPlugin.php +++ b/apps/dav/lib/Connector/Sabre/TagsPlugin.php @@ -108,6 +108,7 @@ class TagsPlugin extends \Sabre\DAV\ServerPlugin { private function getTagger() { if (!$this->tagger) { $this->tagger = $this->tagManager->load('files'); + assert($this->tagger !== null); } return $this->tagger; } diff --git a/apps/files_sharing/lib/External/Scanner.php b/apps/files_sharing/lib/External/Scanner.php index 0d57248595b..e6f96a846d6 100644 --- a/apps/files_sharing/lib/External/Scanner.php +++ b/apps/files_sharing/lib/External/Scanner.php @@ -13,10 +13,10 @@ use OCP\Files\NotFoundException; use OCP\Files\StorageInvalidException; use OCP\Files\StorageNotAvailableException; +/** + * @property Storage $storage + */ class Scanner extends \OC\Files\Cache\Scanner { - /** @var Storage */ - protected $storage; - public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) { // Disable locking for federated shares parent::scan($path, $recursive, $reuse, false); diff --git a/apps/files_sharing/lib/Scanner.php b/apps/files_sharing/lib/Scanner.php index 28972c1b462..c15a5ea0311 100644 --- a/apps/files_sharing/lib/Scanner.php +++ b/apps/files_sharing/lib/Scanner.php @@ -10,17 +10,14 @@ namespace OCA\Files_Sharing; use OC\Files\ObjectStore\ObjectStoreScanner; use OC\Files\Storage\Storage; +use OCP\Files\Cache\IScanner; /** * Scanner for SharedStorage + * @property SharedStorage $storage */ class Scanner extends \OC\Files\Cache\Scanner { - /** - * @var SharedStorage $storage - */ - protected $storage; - - private $sourceScanner; + private ?IScanner $sourceScanner = null; /** * Returns metadata from the shared storage, but @@ -40,7 +37,7 @@ class Scanner extends \OC\Files\Cache\Scanner { return $data; } - private function getSourceScanner() { + private function getSourceScanner(): ?IScanner { if ($this->sourceScanner) { return $this->sourceScanner; } diff --git a/build/psalm-baseline.xml b/build/psalm-baseline.xml index b018bff0c15..ba1b541162d 100644 --- a/build/psalm-baseline.xml +++ b/build/psalm-baseline.xml @@ -3214,14 +3214,6 @@ - - - server]]> - - - - - @@ -3261,9 +3253,6 @@ request->server]]> - - - @@ -3612,18 +3601,6 @@ - - - getStorage()]]> - findByNumericId($id)]]> - findByStorageId($id)]]> - - - - - - - @@ -3799,32 +3776,7 @@ getContent())]]> - - - - - - - - - emitter]]> - emitter]]> - emitter]]> - - - - - - - - - - - - - - @@ -3913,11 +3865,6 @@ - - - - - @@ -3979,25 +3926,6 @@ - - - - - - get(IFile::class)]]> - get(IGroupManager::class)]]> - get(IUserManager::class)]]> - get(IUserSession::class)]]> - get(\OCP\Encryption\IManager::class)]]> - - - - - - - - - hasNoAppContainer]]> @@ -4035,11 +3963,6 @@ dbprettyname]]> - - - - - @@ -4065,14 +3988,6 @@ - - - - - - - - diff --git a/build/rector.php b/build/rector.php index 3253b614e63..bd51f7362cb 100644 --- a/build/rector.php +++ b/build/rector.php @@ -23,11 +23,9 @@ return (require 'rector-shared.php') $nextcloudDir . '/remote.php', $nextcloudDir . '/status.php', $nextcloudDir . '/version.php', - $nextcloudDir . '/lib/private/Share20/ProviderFactory.php', - $nextcloudDir . '/lib/private/Template', + $nextcloudDir . '/lib/private', $nextcloudDir . '/tests', // $nextcloudDir . '/config', - // $nextcloudDir . '/lib', // $nextcloudDir . '/themes', ]) ->withTypeCoverageLevel(0); diff --git a/lib/private/Activity/EventMerger.php b/lib/private/Activity/EventMerger.php index 0e7d318103a..2b9294f5852 100644 --- a/lib/private/Activity/EventMerger.php +++ b/lib/private/Activity/EventMerger.php @@ -11,14 +11,12 @@ use OCP\Activity\IEventMerger; use OCP\IL10N; class EventMerger implements IEventMerger { - /** @var IL10N */ - protected $l10n; - /** * @param IL10N $l10n */ - public function __construct(IL10N $l10n) { - $this->l10n = $l10n; + public function __construct( + protected IL10N $l10n, + ) { } /** diff --git a/lib/private/Activity/Manager.php b/lib/private/Activity/Manager.php index 9868abe5127..186ef843e2f 100644 --- a/lib/private/Activity/Manager.php +++ b/lib/private/Activity/Manager.php @@ -26,6 +26,7 @@ use OCP\IUser; use OCP\IUserSession; use OCP\RichObjectStrings\IRichTextFormatter; use OCP\RichObjectStrings\IValidator; +use OCP\Server; class Manager implements IManager { @@ -59,7 +60,7 @@ class Manager implements IManager { private $consumers = []; /** - * @return \OCP\Activity\IConsumer[] + * @return IConsumer[] */ protected function getConsumers(): array { if (!empty($this->consumers)) { @@ -183,7 +184,7 @@ class Manager implements IManager { public function getFilters(): array { foreach ($this->filterClasses as $class => $false) { /** @var IFilter $filter */ - $filter = \OCP\Server::get($class); + $filter = Server::get($class); if (!$filter instanceof IFilter) { throw new \InvalidArgumentException('Invalid activity filter registered'); @@ -230,7 +231,7 @@ class Manager implements IManager { public function getProviders(): array { foreach ($this->providerClasses as $class => $false) { /** @var IProvider $provider */ - $provider = \OCP\Server::get($class); + $provider = Server::get($class); if (!$provider instanceof IProvider) { throw new \InvalidArgumentException('Invalid activity provider registered'); @@ -264,7 +265,7 @@ class Manager implements IManager { public function getSettings(): array { foreach ($this->settingsClasses as $class => $false) { /** @var ISetting $setting */ - $setting = \OCP\Server::get($class); + $setting = Server::get($class); if ($setting instanceof ISetting) { if (!$setting instanceof ActivitySettings) { diff --git a/lib/private/AllConfig.php b/lib/private/AllConfig.php index 6356188bab6..4f8229a8f99 100644 --- a/lib/private/AllConfig.php +++ b/lib/private/AllConfig.php @@ -13,6 +13,7 @@ use OCP\Config\IUserConfig; use OCP\Config\ValueType; use OCP\IConfig; use OCP\PreConditionNotMetException; +use OCP\Server; /** * Class to combine all the configuration options Nextcloud offers @@ -24,7 +25,7 @@ class AllConfig implements IConfig { } /** - * Sets and deletes system-wide values + * Sets and deletes system wide values * * @param array $configs Associative array with `key => value` pairs * If value is null, the config key will be deleted @@ -124,7 +125,7 @@ class AllConfig implements IConfig { * @deprecated 29.0.0 Use {@see IAppConfig} directly */ public function getAppKeys($appName) { - return \OC::$server->get(AppConfig::class)->getKeys($appName); + return Server::get(AppConfig::class)->getKeys($appName); } /** @@ -136,7 +137,7 @@ class AllConfig implements IConfig { * @deprecated 29.0.0 Use {@see IAppConfig} directly */ public function setAppValue($appName, $key, $value) { - \OC::$server->get(AppConfig::class)->setValue($appName, $key, $value); + Server::get(AppConfig::class)->setValue($appName, $key, $value); } /** @@ -149,7 +150,7 @@ class AllConfig implements IConfig { * @deprecated 29.0.0 Use {@see IAppConfig} directly */ public function getAppValue($appName, $key, $default = '') { - return \OC::$server->get(AppConfig::class)->getValue($appName, $key, $default) ?? $default; + return Server::get(AppConfig::class)->getValue($appName, $key, $default) ?? $default; } /** @@ -160,7 +161,7 @@ class AllConfig implements IConfig { * @deprecated 29.0.0 Use {@see IAppConfig} directly */ public function deleteAppValue($appName, $key) { - \OC::$server->get(AppConfig::class)->deleteKey($appName, $key); + Server::get(AppConfig::class)->deleteKey($appName, $key); } /** @@ -170,7 +171,7 @@ class AllConfig implements IConfig { * @deprecated 29.0.0 Use {@see IAppConfig} directly */ public function deleteAppValues($appName) { - \OC::$server->get(AppConfig::class)->deleteApp($appName); + Server::get(AppConfig::class)->deleteApp($appName); } @@ -183,7 +184,7 @@ class AllConfig implements IConfig { * @param string|float|int $value the value that you want to store * @param string $preCondition only update if the config value was previously the value passed as $preCondition * - * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met + * @throws PreConditionNotMetException if a precondition is specified and is not met * @throws \UnexpectedValueException when trying to store an unexpected value * @deprecated 31.0.0 - use {@see IUserConfig} directly * @see IUserConfig::getValueString @@ -198,7 +199,7 @@ class AllConfig implements IConfig { } /** @var UserConfig $userPreferences */ - $userPreferences = \OCP\Server::get(IUserConfig::class); + $userPreferences = Server::get(IUserConfig::class); if ($preCondition !== null) { try { if ($userPreferences->hasKey($userId, $appName, $key) && $userPreferences->getValueMixed($userId, $appName, $key) !== (string)$preCondition) { @@ -232,7 +233,7 @@ class AllConfig implements IConfig { return $default; } /** @var UserConfig $userPreferences */ - $userPreferences = \OCP\Server::get(IUserConfig::class); + $userPreferences = Server::get(IUserConfig::class); // because $default can be null ... if (!$userPreferences->hasKey($userId, $appName, $key)) { return $default; @@ -250,7 +251,7 @@ class AllConfig implements IConfig { * @deprecated 31.0.0 - use {@see IUserConfig::getKeys} directly */ public function getUserKeys($userId, $appName) { - return \OCP\Server::get(IUserConfig::class)->getKeys($userId, $appName); + return Server::get(IUserConfig::class)->getKeys($userId, $appName); } /** @@ -263,7 +264,7 @@ class AllConfig implements IConfig { * @deprecated 31.0.0 - use {@see IUserConfig::deleteUserConfig} directly */ public function deleteUserValue($userId, $appName, $key) { - \OCP\Server::get(IUserConfig::class)->deleteUserConfig($userId, $appName, $key); + Server::get(IUserConfig::class)->deleteUserConfig($userId, $appName, $key); } /** @@ -277,7 +278,7 @@ class AllConfig implements IConfig { if ($userId === null) { return; } - \OCP\Server::get(IUserConfig::class)->deleteAllUserConfig($userId); + Server::get(IUserConfig::class)->deleteAllUserConfig($userId); } /** @@ -288,7 +289,7 @@ class AllConfig implements IConfig { * @deprecated 31.0.0 - use {@see IUserConfig::deleteApp} directly */ public function deleteAppFromAllUsers($appName) { - \OCP\Server::get(IUserConfig::class)->deleteApp($appName); + Server::get(IUserConfig::class)->deleteApp($appName); } /** @@ -308,7 +309,7 @@ class AllConfig implements IConfig { return []; } - $values = \OCP\Server::get(IUserConfig::class)->getAllValues($userId); + $values = Server::get(IUserConfig::class)->getAllValues($userId); $result = []; foreach ($values as $app => $list) { foreach ($list as $key => $value) { @@ -329,7 +330,7 @@ class AllConfig implements IConfig { * @deprecated 31.0.0 - use {@see IUserConfig::getValuesByUsers} directly */ public function getUserValueForUsers($appName, $key, $userIds) { - return \OCP\Server::get(IUserConfig::class)->getValuesByUsers($appName, $key, ValueType::MIXED, $userIds); + return Server::get(IUserConfig::class)->getValuesByUsers($appName, $key, ValueType::MIXED, $userIds); } /** @@ -344,7 +345,7 @@ class AllConfig implements IConfig { */ public function getUsersForUserValue($appName, $key, $value) { /** @var list $result */ - $result = iterator_to_array(\OCP\Server::get(IUserConfig::class)->searchUsersByValueString($appName, $key, $value)); + $result = iterator_to_array(Server::get(IUserConfig::class)->searchUsersByValueString($appName, $key, $value)); return $result; } diff --git a/lib/private/App/AppManager.php b/lib/private/App/AppManager.php index 655d80e9b6c..6eddb2b2c41 100644 --- a/lib/private/App/AppManager.php +++ b/lib/private/App/AppManager.php @@ -11,6 +11,7 @@ use OC\AppConfig; use OC\AppFramework\Bootstrap\Coordinator; use OC\Config\ConfigManager; use OC\DB\MigrationService; +use OC\Migration\BackgroundRepair; use OCP\Activity\IManager as IActivityManager; use OCP\App\AppPathNotFoundException; use OCP\App\Events\AppDisableEvent; @@ -211,7 +212,7 @@ class AppManager implements IAppManager { /** * List all apps enabled for a user * - * @param \OCP\IUser $user + * @param IUser $user * @return list */ public function getEnabledAppsForUser(IUser $user) { @@ -344,7 +345,7 @@ class AppManager implements IAppManager { * Check if an app is enabled for user * * @param string $appId - * @param \OCP\IUser|null $user (optional) if not defined, the currently logged in user will be used + * @param IUser|null $user (optional) if not defined, the currently logged in user will be used * @return bool */ public function isEnabledForUser($appId, $user = null) { @@ -465,7 +466,7 @@ class AppManager implements IAppManager { ]); return; } - $eventLogger = \OC::$server->get(IEventLogger::class); + $eventLogger = Server::get(IEventLogger::class); $eventLogger->start("bootstrap:load_app:$app", "Load app: $app"); // in case someone calls loadApp() directly @@ -483,7 +484,7 @@ class AppManager implements IAppManager { $eventLogger->start("bootstrap:load_app:$app:info", "Load info.xml for $app and register any services defined in it"); $info = $this->getAppInfo($app); if (!empty($info['activity'])) { - $activityManager = \OC::$server->get(IActivityManager::class); + $activityManager = Server::get(IActivityManager::class); if (!empty($info['activity']['filters'])) { foreach ($info['activity']['filters'] as $filter) { $activityManager->registerFilter($filter); @@ -502,7 +503,7 @@ class AppManager implements IAppManager { } if (!empty($info['settings'])) { - $settingsManager = \OCP\Server::get(ISettingsManager::class); + $settingsManager = Server::get(ISettingsManager::class); if (!empty($info['settings']['admin'])) { foreach ($info['settings']['admin'] as $setting) { $settingsManager->registerSetting('admin', $setting); @@ -547,10 +548,10 @@ class AppManager implements IAppManager { 'shareType' => $plugin['@attributes']['share-type'], 'class' => $plugin['@value'], ]; - $collaboratorSearch ??= \OC::$server->get(ICollaboratorSearch::class); + $collaboratorSearch ??= Server::get(ICollaboratorSearch::class); $collaboratorSearch->registerPlugin($pluginInfo); } elseif ($plugin['@attributes']['type'] === 'autocomplete-sort') { - $autoCompleteManager ??= \OC::$server->get(IAutoCompleteManager::class); + $autoCompleteManager ??= Server::get(IAutoCompleteManager::class); $autoCompleteManager->registerSorter($plugin['@value']); } } @@ -1075,7 +1076,7 @@ class AppManager implements IAppManager { \OC_App::executeRepairSteps($appId, $appData['repair-steps']['post-migration']); $queue = Server::get(IJobList::class); foreach ($appData['repair-steps']['live-migration'] as $step) { - $queue->add(\OC\Migration\BackgroundRepair::class, [ + $queue->add(BackgroundRepair::class, [ 'app' => $appId, 'step' => $step]); } diff --git a/lib/private/App/Platform.php b/lib/private/App/Platform.php index 80e4cefed64..38b0bd58b98 100644 --- a/lib/private/App/Platform.php +++ b/lib/private/App/Platform.php @@ -9,6 +9,8 @@ namespace OC\App; use OCP\IBinaryFinder; use OCP\IConfig; +use OCP\Server; +use OCP\Util; /** * Class Platform @@ -32,7 +34,7 @@ class Platform { } public function getOcVersion(): string { - $v = \OCP\Util::getVersion(); + $v = Util::getVersion(); return implode('.', $v); } @@ -53,7 +55,7 @@ class Platform { * @param $command */ public function isCommandKnown(string $command): bool { - return \OCP\Server::get(IBinaryFinder::class)->findBinaryPath($command) !== false; + return Server::get(IBinaryFinder::class)->findBinaryPath($command) !== false; } public function getLibraryVersion(string $name): ?string { diff --git a/lib/private/AppConfig.php b/lib/private/AppConfig.php index be701f3da53..e4da80b94d9 100644 --- a/lib/private/AppConfig.php +++ b/lib/private/AppConfig.php @@ -29,6 +29,7 @@ use OCP\ICacheFactory; use OCP\IConfig; use OCP\IDBConnection; use OCP\Security\ICrypto; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -85,7 +86,7 @@ class AppConfig implements IAppConfig { public readonly CacheFactory $cacheFactory, ) { if ($config->getSystemValueBool('cache_app_config', true) && $cacheFactory->isLocalCacheAvailable()) { - $cacheFactory->withServerVersionPrefix(function (ICacheFactory $factory) { + $cacheFactory->withServerVersionPrefix(function (ICacheFactory $factory): void { $this->localCache = $factory->createLocal(); }); } @@ -1783,7 +1784,7 @@ class AppConfig implements IAppConfig { public function getConfigDetailsFromLexicon(string $appId): array { if (!array_key_exists($appId, $this->configLexiconDetails)) { $entries = $aliases = []; - $bootstrapCoordinator = \OCP\Server::get(Coordinator::class); + $bootstrapCoordinator = Server::get(Coordinator::class); $configLexicon = $bootstrapCoordinator->getRegistrationContext()?->getConfigLexicon($appId); foreach ($configLexicon?->getAppConfigs() ?? [] as $configEntry) { $entries[$configEntry->getKey()] = $configEntry; diff --git a/lib/private/AppFramework/App.php b/lib/private/AppFramework/App.php index 7bf32852209..f6ca284346c 100644 --- a/lib/private/AppFramework/App.php +++ b/lib/private/AppFramework/App.php @@ -21,6 +21,7 @@ use OCP\Diagnostics\IEventLogger; use OCP\HintException; use OCP\IRequest; use OCP\Profiler\IProfiler; +use OCP\Server; /** * Entry point for every request in your app. You can consider this as your @@ -46,7 +47,7 @@ class App { return $topNamespace . self::$nameSpaceCache[$appId]; } - $appInfo = \OCP\Server::get(IAppManager::class)->getAppInfo($appId); + $appInfo = Server::get(IAppManager::class)->getAppInfo($appId); if (isset($appInfo['namespace'])) { self::$nameSpaceCache[$appId] = trim($appInfo['namespace']); } else { @@ -93,7 +94,7 @@ class App { // Disable profiler on the profiler UI $profiler->setEnabled($profiler->isEnabled() && !is_null($urlParams) && isset($urlParams['_route']) && !str_starts_with($urlParams['_route'], 'profiler.')); if ($profiler->isEnabled()) { - \OC::$server->get(IEventLogger::class)->activate(); + Server::get(IEventLogger::class)->activate(); $profiler->add(new RoutingDataCollector($container['appName'], $controllerName, $methodName)); } @@ -185,7 +186,7 @@ class App { $expireDate, $container->getServer()->getWebRoot(), null, - $container->getServer()->getRequest()->getServerProtocol() === 'https', + $container->getServer()->get(IRequest::class)->getServerProtocol() === 'https', true, $sameSite ); diff --git a/lib/private/AppFramework/Bootstrap/ARegistration.php b/lib/private/AppFramework/Bootstrap/ARegistration.php index 37984667727..d90e87ae449 100644 --- a/lib/private/AppFramework/Bootstrap/ARegistration.php +++ b/lib/private/AppFramework/Bootstrap/ARegistration.php @@ -12,11 +12,9 @@ namespace OC\AppFramework\Bootstrap; * @psalm-immutable */ abstract class ARegistration { - /** @var string */ - private $appId; - - public function __construct(string $appId) { - $this->appId = $appId; + public function __construct( + private string $appId, + ) { } /** diff --git a/lib/private/AppFramework/Bootstrap/BootContext.php b/lib/private/AppFramework/Bootstrap/BootContext.php index b3da08adb07..5240f18d3b8 100644 --- a/lib/private/AppFramework/Bootstrap/BootContext.php +++ b/lib/private/AppFramework/Bootstrap/BootContext.php @@ -13,11 +13,9 @@ use OCP\AppFramework\IAppContainer; use OCP\IServerContainer; class BootContext implements IBootContext { - /** @var IAppContainer */ - private $appContainer; - - public function __construct(IAppContainer $appContainer) { - $this->appContainer = $appContainer; + public function __construct( + private IAppContainer $appContainer, + ) { } public function getAppContainer(): IAppContainer { diff --git a/lib/private/AppFramework/Bootstrap/EventListenerRegistration.php b/lib/private/AppFramework/Bootstrap/EventListenerRegistration.php index 92955fc4123..0ceafcaa20a 100644 --- a/lib/private/AppFramework/Bootstrap/EventListenerRegistration.php +++ b/lib/private/AppFramework/Bootstrap/EventListenerRegistration.php @@ -8,24 +8,20 @@ declare(strict_types=1); */ namespace OC\AppFramework\Bootstrap; +use OCP\EventDispatcher\IEventListener; + /** * @psalm-immutable - * @template-extends ServiceRegistration<\OCP\EventDispatcher\IEventListener> + * @template-extends ServiceRegistration */ class EventListenerRegistration extends ServiceRegistration { - /** @var string */ - private $event; - - /** @var int */ - private $priority; - - public function __construct(string $appId, - string $event, + public function __construct( + string $appId, + private string $event, string $service, - int $priority) { + private int $priority, + ) { parent::__construct($appId, $service); - $this->event = $event; - $this->priority = $priority; } /** diff --git a/lib/private/AppFramework/Bootstrap/FunctionInjector.php b/lib/private/AppFramework/Bootstrap/FunctionInjector.php index 973fc13aa2c..6177bf0aa06 100644 --- a/lib/private/AppFramework/Bootstrap/FunctionInjector.php +++ b/lib/private/AppFramework/Bootstrap/FunctionInjector.php @@ -16,11 +16,9 @@ use ReflectionParameter; use function array_map; class FunctionInjector { - /** @var ContainerInterface */ - private $container; - - public function __construct(ContainerInterface $container) { - $this->container = $container; + public function __construct( + private ContainerInterface $container, + ) { } public function injectFn(callable $fn) { diff --git a/lib/private/AppFramework/Bootstrap/MiddlewareRegistration.php b/lib/private/AppFramework/Bootstrap/MiddlewareRegistration.php index d2ad6bbf0f6..200b0670fd3 100644 --- a/lib/private/AppFramework/Bootstrap/MiddlewareRegistration.php +++ b/lib/private/AppFramework/Bootstrap/MiddlewareRegistration.php @@ -16,11 +16,12 @@ use OCP\AppFramework\Middleware; * @template-extends ServiceRegistration */ class MiddlewareRegistration extends ServiceRegistration { - private bool $global; - - public function __construct(string $appId, string $service, bool $global) { + public function __construct( + string $appId, + string $service, + private bool $global, + ) { parent::__construct($appId, $service); - $this->global = $global; } public function isGlobal(): bool { diff --git a/lib/private/AppFramework/Bootstrap/ParameterRegistration.php b/lib/private/AppFramework/Bootstrap/ParameterRegistration.php index cc9a4875e9a..7398628e62f 100644 --- a/lib/private/AppFramework/Bootstrap/ParameterRegistration.php +++ b/lib/private/AppFramework/Bootstrap/ParameterRegistration.php @@ -12,18 +12,15 @@ namespace OC\AppFramework\Bootstrap; * @psalm-immutable */ final class ParameterRegistration extends ARegistration { - /** @var string */ - private $name; - - /** @var mixed */ - private $value; - - public function __construct(string $appId, - string $name, - $value) { + /** + * @param mixed $value + */ + public function __construct( + string $appId, + private string $name, + private $value, + ) { parent::__construct($appId); - $this->name = $name; - $this->value = $value; } public function getName(): string { diff --git a/lib/private/AppFramework/Bootstrap/PreviewProviderRegistration.php b/lib/private/AppFramework/Bootstrap/PreviewProviderRegistration.php index 7ecc4aac7f2..02e67b742a1 100644 --- a/lib/private/AppFramework/Bootstrap/PreviewProviderRegistration.php +++ b/lib/private/AppFramework/Bootstrap/PreviewProviderRegistration.php @@ -9,19 +9,19 @@ declare(strict_types=1); namespace OC\AppFramework\Bootstrap; +use OCP\Preview\IProviderV2; + /** * @psalm-immutable - * @template-extends ServiceRegistration<\OCP\Preview\IProviderV2> + * @template-extends ServiceRegistration */ class PreviewProviderRegistration extends ServiceRegistration { - /** @var string */ - private $mimeTypeRegex; - - public function __construct(string $appId, + public function __construct( + string $appId, string $service, - string $mimeTypeRegex) { + private string $mimeTypeRegex, + ) { parent::__construct($appId, $service); - $this->mimeTypeRegex = $mimeTypeRegex; } public function getMimeTypeRegex(): string { diff --git a/lib/private/AppFramework/Bootstrap/RegistrationContext.php b/lib/private/AppFramework/Bootstrap/RegistrationContext.php index 8bd1ff35610..6b68b4b7552 100644 --- a/lib/private/AppFramework/Bootstrap/RegistrationContext.php +++ b/lib/private/AppFramework/Bootstrap/RegistrationContext.php @@ -25,18 +25,21 @@ use OCP\Config\Lexicon\ILexicon; use OCP\Dashboard\IManager; use OCP\Dashboard\IWidget; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Files\Conversion\IConversionProvider; use OCP\Files\Template\ICustomTemplateProvider; use OCP\Http\WellKnown\IHandler; use OCP\Mail\Provider\IProvider as IMailProvider; use OCP\Notification\INotifier; use OCP\Profile\ILinkAction; use OCP\Search\IProvider; +use OCP\Server; use OCP\Settings\IDeclarativeSettingsForm; use OCP\SetupCheck\ISetupCheck; use OCP\Share\IPublicShareTemplateProvider; use OCP\SpeechToText\ISpeechToTextProvider; use OCP\Support\CrashReport\IReporter; use OCP\Talk\ITalkBackend; +use OCP\TaskProcessing\ITaskType; use OCP\Teams\ITeamResourceProvider; use OCP\TextProcessing\IProvider as ITextProcessingProvider; use OCP\Translation\ITranslationProvider; @@ -131,8 +134,6 @@ class RegistrationContext { /** @var ServiceRegistration[] */ private $publicShareTemplateProviders = []; - private LoggerInterface $logger; - /** @var ServiceRegistration[] */ private array $setupChecks = []; @@ -151,30 +152,26 @@ class RegistrationContext { /** @var ServiceRegistration<\OCP\TaskProcessing\IProvider>[] */ private array $taskProcessingProviders = []; - /** @var ServiceRegistration<\OCP\TaskProcessing\ITaskType>[] */ + /** @var ServiceRegistration[] */ private array $taskProcessingTaskTypes = []; - /** @var ServiceRegistration<\OCP\Files\Conversion\IConversionProvider>[] */ + /** @var ServiceRegistration[] */ private array $fileConversionProviders = []; /** @var ServiceRegistration[] */ private $mailProviders = []; - public function __construct(LoggerInterface $logger) { - $this->logger = $logger; + public function __construct( + private LoggerInterface $logger, + ) { } public function for(string $appId): IRegistrationContext { return new class($appId, $this) implements IRegistrationContext { - /** @var string */ - private $appId; - - /** @var RegistrationContext */ - private $context; - - public function __construct(string $appId, RegistrationContext $context) { - $this->appId = $appId; - $this->context = $context; + public function __construct( + private string $appId, + private RegistrationContext $context, + ) { } public function registerCapability(string $capability): void { @@ -630,14 +627,14 @@ class RegistrationContext { } /** - * @psalm-param class-string<\OCP\TaskProcessing\ITaskType> $declarativeSettingsClass + * @psalm-param class-string $declarativeSettingsClass */ public function registerTaskProcessingTaskType(string $appId, string $taskProcessingTaskTypeClass) { $this->taskProcessingTaskTypes[] = new ServiceRegistration($appId, $taskProcessingTaskTypeClass); } /** - * @psalm-param class-string<\OCP\Files\Conversion\IConversionProvider> $class + * @psalm-param class-string $class */ public function registerFileConversionProvider(string $appId, string $class): void { $this->fileConversionProviders[] = new ServiceRegistration($appId, $class); @@ -996,14 +993,14 @@ class RegistrationContext { } /** - * @return ServiceRegistration<\OCP\TaskProcessing\ITaskType>[] + * @return ServiceRegistration[] */ public function getTaskProcessingTaskTypes(): array { return $this->taskProcessingTaskTypes; } /** - * @return ServiceRegistration<\OCP\Files\Conversion\IConversionProvider>[] + * @return ServiceRegistration[] */ public function getFileConversionProviders(): array { return $this->fileConversionProviders; @@ -1029,6 +1026,6 @@ class RegistrationContext { return null; } - return \OCP\Server::get($this->configLexiconClasses[$appId]); + return Server::get($this->configLexiconClasses[$appId]); } } diff --git a/lib/private/AppFramework/Bootstrap/ServiceAliasRegistration.php b/lib/private/AppFramework/Bootstrap/ServiceAliasRegistration.php index aa3e38e4c46..928965d1d52 100644 --- a/lib/private/AppFramework/Bootstrap/ServiceAliasRegistration.php +++ b/lib/private/AppFramework/Bootstrap/ServiceAliasRegistration.php @@ -12,28 +12,22 @@ namespace OC\AppFramework\Bootstrap; * @psalm-immutable */ class ServiceAliasRegistration extends ARegistration { - /** - * @var string - * @psalm-var string|class-string - */ - private $alias; - - /** - * @var string - * @psalm-var string|class-string - */ - private $target; - /** * @psalm-param string|class-string $alias * @paslm-param string|class-string $target */ - public function __construct(string $appId, - string $alias, - string $target) { + public function __construct( + string $appId, + /** + * @psalm-var string|class-string + */ + private string $alias, + /** + * @psalm-var string|class-string + */ + private string $target, + ) { parent::__construct($appId); - $this->alias = $alias; - $this->target = $target; } /** diff --git a/lib/private/AppFramework/Bootstrap/ServiceFactoryRegistration.php b/lib/private/AppFramework/Bootstrap/ServiceFactoryRegistration.php index 63e73410b5a..1c1a2223590 100644 --- a/lib/private/AppFramework/Bootstrap/ServiceFactoryRegistration.php +++ b/lib/private/AppFramework/Bootstrap/ServiceFactoryRegistration.php @@ -12,29 +12,23 @@ namespace OC\AppFramework\Bootstrap; * @psalm-immutable */ class ServiceFactoryRegistration extends ARegistration { - /** - * @var string - * @psalm-var string|class-string - */ - private $name; - /** * @var callable * @psalm-var callable(\Psr\Container\ContainerInterface): mixed */ private $factory; - /** @var bool */ - private $shared; - - public function __construct(string $appId, - string $alias, + public function __construct( + string $appId, + /** + * @psalm-var string|class-string + */ + private string $name, callable $target, - bool $shared) { + private bool $shared, + ) { parent::__construct($appId); - $this->name = $alias; $this->factory = $target; - $this->shared = $shared; } public function getName(): string { diff --git a/lib/private/AppFramework/Bootstrap/ServiceRegistration.php b/lib/private/AppFramework/Bootstrap/ServiceRegistration.php index 6eda5e0196f..42825816a7e 100644 --- a/lib/private/AppFramework/Bootstrap/ServiceRegistration.php +++ b/lib/private/AppFramework/Bootstrap/ServiceRegistration.php @@ -13,18 +13,14 @@ namespace OC\AppFramework\Bootstrap; * @template T */ class ServiceRegistration extends ARegistration { - /** - * @var string - * @psalm-var class-string - */ - private $service; - /** * @psalm-param class-string $service */ - public function __construct(string $appId, string $service) { + public function __construct( + string $appId, + private string $service, + ) { parent::__construct($appId); - $this->service = $service; } /** diff --git a/lib/private/AppFramework/DependencyInjection/DIContainer.php b/lib/private/AppFramework/DependencyInjection/DIContainer.php index 82b840b8072..258c88f56f8 100644 --- a/lib/private/AppFramework/DependencyInjection/DIContainer.php +++ b/lib/private/AppFramework/DependencyInjection/DIContainer.php @@ -10,6 +10,8 @@ declare(strict_types=1); namespace OC\AppFramework\DependencyInjection; +use OC\AppFramework\App; +use OC\AppFramework\Bootstrap\Coordinator; use OC\AppFramework\Http; use OC\AppFramework\Http\Dispatcher; use OC\AppFramework\Http\Output; @@ -32,6 +34,8 @@ use OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware; use OC\AppFramework\Middleware\Security\SecurityMiddleware; use OC\AppFramework\Middleware\SessionMiddleware; use OC\AppFramework\ScopedPsrLogger; +use OC\AppFramework\Services\AppConfig; +use OC\AppFramework\Services\InitialState; use OC\AppFramework\Utility\ControllerMethodReflector; use OC\AppFramework\Utility\SimpleContainer; use OC\Core\Middleware\TwoFactorMiddleware; @@ -39,6 +43,7 @@ use OC\Diagnostics\EventLogger; use OC\Log\PsrLoggerAdapter; use OC\ServerContainer; use OC\Settings\AuthorizedGroupMapper; +use OC\User\Session; use OCA\WorkflowEngine\Manager; use OCP\App\IAppManager; use OCP\AppFramework\Http\IOutput; @@ -49,6 +54,7 @@ use OCP\AppFramework\Services\IInitialState; use OCP\Files\AppData\IAppDataFactory; use OCP\Files\Folder; use OCP\Files\IAppData; +use OCP\Files\IRootFolder; use OCP\Group\ISubAdmin; use OCP\IConfig; use OCP\IDBConnection; @@ -60,19 +66,23 @@ use OCP\IServerContainer; use OCP\ISession; use OCP\IURLGenerator; use OCP\IUserSession; +use OCP\L10N\IFactory; use OCP\Security\Ip\IRemoteAddress; +use OCP\Server; use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; class DIContainer extends SimpleContainer implements IAppContainer { - protected string $appName; private array $middleWares = []; private ServerContainer $server; - public function __construct(string $appName, array $urlParams = [], ?ServerContainer $server = null) { + public function __construct( + protected string $appName, + array $urlParams = [], + ?ServerContainer $server = null, + ) { parent::__construct(); - $this->appName = $appName; - $this->registerParameter('appName', $appName); + $this->registerParameter('appName', $this->appName); $this->registerParameter('urlParams', $urlParams); /** @deprecated 32.0.0 */ @@ -82,7 +92,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { $server = \OC::$server; } $this->server = $server; - $this->server->registerAppContainer($appName, $this); + $this->server->registerAppContainer($this->appName, $this); // aliases /** @deprecated 26.0.0 inject $appName */ @@ -99,7 +109,11 @@ class DIContainer extends SimpleContainer implements IAppContainer { $this->registerService(IOutput::class, fn (ContainerInterface $c): IOutput => new Output($c->get('webRoot'))); $this->registerService(Folder::class, function () { - return $this->getServer()->getUserFolder(); + $user = $this->get(IUserSession::class)->getUser(); + if ($user === null) { + return null; + } + return $this->getServer()->get(IRootFolder::class)->getUserFolder($user->getUID()); }); $this->registerService(IAppData::class, function (ContainerInterface $c): IAppData { @@ -107,7 +121,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { }); $this->registerService(IL10N::class, function (ContainerInterface $c) { - return $this->getServer()->getL10N($c->get('appName')); + return $this->getServer()->get(IFactory::class)->get($c->get('appName')); }); // Log wrappers @@ -199,11 +213,11 @@ class DIContainer extends SimpleContainer implements IAppContainer { $c->get(IURLGenerator::class), $c->get(LoggerInterface::class), $c->get('appName'), - $server->getUserSession()->isLoggedIn(), + $server->get(IUserSession::class)->isLoggedIn(), $c->get(IGroupManager::class), $c->get(ISubAdmin::class), $c->get(IAppManager::class), - $server->getL10N('lib'), + $server->get(IFactory::class)->get('lib'), $c->get(AuthorizedGroupMapper::class), $c->get(IUserSession::class), $c->get(IRemoteAddress::class), @@ -218,7 +232,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { $dispatcher->registerMiddleware($c->get(PublicShareMiddleware::class)); $dispatcher->registerMiddleware($c->get(AdditionalScriptsMiddleware::class)); - $coordinator = $c->get(\OC\AppFramework\Bootstrap\Coordinator::class); + $coordinator = $c->get(Coordinator::class); $registrationContext = $coordinator->getRegistrationContext(); if ($registrationContext !== null) { $appId = $this->get('appName'); @@ -237,14 +251,11 @@ class DIContainer extends SimpleContainer implements IAppContainer { return $dispatcher; }); - $this->registerAlias(IAppConfig::class, \OC\AppFramework\Services\AppConfig::class); - $this->registerAlias(IInitialState::class, \OC\AppFramework\Services\InitialState::class); + $this->registerAlias(IAppConfig::class, AppConfig::class); + $this->registerAlias(IInitialState::class, InitialState::class); } - /** - * @return \OCP\IServerContainer - */ - public function getServer() { + public function getServer(): ServerContainer { return $this->server; } @@ -272,7 +283,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { * @return boolean */ public function isLoggedIn() { - return \OC::$server->getUserSession()->isLoggedIn(); + return Server::get(IUserSession::class)->isLoggedIn(); } /** @@ -285,7 +296,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { } private function getUserId(): string { - return $this->getServer()->getSession()->get('user_id'); + return $this->getServer()->get(Session::class)->getSession()->get('user_id'); } /** @@ -294,7 +305,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { * @param string $serviceName e.g. 'OCA\Files\Capabilities' */ public function registerCapability($serviceName) { - $this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) { + $this->query(\OC\CapabilitiesManager::class)->registerCapability(function () use ($serviceName) { return $this->query($serviceName); }); } @@ -357,7 +368,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { return parent::query($name, chain: $chain); } elseif ($this->appName === 'core' && str_starts_with($name, 'OC\\Core\\')) { return parent::query($name, chain: $chain); - } elseif (str_starts_with($name, \OC\AppFramework\App::buildAppNamespace($this->appName) . '\\')) { + } elseif (str_starts_with($name, App::buildAppNamespace($this->appName) . '\\')) { return parent::query($name, chain: $chain); } elseif ( str_starts_with($name, 'OC\\AppFramework\\Services\\') diff --git a/lib/private/AppFramework/Http.php b/lib/private/AppFramework/Http.php index 08d6259c2a2..ee5a4397952 100644 --- a/lib/private/AppFramework/Http.php +++ b/lib/private/AppFramework/Http.php @@ -10,18 +10,16 @@ namespace OC\AppFramework; use OCP\AppFramework\Http as BaseHttp; class Http extends BaseHttp { - private $server; - private $protocolVersion; protected $headers; /** * @param array $server $_SERVER * @param string $protocolVersion the http version to use defaults to HTTP/1.1 */ - public function __construct($server, $protocolVersion = 'HTTP/1.1') { - $this->server = $server; - $this->protocolVersion = $protocolVersion; - + public function __construct( + private $server, + private $protocolVersion = 'HTTP/1.1', + ) { $this->headers = [ self::STATUS_CONTINUE => 'Continue', self::STATUS_SWITCHING_PROTOCOLS => 'Switching Protocols', diff --git a/lib/private/AppFramework/Http/Request.php b/lib/private/AppFramework/Http/Request.php index 6978d46f2d6..5cf2c9582e6 100644 --- a/lib/private/AppFramework/Http/Request.php +++ b/lib/private/AppFramework/Http/Request.php @@ -14,6 +14,7 @@ use OC\Security\TrustedDomainHelper; use OCP\IConfig; use OCP\IRequest; use OCP\IRequestId; +use OCP\Server; use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\IpUtils; @@ -44,8 +45,6 @@ class Request implements \ArrayAccess, \Countable, IRequest { public const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#'; public const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#'; public const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|\[::1\])$/'; - - protected string $inputStream; private bool $isPutStreamContentAlreadySent = false; protected array $items = []; protected array $allowedKeys = [ @@ -60,9 +59,6 @@ class Request implements \ArrayAccess, \Countable, IRequest { 'method', 'requesttoken', ]; - protected IRequestId $requestId; - protected IConfig $config; - protected ?CsrfTokenManager $csrfTokenManager; protected bool $contentDecoded = false; private ?\JsonException $decodingException = null; @@ -81,19 +77,17 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @param IRequestId $requestId * @param IConfig $config * @param CsrfTokenManager|null $csrfTokenManager - * @param string $stream + * @param string $inputStream * @see https://www.php.net/manual/en/reserved.variables.php */ - public function __construct(array $vars, - IRequestId $requestId, - IConfig $config, - ?CsrfTokenManager $csrfTokenManager = null, - string $stream = 'php://input') { - $this->inputStream = $stream; + public function __construct( + array $vars, + protected IRequestId $requestId, + protected IConfig $config, + protected ?CsrfTokenManager $csrfTokenManager = null, + protected string $inputStream = 'php://input', + ) { $this->items['params'] = []; - $this->requestId = $requestId; - $this->config = $config; - $this->csrfTokenManager = $csrfTokenManager; if (!array_key_exists('method', $vars)) { $vars['method'] = 'GET'; @@ -660,7 +654,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { if ($proto !== 'https' && $proto !== 'http') { // log unrecognized value so admin has a chance to fix it - \OCP\Server::get(LoggerInterface::class)->critical( + Server::get(LoggerInterface::class)->critical( 'Server protocol is malformed [falling back to http] (check overwriteprotocol and/or X-Forwarded-Proto to remedy): ' . $proto, ['app' => 'core'] ); diff --git a/lib/private/AppFramework/Http/RequestId.php b/lib/private/AppFramework/Http/RequestId.php index c3a99c93591..1fa2d351456 100644 --- a/lib/private/AppFramework/Http/RequestId.php +++ b/lib/private/AppFramework/Http/RequestId.php @@ -11,13 +11,10 @@ use OCP\IRequestId; use OCP\Security\ISecureRandom; class RequestId implements IRequestId { - protected ISecureRandom $secureRandom; - protected string $requestId; - - public function __construct(string $uniqueId, - ISecureRandom $secureRandom) { - $this->requestId = $uniqueId; - $this->secureRandom = $secureRandom; + public function __construct( + protected string $requestId, + protected ISecureRandom $secureRandom, + ) { } /** diff --git a/lib/private/AppFramework/Middleware/CompressionMiddleware.php b/lib/private/AppFramework/Middleware/CompressionMiddleware.php index 8bc56beb62e..1cdd8c19f05 100644 --- a/lib/private/AppFramework/Middleware/CompressionMiddleware.php +++ b/lib/private/AppFramework/Middleware/CompressionMiddleware.php @@ -20,11 +20,9 @@ class CompressionMiddleware extends Middleware { /** @var bool */ private $useGZip; - /** @var IRequest */ - private $request; - - public function __construct(IRequest $request) { - $this->request = $request; + public function __construct( + private IRequest $request, + ) { $this->useGZip = false; } diff --git a/lib/private/AppFramework/Middleware/NotModifiedMiddleware.php b/lib/private/AppFramework/Middleware/NotModifiedMiddleware.php index 08b30092155..e2514916d7d 100644 --- a/lib/private/AppFramework/Middleware/NotModifiedMiddleware.php +++ b/lib/private/AppFramework/Middleware/NotModifiedMiddleware.php @@ -14,11 +14,9 @@ use OCP\AppFramework\Middleware; use OCP\IRequest; class NotModifiedMiddleware extends Middleware { - /** @var IRequest */ - private $request; - - public function __construct(IRequest $request) { - $this->request = $request; + public function __construct( + private IRequest $request, + ) { } public function afterController($controller, $methodName, Response $response) { diff --git a/lib/private/AppFramework/Middleware/OCSMiddleware.php b/lib/private/AppFramework/Middleware/OCSMiddleware.php index dd3ae6f268b..d592b24a289 100644 --- a/lib/private/AppFramework/Middleware/OCSMiddleware.php +++ b/lib/private/AppFramework/Middleware/OCSMiddleware.php @@ -20,17 +20,15 @@ use OCP\AppFramework\OCSController; use OCP\IRequest; class OCSMiddleware extends Middleware { - /** @var IRequest */ - private $request; - /** @var int */ private $ocsVersion; /** * @param IRequest $request */ - public function __construct(IRequest $request) { - $this->request = $request; + public function __construct( + private IRequest $request, + ) { } /** @@ -59,7 +57,7 @@ class OCSMiddleware extends Middleware { if ($controller instanceof OCSController && $exception instanceof OCSException) { $code = $exception->getCode(); if ($code === 0) { - $code = \OCP\AppFramework\OCSController::RESPOND_UNKNOWN_ERROR; + $code = OCSController::RESPOND_UNKNOWN_ERROR; } return $this->buildNewResponse($controller, $code, $exception->getMessage()); @@ -72,7 +70,7 @@ class OCSMiddleware extends Middleware { * @param Controller $controller * @param string $methodName * @param Response $response - * @return \OCP\AppFramework\Http\Response + * @return Response */ public function afterController($controller, $methodName, Response $response) { /* diff --git a/lib/private/AppFramework/Middleware/Security/FeaturePolicyMiddleware.php b/lib/private/AppFramework/Middleware/Security/FeaturePolicyMiddleware.php index 921630e6326..632eceaa71b 100644 --- a/lib/private/AppFramework/Middleware/Security/FeaturePolicyMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/FeaturePolicyMiddleware.php @@ -16,11 +16,9 @@ use OCP\AppFramework\Http\Response; use OCP\AppFramework\Middleware; class FeaturePolicyMiddleware extends Middleware { - /** @var FeaturePolicyManager */ - private $policyManager; - - public function __construct(FeaturePolicyManager $policyManager) { - $this->policyManager = $policyManager; + public function __construct( + private FeaturePolicyManager $policyManager, + ) { } /** diff --git a/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php b/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php index e770fa4cbff..298921eedaa 100644 --- a/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php @@ -19,14 +19,10 @@ use OCP\IURLGenerator; * a reload but if the session variable is set we properly redirect to the login page. */ class ReloadExecutionMiddleware extends Middleware { - /** @var ISession */ - private $session; - /** @var IURLGenerator */ - private $urlGenerator; - - public function __construct(ISession $session, IURLGenerator $urlGenerator) { - $this->session = $session; - $this->urlGenerator = $urlGenerator; + public function __construct( + private ISession $session, + private IURLGenerator $urlGenerator, + ) { } public function beforeController($controller, $methodName) { diff --git a/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php b/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php index d0ca1b2ebe1..ac02253bccd 100644 --- a/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php @@ -19,6 +19,7 @@ use OC\AppFramework\Middleware\Security\Exceptions\SecurityException; use OC\AppFramework\Middleware\Security\Exceptions\StrictCookieMissingException; use OC\Settings\AuthorizedGroupMapper; use OC\User\Session; +use OCA\Talk\Controller\PageController; use OCP\App\AppPathNotFoundException; use OCP\App\IAppManager; use OCP\AppFramework\Controller; @@ -108,7 +109,8 @@ class SecurityMiddleware extends Middleware { // for normal HTML requests and not for AJAX requests $this->navigationManager->setActiveEntry($this->appName); - if (get_class($controller) === \OCA\Talk\Controller\PageController::class && $methodName === 'showCall') { + /** @psalm-suppress UndefinedClass */ + if (get_class($controller) === PageController::class && $methodName === 'showCall') { $this->navigationManager->setActiveEntry('spreed'); } diff --git a/lib/private/AppFramework/Middleware/SessionMiddleware.php b/lib/private/AppFramework/Middleware/SessionMiddleware.php index b7b0fb118c2..5b2ef810898 100644 --- a/lib/private/AppFramework/Middleware/SessionMiddleware.php +++ b/lib/private/AppFramework/Middleware/SessionMiddleware.php @@ -17,16 +17,10 @@ use OCP\ISession; use ReflectionMethod; class SessionMiddleware extends Middleware { - /** @var ControllerMethodReflector */ - private $reflector; - - /** @var ISession */ - private $session; - - public function __construct(ControllerMethodReflector $reflector, - ISession $session) { - $this->reflector = $reflector; - $this->session = $session; + public function __construct( + private ControllerMethodReflector $reflector, + private ISession $session, + ) { } /** diff --git a/lib/private/AppFramework/OCS/BaseResponse.php b/lib/private/AppFramework/OCS/BaseResponse.php index 05ce133db24..3f0a73f7f22 100644 --- a/lib/private/AppFramework/OCS/BaseResponse.php +++ b/lib/private/AppFramework/OCS/BaseResponse.php @@ -21,39 +21,20 @@ abstract class BaseResponse extends Response { /** @var array */ protected $data; - /** @var string */ - protected $format; - - /** @var ?string */ - protected $statusMessage; - - /** @var ?int */ - protected $itemsCount; - - /** @var ?int */ - protected $itemsPerPage; - /** * BaseResponse constructor. * * @param DataResponse $dataResponse - * @param string $format - * @param string|null $statusMessage - * @param int|null $itemsCount - * @param int|null $itemsPerPage */ - public function __construct(DataResponse $dataResponse, - $format = 'xml', - $statusMessage = null, - $itemsCount = null, - $itemsPerPage = null) { + public function __construct( + DataResponse $dataResponse, + protected string $format = 'xml', + protected ?string $statusMessage = null, + protected ?int $itemsCount = null, + protected ?int $itemsPerPage = null, + ) { parent::__construct(); - $this->format = $format; - $this->statusMessage = $statusMessage; - $this->itemsCount = $itemsCount; - $this->itemsPerPage = $itemsPerPage; - $this->data = $dataResponse->getData(); $this->setHeaders($dataResponse->getHeaders()); @@ -67,7 +48,7 @@ abstract class BaseResponse extends Response { $this->throttle($throttleMetadata); } - if ($format === 'json') { + if ($this->format === 'json') { $this->addHeader( 'Content-Type', 'application/json; charset=utf-8' ); diff --git a/lib/private/AppFramework/Routing/RouteActionHandler.php b/lib/private/AppFramework/Routing/RouteActionHandler.php index ec38105a5a0..085ef7178b3 100644 --- a/lib/private/AppFramework/Routing/RouteActionHandler.php +++ b/lib/private/AppFramework/Routing/RouteActionHandler.php @@ -11,18 +11,15 @@ use OC\AppFramework\App; use OC\AppFramework\DependencyInjection\DIContainer; class RouteActionHandler { - private $controllerName; - private $actionName; - private $container; - /** * @param string $controllerName * @param string $actionName */ - public function __construct(DIContainer $container, $controllerName, $actionName) { - $this->controllerName = $controllerName; - $this->actionName = $actionName; - $this->container = $container; + public function __construct( + private DIContainer $container, + private $controllerName, + private $actionName, + ) { } public function __invoke($params) { diff --git a/lib/private/AppFramework/ScopedPsrLogger.php b/lib/private/AppFramework/ScopedPsrLogger.php index 0a8e2b0d303..a413710a7d7 100644 --- a/lib/private/AppFramework/ScopedPsrLogger.php +++ b/lib/private/AppFramework/ScopedPsrLogger.php @@ -12,16 +12,10 @@ use Psr\Log\LoggerInterface; use function array_merge; class ScopedPsrLogger implements LoggerInterface { - /** @var LoggerInterface */ - private $inner; - - /** @var string */ - private $appId; - - public function __construct(LoggerInterface $inner, - string $appId) { - $this->inner = $inner; - $this->appId = $appId; + public function __construct( + private LoggerInterface $inner, + private string $appId, + ) { } public function emergency($message, array $context = []): void { diff --git a/lib/private/AppFramework/Services/InitialState.php b/lib/private/AppFramework/Services/InitialState.php index da225b612cf..51c5fbe672d 100644 --- a/lib/private/AppFramework/Services/InitialState.php +++ b/lib/private/AppFramework/Services/InitialState.php @@ -12,15 +12,10 @@ use OCP\AppFramework\Services\IInitialState; use OCP\IInitialStateService; class InitialState implements IInitialState { - /** @var IInitialStateService */ - private $state; - - /** @var string */ - private $appName; - - public function __construct(IInitialStateService $state, string $appName) { - $this->state = $state; - $this->appName = $appName; + public function __construct( + private IInitialStateService $state, + private string $appName, + ) { } public function provideInitialState(string $key, $data): void { diff --git a/lib/private/AppScriptSort.php b/lib/private/AppScriptSort.php index 134dad100dc..286d63c695c 100644 --- a/lib/private/AppScriptSort.php +++ b/lib/private/AppScriptSort.php @@ -14,11 +14,9 @@ use Psr\Log\LoggerInterface; * Implementation based on https://github.com/marcj/topsort.php */ class AppScriptSort { - /** @var LoggerInterface */ - private $logger; - - public function __construct(LoggerInterface $logger) { - $this->logger = $logger; + public function __construct( + private LoggerInterface $logger, + ) { } /** diff --git a/lib/private/Archive/TAR.php b/lib/private/Archive/TAR.php index f2b43862e20..4de0f35ccfa 100644 --- a/lib/private/Archive/TAR.php +++ b/lib/private/Archive/TAR.php @@ -8,6 +8,9 @@ namespace OC\Archive; use Icewind\Streams\CallbackWrapper; +use OCP\Files; +use OCP\ITempManager; +use OCP\Server; class TAR extends Archive { public const PLAIN = 0; @@ -25,12 +28,11 @@ class TAR extends Archive { private \Archive_Tar $tar; - private string $path; - - public function __construct(string $source) { + public function __construct( + private string $path, + ) { $types = [null, 'gz', 'bz2']; - $this->path = $source; - $this->tar = new \Archive_Tar($source, $types[self::getTarType($source)]); + $this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]); } /** @@ -60,7 +62,7 @@ class TAR extends Archive { * add an empty folder to the archive */ public function addFolder(string $path): bool { - $tmpBase = \OC::$server->getTempManager()->getTemporaryFolder(); + $tmpBase = Server::get(ITempManager::class)->getTemporaryFolder(); $path = rtrim($path, '/') . '/'; if ($this->fileExists($path)) { return false; @@ -103,7 +105,7 @@ class TAR extends Archive { */ public function rename(string $source, string $dest): bool { //no proper way to delete, rename entire archive, rename file and remake archive - $tmp = \OC::$server->getTempManager()->getTemporaryFolder(); + $tmp = Server::get(ITempManager::class)->getTemporaryFolder(); $this->tar->extract($tmp); rename($tmp . $source, $tmp . $dest); $this->tar->_close(); @@ -216,7 +218,7 @@ class TAR extends Archive { * extract a single file from the archive */ public function extractFile(string $path, string $dest): bool { - $tmp = \OC::$server->getTempManager()->getTemporaryFolder(); + $tmp = Server::get(ITempManager::class)->getTemporaryFolder(); if (!$this->fileExists($path)) { return false; } @@ -228,7 +230,7 @@ class TAR extends Archive { if ($success) { rename($tmp . $path, $dest); } - \OCP\Files::rmdirr($tmp); + Files::rmdirr($tmp); return $success; } @@ -272,9 +274,9 @@ class TAR extends Archive { $this->fileList = false; $this->cachedHeaders = false; //no proper way to delete, extract entire archive, delete file and remake archive - $tmp = \OC::$server->getTempManager()->getTemporaryFolder(); + $tmp = Server::get(ITempManager::class)->getTemporaryFolder(); $this->tar->extract($tmp); - \OCP\Files::rmdirr($tmp . $path); + Files::rmdirr($tmp . $path); unlink($this->path); $this->reopen(); $this->tar->createModify([$tmp], '', $tmp); @@ -293,7 +295,7 @@ class TAR extends Archive { } else { $ext = ''; } - $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext); + $tmpFile = Server::get(ITempManager::class)->getTemporaryFile($ext); if ($this->fileExists($path)) { $this->extractFile($path, $tmpFile); } elseif ($mode === 'r' || $mode === 'rb') { @@ -303,7 +305,7 @@ class TAR extends Archive { return fopen($tmpFile, $mode); } else { $handle = fopen($tmpFile, $mode); - return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) { + return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile): void { $this->writeBack($tmpFile, $path); }); } diff --git a/lib/private/Archive/ZIP.php b/lib/private/Archive/ZIP.php index bd1a0d6d9ed..0ed83110632 100644 --- a/lib/private/Archive/ZIP.php +++ b/lib/private/Archive/ZIP.php @@ -8,6 +8,8 @@ namespace OC\Archive; use Icewind\Streams\CallbackWrapper; +use OCP\ITempManager; +use OCP\Server; use Psr\Log\LoggerInterface; class ZIP extends Archive { @@ -16,17 +18,13 @@ class ZIP extends Archive { */ private $zip; - /** - * @var string - */ - private $path; - - public function __construct(string $source) { - $this->path = $source; + public function __construct( + private string $path, + ) { $this->zip = new \ZipArchive(); - if ($this->zip->open($source, \ZipArchive::CREATE)) { + if ($this->zip->open($this->path, \ZipArchive::CREATE)) { } else { - \OC::$server->get(LoggerInterface::class)->warning('Error while opening archive ' . $source, ['app' => 'files_archive']); + Server::get(LoggerInterface::class)->warning('Error while opening archive ' . $this->path, ['app' => 'files_archive']); } } @@ -200,12 +198,12 @@ class ZIP extends Archive { } else { $ext = ''; } - $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext); + $tmpFile = Server::get(ITempManager::class)->getTemporaryFile($ext); if ($this->fileExists($path)) { $this->extractFile($path, $tmpFile); } $handle = fopen($tmpFile, $mode); - return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) { + return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile): void { $this->writeBack($tmpFile, $path); }); } diff --git a/lib/private/Authentication/Events/ARemoteWipeEvent.php b/lib/private/Authentication/Events/ARemoteWipeEvent.php index ba1e93d26ae..438fcd2615d 100644 --- a/lib/private/Authentication/Events/ARemoteWipeEvent.php +++ b/lib/private/Authentication/Events/ARemoteWipeEvent.php @@ -12,12 +12,10 @@ use OC\Authentication\Token\IToken; use OCP\EventDispatcher\Event; abstract class ARemoteWipeEvent extends Event { - /** @var IToken */ - private $token; - - public function __construct(IToken $token) { + public function __construct( + private IToken $token, + ) { parent::__construct(); - $this->token = $token; } public function getToken(): IToken { diff --git a/lib/private/Authentication/Events/LoginFailed.php b/lib/private/Authentication/Events/LoginFailed.php index 23eeaef87ad..b946afc2afd 100644 --- a/lib/private/Authentication/Events/LoginFailed.php +++ b/lib/private/Authentication/Events/LoginFailed.php @@ -11,14 +11,11 @@ namespace OC\Authentication\Events; use OCP\EventDispatcher\Event; class LoginFailed extends Event { - private string $loginName; - private ?string $password; - - public function __construct(string $loginName, ?string $password) { + public function __construct( + private string $loginName, + private ?string $password, + ) { parent::__construct(); - - $this->loginName = $loginName; - $this->password = $password; } public function getLoginName(): string { diff --git a/lib/private/Authentication/Listeners/LoginFailedListener.php b/lib/private/Authentication/Listeners/LoginFailedListener.php index 0358887bb86..7e46d2e7b24 100644 --- a/lib/private/Authentication/Listeners/LoginFailedListener.php +++ b/lib/private/Authentication/Listeners/LoginFailedListener.php @@ -18,18 +18,13 @@ use OCP\IUserManager; use OCP\Util; /** - * @template-implements IEventListener<\OC\Authentication\Events\LoginFailed> + * @template-implements IEventListener */ class LoginFailedListener implements IEventListener { - /** @var IEventDispatcher */ - private $dispatcher; - - /** @var IUserManager */ - private $userManager; - - public function __construct(IEventDispatcher $dispatcher, IUserManager $userManager) { - $this->dispatcher = $dispatcher; - $this->userManager = $userManager; + public function __construct( + private IEventDispatcher $dispatcher, + private IUserManager $userManager, + ) { } public function handle(Event $event): void { diff --git a/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php b/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php index 457630eff27..b071886fd74 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php @@ -9,6 +9,7 @@ declare(strict_types=1); namespace OC\Authentication\Listeners; use BadMethodCallException; +use OC\Authentication\Events\ARemoteWipeEvent; use OC\Authentication\Events\RemoteWipeFinished; use OC\Authentication\Events\RemoteWipeStarted; use OC\Authentication\Token\IToken; @@ -18,19 +19,13 @@ use OCP\EventDispatcher\IEventListener; use Psr\Log\LoggerInterface; /** - * @template-implements IEventListener<\OC\Authentication\Events\ARemoteWipeEvent> + * @template-implements IEventListener */ class RemoteWipeActivityListener implements IEventListener { - /** @var IActvityManager */ - private $activityManager; - - /** @var LoggerInterface */ - private $logger; - - public function __construct(IActvityManager $activityManager, - LoggerInterface $logger) { - $this->activityManager = $activityManager; - $this->logger = $logger; + public function __construct( + private IActvityManager $activityManager, + private LoggerInterface $logger, + ) { } public function handle(Event $event): void { diff --git a/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php b/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php index 96878c44123..7572f997a5d 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php @@ -9,6 +9,7 @@ declare(strict_types=1); namespace OC\Authentication\Listeners; use Exception; +use OC\Authentication\Events\ARemoteWipeEvent; use OC\Authentication\Events\RemoteWipeFinished; use OC\Authentication\Events\RemoteWipeStarted; use OCP\EventDispatcher\Event; @@ -23,29 +24,19 @@ use Psr\Log\LoggerInterface; use function substr; /** - * @template-implements IEventListener<\OC\Authentication\Events\ARemoteWipeEvent> + * @template-implements IEventListener */ class RemoteWipeEmailListener implements IEventListener { - /** @var IMailer */ - private $mailer; - - /** @var IUserManager */ - private $userManager; - /** @var IL10N */ private $l10n; - /** @var LoggerInterface */ - private $logger; - - public function __construct(IMailer $mailer, - IUserManager $userManager, + public function __construct( + private IMailer $mailer, + private IUserManager $userManager, IL10nFactory $l10nFactory, - LoggerInterface $logger) { - $this->mailer = $mailer; - $this->userManager = $userManager; + private LoggerInterface $logger, + ) { $this->l10n = $l10nFactory->get('core'); - $this->logger = $logger; } /** diff --git a/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php b/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php index 5781c1edf16..5e5b0fcaa50 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php @@ -8,6 +8,7 @@ declare(strict_types=1); */ namespace OC\Authentication\Listeners; +use OC\Authentication\Events\ARemoteWipeEvent; use OC\Authentication\Events\RemoteWipeFinished; use OC\Authentication\Events\RemoteWipeStarted; use OC\Authentication\Token\IToken; @@ -17,19 +18,13 @@ use OCP\EventDispatcher\IEventListener; use OCP\Notification\IManager as INotificationManager; /** - * @template-implements IEventListener<\OC\Authentication\Events\ARemoteWipeEvent> + * @template-implements IEventListener */ class RemoteWipeNotificationsListener implements IEventListener { - /** @var INotificationManager */ - private $notificationManager; - - /** @var ITimeFactory */ - private $timeFactory; - - public function __construct(INotificationManager $notificationManager, - ITimeFactory $timeFactory) { - $this->notificationManager = $notificationManager; - $this->timeFactory = $timeFactory; + public function __construct( + private INotificationManager $notificationManager, + private ITimeFactory $timeFactory, + ) { } public function handle(Event $event): void { diff --git a/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php b/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php index 5f21c640780..d7a9bf4fb29 100644 --- a/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php +++ b/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php @@ -14,14 +14,12 @@ use OCP\EventDispatcher\IEventListener; use OCP\User\Events\UserDeletedEvent; /** - * @template-implements IEventListener<\OCP\User\Events\UserDeletedEvent> + * @template-implements IEventListener */ class UserDeletedStoreCleanupListener implements IEventListener { - /** @var Registry */ - private $registry; - - public function __construct(Registry $registry) { - $this->registry = $registry; + public function __construct( + private Registry $registry, + ) { } public function handle(Event $event): void { diff --git a/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php b/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php index 3631c04432c..6365e973ec6 100644 --- a/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php +++ b/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php @@ -16,19 +16,13 @@ use Psr\Log\LoggerInterface; use Throwable; /** - * @template-implements IEventListener<\OCP\User\Events\UserDeletedEvent> + * @template-implements IEventListener */ class UserDeletedTokenCleanupListener implements IEventListener { - /** @var Manager */ - private $manager; - - /** @var LoggerInterface */ - private $logger; - - public function __construct(Manager $manager, - LoggerInterface $logger) { - $this->manager = $manager; - $this->logger = $logger; + public function __construct( + private Manager $manager, + private LoggerInterface $logger, + ) { } public function handle(Event $event): void { diff --git a/lib/private/Authentication/Listeners/UserDeletedWebAuthnCleanupListener.php b/lib/private/Authentication/Listeners/UserDeletedWebAuthnCleanupListener.php index 67f8ff7cfcd..d025a2150a3 100644 --- a/lib/private/Authentication/Listeners/UserDeletedWebAuthnCleanupListener.php +++ b/lib/private/Authentication/Listeners/UserDeletedWebAuthnCleanupListener.php @@ -16,11 +16,9 @@ use OCP\User\Events\UserDeletedEvent; /** @template-implements IEventListener */ class UserDeletedWebAuthnCleanupListener implements IEventListener { - /** @var PublicKeyCredentialMapper */ - private $credentialMapper; - - public function __construct(PublicKeyCredentialMapper $credentialMapper) { - $this->credentialMapper = $credentialMapper; + public function __construct( + private PublicKeyCredentialMapper $credentialMapper, + ) { } public function handle(Event $event): void { diff --git a/lib/private/Authentication/Listeners/UserLoggedInListener.php b/lib/private/Authentication/Listeners/UserLoggedInListener.php index a8d4baeafa1..a4fc2d50611 100644 --- a/lib/private/Authentication/Listeners/UserLoggedInListener.php +++ b/lib/private/Authentication/Listeners/UserLoggedInListener.php @@ -14,14 +14,12 @@ use OCP\EventDispatcher\IEventListener; use OCP\User\Events\PostLoginEvent; /** - * @template-implements IEventListener<\OCP\User\Events\PostLoginEvent> + * @template-implements IEventListener */ class UserLoggedInListener implements IEventListener { - /** @var Manager */ - private $manager; - - public function __construct(Manager $manager) { - $this->manager = $manager; + public function __construct( + private Manager $manager, + ) { } public function handle(Event $event): void { diff --git a/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php b/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php index 40369c383ac..cd40348b056 100644 --- a/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php +++ b/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php @@ -11,11 +11,9 @@ namespace OC\Authentication\Login; use OCP\IConfig; class ClearLostPasswordTokensCommand extends ALoginCommand { - /** @var IConfig */ - private $config; - - public function __construct(IConfig $config) { - $this->config = $config; + public function __construct( + private IConfig $config, + ) { } /** diff --git a/lib/private/Authentication/Login/CompleteLoginCommand.php b/lib/private/Authentication/Login/CompleteLoginCommand.php index ec6fdf75f40..974775a2a3d 100644 --- a/lib/private/Authentication/Login/CompleteLoginCommand.php +++ b/lib/private/Authentication/Login/CompleteLoginCommand.php @@ -11,11 +11,9 @@ namespace OC\Authentication\Login; use OC\User\Session; class CompleteLoginCommand extends ALoginCommand { - /** @var Session */ - private $userSession; - - public function __construct(Session $userSession) { - $this->userSession = $userSession; + public function __construct( + private Session $userSession, + ) { } public function process(LoginData $loginData): LoginResult { diff --git a/lib/private/Authentication/Login/CreateSessionTokenCommand.php b/lib/private/Authentication/Login/CreateSessionTokenCommand.php index 21f0433d948..806af13eae4 100644 --- a/lib/private/Authentication/Login/CreateSessionTokenCommand.php +++ b/lib/private/Authentication/Login/CreateSessionTokenCommand.php @@ -13,16 +13,10 @@ use OC\User\Session; use OCP\IConfig; class CreateSessionTokenCommand extends ALoginCommand { - /** @var IConfig */ - private $config; - - /** @var Session */ - private $userSession; - - public function __construct(IConfig $config, - Session $userSession) { - $this->config = $config; - $this->userSession = $userSession; + public function __construct( + private IConfig $config, + private Session $userSession, + ) { } public function process(LoginData $loginData): LoginResult { diff --git a/lib/private/Authentication/Login/FinishRememberedLoginCommand.php b/lib/private/Authentication/Login/FinishRememberedLoginCommand.php index 3eb1f8f1a65..e455a67f31d 100644 --- a/lib/private/Authentication/Login/FinishRememberedLoginCommand.php +++ b/lib/private/Authentication/Login/FinishRememberedLoginCommand.php @@ -12,14 +12,10 @@ use OC\User\Session; use OCP\IConfig; class FinishRememberedLoginCommand extends ALoginCommand { - /** @var Session */ - private $userSession; - /** @var IConfig */ - private $config; - - public function __construct(Session $userSession, IConfig $config) { - $this->userSession = $userSession; - $this->config = $config; + public function __construct( + private Session $userSession, + private IConfig $config, + ) { } public function process(LoginData $loginData): LoginResult { diff --git a/lib/private/Authentication/Login/LoggedInCheckCommand.php b/lib/private/Authentication/Login/LoggedInCheckCommand.php index b6b59ced6ce..5ffa4d5dd27 100644 --- a/lib/private/Authentication/Login/LoggedInCheckCommand.php +++ b/lib/private/Authentication/Login/LoggedInCheckCommand.php @@ -14,15 +14,10 @@ use OCP\EventDispatcher\IEventDispatcher; use Psr\Log\LoggerInterface; class LoggedInCheckCommand extends ALoginCommand { - /** @var LoggerInterface */ - private $logger; - /** @var IEventDispatcher */ - private $dispatcher; - - public function __construct(LoggerInterface $logger, - IEventDispatcher $dispatcher) { - $this->logger = $logger; - $this->dispatcher = $dispatcher; + public function __construct( + private LoggerInterface $logger, + private IEventDispatcher $dispatcher, + ) { } public function process(LoginData $loginData): LoginResult { diff --git a/lib/private/Authentication/Login/LoginResult.php b/lib/private/Authentication/Login/LoginResult.php index 95e87b520e3..a71ff6da555 100644 --- a/lib/private/Authentication/Login/LoginResult.php +++ b/lib/private/Authentication/Login/LoginResult.php @@ -11,21 +11,16 @@ namespace OC\Authentication\Login; use OC\Core\Controller\LoginController; class LoginResult { - /** @var bool */ - private $success; - - /** @var LoginData */ - private $loginData; - /** @var string|null */ private $redirectUrl; /** @var string|null */ private $errorMessage; - private function __construct(bool $success, LoginData $loginData) { - $this->success = $success; - $this->loginData = $loginData; + private function __construct( + private bool $success, + private LoginData $loginData, + ) { } private function setRedirectUrl(string $url) { diff --git a/lib/private/Authentication/Login/PreLoginHookCommand.php b/lib/private/Authentication/Login/PreLoginHookCommand.php index d5aa174094d..5fd8a9dbaef 100644 --- a/lib/private/Authentication/Login/PreLoginHookCommand.php +++ b/lib/private/Authentication/Login/PreLoginHookCommand.php @@ -12,11 +12,9 @@ use OC\Hooks\PublicEmitter; use OCP\IUserManager; class PreLoginHookCommand extends ALoginCommand { - /** @var IUserManager */ - private $userManager; - - public function __construct(IUserManager $userManager) { - $this->userManager = $userManager; + public function __construct( + private IUserManager $userManager, + ) { } public function process(LoginData $loginData): LoginResult { diff --git a/lib/private/Authentication/Login/SetUserTimezoneCommand.php b/lib/private/Authentication/Login/SetUserTimezoneCommand.php index ea80fbfc714..635be703336 100644 --- a/lib/private/Authentication/Login/SetUserTimezoneCommand.php +++ b/lib/private/Authentication/Login/SetUserTimezoneCommand.php @@ -14,16 +14,10 @@ use OCP\IConfig; use OCP\ISession; class SetUserTimezoneCommand extends ALoginCommand { - /** @var IConfig */ - private $config; - - /** @var ISession */ - private $session; - - public function __construct(IConfig $config, - ISession $session) { - $this->config = $config; - $this->session = $session; + public function __construct( + private IConfig $config, + private ISession $session, + ) { } public function process(LoginData $loginData): LoginResult { diff --git a/lib/private/Authentication/Login/TwoFactorCommand.php b/lib/private/Authentication/Login/TwoFactorCommand.php index fc5285221a2..e66d16dc735 100644 --- a/lib/private/Authentication/Login/TwoFactorCommand.php +++ b/lib/private/Authentication/Login/TwoFactorCommand.php @@ -16,21 +16,11 @@ use function array_pop; use function count; class TwoFactorCommand extends ALoginCommand { - /** @var Manager */ - private $twoFactorManager; - - /** @var MandatoryTwoFactor */ - private $mandatoryTwoFactor; - - /** @var IURLGenerator */ - private $urlGenerator; - - public function __construct(Manager $twoFactorManager, - MandatoryTwoFactor $mandatoryTwoFactor, - IURLGenerator $urlGenerator) { - $this->twoFactorManager = $twoFactorManager; - $this->mandatoryTwoFactor = $mandatoryTwoFactor; - $this->urlGenerator = $urlGenerator; + public function __construct( + private Manager $twoFactorManager, + private MandatoryTwoFactor $mandatoryTwoFactor, + private IURLGenerator $urlGenerator, + ) { } public function process(LoginData $loginData): LoginResult { diff --git a/lib/private/Authentication/Login/UidLoginCommand.php b/lib/private/Authentication/Login/UidLoginCommand.php index 511b5f61e0e..c722a5057cc 100644 --- a/lib/private/Authentication/Login/UidLoginCommand.php +++ b/lib/private/Authentication/Login/UidLoginCommand.php @@ -12,11 +12,9 @@ use OC\User\Manager; use OCP\IUser; class UidLoginCommand extends ALoginCommand { - /** @var Manager */ - private $userManager; - - public function __construct(Manager $userManager) { - $this->userManager = $userManager; + public function __construct( + private Manager $userManager, + ) { } /** diff --git a/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php b/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php index 0582239e9de..a13dd1d6f17 100644 --- a/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php +++ b/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php @@ -11,11 +11,9 @@ namespace OC\Authentication\Login; use OCP\ISession; class UpdateLastPasswordConfirmCommand extends ALoginCommand { - /** @var ISession */ - private $session; - - public function __construct(ISession $session) { - $this->session = $session; + public function __construct( + private ISession $session, + ) { } public function process(LoginData $loginData): LoginResult { diff --git a/lib/private/Authentication/Login/UserDisabledCheckCommand.php b/lib/private/Authentication/Login/UserDisabledCheckCommand.php index 8777aa6dcea..be91fe42e56 100644 --- a/lib/private/Authentication/Login/UserDisabledCheckCommand.php +++ b/lib/private/Authentication/Login/UserDisabledCheckCommand.php @@ -13,16 +13,10 @@ use OCP\IUserManager; use Psr\Log\LoggerInterface; class UserDisabledCheckCommand extends ALoginCommand { - /** @var IUserManager */ - private $userManager; - - /** @var LoggerInterface */ - private $logger; - - public function __construct(IUserManager $userManager, - LoggerInterface $logger) { - $this->userManager = $userManager; - $this->logger = $logger; + public function __construct( + private IUserManager $userManager, + private LoggerInterface $logger, + ) { } public function process(LoginData $loginData): LoginResult { diff --git a/lib/private/Authentication/Login/WebAuthnChain.php b/lib/private/Authentication/Login/WebAuthnChain.php index ae523c43da6..6732a4339fa 100644 --- a/lib/private/Authentication/Login/WebAuthnChain.php +++ b/lib/private/Authentication/Login/WebAuthnChain.php @@ -9,57 +9,18 @@ declare(strict_types=1); namespace OC\Authentication\Login; class WebAuthnChain { - /** @var UserDisabledCheckCommand */ - private $userDisabledCheckCommand; - - /** @var LoggedInCheckCommand */ - private $loggedInCheckCommand; - - /** @var CompleteLoginCommand */ - private $completeLoginCommand; - - /** @var CreateSessionTokenCommand */ - private $createSessionTokenCommand; - - /** @var ClearLostPasswordTokensCommand */ - private $clearLostPasswordTokensCommand; - - /** @var UpdateLastPasswordConfirmCommand */ - private $updateLastPasswordConfirmCommand; - - /** @var SetUserTimezoneCommand */ - private $setUserTimezoneCommand; - - /** @var TwoFactorCommand */ - private $twoFactorCommand; - - /** @var FinishRememberedLoginCommand */ - private $finishRememberedLoginCommand; - - /** @var WebAuthnLoginCommand */ - private $webAuthnLoginCommand; - - public function __construct(UserDisabledCheckCommand $userDisabledCheckCommand, - WebAuthnLoginCommand $webAuthnLoginCommand, - LoggedInCheckCommand $loggedInCheckCommand, - CompleteLoginCommand $completeLoginCommand, - CreateSessionTokenCommand $createSessionTokenCommand, - ClearLostPasswordTokensCommand $clearLostPasswordTokensCommand, - UpdateLastPasswordConfirmCommand $updateLastPasswordConfirmCommand, - SetUserTimezoneCommand $setUserTimezoneCommand, - TwoFactorCommand $twoFactorCommand, - FinishRememberedLoginCommand $finishRememberedLoginCommand, + public function __construct( + private UserDisabledCheckCommand $userDisabledCheckCommand, + private WebAuthnLoginCommand $webAuthnLoginCommand, + private LoggedInCheckCommand $loggedInCheckCommand, + private CompleteLoginCommand $completeLoginCommand, + private CreateSessionTokenCommand $createSessionTokenCommand, + private ClearLostPasswordTokensCommand $clearLostPasswordTokensCommand, + private UpdateLastPasswordConfirmCommand $updateLastPasswordConfirmCommand, + private SetUserTimezoneCommand $setUserTimezoneCommand, + private TwoFactorCommand $twoFactorCommand, + private FinishRememberedLoginCommand $finishRememberedLoginCommand, ) { - $this->userDisabledCheckCommand = $userDisabledCheckCommand; - $this->webAuthnLoginCommand = $webAuthnLoginCommand; - $this->loggedInCheckCommand = $loggedInCheckCommand; - $this->completeLoginCommand = $completeLoginCommand; - $this->createSessionTokenCommand = $createSessionTokenCommand; - $this->clearLostPasswordTokensCommand = $clearLostPasswordTokensCommand; - $this->updateLastPasswordConfirmCommand = $updateLastPasswordConfirmCommand; - $this->setUserTimezoneCommand = $setUserTimezoneCommand; - $this->twoFactorCommand = $twoFactorCommand; - $this->finishRememberedLoginCommand = $finishRememberedLoginCommand; } public function process(LoginData $loginData): LoginResult { diff --git a/lib/private/Authentication/Login/WebAuthnLoginCommand.php b/lib/private/Authentication/Login/WebAuthnLoginCommand.php index 8f14e5b3f6d..3c9dcacbc8f 100644 --- a/lib/private/Authentication/Login/WebAuthnLoginCommand.php +++ b/lib/private/Authentication/Login/WebAuthnLoginCommand.php @@ -11,11 +11,9 @@ namespace OC\Authentication\Login; use OCP\IUserManager; class WebAuthnLoginCommand extends ALoginCommand { - /** @var IUserManager */ - private $userManager; - - public function __construct(IUserManager $userManager) { - $this->userManager = $userManager; + public function __construct( + private IUserManager $userManager, + ) { } public function process(LoginData $loginData): LoginResult { diff --git a/lib/private/Authentication/LoginCredentials/Credentials.php b/lib/private/Authentication/LoginCredentials/Credentials.php index 3414034b33c..27af14a022c 100644 --- a/lib/private/Authentication/LoginCredentials/Credentials.php +++ b/lib/private/Authentication/LoginCredentials/Credentials.php @@ -9,24 +9,16 @@ namespace OC\Authentication\LoginCredentials; use OCP\Authentication\LoginCredentials\ICredentials; class Credentials implements ICredentials { - /** @var string */ - private $uid; - - /** @var string */ - private $loginName; - - /** @var string */ - private $password; - /** * @param string $uid * @param string $loginName * @param string $password */ - public function __construct($uid, $loginName, $password) { - $this->uid = $uid; - $this->loginName = $loginName; - $this->password = $password; + public function __construct( + private $uid, + private $loginName, + private $password, + ) { } /** diff --git a/lib/private/Authentication/LoginCredentials/Store.php b/lib/private/Authentication/LoginCredentials/Store.php index 67c5712715c..45812ba4350 100644 --- a/lib/private/Authentication/LoginCredentials/Store.php +++ b/lib/private/Authentication/LoginCredentials/Store.php @@ -22,25 +22,12 @@ use OCP\Util; use Psr\Log\LoggerInterface; class Store implements IStore { - /** @var ISession */ - private $session; - - /** @var LoggerInterface */ - private $logger; - - /** @var IProvider|null */ - private $tokenProvider; - public function __construct( - ISession $session, - LoggerInterface $logger, + private ISession $session, + private LoggerInterface $logger, private readonly ICrypto $crypto, - ?IProvider $tokenProvider = null, + private ?IProvider $tokenProvider = null, ) { - $this->session = $session; - $this->logger = $logger; - $this->tokenProvider = $tokenProvider; - Util::connectHook('OC_User', 'post_login', $this, 'authenticate'); } diff --git a/lib/private/Authentication/Notifications/Notifier.php b/lib/private/Authentication/Notifications/Notifier.php index a81e385d8b1..7742eb95a2b 100644 --- a/lib/private/Authentication/Notifications/Notifier.php +++ b/lib/private/Authentication/Notifications/Notifier.php @@ -14,11 +14,9 @@ use OCP\Notification\INotifier; use OCP\Notification\UnknownNotificationException; class Notifier implements INotifier { - /** @var IL10nFactory */ - private $factory; - - public function __construct(IL10nFactory $l10nFactory) { - $this->factory = $l10nFactory; + public function __construct( + private IL10nFactory $factory, + ) { } /** diff --git a/lib/private/Authentication/Token/Manager.php b/lib/private/Authentication/Token/Manager.php index b55970a4979..f3eb78876b0 100644 --- a/lib/private/Authentication/Token/Manager.php +++ b/lib/private/Authentication/Token/Manager.php @@ -17,11 +17,9 @@ use OCP\Authentication\Token\IToken as OCPIToken; use OCP\DB\Exception; class Manager implements IProvider, OCPIProvider { - /** @var PublicKeyTokenProvider */ - private $publicKeyTokenProvider; - - public function __construct(PublicKeyTokenProvider $publicKeyTokenProvider) { - $this->publicKeyTokenProvider = $publicKeyTokenProvider; + public function __construct( + private PublicKeyTokenProvider $publicKeyTokenProvider, + ) { } /** diff --git a/lib/private/Authentication/Token/PublicKeyTokenProvider.php b/lib/private/Authentication/Token/PublicKeyTokenProvider.php index 82f9bdc0db6..14cd53435e3 100644 --- a/lib/private/Authentication/Token/PublicKeyTokenProvider.php +++ b/lib/private/Authentication/Token/PublicKeyTokenProvider.php @@ -34,53 +34,23 @@ class PublicKeyTokenProvider implements IProvider { use TTransactional; - /** @var PublicKeyTokenMapper */ - private $mapper; - - /** @var ICrypto */ - private $crypto; - - /** @var IConfig */ - private $config; - - private IDBConnection $db; - - /** @var LoggerInterface */ - private $logger; - - /** @var ITimeFactory */ - private $time; - /** @var ICache */ private $cache; - /** @var IHasher */ - private $hasher; - - private IEventDispatcher $eventDispatcher; - - public function __construct(PublicKeyTokenMapper $mapper, - ICrypto $crypto, - IConfig $config, - IDBConnection $db, - LoggerInterface $logger, - ITimeFactory $time, - IHasher $hasher, + public function __construct( + private PublicKeyTokenMapper $mapper, + private ICrypto $crypto, + private IConfig $config, + private IDBConnection $db, + private LoggerInterface $logger, + private ITimeFactory $time, + private IHasher $hasher, ICacheFactory $cacheFactory, - IEventDispatcher $eventDispatcher, + private IEventDispatcher $eventDispatcher, ) { - $this->mapper = $mapper; - $this->crypto = $crypto; - $this->config = $config; - $this->db = $db; - $this->logger = $logger; - $this->time = $time; - $this->cache = $cacheFactory->isLocalCacheAvailable() ? $cacheFactory->createLocal('authtoken_') : $cacheFactory->createInMemory(); - $this->hasher = $hasher; - $this->eventDispatcher = $eventDispatcher; } /** @@ -365,7 +335,7 @@ class PublicKeyTokenProvider implements IProvider { throw new InvalidTokenException('Invalid token type'); } - $this->atomic(function () use ($password, $token) { + $this->atomic(function () use ($password, $token): void { // When changing passwords all temp tokens are deleted $this->mapper->deleteTempToken($token); @@ -530,7 +500,7 @@ class PublicKeyTokenProvider implements IProvider { return; } - $this->atomic(function () use ($password, $uid) { + $this->atomic(function () use ($password, $uid): void { // Update the password for all tokens $tokens = $this->mapper->getTokenByUser($uid); $newPasswordHash = null; diff --git a/lib/private/Authentication/Token/RemoteWipe.php b/lib/private/Authentication/Token/RemoteWipe.php index 80ba330b66d..2a023f43b68 100644 --- a/lib/private/Authentication/Token/RemoteWipe.php +++ b/lib/private/Authentication/Token/RemoteWipe.php @@ -18,21 +18,11 @@ use Psr\Log\LoggerInterface; use function array_filter; class RemoteWipe { - /** @var IProvider */ - private $tokenProvider; - - /** @var IEventDispatcher */ - private $eventDispatcher; - - /** @var LoggerInterface */ - private $logger; - - public function __construct(IProvider $tokenProvider, - IEventDispatcher $eventDispatcher, - LoggerInterface $logger) { - $this->tokenProvider = $tokenProvider; - $this->eventDispatcher = $eventDispatcher; - $this->logger = $logger; + public function __construct( + private IProvider $tokenProvider, + private IEventDispatcher $eventDispatcher, + private LoggerInterface $logger, + ) { } /** diff --git a/lib/private/Authentication/Token/TokenCleanupJob.php b/lib/private/Authentication/Token/TokenCleanupJob.php index e6d1e69e9b4..ee6abebc850 100644 --- a/lib/private/Authentication/Token/TokenCleanupJob.php +++ b/lib/private/Authentication/Token/TokenCleanupJob.php @@ -10,11 +10,11 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\TimedJob; class TokenCleanupJob extends TimedJob { - private IProvider $provider; - - public function __construct(ITimeFactory $time, IProvider $provider) { + public function __construct( + ITimeFactory $time, + private IProvider $provider, + ) { parent::__construct($time); - $this->provider = $provider; // Run once a day at off-peak time $this->setInterval(24 * 60 * 60); $this->setTimeSensitivity(self::TIME_INSENSITIVE); diff --git a/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php b/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php index cc468dbeba0..613185a2aec 100644 --- a/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php +++ b/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php @@ -18,11 +18,9 @@ use function array_map; class ProviderUserAssignmentDao { public const TABLE_NAME = 'twofactor_providers'; - /** @var IDBConnection */ - private $conn; - - public function __construct(IDBConnection $dbConn) { - $this->conn = $dbConn; + public function __construct( + private IDBConnection $conn, + ) { } /** diff --git a/lib/private/Authentication/TwoFactorAuth/EnforcementState.php b/lib/private/Authentication/TwoFactorAuth/EnforcementState.php index e02064bc8f7..05014e09128 100644 --- a/lib/private/Authentication/TwoFactorAuth/EnforcementState.php +++ b/lib/private/Authentication/TwoFactorAuth/EnforcementState.php @@ -11,15 +11,6 @@ namespace OC\Authentication\TwoFactorAuth; use JsonSerializable; class EnforcementState implements JsonSerializable { - /** @var bool */ - private $enforced; - - /** @var array */ - private $enforcedGroups; - - /** @var array */ - private $excludedGroups; - /** * EnforcementState constructor. * @@ -27,12 +18,11 @@ class EnforcementState implements JsonSerializable { * @param string[] $enforcedGroups * @param string[] $excludedGroups */ - public function __construct(bool $enforced, - array $enforcedGroups = [], - array $excludedGroups = []) { - $this->enforced = $enforced; - $this->enforcedGroups = $enforcedGroups; - $this->excludedGroups = $excludedGroups; + public function __construct( + private bool $enforced, + private array $enforcedGroups = [], + private array $excludedGroups = [], + ) { } /** diff --git a/lib/private/Authentication/TwoFactorAuth/Manager.php b/lib/private/Authentication/TwoFactorAuth/Manager.php index 07aa98610ed..fe6aae0f99f 100644 --- a/lib/private/Authentication/TwoFactorAuth/Manager.php +++ b/lib/private/Authentication/TwoFactorAuth/Manager.php @@ -11,6 +11,7 @@ namespace OC\Authentication\TwoFactorAuth; use BadMethodCallException; use Exception; use OC\Authentication\Token\IProvider as TokenProvider; +use OC\User\Session; use OCP\Activity\IManager; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Utility\ITimeFactory; @@ -26,6 +27,8 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; use OCP\ISession; use OCP\IUser; +use OCP\IUserSession; +use OCP\Server; use OCP\Session\Exceptions\SessionNotAvailableException; use Psr\Log\LoggerInterface; use function array_diff; @@ -37,59 +40,21 @@ class Manager { public const REMEMBER_LOGIN = 'two_factor_remember_login'; public const BACKUP_CODES_PROVIDER_ID = 'backup_codes'; - /** @var ProviderLoader */ - private $providerLoader; - - /** @var IRegistry */ - private $providerRegistry; - - /** @var MandatoryTwoFactor */ - private $mandatoryTwoFactor; - - /** @var ISession */ - private $session; - - /** @var IConfig */ - private $config; - - /** @var IManager */ - private $activityManager; - - /** @var LoggerInterface */ - private $logger; - - /** @var TokenProvider */ - private $tokenProvider; - - /** @var ITimeFactory */ - private $timeFactory; - - /** @var IEventDispatcher */ - private $dispatcher; - /** @psalm-var array */ private $userIsTwoFactorAuthenticated = []; - public function __construct(ProviderLoader $providerLoader, - IRegistry $providerRegistry, - MandatoryTwoFactor $mandatoryTwoFactor, - ISession $session, - IConfig $config, - IManager $activityManager, - LoggerInterface $logger, - TokenProvider $tokenProvider, - ITimeFactory $timeFactory, - IEventDispatcher $eventDispatcher) { - $this->providerLoader = $providerLoader; - $this->providerRegistry = $providerRegistry; - $this->mandatoryTwoFactor = $mandatoryTwoFactor; - $this->session = $session; - $this->config = $config; - $this->activityManager = $activityManager; - $this->logger = $logger; - $this->tokenProvider = $tokenProvider; - $this->timeFactory = $timeFactory; - $this->dispatcher = $eventDispatcher; + public function __construct( + private ProviderLoader $providerLoader, + private IRegistry $providerRegistry, + private MandatoryTwoFactor $mandatoryTwoFactor, + private ISession $session, + private IConfig $config, + private IManager $activityManager, + private LoggerInterface $logger, + private TokenProvider $tokenProvider, + private ITimeFactory $timeFactory, + private IEventDispatcher $dispatcher, + ) { } /** @@ -239,7 +204,9 @@ class Manager { if ($passed) { if ($this->session->get(self::REMEMBER_LOGIN) === true) { // TODO: resolve cyclic dependency and use DI - \OC::$server->getUserSession()->createRememberMeToken($user); + /** @var Session $session */ + $session = Server::get(IUserSession::class); + $session->createRememberMeToken($user); } $this->session->remove(self::SESSION_UID_KEY); $this->session->remove(self::REMEMBER_LOGIN); diff --git a/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php b/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php index 37c9d3fc550..bf4c187f1e9 100644 --- a/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php +++ b/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php @@ -13,15 +13,10 @@ use OCP\IGroupManager; use OCP\IUser; class MandatoryTwoFactor { - /** @var IConfig */ - private $config; - - /** @var IGroupManager */ - private $groupManager; - - public function __construct(IConfig $config, IGroupManager $groupManager) { - $this->config = $config; - $this->groupManager = $groupManager; + public function __construct( + private IConfig $config, + private IGroupManager $groupManager, + ) { } /** diff --git a/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php b/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php index d3ba27088b2..d1bfc4f4085 100644 --- a/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php +++ b/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php @@ -14,6 +14,7 @@ use OCP\App\IAppManager; use OCP\AppFramework\QueryException; use OCP\Authentication\TwoFactorAuth\IProvider; use OCP\IUser; +use OCP\Server; class ProviderLoader { public const BACKUP_CODES_APP_ID = 'twofactor_backupcodes'; @@ -46,7 +47,7 @@ class ProviderLoader { foreach ($providerClasses as $class) { try { $this->loadTwoFactorApp($appId); - $provider = \OCP\Server::get($class); + $provider = Server::get($class); $providers[$provider->getId()] = $provider; } catch (QueryException $exc) { // Provider class can not be resolved @@ -60,7 +61,7 @@ class ProviderLoader { foreach ($registeredProviders as $provider) { try { $this->loadTwoFactorApp($provider->getAppId()); - $providerInstance = \OCP\Server::get($provider->getService()); + $providerInstance = Server::get($provider->getService()); $providers[$providerInstance->getId()] = $providerInstance; } catch (QueryException $exc) { // Provider class can not be resolved diff --git a/lib/private/Authentication/TwoFactorAuth/ProviderManager.php b/lib/private/Authentication/TwoFactorAuth/ProviderManager.php index 5ce4c598154..f82f666ac9d 100644 --- a/lib/private/Authentication/TwoFactorAuth/ProviderManager.php +++ b/lib/private/Authentication/TwoFactorAuth/ProviderManager.php @@ -16,15 +16,10 @@ use OCP\Authentication\TwoFactorAuth\IRegistry; use OCP\IUser; class ProviderManager { - /** @var ProviderLoader */ - private $providerLoader; - - /** @var IRegistry */ - private $providerRegistry; - - public function __construct(ProviderLoader $providerLoader, IRegistry $providerRegistry) { - $this->providerLoader = $providerLoader; - $this->providerRegistry = $providerRegistry; + public function __construct( + private ProviderLoader $providerLoader, + private IRegistry $providerRegistry, + ) { } private function getProvider(string $providerId, IUser $user): IProvider { diff --git a/lib/private/Authentication/TwoFactorAuth/ProviderSet.php b/lib/private/Authentication/TwoFactorAuth/ProviderSet.php index 15b82be6dec..d417721268c 100644 --- a/lib/private/Authentication/TwoFactorAuth/ProviderSet.php +++ b/lib/private/Authentication/TwoFactorAuth/ProviderSet.php @@ -19,19 +19,18 @@ class ProviderSet { /** @var IProvider */ private $providers; - /** @var bool */ - private $providerMissing; - /** * @param IProvider[] $providers * @param bool $providerMissing */ - public function __construct(array $providers, bool $providerMissing) { + public function __construct( + array $providers, + private bool $providerMissing, + ) { $this->providers = []; foreach ($providers as $provider) { $this->providers[$provider->getId()] = $provider; } - $this->providerMissing = $providerMissing; } /** diff --git a/lib/private/Authentication/TwoFactorAuth/Registry.php b/lib/private/Authentication/TwoFactorAuth/Registry.php index 544f60c4f97..6534daa41ca 100644 --- a/lib/private/Authentication/TwoFactorAuth/Registry.php +++ b/lib/private/Authentication/TwoFactorAuth/Registry.php @@ -20,16 +20,10 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\IUser; class Registry implements IRegistry { - /** @var ProviderUserAssignmentDao */ - private $assignmentDao; - - /** @var IEventDispatcher */ - private $dispatcher; - - public function __construct(ProviderUserAssignmentDao $assignmentDao, - IEventDispatcher $dispatcher) { - $this->assignmentDao = $assignmentDao; - $this->dispatcher = $dispatcher; + public function __construct( + private ProviderUserAssignmentDao $assignmentDao, + private IEventDispatcher $dispatcher, + ) { } public function getProviderStates(IUser $user): array { diff --git a/lib/private/Authentication/WebAuthn/CredentialRepository.php b/lib/private/Authentication/WebAuthn/CredentialRepository.php index 203f2ef9020..e6503d1c38a 100644 --- a/lib/private/Authentication/WebAuthn/CredentialRepository.php +++ b/lib/private/Authentication/WebAuthn/CredentialRepository.php @@ -16,11 +16,9 @@ use Webauthn\PublicKeyCredentialSourceRepository; use Webauthn\PublicKeyCredentialUserEntity; class CredentialRepository implements PublicKeyCredentialSourceRepository { - /** @var PublicKeyCredentialMapper */ - private $credentialMapper; - - public function __construct(PublicKeyCredentialMapper $credentialMapper) { - $this->credentialMapper = $credentialMapper; + public function __construct( + private PublicKeyCredentialMapper $credentialMapper, + ) { } public function findOneByCredentialId(string $publicKeyCredentialId): ?PublicKeyCredentialSource { diff --git a/lib/private/Authentication/WebAuthn/Manager.php b/lib/private/Authentication/WebAuthn/Manager.php index 96dc0719b54..c322c844c9c 100644 --- a/lib/private/Authentication/WebAuthn/Manager.php +++ b/lib/private/Authentication/WebAuthn/Manager.php @@ -37,28 +37,12 @@ use Webauthn\PublicKeyCredentialUserEntity; use Webauthn\TokenBinding\TokenBindingNotSupportedHandler; class Manager { - /** @var CredentialRepository */ - private $repository; - - /** @var PublicKeyCredentialMapper */ - private $credentialMapper; - - /** @var LoggerInterface */ - private $logger; - - /** @var IConfig */ - private $config; - public function __construct( - CredentialRepository $repository, - PublicKeyCredentialMapper $credentialMapper, - LoggerInterface $logger, - IConfig $config, + private CredentialRepository $repository, + private PublicKeyCredentialMapper $credentialMapper, + private LoggerInterface $logger, + private IConfig $config, ) { - $this->repository = $repository; - $this->credentialMapper = $credentialMapper; - $this->logger = $logger; - $this->config = $config; } public function startRegistration(IUser $user, string $serverHost): PublicKeyCredentialCreationOptions { diff --git a/lib/private/Avatar/Avatar.php b/lib/private/Avatar/Avatar.php index dc65c9d5743..987298e0483 100644 --- a/lib/private/Avatar/Avatar.php +++ b/lib/private/Avatar/Avatar.php @@ -15,6 +15,7 @@ use OCP\Color; use OCP\Files\NotFoundException; use OCP\IAvatar; use OCP\IConfig; +use OCP\Image; use Psr\Log\LoggerInterface; /** @@ -70,7 +71,7 @@ abstract class Avatar implements IAvatar { return false; } - $avatar = new \OCP\Image(); + $avatar = new Image(); $avatar->loadFromData($file->getContent()); return $avatar; } @@ -137,7 +138,7 @@ abstract class Avatar implements IAvatar { $avatar->setFont($font); $avatar->readImageBlob($svg); $avatar->setImageFormat('png'); - $image = new \OCP\Image(); + $image = new Image(); $image->loadFromData((string)$avatar); return $image->data(); } catch (\Exception $e) { diff --git a/lib/private/Avatar/GuestAvatar.php b/lib/private/Avatar/GuestAvatar.php index aa515e1ad4b..6d2e2df19fc 100644 --- a/lib/private/Avatar/GuestAvatar.php +++ b/lib/private/Avatar/GuestAvatar.php @@ -12,6 +12,7 @@ use OCP\Color; use OCP\Files\SimpleFS\InMemoryFile; use OCP\Files\SimpleFS\ISimpleFile; use OCP\IConfig; +use OCP\IImage; use Psr\Log\LoggerInterface; /** @@ -49,7 +50,7 @@ class GuestAvatar extends Avatar { /** * Setting avatars isn't implemented for guests. * - * @param \OCP\IImage|resource|string $data + * @param IImage|resource|string $data */ public function set($data): void { // unimplemented for guest user avatars diff --git a/lib/private/Avatar/PlaceholderAvatar.php b/lib/private/Avatar/PlaceholderAvatar.php index f5f49fb7cb2..8edf4d39a68 100644 --- a/lib/private/Avatar/PlaceholderAvatar.php +++ b/lib/private/Avatar/PlaceholderAvatar.php @@ -16,6 +16,7 @@ use OCP\Files\SimpleFS\ISimpleFile; use OCP\Files\SimpleFS\ISimpleFolder; use OCP\IConfig; use OCP\IImage; +use OCP\PreConditionNotMetException; use Psr\Log\LoggerInterface; /** @@ -70,8 +71,8 @@ class PlaceholderAvatar extends Avatar { * If there is no avatar file yet, one is generated. * * @throws NotFoundException - * @throws \OCP\Files\NotPermittedException - * @throws \OCP\PreConditionNotMetException + * @throws NotPermittedException + * @throws PreConditionNotMetException */ public function getFile(int $size, bool $darkTheme = false): ISimpleFile { $ext = 'png'; @@ -120,7 +121,7 @@ class PlaceholderAvatar extends Avatar { * @param mixed $oldValue The previous value * @param mixed $newValue The new value * @throws NotPermittedException - * @throws \OCP\PreConditionNotMetException + * @throws PreConditionNotMetException */ public function userChanged(string $feature, $oldValue, $newValue): void { $this->remove(); diff --git a/lib/private/Avatar/UserAvatar.php b/lib/private/Avatar/UserAvatar.php index aca2aa574bc..86fd1cf1220 100644 --- a/lib/private/Avatar/UserAvatar.php +++ b/lib/private/Avatar/UserAvatar.php @@ -17,6 +17,8 @@ use OCP\Files\SimpleFS\ISimpleFolder; use OCP\IConfig; use OCP\IImage; use OCP\IL10N; +use OCP\Image; +use OCP\PreConditionNotMetException; use Psr\Log\LoggerInterface; /** @@ -80,7 +82,7 @@ class UserAvatar extends Avatar { return $data; } - $img = new \OCP\Image(); + $img = new Image(); if ( (is_resource($data) && get_resource_type($data) === 'gd') || (is_object($data) && get_class($data) === \GdImage::class) @@ -145,8 +147,8 @@ class UserAvatar extends Avatar { /** * Removes the users avatar. - * @throws \OCP\Files\NotPermittedException - * @throws \OCP\PreConditionNotMetException + * @throws NotPermittedException + * @throws PreConditionNotMetException */ public function remove(bool $silent = false): void { $avatars = $this->folder->getDirectoryListing(); @@ -192,8 +194,8 @@ class UserAvatar extends Avatar { * If there is no avatar file yet, one is generated. * * @throws NotFoundException - * @throws \OCP\Files\NotPermittedException - * @throws \OCP\PreConditionNotMetException + * @throws NotPermittedException + * @throws PreConditionNotMetException */ public function getFile(int $size, bool $darkTheme = false): ISimpleFile { $generated = $this->folder->fileExists('generated'); @@ -240,7 +242,7 @@ class UserAvatar extends Avatar { $data = $this->generateAvatar($userDisplayName, $size, $darkTheme); } } else { - $avatar = new \OCP\Image(); + $avatar = new Image(); $file = $this->folder->getFile('avatar.' . $ext); $avatar->loadFromData($file->getContent()); $avatar->resize($size); @@ -278,7 +280,7 @@ class UserAvatar extends Avatar { * @param mixed $oldValue The previous value * @param mixed $newValue The new value * @throws NotPermittedException - * @throws \OCP\PreConditionNotMetException + * @throws PreConditionNotMetException */ public function userChanged(string $feature, $oldValue, $newValue): void { // If the avatar is not generated (so an uploaded image) we skip this diff --git a/lib/private/BackgroundJob/JobList.php b/lib/private/BackgroundJob/JobList.php index ab7a1981419..203a070bf2c 100644 --- a/lib/private/BackgroundJob/JobList.php +++ b/lib/private/BackgroundJob/JobList.php @@ -12,10 +12,12 @@ use OCP\AutoloadNotAllowedException; use OCP\BackgroundJob\IJob; use OCP\BackgroundJob\IJobList; use OCP\BackgroundJob\IParallelAwareJob; +use OCP\BackgroundJob\TimedJob; use OCP\DB\Exception; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IConfig; use OCP\IDBConnection; +use OCP\Server; use OCP\Snowflake\ISnowflakeGenerator; use Override; use Psr\Container\ContainerExceptionInterface; @@ -217,7 +219,7 @@ class JobList implements IJobList { unset($this->alreadyVisitedParallelBlocked[get_class($job)]); } - if ($job instanceof \OCP\BackgroundJob\TimedJob) { + if ($job instanceof TimedJob) { $now = $this->timeFactory->getTime(); $nextPossibleRun = $job->getLastRun() + $job->getInterval(); if ($now < $nextPossibleRun) { @@ -312,7 +314,7 @@ class JobList implements IJobList { try { // Try to load the job as a service /** @var IJob $job */ - $job = \OCP\Server::get($row['class']); + $job = Server::get($row['class']); } catch (ContainerExceptionInterface $e) { if (class_exists($row['class'])) { $class = $row['class']; @@ -363,7 +365,7 @@ class JobList implements IJobList { ->set('last_run', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT)) ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId()))); - if ($job instanceof \OCP\BackgroundJob\TimedJob + if ($job instanceof TimedJob && !$job->isTimeSensitive()) { $query->set('time_sensitive', $query->createNamedParameter(IJob::TIME_INSENSITIVE)); } diff --git a/lib/private/BinaryFinder.php b/lib/private/BinaryFinder.php index 74e72d1564a..221d05f5c27 100644 --- a/lib/private/BinaryFinder.php +++ b/lib/private/BinaryFinder.php @@ -12,6 +12,7 @@ use OCP\IBinaryFinder; use OCP\ICache; use OCP\ICacheFactory; use OCP\IConfig; +use OCP\Util; use Symfony\Component\Process\ExecutableFinder; /** @@ -47,7 +48,7 @@ class BinaryFinder implements IBinaryFinder { return $result; } $result = false; - if (\OCP\Util::isFunctionEnabled('exec')) { + if (Util::isFunctionEnabled('exec')) { $exeSniffer = new ExecutableFinder(); // Returns null if nothing is found $result = $exeSniffer->find( diff --git a/lib/private/Broadcast/Events/BroadcastEvent.php b/lib/private/Broadcast/Events/BroadcastEvent.php index d6c2cf49904..c0227a75c6a 100644 --- a/lib/private/Broadcast/Events/BroadcastEvent.php +++ b/lib/private/Broadcast/Events/BroadcastEvent.php @@ -14,13 +14,10 @@ use OCP\EventDispatcher\ABroadcastedEvent; use OCP\EventDispatcher\Event; class BroadcastEvent extends Event implements IBroadcastEvent { - /** @var ABroadcastedEvent */ - private $event; - - public function __construct(ABroadcastedEvent $event) { + public function __construct( + private ABroadcastedEvent $event, + ) { parent::__construct(); - - $this->event = $event; } public function getName(): string { diff --git a/lib/private/Cache/File.php b/lib/private/Cache/File.php index e5cd9c1dd30..82afdd4ce3e 100644 --- a/lib/private/Cache/File.php +++ b/lib/private/Cache/File.php @@ -9,8 +9,12 @@ namespace OC\Cache; use OC\Files\Filesystem; use OC\Files\View; +use OC\ForbiddenException; +use OC\User\NoUserException; +use OCP\Files\LockNotAcquiredException; use OCP\ICache; use OCP\IUserSession; +use OCP\Lock\LockedException; use OCP\Security\ISecureRandom; use OCP\Server; use Psr\Log\LoggerInterface; @@ -22,9 +26,9 @@ class File implements ICache { /** * Returns the cache storage for the logged in user * - * @return \OC\Files\View cache storage - * @throws \OC\ForbiddenException - * @throws \OC\User\NoUserException + * @return View cache storage + * @throws ForbiddenException + * @throws NoUserException */ protected function getStorage() { if ($this->storage !== null) { @@ -42,14 +46,14 @@ class File implements ICache { return $this->storage; } else { Server::get(LoggerInterface::class)->error('Can\'t get cache storage, user not logged in', ['app' => 'core']); - throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in'); + throw new ForbiddenException('Can\t get cache storage, user not logged in'); } } /** * @param string $key * @return mixed|null - * @throws \OC\ForbiddenException + * @throws ForbiddenException */ public function get($key) { $result = null; @@ -80,7 +84,7 @@ class File implements ICache { * @param mixed $value * @param int $ttl * @return bool|mixed - * @throws \OC\ForbiddenException + * @throws ForbiddenException */ public function set($key, $value, $ttl = 0) { $storage = $this->getStorage(); @@ -107,7 +111,7 @@ class File implements ICache { /** * @param string $key * @return bool - * @throws \OC\ForbiddenException + * @throws ForbiddenException */ public function hasKey($key) { $storage = $this->getStorage(); @@ -120,7 +124,7 @@ class File implements ICache { /** * @param string $key * @return bool|mixed - * @throws \OC\ForbiddenException + * @throws ForbiddenException */ public function remove($key) { $storage = $this->getStorage(); @@ -133,7 +137,7 @@ class File implements ICache { /** * @param string $prefix * @return bool - * @throws \OC\ForbiddenException + * @throws ForbiddenException */ public function clear($prefix = '') { $storage = $this->getStorage(); @@ -152,7 +156,7 @@ class File implements ICache { /** * Runs GC - * @throws \OC\ForbiddenException + * @throws ForbiddenException */ public function gc() { $storage = $this->getStorage(); @@ -171,12 +175,12 @@ class File implements ICache { if ($mtime < $now) { $storage->unlink('/' . $file); } - } catch (\OCP\Lock\LockedException $e) { + } catch (LockedException $e) { // ignore locked chunks Server::get(LoggerInterface::class)->debug('Could not cleanup locked chunk "' . $file . '"', ['app' => 'core']); } catch (\OCP\Files\ForbiddenException $e) { Server::get(LoggerInterface::class)->debug('Could not cleanup forbidden chunk "' . $file . '"', ['app' => 'core']); - } catch (\OCP\Files\LockNotAcquiredException $e) { + } catch (LockNotAcquiredException $e) { Server::get(LoggerInterface::class)->debug('Could not cleanup locked chunk "' . $file . '"', ['app' => 'core']); } } diff --git a/lib/private/Calendar/Resource/Manager.php b/lib/private/Calendar/Resource/Manager.php index db04e6a648a..221b77d4704 100644 --- a/lib/private/Calendar/Resource/Manager.php +++ b/lib/private/Calendar/Resource/Manager.php @@ -10,6 +10,7 @@ namespace OC\Calendar\Resource; use OC\AppFramework\Bootstrap\Coordinator; use OC\Calendar\ResourcesRoomsUpdater; +use OCP\AppFramework\QueryException; use OCP\Calendar\Resource\IBackend; use OCP\Calendar\Resource\IManager; use OCP\IServerContainer; @@ -69,7 +70,7 @@ class Manager implements IManager { /** * @return IBackend[] - * @throws \OCP\AppFramework\QueryException + * @throws QueryException * @since 14.0.0 */ public function getBackends():array { @@ -88,7 +89,7 @@ class Manager implements IManager { /** * @param string $backendId - * @throws \OCP\AppFramework\QueryException + * @throws QueryException */ public function getBackend($backendId): ?IBackend { $backends = $this->getBackends(); diff --git a/lib/private/Calendar/Room/Manager.php b/lib/private/Calendar/Room/Manager.php index 65897010f2a..8097fecb2ac 100644 --- a/lib/private/Calendar/Room/Manager.php +++ b/lib/private/Calendar/Room/Manager.php @@ -10,6 +10,7 @@ namespace OC\Calendar\Room; use OC\AppFramework\Bootstrap\Coordinator; use OC\Calendar\ResourcesRoomsUpdater; +use OCP\AppFramework\QueryException; use OCP\Calendar\Room\IBackend; use OCP\Calendar\Room\IManager; use OCP\IServerContainer; @@ -70,7 +71,7 @@ class Manager implements IManager { /** * @return IBackend[] - * @throws \OCP\AppFramework\QueryException + * @throws QueryException * @since 14.0.0 */ public function getBackends():array { @@ -95,7 +96,7 @@ class Manager implements IManager { /** * @param string $backendId - * @throws \OCP\AppFramework\QueryException + * @throws QueryException */ public function getBackend($backendId): ?IBackend { $backends = $this->getBackends(); diff --git a/lib/private/CapabilitiesManager.php b/lib/private/CapabilitiesManager.php index 07076d9aacd..2e33ceb67b2 100644 --- a/lib/private/CapabilitiesManager.php +++ b/lib/private/CapabilitiesManager.php @@ -12,6 +12,7 @@ use OCP\AppFramework\QueryException; use OCP\Capabilities\ICapability; use OCP\Capabilities\IInitialStateExcludedCapability; use OCP\Capabilities\IPublicCapability; +use OCP\ILogger; use Psr\Log\LoggerInterface; class CapabilitiesManager { @@ -24,11 +25,9 @@ class CapabilitiesManager { /** @var \Closure[] */ private $capabilities = []; - /** @var LoggerInterface */ - private $logger; - - public function __construct(LoggerInterface $logger) { - $this->logger = $logger; + public function __construct( + private LoggerInterface $logger, + ) { } /** @@ -63,11 +62,11 @@ class CapabilitiesManager { $timeSpent = $endTime - $startTime; if ($timeSpent > self::ACCEPTABLE_LOADING_TIME) { $logLevel = match (true) { - $timeSpent > self::ACCEPTABLE_LOADING_TIME * 16 => \OCP\ILogger::FATAL, - $timeSpent > self::ACCEPTABLE_LOADING_TIME * 8 => \OCP\ILogger::ERROR, - $timeSpent > self::ACCEPTABLE_LOADING_TIME * 4 => \OCP\ILogger::WARN, - $timeSpent > self::ACCEPTABLE_LOADING_TIME * 2 => \OCP\ILogger::INFO, - default => \OCP\ILogger::DEBUG, + $timeSpent > self::ACCEPTABLE_LOADING_TIME * 16 => ILogger::FATAL, + $timeSpent > self::ACCEPTABLE_LOADING_TIME * 8 => ILogger::ERROR, + $timeSpent > self::ACCEPTABLE_LOADING_TIME * 4 => ILogger::WARN, + $timeSpent > self::ACCEPTABLE_LOADING_TIME * 2 => ILogger::INFO, + default => ILogger::DEBUG, }; $this->logger->log( $logLevel, diff --git a/lib/private/Collaboration/Collaborators/Search.php b/lib/private/Collaboration/Collaborators/Search.php index ea39f885fc6..4fbfb787996 100644 --- a/lib/private/Collaboration/Collaborators/Search.php +++ b/lib/private/Collaboration/Collaborators/Search.php @@ -6,6 +6,7 @@ */ namespace OC\Collaboration\Collaborators; +use OCP\AppFramework\QueryException; use OCP\Collaboration\Collaborators\ISearch; use OCP\Collaboration\Collaborators\ISearchPlugin; use OCP\Collaboration\Collaborators\ISearchResult; @@ -26,7 +27,7 @@ class Search implements ISearch { * @param bool $lookup * @param int|null $limit * @param int|null $offset - * @throws \OCP\AppFramework\QueryException + * @throws QueryException */ public function search($search, array $shareTypes, $lookup, $limit, $offset): array { $hasMoreResults = false; diff --git a/lib/private/Collaboration/Resources/Collection.php b/lib/private/Collaboration/Resources/Collection.php index a8219bc633b..9bee7ea8dc8 100644 --- a/lib/private/Collaboration/Resources/Collection.php +++ b/lib/private/Collaboration/Resources/Collection.php @@ -78,7 +78,7 @@ class Collection implements ICollection { * @since 16.0.0 */ public function addResource(IResource $resource): void { - array_map(function (IResource $r) use ($resource) { + array_map(function (IResource $r) use ($resource): void { if ($this->isSameResource($r, $resource)) { throw new ResourceException('Already part of the collection'); } diff --git a/lib/private/Collaboration/Resources/Listener.php b/lib/private/Collaboration/Resources/Listener.php index dfdde24d78e..1ee792a0b55 100644 --- a/lib/private/Collaboration/Resources/Listener.php +++ b/lib/private/Collaboration/Resources/Listener.php @@ -13,37 +13,38 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\Group\Events\BeforeGroupDeletedEvent; use OCP\Group\Events\UserAddedEvent; use OCP\Group\Events\UserRemovedEvent; +use OCP\Server; use OCP\User\Events\UserDeletedEvent; class Listener { public static function register(IEventDispatcher $eventDispatcher): void { - $eventDispatcher->addListener(UserAddedEvent::class, function (UserAddedEvent $event) { + $eventDispatcher->addListener(UserAddedEvent::class, function (UserAddedEvent $event): void { $user = $event->getUser(); /** @var IManager $resourceManager */ - $resourceManager = \OCP\Server::get(IManager::class); + $resourceManager = Server::get(IManager::class); $resourceManager->invalidateAccessCacheForUser($user); }); - $eventDispatcher->addListener(UserRemovedEvent::class, function (UserRemovedEvent $event) { + $eventDispatcher->addListener(UserRemovedEvent::class, function (UserRemovedEvent $event): void { $user = $event->getUser(); /** @var IManager $resourceManager */ - $resourceManager = \OCP\Server::get(IManager::class); + $resourceManager = Server::get(IManager::class); $resourceManager->invalidateAccessCacheForUser($user); }); - $eventDispatcher->addListener(UserDeletedEvent::class, function (UserDeletedEvent $event) { + $eventDispatcher->addListener(UserDeletedEvent::class, function (UserDeletedEvent $event): void { $user = $event->getUser(); /** @var IManager $resourceManager */ - $resourceManager = \OCP\Server::get(IManager::class); + $resourceManager = Server::get(IManager::class); $resourceManager->invalidateAccessCacheForUser($user); }); - $eventDispatcher->addListener(BeforeGroupDeletedEvent::class, function (BeforeGroupDeletedEvent $event) { + $eventDispatcher->addListener(BeforeGroupDeletedEvent::class, function (BeforeGroupDeletedEvent $event): void { $group = $event->getGroup(); /** @var IManager $resourceManager */ - $resourceManager = \OCP\Server::get(IManager::class); + $resourceManager = Server::get(IManager::class); foreach ($group->getUsers() as $user) { $resourceManager->invalidateAccessCacheForUser($user); diff --git a/lib/private/Color.php b/lib/private/Color.php index d97c519e552..8e5cfb56c83 100644 --- a/lib/private/Color.php +++ b/lib/private/Color.php @@ -7,12 +7,10 @@ namespace OC; class Color { - public $r; - public $g; - public $b; - public function __construct($r, $g, $b) { - $this->r = $r; - $this->g = $g; - $this->b = $b; + public function __construct( + public $r, + public $g, + public $b, + ) { } } diff --git a/lib/private/Command/CommandJob.php b/lib/private/Command/CommandJob.php index 5ea2b35bf73..b22ed38fdee 100644 --- a/lib/private/Command/CommandJob.php +++ b/lib/private/Command/CommandJob.php @@ -7,6 +7,7 @@ */ namespace OC\Command; +use OCA\Files_Trashbin\Command\Expire; use OCP\BackgroundJob\QueuedJob; use OCP\Command\ICommand; @@ -19,7 +20,7 @@ class CommandJob extends QueuedJob { \Test\Command\SimpleCommand::class, \Test\Command\StateFullCommand::class, \Test\Command\FilesystemCommand::class, - \OCA\Files_Trashbin\Command\Expire::class, + Expire::class, \OCA\Files_Versions\Command\Expire::class, ]]); if ($command instanceof ICommand) { diff --git a/lib/private/Command/QueueBus.php b/lib/private/Command/QueueBus.php index 2712ef731a4..06c7bacf55e 100644 --- a/lib/private/Command/QueueBus.php +++ b/lib/private/Command/QueueBus.php @@ -9,6 +9,7 @@ declare(strict_types=1); */ namespace OC\Command; +use OCA\Files_Trashbin\Command\Expire; use OCP\Command\IBus; use OCP\Command\ICommand; @@ -41,7 +42,7 @@ class QueueBus implements IBus { \Test\Command\SimpleCommand::class, \Test\Command\StateFullCommand::class, \Test\Command\FilesystemCommand::class, - \OCA\Files_Trashbin\Command\Expire::class, + Expire::class, \OCA\Files_Versions\Command\Expire::class, ]]); $unserialized->handle(); diff --git a/lib/private/Comments/Manager.php b/lib/private/Comments/Manager.php index 58d05a64d12..59f4c824882 100644 --- a/lib/private/Comments/Manager.php +++ b/lib/private/Comments/Manager.php @@ -1325,7 +1325,7 @@ class Manager implements ICommentsManager { /** * deletes the read markers for the specified user * - * @param \OCP\IUser $user + * @param IUser $user * @return bool * @since 9.0.0 */ @@ -1512,7 +1512,7 @@ class Manager implements ICommentsManager { /** * returns valid, registered entities * - * @return \OCP\Comments\ICommentsEventHandler[] + * @return ICommentsEventHandler[] */ private function getEventHandlers() { if (!empty($this->eventHandlers)) { diff --git a/lib/private/Comments/ManagerFactory.php b/lib/private/Comments/ManagerFactory.php index 2436ca74c66..ec30fb00d3f 100644 --- a/lib/private/Comments/ManagerFactory.php +++ b/lib/private/Comments/ManagerFactory.php @@ -12,20 +12,17 @@ use OCP\Comments\ICommentsManagerFactory; use OCP\IServerContainer; class ManagerFactory implements ICommentsManagerFactory { - /** - * Server container - * - * @var IServerContainer - */ - private $serverContainer; - /** * Constructor for the comments manager factory * * @param IServerContainer $serverContainer server container */ - public function __construct(IServerContainer $serverContainer) { - $this->serverContainer = $serverContainer; + public function __construct( + /** + * Server container + */ + private IServerContainer $serverContainer, + ) { } /** diff --git a/lib/private/Config.php b/lib/private/Config.php index 30ccbb2f2d4..1d2d0c65ef3 100644 --- a/lib/private/Config.php +++ b/lib/private/Config.php @@ -8,6 +8,7 @@ namespace OC; use OCP\HintException; +use OCP\Util; /** * This class is responsible for reading and writing config.php, the very basic @@ -21,8 +22,6 @@ class Config { /** @var array */ protected $envCache = []; /** @var string */ - protected $configDir; - /** @var string */ protected $configFilePath; /** @var string */ protected $configFileName; @@ -33,8 +32,10 @@ class Config { * @param string $configDir Path to the config dir, needs to end with '/' * @param string $fileName (Optional) Name of the config file. Defaults to config.php */ - public function __construct($configDir, $fileName = 'config.php') { - $this->configDir = $configDir; + public function __construct( + protected $configDir, + $fileName = 'config.php', + ) { $this->configFilePath = $this->configDir . $fileName; $this->configFileName = $fileName; $this->readData(); @@ -237,7 +238,7 @@ class Config { // syntax issues in the config file like leading spaces causing PHP to send output $errorMessage = sprintf('Config file has leading content, please remove everything before "configLexiconDetails)) { $entries = $aliases = []; - $bootstrapCoordinator = \OCP\Server::get(Coordinator::class); + $bootstrapCoordinator = Server::get(Coordinator::class); $configLexicon = $bootstrapCoordinator->getRegistrationContext()?->getConfigLexicon($appId); foreach ($configLexicon?->getUserConfigs() ?? [] as $configEntry) { $entries[$configEntry->getKey()] = $configEntry; diff --git a/lib/private/Console/Application.php b/lib/private/Console/Application.php index 4cf1e0da8ca..2e4783a11cf 100644 --- a/lib/private/Console/Application.php +++ b/lib/private/Console/Application.php @@ -20,6 +20,7 @@ use OCP\IConfig; use OCP\IRequest; use OCP\Server; use OCP\ServerVersion; +use OCP\Util; use Psr\Container\ContainerExceptionInterface; use Psr\Log\LoggerInterface; use Symfony\Component\Console\Application as SymfonyApplication; @@ -82,7 +83,7 @@ class Application { try { require_once __DIR__ . '/../../../core/register_command.php'; if ($this->config->getSystemValueBool('installed', false)) { - if (\OCP\Util::needUpgrade()) { + if (Util::needUpgrade()) { throw new NeedsUpdateException(); } elseif ($this->config->getSystemValueBool('maintenance')) { $this->writeMaintenanceModeInfo($input, $output); diff --git a/lib/private/Console/TimestampFormatter.php b/lib/private/Console/TimestampFormatter.php index e8d9eef6b16..e5398e35a6d 100644 --- a/lib/private/Console/TimestampFormatter.php +++ b/lib/private/Console/TimestampFormatter.php @@ -12,9 +12,6 @@ use Symfony\Component\Console\Formatter\OutputFormatterInterface; use Symfony\Component\Console\Formatter\OutputFormatterStyleInterface; class TimestampFormatter implements OutputFormatterInterface { - /** @var ?IConfig */ - protected $config; - /** @var OutputFormatterInterface */ protected $formatter; @@ -22,8 +19,10 @@ class TimestampFormatter implements OutputFormatterInterface { * @param ?IConfig $config * @param OutputFormatterInterface $formatter */ - public function __construct(?IConfig $config, OutputFormatterInterface $formatter) { - $this->config = $config; + public function __construct( + protected ?IConfig $config, + OutputFormatterInterface $formatter, + ) { $this->formatter = $formatter; } diff --git a/lib/private/DB/Adapter.php b/lib/private/DB/Adapter.php index 8f1b8e6d75f..4acd28dba7c 100644 --- a/lib/private/DB/Adapter.php +++ b/lib/private/DB/Adapter.php @@ -17,12 +17,11 @@ use OC\DB\Exceptions\DbalException; */ class Adapter { /** - * @var \OC\DB\Connection $conn + * @param \OC\DB\Connection $conn */ - protected $conn; - - public function __construct($conn) { - $this->conn = $conn; + public function __construct( + protected $conn, + ) { } /** diff --git a/lib/private/DB/Connection.php b/lib/private/DB/Connection.php index f86cbc341a4..dd1d2683011 100644 --- a/lib/private/DB/Connection.php +++ b/lib/private/DB/Connection.php @@ -36,7 +36,9 @@ use OC\SystemConfig; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\DB\QueryBuilder\Sharded\IShardMapper; use OCP\Diagnostics\IEventLogger; +use OCP\EventDispatcher\IEventDispatcher; use OCP\ICacheFactory; +use OCP\IConfig; use OCP\IDBConnection; use OCP\ILogger; use OCP\IRequestId; @@ -53,7 +55,7 @@ class Connection extends PrimaryReadReplicaConnection { /** @var string */ protected $tablePrefix; - /** @var \OC\DB\Adapter $adapter */ + /** @var Adapter $adapter */ protected $adapter; /** @var SystemConfig */ @@ -143,7 +145,7 @@ class Connection extends PrimaryReadReplicaConnection { $this->shardConnectionManager, ); } - $this->systemConfig = \OC::$server->getSystemConfig(); + $this->systemConfig = Server::get(SystemConfig::class); $this->clock = Server::get(ClockInterface::class); $this->logger = Server::get(LoggerInterface::class); @@ -151,7 +153,7 @@ class Connection extends PrimaryReadReplicaConnection { $this->logDbException = $this->systemConfig->getValue('db.log_exceptions', false); $this->requestId = Server::get(IRequestId::class)->getId(); - /** @var \OCP\Profiler\IProfiler */ + /** @var IProfiler */ $profiler = Server::get(IProfiler::class); if ($profiler->isEnabled()) { $this->dbDataCollector = new DbDataCollector($this); @@ -820,10 +822,10 @@ class Connection extends PrimaryReadReplicaConnection { private function getMigrator() { // TODO properly inject those dependencies - $random = \OC::$server->get(ISecureRandom::class); + $random = Server::get(ISecureRandom::class); $platform = $this->getDatabasePlatform(); - $config = \OC::$server->getConfig(); - $dispatcher = Server::get(\OCP\EventDispatcher\IEventDispatcher::class); + $config = Server::get(IConfig::class); + $dispatcher = Server::get(IEventDispatcher::class); if ($platform instanceof SqlitePlatform) { return new SQLiteMigrator($this, $config, $dispatcher); } elseif ($platform instanceof OraclePlatform) { diff --git a/lib/private/DB/ConnectionAdapter.php b/lib/private/DB/ConnectionAdapter.php index d9ccb3c54f2..60b549dabcf 100644 --- a/lib/private/DB/ConnectionAdapter.php +++ b/lib/private/DB/ConnectionAdapter.php @@ -23,11 +23,9 @@ use OCP\IDBConnection; * Adapts the public API to our internal DBAL connection wrapper */ class ConnectionAdapter implements IDBConnection { - /** @var Connection */ - private $inner; - - public function __construct(Connection $inner) { - $this->inner = $inner; + public function __construct( + private Connection $inner, + ) { } public function getQueryBuilder(): IQueryBuilder { diff --git a/lib/private/DB/DbDataCollector.php b/lib/private/DB/DbDataCollector.php index e3c7cd35855..a85db66fc41 100644 --- a/lib/private/DB/DbDataCollector.php +++ b/lib/private/DB/DbDataCollector.php @@ -12,16 +12,17 @@ use Doctrine\DBAL\Types\ConversionException; use Doctrine\DBAL\Types\Type; use OC\AppFramework\Http\Request; use OCP\AppFramework\Http\Response; +use OCP\DataCollector\AbstractDataCollector; -class DbDataCollector extends \OCP\DataCollector\AbstractDataCollector { +class DbDataCollector extends AbstractDataCollector { protected ?BacktraceDebugStack $debugStack = null; - private Connection $connection; /** * DbDataCollector constructor. */ - public function __construct(Connection $connection) { - $this->connection = $connection; + public function __construct( + private Connection $connection, + ) { } public function setDebugStack(BacktraceDebugStack $debugStack, $name = 'default'): void { diff --git a/lib/private/DB/Exceptions/DbalException.php b/lib/private/DB/Exceptions/DbalException.php index 2ce6ddf80a6..fa22641fe28 100644 --- a/lib/private/DB/Exceptions/DbalException.php +++ b/lib/private/DB/Exceptions/DbalException.php @@ -35,21 +35,24 @@ use OCP\DB\Exception; class DbalException extends Exception { /** @var \Doctrine\DBAL\Exception */ private $original; - public readonly ?string $query; /** * @param \Doctrine\DBAL\Exception $original * @param int $code * @param string $message */ - private function __construct(\Doctrine\DBAL\Exception $original, int $code, string $message, ?string $query = null) { + private function __construct( + \Doctrine\DBAL\Exception $original, + int $code, + string $message, + public readonly ?string $query = null, + ) { parent::__construct( $message, $code, $original ); $this->original = $original; - $this->query = $query; } public static function wrap(\Doctrine\DBAL\Exception $original, string $message = '', ?string $query = null): self { diff --git a/lib/private/DB/MigrationException.php b/lib/private/DB/MigrationException.php index 5b50f8ed3a4..2fd58478d2f 100644 --- a/lib/private/DB/MigrationException.php +++ b/lib/private/DB/MigrationException.php @@ -8,10 +8,10 @@ namespace OC\DB; class MigrationException extends \Exception { - private $table; - - public function __construct($table, $message) { - $this->table = $table; + public function __construct( + private $table, + $message, + ) { parent::__construct($message); } diff --git a/lib/private/DB/MigrationService.php b/lib/private/DB/MigrationService.php index 9eeca432077..4f8ca639520 100644 --- a/lib/private/DB/MigrationService.php +++ b/lib/private/DB/MigrationService.php @@ -34,41 +34,36 @@ class MigrationService { private string $migrationsNamespace; private IOutput $output; private LoggerInterface $logger; - private Connection $connection; - private string $appName; - private bool $checkOracle; + private bool $checkOracle = false; /** * @throws \Exception */ public function __construct( - string $appName, - Connection $connection, + private string $appName, + private Connection $connection, ?IOutput $output = null, ?LoggerInterface $logger = null, ) { - $this->appName = $appName; - $this->checkOracle = false; - $this->connection = $connection; if ($logger === null) { $this->logger = Server::get(LoggerInterface::class); } else { $this->logger = $logger; } if ($output === null) { - $this->output = new SimpleOutput($this->logger, $appName); + $this->output = new SimpleOutput($this->logger, $this->appName); } else { $this->output = $output; } - if ($appName === 'core') { + if ($this->appName === 'core') { $this->migrationsPath = \OC::$SERVERROOT . '/core/Migrations'; $this->migrationsNamespace = 'OC\\Core\\Migrations'; $this->checkOracle = true; } else { $appManager = Server::get(IAppManager::class); - $appPath = $appManager->getAppPath($appName); - $namespace = App::buildAppNamespace($appName); + $appPath = $appManager->getAppPath($this->appName); + $namespace = App::buildAppNamespace($this->appName); $this->migrationsPath = "$appPath/lib/Migration"; $this->migrationsNamespace = $namespace . '\\Migration'; @@ -105,7 +100,7 @@ class MigrationService { return false; } - if ($this->connection->tableExists('migrations') && \OCP\Server::get(IConfig::class)->getAppValue('core', 'vendor', '') !== 'owncloud') { + if ($this->connection->tableExists('migrations') && Server::get(IConfig::class)->getAppValue('core', 'vendor', '') !== 'owncloud') { $this->migrationTableCreated = true; return false; } @@ -477,7 +472,7 @@ class MigrationService { /** @psalm-var class-string $class */ $class = $this->getClass($version); try { - $s = \OCP\Server::get($class); + $s = Server::get($class); } catch (NotFoundExceptionInterface) { if (class_exists($class)) { $s = new $class(); @@ -710,7 +705,7 @@ class MigrationService { } } elseif (!$primaryKey instanceof Index && !$sourceTable instanceof Table) { /** @var LoggerInterface $logger */ - $logger = \OCP\Server::get(LoggerInterface::class); + $logger = Server::get(LoggerInterface::class); $logger->error('Table "' . $table->getName() . '" has no primary key and therefor will not behave sane in clustered setups. This will throw an exception and not be installable in a future version of Nextcloud.'); // throw new \InvalidArgumentException('Table "' . $table->getName() . '" has no primary key and therefor will not behave sane in clustered setups.'); } diff --git a/lib/private/DB/Migrator.php b/lib/private/DB/Migrator.php index 40f8ad9676a..87d65b33b92 100644 --- a/lib/private/DB/Migrator.php +++ b/lib/private/DB/Migrator.php @@ -23,20 +23,15 @@ class Migrator { /** @var Connection */ protected $connection; - /** @var IConfig */ - protected $config; - - private ?IEventDispatcher $dispatcher; - /** @var bool */ private $noEmit = false; - public function __construct(Connection $connection, - IConfig $config, - ?IEventDispatcher $dispatcher = null) { + public function __construct( + Connection $connection, + protected IConfig $config, + private ?IEventDispatcher $dispatcher = null, + ) { $this->connection = $connection; - $this->config = $config; - $this->dispatcher = $dispatcher; } /** diff --git a/lib/private/DB/MigratorExecuteSqlEvent.php b/lib/private/DB/MigratorExecuteSqlEvent.php index 340cd636300..8a5c43cf5e5 100644 --- a/lib/private/DB/MigratorExecuteSqlEvent.php +++ b/lib/private/DB/MigratorExecuteSqlEvent.php @@ -11,18 +11,11 @@ namespace OC\DB; use OCP\EventDispatcher\Event; class MigratorExecuteSqlEvent extends Event { - private string $sql; - private int $current; - private int $max; - public function __construct( - string $sql, - int $current, - int $max, + private string $sql, + private int $current, + private int $max, ) { - $this->sql = $sql; - $this->current = $current; - $this->max = $max; } public function getSql(): string { diff --git a/lib/private/DB/ObjectParameter.php b/lib/private/DB/ObjectParameter.php index 1b013734c95..ed5894c92bf 100644 --- a/lib/private/DB/ObjectParameter.php +++ b/lib/private/DB/ObjectParameter.php @@ -11,19 +11,18 @@ declare(strict_types = 1); namespace OC\DB; final class ObjectParameter { - private $object; - private $error; private $stringable; private $class; /** * @param object $object */ - public function __construct($object, ?\Throwable $error) { - $this->object = $object; - $this->error = $error; - $this->stringable = \is_callable([$object, '__toString']); - $this->class = \get_class($object); + public function __construct( + private $object, + private ?\Throwable $error, + ) { + $this->stringable = \is_callable([$this->object, '__toString']); + $this->class = \get_class($this->object); } /** diff --git a/lib/private/DB/PgSqlTools.php b/lib/private/DB/PgSqlTools.php index d529cb26b09..94b1b65626e 100644 --- a/lib/private/DB/PgSqlTools.php +++ b/lib/private/DB/PgSqlTools.php @@ -16,14 +16,12 @@ use function preg_quote; * Various PostgreSQL specific helper functions. */ class PgSqlTools { - /** @var \OCP\IConfig */ - private $config; - /** - * @param \OCP\IConfig $config + * @param IConfig $config */ - public function __construct(IConfig $config) { - $this->config = $config; + public function __construct( + private IConfig $config, + ) { } /** diff --git a/lib/private/DB/QueryBuilder/CompositeExpression.php b/lib/private/DB/QueryBuilder/CompositeExpression.php index 122998036ae..0335d29cb42 100644 --- a/lib/private/DB/QueryBuilder/CompositeExpression.php +++ b/lib/private/DB/QueryBuilder/CompositeExpression.php @@ -25,7 +25,7 @@ class CompositeExpression implements ICompositeExpression, \Countable { * * @param array $parts * - * @return \OCP\DB\QueryBuilder\ICompositeExpression + * @return ICompositeExpression */ public function addMultiple(array $parts = []): ICompositeExpression { foreach ($parts as $part) { @@ -40,7 +40,7 @@ class CompositeExpression implements ICompositeExpression, \Countable { * * @param mixed $part * - * @return \OCP\DB\QueryBuilder\ICompositeExpression + * @return ICompositeExpression */ public function add($part): ICompositeExpression { if ($part === null) { diff --git a/lib/private/DB/QueryBuilder/ExpressionBuilder/ExpressionBuilder.php b/lib/private/DB/QueryBuilder/ExpressionBuilder/ExpressionBuilder.php index b922c861630..f57a5e3c347 100644 --- a/lib/private/DB/QueryBuilder/ExpressionBuilder/ExpressionBuilder.php +++ b/lib/private/DB/QueryBuilder/ExpressionBuilder/ExpressionBuilder.php @@ -20,7 +20,6 @@ use OCP\DB\QueryBuilder\ILiteral; use OCP\DB\QueryBuilder\IParameter; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\DB\QueryBuilder\IQueryFunction; -use OCP\IDBConnection; use Psr\Log\LoggerInterface; class ExpressionBuilder implements IExpressionBuilder { @@ -30,20 +29,16 @@ class ExpressionBuilder implements IExpressionBuilder { /** @var QuoteHelper */ protected $helper; - /** @var IDBConnection */ - protected $connection; - - /** @var LoggerInterface */ - protected $logger; - /** @var FunctionBuilder */ protected $functionBuilder; - public function __construct(ConnectionAdapter $connection, IQueryBuilder $queryBuilder, LoggerInterface $logger) { - $this->connection = $connection; - $this->logger = $logger; + public function __construct( + protected ConnectionAdapter $connection, + IQueryBuilder $queryBuilder, + protected LoggerInterface $logger, + ) { $this->helper = new QuoteHelper(); - $this->expressionBuilder = new DoctrineExpressionBuilder($connection->getInner()); + $this->expressionBuilder = new DoctrineExpressionBuilder($this->connection->getInner()); $this->functionBuilder = $queryBuilder->func(); } @@ -59,7 +54,7 @@ class ExpressionBuilder implements IExpressionBuilder { * @param mixed ...$x Optional clause. Defaults = null, but requires * at least one defined when converting to string. * - * @return \OCP\DB\QueryBuilder\ICompositeExpression + * @return ICompositeExpression */ public function andX(...$x): ICompositeExpression { if (empty($x)) { @@ -80,7 +75,7 @@ class ExpressionBuilder implements IExpressionBuilder { * @param mixed ...$x Optional clause. Defaults = null, but requires * at least one defined when converting to string. * - * @return \OCP\DB\QueryBuilder\ICompositeExpression + * @return ICompositeExpression */ public function orX(...$x): ICompositeExpression { if (empty($x)) { diff --git a/lib/private/DB/QueryBuilder/FunctionBuilder/FunctionBuilder.php b/lib/private/DB/QueryBuilder/FunctionBuilder/FunctionBuilder.php index f4ded03c2f7..c488bb7ff95 100644 --- a/lib/private/DB/QueryBuilder/FunctionBuilder/FunctionBuilder.php +++ b/lib/private/DB/QueryBuilder/FunctionBuilder/FunctionBuilder.php @@ -6,7 +6,6 @@ */ namespace OC\DB\QueryBuilder\FunctionBuilder; -use OC\DB\Connection; use OC\DB\QueryBuilder\QueryFunction; use OC\DB\QueryBuilder\QuoteHelper; use OCP\DB\QueryBuilder\IFunctionBuilder; @@ -16,19 +15,11 @@ use OCP\IDBConnection; use Override; class FunctionBuilder implements IFunctionBuilder { - /** @var IDBConnection|Connection */ - protected $connection; - - /** @var IQueryBuilder */ - protected $queryBuilder; - - /** @var QuoteHelper */ - protected $helper; - - public function __construct(IDBConnection $connection, IQueryBuilder $queryBuilder, QuoteHelper $helper) { - $this->connection = $connection; - $this->queryBuilder = $queryBuilder; - $this->helper = $helper; + public function __construct( + protected IDBConnection $connection, + protected IQueryBuilder $queryBuilder, + protected QuoteHelper $helper, + ) { } public function md5($input): IQueryFunction { diff --git a/lib/private/DB/QueryBuilder/FunctionBuilder/OCIFunctionBuilder.php b/lib/private/DB/QueryBuilder/FunctionBuilder/OCIFunctionBuilder.php index 47a8eaa6fd0..6959d13b720 100644 --- a/lib/private/DB/QueryBuilder/FunctionBuilder/OCIFunctionBuilder.php +++ b/lib/private/DB/QueryBuilder/FunctionBuilder/OCIFunctionBuilder.php @@ -6,6 +6,7 @@ */ namespace OC\DB\QueryBuilder\FunctionBuilder; +use OC\DB\ConnectionAdapter; use OC\DB\QueryBuilder\QueryFunction; use OCP\DB\QueryBuilder\ILiteral; use OCP\DB\QueryBuilder\IParameter; @@ -13,7 +14,9 @@ use OCP\DB\QueryBuilder\IQueryFunction; class OCIFunctionBuilder extends FunctionBuilder { public function md5($input): IQueryFunction { - if (version_compare($this->connection->getServerVersion(), '20', '>=')) { + /** @var ConnectionAdapter $co */ + $co = $this->connection; + if (version_compare($co->getServerVersion(), '20', '>=')) { return new QueryFunction('LOWER(STANDARD_HASH(' . $this->helper->quoteColumnName($input) . ", 'MD5'))"); } return new QueryFunction('LOWER(DBMS_OBFUSCATION_TOOLKIT.md5 (input => UTL_RAW.cast_to_raw(' . $this->helper->quoteColumnName($input) . ')))'); diff --git a/lib/private/DB/QueryBuilder/Literal.php b/lib/private/DB/QueryBuilder/Literal.php index 3fb897328e5..8cdb071b52b 100644 --- a/lib/private/DB/QueryBuilder/Literal.php +++ b/lib/private/DB/QueryBuilder/Literal.php @@ -10,11 +10,12 @@ namespace OC\DB\QueryBuilder; use OCP\DB\QueryBuilder\ILiteral; class Literal implements ILiteral { - /** @var mixed */ - protected $literal; - - public function __construct($literal) { - $this->literal = $literal; + /** + * @param mixed $literal + */ + public function __construct( + protected $literal, + ) { } public function __toString(): string { diff --git a/lib/private/DB/QueryBuilder/Parameter.php b/lib/private/DB/QueryBuilder/Parameter.php index a272c744d62..11732c973fc 100644 --- a/lib/private/DB/QueryBuilder/Parameter.php +++ b/lib/private/DB/QueryBuilder/Parameter.php @@ -10,11 +10,12 @@ namespace OC\DB\QueryBuilder; use OCP\DB\QueryBuilder\IParameter; class Parameter implements IParameter { - /** @var mixed */ - protected $name; - - public function __construct($name) { - $this->name = $name; + /** + * @param mixed $name + */ + public function __construct( + protected $name, + ) { } public function __toString(): string { diff --git a/lib/private/DB/QueryBuilder/QueryBuilder.php b/lib/private/DB/QueryBuilder/QueryBuilder.php index e88af61a705..962ad48b1c4 100644 --- a/lib/private/DB/QueryBuilder/QueryBuilder.php +++ b/lib/private/DB/QueryBuilder/QueryBuilder.php @@ -20,6 +20,8 @@ use OC\DB\QueryBuilder\FunctionBuilder\SqliteFunctionBuilder; use OC\SystemConfig; use OCP\DB\IResult; use OCP\DB\QueryBuilder\ICompositeExpression; +use OCP\DB\QueryBuilder\IExpressionBuilder; +use OCP\DB\QueryBuilder\IFunctionBuilder; use OCP\DB\QueryBuilder\ILiteral; use OCP\DB\QueryBuilder\IParameter; use OCP\DB\QueryBuilder\IQueryBuilder; @@ -28,38 +30,21 @@ use OCP\IDBConnection; use Psr\Log\LoggerInterface; class QueryBuilder implements IQueryBuilder { - /** @var ConnectionAdapter */ - private $connection; - - /** @var SystemConfig */ - private $systemConfig; - - private LoggerInterface $logger; - - /** @var \Doctrine\DBAL\Query\QueryBuilder */ - private $queryBuilder; - - /** @var QuoteHelper */ - private $helper; - - /** @var bool */ - private $automaticTablePrefix = true; + private \Doctrine\DBAL\Query\QueryBuilder $queryBuilder; + private QuoteHelper $helper; + private bool $automaticTablePrefix = true; private bool $nonEmptyWhere = false; - - /** @var string */ - protected $lastInsertedTable; + protected ?string $lastInsertedTable = null; private array $selectedColumns = []; /** * Initializes a new QueryBuilder. - * - * @param ConnectionAdapter $connection - * @param SystemConfig $systemConfig */ - public function __construct(ConnectionAdapter $connection, SystemConfig $systemConfig, LoggerInterface $logger) { - $this->connection = $connection; - $this->systemConfig = $systemConfig; - $this->logger = $logger; + public function __construct( + private ConnectionAdapter $connection, + private SystemConfig $systemConfig, + private LoggerInterface $logger, + ) { $this->queryBuilder = new \Doctrine\DBAL\Query\QueryBuilder($this->connection->getInner()); $this->helper = new QuoteHelper(); } @@ -89,7 +74,7 @@ class QueryBuilder implements IQueryBuilder { * For more complex expression construction, consider storing the expression * builder object in a local variable. * - * @return \OCP\DB\QueryBuilder\IExpressionBuilder + * @return IExpressionBuilder */ public function expr() { return match($this->connection->getDatabaseProvider()) { @@ -115,7 +100,7 @@ class QueryBuilder implements IQueryBuilder { * For more complex function construction, consider storing the function * builder object in a local variable. * - * @return \OCP\DB\QueryBuilder\IFunctionBuilder + * @return IFunctionBuilder */ public function func() { return match($this->connection->getDatabaseProvider()) { @@ -139,7 +124,7 @@ class QueryBuilder implements IQueryBuilder { /** * Gets the associated DBAL Connection for this query builder. * - * @return \OCP\IDBConnection + * @return IDBConnection */ public function getConnection() { return $this->connection; diff --git a/lib/private/DB/QueryBuilder/QueryFunction.php b/lib/private/DB/QueryBuilder/QueryFunction.php index 7f2ab584a73..ae168b0bc63 100644 --- a/lib/private/DB/QueryBuilder/QueryFunction.php +++ b/lib/private/DB/QueryBuilder/QueryFunction.php @@ -10,11 +10,12 @@ namespace OC\DB\QueryBuilder; use OCP\DB\QueryBuilder\IQueryFunction; class QueryFunction implements IQueryFunction { - /** @var string */ - protected $function; - - public function __construct($function) { - $this->function = $function; + /** + * @param string $function + */ + public function __construct( + protected $function, + ) { } public function __toString(): string { diff --git a/lib/private/DB/QueryBuilder/Sharded/ShardConnectionManager.php b/lib/private/DB/QueryBuilder/Sharded/ShardConnectionManager.php index 74358e3ca96..18dcc68fd4c 100644 --- a/lib/private/DB/QueryBuilder/Sharded/ShardConnectionManager.php +++ b/lib/private/DB/QueryBuilder/Sharded/ShardConnectionManager.php @@ -12,6 +12,7 @@ use OC\DB\ConnectionAdapter; use OC\DB\ConnectionFactory; use OC\SystemConfig; use OCP\IDBConnection; +use OCP\Server; /** * Keeps track of the db connections to the various shards @@ -34,7 +35,7 @@ class ShardConnectionManager { } if ($shard === ShardDefinition::MIGRATION_SHARD) { - $this->connections[$connectionKey] = \OC::$server->get(IDBConnection::class); + $this->connections[$connectionKey] = Server::get(IDBConnection::class); } elseif (isset($shardDefinition->shards[$shard])) { $this->connections[$connectionKey] = $this->createConnection($shardDefinition->shards[$shard]); } else { diff --git a/lib/private/DB/SQLiteSessionInit.php b/lib/private/DB/SQLiteSessionInit.php index 3e05b6e59a1..32a8e3639fa 100644 --- a/lib/private/DB/SQLiteSessionInit.php +++ b/lib/private/DB/SQLiteSessionInit.php @@ -12,25 +12,16 @@ use Doctrine\DBAL\Event\ConnectionEventArgs; use Doctrine\DBAL\Events; class SQLiteSessionInit implements EventSubscriber { - /** - * @var bool - */ - private $caseSensitiveLike; - - /** - * @var string - */ - private $journalMode; - /** * Configure case sensitive like for each connection * * @param bool $caseSensitiveLike * @param string $journalMode */ - public function __construct($caseSensitiveLike, $journalMode) { - $this->caseSensitiveLike = $caseSensitiveLike; - $this->journalMode = $journalMode; + public function __construct( + private $caseSensitiveLike, + private $journalMode, + ) { } /** diff --git a/lib/private/DB/SchemaWrapper.php b/lib/private/DB/SchemaWrapper.php index 19a0bc576f2..273c591038b 100644 --- a/lib/private/DB/SchemaWrapper.php +++ b/lib/private/DB/SchemaWrapper.php @@ -15,17 +15,16 @@ use OCP\Server; use Psr\Log\LoggerInterface; class SchemaWrapper implements ISchemaWrapper { - /** @var Connection */ - protected $connection; - /** @var Schema */ protected $schema; /** @var array */ protected $tablesToDelete = []; - public function __construct(Connection $connection, ?Schema $schema = null) { - $this->connection = $connection; + public function __construct( + protected Connection $connection, + ?Schema $schema = null, + ) { if ($schema) { $this->schema = $schema; } else { diff --git a/lib/private/Dashboard/Manager.php b/lib/private/Dashboard/Manager.php index d4a9eb189ff..d6ced08e1bb 100644 --- a/lib/private/Dashboard/Manager.php +++ b/lib/private/Dashboard/Manager.php @@ -13,6 +13,7 @@ use OCP\App\IAppManager; use OCP\Dashboard\IConditionalWidget; use OCP\Dashboard\IManager; use OCP\Dashboard\IWidget; +use OCP\Server; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; @@ -68,7 +69,7 @@ class Manager implements IManager { * There is a circular dependency between the logger and the registry, so * we can not inject it. Thus the static call. */ - \OC::$server->get(LoggerInterface::class)->critical( + Server::get(LoggerInterface::class)->critical( 'Could not load lazy dashboard widget: ' . $service['class'], ['exception' => $e] ); @@ -89,7 +90,7 @@ class Manager implements IManager { * There is a circular dependency between the logger and the registry, so * we can not inject it. Thus the static call. */ - \OC::$server->get(LoggerInterface::class)->critical( + Server::get(LoggerInterface::class)->critical( 'Could not register lazy dashboard widget: ' . $service['class'], ['exception' => $e] ); @@ -102,7 +103,7 @@ class Manager implements IManager { $endTime = microtime(true); $duration = $endTime - $startTime; if ($duration > 1) { - \OC::$server->get(LoggerInterface::class)->info( + Server::get(LoggerInterface::class)->info( 'Dashboard widget {widget} took {duration} seconds to load.', [ 'widget' => $widget->getId(), @@ -111,7 +112,7 @@ class Manager implements IManager { ); } } catch (Throwable $e) { - \OC::$server->get(LoggerInterface::class)->critical( + Server::get(LoggerInterface::class)->critical( 'Error during dashboard widget loading: ' . $service['class'], ['exception' => $e] ); diff --git a/lib/private/DateTimeFormatter.php b/lib/private/DateTimeFormatter.php index 2882a7d8cd7..2a20c65ada3 100644 --- a/lib/private/DateTimeFormatter.php +++ b/lib/private/DateTimeFormatter.php @@ -7,22 +7,20 @@ */ namespace OC; -class DateTimeFormatter implements \OCP\IDateTimeFormatter { - /** @var \DateTimeZone */ - protected $defaultTimeZone; - - /** @var \OCP\IL10N */ - protected $defaultL10N; +use OCP\IDateTimeFormatter; +use OCP\IL10N; +class DateTimeFormatter implements IDateTimeFormatter { /** * Constructor * * @param \DateTimeZone $defaultTimeZone Set the timezone for the format - * @param \OCP\IL10N $defaultL10N Set the language for the format + * @param IL10N $defaultL10N Set the language for the format */ - public function __construct(\DateTimeZone $defaultTimeZone, \OCP\IL10N $defaultL10N) { - $this->defaultTimeZone = $defaultTimeZone; - $this->defaultL10N = $defaultL10N; + public function __construct( + protected \DateTimeZone $defaultTimeZone, + protected IL10N $defaultL10N, + ) { } /** @@ -42,8 +40,8 @@ class DateTimeFormatter implements \OCP\IDateTimeFormatter { /** * Get \OCP\IL10N to use * - * @param \OCP\IL10N $l The locale to use - * @return \OCP\IL10N The locale to use, falling back to the current user's locale + * @param IL10N $l The locale to use + * @return IL10N The locale to use, falling back to the current user's locale */ protected function getLocale($l = null) { if ($l === null) { @@ -85,10 +83,10 @@ class DateTimeFormatter implements \OCP\IDateTimeFormatter { * short: e.g. 'M/d/yy' => '8/20/14' * The exact format is dependent on the language * @param \DateTimeZone $timeZone The timezone to use - * @param \OCP\IL10N $l The locale to use + * @param IL10N $l The locale to use * @return string Formatted date string */ - public function formatDate($timestamp, $format = 'long', ?\DateTimeZone $timeZone = null, ?\OCP\IL10N $l = null) { + public function formatDate($timestamp, $format = 'long', ?\DateTimeZone $timeZone = null, ?IL10N $l = null) { return $this->format($timestamp, 'date', $format, $timeZone, $l); } @@ -104,10 +102,10 @@ class DateTimeFormatter implements \OCP\IDateTimeFormatter { * The exact format is dependent on the language * Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable * @param \DateTimeZone $timeZone The timezone to use - * @param \OCP\IL10N $l The locale to use + * @param IL10N $l The locale to use * @return string Formatted relative date string */ - public function formatDateRelativeDay($timestamp, $format = 'long', ?\DateTimeZone $timeZone = null, ?\OCP\IL10N $l = null) { + public function formatDateRelativeDay($timestamp, $format = 'long', ?\DateTimeZone $timeZone = null, ?IL10N $l = null) { if (!str_ends_with($format, '^') && !str_ends_with($format, '*')) { $format .= '^'; } @@ -121,13 +119,13 @@ class DateTimeFormatter implements \OCP\IDateTimeFormatter { * * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object * @param int|\DateTime $baseTimestamp Timestamp to compare $timestamp against, defaults to current time - * @param \OCP\IL10N $l The locale to use + * @param IL10N $l The locale to use * @return string Formatted date span. Dates returned are: * < 1 month => Today, Yesterday, n days ago * < 13 month => last month, n months ago * >= 13 month => last year, n years ago */ - public function formatDateSpan($timestamp, $baseTimestamp = null, ?\OCP\IL10N $l = null) { + public function formatDateSpan($timestamp, $baseTimestamp = null, ?IL10N $l = null) { $l = $this->getLocale($l); $timestamp = $this->getDateTime($timestamp); $timestamp->setTime(0, 0, 0); @@ -190,10 +188,10 @@ class DateTimeFormatter implements \OCP\IDateTimeFormatter { * short: e.g. 'h:mm a' => '11:42 AM' * The exact format is dependent on the language * @param \DateTimeZone $timeZone The timezone to use - * @param \OCP\IL10N $l The locale to use + * @param IL10N $l The locale to use * @return string Formatted time string */ - public function formatTime($timestamp, $format = 'medium', ?\DateTimeZone $timeZone = null, ?\OCP\IL10N $l = null) { + public function formatTime($timestamp, $format = 'medium', ?\DateTimeZone $timeZone = null, ?IL10N $l = null) { return $this->format($timestamp, 'time', $format, $timeZone, $l); } @@ -202,7 +200,7 @@ class DateTimeFormatter implements \OCP\IDateTimeFormatter { * * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object * @param int|\DateTime $baseTimestamp Timestamp to compare $timestamp against, defaults to current time - * @param \OCP\IL10N $l The locale to use + * @param IL10N $l The locale to use * @return string Formatted time span. Dates returned are: * < 60 sec => seconds ago * < 1 hour => n minutes ago @@ -211,7 +209,7 @@ class DateTimeFormatter implements \OCP\IDateTimeFormatter { * < 13 month => last month, n months ago * >= 13 month => last year, n years ago */ - public function formatTimeSpan($timestamp, $baseTimestamp = null, ?\OCP\IL10N $l = null) { + public function formatTimeSpan($timestamp, $baseTimestamp = null, ?IL10N $l = null) { $l = $this->getLocale($l); $timestamp = $this->getDateTime($timestamp); if ($baseTimestamp === null) { @@ -251,10 +249,10 @@ class DateTimeFormatter implements \OCP\IDateTimeFormatter { * @param string $formatDate See formatDate() for description * @param string $formatTime See formatTime() for description * @param \DateTimeZone $timeZone The timezone to use - * @param \OCP\IL10N $l The locale to use + * @param IL10N $l The locale to use * @return string Formatted date and time string */ - public function formatDateTime($timestamp, $formatDate = 'long', $formatTime = 'medium', ?\DateTimeZone $timeZone = null, ?\OCP\IL10N $l = null) { + public function formatDateTime($timestamp, $formatDate = 'long', $formatTime = 'medium', ?\DateTimeZone $timeZone = null, ?IL10N $l = null) { return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l); } @@ -266,10 +264,10 @@ class DateTimeFormatter implements \OCP\IDateTimeFormatter { * Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable * @param string $formatTime See formatTime() for description * @param \DateTimeZone $timeZone The timezone to use - * @param \OCP\IL10N $l The locale to use + * @param IL10N $l The locale to use * @return string Formatted relative date and time string */ - public function formatDateTimeRelativeDay($timestamp, $formatDate = 'long', $formatTime = 'medium', ?\DateTimeZone $timeZone = null, ?\OCP\IL10N $l = null) { + public function formatDateTimeRelativeDay($timestamp, $formatDate = 'long', $formatTime = 'medium', ?\DateTimeZone $timeZone = null, ?IL10N $l = null) { if (!str_ends_with($formatDate, '^') && !str_ends_with($formatDate, '*')) { $formatDate .= '^'; } @@ -284,10 +282,10 @@ class DateTimeFormatter implements \OCP\IDateTimeFormatter { * @param string $type One of 'date', 'datetime' or 'time' * @param string $format Format string * @param \DateTimeZone $timeZone The timezone to use - * @param \OCP\IL10N $l The locale to use + * @param IL10N $l The locale to use * @return string Formatted date and time string */ - protected function format($timestamp, $type, $format, ?\DateTimeZone $timeZone = null, ?\OCP\IL10N $l = null) { + protected function format($timestamp, $type, $format, ?\DateTimeZone $timeZone = null, ?IL10N $l = null) { $l = $this->getLocale($l); $timeZone = $this->getTimeZone($timeZone); $timestamp = $this->getDateTime($timestamp, $timeZone); diff --git a/lib/private/DateTimeZone.php b/lib/private/DateTimeZone.php index 75eb3a6b769..3597c4ec1ff 100644 --- a/lib/private/DateTimeZone.php +++ b/lib/private/DateTimeZone.php @@ -10,24 +10,20 @@ namespace OC; use OCP\IConfig; use OCP\IDateTimeZone; use OCP\ISession; +use OCP\Server; use Psr\Log\LoggerInterface; class DateTimeZone implements IDateTimeZone { - /** @var IConfig */ - protected $config; - - /** @var ISession */ - protected $session; - /** * Constructor * * @param IConfig $config * @param ISession $session */ - public function __construct(IConfig $config, ISession $session) { - $this->config = $config; - $this->session = $session; + public function __construct( + protected IConfig $config, + protected ISession $session, + ) { } /** @@ -46,7 +42,7 @@ class DateTimeZone implements IDateTimeZone { try { return new \DateTimeZone($timezoneName); } catch (\Exception $e) { - \OCP\Server::get(LoggerInterface::class)->debug('Failed to created DateTimeZone "' . $timezoneName . '"', ['app' => 'datetimezone']); + Server::get(LoggerInterface::class)->debug('Failed to created DateTimeZone "' . $timezoneName . '"', ['app' => 'datetimezone']); return $this->getDefaultTimeZone(); } } @@ -102,7 +98,7 @@ class DateTimeZone implements IDateTimeZone { } // No timezone found, fallback to UTC - \OCP\Server::get(LoggerInterface::class)->debug('Failed to find DateTimeZone for offset "' . $offset . '"', ['app' => 'datetimezone']); + Server::get(LoggerInterface::class)->debug('Failed to find DateTimeZone for offset "' . $offset . '"', ['app' => 'datetimezone']); return $this->getDefaultTimeZone(); } } diff --git a/lib/private/Diagnostics/Event.php b/lib/private/Diagnostics/Event.php index 11d6505a888..74750212806 100644 --- a/lib/private/Diagnostics/Event.php +++ b/lib/private/Diagnostics/Event.php @@ -10,35 +10,21 @@ namespace OC\Diagnostics; use OCP\Diagnostics\IEvent; class Event implements IEvent { - /** - * @var string - */ - protected $id; - - /** - * @var float - */ - protected $start; - /** * @var float */ protected $end; - /** - * @var string - */ - protected $description; - /** * @param string $id * @param string $description * @param float $start */ - public function __construct($id, $description, $start) { - $this->id = $id; - $this->description = $description; - $this->start = $start; + public function __construct( + protected $id, + protected $description, + protected $start, + ) { } /** diff --git a/lib/private/Diagnostics/EventLogger.php b/lib/private/Diagnostics/EventLogger.php index 3ec35a5e9ce..da522646d88 100644 --- a/lib/private/Diagnostics/EventLogger.php +++ b/lib/private/Diagnostics/EventLogger.php @@ -17,25 +17,16 @@ class EventLogger implements IEventLogger { /** @var Event[] */ private $events = []; - /** @var SystemConfig */ - private $config; - - /** @var LoggerInterface */ - private $logger; - - /** @var Log */ - private $internalLogger; - /** * @var bool - Module needs to be activated by some app */ private $activated = false; - public function __construct(SystemConfig $config, LoggerInterface $logger, Log $internalLogger) { - $this->config = $config; - $this->logger = $logger; - $this->internalLogger = $internalLogger; - + public function __construct( + private SystemConfig $config, + private LoggerInterface $logger, + private Log $internalLogger, + ) { if ($this->isLoggingActivated()) { $this->activate(); } diff --git a/lib/private/Diagnostics/Query.php b/lib/private/Diagnostics/Query.php index 020fc4bb512..829bbf15dc1 100644 --- a/lib/private/Diagnostics/Query.php +++ b/lib/private/Diagnostics/Query.php @@ -10,26 +10,19 @@ namespace OC\Diagnostics; use OCP\Diagnostics\IQuery; class Query implements IQuery { - private $sql; - - private $params; - - private $start; - private $end; - private $stack; - /** * @param string $sql * @param array $params * @param int $start */ - public function __construct($sql, $params, $start, array $stack) { - $this->sql = $sql; - $this->params = $params; - $this->start = $start; - $this->stack = $stack; + public function __construct( + private $sql, + private $params, + private $start, + private array $stack, + ) { } public function end($time) { diff --git a/lib/private/DirectEditing/Manager.php b/lib/private/DirectEditing/Manager.php index 154002ef340..bcb69163dbb 100644 --- a/lib/private/DirectEditing/Manager.php +++ b/lib/private/DirectEditing/Manager.php @@ -7,6 +7,7 @@ namespace OC\DirectEditing; use Doctrine\DBAL\FetchMode; +use OCA\Encryption\Util; use OCP\AppFramework\Http\NotFoundResponse; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Http\TemplateResponse; @@ -27,6 +28,7 @@ use OCP\IL10N; use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Security\ISecureRandom; +use OCP\Server; use OCP\Share\IShare; use Throwable; use function array_key_exists; @@ -288,8 +290,8 @@ class Manager implements IManager { try { $moduleId = $this->encryptionManager->getDefaultEncryptionModuleId(); $module = $this->encryptionManager->getEncryptionModule($moduleId); - /** @var \OCA\Encryption\Util $util */ - $util = \OCP\Server::get(\OCA\Encryption\Util::class); + /** @var Util $util */ + $util = Server::get(Util::class); if ($module->isReadyForUser($this->userId) && $util->isMasterKeyEnabled()) { return true; } diff --git a/lib/private/DirectEditing/Token.php b/lib/private/DirectEditing/Token.php index ca01265f9df..a816bf18dcc 100644 --- a/lib/private/DirectEditing/Token.php +++ b/lib/private/DirectEditing/Token.php @@ -10,13 +10,10 @@ use OCP\DirectEditing\IToken; use OCP\Files\File; class Token implements IToken { - /** @var Manager */ - private $manager; - private $data; - - public function __construct(Manager $manager, $data) { - $this->manager = $manager; - $this->data = $data; + public function __construct( + private Manager $manager, + private $data, + ) { } public function extend(): void { diff --git a/lib/private/EmojiHelper.php b/lib/private/EmojiHelper.php index 52ab441e73a..d305fc24799 100644 --- a/lib/private/EmojiHelper.php +++ b/lib/private/EmojiHelper.php @@ -12,10 +12,9 @@ use OCP\IDBConnection; use OCP\IEmojiHelper; class EmojiHelper implements IEmojiHelper { - private IDBConnection $db; - - public function __construct(IDBConnection $db) { - $this->db = $db; + public function __construct( + private IDBConnection $db, + ) { } public function doesPlatformSupportEmoji(): bool { diff --git a/lib/private/Encryption/EncryptionWrapper.php b/lib/private/Encryption/EncryptionWrapper.php index b9db9616538..68d2efd8b8c 100644 --- a/lib/private/Encryption/EncryptionWrapper.php +++ b/lib/private/Encryption/EncryptionWrapper.php @@ -16,6 +16,11 @@ use OCP\Encryption\Keys\IStorage as EncryptionKeysStorage; use OCP\Files\Mount\IMountPoint; use OCP\Files\Storage\IDisableEncryptionStorage; use OCP\Files\Storage\IStorage; +use OCP\IConfig; +use OCP\IGroupManager; +use OCP\IUserManager; +use OCP\IUserSession; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -26,24 +31,14 @@ use Psr\Log\LoggerInterface; * @package OC\Encryption */ class EncryptionWrapper { - /** @var ArrayCache */ - private $arrayCache; - - /** @var Manager */ - private $manager; - - private LoggerInterface $logger; - /** * EncryptionWrapper constructor. */ - public function __construct(ArrayCache $arrayCache, - Manager $manager, - LoggerInterface $logger, + public function __construct( + private ArrayCache $arrayCache, + private Manager $manager, + private LoggerInterface $logger, ) { - $this->arrayCache = $arrayCache; - $this->manager = $manager; - $this->logger = $logger; } /** @@ -63,17 +58,17 @@ class EncryptionWrapper { ]; if ($force || (!$storage->instanceOfStorage(IDisableEncryptionStorage::class) && $mountPoint !== '/')) { - $user = \OC::$server->getUserSession()->getUser(); + $user = Server::get(IUserSession::class)->getUser(); $mountManager = Filesystem::getMountManager(); $uid = $user ? $user->getUID() : null; - $fileHelper = \OC::$server->get(IFile::class); - $keyStorage = \OC::$server->get(EncryptionKeysStorage::class); + $fileHelper = Server::get(IFile::class); + $keyStorage = Server::get(EncryptionKeysStorage::class); $util = new Util( new View(), - \OC::$server->getUserManager(), - \OC::$server->getGroupManager(), - \OC::$server->getConfig() + Server::get(IUserManager::class), + Server::get(IGroupManager::class), + Server::get(IConfig::class) ); return new Encryption( $parameters, diff --git a/lib/private/Encryption/File.php b/lib/private/Encryption/File.php index 26e643d1006..8da0bcfcc0d 100644 --- a/lib/private/Encryption/File.php +++ b/lib/private/Encryption/File.php @@ -10,15 +10,13 @@ namespace OC\Encryption; use OCA\Files_External\Service\GlobalStoragesService; use OCP\App\IAppManager; use OCP\Cache\CappedMemoryCache; +use OCP\Encryption\IFile; use OCP\Files\IRootFolder; use OCP\Files\NotFoundException; +use OCP\Server; use OCP\Share\IManager; -class File implements \OCP\Encryption\IFile { - protected Util $util; - private IRootFolder $rootFolder; - private IManager $shareManager; - +class File implements IFile { /** * Cache results of already checked folders * @var CappedMemoryCache @@ -26,13 +24,12 @@ class File implements \OCP\Encryption\IFile { protected CappedMemoryCache $cache; private ?IAppManager $appManager = null; - public function __construct(Util $util, - IRootFolder $rootFolder, - IManager $shareManager) { - $this->util = $util; + public function __construct( + protected Util $util, + private IRootFolder $rootFolder, + private IManager $shareManager, + ) { $this->cache = new CappedMemoryCache(); - $this->rootFolder = $rootFolder; - $this->shareManager = $shareManager; } public function getAppManager(): IAppManager { @@ -40,7 +37,7 @@ class File implements \OCP\Encryption\IFile { if ($this->appManager) { return $this->appManager; } - $this->appManager = \OCP\Server::get(IAppManager::class); + $this->appManager = Server::get(IAppManager::class); return $this->appManager; } @@ -94,7 +91,7 @@ class File implements \OCP\Encryption\IFile { // check if it is a group mount if ($this->getAppManager()->isEnabledForUser('files_external')) { /** @var GlobalStoragesService $storageService */ - $storageService = \OC::$server->get(GlobalStoragesService::class); + $storageService = Server::get(GlobalStoragesService::class); $storages = $storageService->getAllStorages(); foreach ($storages as $storage) { if ($storage->getMountPoint() == substr($ownerPath, 0, strlen($storage->getMountPoint()))) { diff --git a/lib/private/Encryption/Keys/Storage.php b/lib/private/Encryption/Keys/Storage.php index cce22b9138a..bad832dcddf 100644 --- a/lib/private/Encryption/Keys/Storage.php +++ b/lib/private/Encryption/Keys/Storage.php @@ -20,12 +20,6 @@ class Storage implements IStorage { // hidden file which indicate that the folder is a valid key storage public const KEY_STORAGE_MARKER = '.oc_key_storage'; - /** @var View */ - private $view; - - /** @var Util */ - private $util; - // base dir where all the file related keys are stored /** @var string */ private $keys_base_dir; @@ -43,26 +37,20 @@ class Storage implements IStorage { /** @var array */ private $keyCache = []; - /** @var ICrypto */ - private $crypto; - - /** @var IConfig */ - private $config; - /** * @param View $view * @param Util $util */ - public function __construct(View $view, Util $util, ICrypto $crypto, IConfig $config) { - $this->view = $view; - $this->util = $util; - + public function __construct( + private View $view, + private Util $util, + private ICrypto $crypto, + private IConfig $config, + ) { $this->encryption_base_dir = '/files_encryption'; $this->keys_base_dir = $this->encryption_base_dir . '/keys'; $this->backup_base_dir = $this->encryption_base_dir . '/backup'; $this->root_dir = $this->util->getKeyStorageRoot(); - $this->crypto = $crypto; - $this->config = $config; } /** @@ -193,7 +181,7 @@ class Storage implements IStorage { . $encryptionModuleId . '/' . $uid . '.' . $keyId; } - return \OC\Files\Filesystem::normalizePath($path); + return Filesystem::normalizePath($path); } /** diff --git a/lib/private/Encryption/Manager.php b/lib/private/Encryption/Manager.php index a07c778bfe0..a357ae0a150 100644 --- a/lib/private/Encryption/Manager.php +++ b/lib/private/Encryption/Manager.php @@ -7,6 +7,8 @@ */ namespace OC\Encryption; +use OC\Encryption\Exceptions\ModuleAlreadyExistsException; +use OC\Encryption\Exceptions\ModuleDoesNotExistsException; use OC\Encryption\Keys\Storage; use OC\Files\Filesystem; use OC\Files\View; @@ -92,7 +94,7 @@ class Manager implements IManager { */ public function registerEncryptionModule($id, $displayName, callable $callback) { if (isset($this->encryptionModules[$id])) { - throw new Exceptions\ModuleAlreadyExistsException($id, $displayName); + throw new ModuleAlreadyExistsException($id, $displayName); } $this->encryptionModules[$id] = [ @@ -142,26 +144,26 @@ class Manager implements IManager { } $message = "Module with ID: $moduleId does not exist."; $hint = $this->l->t('Module with ID: %s does not exist. Please enable it in your apps settings or contact your administrator.', [$moduleId]); - throw new Exceptions\ModuleDoesNotExistsException($message, $hint); + throw new ModuleDoesNotExistsException($message, $hint); } /** * get default encryption module * - * @return \OCP\Encryption\IEncryptionModule + * @return IEncryptionModule * @throws Exceptions\ModuleDoesNotExistsException */ protected function getDefaultEncryptionModule() { $defaultModuleId = $this->getDefaultEncryptionModuleId(); if (empty($defaultModuleId)) { $message = 'No default encryption module defined'; - throw new Exceptions\ModuleDoesNotExistsException($message); + throw new ModuleDoesNotExistsException($message); } if (isset($this->encryptionModules[$defaultModuleId])) { return call_user_func($this->encryptionModules[$defaultModuleId]['callback']); } $message = 'Default encryption module not loaded'; - throw new Exceptions\ModuleDoesNotExistsException($message); + throw new ModuleDoesNotExistsException($message); } /** diff --git a/lib/private/Encryption/Util.php b/lib/private/Encryption/Util.php index 2d7bc28129b..393ac229421 100644 --- a/lib/private/Encryption/Util.php +++ b/lib/private/Encryption/Util.php @@ -12,6 +12,7 @@ use OC\Encryption\Exceptions\EncryptionHeaderToLargeException; use OC\Encryption\Exceptions\ModuleDoesNotExistsException; use OC\Files\Filesystem; use OC\Files\View; +use OCA\Encryption\Crypto\Encryption; use OCP\Encryption\IEncryptionModule; use OCP\Files\Mount\ISystemMountPoint; use OCP\IConfig; @@ -40,19 +41,11 @@ class Util { */ protected $blockSize = 8192; - /** @var View */ - protected $rootView; - /** @var array */ protected $ocHeaderKeys; - /** @var IConfig */ - protected $config; - /** @var array paths excluded from encryption */ protected array $excludedPaths = []; - protected IGroupManager $groupManager; - protected IUserManager $userManager; /** * @@ -60,21 +53,17 @@ class Util { * @param IConfig $config */ public function __construct( - View $rootView, - IUserManager $userManager, - IGroupManager $groupManager, - IConfig $config) { + protected View $rootView, + protected IUserManager $userManager, + protected IGroupManager $groupManager, + protected IConfig $config, + ) { $this->ocHeaderKeys = [ self::HEADER_ENCRYPTION_MODULE_KEY ]; - $this->rootView = $rootView; - $this->userManager = $userManager; - $this->groupManager = $groupManager; - $this->config = $config; - $this->excludedPaths[] = 'files_encryption'; - $this->excludedPaths[] = 'appdata_' . $config->getSystemValueString('instanceid'); + $this->excludedPaths[] = 'appdata_' . $this->config->getSystemValueString('instanceid'); $this->excludedPaths[] = 'files_external'; } @@ -95,7 +84,7 @@ class Util { if (class_exists('\OCA\Encryption\Crypto\Encryption')) { // fall back to default encryption if the user migrated from // ownCloud <= 8.0 with the old encryption - $id = \OCA\Encryption\Crypto\Encryption::ID; + $id = Encryption::ID; } else { throw new ModuleDoesNotExistsException('Default encryption module missing'); } diff --git a/lib/private/EventDispatcher/EventDispatcher.php b/lib/private/EventDispatcher/EventDispatcher.php index 474c902013b..4c87271009a 100644 --- a/lib/private/EventDispatcher/EventDispatcher.php +++ b/lib/private/EventDispatcher/EventDispatcher.php @@ -10,6 +10,7 @@ namespace OC\EventDispatcher; use OC\Broadcast\Events\BroadcastEvent; use OC\Log; +use OC\Log\PsrLoggerAdapter; use OCP\Broadcast\Events\IBroadcastEvent; use OCP\EventDispatcher\ABroadcastedEvent; use OCP\EventDispatcher\Event; @@ -27,7 +28,7 @@ class EventDispatcher implements IEventDispatcher { ) { // inject the event dispatcher into the logger // this is done here because there is a cyclic dependency between the event dispatcher and logger - if ($this->logger instanceof Log || $this->logger instanceof Log\PsrLoggerAdapter) { + if ($this->logger instanceof Log || $this->logger instanceof PsrLoggerAdapter) { $this->logger->setEventDispatcher($this); } } diff --git a/lib/private/Federation/CloudId.php b/lib/private/Federation/CloudId.php index b807c29d812..643524b3acd 100644 --- a/lib/private/Federation/CloudId.php +++ b/lib/private/Federation/CloudId.php @@ -10,6 +10,7 @@ namespace OC\Federation; use OCP\Federation\ICloudId; use OCP\Federation\ICloudIdManager; +use OCP\Server; class CloudId implements ICloudId { public function __construct( @@ -32,7 +33,7 @@ class CloudId implements ICloudId { public function getDisplayId(): string { if ($this->displayName === null) { /** @var CloudIdManager $cloudIdManager */ - $cloudIdManager = \OCP\Server::get(ICloudIdManager::class); + $cloudIdManager = Server::get(ICloudIdManager::class); $this->displayName = $cloudIdManager->getDisplayNameFromContact($this->getId()); } diff --git a/lib/private/Files/AppData/AppData.php b/lib/private/Files/AppData/AppData.php index c13372ae1d9..ee809c4050d 100644 --- a/lib/private/Files/AppData/AppData.php +++ b/lib/private/Files/AppData/AppData.php @@ -20,9 +20,6 @@ use OCP\Files\NotPermittedException; use OCP\Files\SimpleFS\ISimpleFolder; class AppData implements IAppData { - private IRootFolder $rootFolder; - private SystemConfig $config; - private string $appId; private ?Folder $folder = null; /** @var CappedMemoryCache */ private CappedMemoryCache $folders; @@ -31,15 +28,14 @@ class AppData implements IAppData { * AppData constructor. * * @param IRootFolder $rootFolder - * @param SystemConfig $systemConfig + * @param SystemConfig $config * @param string $appId */ - public function __construct(IRootFolder $rootFolder, - SystemConfig $systemConfig, - string $appId) { - $this->rootFolder = $rootFolder; - $this->config = $systemConfig; - $this->appId = $appId; + public function __construct( + private IRootFolder $rootFolder, + private SystemConfig $config, + private string $appId, + ) { $this->folders = new CappedMemoryCache(); } diff --git a/lib/private/Files/AppData/Factory.php b/lib/private/Files/AppData/Factory.php index 38b73f370b8..75d20e454e5 100644 --- a/lib/private/Files/AppData/Factory.php +++ b/lib/private/Files/AppData/Factory.php @@ -14,16 +14,13 @@ use OCP\Files\IAppData; use OCP\Files\IRootFolder; class Factory implements IAppDataFactory { - private IRootFolder $rootFolder; - private SystemConfig $config; - /** @var array */ private array $folders = []; - public function __construct(IRootFolder $rootFolder, - SystemConfig $systemConfig) { - $this->rootFolder = $rootFolder; - $this->config = $systemConfig; + public function __construct( + private IRootFolder $rootFolder, + private SystemConfig $config, + ) { } public function get(string $appId): IAppData { diff --git a/lib/private/Files/Cache/Cache.php b/lib/private/Files/Cache/Cache.php index 6213b88fc17..cfadf7ed4ec 100644 --- a/lib/private/Files/Cache/Cache.php +++ b/lib/private/Files/Cache/Cache.php @@ -7,6 +7,7 @@ */ namespace OC\Files\Cache; +use OC\DatabaseException; use OC\DB\Exceptions\DbalException; use OC\DB\QueryBuilder\Sharded\ShardDefinition; use OC\Files\Cache\Wrapper\CacheJail; @@ -34,6 +35,7 @@ use OCP\Files\Search\ISearchQuery; use OCP\Files\Storage\IStorage; use OCP\FilesMetadata\IFilesMetadataManager; use OCP\IDBConnection; +use OCP\Server; use OCP\Util; use Psr\Log\LoggerInterface; @@ -77,7 +79,7 @@ class Cache implements ICache { $this->storageId = md5($this->storageId); } if (!$dependencies) { - $dependencies = \OCP\Server::get(CacheDependencies::class); + $dependencies = Server::get(CacheDependencies::class); } $this->storageCache = new Storage($this->storage, true, $dependencies->getConnection()); $this->mimetypeLoader = $dependencies->getMimeTypeLoader(); @@ -571,7 +573,7 @@ class Cache implements ICache { * Remove all children of a folder * * @param ICacheEntry $entry the cache entry of the folder to remove the children of - * @throws \OC\DatabaseException + * @throws DatabaseException */ private function removeChildren(ICacheEntry $entry) { $parentIds = [$entry->getId()]; @@ -700,7 +702,7 @@ class Cache implements ICache { * @param ICache $sourceCache * @param string $sourcePath * @param string $targetPath - * @throws \OC\DatabaseException + * @throws DatabaseException * @throws \Exception if the given storages have an invalid id */ public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) { @@ -777,7 +779,7 @@ class Cache implements ICache { $query->executeStatement(); } break; - } catch (\OC\DatabaseException $e) { + } catch (DatabaseException $e) { $this->connection->rollBack(); throw $e; } catch (DbalException $e) { @@ -1169,7 +1171,7 @@ class Cache implements ICache { * @deprecated 17.0.0 use getPathById() instead */ public static function getById($id) { - $query = \OC::$server->getDatabaseConnection()->getQueryBuilder(); + $query = Server::get(IDBConnection::class)->getQueryBuilder(); $query->select('path', 'storage') ->from('filecache') ->where($query->expr()->eq('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT))); diff --git a/lib/private/Files/Cache/FailedCache.php b/lib/private/Files/Cache/FailedCache.php index 44c1016ca8e..bbab4a3e9a0 100644 --- a/lib/private/Files/Cache/FailedCache.php +++ b/lib/private/Files/Cache/FailedCache.php @@ -19,16 +19,14 @@ use OCP\Files\Search\ISearchQuery; * Storage placeholder to represent a missing precondition, storage unavailable */ class FailedCache implements ICache { - /** @var bool whether to show the failed storage in the ui */ - private $visible; - /** * FailedCache constructor. * * @param bool $visible */ - public function __construct($visible = true) { - $this->visible = $visible; + public function __construct( + private $visible = true, + ) { } diff --git a/lib/private/Files/Cache/FileAccess.php b/lib/private/Files/Cache/FileAccess.php index 86243b9ca25..ee92c4fdc7a 100644 --- a/lib/private/Files/Cache/FileAccess.php +++ b/lib/private/Files/Cache/FileAccess.php @@ -8,6 +8,8 @@ declare(strict_types=1); */ namespace OC\Files\Cache; +use OC\Files\Mount\LocalHomeMountProvider; +use OC\Files\Mount\ObjectHomeMountProvider; use OC\FilesMetadata\FilesMetadataManager; use OC\SystemConfig; use OCP\DB\Exception; @@ -196,8 +198,8 @@ class FileAccess implements IFileAccess { $qb->expr()->orX( $qb->expr()->like('mount_point', $qb->createNamedParameter('/%/files/%')), $qb->expr()->in('mount_provider_class', $qb->createNamedParameter([ - \OC\Files\Mount\LocalHomeMountProvider::class, - \OC\Files\Mount\ObjectHomeMountProvider::class, + LocalHomeMountProvider::class, + ObjectHomeMountProvider::class, ], IQueryBuilder::PARAM_STR_ARRAY)) ) ); @@ -218,8 +220,8 @@ class FileAccess implements IFileAccess { // LocalHomeMountProvider is the default provider for user home directories // ObjectHomeMountProvider is the home directory provider for when S3 primary storage is used if ($onlyUserFilesMounts && in_array($row['mount_provider_class'], [ - \OC\Files\Mount\LocalHomeMountProvider::class, - \OC\Files\Mount\ObjectHomeMountProvider::class, + LocalHomeMountProvider::class, + ObjectHomeMountProvider::class, ], true)) { // Only crawl files, not cache or trashbin $qb = $this->getQuery(); diff --git a/lib/private/Files/Cache/LocalRootScanner.php b/lib/private/Files/Cache/LocalRootScanner.php index d5f7d40e1b6..be9f74daf8a 100644 --- a/lib/private/Files/Cache/LocalRootScanner.php +++ b/lib/private/Files/Cache/LocalRootScanner.php @@ -8,6 +8,7 @@ declare(strict_types=1); */ namespace OC\Files\Cache; +use OC\Files\Storage\Storage; use OCP\IConfig; use OCP\Server; use Override; @@ -15,7 +16,7 @@ use Override; class LocalRootScanner extends Scanner { private string $previewFolder; - public function __construct(\OC\Files\Storage\Storage $storage) { + public function __construct(Storage $storage) { parent::__construct($storage); $config = Server::get(IConfig::class); $this->previewFolder = 'appdata_' . $config->getSystemValueString('instanceid', '') . '/preview'; diff --git a/lib/private/Files/Cache/MoveFromCacheTrait.php b/lib/private/Files/Cache/MoveFromCacheTrait.php index db35c6bb7f8..a13e0d7d00e 100644 --- a/lib/private/Files/Cache/MoveFromCacheTrait.php +++ b/lib/private/Files/Cache/MoveFromCacheTrait.php @@ -30,7 +30,7 @@ trait MoveFromCacheTrait { /** * Move a file or folder in the cache * - * @param \OCP\Files\Cache\ICache $sourceCache + * @param ICache $sourceCache * @param string $sourcePath * @param string $targetPath */ diff --git a/lib/private/Files/Cache/Propagator.php b/lib/private/Files/Cache/Propagator.php index 4a0c3203401..151b15d7590 100644 --- a/lib/private/Files/Cache/Propagator.php +++ b/lib/private/Files/Cache/Propagator.php @@ -113,7 +113,7 @@ class Propagator implements IPropagator { } /** @var LoggerInterface $loggerInterface */ - $loggerInterface = \OCP\Server::get(LoggerInterface::class); + $loggerInterface = Server::get(LoggerInterface::class); $loggerInterface->warning('Retrying propagation query after retryable exception.', [ 'exception' => $e ]); } } diff --git a/lib/private/Files/Cache/Scanner.php b/lib/private/Files/Cache/Scanner.php index 2fa0dd09e4f..98ba4c39bc3 100644 --- a/lib/private/Files/Cache/Scanner.php +++ b/lib/private/Files/Cache/Scanner.php @@ -8,17 +8,24 @@ namespace OC\Files\Cache; use Doctrine\DBAL\Exception; +use OC\Files\Filesystem; +use OC\Files\Storage\Storage; use OC\Files\Storage\Wrapper\Encryption; use OC\Files\Storage\Wrapper\Jail; use OC\Hooks\BasicEmitter; +use OCP\Files\Cache\ICacheEntry; use OCP\Files\Cache\IScanner; use OCP\Files\ForbiddenException; +use OCP\Files\IMimeTypeLoader; use OCP\Files\NotFoundException; use OCP\Files\Storage\ILockingStorage; use OCP\Files\Storage\IReliableEtagStorage; +use OCP\Files\StorageInvalidException; +use OCP\Files\StorageNotAvailableException; use OCP\IConfig; use OCP\IDBConnection; use OCP\Lock\ILockingProvider; +use OCP\Lock\LockedException; use OCP\Server; use Psr\Log\LoggerInterface; @@ -34,18 +41,13 @@ use Psr\Log\LoggerInterface; * @package OC\Files\Cache */ class Scanner extends BasicEmitter implements IScanner { - /** - * @var \OC\Files\Storage\Storage $storage - */ - protected $storage; - /** * @var string $storageId */ protected $storageId; /** - * @var \OC\Files\Cache\Cache $cache + * @var Cache $cache */ protected $cache; @@ -60,16 +62,17 @@ class Scanner extends BasicEmitter implements IScanner { protected $useTransactions = true; /** - * @var \OCP\Lock\ILockingProvider + * @var ILockingProvider */ protected $lockingProvider; protected IDBConnection $connection; - public function __construct(\OC\Files\Storage\Storage $storage) { - $this->storage = $storage; + public function __construct( + protected Storage $storage, + ) { $this->storageId = $this->storage->getId(); - $this->cache = $storage->getCache(); + $this->cache = $this->storage->getCache(); $config = Server::get(IConfig::class); $this->cacheActive = !$config->getSystemValueBool('filesystem_cache_readonly', false); $this->useTransactions = !$config->getSystemValueBool('filescanner_no_transactions', false); @@ -97,7 +100,7 @@ class Scanner extends BasicEmitter implements IScanner { protected function getData($path) { $data = $this->storage->getMetaData($path); if (is_null($data)) { - \OC::$server->get(LoggerInterface::class)->debug("!!! Path '$path' is not accessible or present !!!", ['app' => 'core']); + Server::get(LoggerInterface::class)->debug("!!! Path '$path' is not accessible or present !!!", ['app' => 'core']); } return $data; } @@ -112,7 +115,7 @@ class Scanner extends BasicEmitter implements IScanner { * @param bool $lock set to false to disable getting an additional read lock during scanning * @param array|null $data the metadata for the file, as returned by the storage * @return array|null an array of metadata of the scanned file - * @throws \OCP\Lock\LockedException + * @throws LockedException */ public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true, $data = null) { if ($file !== '') { @@ -207,7 +210,7 @@ class Scanner extends BasicEmitter implements IScanner { * i.e. get all the values in $data that are not present in the cache already * * We need the OC implementation for usage of "getData" method below. - * @var \OC\Files\Cache\CacheEntry $cacheData + * @var CacheEntry $cacheData */ $newData = $this->array_diff_assoc_multi($data, $cacheData->getData()); @@ -382,7 +385,7 @@ class Scanner extends BasicEmitter implements IScanner { * Get the children currently in the cache * * @param int $folderId - * @return array + * @return array */ protected function getExistingChildren($folderId): array { $existingChildren = []; @@ -473,10 +476,10 @@ class Scanner extends BasicEmitter implements IScanner { continue; } $originalFile = $fileMeta['name']; - $file = trim(\OC\Files\Filesystem::normalizePath($originalFile), '/'); + $file = trim(Filesystem::normalizePath($originalFile), '/'); if (trim($originalFile, '/') !== $file) { // encoding mismatch, might require compatibility wrapper - \OC::$server->get(LoggerInterface::class)->debug('Scanner: Skipping non-normalized file name "' . $originalFile . '" in path "' . $path . '".', ['app' => 'core']); + Server::get(LoggerInterface::class)->debug('Scanner: Skipping non-normalized file name "' . $originalFile . '" in path "' . $path . '".', ['app' => 'core']); $this->emit('\OC\Files\Cache\Scanner', 'normalizedNameMismatch', [$path ? $path . '/' . $originalFile : $originalFile]); // skip this entry continue; @@ -511,12 +514,12 @@ class Scanner extends BasicEmitter implements IScanner { $this->connection->rollback(); $this->connection->beginTransaction(); } - \OC::$server->get(LoggerInterface::class)->debug('Exception while scanning file "' . $child . '"', [ + Server::get(LoggerInterface::class)->debug('Exception while scanning file "' . $child . '"', [ 'app' => 'core', 'exception' => $ex, ]); $exceptionOccurred = true; - } catch (\OCP\Lock\LockedException $e) { + } catch (LockedException $e) { if ($this->useTransactions) { $this->connection->rollback(); } @@ -536,7 +539,7 @@ class Scanner extends BasicEmitter implements IScanner { // inserted mimetypes but those weren't available yet inside the transaction // To make sure to have the updated mime types in such cases, // we reload them here - \OC::$server->getMimeTypeLoader()->reset(); + Server::get(IMimeTypeLoader::class)->reset(); } return $childQueue; } @@ -575,14 +578,14 @@ class Scanner extends BasicEmitter implements IScanner { } else { if (!$this->cache->inCache('')) { // if the storage isn't in the cache yet, just scan the root completely - $this->runBackgroundScanJob(function () { + $this->runBackgroundScanJob(function (): void { $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG); }, ''); } else { $lastPath = null; // find any path marked as unscanned and run the scanner until no more paths are unscanned (or we get stuck) while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) { - $this->runBackgroundScanJob(function () use ($path) { + $this->runBackgroundScanJob(function () use ($path): void { $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE); }, $path); // FIXME: this won't proceed with the next item, needs revamping of getIncomplete() @@ -600,13 +603,13 @@ class Scanner extends BasicEmitter implements IScanner { if ($this->cacheActive && $this->cache instanceof Cache) { $this->cache->correctFolderSize($path, null, true); } - } catch (\OCP\Files\StorageInvalidException $e) { + } catch (StorageInvalidException $e) { // skip unavailable storages - } catch (\OCP\Files\StorageNotAvailableException $e) { + } catch (StorageNotAvailableException $e) { // skip unavailable storages - } catch (\OCP\Files\ForbiddenException $e) { + } catch (ForbiddenException $e) { // skip forbidden storages - } catch (\OCP\Lock\LockedException $e) { + } catch (LockedException $e) { // skip unavailable storages } } diff --git a/lib/private/Files/Cache/Storage.php b/lib/private/Files/Cache/Storage.php index a2fdfc76cc7..51def43a4dc 100644 --- a/lib/private/Files/Cache/Storage.php +++ b/lib/private/Files/Cache/Storage.php @@ -10,6 +10,7 @@ namespace OC\Files\Cache; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\Files\Storage\IStorage; use OCP\IDBConnection; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -34,7 +35,7 @@ class Storage { */ public static function getGlobalCache() { if (is_null(self::$globalCache)) { - self::$globalCache = new StorageGlobal(\OC::$server->getDatabaseConnection()); + self::$globalCache = new StorageGlobal(Server::get(IDBConnection::class)); } return self::$globalCache; } @@ -149,10 +150,10 @@ class Storage { public function setAvailability($isAvailable, int $delay = 0) { $available = $isAvailable ? 1 : 0; if (!$isAvailable) { - \OCP\Server::get(LoggerInterface::class)->info('Storage with ' . $this->storageId . ' marked as unavailable', ['app' => 'lib']); + Server::get(LoggerInterface::class)->info('Storage with ' . $this->storageId . ' marked as unavailable', ['app' => 'lib']); } - $query = \OC::$server->getDatabaseConnection()->getQueryBuilder(); + $query = Server::get(IDBConnection::class)->getQueryBuilder(); $query->update('storages') ->set('available', $query->createNamedParameter($available)) ->set('last_checked', $query->createNamedParameter(time() + $delay)) @@ -179,13 +180,13 @@ class Storage { $storageId = self::adjustStorageId($storageId); $numericId = self::getNumericStorageId($storageId); - $query = \OC::$server->getDatabaseConnection()->getQueryBuilder(); + $query = Server::get(IDBConnection::class)->getQueryBuilder(); $query->delete('storages') ->where($query->expr()->eq('id', $query->createNamedParameter($storageId))); $query->executeStatement(); if (!is_null($numericId)) { - $query = \OC::$server->getDatabaseConnection()->getQueryBuilder(); + $query = Server::get(IDBConnection::class)->getQueryBuilder(); $query->delete('filecache') ->where($query->expr()->eq('storage', $query->createNamedParameter($numericId))); $query->executeStatement(); @@ -198,7 +199,7 @@ class Storage { * @param int $mountId */ public static function cleanByMountId(int $mountId) { - $db = \OC::$server->getDatabaseConnection(); + $db = Server::get(IDBConnection::class); try { $db->beginTransaction(); diff --git a/lib/private/Files/Cache/Updater.php b/lib/private/Files/Cache/Updater.php index cdbff8b6c9a..894f46c622c 100644 --- a/lib/private/Files/Cache/Updater.php +++ b/lib/private/Files/Cache/Updater.php @@ -10,10 +10,12 @@ namespace OC\Files\Cache; use Doctrine\DBAL\Exception\DeadlockException; use OC\Files\FileInfo; use OC\Files\ObjectStore\ObjectStoreStorage; +use OC\Files\Storage\Storage; use OCP\Files\Cache\ICache; use OCP\Files\Cache\ICacheEntry; use OCP\Files\Cache\IUpdater; use OCP\Files\Storage\IStorage; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -27,12 +29,7 @@ class Updater implements IUpdater { protected $enabled = true; /** - * @var \OC\Files\Storage\Storage - */ - protected $storage; - - /** - * @var \OC\Files\Cache\Propagator + * @var Propagator */ protected $propagator; @@ -49,14 +46,15 @@ class Updater implements IUpdater { private LoggerInterface $logger; /** - * @param \OC\Files\Storage\Storage $storage + * @param Storage $storage */ - public function __construct(\OC\Files\Storage\Storage $storage) { - $this->storage = $storage; - $this->propagator = $storage->getPropagator(); - $this->scanner = $storage->getScanner(); - $this->cache = $storage->getCache(); - $this->logger = \OC::$server->get(LoggerInterface::class); + public function __construct( + protected Storage $storage, + ) { + $this->propagator = $this->storage->getPropagator(); + $this->scanner = $this->storage->getScanner(); + $this->cache = $this->storage->getCache(); + $this->logger = Server::get(LoggerInterface::class); } /** @@ -166,7 +164,7 @@ class Updater implements IUpdater { * @param string $target */ public function renameFromStorage(IStorage $sourceStorage, $source, $target) { - $this->copyOrRenameFromStorage($sourceStorage, $source, $target, function (ICache $sourceCache) use ($sourceStorage, $source, $target) { + $this->copyOrRenameFromStorage($sourceStorage, $source, $target, function (ICache $sourceCache) use ($sourceStorage, $source, $target): void { // Remove existing cache entry to no reuse the fileId. if ($this->cache->inCache($target)) { $this->cache->remove($target); @@ -184,7 +182,7 @@ class Updater implements IUpdater { * Copy a file or folder in the cache. */ public function copyFromStorage(IStorage $sourceStorage, string $source, string $target): void { - $this->copyOrRenameFromStorage($sourceStorage, $source, $target, function (ICache $sourceCache, ICacheEntry $sourceInfo) use ($target) { + $this->copyOrRenameFromStorage($sourceStorage, $source, $target, function (ICache $sourceCache, ICacheEntry $sourceInfo) use ($target): void { $parent = dirname($target); if ($parent === '.') { $parent = ''; diff --git a/lib/private/Files/Cache/Watcher.php b/lib/private/Files/Cache/Watcher.php index 891fe762eb8..ee992a38c45 100644 --- a/lib/private/Files/Cache/Watcher.php +++ b/lib/private/Files/Cache/Watcher.php @@ -7,7 +7,7 @@ */ namespace OC\Files\Cache; -use OCP\Files\Cache\ICache; +use OC\Files\Storage\Storage; use OCP\Files\Cache\ICacheEntry; use OCP\Files\Cache\IScanner; use OCP\Files\Cache\IWatcher; @@ -22,12 +22,7 @@ class Watcher implements IWatcher { protected $checkedPaths = []; /** - * @var IStorage $storage - */ - protected $storage; - - /** - * @var ICache $cache + * @var Cache $cache */ protected $cache; @@ -41,10 +36,11 @@ class Watcher implements IWatcher { protected ?string $checkFilter = null; - public function __construct(IStorage $storage) { - $this->storage = $storage; - $this->cache = $storage->getCache(); - $this->scanner = $storage->getScanner(); + public function __construct( + protected IStorage $storage, + ) { + $this->cache = $this->storage->getCache(); + $this->scanner = $this->storage->getScanner(); } /** diff --git a/lib/private/Files/Cache/Wrapper/CacheJail.php b/lib/private/Files/Cache/Wrapper/CacheJail.php index 91bb31df872..ba2ffd081e7 100644 --- a/lib/private/Files/Cache/Wrapper/CacheJail.php +++ b/lib/private/Files/Cache/Wrapper/CacheJail.php @@ -280,11 +280,11 @@ class CacheJail extends CacheWrapper { * * Note that this should make sure the entries are removed from the source cache * - * @param \OCP\Files\Cache\ICache $sourceCache + * @param ICache $sourceCache * @param string $sourcePath * @param string $targetPath */ - public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) { + public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) { if ($sourceCache === $this) { return $this->move($sourcePath, $targetPath); } diff --git a/lib/private/Files/Cache/Wrapper/CachePermissionsMask.php b/lib/private/Files/Cache/Wrapper/CachePermissionsMask.php index 12db55980c5..6d2cfb2922f 100644 --- a/lib/private/Files/Cache/Wrapper/CachePermissionsMask.php +++ b/lib/private/Files/Cache/Wrapper/CachePermissionsMask.php @@ -7,19 +7,18 @@ */ namespace OC\Files\Cache\Wrapper; +use OCP\Files\Cache\ICache; + class CachePermissionsMask extends CacheWrapper { /** - * @var int - */ - protected $mask; - - /** - * @param \OCP\Files\Cache\ICache $cache + * @param ICache $cache * @param int $mask */ - public function __construct($cache, $mask) { + public function __construct( + $cache, + protected $mask, + ) { parent::__construct($cache); - $this->mask = $mask; } protected function formatCacheEntry($entry) { diff --git a/lib/private/Files/Cache/Wrapper/CacheWrapper.php b/lib/private/Files/Cache/Wrapper/CacheWrapper.php index bf23f1cc30a..7d964e135b8 100644 --- a/lib/private/Files/Cache/Wrapper/CacheWrapper.php +++ b/lib/private/Files/Cache/Wrapper/CacheWrapper.php @@ -16,17 +16,14 @@ use OCP\Files\Search\ISearchQuery; use OCP\Server; class CacheWrapper extends Cache { - /** - * @var ?ICache - */ - protected $cache; - - public function __construct(?ICache $cache, ?CacheDependencies $dependencies = null) { - $this->cache = $cache; - if (!$dependencies && $cache instanceof Cache) { - $this->mimetypeLoader = $cache->mimetypeLoader; - $this->connection = $cache->connection; - $this->querySearchHelper = $cache->querySearchHelper; + public function __construct( + protected ?ICache $cache, + ?CacheDependencies $dependencies = null, + ) { + if (!$dependencies && $this->cache instanceof Cache) { + $this->mimetypeLoader = $this->cache->mimetypeLoader; + $this->connection = $this->cache->connection; + $this->querySearchHelper = $this->cache->querySearchHelper; } else { if (!$dependencies) { $dependencies = Server::get(CacheDependencies::class); diff --git a/lib/private/Files/Cache/Wrapper/JailWatcher.php b/lib/private/Files/Cache/Wrapper/JailWatcher.php index b1ae516654a..18a1c22495c 100644 --- a/lib/private/Files/Cache/Wrapper/JailWatcher.php +++ b/lib/private/Files/Cache/Wrapper/JailWatcher.php @@ -10,12 +10,10 @@ namespace OC\Files\Cache\Wrapper; use OC\Files\Cache\Watcher; class JailWatcher extends Watcher { - private string $root; - private Watcher $watcher; - - public function __construct(Watcher $watcher, string $root) { - $this->watcher = $watcher; - $this->root = $root; + public function __construct( + private Watcher $watcher, + private string $root, + ) { } protected function getRoot(): string { diff --git a/lib/private/Files/Config/CachedMountFileInfo.php b/lib/private/Files/Config/CachedMountFileInfo.php index 69bd4e9301e..1ea77a53e5f 100644 --- a/lib/private/Files/Config/CachedMountFileInfo.php +++ b/lib/private/Files/Config/CachedMountFileInfo.php @@ -10,8 +10,6 @@ use OCP\Files\Config\ICachedMountFileInfo; use OCP\IUser; class CachedMountFileInfo extends CachedMountInfo implements ICachedMountFileInfo { - private string $internalPath; - public function __construct( IUser $user, int $storageId, @@ -20,10 +18,9 @@ class CachedMountFileInfo extends CachedMountInfo implements ICachedMountFileInf ?int $mountId, string $mountProvider, string $rootInternalPath, - string $internalPath, + private string $internalPath, ) { parent::__construct($user, $storageId, $rootId, $mountPoint, $mountProvider, $mountId, $rootInternalPath); - $this->internalPath = $internalPath; } public function getInternalPath(): string { diff --git a/lib/private/Files/Config/LazyStorageMountInfo.php b/lib/private/Files/Config/LazyStorageMountInfo.php index eb2c60dfa46..a3e5140b8cd 100644 --- a/lib/private/Files/Config/LazyStorageMountInfo.php +++ b/lib/private/Files/Config/LazyStorageMountInfo.php @@ -11,17 +11,17 @@ use OCP\Files\Mount\IMountPoint; use OCP\IUser; class LazyStorageMountInfo extends CachedMountInfo { - private IMountPoint $mount; - /** * CachedMountInfo constructor. * * @param IUser $user * @param IMountPoint $mount */ - public function __construct(IUser $user, IMountPoint $mount) { + public function __construct( + IUser $user, + private IMountPoint $mount, + ) { $this->user = $user; - $this->mount = $mount; $this->rootId = 0; $this->storageId = 0; $this->mountPoint = ''; diff --git a/lib/private/Files/Config/UserMountCache.php b/lib/private/Files/Config/UserMountCache.php index 424642f7ca6..ebdfc64d83e 100644 --- a/lib/private/Files/Config/UserMountCache.php +++ b/lib/private/Files/Config/UserMountCache.php @@ -339,7 +339,7 @@ class UserMountCache implements IUserMountCache { /** * @param $fileId * @return array{int, string, int} - * @throws \OCP\Files\NotFoundException + * @throws NotFoundException */ private function getCacheInfoFromFileId($fileId): array { if (!isset($this->cacheInfoCache[$fileId])) { diff --git a/lib/private/Files/Config/UserMountCacheListener.php b/lib/private/Files/Config/UserMountCacheListener.php index 40995de8986..d7ff0b23a4d 100644 --- a/lib/private/Files/Config/UserMountCacheListener.php +++ b/lib/private/Files/Config/UserMountCacheListener.php @@ -14,18 +14,14 @@ use OCP\Files\Config\IUserMountCache; * Listen to hooks and update the mount cache as needed */ class UserMountCacheListener { - /** - * @var IUserMountCache - */ - private $userMountCache; - /** * UserMountCacheListener constructor. * * @param IUserMountCache $userMountCache */ - public function __construct(IUserMountCache $userMountCache) { - $this->userMountCache = $userMountCache; + public function __construct( + private IUserMountCache $userMountCache, + ) { } public function listen(Manager $manager) { diff --git a/lib/private/Files/FilenameValidator.php b/lib/private/Files/FilenameValidator.php index a78c6d3cc3c..987575292d7 100644 --- a/lib/private/Files/FilenameValidator.php +++ b/lib/private/Files/FilenameValidator.php @@ -7,6 +7,7 @@ declare(strict_types=1); */ namespace OC\Files; +use OCP\Constants; use OCP\Files\EmptyFileNameException; use OCP\Files\FileNameTooLongException; use OCP\Files\IFilenameValidator; @@ -126,7 +127,7 @@ class FilenameValidator implements IFilenameValidator { public function getForbiddenCharacters(): array { if (empty($this->forbiddenCharacters)) { // Get always forbidden characters - $forbiddenCharacters = str_split(\OCP\Constants::FILENAME_INVALID_CHARS); + $forbiddenCharacters = str_split(Constants::FILENAME_INVALID_CHARS); // Get admin defined invalid characters $additionalChars = $this->config->getSystemValue('forbidden_filename_characters', []); @@ -159,7 +160,7 @@ class FilenameValidator implements IFilenameValidator { public function isFilenameValid(string $filename): bool { try { $this->validateFilename($filename); - } catch (\OCP\Files\InvalidPathException) { + } catch (InvalidPathException) { return false; } return true; diff --git a/lib/private/Files/Filesystem.php b/lib/private/Files/Filesystem.php index 3054eddf3e7..633ad43e26c 100644 --- a/lib/private/Files/Filesystem.php +++ b/lib/private/Files/Filesystem.php @@ -7,16 +7,22 @@ */ namespace OC\Files; +use OC\Files\Mount\MountPoint; +use OC\Files\Storage\Storage; use OC\Files\Storage\StorageFactory; use OC\User\NoUserException; use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\Events\Node\FilesystemTornDownEvent; +use OCP\Files\InvalidPathException; use OCP\Files\Mount\IMountManager; +use OCP\Files\Mount\IMountPoint; use OCP\Files\NotFoundException; +use OCP\Files\Storage\IStorage; use OCP\Files\Storage\IStorageFactory; use OCP\IUser; use OCP\IUserManager; use OCP\IUserSession; +use OCP\Server; use Psr\Log\LoggerInterface; class Filesystem { @@ -145,7 +151,7 @@ class Filesystem { public const signal_param_mount_type = 'mounttype'; public const signal_param_users = 'users'; - private static ?\OC\Files\Storage\StorageFactory $loader = null; + private static ?StorageFactory $loader = null; private static bool $logWarningWhenAddingStorageWrapper = true; @@ -167,7 +173,7 @@ class Filesystem { */ public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) { if (self::$logWarningWhenAddingStorageWrapper) { - \OCP\Server::get(LoggerInterface::class)->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [ + Server::get(LoggerInterface::class)->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [ 'wrapper' => $wrapperName, 'app' => 'filesystem', ]); @@ -189,7 +195,7 @@ class Filesystem { */ public static function getLoader() { if (!self::$loader) { - self::$loader = \OC::$server->get(IStorageFactory::class); + self::$loader = Server::get(IStorageFactory::class); } return self::$loader; } @@ -242,7 +248,7 @@ class Filesystem { * get the storage mounted at $mountPoint * * @param string $mountPoint - * @return \OC\Files\Storage\Storage|null + * @return IStorage|null */ public static function getStorage($mountPoint) { $mount = self::getMountManager()->find($mountPoint); @@ -251,7 +257,7 @@ class Filesystem { /** * @param string $id - * @return Mount\MountPoint[] + * @return IMountPoint[] */ public static function getMountByStorageId($id) { return self::getMountManager()->findByStorageId($id); @@ -259,7 +265,7 @@ class Filesystem { /** * @param int $id - * @return Mount\MountPoint[] + * @return IMountPoint[] */ public static function getMountByNumericId($id) { return self::getMountManager()->findByNumericId($id); @@ -269,7 +275,7 @@ class Filesystem { * resolve a path to a storage and internal path * * @param string $path - * @return array{?\OCP\Files\Storage\IStorage, string} an array consisting of the storage and the internal path + * @return array{?IStorage, string} an array consisting of the storage and the internal path */ public static function resolvePath($path): array { $mount = self::getMountManager()->find($path); @@ -295,8 +301,8 @@ class Filesystem { self::getLoader(); self::$defaultInstance = new View($root); /** @var IEventDispatcher $eventDispatcher */ - $eventDispatcher = \OC::$server->get(IEventDispatcher::class); - $eventDispatcher->addListener(FilesystemTornDownEvent::class, function () { + $eventDispatcher = Server::get(IEventDispatcher::class); + $eventDispatcher->addListener(FilesystemTornDownEvent::class, function (): void { self::$defaultInstance = null; self::$loaded = false; }); @@ -310,23 +316,23 @@ class Filesystem { public static function initMountManager(): void { if (!self::$mounts) { - self::$mounts = \OC::$server->get(IMountManager::class); + self::$mounts = Server::get(IMountManager::class); } } /** * Initialize system and personal mount points for a user * - * @throws \OC\User\NoUserException if the user is not available + * @throws NoUserException if the user is not available */ public static function initMountPoints(string|IUser|null $user = ''): void { /** @var IUserManager $userManager */ - $userManager = \OC::$server->get(IUserManager::class); + $userManager = Server::get(IUserManager::class); $userObject = ($user instanceof IUser) ? $user : $userManager->get($user); if ($userObject) { /** @var SetupManager $setupManager */ - $setupManager = \OC::$server->get(SetupManager::class); + $setupManager = Server::get(SetupManager::class); $setupManager->setupForUser($userObject); } else { throw new NoUserException(); @@ -339,7 +345,7 @@ class Filesystem { public static function getView(): ?View { if (!self::$defaultInstance) { /** @var IUserSession $session */ - $session = \OC::$server->get(IUserSession::class); + $session = Server::get(IUserSession::class); $user = $session->getUser(); if ($user) { $userDir = '/' . $user->getUID() . '/files'; @@ -373,7 +379,7 @@ class Filesystem { /** * mount an \OC\Files\Storage\Storage in our virtual filesystem * - * @param \OC\Files\Storage\Storage|string $class + * @param Storage|string $class * @param array $arguments * @param string $mountpoint */ @@ -381,7 +387,7 @@ class Filesystem { if (!self::$mounts) { \OC_Util::setupFS(); } - $mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader()); + $mount = new MountPoint($class, $mountpoint, $arguments, self::getLoader()); self::$mounts->addMount($mount); } @@ -410,7 +416,7 @@ class Filesystem { */ public static function isFileBlacklisted($filename) { if (self::$validator === null) { - self::$validator = \OCP\Server::get(FilenameValidator::class); + self::$validator = Server::get(FilenameValidator::class); } $filename = self::normalizePath($filename); @@ -527,7 +533,7 @@ class Filesystem { /** * @param string $path - * @throws \OCP\Files\InvalidPathException + * @throws InvalidPathException */ public static function toTmpFile($path): string|false { return self::$defaultInstance->toTmpFile($path); @@ -637,7 +643,7 @@ class Filesystem { * @param string $path * @param bool|string $includeMountPoints whether to add mountpoint sizes, * defaults to true - * @return \OC\Files\FileInfo|false False if file does not exist + * @return FileInfo|false False if file does not exist */ public static function getFileInfo($path, $includeMountPoints = true) { return self::getView()->getFileInfo($path, $includeMountPoints); @@ -661,7 +667,7 @@ class Filesystem { * * @param string $directory path under datadirectory * @param string $mimetype_filter limit returned content to this mimetype or mimepart - * @return \OC\Files\FileInfo[] + * @return FileInfo[] */ public static function getDirectoryContent($directory, $mimetype_filter = '') { return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter); diff --git a/lib/private/Files/Lock/LockManager.php b/lib/private/Files/Lock/LockManager.php index 978c378e506..e200efa78a7 100644 --- a/lib/private/Files/Lock/LockManager.php +++ b/lib/private/Files/Lock/LockManager.php @@ -11,6 +11,7 @@ use OCP\Files\Lock\ILockManager; use OCP\Files\Lock\ILockProvider; use OCP\Files\Lock\LockContext; use OCP\PreConditionNotMetException; +use OCP\Server; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; @@ -41,7 +42,7 @@ class LockManager implements ILockManager { } if ($this->lockProviderClass) { try { - $this->lockProvider = \OCP\Server::get($this->lockProviderClass); + $this->lockProvider = Server::get($this->lockProviderClass); } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) { } } diff --git a/lib/private/Files/Mount/HomeMountPoint.php b/lib/private/Files/Mount/HomeMountPoint.php index 5a648f08c89..0c3b387f00f 100644 --- a/lib/private/Files/Mount/HomeMountPoint.php +++ b/lib/private/Files/Mount/HomeMountPoint.php @@ -12,10 +12,8 @@ use OCP\Files\Storage\IStorageFactory; use OCP\IUser; class HomeMountPoint extends MountPoint { - private IUser $user; - public function __construct( - IUser $user, + private IUser $user, $storage, string $mountpoint, ?array $arguments = null, @@ -25,7 +23,6 @@ class HomeMountPoint extends MountPoint { ?string $mountProvider = null, ) { parent::__construct($storage, $mountpoint, $arguments, $loader, $mountOptions, $mountId, $mountProvider); - $this->user = $user; } public function getUser(): IUser { diff --git a/lib/private/Files/Mount/LocalHomeMountProvider.php b/lib/private/Files/Mount/LocalHomeMountProvider.php index a2b3d3b2a99..efd4e63831c 100644 --- a/lib/private/Files/Mount/LocalHomeMountProvider.php +++ b/lib/private/Files/Mount/LocalHomeMountProvider.php @@ -8,6 +8,7 @@ namespace OC\Files\Mount; use OCP\Files\Config\IHomeMountProvider; +use OCP\Files\Mount\IMountPoint; use OCP\Files\Storage\IStorageFactory; use OCP\IUser; @@ -20,7 +21,7 @@ class LocalHomeMountProvider implements IHomeMountProvider { * * @param IUser $user * @param IStorageFactory $loader - * @return \OCP\Files\Mount\IMountPoint|null + * @return IMountPoint|null */ public function getHomeMountForUser(IUser $user, IStorageFactory $loader) { $arguments = ['user' => $user]; diff --git a/lib/private/Files/Mount/MountPoint.php b/lib/private/Files/Mount/MountPoint.php index a50a762c6b9..e1a38e86084 100644 --- a/lib/private/Files/Mount/MountPoint.php +++ b/lib/private/Files/Mount/MountPoint.php @@ -12,11 +12,12 @@ use OC\Files\Storage\Storage; use OC\Files\Storage\StorageFactory; use OCP\Files\Mount\IMountPoint; use OCP\Files\Storage\IStorageFactory; +use OCP\Server; use Psr\Log\LoggerInterface; class MountPoint implements IMountPoint { /** - * @var \OC\Files\Storage\Storage|null $storage + * @var Storage|null $storage */ protected $storage = null; protected $class; @@ -40,7 +41,7 @@ class MountPoint implements IMountPoint { protected $mountOptions = []; /** - * @var \OC\Files\Storage\StorageFactory $loader + * @var StorageFactory $loader */ private $loader; @@ -52,17 +53,14 @@ class MountPoint implements IMountPoint { */ private $invalidStorage = false; - /** @var int|null */ - protected $mountId; - /** @var string */ protected $mountProvider; /** - * @param string|\OC\Files\Storage\Storage $storage + * @param string|Storage $storage * @param string $mountpoint * @param array $arguments (optional) configuration for the storage backend - * @param \OCP\Files\Storage\IStorageFactory $loader + * @param IStorageFactory $loader * @param array $mountOptions mount specific options * @param int|null $mountId * @param string|null $mountProvider @@ -74,7 +72,7 @@ class MountPoint implements IMountPoint { ?array $arguments = null, ?IStorageFactory $loader = null, ?array $mountOptions = null, - ?int $mountId = null, + protected ?int $mountId = null, ?string $mountProvider = null, ) { if (is_null($arguments)) { @@ -92,7 +90,6 @@ class MountPoint implements IMountPoint { $mountpoint = $this->formatPath($mountpoint); $this->mountPoint = $mountpoint; - $this->mountId = $mountId; if ($storage instanceof Storage) { $this->class = get_class($storage); $this->storage = $this->loader->wrap($this, $storage); @@ -151,19 +148,19 @@ class MountPoint implements IMountPoint { // the root storage could not be initialized, show the user! throw new \Exception('The root storage could not be initialized. Please contact your local administrator.', $exception->getCode(), $exception); } else { - \OC::$server->get(LoggerInterface::class)->error($exception->getMessage(), ['exception' => $exception]); + Server::get(LoggerInterface::class)->error($exception->getMessage(), ['exception' => $exception]); } return; } } else { - \OC::$server->get(LoggerInterface::class)->error('Storage backend ' . $this->class . ' not found', ['app' => 'core']); + Server::get(LoggerInterface::class)->error('Storage backend ' . $this->class . ' not found', ['app' => 'core']); $this->invalidStorage = true; return; } } /** - * @return \OC\Files\Storage\Storage|null + * @return Storage|null */ public function getStorage() { if (is_null($this->storage)) { diff --git a/lib/private/Files/Mount/RootMountProvider.php b/lib/private/Files/Mount/RootMountProvider.php index 5e0c924ad38..a1ab474ba28 100644 --- a/lib/private/Files/Mount/RootMountProvider.php +++ b/lib/private/Files/Mount/RootMountProvider.php @@ -17,12 +17,10 @@ use OCP\Files\Storage\IStorageFactory; use OCP\IConfig; class RootMountProvider implements IRootMountProvider { - private PrimaryObjectStoreConfig $objectStoreConfig; - private IConfig $config; - - public function __construct(PrimaryObjectStoreConfig $objectStoreConfig, IConfig $config) { - $this->objectStoreConfig = $objectStoreConfig; - $this->config = $config; + public function __construct( + private PrimaryObjectStoreConfig $objectStoreConfig, + private IConfig $config, + ) { } public function getRootMounts(IStorageFactory $loader): array { diff --git a/lib/private/Files/Notify/Change.php b/lib/private/Files/Notify/Change.php index c8eccd11ae2..dd45ebe98c6 100644 --- a/lib/private/Files/Notify/Change.php +++ b/lib/private/Files/Notify/Change.php @@ -9,21 +9,16 @@ namespace OC\Files\Notify; use OCP\Files\Notify\IChange; class Change implements IChange { - /** @var int */ - private $type; - - /** @var string */ - private $path; - /** * Change constructor. * * @param int $type * @param string $path */ - public function __construct($type, $path) { - $this->type = $type; - $this->path = $path; + public function __construct( + private $type, + private $path, + ) { } /** diff --git a/lib/private/Files/Notify/RenameChange.php b/lib/private/Files/Notify/RenameChange.php index 28554ceaa26..0713244efc1 100644 --- a/lib/private/Files/Notify/RenameChange.php +++ b/lib/private/Files/Notify/RenameChange.php @@ -9,9 +9,6 @@ namespace OC\Files\Notify; use OCP\Files\Notify\IRenameChange; class RenameChange extends Change implements IRenameChange { - /** @var string */ - private $targetPath; - /** * Change constructor. * @@ -19,9 +16,12 @@ class RenameChange extends Change implements IRenameChange { * @param string $path * @param string $targetPath */ - public function __construct($type, $path, $targetPath) { + public function __construct( + $type, + $path, + private $targetPath, + ) { parent::__construct($type, $path); - $this->targetPath = $targetPath; } /** diff --git a/lib/private/Files/ObjectStore/ObjectStoreScanner.php b/lib/private/Files/ObjectStore/ObjectStoreScanner.php index 5c3992b8458..a31947ec8ae 100644 --- a/lib/private/Files/ObjectStore/ObjectStoreScanner.php +++ b/lib/private/Files/ObjectStore/ObjectStoreScanner.php @@ -29,7 +29,7 @@ class ObjectStoreScanner extends Scanner { // find any path marked as unscanned and run the scanner until no more paths are unscanned (or we get stuck) // we sort by path DESC to ensure that contents of a folder are handled before the parent folder while (($path = $this->getIncomplete()) !== false && $path !== $lastPath) { - $this->runBackgroundScanJob(function () use ($path) { + $this->runBackgroundScanJob(function () use ($path): void { $item = $this->cache->get($path); if ($item && $item->getMimeType() !== FileInfo::MIMETYPE_FOLDER) { $fh = $this->storage->fopen($path, 'r'); diff --git a/lib/private/Files/ObjectStore/ObjectStoreStorage.php b/lib/private/Files/ObjectStore/ObjectStoreStorage.php index ce5fc5b1063..a28475e0e4b 100644 --- a/lib/private/Files/ObjectStore/ObjectStoreStorage.php +++ b/lib/private/Files/ObjectStore/ObjectStoreStorage.php @@ -14,13 +14,16 @@ use Icewind\Streams\CountWrapper; use Icewind\Streams\IteratorDirectory; use OC\Files\Cache\Cache; use OC\Files\Cache\CacheEntry; +use OC\Files\Storage\Common; use OC\Files\Storage\PolyFill\CopyDirectory; +use OCP\Constants; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\Files\Cache\ICache; use OCP\Files\Cache\ICacheEntry; use OCP\Files\Cache\IScanner; use OCP\Files\FileInfo; use OCP\Files\GenericFileException; +use OCP\Files\IMimeTypeDetector; use OCP\Files\NotFoundException; use OCP\Files\ObjectStore\IObjectStore; use OCP\Files\ObjectStore\IObjectStoreMetaData; @@ -28,11 +31,12 @@ use OCP\Files\ObjectStore\IObjectStoreMultiPartUpload; use OCP\Files\Storage\IChunkedFileWrite; use OCP\Files\Storage\IStorage; use OCP\IDBConnection; +use OCP\ITempManager; use OCP\Server; use Override; use Psr\Log\LoggerInterface; -class ObjectStoreStorage extends \OC\Files\Storage\Common implements IChunkedFileWrite { +class ObjectStoreStorage extends Common implements IChunkedFileWrite { use CopyDirectory; protected IObjectStore $objectStore; @@ -72,7 +76,7 @@ class ObjectStoreStorage extends \OC\Files\Storage\Common implements IChunkedFil $this->totalSizeLimit = $parameters['totalSizeLimit']; } - $this->logger = \OCP\Server::get(LoggerInterface::class); + $this->logger = Server::get(LoggerInterface::class); } public function mkdir(string $path, bool $force = false, array $metadata = []): bool { @@ -88,7 +92,7 @@ class ObjectStoreStorage extends \OC\Files\Storage\Common implements IChunkedFil 'size' => $metadata['size'] ?? 0, 'mtime' => $mTime, 'storage_mtime' => $mTime, - 'permissions' => \OCP\Constants::PERMISSION_ALL, + 'permissions' => Constants::PERMISSION_ALL, ]; if ($path === '') { //create root on the fly @@ -144,7 +148,7 @@ class ObjectStoreStorage extends \OC\Files\Storage\Common implements IChunkedFil if (!isset($this->scanner)) { $this->scanner = new ObjectStoreScanner($storage); } - /** @var \OC\Files\ObjectStore\ObjectStoreScanner */ + /** @var ObjectStoreScanner */ return $this->scanner; } @@ -352,9 +356,9 @@ class ObjectStoreStorage extends \OC\Files\Storage\Common implements IChunkedFil return false; } - $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext); + $tmpFile = Server::get(ITempManager::class)->getTemporaryFile($ext); $handle = fopen($tmpFile, $mode); - return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) { + return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile): void { $this->writeBack($tmpFile, $path); unlink($tmpFile); }); @@ -366,13 +370,13 @@ class ObjectStoreStorage extends \OC\Files\Storage\Common implements IChunkedFil case 'x+': case 'c': case 'c+': - $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext); + $tmpFile = Server::get(ITempManager::class)->getTemporaryFile($ext); if ($this->file_exists($path)) { $source = $this->fopen($path, 'r'); file_put_contents($tmpFile, $source); } $handle = fopen($tmpFile, $mode); - return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) { + return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile): void { $this->writeBack($tmpFile, $path); unlink($tmpFile); }); @@ -467,7 +471,7 @@ class ObjectStoreStorage extends \OC\Files\Storage\Common implements IChunkedFil if (empty($stat)) { // create new file $stat = [ - 'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE, + 'permissions' => Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE, ]; } // update stat with new data @@ -476,7 +480,7 @@ class ObjectStoreStorage extends \OC\Files\Storage\Common implements IChunkedFil $stat['mtime'] = $mTime; $stat['storage_mtime'] = $mTime; - $mimetypeDetector = \OC::$server->getMimeTypeDetector(); + $mimetypeDetector = Server::get(IMimeTypeDetector::class); $mimetype = $mimetypeDetector->detectPath($path); $metadata = [ 'mimetype' => $mimetype, @@ -509,7 +513,7 @@ class ObjectStoreStorage extends \OC\Files\Storage\Common implements IChunkedFil //upload to object storage $totalWritten = 0; - $countStream = CountWrapper::wrap($stream, function ($writtenSize) use ($fileId, $size, $exists, &$totalWritten) { + $countStream = CountWrapper::wrap($stream, function ($writtenSize) use ($fileId, $size, $exists, &$totalWritten): void { if (is_null($size) && !$exists) { $this->getCache()->update($fileId, [ 'size' => $writtenSize, @@ -732,7 +736,7 @@ class ObjectStoreStorage extends \OC\Files\Storage\Common implements IChunkedFil $this->objectStore->copyObject($sourceUrn, $targetUrn); if ($this->handleCopiesAsOwned) { // Copied the file thus we gain all permissions as we are the owner now ! warning while this aligns with local storage it should not be used and instead fix local storage ! - $cache->update($targetId, ['permissions' => \OCP\Constants::PERMISSION_ALL]); + $cache->update($targetId, ['permissions' => Constants::PERMISSION_ALL]); } } catch (\Exception $e) { $cache->remove($to); diff --git a/lib/private/Files/ObjectStore/S3ObjectTrait.php b/lib/private/Files/ObjectStore/S3ObjectTrait.php index b6b55c746b2..384e9f0ff58 100644 --- a/lib/private/Files/ObjectStore/S3ObjectTrait.php +++ b/lib/private/Files/ObjectStore/S3ObjectTrait.php @@ -16,6 +16,7 @@ use Aws\S3\S3Client; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Utils; use OC\Files\Stream\SeekableHttpStream; +use OCA\DAV\Connector\Sabre\Exception\BadGateway; use Psr\Http\Message\StreamInterface; trait S3ObjectTrait { @@ -157,10 +158,10 @@ trait S3ObjectTrait { 'Metadata' => $this->buildS3Metadata($metaData), 'StorageClass' => $this->storageClass, ] + $this->getSSECParameters(), - 'before_upload' => function (Command $command) use (&$totalWritten) { + 'before_upload' => function (Command $command) use (&$totalWritten): void { $totalWritten += $command['ContentLength']; }, - 'before_complete' => function ($_command) use (&$totalWritten, $size, &$uploader, &$attempts) { + 'before_complete' => function ($_command) use (&$totalWritten, $size, &$uploader, &$attempts): void { if ($size !== null && $totalWritten != $size) { $e = new \Exception('Incomplete multi part upload, expected ' . $size . ' bytes, wrote ' . $totalWritten); throw new MultipartUploadException($uploader->getState(), $e); @@ -196,7 +197,7 @@ trait S3ObjectTrait { $this->getConnection()->abortMultipartUpload($uploadInfo); } - throw new \OCA\DAV\Connector\Sabre\Exception\BadGateway('Error while uploading to S3 bucket', 0, $exception); + throw new BadGateway('Error while uploading to S3 bucket', 0, $exception); } } diff --git a/lib/private/Files/ObjectStore/StorageObjectStore.php b/lib/private/Files/ObjectStore/StorageObjectStore.php index c20efb346a1..3b71bace3c4 100644 --- a/lib/private/Files/ObjectStore/StorageObjectStore.php +++ b/lib/private/Files/ObjectStore/StorageObjectStore.php @@ -14,14 +14,12 @@ use function is_resource; * Object store that wraps a storage backend, mostly for testing purposes */ class StorageObjectStore implements IObjectStore { - /** @var IStorage */ - private $storage; - /** * @param IStorage $storage */ - public function __construct(IStorage $storage) { - $this->storage = $storage; + public function __construct( + private IStorage $storage, + ) { } /** diff --git a/lib/private/Files/ObjectStore/Swift.php b/lib/private/Files/ObjectStore/Swift.php index 9006f29160d..b1fb7e520db 100644 --- a/lib/private/Files/ObjectStore/Swift.php +++ b/lib/private/Files/ObjectStore/Swift.php @@ -14,6 +14,10 @@ use Icewind\Streams\RetryWrapper; use OCP\Files\NotFoundException; use OCP\Files\ObjectStore\IObjectStore; use OCP\Files\StorageAuthException; +use OCP\Files\StorageNotAvailableException; +use OCP\ICacheFactory; +use OCP\ITempManager; +use OCP\Server; use Psr\Log\LoggerInterface; const SWIFT_SEGMENT_SIZE = 1073741824; // 1GB @@ -29,9 +33,9 @@ class Swift implements IObjectStore { public function __construct($params, ?SwiftFactory $connectionFactory = null) { $this->swiftFactory = $connectionFactory ?: new SwiftFactory( - \OC::$server->getMemCacheFactory()->createDistributed('swift::'), + Server::get(ICacheFactory::class)->createDistributed('swift::'), $params, - \OC::$server->get(LoggerInterface::class) + Server::get(LoggerInterface::class) ); $this->params = $params; } @@ -39,7 +43,7 @@ class Swift implements IObjectStore { /** * @return \OpenStack\ObjectStore\v1\Models\Container * @throws StorageAuthException - * @throws \OCP\Files\StorageNotAvailableException + * @throws StorageNotAvailableException */ private function getContainer() { return $this->swiftFactory->getContainer(); @@ -57,7 +61,7 @@ class Swift implements IObjectStore { } public function writeObject($urn, $stream, ?string $mimetype = null) { - $tmpFile = \OC::$server->getTempManager()->getTemporaryFile('swiftwrite'); + $tmpFile = Server::get(ITempManager::class)->getTemporaryFile('swiftwrite'); file_put_contents($tmpFile, $stream); $handle = fopen($tmpFile, 'rb'); diff --git a/lib/private/Files/ObjectStore/SwiftFactory.php b/lib/private/Files/ObjectStore/SwiftFactory.php index 118724159e5..f2da11c4901 100644 --- a/lib/private/Files/ObjectStore/SwiftFactory.php +++ b/lib/private/Files/ObjectStore/SwiftFactory.php @@ -28,11 +28,8 @@ use Psr\Http\Message\RequestInterface; use Psr\Log\LoggerInterface; class SwiftFactory { - private $cache; - private $params; /** @var Container|null */ private $container = null; - private LoggerInterface $logger; public const DEFAULT_OPTIONS = [ 'autocreate' => false, @@ -41,10 +38,11 @@ class SwiftFactory { 'catalogType' => 'object-store' ]; - public function __construct(ICache $cache, array $params, LoggerInterface $logger) { - $this->cache = $cache; - $this->params = $params; - $this->logger = $logger; + public function __construct( + private ICache $cache, + private array $params, + private LoggerInterface $logger, + ) { } /** diff --git a/lib/private/Files/Search/SearchBinaryOperator.php b/lib/private/Files/Search/SearchBinaryOperator.php index 49f599933f4..3424a044179 100644 --- a/lib/private/Files/Search/SearchBinaryOperator.php +++ b/lib/private/Files/Search/SearchBinaryOperator.php @@ -10,10 +10,6 @@ use OCP\Files\Search\ISearchBinaryOperator; use OCP\Files\Search\ISearchOperator; class SearchBinaryOperator implements ISearchBinaryOperator { - /** @var string */ - private $type; - /** @var (SearchBinaryOperator|SearchComparison)[] */ - private $arguments; private $hints = []; /** @@ -22,9 +18,10 @@ class SearchBinaryOperator implements ISearchBinaryOperator { * @param string $type * @param (SearchBinaryOperator|SearchComparison)[] $arguments */ - public function __construct($type, array $arguments) { - $this->type = $type; - $this->arguments = $arguments; + public function __construct( + private $type, + private array $arguments, + ) { } /** diff --git a/lib/private/Files/Search/SearchQuery.php b/lib/private/Files/Search/SearchQuery.php index 592749cf4a0..131d8c36e38 100644 --- a/lib/private/Files/Search/SearchQuery.php +++ b/lib/private/Files/Search/SearchQuery.php @@ -12,18 +12,6 @@ use OCP\Files\Search\ISearchQuery; use OCP\IUser; class SearchQuery implements ISearchQuery { - /** @var ISearchOperator */ - private $searchOperation; - /** @var integer */ - private $limit; - /** @var integer */ - private $offset; - /** @var ISearchOrder[] */ - private $order; - /** @var ?IUser */ - private $user; - private $limitToHome; - /** * SearchQuery constructor. * @@ -35,19 +23,13 @@ class SearchQuery implements ISearchQuery { * @param bool $limitToHome */ public function __construct( - ISearchOperator $searchOperation, - int $limit, - int $offset, - array $order, - ?IUser $user = null, - bool $limitToHome = false, + private ISearchOperator $searchOperation, + private int $limit, + private int $offset, + private array $order, + private ?IUser $user = null, + private bool $limitToHome = false, ) { - $this->searchOperation = $searchOperation; - $this->limit = $limit; - $this->offset = $offset; - $this->order = $order; - $this->user = $user; - $this->limitToHome = $limitToHome; } /** diff --git a/lib/private/Files/SetupManager.php b/lib/private/Files/SetupManager.php index d23314ace21..c8945de7cae 100644 --- a/lib/private/Files/SetupManager.php +++ b/lib/private/Files/SetupManager.php @@ -19,6 +19,7 @@ use OC\Files\Storage\Wrapper\Encoding; use OC\Files\Storage\Wrapper\PermissionsMask; use OC\Files\Storage\Wrapper\Quota; use OC\Lockdown\Filesystem\NullStorage; +use OC\ServerNotAvailableException; use OC\Share\Share; use OC\Share20\ShareDisableChecker; use OC_Hook; @@ -49,6 +50,7 @@ use OCP\Files\NotFoundException; use OCP\Files\Storage\IStorage; use OCP\Group\Events\UserAddedEvent; use OCP\Group\Events\UserRemovedEvent; +use OCP\HintException; use OCP\ICache; use OCP\ICacheFactory; use OCP\IConfig; @@ -272,7 +274,7 @@ class SetupManager implements ISetupManager { $this->setupUserMountProviders[$user->getUID()] ??= []; $previouslySetupProviders = $this->setupUserMountProviders[$user->getUID()]; - $this->setupForUserWith($user, function () use ($user) { + $this->setupForUserWith($user, function () use ($user): void { $this->mountProviderCollection->addMountForUser($user, $this->mountManager, function ( string $providerClass, ) use ($user) { @@ -381,13 +383,9 @@ class SetupManager implements ISetupManager { * Executes the one-time user setup and, if the user can access the * filesystem, executes $mountCallback. * - * @param IUser $user - * @param IMountPoint $mounts - * @return void - * @throws \OCP\HintException - * @throws \OC\ServerNotAvailableException + * @throws HintException + * @throws ServerNotAvailableException * @see self::oneTimeUserSetup() - * */ private function setupForUserWith(IUser $user, callable $mountCallback): void { $this->oneTimeUserSetup($user); @@ -715,7 +713,7 @@ class SetupManager implements ISetupManager { } $this->registerMounts($user, $mounts, $providers); - $this->setupForUserWith($user, function () use ($mounts) { + $this->setupForUserWith($user, function () use ($mounts): void { array_walk($mounts, [$this->mountManager, 'addMount']); }); $this->eventLogger->end('fs:setup:user:providers'); @@ -742,7 +740,7 @@ class SetupManager implements ISetupManager { $this->listeningForProviders = true; $this->mountProviderCollection->listen('\OC\Files\Config', 'registerMountProvider', function ( IMountProvider $provider, - ) { + ): void { foreach ($this->setupUsers as $userId) { $user = $this->userManager->get($userId); if ($user) { @@ -758,13 +756,13 @@ class SetupManager implements ISetupManager { // note that this event handling is intentionally pessimistic // clearing the cache to often is better than not enough - $this->eventDispatcher->addListener(UserAddedEvent::class, function (UserAddedEvent $event) { + $this->eventDispatcher->addListener(UserAddedEvent::class, function (UserAddedEvent $event): void { $this->cache->remove($event->getUser()->getUID()); }); - $this->eventDispatcher->addListener(UserRemovedEvent::class, function (UserRemovedEvent $event) { + $this->eventDispatcher->addListener(UserRemovedEvent::class, function (UserRemovedEvent $event): void { $this->cache->remove($event->getUser()->getUID()); }); - $this->eventDispatcher->addListener(ShareCreatedEvent::class, function (ShareCreatedEvent $event) { + $this->eventDispatcher->addListener(ShareCreatedEvent::class, function (ShareCreatedEvent $event): void { $this->cache->remove($event->getShare()->getSharedWith()); }); $this->eventDispatcher->addListener(BeforeNodeRenamedEvent::class, function (BeforeNodeRenamedEvent $event) { @@ -778,7 +776,7 @@ class SetupManager implements ISetupManager { } }); $this->eventDispatcher->addListener(InvalidateMountCacheEvent::class, function (InvalidateMountCacheEvent $event, - ) { + ): void { if ($user = $event->getUser()) { $this->cache->remove($user->getUID()); } else { @@ -794,7 +792,7 @@ class SetupManager implements ISetupManager { ]; foreach ($genericEvents as $genericEvent) { - $this->eventDispatcher->addListener($genericEvent, function ($event) { + $this->eventDispatcher->addListener($genericEvent, function ($event): void { $this->cache->clear(); }); } diff --git a/lib/private/Files/SimpleFS/NewSimpleFile.php b/lib/private/Files/SimpleFS/NewSimpleFile.php index d0986592c03..cf676016510 100644 --- a/lib/private/Files/SimpleFS/NewSimpleFile.php +++ b/lib/private/Files/SimpleFS/NewSimpleFile.php @@ -16,16 +16,15 @@ use OCP\Files\NotPermittedException; use OCP\Files\SimpleFS\ISimpleFile; class NewSimpleFile implements ISimpleFile { - private Folder $parentFolder; - private string $name; private ?File $file = null; /** * File constructor. */ - public function __construct(Folder $parentFolder, string $name) { - $this->parentFolder = $parentFolder; - $this->name = $name; + public function __construct( + private Folder $parentFolder, + private string $name, + ) { } /** @@ -179,7 +178,7 @@ class NewSimpleFile implements ISimpleFile { * Open the file as stream for reading, resulting resource can be operated as stream like the result from php's own fopen * * @return resource|false - * @throws \OCP\Files\NotPermittedException + * @throws NotPermittedException * @since 14.0.0 */ public function read() { @@ -194,7 +193,7 @@ class NewSimpleFile implements ISimpleFile { * Open the file as stream for writing, resulting resource can be operated as stream like the result from php's own fopen * * @return resource|bool - * @throws \OCP\Files\NotPermittedException + * @throws NotPermittedException * @since 14.0.0 */ public function write() { @@ -202,7 +201,7 @@ class NewSimpleFile implements ISimpleFile { return $this->file->fopen('w'); } else { $source = fopen('php://temp', 'w+'); - return CallbackWrapper::wrap($source, null, null, null, null, function () use ($source) { + return CallbackWrapper::wrap($source, null, null, null, null, function () use ($source): void { rewind($source); $this->putContent($source); }); diff --git a/lib/private/Files/SimpleFS/SimpleFile.php b/lib/private/Files/SimpleFS/SimpleFile.php index d9c1b47d2f1..4f9911a9ce9 100644 --- a/lib/private/Files/SimpleFS/SimpleFile.php +++ b/lib/private/Files/SimpleFS/SimpleFile.php @@ -14,10 +14,9 @@ use OCP\Files\SimpleFS\ISimpleFile; use OCP\Lock\LockedException; class SimpleFile implements ISimpleFile { - private File $file; - - public function __construct(File $file) { - $this->file = $file; + public function __construct( + private File $file, + ) { } /** @@ -139,7 +138,7 @@ class SimpleFile implements ISimpleFile { * Open the file as stream for reading, resulting resource can be operated as stream like the result from php's own fopen * * @return resource|false - * @throws \OCP\Files\NotPermittedException + * @throws NotPermittedException * @since 14.0.0 */ public function read() { @@ -150,7 +149,7 @@ class SimpleFile implements ISimpleFile { * Open the file as stream for writing, resulting resource can be operated as stream like the result from php's own fopen * * @return resource|false - * @throws \OCP\Files\NotPermittedException + * @throws NotPermittedException * @since 14.0.0 */ public function write() { diff --git a/lib/private/Files/SimpleFS/SimpleFolder.php b/lib/private/Files/SimpleFS/SimpleFolder.php index 62f3db25e9b..f8c3b8c2485 100644 --- a/lib/private/Files/SimpleFS/SimpleFolder.php +++ b/lib/private/Files/SimpleFS/SimpleFolder.php @@ -14,16 +14,14 @@ use OCP\Files\SimpleFS\ISimpleFile; use OCP\Files\SimpleFS\ISimpleFolder; class SimpleFolder implements ISimpleFolder { - /** @var Folder */ - private $folder; - /** * Folder constructor. * * @param Folder $folder */ - public function __construct(Folder $folder) { - $this->folder = $folder; + public function __construct( + private Folder $folder, + ) { } public function getName(): string { diff --git a/lib/private/Files/Storage/Common.php b/lib/private/Files/Storage/Common.php index 6040059370f..e19f8812e9a 100644 --- a/lib/private/Files/Storage/Common.php +++ b/lib/private/Files/Storage/Common.php @@ -19,15 +19,18 @@ use OC\Files\ObjectStore\ObjectStoreStorage; use OC\Files\Storage\Wrapper\Encryption; use OC\Files\Storage\Wrapper\Jail; use OC\Files\Storage\Wrapper\Wrapper; +use OCP\Constants; use OCP\Files; use OCP\Files\Cache\ICache; use OCP\Files\Cache\IPropagator; use OCP\Files\Cache\IScanner; use OCP\Files\Cache\IUpdater; use OCP\Files\Cache\IWatcher; +use OCP\Files\FileInfo; use OCP\Files\ForbiddenException; use OCP\Files\GenericFileException; use OCP\Files\IFilenameValidator; +use OCP\Files\IMimeTypeDetector; use OCP\Files\InvalidPathException; use OCP\Files\Storage\IConstructableStorage; use OCP\Files\Storage\ILockingStorage; @@ -35,9 +38,11 @@ use OCP\Files\Storage\IStorage; use OCP\Files\Storage\IWriteStreamStorage; use OCP\Files\StorageNotAvailableException; use OCP\IConfig; +use OCP\IDBConnection; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; use OCP\Server; +use OCP\Util; use Override; use Psr\Log\LoggerInterface; @@ -135,19 +140,19 @@ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage, public function getPermissions(string $path): int { $permissions = 0; if ($this->isCreatable($path)) { - $permissions |= \OCP\Constants::PERMISSION_CREATE; + $permissions |= Constants::PERMISSION_CREATE; } if ($this->isReadable($path)) { - $permissions |= \OCP\Constants::PERMISSION_READ; + $permissions |= Constants::PERMISSION_READ; } if ($this->isUpdatable($path)) { - $permissions |= \OCP\Constants::PERMISSION_UPDATE; + $permissions |= Constants::PERMISSION_UPDATE; } if ($this->isDeletable($path)) { - $permissions |= \OCP\Constants::PERMISSION_DELETE; + $permissions |= Constants::PERMISSION_DELETE; } if ($this->isSharable($path)) { - $permissions |= \OCP\Constants::PERMISSION_SHARE; + $permissions |= Constants::PERMISSION_SHARE; } return $permissions; } @@ -220,7 +225,7 @@ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage, if ($this->is_dir($path)) { return 'httpd/unix-directory'; } elseif ($this->file_exists($path)) { - return \OC::$server->getMimeTypeDetector()->detectPath($path); + return Server::get(IMimeTypeDetector::class)->detectPath($path); } else { return false; } @@ -346,7 +351,7 @@ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage, /** @var self $storage */ if (!isset($storage->propagator)) { $config = Server::get(IConfig::class); - $storage->propagator = new Propagator($storage, \OC::$server->getDatabaseConnection(), ['appdata_' . $config->getSystemValueString('instanceid')]); + $storage->propagator = new Propagator($storage, Server::get(IDBConnection::class), ['appdata_' . $config->getSystemValueString('instanceid')]); } return $storage->propagator; } @@ -427,7 +432,7 @@ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage, } public function free_space(string $path): int|float|false { - return \OCP\Files\FileInfo::SPACE_UNKNOWN; + return FileInfo::SPACE_UNKNOWN; } public function isLocal(): bool { @@ -468,7 +473,7 @@ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage, } catch (InvalidPathException $e) { // Ignore invalid file type exceptions on directories if ($e->getCode() !== FilenameValidator::INVALID_FILE_TYPE) { - $l = \OCP\Util::getL10N('lib'); + $l = Util::getL10N('lib'); throw new InvalidPathException($l->t('Invalid parent path'), previous: $e); } } @@ -600,7 +605,7 @@ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage, } $permissions = $this->getPermissions($path); - if (!$permissions & \OCP\Constants::PERMISSION_READ) { + if (!$permissions & Constants::PERMISSION_READ) { //can't read, nothing we can do return null; } diff --git a/lib/private/Files/Storage/CommonTest.php b/lib/private/Files/Storage/CommonTest.php index da796130899..a36fe687192 100644 --- a/lib/private/Files/Storage/CommonTest.php +++ b/lib/private/Files/Storage/CommonTest.php @@ -7,15 +7,15 @@ */ namespace OC\Files\Storage; -class CommonTest extends \OC\Files\Storage\Common { +class CommonTest extends Common { /** * underlying local storage used for missing functions - * @var \OC\Files\Storage\Local + * @var Local */ private $storage; public function __construct(array $parameters) { - $this->storage = new \OC\Files\Storage\Local($parameters); + $this->storage = new Local($parameters); } public function getId(): string { diff --git a/lib/private/Files/Storage/DAV.php b/lib/private/Files/Storage/DAV.php index 05899365fbe..49a91cced9c 100644 --- a/lib/private/Files/Storage/DAV.php +++ b/lib/private/Files/Storage/DAV.php @@ -26,6 +26,8 @@ use OCP\Http\Client\IClient; use OCP\Http\Client\IClientService; use OCP\ICertificateManager; use OCP\IConfig; +use OCP\ITempManager; +use OCP\Lock\LockedException; use OCP\Server; use OCP\Util; use Psr\Http\Message\ResponseInterface; @@ -128,7 +130,7 @@ class DAV extends Common { $this->eventLogger = Server::get(IEventLogger::class); // This timeout value will be used for the download and upload of files $this->timeout = Server::get(IConfig::class)->getSystemValueInt('davstorage.request_timeout', IClient::DEFAULT_REQUEST_TIMEOUT); - $this->mimeTypeDetector = \OC::$server->getMimeTypeDetector(); + $this->mimeTypeDetector = Server::get(IMimeTypeDetector::class); } protected function init(): void { @@ -165,12 +167,12 @@ class DAV extends Common { } $lastRequestStart = 0; - $this->client->on('beforeRequest', function (RequestInterface $request) use (&$lastRequestStart) { + $this->client->on('beforeRequest', function (RequestInterface $request) use (&$lastRequestStart): void { $this->logger->debug('sending dav ' . $request->getMethod() . ' request to external storage: ' . $request->getAbsoluteUrl(), ['app' => 'dav']); $lastRequestStart = microtime(true); $this->eventLogger->start('fs:storage:dav:request', 'Sending dav request to external storage'); }); - $this->client->on('afterRequest', function (RequestInterface $request) use (&$lastRequestStart) { + $this->client->on('afterRequest', function (RequestInterface $request) use (&$lastRequestStart): void { $elapsed = microtime(true) - $lastRequestStart; $this->logger->debug('dav ' . $request->getMethod() . ' request to external storage: ' . $request->getAbsoluteUrl() . ' took ' . round($elapsed * 1000, 1) . 'ms', ['app' => 'dav']); $this->eventLogger->end('fs:storage:dav:request'); @@ -374,7 +376,7 @@ class DAV extends Common { if ($response->getStatusCode() !== Http::STATUS_OK) { if ($response->getStatusCode() === Http::STATUS_LOCKED) { - throw new \OCP\Lock\LockedException($path); + throw new LockedException($path); } else { $this->logger->error('Guzzle get returned status code ' . $response->getStatusCode(), ['app' => 'webdav client']); } @@ -400,7 +402,7 @@ class DAV extends Common { case 'c': case 'c+': //emulate these - $tempManager = \OC::$server->getTempManager(); + $tempManager = Server::get(ITempManager::class); if (strrpos($path, '.') !== false) { $ext = substr($path, strrpos($path, '.')); } else { @@ -422,7 +424,7 @@ class DAV extends Common { $tmpFile = $tempManager->getTemporaryFile($ext); } $handle = fopen($tmpFile, $mode); - return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) { + return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile): void { $this->writeBack($tmpFile, $path); }); } @@ -814,7 +816,7 @@ class DAV extends Common { $this->logger->debug($e->getMessage(), ['app' => 'files_external', 'exception' => $e]); if ($e instanceof ClientHttpException) { if ($e->getHttpStatus() === Http::STATUS_LOCKED) { - throw new \OCP\Lock\LockedException($path); + throw new LockedException($path); } if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) { // either password was changed or was invalid all along diff --git a/lib/private/Files/Storage/Home.php b/lib/private/Files/Storage/Home.php index 91b8071ac30..195c9102166 100644 --- a/lib/private/Files/Storage/Home.php +++ b/lib/private/Files/Storage/Home.php @@ -7,23 +7,28 @@ */ namespace OC\Files\Storage; +use OC\Files\Cache\HomeCache; use OC\Files\Cache\HomePropagator; +use OC\User\User; use OCP\Files\Cache\ICache; use OCP\Files\Cache\IPropagator; +use OCP\Files\IHomeStorage; use OCP\Files\Storage\IStorage; +use OCP\IDBConnection; use OCP\IUser; +use OCP\Server; /** * Specialized version of Local storage for home directory usage */ -class Home extends Local implements \OCP\Files\IHomeStorage { +class Home extends Local implements IHomeStorage { /** * @var string */ protected $id; /** - * @var \OC\User\User $user + * @var User $user */ protected $user; @@ -50,7 +55,7 @@ class Home extends Local implements \OCP\Files\IHomeStorage { $storage = $this; } if (!isset($this->cache)) { - $this->cache = new \OC\Files\Cache\HomeCache($storage, $this->getCacheDependencies()); + $this->cache = new HomeCache($storage, $this->getCacheDependencies()); } return $this->cache; } @@ -60,7 +65,7 @@ class Home extends Local implements \OCP\Files\IHomeStorage { $storage = $this; } if (!isset($this->propagator)) { - $this->propagator = new HomePropagator($storage, \OC::$server->getDatabaseConnection()); + $this->propagator = new HomePropagator($storage, Server::get(IDBConnection::class)); } return $this->propagator; } diff --git a/lib/private/Files/Storage/Local.php b/lib/private/Files/Storage/Local.php index 0a12b8d5314..a27489ce7b6 100644 --- a/lib/private/Files/Storage/Local.php +++ b/lib/private/Files/Storage/Local.php @@ -10,7 +10,10 @@ namespace OC\Files\Storage; use OC\Files\Filesystem; use OC\Files\Storage\Wrapper\Encryption; use OC\Files\Storage\Wrapper\Jail; +use OC\LargeFileHelper; +use OCA\FilesAccessControl\StorageWrapper; use OCP\Constants; +use OCP\Files\FileInfo; use OCP\Files\ForbiddenException; use OCP\Files\GenericFileException; use OCP\Files\IMimeTypeDetector; @@ -24,7 +27,7 @@ use Psr\Log\LoggerInterface; /** * for local filestore, we only have to map the paths */ -class Local extends \OC\Files\Storage\Common { +class Local extends Common { protected $datadir; protected $dataDirLength; @@ -228,7 +231,7 @@ class Local extends \OC\Files\Storage\Common { } $fullPath = $this->getSourcePath($path); if (PHP_INT_SIZE === 4) { - $helper = new \OC\LargeFileHelper; + $helper = new LargeFileHelper; return $helper->getFileSize($fullPath); } return filesize($fullPath); @@ -263,7 +266,7 @@ class Local extends \OC\Files\Storage\Common { return false; } if (PHP_INT_SIZE === 4) { - $helper = new \OC\LargeFileHelper(); + $helper = new LargeFileHelper(); return $helper->getFileMtime($fullPath); } return filemtime($fullPath); @@ -415,7 +418,7 @@ class Local extends \OC\Files\Storage\Common { } $space = (function_exists('disk_free_space') && is_dir($sourcePath)) ? disk_free_space($sourcePath) : false; if ($space === false || is_null($space)) { - return \OCP\Files\FileInfo::SPACE_UNKNOWN; + return FileInfo::SPACE_UNKNOWN; } return Util::numericToNumber($space); } @@ -432,7 +435,7 @@ class Local extends \OC\Files\Storage\Common { $files = []; $physicalDir = $this->getSourcePath($dir); foreach (scandir($physicalDir) as $item) { - if (\OC\Files\Filesystem::isIgnoredDir($item)) { + if (Filesystem::isIgnoredDir($item)) { continue; } $physicalItem = $physicalDir . '/' . $item; @@ -534,7 +537,7 @@ class Local extends \OC\Files\Storage\Common { // more permissions checks. && !$sourceStorage->instanceOfStorage('OCA\GroupFolders\ACL\ACLStorageWrapper') // Same for access control - && !$sourceStorage->instanceOfStorage(\OCA\FilesAccessControl\StorageWrapper::class) + && !$sourceStorage->instanceOfStorage(StorageWrapper::class) // when moving encrypted files we have to handle keys and the target might not be encrypted && !$sourceStorage->instanceOfStorage(Encryption::class); } @@ -544,13 +547,13 @@ class Local extends \OC\Files\Storage\Common { // resolve any jailed paths while ($sourceStorage->instanceOfStorage(Jail::class)) { /** - * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage + * @var Jail $sourceStorage */ $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath); $sourceStorage = $sourceStorage->getUnjailedStorage(); } /** - * @var \OC\Files\Storage\Local $sourceStorage + * @var Local $sourceStorage */ $rootStorage = new Local(['datadir' => '/']); return $rootStorage->copy($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath)); @@ -564,13 +567,13 @@ class Local extends \OC\Files\Storage\Common { // resolve any jailed paths while ($sourceStorage->instanceOfStorage(Jail::class)) { /** - * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage + * @var Jail $sourceStorage */ $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath); $sourceStorage = $sourceStorage->getUnjailedStorage(); } /** - * @var \OC\Files\Storage\Local $sourceStorage + * @var Local $sourceStorage */ $rootStorage = new Local(['datadir' => '/']); return $rootStorage->rename($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath)); diff --git a/lib/private/Files/Storage/LocalTempFileTrait.php b/lib/private/Files/Storage/LocalTempFileTrait.php index fffc3e789f3..5824189e3d8 100644 --- a/lib/private/Files/Storage/LocalTempFileTrait.php +++ b/lib/private/Files/Storage/LocalTempFileTrait.php @@ -8,6 +8,8 @@ namespace OC\Files\Storage; use OCP\Files; +use OCP\ITempManager; +use OCP\Server; /** * Storage backend class for providing common filesystem operation methods @@ -45,7 +47,7 @@ trait LocalTempFileTrait { } else { $extension = ''; } - $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension); + $tmpFile = Server::get(ITempManager::class)->getTemporaryFile($extension); $target = fopen($tmpFile, 'w'); Files::streamCopy($source, $target); fclose($target); diff --git a/lib/private/Files/Storage/PolyFill/CopyDirectory.php b/lib/private/Files/Storage/PolyFill/CopyDirectory.php index 2f6167ef85e..afb7334afd4 100644 --- a/lib/private/Files/Storage/PolyFill/CopyDirectory.php +++ b/lib/private/Files/Storage/PolyFill/CopyDirectory.php @@ -7,6 +7,8 @@ */ namespace OC\Files\Storage\PolyFill; +use OC\Files\Filesystem; + trait CopyDirectory { /** * Check if a path is a directory @@ -54,7 +56,7 @@ trait CopyDirectory { $dh = $this->opendir($source); $result = true; while (($file = readdir($dh)) !== false) { - if (!\OC\Files\Filesystem::isIgnoredDir($file)) { + if (!Filesystem::isIgnoredDir($file)) { if ($this->is_dir($source . '/' . $file)) { $this->mkdir($target . '/' . $file); $result = $this->copyRecursive($source . '/' . $file, $target . '/' . $file); diff --git a/lib/private/Files/Storage/StorageFactory.php b/lib/private/Files/Storage/StorageFactory.php index 603df7fe007..24efd3ecc1c 100644 --- a/lib/private/Files/Storage/StorageFactory.php +++ b/lib/private/Files/Storage/StorageFactory.php @@ -11,6 +11,7 @@ use OCP\Files\Mount\IMountPoint; use OCP\Files\Storage\IConstructableStorage; use OCP\Files\Storage\IStorage; use OCP\Files\Storage\IStorageFactory; +use OCP\Server; use Psr\Log\LoggerInterface; class StorageFactory implements IStorageFactory { @@ -48,7 +49,7 @@ class StorageFactory implements IStorageFactory { */ public function getInstance(IMountPoint $mountPoint, string $class, array $arguments): IStorage { if (!is_a($class, IConstructableStorage::class, true)) { - \OCP\Server::get(LoggerInterface::class)->warning('Building a storage not implementing IConstructableStorage is deprecated since 31.0.0', ['class' => $class]); + Server::get(LoggerInterface::class)->warning('Building a storage not implementing IConstructableStorage is deprecated since 31.0.0', ['class' => $class]); } return $this->wrap($mountPoint, new $class($arguments)); } diff --git a/lib/private/Files/Storage/Wrapper/Availability.php b/lib/private/Files/Storage/Wrapper/Availability.php index 9d184e6a660..7ae6bbe08be 100644 --- a/lib/private/Files/Storage/Wrapper/Availability.php +++ b/lib/private/Files/Storage/Wrapper/Availability.php @@ -11,6 +11,7 @@ use OCP\Files\Storage\IStorage; use OCP\Files\StorageAuthException; use OCP\Files\StorageNotAvailableException; use OCP\IConfig; +use OCP\Server; /** * Availability checker for storages @@ -25,7 +26,7 @@ class Availability extends Wrapper { protected ?bool $available = null; public function __construct(array $parameters) { - $this->config = $parameters['config'] ?? \OCP\Server::get(IConfig::class); + $this->config = $parameters['config'] ?? Server::get(IConfig::class); parent::__construct($parameters); } diff --git a/lib/private/Files/Storage/Wrapper/Encoding.php b/lib/private/Files/Storage/Wrapper/Encoding.php index 3e98be8e553..08a60a12791 100644 --- a/lib/private/Files/Storage/Wrapper/Encoding.php +++ b/lib/private/Files/Storage/Wrapper/Encoding.php @@ -9,6 +9,7 @@ namespace OC\Files\Storage\Wrapper; use OC\Files\Filesystem; use OCP\Cache\CappedMemoryCache; +use OCP\Files\Cache\ICache; use OCP\Files\Cache\IScanner; use OCP\Files\Storage\IStorage; @@ -226,7 +227,7 @@ class Encoding extends Wrapper { return $this->storage->hasUpdated($this->findPathToUse($path), $time); } - public function getCache(string $path = '', ?IStorage $storage = null): \OCP\Files\Cache\ICache { + public function getCache(string $path = '', ?IStorage $storage = null): ICache { if (!$storage) { $storage = $this; } diff --git a/lib/private/Files/Storage/Wrapper/Encryption.php b/lib/private/Files/Storage/Wrapper/Encryption.php index 380ec0f2530..9673ba9575a 100644 --- a/lib/private/Files/Storage/Wrapper/Encryption.php +++ b/lib/private/Files/Storage/Wrapper/Encryption.php @@ -18,6 +18,7 @@ use OC\Files\Storage\LocalTempFileTrait; use OC\Memcache\ArrayCache; use OCP\Cache\CappedMemoryCache; use OCP\Encryption\Exceptions\InvalidHeaderException; +use OCP\Encryption\IEncryptionModule; use OCP\Encryption\IFile; use OCP\Encryption\IManager; use OCP\Encryption\Keys\IStorage; @@ -840,7 +841,7 @@ class Encryption extends Wrapper { * @throws ModuleDoesNotExistsException * @throws \Exception */ - protected function getEncryptionModule(string $path): ?\OCP\Encryption\IEncryptionModule { + protected function getEncryptionModule(string $path): ?IEncryptionModule { $encryptionModule = null; $header = $this->getHeader($path); $encryptionModuleId = $this->util->getEncryptionModuleId($header); diff --git a/lib/private/Files/Storage/Wrapper/Jail.php b/lib/private/Files/Storage/Wrapper/Jail.php index 3ce6e6bb3b6..125f5469f92 100644 --- a/lib/private/Files/Storage/Wrapper/Jail.php +++ b/lib/private/Files/Storage/Wrapper/Jail.php @@ -17,7 +17,9 @@ use OCP\Files\Cache\IPropagator; use OCP\Files\Cache\IWatcher; use OCP\Files\Storage\IStorage; use OCP\Files\Storage\IWriteStreamStorage; +use OCP\IDBConnection; use OCP\Lock\ILockingProvider; +use OCP\Server; /** * Jail to a subdirectory of the wrapped storage @@ -245,7 +247,7 @@ class Jail extends Wrapper { if (!$storage) { $storage = $this; } - $this->propagator = new JailPropagator($storage, \OC::$server->getDatabaseConnection()); + $this->propagator = new JailPropagator($storage, Server::get(IDBConnection::class)); return $this->propagator; } diff --git a/lib/private/Files/Storage/Wrapper/PermissionsMask.php b/lib/private/Files/Storage/Wrapper/PermissionsMask.php index 692824d00bd..885fbb259e0 100644 --- a/lib/private/Files/Storage/Wrapper/PermissionsMask.php +++ b/lib/private/Files/Storage/Wrapper/PermissionsMask.php @@ -9,6 +9,8 @@ namespace OC\Files\Storage\Wrapper; use OC\Files\Cache\Wrapper\CachePermissionsMask; use OCP\Constants; +use OCP\Files\Cache\ICache; +use OCP\Files\Cache\IScanner; use OCP\Files\Storage\IStorage; /** @@ -102,7 +104,7 @@ class PermissionsMask extends Wrapper { } } - public function getCache(string $path = '', ?IStorage $storage = null): \OCP\Files\Cache\ICache { + public function getCache(string $path = '', ?IStorage $storage = null): ICache { if (!$storage) { $storage = $this; } @@ -120,7 +122,7 @@ class PermissionsMask extends Wrapper { return $data; } - public function getScanner(string $path = '', ?IStorage $storage = null): \OCP\Files\Cache\IScanner { + public function getScanner(string $path = '', ?IStorage $storage = null): IScanner { if (!$storage) { $storage = $this->storage; } diff --git a/lib/private/Files/Storage/Wrapper/Wrapper.php b/lib/private/Files/Storage/Wrapper/Wrapper.php index d5454050fcb..19fe9a6621e 100644 --- a/lib/private/Files/Storage/Wrapper/Wrapper.php +++ b/lib/private/Files/Storage/Wrapper/Wrapper.php @@ -23,9 +23,9 @@ use OCP\Server; use Override; use Psr\Log\LoggerInterface; -class Wrapper implements \OC\Files\Storage\Storage, ILockingStorage, IWriteStreamStorage { +class Wrapper implements Storage, ILockingStorage, IWriteStreamStorage { /** - * @var \OC\Files\Storage\Storage $storage + * @var Storage $storage */ protected $storage; diff --git a/lib/private/Files/Template/TemplateManager.php b/lib/private/Files/Template/TemplateManager.php index 73297869f12..8d33e7ebb17 100644 --- a/lib/private/Files/Template/TemplateManager.php +++ b/lib/private/Files/Template/TemplateManager.php @@ -11,14 +11,17 @@ namespace OC\Files\Template; use OC\AppFramework\Bootstrap\Coordinator; use OC\Files\Cache\Scanner; use OC\Files\Filesystem; +use OC\User\NoUserException; use OCA\Files\ResponseDefinitions; use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\File; use OCP\Files\Folder; use OCP\Files\GenericFileException; use OCP\Files\IFilenameValidator; +use OCP\Files\InvalidPathException; use OCP\Files\IRootFolder; use OCP\Files\NotFoundException; +use OCP\Files\NotPermittedException; use OCP\Files\Template\BeforeGetTemplatesEvent; use OCP\Files\Template\FileCreatedFromTemplateEvent; use OCP\Files\Template\ICustomTemplateProvider; @@ -177,9 +180,9 @@ class TemplateManager implements ITemplateManager { } /** - * @throws \OCP\Files\NotFoundException - * @throws \OCP\Files\NotPermittedException - * @throws \OC\User\NoUserException + * @throws NotFoundException + * @throws NotPermittedException + * @throws NoUserException */ private function getTemplateFolder(): Folder { if ($this->getTemplatePath() !== '') { @@ -275,7 +278,7 @@ class TemplateManager implements ITemplateManager { /** * @return FilesTemplateFile * @throws NotFoundException - * @throws \OCP\Files\InvalidPathException + * @throws InvalidPathException */ private function formatFile(File $file): array { return [ diff --git a/lib/private/Files/Type/Detection.php b/lib/private/Files/Type/Detection.php index 2fa2db71ddc..f056c5bdd58 100644 --- a/lib/private/Files/Type/Detection.php +++ b/lib/private/Files/Type/Detection.php @@ -12,6 +12,7 @@ use OCP\Files\IMimeTypeDetector; use OCP\IBinaryFinder; use OCP\ITempManager; use OCP\IURLGenerator; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -245,7 +246,7 @@ class Detection implements IMimeTypeDetector { } } - $binaryFinder = \OCP\Server::get(IBinaryFinder::class); + $binaryFinder = Server::get(IBinaryFinder::class); $program = $binaryFinder->findBinaryPath('file'); if ($program !== false) { // it looks like we have a 'file' command, @@ -298,7 +299,7 @@ class Detection implements IMimeTypeDetector { } } - $tmpFile = \OCP\Server::get(ITempManager::class)->getTemporaryFile(); + $tmpFile = Server::get(ITempManager::class)->getTemporaryFile(); $fh = fopen($tmpFile, 'wb'); fwrite($fh, $data, 8024); fclose($fh); diff --git a/lib/private/Files/Utils/Scanner.php b/lib/private/Files/Utils/Scanner.php index 576cb66b3cf..f78dd71fd24 100644 --- a/lib/private/Files/Utils/Scanner.php +++ b/lib/private/Files/Utils/Scanner.php @@ -9,6 +9,7 @@ namespace OC\Files\Utils; use OC\Files\Cache\Cache; use OC\Files\Filesystem; +use OC\Files\Mount\MountPoint; use OC\Files\Storage\FailedStorage; use OC\Files\Storage\Home; use OC\ForbiddenException; @@ -30,6 +31,7 @@ use OCP\Files\StorageNotAvailableException; use OCP\IDBConnection; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -44,17 +46,6 @@ use Psr\Log\LoggerInterface; class Scanner extends PublicEmitter { public const MAX_ENTRIES_TO_COMMIT = 10000; - /** @var string $user */ - private $user; - - /** @var IDBConnection */ - protected $db; - - /** @var IEventDispatcher */ - private $dispatcher; - - protected LoggerInterface $logger; - /** * Whether to use a DB transaction * @@ -74,13 +65,14 @@ class Scanner extends PublicEmitter { * @param IDBConnection|null $db * @param IEventDispatcher $dispatcher */ - public function __construct($user, $db, IEventDispatcher $dispatcher, LoggerInterface $logger) { - $this->user = $user; - $this->db = $db; - $this->dispatcher = $dispatcher; - $this->logger = $logger; + public function __construct( + private $user, + protected $db, + private IEventDispatcher $dispatcher, + protected LoggerInterface $logger, + ) { // when DB locking is used, no DB transactions will be used - $this->useTransaction = !(\OC::$server->get(ILockingProvider::class) instanceof DBLockingProvider); + $this->useTransaction = !(Server::get(ILockingProvider::class) instanceof DBLockingProvider); } /** @@ -106,28 +98,28 @@ class Scanner extends PublicEmitter { /** * attach listeners to the scanner * - * @param \OC\Files\Mount\MountPoint $mount + * @param MountPoint $mount */ protected function attachListener($mount) { /** @var \OC\Files\Cache\Scanner $scanner */ $scanner = $mount->getStorage()->getScanner(); - $scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function ($path) use ($mount) { + $scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function ($path) use ($mount): void { $this->emit('\OC\Files\Utils\Scanner', 'scanFile', [$mount->getMountPoint() . $path]); $this->dispatcher->dispatchTyped(new BeforeFileScannedEvent($mount->getMountPoint() . $path)); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function ($path) use ($mount) { + $scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function ($path) use ($mount): void { $this->emit('\OC\Files\Utils\Scanner', 'scanFolder', [$mount->getMountPoint() . $path]); $this->dispatcher->dispatchTyped(new BeforeFolderScannedEvent($mount->getMountPoint() . $path)); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFile', function ($path) use ($mount) { + $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFile', function ($path) use ($mount): void { $this->emit('\OC\Files\Utils\Scanner', 'postScanFile', [$mount->getMountPoint() . $path]); $this->dispatcher->dispatchTyped(new FileScannedEvent($mount->getMountPoint() . $path)); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFolder', function ($path) use ($mount) { + $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFolder', function ($path) use ($mount): void { $this->emit('\OC\Files\Utils\Scanner', 'postScanFolder', [$mount->getMountPoint() . $path]); $this->dispatcher->dispatchTyped(new FolderScannedEvent($mount->getMountPoint() . $path)); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'normalizedNameMismatch', function ($path) use ($mount) { + $scanner->listen('\OC\Files\Cache\Scanner', 'normalizedNameMismatch', function ($path) use ($mount): void { $this->emit('\OC\Files\Utils\Scanner', 'normalizedNameMismatch', [$path]); }); } @@ -153,13 +145,13 @@ class Scanner extends PublicEmitter { $scanner = $storage->getScanner(); $this->attachListener($mount); - $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) { + $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage): void { $this->triggerPropagator($storage, $path); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) { + $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage): void { $this->triggerPropagator($storage, $path); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) { + $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage): void { $this->triggerPropagator($storage, $path); }); @@ -234,15 +226,15 @@ class Scanner extends PublicEmitter { $scanner->setUseTransactions(false); $this->attachListener($mount); - $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) { + $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage): void { $this->postProcessEntry($storage, $path); $this->dispatcher->dispatchTyped(new NodeRemovedFromCache($storage, $path)); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) { + $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage): void { $this->postProcessEntry($storage, $path); $this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path)); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path, $storageId, $data, $fileId) use ($storage) { + $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path, $storageId, $data, $fileId) use ($storage): void { $this->postProcessEntry($storage, $path); if ($fileId) { $this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path)); diff --git a/lib/private/Files/View.php b/lib/private/Files/View.php index c0325d9aa28..71348c5321a 100644 --- a/lib/private/Files/View.php +++ b/lib/private/Files/View.php @@ -9,13 +9,17 @@ namespace OC\Files; use Icewind\Streams\CallbackWrapper; use OC\Files\Cache\CacheEntry; +use OC\Files\Cache\Scanner; +use OC\Files\Mount\MountPoint; use OC\Files\Mount\MoveableMount; use OC\Files\Storage\Storage; use OC\Files\Storage\Wrapper\Quota; use OC\Files\Utils\PathHelper; +use OC\Lock\NoopLockingProvider; use OC\Share\Share; use OC\User\LazyUser; use OC\User\Manager as UserManager; +use OC\User\NoUserException; use OC\User\User; use OCA\Files_Sharing\SharedMount; use OCP\Constants; @@ -28,12 +32,16 @@ use OCP\Files\ForbiddenException; use OCP\Files\InvalidCharacterInPathException; use OCP\Files\InvalidDirectoryException; use OCP\Files\InvalidPathException; +use OCP\Files\IRootFolder; use OCP\Files\Mount\IMountManager; use OCP\Files\Mount\IMountPoint; use OCP\Files\NotFoundException; use OCP\Files\ReservedWordException; +use OCP\Files\Storage\IStorage; use OCP\Files\StorageInvalidException; use OCP\Files\StorageNotAvailableException; +use OCP\Files\UnseekableException; +use OCP\ITempManager; use OCP\IUser; use OCP\IUserManager; use OCP\L10N\IFactory; @@ -42,6 +50,7 @@ use OCP\Lock\LockedException; use OCP\Server; use OCP\Share\IManager; use OCP\Share\IShare; +use OCP\Util; use Psr\Log\LoggerInterface; /** @@ -79,10 +88,10 @@ class View { } $this->fakeRoot = $root; - $this->lockingProvider = \OC::$server->get(ILockingProvider::class); - $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider); - $this->userManager = \OC::$server->getUserManager(); - $this->logger = \OC::$server->get(LoggerInterface::class); + $this->lockingProvider = Server::get(ILockingProvider::class); + $this->lockingEnabled = !($this->lockingProvider instanceof NoopLockingProvider); + $this->userManager = Server::get(IUserManager::class); + $this->logger = Server::get(LoggerInterface::class); } /** @@ -178,7 +187,7 @@ class View { * Resolve a path to a storage and internal path * * @param string $path - * @return array{?\OCP\Files\Storage\IStorage, string} an array consisting of the storage and the internal path + * @return array{?IStorage, string} an array consisting of the storage and the internal path */ public function resolvePath($path): array { $a = $this->getAbsolutePath($path); @@ -391,7 +400,7 @@ class View { * @param int $to * @return bool|mixed * @throws InvalidPathException - * @throws \OCP\Files\UnseekableException + * @throws UnseekableException */ public function readfilePart($path, $from, $to) { $this->assertPathLength($path); @@ -435,7 +444,7 @@ class View { return ftell($handle) - $from; } - throw new \OCP\Files\UnseekableException('fseek error'); + throw new UnseekableException('fseek error'); } return false; } @@ -715,7 +724,7 @@ class View { } /** @var IMountManager $mountManager */ - $mountManager = \OC::$server->get(IMountManager::class); + $mountManager = Server::get(IMountManager::class); $targetParts = explode('/', $absolutePath2); $targetUser = $targetParts[1] ?? null; @@ -744,7 +753,7 @@ class View { $this->lockFile($target, ILockingProvider::LOCK_SHARED, true); $run = true; - if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) { + if ($this->shouldEmitHooks($source) && (Scanner::isPartialFile($source) && !Scanner::isPartialFile($target))) { // if it was a rename from a part file to a regular file it was a write and not a rename operation $this->emit_file_hooks_pre($exists, $target, $run); } elseif ($this->shouldEmitHooks($source)) { @@ -785,7 +794,7 @@ class View { $movedMounts[] = $mount1; $this->validateMountMove($movedMounts, $sourceParentMount, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2)); /** - * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1 + * @var MountPoint|MoveableMount $mount1 */ $sourceMountPoint = $mount1->getMountPoint(); $result = $mount1->moveMount($absolutePath2); @@ -809,7 +818,7 @@ class View { $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2); } - if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) { + if ((Scanner::isPartialFile($source) && !Scanner::isPartialFile($target)) && $result !== false) { // if it was a rename from a part file to a regular file it was a write and not a rename operation $this->writeUpdate($storage2, $internalPath2); } elseif ($result) { @@ -824,7 +833,7 @@ class View { $this->changeLock($target, ILockingProvider::LOCK_SHARED, true); } - if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) { + if ((Scanner::isPartialFile($source) && !Scanner::isPartialFile($target)) && $result !== false) { if ($this->shouldEmitHooks()) { $this->emit_file_hooks_post($exists, $target); } @@ -866,7 +875,7 @@ class View { $targetPath = $targetMount->getMountPoint(); } - $l = \OC::$server->get(IFactory::class)->get('files'); + $l = Server::get(IFactory::class)->get('files'); foreach ($mounts as $mount) { $sourcePath = $this->getRelativePath($mount->getMountPoint()); if ($sourcePath) { @@ -1058,7 +1067,7 @@ class View { $source = $this->fopen($path, 'r'); if ($source) { $extension = pathinfo($path, PATHINFO_EXTENSION); - $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension); + $tmpFile = Server::get(ITempManager::class)->getTemporaryFile($extension); file_put_contents($tmpFile, $source); return $tmpFile; } else { @@ -1241,7 +1250,7 @@ class View { $unlockLater = true; // make sure our unlocking callback will still be called if connection is aborted ignore_user_abort(true); - $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) { + $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path): void { if (in_array('write', $hooks)) { $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE); } elseif (in_array('read', $hooks)) { @@ -1284,7 +1293,7 @@ class View { } private function shouldEmitHooks(string $path = ''): bool { - if ($path && Cache\Scanner::isPartialFile($path)) { + if ($path && Scanner::isPartialFile($path)) { return false; } if (!Filesystem::$loaded) { @@ -1381,9 +1390,9 @@ class View { } // don't need to get a lock here since the scanner does it's own locking $scanner = $storage->getScanner($internalPath); - $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW); + $scanner->scan($internalPath, Scanner::SCAN_SHALLOW); $data = $cache->get($internalPath); - } elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) { + } elseif (!Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) { $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED); $watcher->update($internalPath, $data); $storage->getPropagator()->propagateChange($internalPath, time()); @@ -1403,7 +1412,7 @@ class View { * @param string $path * @param bool|string $includeMountPoints true to add mountpoint sizes, * 'ext' to add only ext storage mount point sizes. Defaults to true. - * @return \OC\Files\FileInfo|false False if file does not exist + * @return FileInfo|false False if file does not exist */ public function getFileInfo($path, $includeMountPoints = true) { $this->assertPathLength($path); @@ -1420,7 +1429,7 @@ class View { $data = $this->getCacheEntry($storage, $internalPath, $relativePath); if (!$data instanceof ICacheEntry) { - if (Cache\Scanner::isPartialFile($relativePath)) { + if (Scanner::isPartialFile($relativePath)) { return $this->getPartFileInfo($relativePath); } @@ -1428,7 +1437,7 @@ class View { } if ($mount instanceof MoveableMount && $internalPath === '') { - $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE; + $data['permissions'] |= Constants::PERMISSION_DELETE; } if ($internalPath === '' && $data['name']) { $data['name'] = basename($path); @@ -1609,16 +1618,16 @@ class View { // do not allow renaming/deleting the mount point if they are not shared files/folders // for shared files/folders we use the permissions given by the owner if ($mount instanceof MoveableMount) { - $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE; + $rootEntry['permissions'] = $permissions | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE; } else { - $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE)); + $rootEntry['permissions'] = $permissions & (Constants::PERMISSION_ALL - (Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE)); } $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/ // if sharing was disabled for the user we remove the share permissions if ($sharingDisabled) { - $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE; + $rootEntry['permissions'] = $rootEntry['permissions'] & ~Constants::PERMISSION_SHARE; } $ownerId = $subStorage->getOwner(''); @@ -1674,7 +1683,7 @@ class View { if (!$cache->inCache($internalPath)) { $scanner = $storage->getScanner($internalPath); - $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW); + $scanner->scan($internalPath, Scanner::SCAN_SHALLOW); } return $cache->put($internalPath, $data); @@ -1736,7 +1745,7 @@ class View { $mount = $this->getMount(''); $mountPoint = $mount->getMountPoint(); $storage = $mount->getStorage(); - $userManager = \OC::$server->getUserManager(); + $userManager = Server::get(IUserManager::class); if ($storage) { $cache = $storage->getCache(''); @@ -1830,7 +1839,7 @@ class View { */ public function getPath($id, ?int $storageId = null): string { $id = (int)$id; - $rootFolder = Server::get(Files\IRootFolder::class); + $rootFolder = Server::get(IRootFolder::class); $node = $rootFolder->getFirstNodeByIdInPath($id, $this->getRoot()); if ($node) { @@ -1908,7 +1917,7 @@ class View { /** * Get a fileinfo object for files that are ignored in the cache (part files) */ - private function getPartFileInfo(string $path): \OC\Files\FileInfo { + private function getPartFileInfo(string $path): FileInfo { $mount = $this->getMount($path); $storage = $mount->getStorage(); $internalPath = $mount->getInternalPath($this->getAbsolutePath($path)); @@ -1930,7 +1939,7 @@ class View { 'size' => $storage->filesize($internalPath), 'mtime' => $storage->filemtime($internalPath), 'encrypted' => false, - 'permissions' => \OCP\Constants::PERMISSION_ALL + 'permissions' => Constants::PERMISSION_ALL ], $mount, $owner @@ -1946,7 +1955,7 @@ class View { public function verifyPath($path, $fileName, $readonly = false): void { // All of the view's functions disallow '..' in the path so we can short cut if the path is invalid if (!Filesystem::isValidPath($path ?: '/')) { - $l = \OCP\Util::getL10N('lib'); + $l = Util::getL10N('lib'); throw new InvalidPathException($l->t('Path contains invalid segments')); } @@ -1954,7 +1963,7 @@ class View { if ($readonly) { $validator = Server::get(FilenameValidator::class); if ($validator->isForbidden($fileName)) { - $l = \OCP\Util::getL10N('lib'); + $l = Util::getL10N('lib'); throw new InvalidPathException($l->t('Filename is a reserved word')); } return; @@ -1965,19 +1974,19 @@ class View { [$storage, $internalPath] = $this->resolvePath($path); $storage->verifyPath($internalPath, $fileName); } catch (ReservedWordException $ex) { - $l = \OCP\Util::getL10N('lib'); + $l = Util::getL10N('lib'); throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename is a reserved word')); } catch (InvalidCharacterInPathException $ex) { - $l = \OCP\Util::getL10N('lib'); + $l = Util::getL10N('lib'); throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename contains at least one invalid character')); } catch (FileNameTooLongException $ex) { - $l = \OCP\Util::getL10N('lib'); + $l = Util::getL10N('lib'); throw new InvalidPathException($l->t('Filename is too long')); } catch (InvalidDirectoryException $ex) { - $l = \OCP\Util::getL10N('lib'); + $l = Util::getL10N('lib'); throw new InvalidPathException($l->t('Dot files are not allowed')); } catch (EmptyFileNameException $ex) { - $l = \OCP\Util::getL10N('lib'); + $l = Util::getL10N('lib'); throw new InvalidPathException($l->t('Empty filename is not allowed')); } } @@ -2247,7 +2256,7 @@ class View { /** * @param string $filename * @return array - * @throws \OC\User\NoUserException + * @throws NoUserException * @throws NotFoundException */ public function getUidAndFilename($filename) { diff --git a/lib/private/FullTextSearch/Model/IndexDocument.php b/lib/private/FullTextSearch/Model/IndexDocument.php index a51447393ed..2a46c7bee57 100644 --- a/lib/private/FullTextSearch/Model/IndexDocument.php +++ b/lib/private/FullTextSearch/Model/IndexDocument.php @@ -30,8 +30,6 @@ use OCP\FullTextSearch\Model\IIndexDocument; * @package OC\FullTextSearch\Model */ class IndexDocument implements IIndexDocument, JsonSerializable { - protected string $id = ''; - protected DocumentAccess $access; protected ?IIndex $index = null; @@ -77,9 +75,8 @@ class IndexDocument implements IIndexDocument, JsonSerializable { */ public function __construct( protected string $providerId, - string $documentId, + protected string $id, ) { - $this->id = $documentId; } diff --git a/lib/private/GlobalScale/Config.php b/lib/private/GlobalScale/Config.php index 2f729c2702e..216efc4a834 100644 --- a/lib/private/GlobalScale/Config.php +++ b/lib/private/GlobalScale/Config.php @@ -9,16 +9,14 @@ namespace OC\GlobalScale; use OCP\IConfig; class Config implements \OCP\GlobalScale\IConfig { - /** @var IConfig */ - private $config; - /** * Config constructor. * * @param IConfig $config */ - public function __construct(IConfig $config) { - $this->config = $config; + public function __construct( + private IConfig $config, + ) { } /** diff --git a/lib/private/Group/Backend.php b/lib/private/Group/Backend.php index f4a90018b5a..011ff986143 100644 --- a/lib/private/Group/Backend.php +++ b/lib/private/Group/Backend.php @@ -7,10 +7,12 @@ */ namespace OC\Group; +use OCP\GroupInterface; + /** * Abstract base class for user management */ -abstract class Backend implements \OCP\GroupInterface { +abstract class Backend implements GroupInterface { /** * error code for functions not provided by the group backend */ diff --git a/lib/private/Group/Database.php b/lib/private/Group/Database.php index 62a3990c319..190eb37348b 100644 --- a/lib/private/Group/Database.php +++ b/lib/private/Group/Database.php @@ -25,6 +25,7 @@ use OCP\Group\Backend\ISearchableGroupBackend; use OCP\Group\Backend\ISetDisplayNameBackend; use OCP\IDBConnection; use OCP\IUserManager; +use OCP\Server; /** * Class for group management in a SQL Database (e.g. MySQL, SQLite) @@ -60,7 +61,7 @@ class Database extends ABackend implements */ private function fixDI() { if ($this->dbConn === null) { - $this->dbConn = \OC::$server->getDatabaseConnection(); + $this->dbConn = Server::get(IDBConnection::class); } } @@ -411,7 +412,7 @@ class Database extends ABackend implements $result = $query->executeQuery(); $users = []; - $userManager = \OCP\Server::get(IUserManager::class); + $userManager = Server::get(IUserManager::class); while ($row = $result->fetch()) { $users[$row['uid']] = new LazyUser($row['uid'], $userManager, $row['displayname'] ?? null); } diff --git a/lib/private/Group/DisplayNameCache.php b/lib/private/Group/DisplayNameCache.php index fef8d40a05f..8108b359726 100644 --- a/lib/private/Group/DisplayNameCache.php +++ b/lib/private/Group/DisplayNameCache.php @@ -25,12 +25,13 @@ use OCP\IGroupManager; class DisplayNameCache implements IEventListener { private CappedMemoryCache $cache; private ICache $memCache; - private IGroupManager $groupManager; - public function __construct(ICacheFactory $cacheFactory, IGroupManager $groupManager) { + public function __construct( + ICacheFactory $cacheFactory, + private IGroupManager $groupManager, + ) { $this->cache = new CappedMemoryCache(); $this->memCache = $cacheFactory->createDistributed('groupDisplayNameMappingCache'); - $this->groupManager = $groupManager; } public function getDisplayName(string $groupId): ?string { diff --git a/lib/private/Group/Group.php b/lib/private/Group/Group.php index a6bb192390f..5d386b805ad 100644 --- a/lib/private/Group/Group.php +++ b/lib/private/Group/Group.php @@ -9,11 +9,16 @@ namespace OC\Group; use OC\Hooks\PublicEmitter; use OC\User\LazyUser; +use OC\User\User; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Group\Backend\IAddToGroupBackend; use OCP\Group\Backend\ICountDisabledInGroup; +use OCP\Group\Backend\ICountUsersBackend; +use OCP\Group\Backend\IDeleteGroupBackend; use OCP\Group\Backend\IGetDisplayNameBackend; use OCP\Group\Backend\IHideFromCollaborationBackend; use OCP\Group\Backend\INamedBackend; +use OCP\Group\Backend\IRemoveFromGroupBackend; use OCP\Group\Backend\ISearchableGroupBackend; use OCP\Group\Backend\ISetDisplayNameBackend; use OCP\Group\Events\BeforeGroupChangedEvent; @@ -28,36 +33,24 @@ use OCP\GroupInterface; use OCP\IGroup; use OCP\IUser; use OCP\IUserManager; +use OCP\Server; class Group implements IGroup { - /** @var null|string */ - protected $displayName; - - /** @var string */ - private $gid; - - /** @var \OC\User\User[] */ + /** @var User[] */ private $users = []; /** @var bool */ private $usersLoaded; - /** @var Backend[] */ - private $backends; - /** @var IEventDispatcher */ - private $dispatcher; - /** @var \OC\User\Manager|IUserManager */ - private $userManager; - /** @var PublicEmitter */ - private $emitter; - - public function __construct(string $gid, array $backends, IEventDispatcher $dispatcher, IUserManager $userManager, ?PublicEmitter $emitter = null, ?string $displayName = null) { - $this->gid = $gid; - $this->backends = $backends; - $this->dispatcher = $dispatcher; - $this->userManager = $userManager; - $this->emitter = $emitter; - $this->displayName = $displayName; + public function __construct( + private string $gid, + /** @var list */ + private array $backends, + private IEventDispatcher $dispatcher, + private IUserManager $userManager, + private ?PublicEmitter $emitter = null, + protected ?string $displayName = null, + ) { } public function getGID(): string { @@ -99,7 +92,7 @@ class Group implements IGroup { /** * get all users in the group * - * @return \OC\User\User[] + * @return array */ public function getUsers(): array { if ($this->usersLoaded) { @@ -158,6 +151,7 @@ class Group implements IGroup { } foreach ($this->backends as $backend) { if ($backend->implementsActions(\OC\Group\Backend::ADD_TO_GROUP)) { + /** @var IAddToGroupBackend $backend */ $backend->addToGroup($user->getUID(), $this->gid); $this->users[$user->getUID()] = $user; @@ -182,6 +176,7 @@ class Group implements IGroup { } foreach ($this->backends as $backend) { if ($backend->implementsActions(\OC\Group\Backend::REMOVE_FROM_GOUP) && $backend->inGroup($user->getUID(), $this->gid)) { + /** @var IRemoveFromGroupBackend $backend */ $backend->removeFromGroup($user->getUID(), $this->gid); $result = true; } @@ -213,7 +208,7 @@ class Group implements IGroup { $users += $backend->searchInGroup($this->gid, $search, $limit ?? -1, $offset ?? 0); } else { $userIds = $backend->usersInGroup($this->gid, $search, $limit ?? -1, $offset ?? 0); - $userManager = \OCP\Server::get(IUserManager::class); + $userManager = Server::get(IUserManager::class); foreach ($userIds as $userId) { if (!isset($users[$userId])) { $users[$userId] = new LazyUser($userId, $userManager); @@ -237,6 +232,7 @@ class Group implements IGroup { $users = false; foreach ($this->backends as $backend) { if ($backend->implementsActions(\OC\Group\Backend::COUNT_USERS)) { + /** @var ICountUsersBackend $backend */ if ($users === false) { //we could directly add to a bool variable, but this would //be ugly @@ -317,6 +313,7 @@ class Group implements IGroup { } foreach ($this->backends as $backend) { if ($backend->implementsActions(\OC\Group\Backend::DELETE_GROUP)) { + /** @var IDeleteGroupBackend $backend */ $result = $result || $backend->deleteGroup($this->gid); } } @@ -332,7 +329,7 @@ class Group implements IGroup { /** * returns all the Users from an array that really exists * @param string[] $userIds an array containing user IDs - * @return \OC\User\User[] an Array with the userId as Key and \OC\User\User as value + * @return array an Array with the userId as Key and \OC\User\User as value */ private function getVerifiedUsers(array $userIds): array { $users = []; diff --git a/lib/private/Group/Manager.php b/lib/private/Group/Manager.php index f4bbeea3d69..e3279f72b87 100644 --- a/lib/private/Group/Manager.php +++ b/lib/private/Group/Manager.php @@ -9,6 +9,8 @@ namespace OC\Group; use OC\Hooks\PublicEmitter; use OC\Settings\AuthorizedGroupMapper; +use OC\SubAdmin; +use OCA\Settings\Settings\Admin\Users; use OCP\EventDispatcher\IEventDispatcher; use OCP\Group\Backend\IBatchMethodsBackend; use OCP\Group\Backend\ICreateNamedGroupBackend; @@ -17,10 +19,12 @@ use OCP\Group\Events\BeforeGroupCreatedEvent; use OCP\Group\Events\GroupCreatedEvent; use OCP\GroupInterface; use OCP\ICacheFactory; +use OCP\IDBConnection; use OCP\IGroup; use OCP\IGroupManager; use OCP\IUser; use OCP\Security\Ip\IRemoteAddress; +use OCP\Server; use Psr\Log\LoggerInterface; use function is_string; @@ -49,7 +53,7 @@ class Manager extends PublicEmitter implements IGroupManager { /** @var array> */ private $cachedUserGroups = []; - /** @var \OC\SubAdmin */ + /** @var SubAdmin */ private $subAdmin = null; private DisplayNameCache $displayNameCache; @@ -96,7 +100,7 @@ class Manager extends PublicEmitter implements IGroupManager { } /** - * @param \OCP\GroupInterface $backend + * @param GroupInterface $backend */ public function addBackend($backend) { $this->backends[] = $backend; @@ -111,7 +115,7 @@ class Manager extends PublicEmitter implements IGroupManager { /** * Get the active backends * - * @return \OCP\GroupInterface[] + * @return GroupInterface[] */ public function getBackends() { return $this->backends; @@ -137,7 +141,7 @@ class Manager extends PublicEmitter implements IGroupManager { /** * @param string $gid * @param string $displayName - * @return \OCP\IGroup|null + * @return IGroup|null */ protected function getGroupObject($gid, $displayName = null) { $backends = []; @@ -181,7 +185,7 @@ class Manager extends PublicEmitter implements IGroupManager { } foreach ($this->backends as $backend) { if ($backend instanceof IGroupDetailsBackend || $backend->implementsActions(GroupInterface::GROUP_DETAILS)) { - /** @var IGroupDetailsBackend $backend */ + /** @var GroupInterface&IGroupDetailsBackend $backend */ if ($backend instanceof IBatchMethodsBackend) { $groupDatas = $backend->getGroupsDetails($gids); } else { @@ -281,9 +285,9 @@ class Manager extends PublicEmitter implements IGroupManager { /** * @param IUser|null $user - * @return \OC\Group\Group[] + * @return array */ - public function getUserGroups(?IUser $user = null) { + public function getUserGroups(?IUser $user = null): array { if (!$user instanceof IUser) { return []; } @@ -292,7 +296,7 @@ class Manager extends PublicEmitter implements IGroupManager { /** * @param string $uid the user id - * @return \OC\Group\Group[] + * @return array */ public function getUserIdGroups(string $uid): array { $groups = []; @@ -334,10 +338,10 @@ class Manager extends PublicEmitter implements IGroupManager { } // Check if the user as admin delegation for users listing - $authorizedGroupMapper = \OCP\Server::get(AuthorizedGroupMapper::class); + $authorizedGroupMapper = Server::get(AuthorizedGroupMapper::class); $user = $this->userManager->get($userId); $authorizedClasses = $authorizedGroupMapper->findAllClassesForUser($user); - return in_array(\OCA\Settings\Settings\Admin\Users::class, $authorizedClasses, true); + return in_array(Users::class, $authorizedClasses, true); } /** @@ -446,14 +450,14 @@ class Manager extends PublicEmitter implements IGroupManager { } /** - * @return \OC\SubAdmin + * @return SubAdmin */ public function getSubAdmin() { if (!$this->subAdmin) { - $this->subAdmin = new \OC\SubAdmin( + $this->subAdmin = new SubAdmin( $this->userManager, $this, - \OC::$server->getDatabaseConnection(), + Server::get(IDBConnection::class), $this->dispatcher ); } diff --git a/lib/private/Http/Client/Client.php b/lib/private/Http/Client/Client.php index 9b3b34b99d1..6160e68a99c 100644 --- a/lib/private/Http/Client/Client.php +++ b/lib/private/Http/Client/Client.php @@ -28,26 +28,14 @@ use function parse_url; * @package OC\Http */ class Client implements IClient { - /** @var GuzzleClient */ - private $client; - /** @var IConfig */ - private $config; - /** @var ICertificateManager */ - private $certificateManager; - private IRemoteHostValidator $remoteHostValidator; - public function __construct( - IConfig $config, - ICertificateManager $certificateManager, - GuzzleClient $client, - IRemoteHostValidator $remoteHostValidator, + private IConfig $config, + private ICertificateManager $certificateManager, + private GuzzleClient $client, + private IRemoteHostValidator $remoteHostValidator, protected LoggerInterface $logger, protected ServerVersion $serverVersion, ) { - $this->config = $config; - $this->client = $client; - $this->certificateManager = $certificateManager; - $this->remoteHostValidator = $remoteHostValidator; } private function buildRequestOptions(array $options): array { @@ -67,7 +55,7 @@ class Client implements IClient { \Psr\Http\Message\RequestInterface $request, \Psr\Http\Message\ResponseInterface $response, \Psr\Http\Message\UriInterface $uri, - ) use ($options) { + ) use ($options): void { $this->preventLocalAddress($uri->__toString(), $options); }; diff --git a/lib/private/Http/Client/ClientService.php b/lib/private/Http/Client/ClientService.php index a505dff9aa2..e133c987985 100644 --- a/lib/private/Http/Client/ClientService.php +++ b/lib/private/Http/Client/ClientService.php @@ -28,29 +28,15 @@ use Psr\Log\LoggerInterface; * @package OC\Http */ class ClientService implements IClientService { - /** @var IConfig */ - private $config; - /** @var ICertificateManager */ - private $certificateManager; - /** @var DnsPinMiddleware */ - private $dnsPinMiddleware; - private IRemoteHostValidator $remoteHostValidator; - private IEventLogger $eventLogger; - public function __construct( - IConfig $config, - ICertificateManager $certificateManager, - DnsPinMiddleware $dnsPinMiddleware, - IRemoteHostValidator $remoteHostValidator, - IEventLogger $eventLogger, + private IConfig $config, + private ICertificateManager $certificateManager, + private DnsPinMiddleware $dnsPinMiddleware, + private IRemoteHostValidator $remoteHostValidator, + private IEventLogger $eventLogger, protected LoggerInterface $logger, protected ServerVersion $serverVersion, ) { - $this->config = $config; - $this->certificateManager = $certificateManager; - $this->dnsPinMiddleware = $dnsPinMiddleware; - $this->remoteHostValidator = $remoteHostValidator; - $this->eventLogger = $eventLogger; } /** @@ -62,9 +48,9 @@ class ClientService implements IClientService { if ($this->config->getSystemValueBool('dns_pinning', true)) { $stack->push($this->dnsPinMiddleware->addDnsPinning()); } - $stack->push(Middleware::tap(function (RequestInterface $request) { + $stack->push(Middleware::tap(function (RequestInterface $request): void { $this->eventLogger->start('http:request', $request->getMethod() . ' request to ' . $request->getRequestTarget()); - }, function () { + }, function (): void { $this->eventLogger->end('http:request'); }), 'event logger'); diff --git a/lib/private/Http/Client/GuzzlePromiseAdapter.php b/lib/private/Http/Client/GuzzlePromiseAdapter.php index 03a9ed9a599..7d1e1e19112 100644 --- a/lib/private/Http/Client/GuzzlePromiseAdapter.php +++ b/lib/private/Http/Client/GuzzlePromiseAdapter.php @@ -46,7 +46,7 @@ class GuzzlePromiseAdapter implements IPromise { ?callable $onRejected = null, ): IPromise { if ($onFulfilled !== null) { - $wrappedOnFulfilled = static function (ResponseInterface $response) use ($onFulfilled) { + $wrappedOnFulfilled = static function (ResponseInterface $response) use ($onFulfilled): void { $onFulfilled(new Response($response)); }; } else { @@ -54,7 +54,7 @@ class GuzzlePromiseAdapter implements IPromise { } if ($onRejected !== null) { - $wrappedOnRejected = static function (RequestException $e) use ($onRejected) { + $wrappedOnRejected = static function (RequestException $e) use ($onRejected): void { $onRejected($e); }; } else { diff --git a/lib/private/Http/Client/Response.php b/lib/private/Http/Client/Response.php index 1e4cb3b8fa2..57d0a88d95e 100644 --- a/lib/private/Http/Client/Response.php +++ b/lib/private/Http/Client/Response.php @@ -13,11 +13,12 @@ use Psr\Http\Message\ResponseInterface; class Response implements IResponse { private ResponseInterface $response; - private bool $stream; - public function __construct(ResponseInterface $response, bool $stream = false) { + public function __construct( + ResponseInterface $response, + private bool $stream = false, + ) { $this->response = $response; - $this->stream = $stream; } public function getBody() { diff --git a/lib/private/Http/WellKnown/RequestManager.php b/lib/private/Http/WellKnown/RequestManager.php index 3624bf73962..11d5d388f35 100644 --- a/lib/private/Http/WellKnown/RequestManager.php +++ b/lib/private/Http/WellKnown/RequestManager.php @@ -22,31 +22,19 @@ use RuntimeException; use function array_reduce; class RequestManager { - /** @var Coordinator */ - private $coordinator; - - /** @var IServerContainer */ - private $container; - - /** @var LoggerInterface */ - private $logger; - - public function __construct(Coordinator $coordinator, - IServerContainer $container, - LoggerInterface $logger) { - $this->coordinator = $coordinator; - $this->container = $container; - $this->logger = $logger; + public function __construct( + private Coordinator $coordinator, + private IServerContainer $container, + private LoggerInterface $logger, + ) { } public function process(string $service, IRequest $request): ?IResponse { $handlers = $this->loadHandlers(); $context = new class($request) implements IRequestContext { - /** @var IRequest */ - private $request; - - public function __construct(IRequest $request) { - $this->request = $request; + public function __construct( + private IRequest $request, + ) { } public function getHttpRequest(): IRequest { diff --git a/lib/private/Installer.php b/lib/private/Installer.php index 40a91287e3a..897acd02cb9 100644 --- a/lib/private/Installer.php +++ b/lib/private/Installer.php @@ -29,6 +29,7 @@ use OCP\ITempManager; use OCP\L10N\IFactory; use OCP\Migration\IOutput; use OCP\Server; +use OCP\Util; use phpseclib\File\X509; use Psr\Log\LoggerInterface; @@ -76,7 +77,7 @@ class Installer { $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []); $ignoreMax = $forceEnable || in_array($appId, $ignoreMaxApps, true); - $version = implode('.', \OCP\Util::getVersion()); + $version = implode('.', Util::getVersion()); if (!$this->appManager->isAppCompatible($version, $info, $ignoreMax)) { throw new \Exception( $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.', diff --git a/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php b/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php index f6d4c7afd4a..1d44ed2ebc0 100644 --- a/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php +++ b/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php @@ -8,6 +8,9 @@ declare(strict_types=1); */ namespace OC\IntegrityCheck\Iterator; +use OCP\IConfig; +use OCP\Server; + class ExcludeFoldersByPathFilterIterator extends \RecursiveFilterIterator { private $excludedFolders; @@ -32,7 +35,7 @@ class ExcludeFoldersByPathFilterIterator extends \RecursiveFilterIterator { rtrim($root . '/updater', '/'), rtrim($root . '/_oc_upgrade', '/'), ]; - $customDataDir = \OC::$server->getConfig()->getSystemValueString('datadirectory', ''); + $customDataDir = Server::get(IConfig::class)->getSystemValueString('datadirectory', ''); if ($customDataDir !== '') { $excludedFolders[] = rtrim($customDataDir, '/'); } diff --git a/lib/private/KnownUser/KnownUserService.php b/lib/private/KnownUser/KnownUserService.php index cd257cf1b12..5efe836e125 100644 --- a/lib/private/KnownUser/KnownUserService.php +++ b/lib/private/KnownUser/KnownUserService.php @@ -9,13 +9,12 @@ declare(strict_types=1); namespace OC\KnownUser; class KnownUserService { - /** @var KnownUserMapper */ - protected $mapper; /** @var array */ protected $knownUsers = []; - public function __construct(KnownUserMapper $mapper) { - $this->mapper = $mapper; + public function __construct( + protected KnownUserMapper $mapper, + ) { } /** diff --git a/lib/private/L10N/Factory.php b/lib/private/L10N/Factory.php index abe392335f5..75a9ee91264 100644 --- a/lib/private/L10N/Factory.php +++ b/lib/private/L10N/Factory.php @@ -13,6 +13,7 @@ use OCP\App\IAppManager; use OCP\ICache; use OCP\ICacheFactory; use OCP\IConfig; +use OCP\IL10N; use OCP\IRequest; use OCP\IUser; use OCP\IUserSession; @@ -89,7 +90,7 @@ class Factory implements IFactory { * @param string $app * @param string|null $lang * @param string|null $locale - * @return \OCP\IL10N + * @return IL10N */ public function get($app, $lang = null, $locale = null) { return new LazyL10N(function () use ($app, $lang, $locale) { diff --git a/lib/private/L10N/L10N.php b/lib/private/L10N/L10N.php index 16bdf884993..bf8ee9a190c 100644 --- a/lib/private/L10N/L10N.php +++ b/lib/private/L10N/L10N.php @@ -10,23 +10,12 @@ namespace OC\L10N; use OCP\IL10N; use OCP\L10N\IFactory; +use OCP\Server; use Psr\Log\LoggerInterface; use Punic\Calendar; use Symfony\Component\Translation\IdentityTranslator; class L10N implements IL10N { - /** @var IFactory */ - protected $factory; - - /** @var string App of this object */ - protected $app; - - /** @var string Language of this object */ - protected $lang; - - /** @var string Locale of this object */ - protected $locale; - /** @var IdentityTranslator */ private $identityTranslator; @@ -40,12 +29,13 @@ class L10N implements IL10N { * @param string $locale * @param array $files */ - public function __construct(IFactory $factory, $app, $lang, $locale, array $files) { - $this->factory = $factory; - $this->app = $app; - $this->lang = $lang; - $this->locale = $locale; - + public function __construct( + protected IFactory $factory, + protected $app, + protected $lang, + protected $locale, + array $files, + ) { foreach ($files as $languageFile) { $this->load($languageFile); } @@ -215,7 +205,7 @@ class L10N implements IL10N { $json = json_decode(file_get_contents($translationFile), true); if (!\is_array($json)) { $jsonError = json_last_error(); - \OCP\Server::get(LoggerInterface::class)->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']); + Server::get(LoggerInterface::class)->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']); return false; } diff --git a/lib/private/L10N/L10NString.php b/lib/private/L10N/L10NString.php index a6515e78f24..1fdb9eca7e5 100644 --- a/lib/private/L10N/L10NString.php +++ b/lib/private/L10N/L10NString.php @@ -8,29 +8,18 @@ namespace OC\L10N; class L10NString implements \JsonSerializable { - /** @var L10N */ - protected $l10n; - - /** @var string */ - protected $text; - - /** @var array */ - protected $parameters; - - /** @var integer */ - protected $count; - /** * @param L10N $l10n * @param string|string[] $text * @param array $parameters * @param int $count */ - public function __construct(L10N $l10n, $text, array $parameters, int $count = 1) { - $this->l10n = $l10n; - $this->text = $text; - $this->parameters = $parameters; - $this->count = $count; + public function __construct( + protected L10N $l10n, + protected $text, + protected array $parameters, + protected int $count = 1, + ) { } public function __toString(): string { diff --git a/lib/private/L10N/LanguageIterator.php b/lib/private/L10N/LanguageIterator.php index 531eea5866b..57f1bd68c91 100644 --- a/lib/private/L10N/LanguageIterator.php +++ b/lib/private/L10N/LanguageIterator.php @@ -14,14 +14,11 @@ use OCP\L10N\ILanguageIterator; class LanguageIterator implements ILanguageIterator { private $i = 0; - /** @var IConfig */ - private $config; - /** @var IUser */ - private $user; - public function __construct(IUser $user, IConfig $config) { - $this->config = $config; - $this->user = $user; + public function __construct( + private IUser $user, + private IConfig $config, + ) { } /** diff --git a/lib/private/L10N/LazyL10N.php b/lib/private/L10N/LazyL10N.php index 0d72f638632..ee201a12ff4 100644 --- a/lib/private/L10N/LazyL10N.php +++ b/lib/private/L10N/LazyL10N.php @@ -14,12 +14,10 @@ class LazyL10N implements IL10N { /** @var IL10N */ private $l; - /** @var \Closure */ - private $factory; - - public function __construct(\Closure $factory) { - $this->factory = $factory; + public function __construct( + private \Closure $factory, + ) { } private function getL(): IL10N { diff --git a/lib/private/LargeFileHelper.php b/lib/private/LargeFileHelper.php index fa4c72da756..e5c367bac5e 100644 --- a/lib/private/LargeFileHelper.php +++ b/lib/private/LargeFileHelper.php @@ -8,6 +8,8 @@ namespace OC; use bantu\IniGetWrapper\IniGetWrapper; +use OCP\Server; +use OCP\Util; /** * Helper class for large files on 32-bit platforms. @@ -96,7 +98,7 @@ class LargeFileHelper { * null on failure. */ public function getFileSizeViaCurl(string $fileName): null|int|float { - if (\OC::$server->get(IniGetWrapper::class)->getString('open_basedir') === '') { + if (Server::get(IniGetWrapper::class)->getString('open_basedir') === '') { $encodedFileName = rawurlencode($fileName); $ch = curl_init("file:///$encodedFileName"); curl_setopt($ch, CURLOPT_NOBODY, true); @@ -124,7 +126,7 @@ class LargeFileHelper { * null on failure. */ public function getFileSizeViaExec(string $filename): null|int|float { - if (\OCP\Util::isFunctionEnabled('exec')) { + if (Util::isFunctionEnabled('exec')) { $os = strtolower(php_uname('s')); $arg = escapeshellarg($filename); $result = null; @@ -169,7 +171,7 @@ class LargeFileHelper { $result = - 1; } if ($result < 0) { - if (\OCP\Util::isFunctionEnabled('exec')) { + if (Util::isFunctionEnabled('exec')) { $os = strtolower(php_uname('s')); if (str_contains($os, 'linux')) { return (int)($this->exec('stat -c %Y ' . escapeshellarg($fullPath)) ?? -1); diff --git a/lib/private/Lockdown/Filesystem/NullCache.php b/lib/private/Lockdown/Filesystem/NullCache.php index 5a27c5d5c6e..dde483d7225 100644 --- a/lib/private/Lockdown/Filesystem/NullCache.php +++ b/lib/private/Lockdown/Filesystem/NullCache.php @@ -8,6 +8,7 @@ namespace OC\Lockdown\Filesystem; use OC\Files\Cache\CacheEntry; use OC\Files\Search\SearchComparison; +use OC\ForbiddenException; use OCP\Constants; use OCP\Files\Cache\ICache; use OCP\Files\Cache\ICacheEntry; @@ -50,15 +51,15 @@ class NullCache implements ICache { } public function put($file, array $data) { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function insert($file, array $data) { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function update($id, array $data) { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function getId($file) { @@ -74,15 +75,15 @@ class NullCache implements ICache { } public function remove($file) { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function move($source, $target) { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function getStatus($file) { @@ -114,7 +115,7 @@ class NullCache implements ICache { } public function copyFromCache(ICache $sourceCache, ICacheEntry $sourceEntry, string $targetPath): int { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function getQueryFilterForStorage(): ISearchOperator { diff --git a/lib/private/Lockdown/Filesystem/NullStorage.php b/lib/private/Lockdown/Filesystem/NullStorage.php index d10763287c8..727259319ed 100644 --- a/lib/private/Lockdown/Filesystem/NullStorage.php +++ b/lib/private/Lockdown/Filesystem/NullStorage.php @@ -9,6 +9,7 @@ namespace OC\Lockdown\Filesystem; use Icewind\Streams\IteratorDirectory; use OC\Files\FileInfo; use OC\Files\Storage\Common; +use OC\ForbiddenException; use OCP\Files\Cache\ICache; use OCP\Files\Storage\IStorage; @@ -22,11 +23,11 @@ class NullStorage extends Common { } public function mkdir(string $path): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function rmdir(string $path): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function opendir(string $path): IteratorDirectory { @@ -42,7 +43,7 @@ class NullStorage extends Common { } public function stat(string $path): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function filetype(string $path): string|false { @@ -50,7 +51,7 @@ class NullStorage extends Common { } public function filesize(string $path): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function isCreatable(string $path): bool { @@ -86,35 +87,35 @@ class NullStorage extends Common { } public function file_get_contents(string $path): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function file_put_contents(string $path, mixed $data): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function unlink(string $path): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function rename(string $source, string $target): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function copy(string $source, string $target): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function fopen(string $path, string $mode): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function getMimeType(string $path): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function hash(string $type, string $path, bool $raw = false): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function free_space(string $path): int { @@ -122,7 +123,7 @@ class NullStorage extends Common { } public function touch(string $path, ?int $mtime = null): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function getLocalFile(string $path): string|false { @@ -150,11 +151,11 @@ class NullStorage extends Common { } public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath, bool $preserveMtime = false): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function moveFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): never { - throw new \OC\ForbiddenException('This request is not allowed to access the filesystem'); + throw new ForbiddenException('This request is not allowed to access the filesystem'); } public function test(): bool { diff --git a/lib/private/Log.php b/lib/private/Log.php index 88df3c032af..64f50c45053 100644 --- a/lib/private/Log.php +++ b/lib/private/Log.php @@ -20,6 +20,7 @@ use OCP\Log\BeforeMessageLoggedEvent; use OCP\Log\IDataLogger; use OCP\Log\IFileBased; use OCP\Log\IWriter; +use OCP\Server; use OCP\Support\CrashReport\IRegistry; use Throwable; use function array_merge; @@ -231,7 +232,7 @@ class Log implements ILogger, IDataLogger { // check for user if (isset($logCondition['users'])) { - $user = \OCP\Server::get(IUserSession::class)->getUser(); + $user = Server::get(IUserSession::class)->getUser(); if ($user === null) { // User is not known for this request yet @@ -253,7 +254,7 @@ class Log implements ILogger, IDataLogger { } if ($userId === false && isset($logCondition['matches'])) { - $user = \OCP\Server::get(IUserSession::class)->getUser(); + $user = Server::get(IUserSession::class)->getUser(); $userId = $user === null ? false : $user->getUID(); } @@ -304,7 +305,7 @@ class Log implements ILogger, IDataLogger { } protected function checkLogSecret(string $conditionSecret): bool { - $request = \OCP\Server::get(IRequest::class); + $request = Server::get(IRequest::class); if ($request->getMethod() === 'PUT' && !str_contains($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded') @@ -433,7 +434,7 @@ class Log implements ILogger, IDataLogger { $serializer = new ExceptionSerializer($this->config); try { /** @var Coordinator $coordinator */ - $coordinator = \OCP\Server::get(Coordinator::class); + $coordinator = Server::get(Coordinator::class); foreach ($coordinator->getRegistrationContext()->getSensitiveMethods() as $registration) { $serializer->enlistSensitiveMethods($registration->getName(), $registration->getValue()); } diff --git a/lib/private/Log/File.php b/lib/private/Log/File.php index ba428ba185b..580656ee55a 100644 --- a/lib/private/Log/File.php +++ b/lib/private/Log/File.php @@ -19,17 +19,14 @@ use OCP\Log\IWriter; */ class File extends LogDetails implements IWriter, IFileBased { - protected string $logFile; - protected int $logFileMode; public function __construct( - string $path, + protected string $logFile, string $fallbackPath, private SystemConfig $config, ) { parent::__construct($config); - $this->logFile = $path; if (!file_exists($this->logFile)) { if ( ( diff --git a/lib/private/Log/LogFactory.php b/lib/private/Log/LogFactory.php index ee6054b81f8..58c4f433ca6 100644 --- a/lib/private/Log/LogFactory.php +++ b/lib/private/Log/LogFactory.php @@ -8,6 +8,7 @@ namespace OC\Log; use OC\Log; use OC\SystemConfig; +use OCP\AppFramework\QueryException; use OCP\IServerContainer; use OCP\Log\ILogFactory; use OCP\Log\IWriter; @@ -21,7 +22,7 @@ class LogFactory implements ILogFactory { } /** - * @throws \OCP\AppFramework\QueryException + * @throws QueryException */ public function get(string $type):IWriter { return match (strtolower($type)) { diff --git a/lib/private/Log/Rotate.php b/lib/private/Log/Rotate.php index ee1593b87ac..b433d302ccc 100644 --- a/lib/private/Log/Rotate.php +++ b/lib/private/Log/Rotate.php @@ -11,6 +11,7 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\TimedJob; use OCP\IConfig; use OCP\Log\RotationTrait; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -29,14 +30,14 @@ class Rotate extends TimedJob { } public function run($argument): void { - $config = \OCP\Server::get(IConfig::class); + $config = Server::get(IConfig::class); $this->filePath = $config->getSystemValueString('logfile', $config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . '/nextcloud.log'); $this->maxSize = $config->getSystemValueInt('log_rotate_size', 100 * 1024 * 1024); if ($this->shouldRotateBySize()) { $rotatedFile = $this->rotate(); $msg = 'Log file "' . $this->filePath . '" was over ' . $this->maxSize . ' bytes, moved to "' . $rotatedFile . '"'; - \OCP\Server::get(LoggerInterface::class)->info($msg, ['app' => Rotate::class]); + Server::get(LoggerInterface::class)->info($msg, ['app' => Rotate::class]); } } } diff --git a/lib/private/Mail/Mailer.php b/lib/private/Mail/Mailer.php index 08efdd28224..3ba19162546 100644 --- a/lib/private/Mail/Mailer.php +++ b/lib/private/Mail/Mailer.php @@ -21,6 +21,8 @@ use OCP\Mail\IEMailTemplate; use OCP\Mail\IEmailValidator; use OCP\Mail\IMailer; use OCP\Mail\IMessage; +use OCP\Server; +use OCP\Util; use Psr\Log\LoggerInterface; use Symfony\Component\Mailer\Exception\TransportExceptionInterface; use Symfony\Component\Mailer\Mailer as SymfonyMailer; @@ -171,7 +173,7 @@ class Mailer implements IMailer { } if (empty($message->getFrom())) { - $message->setFrom([\OCP\Util::getDefaultEmailAddress('no-reply') => $this->defaults->getName()]); + $message->setFrom([Util::getDefaultEmailAddress('no-reply') => $this->defaults->getName()]); } $mailer = $this->getInstance(); @@ -190,7 +192,7 @@ class Mailer implements IMailer { $recipients = array_merge($message->getTo(), $message->getCc(), $message->getBcc()); $failedRecipients = []; - array_walk($recipients, function ($value, $key) use (&$failedRecipients) { + array_walk($recipients, function ($value, $key) use (&$failedRecipients): void { if (is_numeric($key)) { $failedRecipients[] = $value; } else { @@ -212,7 +214,7 @@ class Mailer implements IMailer { $recipients = array_merge($message->getTo(), $message->getCc(), $message->getBcc()); $failedRecipients = []; - array_walk($recipients, function ($value, $key) use (&$failedRecipients) { + array_walk($recipients, function ($value, $key) use (&$failedRecipients): void { if (is_numeric($key)) { $failedRecipients[] = $value; } else { @@ -325,7 +327,7 @@ class Mailer implements IMailer { $binaryPath = '/var/qmail/bin/sendmail'; break; default: - $sendmail = \OCP\Server::get(IBinaryFinder::class)->findBinaryPath('sendmail'); + $sendmail = Server::get(IBinaryFinder::class)->findBinaryPath('sendmail'); if ($sendmail === false) { // fallback (though not sure what good it'll do) $sendmail = '/usr/sbin/sendmail'; diff --git a/lib/private/Mail/Message.php b/lib/private/Mail/Message.php index 523a4836760..097af11e24c 100644 --- a/lib/private/Mail/Message.php +++ b/lib/private/Mail/Message.php @@ -75,7 +75,7 @@ class Message implements IMessage { return []; } - array_walk($addresses, function ($readableName, $email) use (&$convertedAddresses) { + array_walk($addresses, function ($readableName, $email) use (&$convertedAddresses): void { if (is_numeric($email)) { $convertedAddresses[] = new Address($readableName); } else { diff --git a/lib/private/Memcache/APCu.php b/lib/private/Memcache/APCu.php index 6bb2799d723..324218797e5 100644 --- a/lib/private/Memcache/APCu.php +++ b/lib/private/Memcache/APCu.php @@ -9,6 +9,7 @@ namespace OC\Memcache; use bantu\IniGetWrapper\IniGetWrapper; use OCP\IMemcache; +use OCP\Server; class APCu extends Cache implements IMemcache { use CASTrait { @@ -111,9 +112,9 @@ class APCu extends Cache implements IMemcache { public static function isAvailable(): bool { if (!extension_loaded('apcu')) { return false; - } elseif (!\OC::$server->get(IniGetWrapper::class)->getBool('apc.enabled')) { + } elseif (!Server::get(IniGetWrapper::class)->getBool('apc.enabled')) { return false; - } elseif (!\OC::$server->get(IniGetWrapper::class)->getBool('apc.enable_cli') && \OC::$CLI) { + } elseif (!Server::get(IniGetWrapper::class)->getBool('apc.enable_cli') && \OC::$CLI) { return false; } elseif (version_compare(phpversion('apcu') ?: '0.0.0', '5.1.0') === -1) { return false; diff --git a/lib/private/Memcache/Cache.php b/lib/private/Memcache/Cache.php index 774769b25fe..d26877c5e96 100644 --- a/lib/private/Memcache/Cache.php +++ b/lib/private/Memcache/Cache.php @@ -7,20 +7,18 @@ */ namespace OC\Memcache; +use OCP\ICache; + /** * @template-implements \ArrayAccess */ -abstract class Cache implements \ArrayAccess, \OCP\ICache { - /** - * @var string $prefix - */ - protected $prefix; - +abstract class Cache implements \ArrayAccess, ICache { /** * @param string $prefix */ - public function __construct($prefix = '') { - $this->prefix = $prefix; + public function __construct( + protected $prefix = '', + ) { } /** diff --git a/lib/private/Memcache/Factory.php b/lib/private/Memcache/Factory.php index 23e0550f62e..e083a357cba 100644 --- a/lib/private/Memcache/Factory.php +++ b/lib/private/Memcache/Factory.php @@ -9,11 +9,13 @@ namespace OC\Memcache; use OC\SystemConfig; use OCP\Cache\CappedMemoryCache; +use OCP\HintException; use OCP\IAppConfig; use OCP\ICache; use OCP\ICacheFactory; use OCP\IMemcache; use OCP\Profiler\IProfiler; +use OCP\Server; use OCP\ServerVersion; use Psr\Log\LoggerInterface; @@ -72,7 +74,7 @@ class Factory implements ICacheFactory { // APCu however cannot be shared between PHP instances (CLI and web) anyway. $localCacheClass = self::NULL_CACHE; } else { - throw new \OCP\HintException(strtr($missingCacheMessage, [ + throw new HintException(strtr($missingCacheMessage, [ '{class}' => $localCacheClass, '{use}' => 'local' ]), $missingCacheHint); } @@ -88,7 +90,7 @@ class Factory implements ICacheFactory { // APCu however cannot be shared between Nextcloud (PHP) instances anyway. $distributedCacheClass = self::NULL_CACHE; } else { - throw new \OCP\HintException(strtr($missingCacheMessage, [ + throw new HintException(strtr($missingCacheMessage, [ '{class}' => $distributedCacheClass, '{use}' => 'distributed' ]), $missingCacheHint); } @@ -112,11 +114,11 @@ class Factory implements ICacheFactory { protected function getGlobalPrefix(): string { if ($this->globalPrefix === null) { - $config = \OCP\Server::get(SystemConfig::class); + $config = Server::get(SystemConfig::class); $maintenanceMode = $config->getValue('maintenance', false); $versions = []; if ($config->getValue('installed', false) && !$maintenanceMode) { - $appConfig = \OCP\Server::get(IAppConfig::class); + $appConfig = Server::get(IAppConfig::class); // only get the enabled apps to clear the cache in case an app is enabled or disabled (e.g. clear routes) $versions = $appConfig->getAppInstalledVersions(true); ksort($versions); @@ -144,7 +146,7 @@ class Factory implements ICacheFactory { $backupPrefix = $this->globalPrefix; // Include instanceid in the prefix, in case multiple instances use the same cache (e.g. same FPM pool) - $instanceid = \OCP\Server::get(SystemConfig::class)->getValue('instanceid'); + $instanceid = Server::get(SystemConfig::class)->getValue('instanceid'); $this->globalPrefix = hash('xxh128', $instanceid . implode('.', $this->serverVersion->getVersion())); $closure($this); $this->globalPrefix = $backupPrefix; diff --git a/lib/private/Memcache/LoggerWrapperCache.php b/lib/private/Memcache/LoggerWrapperCache.php index c2a06731910..6ad0496be0d 100644 --- a/lib/private/Memcache/LoggerWrapperCache.php +++ b/lib/private/Memcache/LoggerWrapperCache.php @@ -17,16 +17,15 @@ class LoggerWrapperCache extends Cache implements IMemcacheTTL { /** @var Redis */ protected $wrappedCache; - /** @var string $logFile */ - private $logFile; - /** @var string $prefix */ protected $prefix; - public function __construct(Redis $wrappedCache, string $logFile) { + public function __construct( + Redis $wrappedCache, + private string $logFile, + ) { parent::__construct($wrappedCache->getPrefix()); $this->wrappedCache = $wrappedCache; - $this->logFile = $logFile; } /** diff --git a/lib/private/Memcache/Memcached.php b/lib/private/Memcache/Memcached.php index ba63b3a48d9..044a0fccd25 100644 --- a/lib/private/Memcache/Memcached.php +++ b/lib/private/Memcache/Memcached.php @@ -7,8 +7,11 @@ */ namespace OC\Memcache; +use OC\SystemConfig; use OCP\HintException; +use OCP\IConfig; use OCP\IMemcache; +use OCP\Server; class Memcached extends Cache implements IMemcache { use CASTrait; @@ -52,7 +55,7 @@ class Memcached extends Cache implements IMemcache { $defaultOptions[\Memcached::OPT_SERIALIZER] = \Memcached::SERIALIZER_IGBINARY; } - $options = \OC::$server->getConfig()->getSystemValue('memcached_options', []); + $options = Server::get(IConfig::class)->getSystemValue('memcached_options', []); if (is_array($options)) { $options = $options + $defaultOptions; self::$cache->setOptions($options); @@ -60,9 +63,9 @@ class Memcached extends Cache implements IMemcache { throw new HintException("Expected 'memcached_options' config to be an array, got $options"); } - $servers = \OC::$server->getSystemConfig()->getValue('memcached_servers'); + $servers = Server::get(SystemConfig::class)->getValue('memcached_servers'); if (!$servers) { - $server = \OC::$server->getSystemConfig()->getValue('memcached_server'); + $server = Server::get(SystemConfig::class)->getValue('memcached_server'); if ($server) { $servers = [$server]; } else { diff --git a/lib/private/Memcache/NullCache.php b/lib/private/Memcache/NullCache.php index eac1e6ddadc..11c17309b87 100644 --- a/lib/private/Memcache/NullCache.php +++ b/lib/private/Memcache/NullCache.php @@ -7,7 +7,9 @@ */ namespace OC\Memcache; -class NullCache extends Cache implements \OCP\IMemcache { +use OCP\IMemcache; + +class NullCache extends Cache implements IMemcache { public function get($key) { return null; } diff --git a/lib/private/Memcache/ProfilerWrapperCache.php b/lib/private/Memcache/ProfilerWrapperCache.php index 97d9d828a32..c9fb77885b4 100644 --- a/lib/private/Memcache/ProfilerWrapperCache.php +++ b/lib/private/Memcache/ProfilerWrapperCache.php @@ -24,13 +24,12 @@ class ProfilerWrapperCache extends AbstractDataCollector implements IMemcacheTTL /** @var string $prefix */ protected $prefix; - /** @var string $type */ - private $type; - - public function __construct(Redis $wrappedCache, string $type) { + public function __construct( + Redis $wrappedCache, + private string $type, + ) { $this->prefix = $wrappedCache->getPrefix(); $this->wrappedCache = $wrappedCache; - $this->type = $type; $this->data['queries'] = []; $this->data['cacheHit'] = 0; $this->data['cacheMiss'] = 0; diff --git a/lib/private/Memcache/Redis.php b/lib/private/Memcache/Redis.php index f8c51570c4f..1611d428f30 100644 --- a/lib/private/Memcache/Redis.php +++ b/lib/private/Memcache/Redis.php @@ -8,6 +8,7 @@ namespace OC\Memcache; use OCP\IMemcacheTTL; +use OCP\Server; class Redis extends Cache implements IMemcacheTTL { /** name => [script, sha1] */ @@ -51,7 +52,7 @@ class Redis extends Cache implements IMemcacheTTL { */ public function getCache() { if (is_null(self::$cache)) { - self::$cache = \OC::$server->get('RedisFactory')->getInstance(); + self::$cache = Server::get('RedisFactory')->getInstance(); } return self::$cache; } @@ -196,7 +197,7 @@ class Redis extends Cache implements IMemcacheTTL { } public static function isAvailable(): bool { - return \OC::$server->get('RedisFactory')->isAvailable(); + return Server::get('RedisFactory')->isAvailable(); } protected function evalLua(string $scriptName, array $keys, array $args) { diff --git a/lib/private/Memcache/WithLocalCache.php b/lib/private/Memcache/WithLocalCache.php index 0fc5d310801..334fa4bc753 100644 --- a/lib/private/Memcache/WithLocalCache.php +++ b/lib/private/Memcache/WithLocalCache.php @@ -13,11 +13,12 @@ use OCP\ICache; * Wrap a cache instance with an extra later of local, in-memory caching */ class WithLocalCache implements ICache { - private ICache $inner; private CappedMemoryCache $cached; - public function __construct(ICache $inner, int $localCapacity = 512) { - $this->inner = $inner; + public function __construct( + private ICache $inner, + int $localCapacity = 512, + ) { $this->cached = new CappedMemoryCache($localCapacity); } diff --git a/lib/private/NaturalSort.php b/lib/private/NaturalSort.php index 09c043764a7..240d4de637a 100644 --- a/lib/private/NaturalSort.php +++ b/lib/private/NaturalSort.php @@ -7,6 +7,7 @@ */ namespace OC; +use OCP\Server; use Psr\Log\LoggerInterface; class NaturalSort { @@ -23,7 +24,7 @@ class NaturalSort { // or inject an instance of \OC\NaturalSort_DefaultCollator to force using Owncloud's default collator if (isset($injectedCollator)) { $this->collator = $injectedCollator; - \OC::$server->get(LoggerInterface::class)->debug('forced use of ' . get_class($injectedCollator)); + Server::get(LoggerInterface::class)->debug('forced use of ' . get_class($injectedCollator)); } } @@ -71,7 +72,7 @@ class NaturalSort { if (class_exists('Collator')) { $this->collator = new \Collator('en_US'); } else { - $this->collator = new \OC\NaturalSort_DefaultCollator(); + $this->collator = new NaturalSort_DefaultCollator(); } } return $this->collator; @@ -110,11 +111,11 @@ class NaturalSort { /** * Returns a singleton - * @return \OC\NaturalSort instance + * @return NaturalSort instance */ public static function getInstance() { if (!isset(self::$instance)) { - self::$instance = new \OC\NaturalSort(); + self::$instance = new NaturalSort(); } return self::$instance; } diff --git a/lib/private/NavigationManager.php b/lib/private/NavigationManager.php index 4e24c72e0b9..d801877ee7f 100644 --- a/lib/private/NavigationManager.php +++ b/lib/private/NavigationManager.php @@ -8,7 +8,6 @@ namespace OC; use InvalidArgumentException; -use OC\App\AppManager; use OC\Group\Manager; use OCP\App\IAppManager; use OCP\EventDispatcher\IEventDispatcher; @@ -34,39 +33,19 @@ class NavigationManager implements INavigationManager { /** @var bool */ protected $init = false; - /** @var IAppManager|AppManager */ - protected $appManager; - /** @var IURLGenerator */ - private $urlGenerator; - /** @var IFactory */ - private $l10nFac; - /** @var IUserSession */ - private $userSession; - /** @var Manager */ - private $groupManager; - /** @var IConfig */ - private $config; /** User defined app order (cached for the `add` function) */ private array $customAppOrder; - private LoggerInterface $logger; public function __construct( - IAppManager $appManager, - IURLGenerator $urlGenerator, - IFactory $l10nFac, - IUserSession $userSession, - IGroupManager $groupManager, - IConfig $config, - LoggerInterface $logger, + protected IAppManager $appManager, + private IURLGenerator $urlGenerator, + private IFactory $l10nFac, + private IUserSession $userSession, + private IGroupManager $groupManager, + private IConfig $config, + private LoggerInterface $logger, protected IEventDispatcher $eventDispatcher, ) { - $this->appManager = $appManager; - $this->urlGenerator = $urlGenerator; - $this->l10nFac = $l10nFac; - $this->userSession = $userSession; - $this->groupManager = $groupManager; - $this->config = $config; - $this->logger = $logger; } /** @@ -410,7 +389,7 @@ class NavigationManager implements INavigationManager { private function isSubadmin() { $user = $this->userSession->getUser(); - if ($user !== null) { + if ($user !== null && $this->groupManager instanceof Manager) { return $this->groupManager->getSubAdmin()->isSubAdmin($user); } return false; diff --git a/lib/private/Notification/Manager.php b/lib/private/Notification/Manager.php index 62fa66df85c..6247f0484df 100644 --- a/lib/private/Notification/Manager.php +++ b/lib/private/Notification/Manager.php @@ -9,6 +9,7 @@ declare(strict_types=1); namespace OC\Notification; use OC\AppFramework\Bootstrap\Coordinator; +use OCA\Notifications\App; use OCP\ICache; use OCP\ICacheFactory; use OCP\IUserManager; @@ -26,6 +27,7 @@ use OCP\Notification\NotificationPreloadReason; use OCP\Notification\UnknownNotificationException; use OCP\RichObjectStrings\IRichTextFormatter; use OCP\RichObjectStrings\IValidator; +use OCP\Server; use OCP\Support\Subscription\IRegistry; use Psr\Container\ContainerExceptionInterface; use Psr\Log\LoggerInterface; @@ -78,7 +80,8 @@ class Manager implements IManager { public function registerApp(string $appClass): void { // other apps may want to rely on the 'main' notification app so make it deterministic that // the 'main' notification app adds it's notifications first and removes it's notifications last - if ($appClass === \OCA\Notifications\App::class) { + /** @psalm-suppress UndefinedClass */ + if ($appClass === App::class) { // add 'main' notifications app to start of internal list of apps array_unshift($this->appClasses, $appClass); } else { @@ -122,7 +125,7 @@ class Manager implements IManager { foreach ($this->appClasses as $appClass) { try { - $app = \OC::$server->get($appClass); + $app = Server::get($appClass); } catch (ContainerExceptionInterface $e) { $this->logger->error('Failed to load notification app class: ' . $appClass, [ 'exception' => $e, @@ -154,7 +157,7 @@ class Manager implements IManager { $notifierServices = $this->coordinator->getRegistrationContext()->getNotifierServices(); foreach ($notifierServices as $notifierService) { try { - $notifier = \OC::$server->get($notifierService->getService()); + $notifier = Server::get($notifierService->getService()); } catch (ContainerExceptionInterface $e) { $this->logger->error('Failed to load notification notifier class: ' . $notifierService->getService(), [ 'exception' => $e, @@ -182,7 +185,7 @@ class Manager implements IManager { foreach ($this->notifierClasses as $notifierClass) { try { - $notifier = \OC::$server->get($notifierClass); + $notifier = Server::get($notifierClass); } catch (ContainerExceptionInterface $e) { $this->logger->error('Failed to load notification notifier class: ' . $notifierClass, [ 'exception' => $e, diff --git a/lib/private/OCS/Provider.php b/lib/private/OCS/Provider.php index 402b6b7059d..3af70b70057 100644 --- a/lib/private/OCS/Provider.php +++ b/lib/private/OCS/Provider.php @@ -20,8 +20,8 @@ class Provider extends Controller { */ public function __construct( $appName, - \OCP\IRequest $request, - private \OCP\App\IAppManager $appManager, + IRequest $request, + private IAppManager $appManager, ) { parent::__construct($appName, $request); } diff --git a/lib/private/Preview/Bitmap.php b/lib/private/Preview/Bitmap.php index a3d5fbfd4ec..9585b8a1f39 100644 --- a/lib/private/Preview/Bitmap.php +++ b/lib/private/Preview/Bitmap.php @@ -10,6 +10,8 @@ namespace OC\Preview; use Imagick; use OCP\Files\File; use OCP\IImage; +use OCP\Image; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -36,7 +38,7 @@ abstract class Bitmap extends ProviderV2 { public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { $tmpPath = $this->getLocalFile($file); if ($tmpPath === false) { - \OC::$server->get(LoggerInterface::class)->error( + Server::get(LoggerInterface::class)->error( 'Failed to get thumbnail for: ' . $file->getPath(), ['app' => 'core'] ); @@ -47,7 +49,7 @@ abstract class Bitmap extends ProviderV2 { try { $bp = $this->getResizedPreview($tmpPath, $maxX, $maxY); } catch (\Exception $e) { - \OC::$server->get(LoggerInterface::class)->info( + Server::get(LoggerInterface::class)->info( 'File: ' . $file->getPath() . ' Imagick says:', [ 'exception' => $e, @@ -60,7 +62,7 @@ abstract class Bitmap extends ProviderV2 { $this->cleanTmpFiles(); //new bitmap image object - $image = new \OCP\Image(); + $image = new Image(); $image->loadFromData((string)$bp); //check if image object is valid return $image->valid() ? $image : null; diff --git a/lib/private/Preview/Bundled.php b/lib/private/Preview/Bundled.php index 6100e8262a4..39070bd6848 100644 --- a/lib/private/Preview/Bundled.php +++ b/lib/private/Preview/Bundled.php @@ -9,6 +9,9 @@ namespace OC\Preview; use OC\Archive\ZIP; use OCP\Files\File; use OCP\IImage; +use OCP\Image; +use OCP\ITempManager; +use OCP\Server; /** * Extracts a preview from files that embed them in an ZIP archive @@ -19,8 +22,8 @@ abstract class Bundled extends ProviderV2 { return null; } - $sourceTmp = \OC::$server->getTempManager()->getTemporaryFile(); - $targetTmp = \OC::$server->getTempManager()->getTemporaryFile(); + $sourceTmp = Server::get(ITempManager::class)->getTemporaryFile(); + $targetTmp = Server::get(ITempManager::class)->getTemporaryFile(); $this->tmpFiles[] = $sourceTmp; $this->tmpFiles[] = $targetTmp; @@ -31,7 +34,7 @@ abstract class Bundled extends ProviderV2 { $zip = new ZIP($sourceTmp); $zip->extractFile($path, $targetTmp); - $image = new \OCP\Image(); + $image = new Image(); $image->loadFromFile($targetTmp); $image->fixOrientation(); diff --git a/lib/private/Preview/Generator.php b/lib/private/Preview/Generator.php index 4627fad93b2..a923321faa0 100644 --- a/lib/private/Preview/Generator.php +++ b/lib/private/Preview/Generator.php @@ -21,6 +21,7 @@ use OCP\Files\SimpleFS\ISimpleFile; use OCP\IAppConfig; use OCP\IConfig; use OCP\IImage; +use OCP\Image; use OCP\IPreview; use OCP\IStreamImage; use OCP\Preview\BeforePreviewFetchedEvent; @@ -194,7 +195,7 @@ class Generator { // Free memory being used by the embedded image resource. Without this the image is kept in memory indefinitely. // Garbage Collection does NOT free this memory. We have to do it ourselves. - if ($maxPreviewImage instanceof \OCP\Image) { + if ($maxPreviewImage instanceof Image) { $maxPreviewImage->destroy(); } diff --git a/lib/private/Preview/HEIC.php b/lib/private/Preview/HEIC.php index 64eb48e58df..f2b6cc7254e 100644 --- a/lib/private/Preview/HEIC.php +++ b/lib/private/Preview/HEIC.php @@ -12,6 +12,7 @@ namespace OC\Preview; use OCP\Files\File; use OCP\Files\FileInfo; use OCP\IImage; +use OCP\Image; use OCP\Server; use Psr\Log\LoggerInterface; @@ -57,7 +58,7 @@ class HEIC extends ProviderV2 { $bp = $this->getResizedPreview($tmpPath, $maxX, $maxY); $bp->setFormat('jpg'); } catch (\Exception $e) { - \OC::$server->get(LoggerInterface::class)->error( + Server::get(LoggerInterface::class)->error( 'File: ' . $file->getPath() . ' Imagick says:', [ 'exception' => $e, @@ -70,7 +71,7 @@ class HEIC extends ProviderV2 { $this->cleanTmpFiles(); //new bitmap image object - $image = new \OCP\Image(); + $image = new Image(); $image->loadFromData((string)$bp); //check if image object is valid return $image->valid() ? $image : null; diff --git a/lib/private/Preview/Image.php b/lib/private/Preview/Image.php index 78a402c636a..25c74b5fdef 100644 --- a/lib/private/Preview/Image.php +++ b/lib/private/Preview/Image.php @@ -8,6 +8,7 @@ namespace OC\Preview; use OCP\Files\File; +use OCP\IConfig; use OCP\IImage; use OCP\Server; use Psr\Log\LoggerInterface; @@ -17,7 +18,7 @@ abstract class Image extends ProviderV2 { * {@inheritDoc} */ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { - $maxSizeForImages = \OC::$server->getConfig()->getSystemValueInt('preview_max_filesize_image', 50); + $maxSizeForImages = Server::get(IConfig::class)->getSystemValueInt('preview_max_filesize_image', 50); $size = $file->getSize(); if ($maxSizeForImages !== -1 && $size > ($maxSizeForImages * 1024 * 1024)) { diff --git a/lib/private/Preview/Imaginary.php b/lib/private/Preview/Imaginary.php index d421da74ac8..bd5645d417e 100644 --- a/lib/private/Preview/Imaginary.php +++ b/lib/private/Preview/Imaginary.php @@ -12,8 +12,9 @@ use OCP\Files\File; use OCP\Http\Client\IClientService; use OCP\IConfig; use OCP\IImage; - use OCP\Image; + +use OCP\Server; use Psr\Log\LoggerInterface; class Imaginary extends ProviderV2 { @@ -28,9 +29,9 @@ class Imaginary extends ProviderV2 { public function __construct(array $config) { parent::__construct($config); - $this->config = \OC::$server->get(IConfig::class); - $this->service = \OC::$server->get(IClientService::class); - $this->logger = \OC::$server->get(LoggerInterface::class); + $this->config = Server::get(IConfig::class); + $this->service = Server::get(IClientService::class); + $this->logger = Server::get(LoggerInterface::class); } /** diff --git a/lib/private/Preview/MP3.php b/lib/private/Preview/MP3.php index add0028738e..dd3e809a7de 100644 --- a/lib/private/Preview/MP3.php +++ b/lib/private/Preview/MP3.php @@ -9,6 +9,7 @@ namespace OC\Preview; use OCP\Files\File; use OCP\IImage; +use OCP\Image; use OCP\Server; use Psr\Log\LoggerInterface; use wapmorgan\Mp3Info\Mp3Info; @@ -50,7 +51,7 @@ class MP3 extends ProviderV2 { } if (is_string($picture)) { - $image = new \OCP\Image(); + $image = new Image(); $image->loadFromData($picture); if ($image->valid()) { diff --git a/lib/private/Preview/MarkDown.php b/lib/private/Preview/MarkDown.php index c20433a1ac0..d8ae8c48ea9 100644 --- a/lib/private/Preview/MarkDown.php +++ b/lib/private/Preview/MarkDown.php @@ -9,6 +9,7 @@ namespace OC\Preview; use OCP\Files\File; use OCP\IImage; +use OCP\Image; class MarkDown extends TXT { /** @@ -119,7 +120,7 @@ class MarkDown extends TXT { } } - $imageObject = new \OCP\Image(); + $imageObject = new Image(); $imageObject->setResource($image); return $imageObject->valid() ? $imageObject : null; diff --git a/lib/private/Preview/Movie.php b/lib/private/Preview/Movie.php index 00648e7526e..ea14423505a 100644 --- a/lib/private/Preview/Movie.php +++ b/lib/private/Preview/Movie.php @@ -12,6 +12,7 @@ use OCP\Files\File; use OCP\Files\FileInfo; use OCP\IConfig; use OCP\IImage; +use OCP\Image; use OCP\ITempManager; use OCP\Server; use Psr\Log\LoggerInterface; @@ -351,7 +352,7 @@ class Movie extends ProviderV2 { ); if ($returnCode === 0) { - $image = new \OCP\Image(); + $image = new Image(); $image->loadFromFile($tmpPath); if ($image->valid()) { unlink($tmpPath); diff --git a/lib/private/Preview/Office.php b/lib/private/Preview/Office.php index ffba0211de2..c67e4829db8 100644 --- a/lib/private/Preview/Office.php +++ b/lib/private/Preview/Office.php @@ -10,6 +10,7 @@ namespace OC\Preview; use OCP\Files\File; use OCP\Files\FileInfo; use OCP\IImage; +use OCP\Image; use OCP\ITempManager; use OCP\Server; use Psr\Log\LoggerInterface; @@ -81,7 +82,7 @@ abstract class Office extends ProviderV2 { $preview = $outdir . pathinfo($absPath, PATHINFO_FILENAME) . '.png'; - $image = new \OCP\Image(); + $image = new Image(); $image->loadFromFile($preview); $this->cleanTmpFiles(); diff --git a/lib/private/Preview/ProviderV2.php b/lib/private/Preview/ProviderV2.php index 556d1099d2d..9e1a6fcefcd 100644 --- a/lib/private/Preview/ProviderV2.php +++ b/lib/private/Preview/ProviderV2.php @@ -46,7 +46,7 @@ abstract class ProviderV2 implements IProviderV2 { * @param File $file * @param int $maxX The maximum X size of the thumbnail. It can be smaller depending on the shape of the image * @param int $maxY The maximum Y size of the thumbnail. It can be smaller depending on the shape of the image - * @return null|\OCP\IImage null if no preview was generated + * @return null|IImage null if no preview was generated * @since 17.0.0 */ abstract public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage; diff --git a/lib/private/Preview/SVG.php b/lib/private/Preview/SVG.php index d9f7701f411..be9b88fcc40 100644 --- a/lib/private/Preview/SVG.php +++ b/lib/private/Preview/SVG.php @@ -9,6 +9,8 @@ namespace OC\Preview; use OCP\Files\File; use OCP\IImage; +use OCP\Image; +use OCP\Server; use Psr\Log\LoggerInterface; class SVG extends ProviderV2 { @@ -46,7 +48,7 @@ class SVG extends ProviderV2 { $svg->readImageBlob($content); $svg->setImageFormat('png32'); } catch (\Exception $e) { - \OC::$server->get(LoggerInterface::class)->error( + Server::get(LoggerInterface::class)->error( 'File: ' . $file->getPath() . ' Imagick says:', [ 'exception' => $e, @@ -57,7 +59,7 @@ class SVG extends ProviderV2 { } //new image object - $image = new \OCP\Image(); + $image = new Image(); $image->loadFromData((string)$svg); //check if image object is valid if ($image->valid()) { diff --git a/lib/private/Preview/TXT.php b/lib/private/Preview/TXT.php index 1a1d64f3e08..2d407d88b56 100644 --- a/lib/private/Preview/TXT.php +++ b/lib/private/Preview/TXT.php @@ -10,6 +10,7 @@ namespace OC\Preview; use OCP\Files\File; use OCP\Files\FileInfo; use OCP\IImage; +use OCP\Image; class TXT extends ProviderV2 { /** @@ -81,7 +82,7 @@ class TXT extends ProviderV2 { } } - $imageObject = new \OCP\Image(); + $imageObject = new Image(); $imageObject->setResource($image); return $imageObject->valid() ? $imageObject : null; diff --git a/lib/private/Preview/WatcherConnector.php b/lib/private/Preview/WatcherConnector.php index c34dd1dde4d..f54607bb0ff 100644 --- a/lib/private/Preview/WatcherConnector.php +++ b/lib/private/Preview/WatcherConnector.php @@ -13,6 +13,7 @@ use OCA\Files_Versions\Events\VersionRestoredEvent; use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\IRootFolder; use OCP\Files\Node; +use OCP\Server; class WatcherConnector { public function __construct( @@ -23,17 +24,17 @@ class WatcherConnector { } private function getWatcher(): Watcher { - return \OCP\Server::get(Watcher::class); + return Server::get(Watcher::class); } public function connectWatcher(): void { // Do not connect if we are not setup yet! if ($this->config->getValue('instanceid', null) !== null) { - $this->root->listen('\OC\Files', 'postWrite', function (Node $node) { + $this->root->listen('\OC\Files', 'postWrite', function (Node $node): void { $this->getWatcher()->postWrite($node); }); - $this->dispatcher->addListener(VersionRestoredEvent::class, function (VersionRestoredEvent $event) { + $this->dispatcher->addListener(VersionRestoredEvent::class, function (VersionRestoredEvent $event): void { $this->getWatcher()->versionRollback(['node' => $event->getVersion()->getSourceFile()]); }); } diff --git a/lib/private/PreviewManager.php b/lib/private/PreviewManager.php index 8387485e6b2..268e265c7ab 100644 --- a/lib/private/PreviewManager.php +++ b/lib/private/PreviewManager.php @@ -9,14 +9,45 @@ namespace OC; use Closure; use OC\AppFramework\Bootstrap\Coordinator; +use OC\Preview\BMP; use OC\Preview\Db\PreviewMapper; +use OC\Preview\EMF; +use OC\Preview\Font; use OC\Preview\Generator; use OC\Preview\GeneratorHelper; +use OC\Preview\GIF; +use OC\Preview\HEIC; +use OC\Preview\Illustrator; +use OC\Preview\Image; use OC\Preview\IMagickSupport; +use OC\Preview\Imaginary; +use OC\Preview\ImaginaryPDF; +use OC\Preview\JPEG; +use OC\Preview\Krita; +use OC\Preview\MarkDown; +use OC\Preview\Movie; +use OC\Preview\MP3; +use OC\Preview\MSOffice2003; +use OC\Preview\MSOffice2007; +use OC\Preview\MSOfficeDoc; +use OC\Preview\OpenDocument; +use OC\Preview\PDF; +use OC\Preview\Photoshop; +use OC\Preview\PNG; +use OC\Preview\Postscript; use OC\Preview\PreviewMigrationService; +use OC\Preview\SGI; +use OC\Preview\StarOffice; use OC\Preview\Storage\StorageFactory; +use OC\Preview\SVG; +use OC\Preview\TGA; +use OC\Preview\TIFF; +use OC\Preview\TXT; +use OC\Preview\WebP; +use OC\Preview\XBitmap; use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\File; +use OCP\Files\FileInfo; use OCP\Files\IRootFolder; use OCP\Files\NotFoundException; use OCP\Files\SimpleFS\ISimpleFile; @@ -35,11 +66,7 @@ use function array_key_exists; * @psalm-import-type ProviderClosure from IPreview */ class PreviewManager implements IPreview { - protected IConfig $config; - protected IRootFolder $rootFolder; - protected IEventDispatcher $eventDispatcher; private ?Generator $generator = null; - private GeneratorHelper $helper; protected bool $providerListDirty = false; protected bool $registeredCoreProviders = false; /** @@ -51,40 +78,26 @@ class PreviewManager implements IPreview { protected array $mimeTypeSupportMap = []; /** @var ?list> $defaultProviders */ protected ?array $defaultProviders = null; - protected ?string $userId; - private Coordinator $bootstrapCoordinator; /** * Hash map (without value) of loaded bootstrap providers * @psalm-var array */ private array $loadedBootstrapProviders = []; - private ContainerInterface $container; - private IBinaryFinder $binaryFinder; - private IMagickSupport $imagickSupport; private bool $enablePreviews; public function __construct( - IConfig $config, - IRootFolder $rootFolder, - IEventDispatcher $eventDispatcher, - GeneratorHelper $helper, - ?string $userId, - Coordinator $bootstrapCoordinator, - ContainerInterface $container, - IBinaryFinder $binaryFinder, - IMagickSupport $imagickSupport, + protected IConfig $config, + protected IRootFolder $rootFolder, + protected IEventDispatcher $eventDispatcher, + private GeneratorHelper $helper, + protected ?string $userId, + private Coordinator $bootstrapCoordinator, + private ContainerInterface $container, + private IBinaryFinder $binaryFinder, + private IMagickSupport $imagickSupport, ) { - $this->config = $config; - $this->rootFolder = $rootFolder; - $this->eventDispatcher = $eventDispatcher; - $this->helper = $helper; - $this->userId = $userId; - $this->bootstrapCoordinator = $bootstrapCoordinator; - $this->container = $container; - $this->binaryFinder = $binaryFinder; - $this->imagickSupport = $imagickSupport; - $this->enablePreviews = $config->getSystemValueBool('enable_previews', true); + $this->enablePreviews = $this->config->getSystemValueBool('enable_previews', true); } /** @@ -207,7 +220,7 @@ class PreviewManager implements IPreview { return false; } - public function isAvailable(\OCP\Files\FileInfo $file, ?string $mimeType = null): bool { + public function isAvailable(FileInfo $file, ?string $mimeType = null): bool { if (!$this->enablePreviews) { return false; } @@ -251,22 +264,22 @@ class PreviewManager implements IPreview { } $imageProviders = [ - Preview\PNG::class, - Preview\JPEG::class, - Preview\GIF::class, - Preview\BMP::class, - Preview\XBitmap::class, - Preview\Krita::class, - Preview\WebP::class, + PNG::class, + JPEG::class, + GIF::class, + BMP::class, + XBitmap::class, + Krita::class, + WebP::class, ]; $this->defaultProviders = $this->config->getSystemValue('enabledPreviewProviders', array_merge([ - Preview\MarkDown::class, - Preview\TXT::class, - Preview\OpenDocument::class, + MarkDown::class, + TXT::class, + OpenDocument::class, ], $imageProviders)); - if (in_array(Preview\Image::class, $this->defaultProviders)) { + if (in_array(Image::class, $this->defaultProviders)) { $this->defaultProviders = array_merge($this->defaultProviders, $imageProviders); } $this->defaultProviders = array_values(array_unique($this->defaultProviders)); @@ -295,33 +308,33 @@ class PreviewManager implements IPreview { } $this->registeredCoreProviders = true; - $this->registerCoreProvider(Preview\TXT::class, '/text\/plain/'); - $this->registerCoreProvider(Preview\MarkDown::class, '/text\/(x-)?markdown/'); - $this->registerCoreProvider(Preview\PNG::class, '/image\/png/'); - $this->registerCoreProvider(Preview\JPEG::class, '/image\/jpeg/'); - $this->registerCoreProvider(Preview\GIF::class, '/image\/gif/'); - $this->registerCoreProvider(Preview\BMP::class, '/image\/bmp/'); - $this->registerCoreProvider(Preview\XBitmap::class, '/image\/x-xbitmap/'); - $this->registerCoreProvider(Preview\WebP::class, '/image\/webp/'); - $this->registerCoreProvider(Preview\Krita::class, '/application\/x-krita/'); - $this->registerCoreProvider(Preview\MP3::class, '/audio\/mpeg$/'); - $this->registerCoreProvider(Preview\OpenDocument::class, '/application\/vnd.oasis.opendocument.*/'); - $this->registerCoreProvider(Preview\Imaginary::class, Preview\Imaginary::supportedMimeTypes()); - $this->registerCoreProvider(Preview\ImaginaryPDF::class, Preview\ImaginaryPDF::supportedMimeTypes()); + $this->registerCoreProvider(TXT::class, '/text\/plain/'); + $this->registerCoreProvider(MarkDown::class, '/text\/(x-)?markdown/'); + $this->registerCoreProvider(PNG::class, '/image\/png/'); + $this->registerCoreProvider(JPEG::class, '/image\/jpeg/'); + $this->registerCoreProvider(GIF::class, '/image\/gif/'); + $this->registerCoreProvider(BMP::class, '/image\/bmp/'); + $this->registerCoreProvider(XBitmap::class, '/image\/x-xbitmap/'); + $this->registerCoreProvider(WebP::class, '/image\/webp/'); + $this->registerCoreProvider(Krita::class, '/application\/x-krita/'); + $this->registerCoreProvider(MP3::class, '/audio\/mpeg$/'); + $this->registerCoreProvider(OpenDocument::class, '/application\/vnd.oasis.opendocument.*/'); + $this->registerCoreProvider(Imaginary::class, Imaginary::supportedMimeTypes()); + $this->registerCoreProvider(ImaginaryPDF::class, ImaginaryPDF::supportedMimeTypes()); // SVG and Bitmap require imagick if ($this->imagickSupport->hasExtension()) { $imagickProviders = [ - 'SVG' => ['mimetype' => '/image\/svg\+xml/', 'class' => Preview\SVG::class], - 'TIFF' => ['mimetype' => '/image\/tiff/', 'class' => Preview\TIFF::class], - 'PDF' => ['mimetype' => '/application\/pdf/', 'class' => Preview\PDF::class], - 'AI' => ['mimetype' => '/application\/illustrator/', 'class' => Preview\Illustrator::class], - 'PSD' => ['mimetype' => '/application\/x-photoshop/', 'class' => Preview\Photoshop::class], - 'EPS' => ['mimetype' => '/application\/postscript/', 'class' => Preview\Postscript::class], - 'TTF' => ['mimetype' => '/application\/(?:font-sfnt|x-font$)/', 'class' => Preview\Font::class], - 'HEIC' => ['mimetype' => '/image\/(x-)?hei(f|c)/', 'class' => Preview\HEIC::class], - 'TGA' => ['mimetype' => '/image\/(x-)?t(ar)?ga/', 'class' => Preview\TGA::class], - 'SGI' => ['mimetype' => '/image\/(x-)?sgi/', 'class' => Preview\SGI::class], + 'SVG' => ['mimetype' => '/image\/svg\+xml/', 'class' => SVG::class], + 'TIFF' => ['mimetype' => '/image\/tiff/', 'class' => TIFF::class], + 'PDF' => ['mimetype' => '/application\/pdf/', 'class' => PDF::class], + 'AI' => ['mimetype' => '/application\/illustrator/', 'class' => Illustrator::class], + 'PSD' => ['mimetype' => '/application\/x-photoshop/', 'class' => Photoshop::class], + 'EPS' => ['mimetype' => '/application\/postscript/', 'class' => Postscript::class], + 'TTF' => ['mimetype' => '/application\/(?:font-sfnt|x-font$)/', 'class' => Font::class], + 'HEIC' => ['mimetype' => '/image\/(x-)?hei(f|c)/', 'class' => HEIC::class], + 'TGA' => ['mimetype' => '/image\/(x-)?t(ar)?ga/', 'class' => TGA::class], + 'SGI' => ['mimetype' => '/image\/(x-)?sgi/', 'class' => SGI::class], ]; foreach ($imagickProviders as $queryFormat => $provider) { @@ -339,7 +352,7 @@ class PreviewManager implements IPreview { $this->registerCoreProvidersOffice(); // Video requires ffmpeg - if (in_array(Preview\Movie::class, $this->getEnabledDefaultProvider())) { + if (in_array(Movie::class, $this->getEnabledDefaultProvider())) { $movieBinary = $this->config->getSystemValue('preview_ffmpeg_path', null); if (!is_string($movieBinary)) { $movieBinary = $this->binaryFinder->findBinaryPath('ffmpeg'); @@ -347,19 +360,19 @@ class PreviewManager implements IPreview { if (is_string($movieBinary)) { - $this->registerCoreProvider(Preview\Movie::class, '/video\/.*/', ['movieBinary' => $movieBinary]); + $this->registerCoreProvider(Movie::class, '/video\/.*/', ['movieBinary' => $movieBinary]); } } } private function registerCoreProvidersOffice(): void { $officeProviders = [ - ['mimetype' => '/application\/msword/', 'class' => Preview\MSOfficeDoc::class], - ['mimetype' => '/application\/vnd.ms-.*/', 'class' => Preview\MSOffice2003::class], - ['mimetype' => '/application\/vnd.openxmlformats-officedocument.*/', 'class' => Preview\MSOffice2007::class], - ['mimetype' => '/application\/vnd.oasis.opendocument.*/', 'class' => Preview\OpenDocument::class], - ['mimetype' => '/application\/vnd.sun.xml.*/', 'class' => Preview\StarOffice::class], - ['mimetype' => '/image\/emf/', 'class' => Preview\EMF::class], + ['mimetype' => '/application\/msword/', 'class' => MSOfficeDoc::class], + ['mimetype' => '/application\/vnd.ms-.*/', 'class' => MSOffice2003::class], + ['mimetype' => '/application\/vnd.openxmlformats-officedocument.*/', 'class' => MSOffice2007::class], + ['mimetype' => '/application\/vnd.oasis.opendocument.*/', 'class' => OpenDocument::class], + ['mimetype' => '/application\/vnd.sun.xml.*/', 'class' => StarOffice::class], + ['mimetype' => '/image\/emf/', 'class' => EMF::class], ]; $findBinary = true; diff --git a/lib/private/Profiler/BuiltInProfiler.php b/lib/private/Profiler/BuiltInProfiler.php index 0a62365e901..55f261aed68 100644 --- a/lib/private/Profiler/BuiltInProfiler.php +++ b/lib/private/Profiler/BuiltInProfiler.php @@ -11,6 +11,7 @@ namespace OC\Profiler; use DateTime; use OCP\IConfig; use OCP\IRequest; +use OCP\Server; class BuiltInProfiler { private \ExcimerProfiler $excimer; @@ -64,7 +65,7 @@ class BuiltInProfiler { return; } - $request = \OCP\Server::get(IRequest::class); + $request = Server::get(IRequest::class); $data = $this->excimer->getLog()->getSpeedscopeData(); $data['profiles'][0]['name'] = $request->getMethod() . ' ' . $request->getRequestUri() . ' ' . $request->getId(); diff --git a/lib/private/Profiler/FileProfilerStorage.php b/lib/private/Profiler/FileProfilerStorage.php index 4fa056b0009..67da2731cf3 100644 --- a/lib/private/Profiler/FileProfilerStorage.php +++ b/lib/private/Profiler/FileProfilerStorage.php @@ -14,9 +14,6 @@ use OCP\Profiler\IProfile; * Storage for profiler using files. */ class FileProfilerStorage { - // Folder where profiler data are stored. - private string $folder; - /** @psalm-suppress UndefinedClass */ public const allowedClasses = [ \OCA\Profiler\DataCollector\EventLoggerDataProvider::class, @@ -35,9 +32,10 @@ class FileProfilerStorage { * * @throws \RuntimeException */ - public function __construct(string $folder) { - $this->folder = $folder; - + public function __construct( + /** @var string $folder Folder where profiler data are stored. */ + private string $folder, + ) { if (!is_dir($this->folder) && @mkdir($this->folder, 0777, true) === false && !is_dir($this->folder)) { throw new \RuntimeException(sprintf('Unable to create the storage directory (%s).', $this->folder)); } diff --git a/lib/private/Profiler/Profile.php b/lib/private/Profiler/Profile.php index c611d79e259..d823a7c8327 100644 --- a/lib/private/Profiler/Profile.php +++ b/lib/private/Profiler/Profile.php @@ -12,8 +12,6 @@ use OCP\DataCollector\IDataCollector; use OCP\Profiler\IProfile; class Profile implements \JsonSerializable, IProfile { - private string $token; - private ?int $time = null; private ?string $url = null; @@ -30,8 +28,9 @@ class Profile implements \JsonSerializable, IProfile { /** @var IProfile[] */ private array $children = []; - public function __construct(string $token) { - $this->token = $token; + public function __construct( + private string $token, + ) { } public function getToken(): string { diff --git a/lib/private/Profiler/RoutingDataCollector.php b/lib/private/Profiler/RoutingDataCollector.php index c8952c76a38..47d4af1149c 100644 --- a/lib/private/Profiler/RoutingDataCollector.php +++ b/lib/private/Profiler/RoutingDataCollector.php @@ -14,14 +14,11 @@ use OCP\AppFramework\Http\Response; use OCP\DataCollector\AbstractDataCollector; class RoutingDataCollector extends AbstractDataCollector { - private string $appName; - private string $controllerName; - private string $actionName; - - public function __construct(string $appName, string $controllerName, string $actionName) { - $this->appName = $appName; - $this->controllerName = $controllerName; - $this->actionName = $actionName; + public function __construct( + private string $appName, + private string $controllerName, + private string $actionName, + ) { } public function collect(Request $request, Response $response, ?\Throwable $exception = null): void { diff --git a/lib/private/RedisFactory.php b/lib/private/RedisFactory.php index 29d45ace696..839e6a9a048 100644 --- a/lib/private/RedisFactory.php +++ b/lib/private/RedisFactory.php @@ -16,18 +16,15 @@ class RedisFactory { /** @var \Redis|\RedisCluster */ private $instance; - private SystemConfig $config; - - private IEventLogger $eventLogger; - /** * RedisFactory constructor. * * @param SystemConfig $config */ - public function __construct(SystemConfig $config, IEventLogger $eventLogger) { - $this->config = $config; - $this->eventLogger = $eventLogger; + public function __construct( + private SystemConfig $config, + private IEventLogger $eventLogger, + ) { } private function create() { diff --git a/lib/private/Remote/Api/ApiBase.php b/lib/private/Remote/Api/ApiBase.php index b2f96fb3c24..2801ece60f6 100644 --- a/lib/private/Remote/Api/ApiBase.php +++ b/lib/private/Remote/Api/ApiBase.php @@ -11,17 +11,11 @@ use OCP\Remote\ICredentials; use OCP\Remote\IInstance; class ApiBase { - /** @var IInstance */ - private $instance; - /** @var ICredentials */ - private $credentials; - /** @var IClientService */ - private $clientService; - - public function __construct(IInstance $instance, ICredentials $credentials, IClientService $clientService) { - $this->instance = $instance; - $this->credentials = $credentials; - $this->clientService = $clientService; + public function __construct( + private IInstance $instance, + private ICredentials $credentials, + private IClientService $clientService, + ) { } protected function getHttpClient() { diff --git a/lib/private/Remote/Api/ApiCollection.php b/lib/private/Remote/Api/ApiCollection.php index f154cd21926..a846eea0848 100644 --- a/lib/private/Remote/Api/ApiCollection.php +++ b/lib/private/Remote/Api/ApiCollection.php @@ -12,17 +12,11 @@ use OCP\Remote\ICredentials; use OCP\Remote\IInstance; class ApiCollection implements IApiCollection { - /** @var IInstance */ - private $instance; - /** @var ICredentials */ - private $credentials; - /** @var IClientService */ - private $clientService; - - public function __construct(IInstance $instance, ICredentials $credentials, IClientService $clientService) { - $this->instance = $instance; - $this->credentials = $credentials; - $this->clientService = $clientService; + public function __construct( + private IInstance $instance, + private ICredentials $credentials, + private IClientService $clientService, + ) { } public function getCapabilitiesApi() { diff --git a/lib/private/Remote/Api/ApiFactory.php b/lib/private/Remote/Api/ApiFactory.php index 795584e566a..f225ab16894 100644 --- a/lib/private/Remote/Api/ApiFactory.php +++ b/lib/private/Remote/Api/ApiFactory.php @@ -12,11 +12,9 @@ use OCP\Remote\ICredentials; use OCP\Remote\IInstance; class ApiFactory implements IApiFactory { - /** @var IClientService */ - private $clientService; - - public function __construct(IClientService $clientService) { - $this->clientService = $clientService; + public function __construct( + private IClientService $clientService, + ) { } public function getApiCollection(IInstance $instance, ICredentials $credentials) { diff --git a/lib/private/Remote/Credentials.php b/lib/private/Remote/Credentials.php index 7f1ffaa727c..ce7c7f88590 100644 --- a/lib/private/Remote/Credentials.php +++ b/lib/private/Remote/Credentials.php @@ -9,18 +9,14 @@ namespace OC\Remote; use OCP\Remote\ICredentials; class Credentials implements ICredentials { - /** @var string */ - private $user; - /** @var string */ - private $password; - /** * @param string $user * @param string $password */ - public function __construct($user, $password) { - $this->user = $user; - $this->password = $password; + public function __construct( + private $user, + private $password, + ) { } /** diff --git a/lib/private/Remote/Instance.php b/lib/private/Remote/Instance.php index 10403af4ec7..0f3311c3dfc 100644 --- a/lib/private/Remote/Instance.php +++ b/lib/private/Remote/Instance.php @@ -18,12 +18,6 @@ class Instance implements IInstance { /** @var string */ private $url; - /** @var ICache */ - private $cache; - - /** @var IClientService */ - private $clientService; - /** @var array|null */ private $status; @@ -32,11 +26,13 @@ class Instance implements IInstance { * @param ICache $cache * @param IClientService $clientService */ - public function __construct($url, ICache $cache, IClientService $clientService) { + public function __construct( + $url, + private ICache $cache, + private IClientService $clientService, + ) { $url = str_replace('https://', '', $url); $this->url = str_replace('http://', '', $url); - $this->cache = $cache; - $this->clientService = $clientService; } /** diff --git a/lib/private/Remote/InstanceFactory.php b/lib/private/Remote/InstanceFactory.php index f1b7a1de4ba..5279d0146cd 100644 --- a/lib/private/Remote/InstanceFactory.php +++ b/lib/private/Remote/InstanceFactory.php @@ -11,14 +11,10 @@ use OCP\ICache; use OCP\Remote\IInstanceFactory; class InstanceFactory implements IInstanceFactory { - /** @var ICache */ - private $cache; - /** @var IClientService */ - private $clientService; - - public function __construct(ICache $cache, IClientService $clientService) { - $this->cache = $cache; - $this->clientService = $clientService; + public function __construct( + private ICache $cache, + private IClientService $clientService, + ) { } public function getInstance($url) { diff --git a/lib/private/Remote/User.php b/lib/private/Remote/User.php index ae1032cdc1c..18a4d8b30b8 100644 --- a/lib/private/Remote/User.php +++ b/lib/private/Remote/User.php @@ -21,11 +21,9 @@ class User implements IUser { 'quota' ]; - /** @var array */ - private $data; - - public function __construct(array $data) { - $this->data = $data; + public function __construct( + private array $data, + ) { } diff --git a/lib/private/Repair.php b/lib/private/Repair.php index ba1a659958a..45524145ed4 100644 --- a/lib/private/Repair.php +++ b/lib/private/Repair.php @@ -63,15 +63,20 @@ use OCA\DAV\Migration\RemoveObjectProperties; use OCA\Files_Sharing\Repair\CleanupShareTarget; use OCP\AppFramework\QueryException; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\BackgroundJob\IJobList; use OCP\Collaboration\Resources\IManager; use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\AppData\IAppDataFactory; use OCP\IAppConfig; +use OCP\ICacheFactory; use OCP\IConfig; use OCP\IDBConnection; +use OCP\IGroupManager; +use OCP\IUserManager; use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; use OCP\Notification\IManager as INotificationManager; +use OCP\Server; use Psr\Log\LoggerInterface; use Throwable; @@ -125,7 +130,7 @@ class Repair implements IOutput { public function addStep($repairStep) { if (is_string($repairStep)) { try { - $s = \OC::$server->get($repairStep); + $s = Server::get($repairStep); } catch (QueryException $e) { if (class_exists($repairStep)) { try { @@ -158,50 +163,50 @@ class Repair implements IOutput { */ public static function getRepairSteps(): array { return [ - new Collation(\OC::$server->getConfig(), \OC::$server->get(LoggerInterface::class), \OC::$server->getDatabaseConnection(), false), - new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()), - new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()), - new MoveUpdaterStepFile(\OC::$server->getConfig()), + new Collation(Server::get(IConfig::class), Server::get(LoggerInterface::class), Server::get(IDBConnection::class), false), + new CleanTags(Server::get(IDBConnection::class), Server::get(IUserManager::class)), + new RepairInvalidShares(Server::get(IConfig::class), Server::get(IDBConnection::class)), + new MoveUpdaterStepFile(Server::get(IConfig::class)), new MoveAvatars( - \OC::$server->getJobList(), - \OC::$server->getConfig() + Server::get(IJobList::class), + Server::get(IConfig::class) ), new CleanPreviews( - \OC::$server->getJobList(), - \OC::$server->getUserManager(), - \OC::$server->getConfig() + Server::get(IJobList::class), + Server::get(IUserManager::class), + Server::get(IConfig::class) ), - \OCP\Server::get(MigratePropertiesTable::class), - \OC::$server->get(MigrateOauthTables::class), - new UpdateLanguageCodes(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()), - new AddLogRotateJob(\OC::$server->getJobList()), - new ClearFrontendCaches(\OC::$server->getMemCacheFactory(), \OCP\Server::get(JSCombiner::class)), - \OCP\Server::get(ClearGeneratedAvatarCache::class), - new AddPreviewBackgroundCleanupJob(\OC::$server->getJobList()), - new AddCleanupUpdaterBackupsJob(\OC::$server->getJobList()), - new CleanupCardDAVPhotoCache(\OC::$server->getConfig(), \OCP\Server::get(IAppDataFactory::class), \OC::$server->get(LoggerInterface::class)), - new AddClenupLoginFlowV2BackgroundJob(\OC::$server->getJobList()), - new RemoveLinkShares(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig(), \OC::$server->getGroupManager(), \OC::$server->get(INotificationManager::class), \OCP\Server::get(ITimeFactory::class)), - new ClearCollectionsAccessCache(\OC::$server->getConfig(), \OCP\Server::get(IManager::class)), - \OCP\Server::get(ResetGeneratedAvatarFlag::class), - \OCP\Server::get(EncryptionLegacyCipher::class), - \OCP\Server::get(EncryptionMigration::class), - \OCP\Server::get(ShippedDashboardEnable::class), - \OCP\Server::get(AddBruteForceCleanupJob::class), - \OCP\Server::get(AddCheckForUserCertificatesJob::class), - \OCP\Server::get(RepairDavShares::class), - \OCP\Server::get(LookupServerSendCheck::class), - \OCP\Server::get(AddTokenCleanupJob::class), - \OCP\Server::get(CleanUpAbandonedApps::class), - \OCP\Server::get(AddMissingSecretJob::class), - \OCP\Server::get(AddRemoveOldTasksBackgroundJob::class), - \OCP\Server::get(AddMetadataGenerationJob::class), - \OCP\Server::get(RepairLogoDimension::class), - \OCP\Server::get(RemoveLegacyDatadirFile::class), - \OCP\Server::get(AddCleanupDeletedUsersBackgroundJob::class), - \OCP\Server::get(SanitizeAccountProperties::class), - \OCP\Server::get(AddMovePreviewJob::class), - \OCP\Server::get(ConfigKeyMigration::class), + Server::get(MigratePropertiesTable::class), + Server::get(MigrateOauthTables::class), + new UpdateLanguageCodes(Server::get(IDBConnection::class), Server::get(IConfig::class)), + new AddLogRotateJob(Server::get(IJobList::class)), + new ClearFrontendCaches(Server::get(ICacheFactory::class), Server::get(JSCombiner::class)), + Server::get(ClearGeneratedAvatarCache::class), + new AddPreviewBackgroundCleanupJob(Server::get(IJobList::class)), + new AddCleanupUpdaterBackupsJob(Server::get(IJobList::class)), + new CleanupCardDAVPhotoCache(Server::get(IConfig::class), Server::get(IAppDataFactory::class), Server::get(LoggerInterface::class)), + new AddClenupLoginFlowV2BackgroundJob(Server::get(IJobList::class)), + new RemoveLinkShares(Server::get(IDBConnection::class), Server::get(IConfig::class), Server::get(IGroupManager::class), Server::get(INotificationManager::class), Server::get(ITimeFactory::class)), + new ClearCollectionsAccessCache(Server::get(IConfig::class), Server::get(IManager::class)), + Server::get(ResetGeneratedAvatarFlag::class), + Server::get(EncryptionLegacyCipher::class), + Server::get(EncryptionMigration::class), + Server::get(ShippedDashboardEnable::class), + Server::get(AddBruteForceCleanupJob::class), + Server::get(AddCheckForUserCertificatesJob::class), + Server::get(RepairDavShares::class), + Server::get(LookupServerSendCheck::class), + Server::get(AddTokenCleanupJob::class), + Server::get(CleanUpAbandonedApps::class), + Server::get(AddMissingSecretJob::class), + Server::get(AddRemoveOldTasksBackgroundJob::class), + Server::get(AddMetadataGenerationJob::class), + Server::get(RepairLogoDimension::class), + Server::get(RemoveLegacyDatadirFile::class), + Server::get(AddCleanupDeletedUsersBackgroundJob::class), + Server::get(SanitizeAccountProperties::class), + Server::get(AddMovePreviewJob::class), + Server::get(ConfigKeyMigration::class), ]; } @@ -213,16 +218,16 @@ class Repair implements IOutput { */ public static function getExpensiveRepairSteps() { return [ - new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager()), - new RemoveBrokenProperties(\OCP\Server::get(IDBConnection::class)), + new OldGroupMembershipShares(Server::get(IDBConnection::class), Server::get(IGroupManager::class)), + new RemoveBrokenProperties(Server::get(IDBConnection::class)), new RepairMimeTypes( - \OCP\Server::get(IConfig::class), - \OCP\Server::get(IAppConfig::class), - \OCP\Server::get(IDBConnection::class) + Server::get(IConfig::class), + Server::get(IAppConfig::class), + Server::get(IDBConnection::class) ), - \OCP\Server::get(DeleteSchedulingObjects::class), - \OC::$server->get(RemoveObjectProperties::class), - \OCP\Server::get(CleanupShareTarget::class), + Server::get(DeleteSchedulingObjects::class), + Server::get(RemoveObjectProperties::class), + Server::get(CleanupShareTarget::class), ]; } @@ -234,10 +239,10 @@ class Repair implements IOutput { */ public static function getBeforeUpgradeRepairSteps() { /** @var ConnectionAdapter $connectionAdapter */ - $connectionAdapter = \OC::$server->get(ConnectionAdapter::class); - $config = \OC::$server->getConfig(); + $connectionAdapter = Server::get(ConnectionAdapter::class); + $config = Server::get(IConfig::class); $steps = [ - new Collation(\OC::$server->getConfig(), \OC::$server->get(LoggerInterface::class), $connectionAdapter, true), + new Collation(Server::get(IConfig::class), Server::get(LoggerInterface::class), $connectionAdapter, true), new SaveAccountsTableData($connectionAdapter, $config), new DropAccountTermsTable($connectionAdapter), ]; diff --git a/lib/private/Repair/AddBruteForceCleanupJob.php b/lib/private/Repair/AddBruteForceCleanupJob.php index dd08e36a597..b580005d86d 100644 --- a/lib/private/Repair/AddBruteForceCleanupJob.php +++ b/lib/private/Repair/AddBruteForceCleanupJob.php @@ -14,11 +14,9 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class AddBruteForceCleanupJob implements IRepairStep { - /** @var IJobList */ - protected $jobList; - - public function __construct(IJobList $jobList) { - $this->jobList = $jobList; + public function __construct( + protected IJobList $jobList, + ) { } public function getName() { diff --git a/lib/private/Repair/AddCleanupDeletedUsersBackgroundJob.php b/lib/private/Repair/AddCleanupDeletedUsersBackgroundJob.php index 9713d8595e7..398518b33d9 100644 --- a/lib/private/Repair/AddCleanupDeletedUsersBackgroundJob.php +++ b/lib/private/Repair/AddCleanupDeletedUsersBackgroundJob.php @@ -14,10 +14,9 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class AddCleanupDeletedUsersBackgroundJob implements IRepairStep { - private IJobList $jobList; - - public function __construct(IJobList $jobList) { - $this->jobList = $jobList; + public function __construct( + private IJobList $jobList, + ) { } public function getName(): string { diff --git a/lib/private/Repair/AddCleanupUpdaterBackupsJob.php b/lib/private/Repair/AddCleanupUpdaterBackupsJob.php index e631a3303f1..be6afebc447 100644 --- a/lib/private/Repair/AddCleanupUpdaterBackupsJob.php +++ b/lib/private/Repair/AddCleanupUpdaterBackupsJob.php @@ -12,11 +12,9 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class AddCleanupUpdaterBackupsJob implements IRepairStep { - /** @var IJobList */ - protected $jobList; - - public function __construct(IJobList $jobList) { - $this->jobList = $jobList; + public function __construct( + protected IJobList $jobList, + ) { } public function getName() { diff --git a/lib/private/Repair/AddRemoveOldTasksBackgroundJob.php b/lib/private/Repair/AddRemoveOldTasksBackgroundJob.php index 4ad320a0311..40146a314f7 100644 --- a/lib/private/Repair/AddRemoveOldTasksBackgroundJob.php +++ b/lib/private/Repair/AddRemoveOldTasksBackgroundJob.php @@ -16,10 +16,9 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class AddRemoveOldTasksBackgroundJob implements IRepairStep { - private IJobList $jobList; - - public function __construct(IJobList $jobList) { - $this->jobList = $jobList; + public function __construct( + private IJobList $jobList, + ) { } public function getName(): string { diff --git a/lib/private/Repair/CleanUpAbandonedApps.php b/lib/private/Repair/CleanUpAbandonedApps.php index 718f625be86..cbc9349c72a 100644 --- a/lib/private/Repair/CleanUpAbandonedApps.php +++ b/lib/private/Repair/CleanUpAbandonedApps.php @@ -13,10 +13,10 @@ use OCP\Migration\IRepairStep; class CleanUpAbandonedApps implements IRepairStep { protected const ABANDONED_APPS = ['accessibility', 'files_videoplayer']; - private IConfig $config; - public function __construct(IConfig $config) { - $this->config = $config; + public function __construct( + private IConfig $config, + ) { } public function getName(): string { diff --git a/lib/private/Repair/ClearFrontendCaches.php b/lib/private/Repair/ClearFrontendCaches.php index 5c57a63379d..ff10c7ae109 100644 --- a/lib/private/Repair/ClearFrontendCaches.php +++ b/lib/private/Repair/ClearFrontendCaches.php @@ -12,16 +12,10 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class ClearFrontendCaches implements IRepairStep { - /** @var ICacheFactory */ - protected $cacheFactory; - - /** @var JSCombiner */ - protected $jsCombiner; - - public function __construct(ICacheFactory $cacheFactory, - JSCombiner $JSCombiner) { - $this->cacheFactory = $cacheFactory; - $this->jsCombiner = $JSCombiner; + public function __construct( + protected ICacheFactory $cacheFactory, + protected JSCombiner $jsCombiner, + ) { } public function getName() { diff --git a/lib/private/Repair/ClearGeneratedAvatarCache.php b/lib/private/Repair/ClearGeneratedAvatarCache.php index 0f743afbb4c..0e4c8a67fda 100644 --- a/lib/private/Repair/ClearGeneratedAvatarCache.php +++ b/lib/private/Repair/ClearGeneratedAvatarCache.php @@ -13,14 +13,11 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class ClearGeneratedAvatarCache implements IRepairStep { - protected AvatarManager $avatarManager; - private IConfig $config; - private IJobList $jobList; - - public function __construct(IConfig $config, AvatarManager $avatarManager, IJobList $jobList) { - $this->config = $config; - $this->avatarManager = $avatarManager; - $this->jobList = $jobList; + public function __construct( + private IConfig $config, + protected AvatarManager $avatarManager, + private IJobList $jobList, + ) { } public function getName(): string { diff --git a/lib/private/Repair/ClearGeneratedAvatarCacheJob.php b/lib/private/Repair/ClearGeneratedAvatarCacheJob.php index 524a470e62a..ff6a67480cd 100644 --- a/lib/private/Repair/ClearGeneratedAvatarCacheJob.php +++ b/lib/private/Repair/ClearGeneratedAvatarCacheJob.php @@ -11,11 +11,11 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\QueuedJob; class ClearGeneratedAvatarCacheJob extends QueuedJob { - protected AvatarManager $avatarManager; - - public function __construct(ITimeFactory $timeFactory, AvatarManager $avatarManager) { + public function __construct( + ITimeFactory $timeFactory, + protected AvatarManager $avatarManager, + ) { parent::__construct($timeFactory); - $this->avatarManager = $avatarManager; } public function run($argument) { diff --git a/lib/private/Repair/Collation.php b/lib/private/Repair/Collation.php index 43229792217..2ffa2086d9f 100644 --- a/lib/private/Repair/Collation.php +++ b/lib/private/Repair/Collation.php @@ -15,30 +15,15 @@ use OCP\Migration\IRepairStep; use Psr\Log\LoggerInterface; class Collation implements IRepairStep { - /** @var IConfig */ - protected $config; - - protected LoggerInterface $logger; - - /** @var IDBConnection */ - protected $connection; - - /** @var bool */ - protected $ignoreFailures; - /** * @param bool $ignoreFailures */ public function __construct( - IConfig $config, - LoggerInterface $logger, - IDBConnection $connection, - $ignoreFailures, + protected IConfig $config, + protected LoggerInterface $logger, + protected IDBConnection $connection, + protected $ignoreFailures, ) { - $this->connection = $connection; - $this->config = $config; - $this->logger = $logger; - $this->ignoreFailures = $ignoreFailures; } public function getName() { diff --git a/lib/private/Repair/Events/RepairAdvanceEvent.php b/lib/private/Repair/Events/RepairAdvanceEvent.php index 476db9e4702..eb5bdb01805 100644 --- a/lib/private/Repair/Events/RepairAdvanceEvent.php +++ b/lib/private/Repair/Events/RepairAdvanceEvent.php @@ -11,15 +11,10 @@ namespace OC\Repair\Events; use OCP\EventDispatcher\Event; class RepairAdvanceEvent extends Event { - private int $increment; - private string $description; - public function __construct( - int $increment, - string $description, + private int $increment, + private string $description, ) { - $this->increment = $increment; - $this->description = $description; } public function getIncrement(): int { diff --git a/lib/private/Repair/Events/RepairErrorEvent.php b/lib/private/Repair/Events/RepairErrorEvent.php index e5be8a5a031..219a7cd97bb 100644 --- a/lib/private/Repair/Events/RepairErrorEvent.php +++ b/lib/private/Repair/Events/RepairErrorEvent.php @@ -11,12 +11,9 @@ namespace OC\Repair\Events; use OCP\EventDispatcher\Event; class RepairErrorEvent extends Event { - private string $message; - public function __construct( - string $message, + private string $message, ) { - $this->message = $message; } public function getMessage(): string { diff --git a/lib/private/Repair/Events/RepairInfoEvent.php b/lib/private/Repair/Events/RepairInfoEvent.php index ce8eb2f99e6..87b2056f8d3 100644 --- a/lib/private/Repair/Events/RepairInfoEvent.php +++ b/lib/private/Repair/Events/RepairInfoEvent.php @@ -11,12 +11,9 @@ namespace OC\Repair\Events; use OCP\EventDispatcher\Event; class RepairInfoEvent extends Event { - private string $message; - public function __construct( - string $message, + private string $message, ) { - $this->message = $message; } public function getMessage(): string { diff --git a/lib/private/Repair/Events/RepairStartEvent.php b/lib/private/Repair/Events/RepairStartEvent.php index 47e713d57d9..e8e97c5233b 100644 --- a/lib/private/Repair/Events/RepairStartEvent.php +++ b/lib/private/Repair/Events/RepairStartEvent.php @@ -11,15 +11,10 @@ namespace OC\Repair\Events; use OCP\EventDispatcher\Event; class RepairStartEvent extends Event { - private int $max; - private string $current; - public function __construct( - int $max, - string $current, + private int $max, + private string $current, ) { - $this->max = $max; - $this->current = $current; } public function getMaxStep(): int { diff --git a/lib/private/Repair/Events/RepairStepEvent.php b/lib/private/Repair/Events/RepairStepEvent.php index 27e1efbdb08..5c68778f260 100644 --- a/lib/private/Repair/Events/RepairStepEvent.php +++ b/lib/private/Repair/Events/RepairStepEvent.php @@ -11,12 +11,9 @@ namespace OC\Repair\Events; use OCP\EventDispatcher\Event; class RepairStepEvent extends Event { - private string $stepName; - public function __construct( - string $stepName, + private string $stepName, ) { - $this->stepName = $stepName; } public function getStepName(): string { diff --git a/lib/private/Repair/Events/RepairWarningEvent.php b/lib/private/Repair/Events/RepairWarningEvent.php index 6893a7212ec..118965739e8 100644 --- a/lib/private/Repair/Events/RepairWarningEvent.php +++ b/lib/private/Repair/Events/RepairWarningEvent.php @@ -11,12 +11,9 @@ namespace OC\Repair\Events; use OCP\EventDispatcher\Event; class RepairWarningEvent extends Event { - private string $message; - public function __construct( - string $message, + private string $message, ) { - $this->message = $message; } public function getMessage(): string { diff --git a/lib/private/Repair/MoveUpdaterStepFile.php b/lib/private/Repair/MoveUpdaterStepFile.php index bb8f9d3acfc..e7cdfa8036c 100644 --- a/lib/private/Repair/MoveUpdaterStepFile.php +++ b/lib/private/Repair/MoveUpdaterStepFile.php @@ -7,18 +7,17 @@ namespace OC\Repair; use OCP\Files; +use OCP\IConfig; use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class MoveUpdaterStepFile implements IRepairStep { - /** @var \OCP\IConfig */ - protected $config; - /** - * @param \OCP\IConfig $config + * @param IConfig $config */ - public function __construct($config) { - $this->config = $config; + public function __construct( + protected $config, + ) { } public function getName() { diff --git a/lib/private/Repair/NC13/AddLogRotateJob.php b/lib/private/Repair/NC13/AddLogRotateJob.php index bd6c510785f..6c41b602587 100644 --- a/lib/private/Repair/NC13/AddLogRotateJob.php +++ b/lib/private/Repair/NC13/AddLogRotateJob.php @@ -12,11 +12,9 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class AddLogRotateJob implements IRepairStep { - /** @var IJobList */ - private $jobList; - - public function __construct(IJobList $jobList) { - $this->jobList = $jobList; + public function __construct( + private IJobList $jobList, + ) { } public function getName() { diff --git a/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php b/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php index 417bc5e6adc..3419716ada4 100644 --- a/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php +++ b/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php @@ -14,11 +14,9 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class AddPreviewBackgroundCleanupJob implements IRepairStep { - /** @var IJobList */ - private $jobList; - - public function __construct(IJobList $jobList) { - $this->jobList = $jobList; + public function __construct( + private IJobList $jobList, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php b/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php index ab5f93415fc..50dd0050fe1 100644 --- a/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php +++ b/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php @@ -14,11 +14,9 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class AddClenupLoginFlowV2BackgroundJob implements IRepairStep { - /** @var IJobList */ - private $jobList; - - public function __construct(IJobList $jobList) { - $this->jobList = $jobList; + public function __construct( + private IJobList $jobList, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC16/ClearCollectionsAccessCache.php b/lib/private/Repair/NC16/ClearCollectionsAccessCache.php index 1627ed40b98..d6d51eb96a0 100644 --- a/lib/private/Repair/NC16/ClearCollectionsAccessCache.php +++ b/lib/private/Repair/NC16/ClearCollectionsAccessCache.php @@ -15,15 +15,10 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class ClearCollectionsAccessCache implements IRepairStep { - /** @var IConfig */ - private $config; - - /** @var Manager */ - private $manager; - - public function __construct(IConfig $config, IManager $manager) { - $this->config = $config; - $this->manager = $manager; + public function __construct( + private IConfig $config, + private IManager $manager, + ) { } public function getName(): string { @@ -37,7 +32,9 @@ class ClearCollectionsAccessCache implements IRepairStep { public function run(IOutput $output): void { if ($this->shouldRun()) { - $this->manager->invalidateAccessCacheForAllCollections(); + /** @var Manager $man */ + $man = $this->manager; + $man->invalidateAccessCacheForAllCollections(); } } } diff --git a/lib/private/Repair/NC18/ResetGeneratedAvatarFlag.php b/lib/private/Repair/NC18/ResetGeneratedAvatarFlag.php index b0dfec295e7..23bd05a69a7 100644 --- a/lib/private/Repair/NC18/ResetGeneratedAvatarFlag.php +++ b/lib/private/Repair/NC18/ResetGeneratedAvatarFlag.php @@ -14,15 +14,10 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class ResetGeneratedAvatarFlag implements IRepairStep { - /** @var IConfig */ - private $config; - /** @var IDBConnection */ - private $connection; - - public function __construct(IConfig $config, - IDBConnection $connection) { - $this->config = $config; - $this->connection = $connection; + public function __construct( + private IConfig $config, + private IDBConnection $connection, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC20/EncryptionLegacyCipher.php b/lib/private/Repair/NC20/EncryptionLegacyCipher.php index 89473ffd5e8..ca8986e78db 100644 --- a/lib/private/Repair/NC20/EncryptionLegacyCipher.php +++ b/lib/private/Repair/NC20/EncryptionLegacyCipher.php @@ -14,15 +14,10 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class EncryptionLegacyCipher implements IRepairStep { - /** @var IConfig */ - private $config; - /** @var IManager */ - private $manager; - - public function __construct(IConfig $config, - IManager $manager) { - $this->config = $config; - $this->manager = $manager; + public function __construct( + private IConfig $config, + private IManager $manager, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC20/EncryptionMigration.php b/lib/private/Repair/NC20/EncryptionMigration.php index 6de143747b3..91fca99c5d2 100644 --- a/lib/private/Repair/NC20/EncryptionMigration.php +++ b/lib/private/Repair/NC20/EncryptionMigration.php @@ -14,15 +14,10 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class EncryptionMigration implements IRepairStep { - /** @var IConfig */ - private $config; - /** @var IManager */ - private $manager; - - public function __construct(IConfig $config, - IManager $manager) { - $this->config = $config; - $this->manager = $manager; + public function __construct( + private IConfig $config, + private IManager $manager, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC20/ShippedDashboardEnable.php b/lib/private/Repair/NC20/ShippedDashboardEnable.php index 955011a8c84..0050cab67f6 100644 --- a/lib/private/Repair/NC20/ShippedDashboardEnable.php +++ b/lib/private/Repair/NC20/ShippedDashboardEnable.php @@ -13,11 +13,9 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class ShippedDashboardEnable implements IRepairStep { - /** @var IConfig */ - private $config; - - public function __construct(IConfig $config) { - $this->config = $config; + public function __construct( + private IConfig $config, + ) { } public function getName() { diff --git a/lib/private/Repair/NC21/AddCheckForUserCertificatesJob.php b/lib/private/Repair/NC21/AddCheckForUserCertificatesJob.php index 5cee33b381c..e20db9d644b 100644 --- a/lib/private/Repair/NC21/AddCheckForUserCertificatesJob.php +++ b/lib/private/Repair/NC21/AddCheckForUserCertificatesJob.php @@ -13,14 +13,10 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class AddCheckForUserCertificatesJob implements IRepairStep { - /** @var IJobList */ - protected $jobList; - /** @var IConfig */ - private $config; - - public function __construct(IConfig $config, IJobList $jobList) { - $this->jobList = $jobList; - $this->config = $config; + public function __construct( + private IConfig $config, + protected IJobList $jobList, + ) { } public function getName() { diff --git a/lib/private/Repair/NC22/LookupServerSendCheck.php b/lib/private/Repair/NC22/LookupServerSendCheck.php index 540dc2a730d..a7e33557347 100644 --- a/lib/private/Repair/NC22/LookupServerSendCheck.php +++ b/lib/private/Repair/NC22/LookupServerSendCheck.php @@ -15,12 +15,10 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class LookupServerSendCheck implements IRepairStep { - private IJobList $jobList; - private IConfig $config; - - public function __construct(IJobList $jobList, IConfig $config) { - $this->jobList = $jobList; - $this->config = $config; + public function __construct( + private IJobList $jobList, + private IConfig $config, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC24/AddTokenCleanupJob.php b/lib/private/Repair/NC24/AddTokenCleanupJob.php index f1dac2d4e12..44ba97e6482 100644 --- a/lib/private/Repair/NC24/AddTokenCleanupJob.php +++ b/lib/private/Repair/NC24/AddTokenCleanupJob.php @@ -14,10 +14,9 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class AddTokenCleanupJob implements IRepairStep { - private IJobList $jobList; - - public function __construct(IJobList $jobList) { - $this->jobList = $jobList; + public function __construct( + private IJobList $jobList, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC25/AddMissingSecretJob.php b/lib/private/Repair/NC25/AddMissingSecretJob.php index 46b89d5f6f7..c8cd30ae23a 100644 --- a/lib/private/Repair/NC25/AddMissingSecretJob.php +++ b/lib/private/Repair/NC25/AddMissingSecretJob.php @@ -15,12 +15,10 @@ use OCP\Migration\IRepairStep; use OCP\Security\ISecureRandom; class AddMissingSecretJob implements IRepairStep { - private IConfig $config; - private ISecureRandom $random; - - public function __construct(IConfig $config, ISecureRandom $random) { - $this->config = $config; - $this->random = $random; + public function __construct( + private IConfig $config, + private ISecureRandom $random, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC29/SanitizeAccountPropertiesJob.php b/lib/private/Repair/NC29/SanitizeAccountPropertiesJob.php index 55ec445e9da..530805d3637 100644 --- a/lib/private/Repair/NC29/SanitizeAccountPropertiesJob.php +++ b/lib/private/Repair/NC29/SanitizeAccountPropertiesJob.php @@ -38,7 +38,7 @@ class SanitizeAccountPropertiesJob extends QueuedJob { protected function run(mixed $argument): void { $numRemoved = 0; - $this->userManager->callForSeenUsers(function (IUser $user) use (&$numRemoved) { + $this->userManager->callForSeenUsers(function (IUser $user) use (&$numRemoved): void { $account = $this->accountManager->getAccount($user); $properties = array_keys($account->jsonSerialize()); diff --git a/lib/private/Repair/Owncloud/CleanPreviews.php b/lib/private/Repair/Owncloud/CleanPreviews.php index 50ee965e087..52ef3a850c8 100644 --- a/lib/private/Repair/Owncloud/CleanPreviews.php +++ b/lib/private/Repair/Owncloud/CleanPreviews.php @@ -14,15 +14,6 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class CleanPreviews implements IRepairStep { - /** @var IJobList */ - private $jobList; - - /** @var IUserManager */ - private $userManager; - - /** @var IConfig */ - private $config; - /** * MoveAvatars constructor. * @@ -30,12 +21,11 @@ class CleanPreviews implements IRepairStep { * @param IUserManager $userManager * @param IConfig $config */ - public function __construct(IJobList $jobList, - IUserManager $userManager, - IConfig $config) { - $this->jobList = $jobList; - $this->userManager = $userManager; - $this->config = $config; + public function __construct( + private IJobList $jobList, + private IUserManager $userManager, + private IConfig $config, + ) { } /** @@ -47,7 +37,7 @@ class CleanPreviews implements IRepairStep { public function run(IOutput $output) { if (!$this->config->getAppValue('core', 'previewsCleanedUp', false)) { - $this->userManager->callForSeenUsers(function (IUser $user) { + $this->userManager->callForSeenUsers(function (IUser $user): void { $this->jobList->add(CleanPreviewsBackgroundJob::class, ['uid' => $user->getUID()]); }); $this->config->setAppValue('core', 'previewsCleanedUp', '1'); diff --git a/lib/private/Repair/Owncloud/DropAccountTermsTable.php b/lib/private/Repair/Owncloud/DropAccountTermsTable.php index 534825c146a..a7e43f8790d 100644 --- a/lib/private/Repair/Owncloud/DropAccountTermsTable.php +++ b/lib/private/Repair/Owncloud/DropAccountTermsTable.php @@ -11,14 +11,12 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class DropAccountTermsTable implements IRepairStep { - /** @var IDBConnection */ - protected $db; - /** * @param IDBConnection $db */ - public function __construct(IDBConnection $db) { - $this->db = $db; + public function __construct( + protected IDBConnection $db, + ) { } /** diff --git a/lib/private/Repair/Owncloud/MoveAvatars.php b/lib/private/Repair/Owncloud/MoveAvatars.php index 9e3f4b89b13..987767eabbf 100644 --- a/lib/private/Repair/Owncloud/MoveAvatars.php +++ b/lib/private/Repair/Owncloud/MoveAvatars.php @@ -12,22 +12,16 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class MoveAvatars implements IRepairStep { - /** @var IJobList */ - private $jobList; - - /** @var IConfig */ - private $config; - /** * MoveAvatars constructor. * * @param IJobList $jobList * @param IConfig $config */ - public function __construct(IJobList $jobList, - IConfig $config) { - $this->jobList = $jobList; - $this->config = $config; + public function __construct( + private IJobList $jobList, + private IConfig $config, + ) { } /** diff --git a/lib/private/Repair/Owncloud/MoveAvatarsBackgroundJob.php b/lib/private/Repair/Owncloud/MoveAvatarsBackgroundJob.php index e5f80eb31bd..3b8936894e7 100644 --- a/lib/private/Repair/Owncloud/MoveAvatarsBackgroundJob.php +++ b/lib/private/Repair/Owncloud/MoveAvatarsBackgroundJob.php @@ -49,7 +49,7 @@ class MoveAvatarsBackgroundJob extends QueuedJob { } $counter = 0; - $this->userManager->callForSeenUsers(function (IUser $user) use (&$counter) { + $this->userManager->callForSeenUsers(function (IUser $user) use (&$counter): void { $uid = $user->getUID(); $path = 'avatars/' . $this->buildOwnCloudAvatarPath($uid); diff --git a/lib/private/Repair/Owncloud/SaveAccountsTableData.php b/lib/private/Repair/Owncloud/SaveAccountsTableData.php index 7f824925765..0f8a9b07964 100644 --- a/lib/private/Repair/Owncloud/SaveAccountsTableData.php +++ b/lib/private/Repair/Owncloud/SaveAccountsTableData.php @@ -20,21 +20,16 @@ use OCP\PreConditionNotMetException; class SaveAccountsTableData implements IRepairStep { public const BATCH_SIZE = 75; - /** @var IDBConnection */ - protected $db; - - /** @var IConfig */ - protected $config; - protected $hasForeignKeyOnPersistentLocks = false; /** * @param IDBConnection $db * @param IConfig $config */ - public function __construct(IDBConnection $db, IConfig $config) { - $this->db = $db; - $this->config = $config; + public function __construct( + protected IDBConnection $db, + protected IConfig $config, + ) { } /** diff --git a/lib/private/Repair/Owncloud/UpdateLanguageCodes.php b/lib/private/Repair/Owncloud/UpdateLanguageCodes.php index 6bcdd899ec9..fe47e19406d 100644 --- a/lib/private/Repair/Owncloud/UpdateLanguageCodes.php +++ b/lib/private/Repair/Owncloud/UpdateLanguageCodes.php @@ -13,20 +13,14 @@ use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; class UpdateLanguageCodes implements IRepairStep { - /** @var IDBConnection */ - private $connection; - - /** @var IConfig */ - private $config; - /** * @param IDBConnection $connection * @param IConfig $config */ - public function __construct(IDBConnection $connection, - IConfig $config) { - $this->connection = $connection; - $this->config = $config; + public function __construct( + private IDBConnection $connection, + private IConfig $config, + ) { } /** diff --git a/lib/private/Repair/RepairInvalidShares.php b/lib/private/Repair/RepairInvalidShares.php index 627ecf6659d..4c85432969a 100644 --- a/lib/private/Repair/RepairInvalidShares.php +++ b/lib/private/Repair/RepairInvalidShares.php @@ -7,6 +7,7 @@ */ namespace OC\Repair; +use OCP\Constants; use OCP\IConfig; use OCP\IDBConnection; use OCP\Migration\IOutput; @@ -32,7 +33,7 @@ class RepairInvalidShares implements IRepairStep { * Adjust file share permissions */ private function adjustFileSharePermissions(IOutput $output): void { - $mask = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE; + $mask = Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE; $builder = $this->connection->getQueryBuilder(); $permsFunc = $builder->expr()->bitwiseAnd('permissions', $mask); diff --git a/lib/private/Search/FilterFactory.php b/lib/private/Search/FilterFactory.php index 07063c604f4..7a9baf10b4c 100644 --- a/lib/private/Search/FilterFactory.php +++ b/lib/private/Search/FilterFactory.php @@ -8,10 +8,19 @@ declare(strict_types=1); */ namespace OC\Search; +use OC\Search\Filter\BooleanFilter; +use OC\Search\Filter\DateTimeFilter; +use OC\Search\Filter\FloatFilter; +use OC\Search\Filter\GroupFilter; +use OC\Search\Filter\IntegerFilter; +use OC\Search\Filter\StringFilter; +use OC\Search\Filter\StringsFilter; +use OC\Search\Filter\UserFilter; use OCP\IGroupManager; use OCP\IUserManager; use OCP\Search\FilterDefinition; use OCP\Search\IFilter; +use OCP\Server; use RuntimeException; final class FilterFactory { @@ -19,15 +28,15 @@ final class FilterFactory { public static function get(string $type, string|array $filter): IFilter { return match ($type) { - FilterDefinition::TYPE_BOOL => new Filter\BooleanFilter($filter), - FilterDefinition::TYPE_DATETIME => new Filter\DateTimeFilter($filter), - FilterDefinition::TYPE_FLOAT => new Filter\FloatFilter($filter), - FilterDefinition::TYPE_INT => new Filter\IntegerFilter($filter), - FilterDefinition::TYPE_NC_GROUP => new Filter\GroupFilter($filter, \OC::$server->get(IGroupManager::class)), - FilterDefinition::TYPE_NC_USER => new Filter\UserFilter($filter, \OC::$server->get(IUserManager::class)), + FilterDefinition::TYPE_BOOL => new BooleanFilter($filter), + FilterDefinition::TYPE_DATETIME => new DateTimeFilter($filter), + FilterDefinition::TYPE_FLOAT => new FloatFilter($filter), + FilterDefinition::TYPE_INT => new IntegerFilter($filter), + FilterDefinition::TYPE_NC_GROUP => new GroupFilter($filter, Server::get(IGroupManager::class)), + FilterDefinition::TYPE_NC_USER => new UserFilter($filter, Server::get(IUserManager::class)), FilterDefinition::TYPE_PERSON => self::getPerson($filter), - FilterDefinition::TYPE_STRING => new Filter\StringFilter($filter), - FilterDefinition::TYPE_STRINGS => new Filter\StringsFilter(... (array)$filter), + FilterDefinition::TYPE_STRING => new StringFilter($filter), + FilterDefinition::TYPE_STRINGS => new StringsFilter(... (array)$filter), default => throw new RuntimeException('Invalid filter type ' . $type), }; } diff --git a/lib/private/Security/CSRF/CsrfTokenManager.php b/lib/private/Security/CSRF/CsrfTokenManager.php index 00e1be5bedf..ab24de33a1d 100644 --- a/lib/private/Security/CSRF/CsrfTokenManager.php +++ b/lib/private/Security/CSRF/CsrfTokenManager.php @@ -16,14 +16,12 @@ use OC\Security\CSRF\TokenStorage\SessionStorage; * @package OC\Security\CSRF */ class CsrfTokenManager { - private SessionStorage $sessionStorage; private ?CsrfToken $csrfToken = null; public function __construct( private CsrfTokenGenerator $tokenGenerator, - SessionStorage $storageInterface, + private SessionStorage $sessionStorage, ) { - $this->sessionStorage = $storageInterface; } /** diff --git a/lib/private/Security/Certificate.php b/lib/private/Security/Certificate.php index 09e01ff99f7..81c2b9461a3 100644 --- a/lib/private/Security/Certificate.php +++ b/lib/private/Security/Certificate.php @@ -11,8 +11,6 @@ namespace OC\Security; use OCP\ICertificate; class Certificate implements ICertificate { - protected string $name; - protected ?string $commonName; protected ?string $organization; @@ -30,8 +28,10 @@ class Certificate implements ICertificate { * @param string $data base64 encoded certificate * @throws \Exception If the certificate could not get parsed */ - public function __construct(string $data, string $name) { - $this->name = $name; + public function __construct( + string $data, + protected string $name, + ) { $gmt = new \DateTimeZone('GMT'); // If string starts with "file://" ignore the certificate diff --git a/lib/private/Security/CertificateManager.php b/lib/private/Security/CertificateManager.php index d8a988261db..5dfeed1c07a 100644 --- a/lib/private/Security/CertificateManager.php +++ b/lib/private/Security/CertificateManager.php @@ -32,7 +32,7 @@ class CertificateManager implements ICertificateManager { /** * Returns all certificates trusted by the user * - * @return \OCP\ICertificate[] + * @return ICertificate[] */ public function listCertificates(): array { if (!$this->config->getSystemValueBool('installed', false)) { diff --git a/lib/private/Security/Normalizer/IpAddress.php b/lib/private/Security/Normalizer/IpAddress.php index eee6489ddd3..70884e6f769 100644 --- a/lib/private/Security/Normalizer/IpAddress.php +++ b/lib/private/Security/Normalizer/IpAddress.php @@ -9,6 +9,7 @@ declare(strict_types=1); namespace OC\Security\Normalizer; use OCP\IConfig; +use OCP\Server; /** * Class IpAddress is used for normalizing IPv4 and IPv6 addresses in security @@ -40,7 +41,7 @@ class IpAddress { $ip = substr($ip, 0, $pos); } - $config = \OCP\Server::get(IConfig::class); + $config = Server::get(IConfig::class); $maskSize = min(64, max(32, $config->getSystemValueInt('security.ipv6_normalized_subnet_size', 56))); $binary = inet_pton($ip); diff --git a/lib/private/Server.php b/lib/private/Server.php index a14ff622647..22c6a81d715 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -15,13 +15,16 @@ use OC\AppFramework\Bootstrap\Coordinator; use OC\AppFramework\Http\Request; use OC\AppFramework\Http\RequestId; use OC\AppFramework\Services\AppConfig; +use OC\AppFramework\Utility\ControllerMethodReflector; use OC\AppFramework\Utility\TimeFactory; use OC\Authentication\Events\LoginFailed; use OC\Authentication\Listeners\LoginFailedListener; use OC\Authentication\Listeners\UserLoggedInListener; use OC\Authentication\LoginCredentials\Store; use OC\Authentication\Token\IProvider; +use OC\Authentication\TwoFactorAuth\Registry; use OC\Avatar\AvatarManager; +use OC\BackgroundJob\JobList; use OC\Blurhash\Listener\GenerateBlurhashMetadata; use OC\Collaboration\Collaborators\GroupPlugin; use OC\Collaboration\Collaborators\MailByMailPlugin; @@ -30,14 +33,20 @@ use OC\Collaboration\Collaborators\RemotePlugin; use OC\Collaboration\Collaborators\UserByMailPlugin; use OC\Collaboration\Collaborators\UserPlugin; use OC\Collaboration\Reference\ReferenceManager; +use OC\Collaboration\Resources\ProviderManager; use OC\Command\CronBus; use OC\Comments\ManagerFactory as CommentsManagerFactory; +use OC\Config\UserConfig; use OC\Contacts\ContactsMenu\ActionFactory; use OC\Contacts\ContactsMenu\ContactsStore; use OC\DB\Connection; use OC\DB\ConnectionAdapter; +use OC\DB\ConnectionFactory; use OC\Diagnostics\EventLogger; use OC\Diagnostics\QueryLogger; +use OC\Encryption\File; +use OC\Encryption\Keys\Storage; +use OC\EventDispatcher\EventDispatcher; use OC\Federation\CloudFederationFactory; use OC\Federation\CloudFederationProviderManager; use OC\Federation\CloudIdManager; @@ -46,6 +55,8 @@ use OC\Files\Config\MountProviderCollection; use OC\Files\Config\UserMountCache; use OC\Files\Config\UserMountCacheListener; use OC\Files\Conversion\ConversionManager; +use OC\Files\FilenameValidator; +use OC\Files\Filesystem; use OC\Files\Lock\LockManager; use OC\Files\Mount\CacheMountProvider; use OC\Files\Mount\LocalHomeMountProvider; @@ -58,6 +69,7 @@ use OC\Files\ObjectStore\PrimaryObjectStoreConfig; use OC\Files\SetupManager; use OC\Files\Storage\StorageFactory; use OC\Files\Template\TemplateManager; +use OC\Files\Type\Detection; use OC\Files\Type\Loader; use OC\Files\View; use OC\FilesMetadata\FilesMetadataManager; @@ -79,22 +91,28 @@ use OC\Mail\EmailValidator; use OC\Mail\Mailer; use OC\Memcache\ArrayCache; use OC\Memcache\Factory; +use OC\Memcache\NullCache; +use OC\Memcache\Redis; use OC\Notification\Manager; use OC\OCM\Model\OCMProvider; use OC\OCM\OCMDiscoveryService; +use OC\OCS\CoreCapabilities; use OC\OCS\DiscoveryService; use OC\Preview\Db\PreviewMapper; use OC\Preview\GeneratorHelper; use OC\Preview\IMagickSupport; use OC\Preview\MimeIconProvider; use OC\Preview\Watcher; +use OC\Preview\WatcherConnector; use OC\Profile\ProfileManager; use OC\Profiler\Profiler; use OC\Remote\Api\ApiFactory; use OC\Remote\InstanceFactory; +use OC\RichObjectStrings\RichTextFormatter; use OC\RichObjectStrings\Validator; use OC\Route\CachingRouter; use OC\Route\Router; +use OC\Security\Bruteforce\Capabilities; use OC\Security\Bruteforce\Throttler; use OC\Security\CertificateManager; use OC\Security\CredentialsManager; @@ -106,14 +124,17 @@ use OC\Security\CSRF\TokenStorage\SessionStorage; use OC\Security\Hasher; use OC\Security\Ip\RemoteAddress; use OC\Security\RateLimiting\Limiter; +use OC\Security\RemoteHostValidator; use OC\Security\SecureRandom; use OC\Security\Signature\SignatureManager; use OC\Security\TrustedDomainHelper; use OC\Security\VerificationToken\VerificationToken; use OC\Session\CryptoWrapper; +use OC\Session\Memory; use OC\Settings\DeclarativeManager; use OC\SetupCheck\SetupCheckManager; use OC\Share20\ProviderFactory; +use OC\Share20\PublicShareTemplateFactory; use OC\Share20\ShareHelper; use OC\Snowflake\APCuSequence; use OC\Snowflake\FileSequence; @@ -121,6 +142,7 @@ use OC\Snowflake\ISequence; use OC\Snowflake\SnowflakeDecoder; use OC\Snowflake\SnowflakeGenerator; use OC\SpeechToText\SpeechToTextManager; +use OC\Support\Subscription\Assertion; use OC\SystemTag\ManagerFactory as SystemTagManagerFactory; use OC\Talk\Broker; use OC\Teams\TeamManager; @@ -131,19 +153,24 @@ use OC\User\DisplayNameCache; use OC\User\Listeners\BeforeUserDeletedListener; use OC\User\Listeners\UserChangedListener; use OC\User\Session; +use OC\User\User; use OCA\Theming\ImageManager; use OCA\Theming\Service\BackgroundService; use OCA\Theming\ThemingDefaults; use OCA\Theming\Util; use OCP\Accounts\IAccountManager; use OCP\App\IAppManager; +use OCP\AppFramework\Utility\IControllerMethodReflector; use OCP\AppFramework\Utility\ITimeFactory; use OCP\Authentication\LoginCredentials\IStore; use OCP\Authentication\Token\IProvider as OCPIProvider; +use OCP\Authentication\TwoFactorAuth\IRegistry; +use OCP\AutoloadNotAllowedException; use OCP\BackgroundJob\IJobList; use OCP\Collaboration\Reference\IReferenceManager; use OCP\Command\IBus; use OCP\Comments\ICommentsManager; +use OCP\Comments\ICommentsManagerFactory; use OCP\Config\IUserConfig; use OCP\Contacts\ContactsMenu\IActionFactory; use OCP\Contacts\ContactsMenu\IContactsStore; @@ -161,6 +188,9 @@ use OCP\Files\Cache\IFileAccess; use OCP\Files\Config\IMountProviderCollection; use OCP\Files\Config\IUserMountCache; use OCP\Files\Conversion\IConversionManager; +use OCP\Files\Folder; +use OCP\Files\IAppData; +use OCP\Files\IFilenameValidator; use OCP\Files\IMimeTypeDetector; use OCP\Files\IMimeTypeLoader; use OCP\Files\IRootFolder; @@ -182,6 +212,7 @@ use OCP\IConfig; use OCP\IDateTimeFormatter; use OCP\IDateTimeZone; use OCP\IDBConnection; +use OCP\IEmojiHelper; use OCP\IEventSourceFactory; use OCP\IGroupManager; use OCP\IInitialStateService; @@ -193,6 +224,7 @@ use OCP\IRequest; use OCP\IRequestId; use OCP\IServerContainer; use OCP\ISession; +use OCP\ITagManager; use OCP\ITempManager; use OCP\IURLGenerator; use OCP\IUserManager; @@ -258,16 +290,15 @@ use Psr\Log\LoggerInterface; * TODO: hookup all manager classes */ class Server extends ServerContainer implements IServerContainer { - /** @var string */ - private $webRoot; - /** * @param string $webRoot - * @param \OC\Config $config + * @param Config $config */ - public function __construct($webRoot, \OC\Config $config) { + public function __construct( + private $webRoot, + Config $config, + ) { parent::__construct(); - $this->webRoot = $webRoot; // To find out if we are running from CLI or not $this->registerParameter('isCLI', \OC::$CLI); @@ -276,7 +307,7 @@ class Server extends ServerContainer implements IServerContainer { $this->registerService(ContainerInterface::class, function (ContainerInterface $c) { return $c; }); - $this->registerDeprecatedAlias(\OCP\IServerContainer::class, ContainerInterface::class); + $this->registerDeprecatedAlias(IServerContainer::class, ContainerInterface::class); $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class); @@ -284,7 +315,7 @@ class Server extends ServerContainer implements IServerContainer { $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class); - $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class); + $this->registerAlias(\OCP\Contacts\IManager::class, ContactsManager::class); $this->registerAlias(\OCP\ContextChat\IContentManager::class, \OC\ContextChat\ContentManager::class); $this->registerAlias(\OCP\Files\ISetupManager::class, \OC\Files\SetupManager::class); @@ -301,7 +332,7 @@ class Server extends ServerContainer implements IServerContainer { $this->registerService(IPreview::class, function (ContainerInterface $c) { return new PreviewManager( - $c->get(\OCP\IConfig::class), + $c->get(IConfig::class), $c->get(IRootFolder::class), $c->get(IEventDispatcher::class), $c->get(GeneratorHelper::class), @@ -332,10 +363,10 @@ class Server extends ServerContainer implements IServerContainer { $view, $c->get(IUserManager::class), $c->get(IGroupManager::class), - $c->get(\OCP\IConfig::class) + $c->get(IConfig::class) ); return new Encryption\Manager( - $c->get(\OCP\IConfig::class), + $c->get(IConfig::class), $c->get(LoggerInterface::class), $c->getL10N('core'), new View(), @@ -350,9 +381,9 @@ class Server extends ServerContainer implements IServerContainer { new View(), $c->get(IUserManager::class), $c->get(IGroupManager::class), - $c->get(\OCP\IConfig::class) + $c->get(IConfig::class) ); - return new Encryption\File( + return new File( $util, $c->get(IRootFolder::class), $c->get(\OCP\Share\IManager::class) @@ -365,22 +396,22 @@ class Server extends ServerContainer implements IServerContainer { $view, $c->get(IUserManager::class), $c->get(IGroupManager::class), - $c->get(\OCP\IConfig::class) + $c->get(IConfig::class) ); - return new Encryption\Keys\Storage( + return new Storage( $view, $util, $c->get(ICrypto::class), - $c->get(\OCP\IConfig::class) + $c->get(IConfig::class) ); }); - $this->registerAlias(\OCP\ITagManager::class, TagManager::class); + $this->registerAlias(ITagManager::class, TagManager::class); $this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) { - /** @var \OCP\IConfig $config */ - $config = $c->get(\OCP\IConfig::class); + /** @var IConfig $config */ + $config = $c->get(IConfig::class); $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class); return new $factoryClass($this); }); @@ -395,7 +426,7 @@ class Server extends ServerContainer implements IServerContainer { }); $this->registerAlias(IFileAccess::class, FileAccess::class); $this->registerService('RootFolder', function (ContainerInterface $c) { - $manager = \OC\Files\Filesystem::getMountManager(); + $manager = Filesystem::getMountManager(); $view = new View(); /** @var IUserSession $userSession */ $userSession = $c->get(IUserSession::class); @@ -411,7 +442,7 @@ class Server extends ServerContainer implements IServerContainer { $this->get(IAppConfig::class), ); - $previewConnector = new \OC\Preview\WatcherConnector( + $previewConnector = new WatcherConnector( $root, $c->get(SystemConfig::class), $this->get(IEventDispatcher::class) @@ -435,13 +466,13 @@ class Server extends ServerContainer implements IServerContainer { }); }); - $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class); + $this->registerAlias(IUserManager::class, \OC\User\Manager::class); $this->registerService(DisplayNameCache::class, function (ContainerInterface $c) { return $c->get(\OC\User\Manager::class)->getDisplayNameCache(); }); - $this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) { + $this->registerService(IGroupManager::class, function (ContainerInterface $c) { $groupManager = new \OC\Group\Manager( $this->get(IUserManager::class), $this->get(IEventDispatcher::class), @@ -454,7 +485,7 @@ class Server extends ServerContainer implements IServerContainer { $this->registerService(Store::class, function (ContainerInterface $c) { $session = $c->get(ISession::class); - if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) { + if (\OCP\Server::get(SystemConfig::class)->getValue('installed', false)) { $tokenProvider = $c->get(IProvider::class); } else { $tokenProvider = null; @@ -467,121 +498,121 @@ class Server extends ServerContainer implements IServerContainer { $this->registerAlias(IProvider::class, Authentication\Token\Manager::class); $this->registerAlias(OCPIProvider::class, Authentication\Token\Manager::class); - $this->registerService(\OC\User\Session::class, function (Server $c) { + $this->registerService(Session::class, function (Server $c) { $manager = $c->get(IUserManager::class); - $session = new \OC\Session\Memory(); + $session = new Memory(); $timeFactory = new TimeFactory(); // Token providers might require a working database. This code // might however be called when Nextcloud is not yet setup. - if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) { + if (\OCP\Server::get(SystemConfig::class)->getValue('installed', false)) { $provider = $c->get(IProvider::class); } else { $provider = null; } - $userSession = new \OC\User\Session( + $userSession = new Session( $manager, $session, $timeFactory, $provider, - $c->get(\OCP\IConfig::class), + $c->get(IConfig::class), $c->get(ISecureRandom::class), $c->get('LockdownManager'), $c->get(LoggerInterface::class), $c->get(IEventDispatcher::class), ); /** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */ - $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) { + $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password): void { \OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]); }); /** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */ - $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) { - /** @var \OC\User\User $user */ + $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password): void { + /** @var User $user */ \OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]); }); /** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */ - $userSession->listen('\OC\User', 'preDelete', function ($user) { - /** @var \OC\User\User $user */ + $userSession->listen('\OC\User', 'preDelete', function ($user): void { + /** @var User $user */ \OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]); }); /** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */ - $userSession->listen('\OC\User', 'postDelete', function ($user) { - /** @var \OC\User\User $user */ + $userSession->listen('\OC\User', 'postDelete', function ($user): void { + /** @var User $user */ \OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]); }); - $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) { - /** @var \OC\User\User $user */ + $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword): void { + /** @var User $user */ \OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]); }); - $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) { - /** @var \OC\User\User $user */ + $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword): void { + /** @var User $user */ \OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]); }); - $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) { + $userSession->listen('\OC\User', 'preLogin', function ($uid, $password): void { \OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->get(IEventDispatcher::class); $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password)); }); - $userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) { - /** @var \OC\User\User $user */ + $userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin): void { + /** @var User $user */ \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->get(IEventDispatcher::class); $dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin)); }); - $userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) { + $userSession->listen('\OC\User', 'preRememberedLogin', function ($uid): void { /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->get(IEventDispatcher::class); $dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid)); }); - $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) { - /** @var \OC\User\User $user */ + $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password): void { + /** @var User $user */ \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->get(IEventDispatcher::class); $dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password)); }); - $userSession->listen('\OC\User', 'logout', function ($user) { + $userSession->listen('\OC\User', 'logout', function ($user): void { \OC_Hook::emit('OC_User', 'logout', []); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->get(IEventDispatcher::class); $dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user)); }); - $userSession->listen('\OC\User', 'postLogout', function ($user) { + $userSession->listen('\OC\User', 'postLogout', function ($user): void { /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->get(IEventDispatcher::class); $dispatcher->dispatchTyped(new UserLoggedOutEvent($user)); }); - $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) { - /** @var \OC\User\User $user */ + $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue): void { + /** @var User $user */ \OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]); }); return $userSession; }); - $this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class); + $this->registerAlias(IUserSession::class, Session::class); - $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class); + $this->registerAlias(IRegistry::class, Registry::class); - $this->registerAlias(INavigationManager::class, \OC\NavigationManager::class); + $this->registerAlias(INavigationManager::class, NavigationManager::class); - $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class); + $this->registerAlias(IConfig::class, AllConfig::class); - $this->registerService(\OC\SystemConfig::class, function ($c) use ($config) { - return new \OC\SystemConfig($config); + $this->registerService(SystemConfig::class, function ($c) use ($config) { + return new SystemConfig($config); }); $this->registerAlias(IAppConfig::class, \OC\AppConfig::class); - $this->registerAlias(IUserConfig::class, \OC\Config\UserConfig::class); + $this->registerAlias(IUserConfig::class, UserConfig::class); $this->registerAlias(IAppManager::class, AppManager::class); $this->registerService(IFactory::class, function (Server $c) { return new \OC\L10N\Factory( - $c->get(\OCP\IConfig::class), + $c->get(IConfig::class), $c->getRequest(), $c->get(IUserSession::class), $c->get(ICacheFactory::class), @@ -600,7 +631,7 @@ class Server extends ServerContainer implements IServerContainer { /** @var SystemConfig $config */ $config = $c->get(SystemConfig::class); if (!$config->getValue('installed', false) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) { - return new \OC\Memcache\Factory( + return new Factory( $logger, $profiler, $serverVersion, @@ -610,7 +641,7 @@ class Server extends ServerContainer implements IServerContainer { ); } - return new \OC\Memcache\Factory( + return new Factory( $logger, $profiler, $serverVersion, @@ -636,7 +667,7 @@ class Server extends ServerContainer implements IServerContainer { return new \OC\Activity\Manager( $c->getRequest(), $c->get(IUserSession::class), - $c->get(\OCP\IConfig::class), + $c->get(IConfig::class), $c->get(IValidator::class), $c->get(IRichTextFormatter::class), $l10n, @@ -658,7 +689,7 @@ class Server extends ServerContainer implements IServerContainer { $c->getAppDataDir('avatar'), $c->getL10N('lib'), $c->get(LoggerInterface::class), - $c->get(\OCP\IConfig::class), + $c->get(IConfig::class), $c->get(IAccountManager::class), $c->get(KnownUserService::class) ); @@ -668,10 +699,10 @@ class Server extends ServerContainer implements IServerContainer { $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class); $this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class); - $this->registerAlias(\OCP\Support\Subscription\IAssertion::class, \OC\Support\Subscription\Assertion::class); + $this->registerAlias(\OCP\Support\Subscription\IAssertion::class, Assertion::class); /** Only used by the PsrLoggerAdapter should not be used by apps */ - $this->registerService(\OC\Log::class, function (Server $c) { + $this->registerService(Log::class, function (Server $c) { $logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file'); $factory = new LogFactory($c, $this->get(SystemConfig::class)); $logger = $factory->get($logType); @@ -686,7 +717,7 @@ class Server extends ServerContainer implements IServerContainer { return new LogFactory($c, $this->get(SystemConfig::class)); }); - $this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class); + $this->registerAlias(IJobList::class, JobList::class); $this->registerService(Router::class, function (Server $c) { $cacheFactory = $c->get(ICacheFactory::class); @@ -700,26 +731,26 @@ class Server extends ServerContainer implements IServerContainer { $this->registerAlias(IRouter::class, Router::class); $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) { - $config = $c->get(\OCP\IConfig::class); - if (ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) { + $config = $c->get(IConfig::class); + if (ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === Redis::class) { $backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend( $c->get(AllConfig::class), $this->get(ICacheFactory::class), - new \OC\AppFramework\Utility\TimeFactory() + new TimeFactory() ); } else { $backend = new \OC\Security\RateLimiting\Backend\DatabaseBackend( $c->get(AllConfig::class), $c->get(IDBConnection::class), - new \OC\AppFramework\Utility\TimeFactory() + new TimeFactory() ); } return $backend; }); - $this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class); - $this->registerAlias(\OCP\Security\IRemoteHostValidator::class, \OC\Security\RemoteHostValidator::class); + $this->registerAlias(ISecureRandom::class, SecureRandom::class); + $this->registerAlias(\OCP\Security\IRemoteHostValidator::class, RemoteHostValidator::class); $this->registerAlias(IVerificationToken::class, VerificationToken::class); $this->registerAlias(ICrypto::class, Crypto::class); @@ -731,10 +762,10 @@ class Server extends ServerContainer implements IServerContainer { $this->registerAlias(IDBConnection::class, ConnectionAdapter::class); $this->registerService(Connection::class, function (Server $c) { $systemConfig = $c->get(SystemConfig::class); - $factory = new \OC\DB\ConnectionFactory($systemConfig, $c->get(ICacheFactory::class)); + $factory = new ConnectionFactory($systemConfig, $c->get(ICacheFactory::class)); $type = $systemConfig->getValue('dbtype', 'sqlite'); if (!$factory->isValidType($type)) { - throw new \OC\DatabaseException('Invalid database type'); + throw new DatabaseException('Invalid database type'); } $connection = $factory->getConnection($type, []); return $connection; @@ -765,7 +796,7 @@ class Server extends ServerContainer implements IServerContainer { $this->registerAlias(IDateTimeZone::class, DateTimeZone::class); $this->registerService(IDateTimeFormatter::class, function (Server $c) { - $language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null); + $language = $c->get(IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null); return new DateTimeFormatter( $c->get(IDateTimeZone::class)->getTimeZone(), @@ -788,7 +819,7 @@ class Server extends ServerContainer implements IServerContainer { // builtin providers - $config = $c->get(\OCP\IConfig::class); + $config = $c->get(IConfig::class); $logger = $c->get(LoggerInterface::class); $objectStoreConfig = $c->get(PrimaryObjectStoreConfig::class); $manager->registerProvider(new CacheMountProvider($config)); @@ -800,7 +831,7 @@ class Server extends ServerContainer implements IServerContainer { }); $this->registerService(IBus::class, function (ContainerInterface $c) { - $busClass = $c->get(\OCP\IConfig::class)->getSystemValueString('commandbus'); + $busClass = $c->get(IConfig::class)->getSystemValueString('commandbus'); if ($busClass) { [$app, $class] = explode('::', $busClass, 2); if ($c->get(IAppManager::class)->isEnabledForUser($app)) { @@ -819,9 +850,9 @@ class Server extends ServerContainer implements IServerContainer { $this->registerAlias(IThrottler::class, Throttler::class); $this->registerService(\OC\Security\Bruteforce\Backend\IBackend::class, function ($c) { - $config = $c->get(\OCP\IConfig::class); + $config = $c->get(IConfig::class); if (!$config->getSystemValueBool('auth.bruteforce.protection.force.database', false) - && ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) { + && ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === Redis::class) { $backend = $c->get(\OC\Security\Bruteforce\Backend\MemoryCacheBackend::class); } else { $backend = $c->get(\OC\Security\Bruteforce\Backend\DatabaseBackend::class); @@ -834,9 +865,9 @@ class Server extends ServerContainer implements IServerContainer { $this->registerService(Checker::class, function (ContainerInterface $c) { // IConfig requires a working database. This code // might however be called when Nextcloud is not yet setup. - if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) { - $config = $c->get(\OCP\IConfig::class); - $appConfig = $c->get(\OCP\IAppConfig::class); + if (\OCP\Server::get(SystemConfig::class)->getValue('installed', false)) { + $config = $c->get(IConfig::class); + $appConfig = $c->get(IAppConfig::class); } else { $config = null; $appConfig = null; @@ -882,12 +913,12 @@ class Server extends ServerContainer implements IServerContainer { 'urlParams' => $urlParams, ], $this->get(IRequestId::class), - $this->get(\OCP\IConfig::class), + $this->get(IConfig::class), $this->get(CsrfTokenManager::class), $stream ); }); - $this->registerAlias(\OCP\IRequest::class, Request::class); + $this->registerAlias(IRequest::class, Request::class); $this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId { return new RequestId( @@ -901,7 +932,7 @@ class Server extends ServerContainer implements IServerContainer { $this->registerService(IMailer::class, function (Server $c) { return new Mailer( - $c->get(\OCP\IConfig::class), + $c->get(IConfig::class), $c->get(LoggerInterface::class), $c->get(Defaults::class), $c->get(IURLGenerator::class), @@ -916,12 +947,12 @@ class Server extends ServerContainer implements IServerContainer { $this->registerAlias(\OCP\Mail\Provider\IManager::class, \OC\Mail\Provider\Manager::class); $this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) { - $config = $c->get(\OCP\IConfig::class); + $config = $c->get(IConfig::class); $factoryClass = $config->getSystemValue('ldapProviderFactory', null); if (is_null($factoryClass) || !class_exists($factoryClass)) { return new NullLDAPProviderFactory($this); } - /** @var \OCP\LDAP\ILDAPProviderFactory $factory */ + /** @var ILDAPProviderFactory $factory */ return new $factoryClass($this); }); $this->registerService(ILDAPProvider::class, function (ContainerInterface $c) { @@ -930,13 +961,13 @@ class Server extends ServerContainer implements IServerContainer { }); $this->registerService(ILockingProvider::class, function (ContainerInterface $c) { $ini = $c->get(IniGetWrapper::class); - $config = $c->get(\OCP\IConfig::class); + $config = $c->get(IConfig::class); $ttl = $config->getSystemValueInt('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time'))); if ($config->getSystemValueBool('filelocking.enabled', true) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) { - /** @var \OC\Memcache\Factory $memcacheFactory */ + /** @var Factory $memcacheFactory */ $memcacheFactory = $c->get(ICacheFactory::class); $memcache = $memcacheFactory->createLocking('lock'); - if (!($memcache instanceof \OC\Memcache\NullCache)) { + if (!($memcache instanceof NullCache)) { $timeFactory = $c->get(ITimeFactory::class); return new MemcacheLockingProvider($memcache, $timeFactory, $ttl); } @@ -962,7 +993,7 @@ class Server extends ServerContainer implements IServerContainer { $this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class); $this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) { - return new \OC\Files\Type\Detection( + return new Detection( $c->get(IURLGenerator::class), $c->get(LoggerInterface::class), \OC::$configDir, @@ -979,18 +1010,18 @@ class Server extends ServerContainer implements IServerContainer { $this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) { $manager = new CapabilitiesManager($c->get(LoggerInterface::class)); $manager->registerCapability(function () use ($c) { - return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class)); + return new CoreCapabilities($c->get(IConfig::class)); }); $manager->registerCapability(function () use ($c) { - return $c->get(\OC\Security\Bruteforce\Capabilities::class); + return $c->get(Capabilities::class); }); return $manager; }); $this->registerService(ICommentsManager::class, function (Server $c) { - $config = $c->get(\OCP\IConfig::class); + $config = $c->get(IConfig::class); $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class); - /** @var \OCP\Comments\ICommentsManagerFactory $factory */ + /** @var ICommentsManagerFactory $factory */ $factory = new $factoryClass($this); $manager = $factory->getManager(); @@ -1011,21 +1042,21 @@ class Server extends ServerContainer implements IServerContainer { $this->registerService('ThemingDefaults', function (Server $c) { try { $classExists = class_exists('OCA\Theming\ThemingDefaults'); - } catch (\OCP\AutoloadNotAllowedException $e) { + } catch (AutoloadNotAllowedException $e) { // App disabled or in maintenance mode $classExists = false; } - if ($classExists && $c->get(\OCP\IConfig::class)->getSystemValueBool('installed', false) && $c->get(IAppManager::class)->isEnabledForAnyone('theming') && $c->get(TrustedDomainHelper::class)->isTrustedDomain($c->getRequest()->getInsecureServerHost())) { + if ($classExists && $c->get(IConfig::class)->getSystemValueBool('installed', false) && $c->get(IAppManager::class)->isEnabledForAnyone('theming') && $c->get(TrustedDomainHelper::class)->isTrustedDomain($c->getRequest()->getInsecureServerHost())) { $backgroundService = new BackgroundService( $c->get(IRootFolder::class), $c->get(IAppDataFactory::class)->get('theming'), $c->get(IAppConfig::class), - $c->get(\OCP\IConfig::class), + $c->get(IConfig::class), $c->get(ISession::class)->get('user_id'), ); $imageManager = new ImageManager( - $c->get(\OCP\IConfig::class), + $c->get(IConfig::class), $c->get(IAppDataFactory::class)->get('theming'), $c->get(IURLGenerator::class), $c->get(ICacheFactory::class), @@ -1035,8 +1066,8 @@ class Server extends ServerContainer implements IServerContainer { ); return new ThemingDefaults( new AppConfig( - $c->get(\OCP\IConfig::class), - $c->get(\OCP\IAppConfig::class), + $c->get(IConfig::class), + $c->get(IAppConfig::class), 'theming', ), $c->get(IUserConfig::class), @@ -1046,7 +1077,7 @@ class Server extends ServerContainer implements IServerContainer { $c->get(ICacheFactory::class), new Util( $c->get(ServerVersion::class), - $c->get(\OCP\IConfig::class), + $c->get(IConfig::class), $this->get(IAppManager::class), $c->get(IAppDataFactory::class)->get('theming'), $imageManager, @@ -1064,11 +1095,11 @@ class Server extends ServerContainer implements IServerContainer { $c->getAppDataDir('js'), $c->get(IURLGenerator::class), $this->get(ICacheFactory::class), - $c->get(\OCP\IConfig::class), + $c->get(IConfig::class), $c->get(LoggerInterface::class) ); }); - $this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class); + $this->registerAlias(IEventDispatcher::class, EventDispatcher::class); $this->registerService('CryptoWrapper', function (ContainerInterface $c) { // FIXME: Instantiated here due to cyclic dependency @@ -1085,7 +1116,7 @@ class Server extends ServerContainer implements IServerContainer { : null, ], $c->get(IRequestId::class), - $c->get(\OCP\IConfig::class) + $c->get(IConfig::class) ); return new CryptoWrapper( @@ -1100,16 +1131,16 @@ class Server extends ServerContainer implements IServerContainer { $this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class); $this->registerService(IProviderFactory::class, function (ContainerInterface $c) { - $config = $c->get(\OCP\IConfig::class); + $config = $c->get(IConfig::class); $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class); - /** @var \OCP\Share\IProviderFactory $factory */ + /** @var IProviderFactory $factory */ return $c->get($factoryClass); }); $this->registerAlias(\OCP\Share\IManager::class, \OC\Share20\Manager::class); - $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) { - $instance = new Collaboration\Collaborators\Search($c); + $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c): \OCP\Collaboration\Collaborators\ISearch { + $instance = new \OC\Collaboration\Collaborators\Search($c); // register default plugins $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]); @@ -1125,7 +1156,7 @@ class Server extends ServerContainer implements IServerContainer { $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class); - $this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class); + $this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, ProviderManager::class); $this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class); $this->registerAlias(IReferenceManager::class, ReferenceManager::class); @@ -1146,7 +1177,7 @@ class Server extends ServerContainer implements IServerContainer { }); }); - $this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) { + $this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c): \OCP\OCS\IDiscoveryService { return new DiscoveryService( $c->get(ICacheFactory::class), $c->get(IClientService::class) @@ -1170,10 +1201,10 @@ class Server extends ServerContainer implements IServerContainer { return new CloudFederationFactory(); }); - $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class); + $this->registerAlias(IControllerMethodReflector::class, ControllerMethodReflector::class); - $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class); - $this->registerAlias(\Psr\Clock\ClockInterface::class, \OCP\AppFramework\Utility\ITimeFactory::class); + $this->registerAlias(ITimeFactory::class, TimeFactory::class); + $this->registerAlias(\Psr\Clock\ClockInterface::class, ITimeFactory::class); $this->registerService(Defaults::class, function (Server $c) { return new Defaults( @@ -1181,8 +1212,8 @@ class Server extends ServerContainer implements IServerContainer { ); }); - $this->registerService(\OCP\ISession::class, function (ContainerInterface $c) { - return $c->get(\OCP\IUserSession::class)->getSession(); + $this->registerService(ISession::class, function (ContainerInterface $c) { + return $c->get(IUserSession::class)->getSession(); }, false); $this->registerService(IShareHelper::class, function (ContainerInterface $c) { @@ -1214,19 +1245,19 @@ class Server extends ServerContainer implements IServerContainer { $this->registerAlias(IInitialStateService::class, InitialStateService::class); - $this->registerAlias(\OCP\IEmojiHelper::class, \OC\EmojiHelper::class); + $this->registerAlias(IEmojiHelper::class, EmojiHelper::class); $this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class); $this->registerAlias(IBroker::class, Broker::class); - $this->registerAlias(\OCP\Files\AppData\IAppDataFactory::class, \OC\Files\AppData\Factory::class); + $this->registerAlias(IAppDataFactory::class, \OC\Files\AppData\Factory::class); - $this->registerAlias(\OCP\Files\IFilenameValidator::class, \OC\Files\FilenameValidator::class); + $this->registerAlias(IFilenameValidator::class, FilenameValidator::class); $this->registerAlias(IBinaryFinder::class, BinaryFinder::class); - $this->registerAlias(\OCP\Share\IPublicShareTemplateFactory::class, \OC\Share20\PublicShareTemplateFactory::class); + $this->registerAlias(\OCP\Share\IPublicShareTemplateFactory::class, PublicShareTemplateFactory::class); $this->registerAlias(ITranslationManager::class, TranslationManager::class); @@ -1262,7 +1293,7 @@ class Server extends ServerContainer implements IServerContainer { $this->registerAlias(\OCP\Security\Ip\IFactory::class, \OC\Security\Ip\Factory::class); - $this->registerAlias(IRichTextFormatter::class, \OC\RichObjectStrings\RichTextFormatter::class); + $this->registerAlias(IRichTextFormatter::class, RichTextFormatter::class); $this->registerAlias(ISignatureManager::class, SignatureManager::class); @@ -1309,18 +1340,16 @@ class Server extends ServerContainer implements IServerContainer { } /** - * @return \OC\Encryption\Manager * @deprecated 20.0.0 */ - public function getEncryptionManager() { + public function getEncryptionManager(): \OCP\Encryption\IManager { return $this->get(\OCP\Encryption\IManager::class); } /** - * @return \OC\Encryption\File * @deprecated 20.0.0 */ - public function getEncryptionFilesHelper() { + public function getEncryptionFilesHelper(): IFile { return $this->get(IFile::class); } @@ -1329,7 +1358,7 @@ class Server extends ServerContainer implements IServerContainer { * currently being processed is returned from this method. * In case the current execution was not initiated by a web request null is returned * - * @return \OCP\IRequest + * @return IRequest * @deprecated 20.0.0 */ public function getRequest() { @@ -1362,7 +1391,7 @@ class Server extends ServerContainer implements IServerContainer { * Returns a view to ownCloud's files folder * * @param string $userId user ID - * @return \OCP\Files\Folder|null + * @return Folder|null * @deprecated 20.0.0 */ public function getUserFolder($userId = null) { @@ -1378,31 +1407,28 @@ class Server extends ServerContainer implements IServerContainer { } /** - * @return \OC\User\Manager * @deprecated 20.0.0 */ - public function getUserManager() { + public function getUserManager(): IUserManager { return $this->get(IUserManager::class); } /** - * @return \OC\Group\Manager * @deprecated 20.0.0 */ - public function getGroupManager() { + public function getGroupManager(): IGroupManager { return $this->get(IGroupManager::class); } /** - * @return \OC\User\Session * @deprecated 20.0.0 */ - public function getUserSession() { + public function getUserSession(): IUserSession { return $this->get(IUserSession::class); } /** - * @return \OCP\ISession + * @return ISession * @deprecated 20.0.0 */ public function getSession() { @@ -1410,17 +1436,17 @@ class Server extends ServerContainer implements IServerContainer { } /** - * @param \OCP\ISession $session + * @param ISession $session * @return void */ - public function setSession(\OCP\ISession $session) { + public function setSession(ISession $session) { $this->get(SessionStorage::class)->setSession($session); $this->get(Session::class)->setSession($session); $this->get(Store::class)->setSession($session); } /** - * @return \OCP\IConfig + * @return IConfig * @deprecated 20.0.0 */ public function getConfig() { @@ -1428,7 +1454,7 @@ class Server extends ServerContainer implements IServerContainer { } /** - * @return \OC\SystemConfig + * @return SystemConfig * @deprecated 20.0.0 */ public function getSystemConfig() { @@ -1477,7 +1503,7 @@ class Server extends ServerContainer implements IServerContainer { /** * Returns an \OCP\CacheFactory instance * - * @return \OCP\ICacheFactory + * @return ICacheFactory * @deprecated 20.0.0 */ public function getMemCacheFactory() { @@ -1487,7 +1513,7 @@ class Server extends ServerContainer implements IServerContainer { /** * Returns the current session * - * @return \OCP\IDBConnection + * @return IDBConnection * @deprecated 20.0.0 */ public function getDatabaseConnection() { @@ -1517,7 +1543,7 @@ class Server extends ServerContainer implements IServerContainer { /** * Returns a SecureRandom instance * - * @return \OCP\Security\ISecureRandom + * @return ISecureRandom * @deprecated 20.0.0 */ public function getSecureRandom() { @@ -1547,7 +1573,7 @@ class Server extends ServerContainer implements IServerContainer { /** * Get the certificate manager * - * @return \OCP\ICertificateManager + * @return ICertificateManager */ public function getCertificateManager() { return $this->get(ICertificateManager::class); @@ -1556,7 +1582,7 @@ class Server extends ServerContainer implements IServerContainer { /** * Get the manager for temporary files and folders * - * @return \OCP\ITempManager + * @return ITempManager * @deprecated 20.0.0 */ public function getTempManager() { @@ -1566,7 +1592,7 @@ class Server extends ServerContainer implements IServerContainer { /** * Get the app manager * - * @return \OCP\App\IAppManager + * @return IAppManager * @deprecated 20.0.0 */ public function getAppManager() { @@ -1636,7 +1662,7 @@ class Server extends ServerContainer implements IServerContainer { } /** - * @return \OCA\Theming\ThemingDefaults + * @return ThemingDefaults * @deprecated 20.0.0 */ public function getThemingDefaults() { @@ -1644,7 +1670,7 @@ class Server extends ServerContainer implements IServerContainer { } /** - * @return \OC\IntegrityCheck\Checker + * @return Checker * @deprecated 20.0.0 */ public function getIntegrityCodeChecker() { @@ -1676,7 +1702,7 @@ class Server extends ServerContainer implements IServerContainer { } /** - * @return \OCP\Files\IAppData + * @return IAppData * @deprecated 20.0.0 Use get(\OCP\Files\AppData\IAppDataFactory::class)->get($app) instead */ public function getAppDataDir($app) { @@ -1685,7 +1711,7 @@ class Server extends ServerContainer implements IServerContainer { } /** - * @return \OCP\Federation\ICloudIdManager + * @return ICloudIdManager * @deprecated 20.0.0 */ public function getCloudIdManager() { diff --git a/lib/private/ServerContainer.php b/lib/private/ServerContainer.php index 42cdf37fce9..a63615d21bb 100644 --- a/lib/private/ServerContainer.php +++ b/lib/private/ServerContainer.php @@ -172,4 +172,8 @@ class ServerContainer extends SimpleContainer { return null; } } + + public function getWebRoot() { + return ''; + } } diff --git a/lib/private/Session/CryptoSessionData.php b/lib/private/Session/CryptoSessionData.php index 323253af534..1420cd94d59 100644 --- a/lib/private/Session/CryptoSessionData.php +++ b/lib/private/Session/CryptoSessionData.php @@ -21,12 +21,6 @@ use function OCP\Log\logger; * @template-implements \ArrayAccess */ class CryptoSessionData implements \ArrayAccess, ISession { - /** @var ISession */ - protected $session; - /** @var \OCP\Security\ICrypto */ - protected $crypto; - /** @var string */ - protected $passphrase; /** @var array */ protected $sessionValues; /** @var bool */ @@ -38,12 +32,11 @@ class CryptoSessionData implements \ArrayAccess, ISession { * @param ICrypto $crypto * @param string $passphrase */ - public function __construct(ISession $session, - ICrypto $crypto, - string $passphrase) { - $this->crypto = $crypto; - $this->session = $session; - $this->passphrase = $passphrase; + public function __construct( + protected ISession $session, + protected ICrypto $crypto, + protected string $passphrase, + ) { $this->initializeSession(); } diff --git a/lib/private/Session/CryptoWrapper.php b/lib/private/Session/CryptoWrapper.php index 40c2ba6adf3..d269a2f1941 100644 --- a/lib/private/Session/CryptoWrapper.php +++ b/lib/private/Session/CryptoWrapper.php @@ -10,10 +10,12 @@ declare(strict_types=1); namespace OC\Session; +use OCP\IConfig; use OCP\IRequest; use OCP\ISession; use OCP\Security\ICrypto; use OCP\Security\ISecureRandom; +use OCP\Server; /** * Class CryptoWrapper provides some rough basic level of additional security by @@ -59,7 +61,7 @@ class CryptoWrapper { [ 'expires' => 0, 'path' => $webRoot, - 'domain' => \OCP\Server::get(\OCP\IConfig::class)->getSystemValueString('cookie_domain'), + 'domain' => Server::get(IConfig::class)->getSystemValueString('cookie_domain'), 'secure' => $secureCookie, 'httponly' => true, 'samesite' => 'Lax', diff --git a/lib/private/Session/Internal.php b/lib/private/Session/Internal.php index 5949471965b..d07174fad14 100644 --- a/lib/private/Session/Internal.php +++ b/lib/private/Session/Internal.php @@ -12,6 +12,7 @@ namespace OC\Session; use OC\Authentication\Token\IProvider; use OC\Diagnostics\TLogSlowOperation; use OCP\Authentication\Exceptions\InvalidTokenException; +use OCP\Server; use OCP\Session\Exceptions\SessionNotAvailableException; use Psr\Log\LoggerInterface; use function call_user_func_array; @@ -136,7 +137,7 @@ class Internal extends Session { $newId = $this->getId(); /** @var IProvider $tokenProvider */ - $tokenProvider = \OCP\Server::get(IProvider::class); + $tokenProvider = Server::get(IProvider::class); try { $tokenProvider->renewSessionToken($oldId, $newId); diff --git a/lib/private/Settings/AuthorizedGroupMapper.php b/lib/private/Settings/AuthorizedGroupMapper.php index b622459426b..f59d3fd7fd9 100644 --- a/lib/private/Settings/AuthorizedGroupMapper.php +++ b/lib/private/Settings/AuthorizedGroupMapper.php @@ -6,7 +6,9 @@ */ namespace OC\Settings; +use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Db\Entity; +use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\AppFramework\Db\QBMapper; use OCP\DB\Exception; use OCP\DB\QueryBuilder\IQueryBuilder; @@ -14,6 +16,7 @@ use OCP\IDBConnection; use OCP\IGroup; use OCP\IGroupManager; use OCP\IUser; +use OCP\Server; /** * @template-extends QBMapper @@ -30,7 +33,7 @@ class AuthorizedGroupMapper extends QBMapper { $qb = $this->db->getQueryBuilder(); /** @var IGroupManager $groupManager */ - $groupManager = \OC::$server->get(IGroupManager::class); + $groupManager = Server::get(IGroupManager::class); $groups = $groupManager->getUserGroups($user); if (count($groups) === 0) { return []; @@ -52,8 +55,8 @@ class AuthorizedGroupMapper extends QBMapper { } /** - * @throws \OCP\AppFramework\Db\DoesNotExistException - * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException + * @throws DoesNotExistException + * @throws MultipleObjectsReturnedException * @throws \OCP\DB\Exception */ public function find(int $id): AuthorizedGroup { diff --git a/lib/private/Settings/Section.php b/lib/private/Settings/Section.php index 6cd8885d2df..1a54eb84a51 100644 --- a/lib/private/Settings/Section.php +++ b/lib/private/Settings/Section.php @@ -9,26 +9,18 @@ namespace OC\Settings; use OCP\Settings\IIconSection; class Section implements IIconSection { - /** @var string */ - private $id; - /** @var string */ - private $name; - /** @var int */ - private $priority; - /** @var string */ - private $icon; - /** * @param string $id * @param string $name * @param int $priority * @param string $icon */ - public function __construct($id, $name, $priority, $icon = '') { - $this->id = $id; - $this->name = $name; - $this->priority = $priority; - $this->icon = $icon; + public function __construct( + private $id, + private $name, + private $priority, + private $icon = '', + ) { } /** diff --git a/lib/private/Setup.php b/lib/private/Setup.php index 550d9f6ef59..4fc8e622814 100644 --- a/lib/private/Setup.php +++ b/lib/private/Setup.php @@ -12,18 +12,27 @@ namespace OC; use bantu\IniGetWrapper\IniGetWrapper; use Exception; use InvalidArgumentException; +use OC\AppFramework\Bootstrap\Coordinator; use OC\Authentication\Token\PublicKeyTokenProvider; use OC\Authentication\Token\TokenCleanupJob; use OC\Core\BackgroundJobs\GenerateMetadataJob; use OC\Core\BackgroundJobs\PreviewMigrationJob; use OC\Log\Rotate; use OC\Preview\BackgroundCleanupJob; +use OC\Setup\AbstractDatabase; +use OC\Setup\MySQL; +use OC\Setup\OCI; +use OC\Setup\PostgreSQL; +use OC\Setup\Sqlite; use OC\TextProcessing\RemoveOldTasksBackgroundJob; use OC\User\BackgroundJobs\CleanupDeletedUsers; +use OC\User\Session; +use OCP\AppFramework\QueryException; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJobList; use OCP\Defaults; use OCP\EventDispatcher\IEventDispatcher; +use OCP\HintException; use OCP\Http\Client\IClientService; use OCP\IAppConfig; use OCP\IConfig; @@ -40,6 +49,7 @@ use OCP\Migration\IOutput; use OCP\Security\ISecureRandom; use OCP\Server; use OCP\ServerVersion; +use OCP\Util; use Psr\Log\LoggerInterface; class Setup { @@ -62,11 +72,11 @@ class Setup { } protected static array $dbSetupClasses = [ - 'mysql' => \OC\Setup\MySQL::class, - 'pgsql' => \OC\Setup\PostgreSQL::class, - 'oci' => \OC\Setup\OCI::class, - 'sqlite' => \OC\Setup\Sqlite::class, - 'sqlite3' => \OC\Setup\Sqlite::class, + 'mysql' => MySQL::class, + 'pgsql' => PostgreSQL::class, + 'oci' => OCI::class, + 'sqlite' => Sqlite::class, + 'sqlite3' => Sqlite::class, ]; /** @@ -181,7 +191,7 @@ class Setup { try { $htAccessWorking = $this->isHtaccessWorking($dataDir); - } catch (\OCP\HintException $e) { + } catch (HintException $e) { $errors[] = [ 'error' => $e->getMessage(), 'exception' => $e, @@ -240,7 +250,7 @@ class Setup { $fp = @fopen($testFile, 'w'); if (!$fp) { - throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.', + throw new HintException('Can\'t create test file to check for working .htaccess file.', 'Make sure it is possible for the web server to write to ' . $testFile); } fwrite($fp, $testContent); @@ -252,10 +262,10 @@ class Setup { /** * Check if the .htaccess file is working * - * @param \OCP\IConfig $config + * @param IConfig $config * @return bool * @throws Exception - * @throws \OCP\HintException If the test file can't get written. + * @throws HintException If the test file can't get written. */ public function isHtaccessWorking(string $dataDir) { $config = Server::get(IConfig::class); @@ -332,7 +342,7 @@ class Setup { $dataDir = htmlspecialchars_decode($options['directory']); $class = self::$dbSetupClasses[$dbType]; - /** @var \OC\Setup\AbstractDatabase $dbSetup */ + /** @var AbstractDatabase $dbSetup */ $dbSetup = new $class($l, $this->config, $this->logger, $this->random); $error = array_merge($error, $dbSetup->validate($options)); @@ -370,7 +380,7 @@ class Setup { 'trusted_domains' => $trustedDomains, 'datadirectory' => $dataDir, 'dbtype' => $dbType, - 'version' => implode('.', \OCP\Util::getVersion()), + 'version' => implode('.', Util::getVersion()), ]; if ($this->config->getValue('overwrite.cli.url', null) === null) { @@ -383,7 +393,7 @@ class Setup { $dbSetup->initialize($options); try { $dbSetup->setupDatabase(); - } catch (\OC\DatabaseSetupException $e) { + } catch (DatabaseSetupException $e) { $error[] = [ 'error' => $e->getMessage(), 'exception' => $e, @@ -472,13 +482,13 @@ class Setup { unlink(\OC::$configDir . '/CAN_INSTALL'); } - $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class); + $bootstrapCoordinator = Server::get(Coordinator::class); $bootstrapCoordinator->runInitialRegistration(); if (!$disableAdminUser) { // Create a session token for the newly created user // The token provider requires a working db, so it's not injected on setup - /** @var \OC\User\Session $userSession */ + /** @var Session $userSession */ $userSession = Server::get(IUserSession::class); $provider = Server::get(PublicKeyTokenProvider::class); $userSession->setTokenProvider($provider); @@ -554,7 +564,7 @@ class Setup { * Append the correct ErrorDocument path for Apache hosts * * @return bool True when success, False otherwise - * @throws \OCP\AppFramework\QueryException + * @throws QueryException */ public static function updateHtaccess(): bool { $config = Server::get(SystemConfig::class); @@ -565,7 +575,7 @@ class Setup { return false; } - $setupHelper = Server::get(\OC\Setup::class); + $setupHelper = Server::get(Setup::class); if (!is_writable($setupHelper->pathToHtaccess())) { return false; diff --git a/lib/private/Setup/AbstractDatabase.php b/lib/private/Setup/AbstractDatabase.php index 8f6294faa66..a679866acf4 100644 --- a/lib/private/Setup/AbstractDatabase.php +++ b/lib/private/Setup/AbstractDatabase.php @@ -14,11 +14,10 @@ use OC\SystemConfig; use OCP\IL10N; use OCP\Migration\IOutput; use OCP\Security\ISecureRandom; +use OCP\Server; use Psr\Log\LoggerInterface; abstract class AbstractDatabase { - /** @var IL10N */ - protected $trans; /** @var string */ protected $dbUser; /** @var string */ @@ -31,20 +30,15 @@ abstract class AbstractDatabase { protected $dbPort; /** @var string */ protected $tablePrefix; - /** @var SystemConfig */ - protected $config; - /** @var LoggerInterface */ - protected $logger; - /** @var ISecureRandom */ - protected $random; /** @var bool */ protected $tryCreateDbUser; - public function __construct(IL10N $trans, SystemConfig $config, LoggerInterface $logger, ISecureRandom $random) { - $this->trans = $trans; - $this->config = $config; - $this->logger = $logger; - $this->random = $random; + public function __construct( + protected IL10N $trans, + protected SystemConfig $config, + protected LoggerInterface $logger, + protected ISecureRandom $random, + ) { } public function validate($config) { @@ -132,7 +126,7 @@ abstract class AbstractDatabase { if (!is_dir(\OC::$SERVERROOT . '/core/Migrations')) { return; } - $ms = new MigrationService('core', \OC::$server->get(Connection::class), $output); + $ms = new MigrationService('core', Server::get(Connection::class), $output); $ms->migrate('latest', true); } } diff --git a/lib/private/Setup/MySQL.php b/lib/private/Setup/MySQL.php index c4794a86743..7f8ea73a1f4 100644 --- a/lib/private/Setup/MySQL.php +++ b/lib/private/Setup/MySQL.php @@ -9,6 +9,7 @@ namespace OC\Setup; use Doctrine\DBAL\Platforms\MySQL80Platform; use Doctrine\DBAL\Platforms\MySQL84Platform; +use OC\DatabaseSetupException; use OC\DB\ConnectionAdapter; use OC\DB\MySqlTools; use OCP\IDBConnection; @@ -52,7 +53,7 @@ class MySQL extends AbstractDatabase { $this->logger->error($e->getMessage(), [ 'exception' => $e, ]); - throw new \OC\DatabaseSetupException($this->trans->t('MySQL Login and/or password not valid'), + throw new DatabaseSetupException($this->trans->t('MySQL Login and/or password not valid'), $this->trans->t('You need to enter details of an existing account.'), 0, $e); } } @@ -90,7 +91,7 @@ class MySQL extends AbstractDatabase { /** * @param IDBConnection $connection - * @throws \OC\DatabaseSetupException + * @throws DatabaseSetupException */ private function createDBUser($connection): void { $name = $this->dbUser; diff --git a/lib/private/Setup/OCI.php b/lib/private/Setup/OCI.php index 61c7f968787..72f3bd04027 100644 --- a/lib/private/Setup/OCI.php +++ b/lib/private/Setup/OCI.php @@ -7,6 +7,8 @@ */ namespace OC\Setup; +use OC\DatabaseSetupException; + class OCI extends AbstractDatabase { public $dbprettyname = 'Oracle'; @@ -46,14 +48,14 @@ class OCI extends AbstractDatabase { } catch (\Exception $e) { $errorMessage = $this->getLastError(); if ($errorMessage) { - throw new \OC\DatabaseSetupException($this->trans->t('Oracle connection could not be established'), + throw new DatabaseSetupException($this->trans->t('Oracle connection could not be established'), $errorMessage . ' Check environment: ORACLE_HOME=' . getenv('ORACLE_HOME') . ' ORACLE_SID=' . getenv('ORACLE_SID') . ' LD_LIBRARY_PATH=' . getenv('LD_LIBRARY_PATH') . ' NLS_LANG=' . getenv('NLS_LANG') . ' tnsnames.ora is ' . (is_readable(getenv('ORACLE_HOME') . '/network/admin/tnsnames.ora') ? '' : 'not ') . 'readable', 0, $e); } - throw new \OC\DatabaseSetupException($this->trans->t('Oracle Login and/or password not valid'), + throw new DatabaseSetupException($this->trans->t('Oracle Login and/or password not valid'), 'Check environment: ORACLE_HOME=' . getenv('ORACLE_HOME') . ' ORACLE_SID=' . getenv('ORACLE_SID') . ' LD_LIBRARY_PATH=' . getenv('LD_LIBRARY_PATH') diff --git a/lib/private/Setup/PostgreSQL.php b/lib/private/Setup/PostgreSQL.php index 3f8d5e05854..e0564b00c60 100644 --- a/lib/private/Setup/PostgreSQL.php +++ b/lib/private/Setup/PostgreSQL.php @@ -8,15 +8,17 @@ namespace OC\Setup; use OC\DatabaseException; +use OC\DatabaseSetupException; use OC\DB\Connection; use OC\DB\QueryBuilder\Literal; use OCP\Security\ISecureRandom; +use OCP\Server; class PostgreSQL extends AbstractDatabase { public $dbprettyname = 'PostgreSQL'; /** - * @throws \OC\DatabaseSetupException + * @throws DatabaseSetupException */ public function setupDatabase() { try { @@ -47,7 +49,7 @@ class PostgreSQL extends AbstractDatabase { //add prefix to the postgresql user name to prevent collisions $this->dbUser = 'oc_admin'; //create a new password so we don't need to store the admin config in the config file - $this->dbPassword = \OC::$server->get(ISecureRandom::class)->generate(30, ISecureRandom::CHAR_ALPHANUMERIC); + $this->dbPassword = Server::get(ISecureRandom::class)->generate(30, ISecureRandom::CHAR_ALPHANUMERIC); $this->createDBUser($connection); } @@ -96,7 +98,7 @@ class PostgreSQL extends AbstractDatabase { $this->logger->error($e->getMessage(), [ 'exception' => $e, ]); - throw new \OC\DatabaseSetupException($this->trans->t('PostgreSQL Login and/or password not valid'), + throw new DatabaseSetupException($this->trans->t('PostgreSQL Login and/or password not valid'), $this->trans->t('You need to enter details of an existing account.'), 0, $e); } } diff --git a/lib/private/Share/Helper.php b/lib/private/Share/Helper.php index 5f7a8f7b42a..58a33b5620d 100644 --- a/lib/private/Share/Helper.php +++ b/lib/private/Share/Helper.php @@ -9,15 +9,17 @@ namespace OC\Share; use OC\Core\AppInfo\ConfigLexicon; use OCP\IAppConfig; +use OCP\IConfig; use OCP\Server; +use OCP\Util; -class Helper extends \OC\Share\Constants { +class Helper extends Constants { /** * get default expire settings defined by the admin * @return array contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays' */ public static function getDefaultExpireSetting() { - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); $appConfig = Server::get(IAppConfig::class); $defaultExpireSettings = ['defaultExpireDateSet' => false]; @@ -33,7 +35,7 @@ class Helper extends \OC\Share\Constants { } public static function calcExpireDate() { - $expireAfter = \OC\Share\Share::getExpireInterval() * 24 * 60 * 60; + $expireAfter = Share::getExpireInterval() * 24 * 60 * 60; $expireAt = time() + $expireAfter; $date = new \DateTime(); $date->setTimestamp($expireAt); @@ -106,17 +108,17 @@ class Helper extends \OC\Share\Constants { * @return bool true if both users and servers are the same */ public static function isSameUserOnSameServer($user1, $server1, $user2, $server2) { - $normalizedServer1 = strtolower(\OC\Share\Share::removeProtocolFromUrl($server1)); - $normalizedServer2 = strtolower(\OC\Share\Share::removeProtocolFromUrl($server2)); + $normalizedServer1 = strtolower(Share::removeProtocolFromUrl($server1)); + $normalizedServer2 = strtolower(Share::removeProtocolFromUrl($server2)); if (rtrim($normalizedServer1, '/') === rtrim($normalizedServer2, '/')) { // FIXME this should be a method in the user management instead - \OCP\Util::emitHook( + Util::emitHook( '\OCA\Files_Sharing\API\Server2Server', 'preLoginNameUsedAsUserName', ['uid' => &$user1] ); - \OCP\Util::emitHook( + Util::emitHook( '\OCA\Files_Sharing\API\Server2Server', 'preLoginNameUsedAsUserName', ['uid' => &$user2] @@ -131,7 +133,7 @@ class Helper extends \OC\Share\Constants { } public static function getTokenLength(): int { - $config = Server::get(\OCP\IAppConfig::class); + $config = Server::get(IAppConfig::class); $tokenLength = $config->getValueInt('core', 'shareapi_token_length', self::DEFAULT_TOKEN_LENGTH); $tokenLength = $tokenLength ?: self::DEFAULT_TOKEN_LENGTH; diff --git a/lib/private/Share/Share.php b/lib/private/Share/Share.php index 1121d71e45f..6f4c373dcf9 100644 --- a/lib/private/Share/Share.php +++ b/lib/private/Share/Share.php @@ -8,6 +8,10 @@ namespace OC\Share; use OCA\Files_Sharing\ShareBackend\File; +use OCP\IConfig; +use OCP\Server; +use OCP\Share_Backend; +use OCP\Util; use Psr\Log\LoggerInterface; /** @@ -44,7 +48,7 @@ class Share extends Constants { * @return boolean true if backend is registered or false if error */ public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) { - if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') { + if (Server::get(IConfig::class)->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') { if (!isset(self::$backendTypes[$itemType])) { self::$backendTypes[$itemType] = [ 'class' => $class, @@ -53,7 +57,7 @@ class Share extends Constants { ]; return true; } - \OC::$server->get(LoggerInterface::class)->warning( + Server::get(LoggerInterface::class)->warning( 'Sharing backend ' . $class . ' not registered, ' . self::$backendTypes[$itemType]['class'] . ' is already registered for ' . $itemType, ['app' => 'files_sharing']); @@ -65,19 +69,19 @@ class Share extends Constants { * Get the backend class for the specified item type * * @param string $itemType - * @return \OCP\Share_Backend + * @return Share_Backend * @throws \Exception */ public static function getBackend($itemType) { - $l = \OCP\Util::getL10N('lib'); - $logger = \OCP\Server::get(LoggerInterface::class); + $l = Util::getL10N('lib'); + $logger = Server::get(LoggerInterface::class); if (isset(self::$backends[$itemType])) { return self::$backends[$itemType]; } elseif (isset(self::$backendTypes[$itemType]['class'])) { $class = self::$backendTypes[$itemType]['class']; if (class_exists($class)) { self::$backends[$itemType] = new $class; - if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) { + if (!(self::$backends[$itemType] instanceof Share_Backend)) { $message = 'Sharing backend %s must implement the interface OCP\Share_Backend'; $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', [$class]); $logger->error(sprintf($message, $class), ['app' => 'OCP\Share']); @@ -106,7 +110,7 @@ class Share extends Constants { */ public static function isResharingAllowed() { if (!isset(self::$isResharingAllowed)) { - if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') { + if (Server::get(IConfig::class)->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') { self::$isResharingAllowed = true; } else { self::$isResharingAllowed = false; @@ -175,6 +179,6 @@ class Share extends Constants { * @return int */ public static function getExpireInterval() { - return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7'); + return (int)Server::get(IConfig::class)->getAppValue('core', 'shareapi_expire_after_n_days', '7'); } } diff --git a/lib/private/Share20/DefaultShareProvider.php b/lib/private/Share20/DefaultShareProvider.php index 8fc15fd8c0d..17c6e9d572b 100644 --- a/lib/private/Share20/DefaultShareProvider.php +++ b/lib/private/Share20/DefaultShareProvider.php @@ -9,6 +9,7 @@ namespace OC\Share20; use OC\Files\Cache\Cache; +use OC\Files\Filesystem; use OC\Share20\Exception\BackendError; use OC\Share20\Exception\InvalidShare; use OC\Share20\Exception\ProviderException; @@ -17,9 +18,13 @@ use OCA\Files_Sharing\AppInfo\Application; use OCP\AppFramework\Utility\ITimeFactory; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\Defaults; +use OCP\Files\File; use OCP\Files\Folder; +use OCP\Files\IMimeTypeLoader; +use OCP\Files\InvalidPathException; use OCP\Files\IRootFolder; use OCP\Files\Node; +use OCP\Files\NotFoundException; use OCP\IConfig; use OCP\IDBConnection; use OCP\IGroupManager; @@ -29,6 +34,7 @@ use OCP\IUser; use OCP\IUserManager; use OCP\L10N\IFactory; use OCP\Mail\IMailer; +use OCP\Server; use OCP\Share\Exceptions\ShareNotFound; use OCP\Share\IAttributes; use OCP\Share\IManager; @@ -38,6 +44,7 @@ use OCP\Share\IShareProviderGetUsers; use OCP\Share\IShareProviderSupportsAccept; use OCP\Share\IShareProviderSupportsAllSharesInFolder; use OCP\Share\IShareProviderWithNotification; +use OCP\Util; use Psr\Log\LoggerInterface; use function str_starts_with; @@ -80,12 +87,12 @@ class DefaultShareProvider implements /** * Share a path * - * @param \OCP\Share\IShare $share - * @return \OCP\Share\IShare The share object + * @param IShare $share + * @return IShare The share object * @throws ShareNotFound * @throws \Exception */ - public function create(\OCP\Share\IShare $share) { + public function create(IShare $share) { $qb = $this->dbConn->getQueryBuilder(); $qb->insert('share'); @@ -143,7 +150,7 @@ class DefaultShareProvider implements // Set what is shares $qb->setValue('item_type', $qb->createParameter('itemType')); - if ($share->getNode() instanceof \OCP\Files\File) { + if ($share->getNode() instanceof File) { $qb->setParameter('itemType', 'file'); } else { $qb->setParameter('itemType', 'folder'); @@ -198,13 +205,13 @@ class DefaultShareProvider implements /** * Update a share * - * @param \OCP\Share\IShare $share - * @return \OCP\Share\IShare The share object + * @param IShare $share + * @return IShare The share object * @throws ShareNotFound - * @throws \OCP\Files\InvalidPathException - * @throws \OCP\Files\NotFoundException + * @throws InvalidPathException + * @throws NotFoundException */ - public function update(\OCP\Share\IShare $share) { + public function update(IShare $share) { $originalShare = $this->getShareById($share->getId()); $shareAttributes = $this->formatShareAttributes($share->getAttributes()); @@ -395,9 +402,9 @@ class DefaultShareProvider implements /** * Delete a share * - * @param \OCP\Share\IShare $share + * @param IShare $share */ - public function delete(\OCP\Share\IShare $share) { + public function delete(IShare $share) { $qb = $this->dbConn->getQueryBuilder(); $qb->delete('share') ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))); @@ -490,7 +497,7 @@ class DefaultShareProvider implements } $target = $shareFolder . '/' . $share->getNode()->getName(); - $target = \OC\Files\Filesystem::normalizePath($target); + $target = Filesystem::normalizePath($target); $qb = $this->dbConn->getQueryBuilder(); $qb->insert('share') @@ -549,7 +556,7 @@ class DefaultShareProvider implements /** * @inheritdoc */ - public function move(\OCP\Share\IShare $share, $recipient) { + public function move(IShare $share, $recipient) { if ($share->getShareType() === IShare::TYPE_USER) { // Just update the target $qb = $this->dbConn->getQueryBuilder(); @@ -782,8 +789,8 @@ class DefaultShareProvider implements /** * Get shares for a given path * - * @param \OCP\Files\Node $path - * @return \OCP\Share\IShare[] + * @param Node $path + * @return IShare[] */ public function getSharesByPath(Node $path) { $qb = $this->dbConn->getQueryBuilder(); @@ -1037,7 +1044,7 @@ class DefaultShareProvider implements * Get a share by token * * @param string $token - * @return \OCP\Share\IShare + * @return IShare * @throws ShareNotFound */ public function getShareByToken($token) { @@ -1069,7 +1076,7 @@ class DefaultShareProvider implements * Create a share object from a database row * * @param mixed[] $data - * @return \OCP\Share\IShare + * @return IShare * @throws InvalidShare */ private function createShare($data) { @@ -1123,7 +1130,7 @@ class DefaultShareProvider implements $entryData['permissions'] = $entryData['f_permissions']; $entryData['parent'] = $entryData['f_parent']; $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData, - \OC::$server->getMimeTypeLoader())); + Server::get(IMimeTypeLoader::class))); } $share->setProviderId($this->identifier()); @@ -1493,7 +1500,7 @@ class DefaultShareProvider implements * propagate notes to the recipients * * @param IShare $share - * @throws \OCP\Files\NotFoundException + * @throws NotFoundException */ private function propagateNote(IShare $share) { if ($share->getShareType() === IShare::TYPE_USER) { @@ -1602,7 +1609,7 @@ class DefaultShareProvider implements $instanceName, ] ); - $message->setFrom([\OCP\Util::getDefaultEmailAddress('noreply') => $senderName]); + $message->setFrom([Util::getDefaultEmailAddress('noreply') => $senderName]); // The "Reply-To" is set to the sharer if an mail address is configured // also the default footer contains a "Do not reply" which needs to be adjusted. @@ -1631,7 +1638,7 @@ class DefaultShareProvider implements * * @param array $recipients * @param IShare $share - * @throws \OCP\Files\NotFoundException + * @throws NotFoundException */ private function sendNote(array $recipients, IShare $share) { $toListByLanguage = []; @@ -1689,7 +1696,7 @@ class DefaultShareProvider implements $instanceName ] ); - $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]); + $message->setFrom([Util::getDefaultEmailAddress($instanceName) => $senderName]); if ($initiatorEmailAddress !== null) { $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]); $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan()); diff --git a/lib/private/Share20/LegacyHooks.php b/lib/private/Share20/LegacyHooks.php index d54c8e3203d..5c79ad9b5d0 100644 --- a/lib/private/Share20/LegacyHooks.php +++ b/lib/private/Share20/LegacyHooks.php @@ -17,25 +17,22 @@ use OCP\Share\Events\ShareDeletedFromSelfEvent; use OCP\Share\IShare; class LegacyHooks { - /** @var IEventDispatcher */ - private $eventDispatcher; - - public function __construct(IEventDispatcher $eventDispatcher) { - $this->eventDispatcher = $eventDispatcher; - - $this->eventDispatcher->addListener(BeforeShareDeletedEvent::class, function (BeforeShareDeletedEvent $event) { + public function __construct( + private IEventDispatcher $eventDispatcher, + ) { + $this->eventDispatcher->addListener(BeforeShareDeletedEvent::class, function (BeforeShareDeletedEvent $event): void { $this->preUnshare($event); }); - $this->eventDispatcher->addListener(ShareDeletedEvent::class, function (ShareDeletedEvent $event) { + $this->eventDispatcher->addListener(ShareDeletedEvent::class, function (ShareDeletedEvent $event): void { $this->postUnshare($event); }); - $this->eventDispatcher->addListener(ShareDeletedFromSelfEvent::class, function (ShareDeletedFromSelfEvent $event) { + $this->eventDispatcher->addListener(ShareDeletedFromSelfEvent::class, function (ShareDeletedFromSelfEvent $event): void { $this->postUnshareFromSelf($event); }); - $this->eventDispatcher->addListener(BeforeShareCreatedEvent::class, function (BeforeShareCreatedEvent $event) { + $this->eventDispatcher->addListener(BeforeShareCreatedEvent::class, function (BeforeShareCreatedEvent $event): void { $this->preShare($event); }); - $this->eventDispatcher->addListener(ShareCreatedEvent::class, function (ShareCreatedEvent $event) { + $this->eventDispatcher->addListener(ShareCreatedEvent::class, function (ShareCreatedEvent $event): void { $this->postShare($event); }); } diff --git a/lib/private/Share20/Manager.php b/lib/private/Share20/Manager.php index 7a1b7045b36..a1442a77211 100644 --- a/lib/private/Share20/Manager.php +++ b/lib/private/Share20/Manager.php @@ -9,13 +9,16 @@ namespace OC\Share20; use ArrayIterator; use OC\Core\AppInfo\ConfigLexicon; +use OC\Files\Filesystem; use OC\Files\Mount\MoveableMount; use OC\KnownUser\KnownUserService; use OC\Share\Helper; use OC\Share20\Exception\ProviderException; +use OCA\Circles\Api\v1\Circles; use OCA\Files_Sharing\AppInfo\Application; use OCA\Files_Sharing\SharedStorage; use OCA\ShareByMail\ShareByMailProvider; +use OCP\Constants; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\File; @@ -40,6 +43,7 @@ use OCP\Security\IHasher; use OCP\Security\ISecureRandom; use OCP\Security\PasswordContext; use OCP\Share; +use OCP\Share\Events\BeforeShareCreatedEvent; use OCP\Share\Events\BeforeShareDeletedEvent; use OCP\Share\Events\ShareAcceptedEvent; use OCP\Share\Events\ShareCreatedEvent; @@ -57,6 +61,7 @@ use OCP\Share\IShareProvider; use OCP\Share\IShareProviderSupportsAccept; use OCP\Share\IShareProviderSupportsAllSharesInFolder; use OCP\Share\IShareProviderWithNotification; +use OCP\Util; use Override; use Psr\Log\LoggerInterface; @@ -164,7 +169,8 @@ class Manager implements IManager { throw new \InvalidArgumentException($this->l->t('Share recipient should not be empty')); } } elseif ($share->getShareType() === IShare::TYPE_CIRCLE) { - $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith()); + /** @psalm-suppress UndefinedClass */ + $circle = Circles::detailsCircle($share->getSharedWith()); if ($circle === null) { throw new \InvalidArgumentException($this->l->t('Share recipient is not a valid circle')); } @@ -192,8 +198,8 @@ class Manager implements IManager { } // And it should be a file or a folder - if (!($share->getNode() instanceof \OCP\Files\File) - && !($share->getNode() instanceof \OCP\Files\Folder)) { + if (!($share->getNode() instanceof File) + && !($share->getNode() instanceof Folder)) { throw new \InvalidArgumentException($this->l->t('Shared path must be either a file or a folder')); } @@ -218,13 +224,13 @@ class Manager implements IManager { } // Permissions must be valid - if ($share->getPermissions() < 0 || $share->getPermissions() > \OCP\Constants::PERMISSION_ALL) { + if ($share->getPermissions() < 0 || $share->getPermissions() > Constants::PERMISSION_ALL) { throw new \InvalidArgumentException($this->l->t('Valid permissions are required for sharing')); } // Single file shares should never have delete or create permissions if (($share->getNode() instanceof File) - && (($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_DELETE)) !== 0)) { + && (($share->getPermissions() & (Constants::PERMISSION_CREATE | Constants::PERMISSION_DELETE)) !== 0)) { throw new \InvalidArgumentException($this->l->t('File shares cannot have create or delete permissions')); } @@ -251,15 +257,15 @@ class Manager implements IManager { $noReadPermissionRequired = $share->getShareType() === IShare::TYPE_LINK || $share->getShareType() === IShare::TYPE_EMAIL; if (!$noReadPermissionRequired - && ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) { + && ($share->getPermissions() & Constants::PERMISSION_READ) === 0) { throw new \InvalidArgumentException($this->l->t('Shares need at least read permissions')); } - if ($share->getNode() instanceof \OCP\Files\File) { - if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) { + if ($share->getNode() instanceof File) { + if ($share->getPermissions() & Constants::PERMISSION_DELETE) { throw new GenericShareException($this->l->t('Files cannot be shared with delete permissions')); } - if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) { + if ($share->getPermissions() & Constants::PERMISSION_CREATE) { throw new GenericShareException($this->l->t('Files cannot be shared with create permissions')); } } @@ -340,7 +346,7 @@ class Manager implements IManager { $accepted = true; $message = ''; - \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [ + Util::emitHook('\OC\Share', 'verifyExpirationDate', [ 'expirationDate' => &$expirationDate, 'accepted' => &$accepted, 'message' => &$message, @@ -423,7 +429,7 @@ class Manager implements IManager { $accepted = true; $message = ''; - \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [ + Util::emitHook('\OC\Share', 'verifyExpirationDate', [ 'expirationDate' => &$expirationDate, 'accepted' => &$accepted, 'message' => &$message, @@ -558,7 +564,7 @@ class Manager implements IManager { // Check if public upload is allowed if ($share->getNodeType() === 'folder' && !$this->shareApiLinkAllowPublicUpload() - && ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) { + && ($share->getPermissions() & (Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE))) { throw new \InvalidArgumentException($this->l->t('Public upload is not allowed')); } } @@ -575,14 +581,14 @@ class Manager implements IManager { protected function setLinkParent(IShare $share): void { $storage = $share->getNode()->getStorage(); if ($storage->instanceOfStorage(SharedStorage::class)) { - /** @var \OCA\Files_Sharing\SharedStorage $storage */ + /** @var SharedStorage $storage */ $share->setParent((int)$storage->getShareId()); } } protected function pathCreateChecks(Node $path): void { // Make sure that we do not share a path that contains a shared mountpoint - if ($path instanceof \OCP\Files\Folder) { + if ($path instanceof Folder) { $mounts = $this->mountManager->findIn($path->getPath()); foreach ($mounts as $mount) { if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { @@ -693,11 +699,11 @@ class Manager implements IManager { } $target = $shareFolder . '/' . $share->getNode()->getName(); - $target = \OC\Files\Filesystem::normalizePath($target); + $target = Filesystem::normalizePath($target); $share->setTarget($target); // Pre share event - $event = new Share\Events\BeforeShareCreatedEvent($share); + $event = new BeforeShareCreatedEvent($share); $this->dispatchEvent($event, 'before share created'); if ($event->isPropagationStopped() && $event->getError()) { throw new \Exception($event->getError()); @@ -850,7 +856,7 @@ class Manager implements IManager { if ($expirationDateUpdated === true) { \OC_Hook::emit(Share::class, 'post_set_expiration_date', [ - 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', + 'itemType' => $share->getNode() instanceof File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'date' => $share->getExpirationDate(), 'uidOwner' => $share->getSharedBy(), @@ -859,7 +865,7 @@ class Manager implements IManager { if ($share->getPassword() !== $originalShare->getPassword()) { \OC_Hook::emit(Share::class, 'post_update_password', [ - 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', + 'itemType' => $share->getNode() instanceof File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'uidOwner' => $share->getSharedBy(), 'token' => $share->getToken(), @@ -874,7 +880,7 @@ class Manager implements IManager { $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy()); } \OC_Hook::emit(Share::class, 'post_update_permissions', [ - 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', + 'itemType' => $share->getNode() instanceof File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'shareType' => $share->getShareType(), 'shareWith' => $share->getSharedWith(), @@ -1186,8 +1192,8 @@ class Manager implements IManager { #[Override] public function getSharesBy(string $userId, int $shareType, ?Node $path = null, bool $reshares = false, int $limit = 50, int $offset = 0, bool $onlyValid = true): array { if ($path !== null - && !($path instanceof \OCP\Files\File) - && !($path instanceof \OCP\Files\Folder)) { + && !($path instanceof File) + && !($path instanceof Folder)) { throw new \InvalidArgumentException($this->l->t('Invalid path')); } @@ -1420,7 +1426,7 @@ class Manager implements IManager { */ if (($share->getShareType() === IShare::TYPE_LINK || $share->getShareType() === IShare::TYPE_EMAIL) && $share->getNodeType() === 'folder' && !$this->shareApiLinkAllowPublicUpload()) { - $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE)); + $share->setPermissions($share->getPermissions() & ~(Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE)); } return $share; diff --git a/lib/private/Share20/ShareHelper.php b/lib/private/Share20/ShareHelper.php index 3f6bab98a7f..d03f89443f5 100644 --- a/lib/private/Share20/ShareHelper.php +++ b/lib/private/Share20/ShareHelper.php @@ -14,11 +14,9 @@ use OCP\Share\IManager; use OCP\Share\IShareHelper; class ShareHelper implements IShareHelper { - /** @var IManager */ - private $shareManager; - - public function __construct(IManager $shareManager) { - $this->shareManager = $shareManager; + public function __construct( + private IManager $shareManager, + ) { } /** diff --git a/lib/private/Share20/UserRemovedListener.php b/lib/private/Share20/UserRemovedListener.php index f06c945b591..10cb68f9b9e 100644 --- a/lib/private/Share20/UserRemovedListener.php +++ b/lib/private/Share20/UserRemovedListener.php @@ -17,11 +17,9 @@ use OCP\Share\IManager; * @template-implements IEventListener */ class UserRemovedListener implements IEventListener { - /** @var IManager */ - protected $shareManager; - - public function __construct(IManager $shareManager) { - $this->shareManager = $shareManager; + public function __construct( + protected IManager $shareManager, + ) { } public function handle(Event $event): void { diff --git a/lib/private/StreamImage.php b/lib/private/StreamImage.php index 34fe590efbd..511a67bdc8a 100644 --- a/lib/private/StreamImage.php +++ b/lib/private/StreamImage.php @@ -18,24 +18,13 @@ use OCP\IStreamImage; * valid result. */ class StreamImage implements IStreamImage { - /** @var resource The internal stream */ - private $stream; - - /** @var null|string */ - private $mimeType; - - /** @var int */ - private $width; - - /** @var int */ - private $height; - /** @param resource $stream */ - public function __construct($stream, string $mimeType, int $width, int $height) { - $this->stream = $stream; - $this->mimeType = $mimeType; - $this->width = $width; - $this->height = $height; + public function __construct( + private $stream, + private string $mimeType, + private int $width, + private int $height, + ) { } /** @inheritDoc */ diff --git a/lib/private/Streamer.php b/lib/private/Streamer.php index 7ebb66bf03a..eba7f4e98e9 100644 --- a/lib/private/Streamer.php +++ b/lib/private/Streamer.php @@ -16,6 +16,7 @@ use OCP\Files\NotFoundException; use OCP\Files\NotPermittedException; use OCP\IDateTimeZone; use OCP\IRequest; +use OCP\Server; use ownCloud\TarStreamer\TarStreamer; use Psr\Log\LoggerInterface; use ZipStreamer\ZipStreamer; @@ -116,13 +117,13 @@ class Streamer { // prevent absolute dirs $internalDir = ltrim($internalDir, '/'); - $userFolder = \OC::$server->get(IRootFolder::class)->get(Filesystem::getRoot()); + $userFolder = Server::get(IRootFolder::class)->get(Filesystem::getRoot()); /** @var Folder $dirNode */ $dirNode = $userFolder->get($dir); $files = $dirNode->getDirectoryListing(); /** @var LoggerInterface $logger */ - $logger = \OC::$server->query(LoggerInterface::class); + $logger = Server::get(LoggerInterface::class); foreach ($files as $file) { if ($file instanceof File) { try { diff --git a/lib/private/SubAdmin.php b/lib/private/SubAdmin.php index 90756e2d3fd..5d97623726b 100644 --- a/lib/private/SubAdmin.php +++ b/lib/private/SubAdmin.php @@ -25,10 +25,10 @@ class SubAdmin extends PublicEmitter implements ISubAdmin { private IDBConnection $dbConn, private IEventDispatcher $eventDispatcher, ) { - $this->userManager->listen('\OC\User', 'postDelete', function ($user) { + $this->userManager->listen('\OC\User', 'postDelete', function ($user): void { $this->post_deleteUser($user); }); - $this->groupManager->listen('\OC\Group', 'postDelete', function ($group) { + $this->groupManager->listen('\OC\Group', 'postDelete', function ($group): void { $this->post_deleteGroup($group); }); } diff --git a/lib/private/Support/Subscription/Assertion.php b/lib/private/Support/Subscription/Assertion.php index 04a0dde739f..7e90b0f2bbc 100644 --- a/lib/private/Support/Subscription/Assertion.php +++ b/lib/private/Support/Subscription/Assertion.php @@ -14,14 +14,11 @@ use OCP\Support\Subscription\IAssertion; use OCP\Support\Subscription\IRegistry; class Assertion implements IAssertion { - private IRegistry $registry; - private IFactory $l10nFactory; - private IManager $notificationManager; - - public function __construct(IRegistry $registry, IFactory $l10nFactory, IManager $notificationManager) { - $this->registry = $registry; - $this->l10nFactory = $l10nFactory; - $this->notificationManager = $notificationManager; + public function __construct( + private IRegistry $registry, + private IFactory $l10nFactory, + private IManager $notificationManager, + ) { } /** diff --git a/lib/private/Support/Subscription/Registry.php b/lib/private/Support/Subscription/Registry.php index 34f24d1d026..dec641966b3 100644 --- a/lib/private/Support/Subscription/Registry.php +++ b/lib/private/Support/Subscription/Registry.php @@ -27,28 +27,13 @@ class Registry implements IRegistry { /** @var string */ private $subscriptionService = null; - /** @var IConfig */ - private $config; - - /** @var IServerContainer */ - private $container; - /** @var IUserManager */ - private $userManager; - /** @var IGroupManager */ - private $groupManager; - /** @var LoggerInterface */ - private $logger; - - public function __construct(IConfig $config, - IServerContainer $container, - IUserManager $userManager, - IGroupManager $groupManager, - LoggerInterface $logger) { - $this->config = $config; - $this->container = $container; - $this->userManager = $userManager; - $this->groupManager = $groupManager; - $this->logger = $logger; + public function __construct( + private IConfig $config, + private IServerContainer $container, + private IUserManager $userManager, + private IGroupManager $groupManager, + private LoggerInterface $logger, + ) { } private function getSubscription(): ?ISubscription { diff --git a/lib/private/SystemTag/SystemTagObjectMapper.php b/lib/private/SystemTag/SystemTagObjectMapper.php index ce399d977df..508adb8c88c 100644 --- a/lib/private/SystemTag/SystemTagObjectMapper.php +++ b/lib/private/SystemTag/SystemTagObjectMapper.php @@ -268,7 +268,7 @@ class SystemTagObjectMapper implements ISystemTagObjectMapper { * * @param string[] $tagIds tag ids to check * - * @throws \OCP\SystemTag\TagNotFoundException if at least one tag did not exist + * @throws TagNotFoundException if at least one tag did not exist */ private function assertTagsExist(array $tagIds): void { $tags = $this->tagManager->getTagsByIds($tagIds); diff --git a/lib/private/TagManager.php b/lib/private/TagManager.php index f9d8d71a5aa..e8fd005ff00 100644 --- a/lib/private/TagManager.php +++ b/lib/private/TagManager.php @@ -45,7 +45,7 @@ class TagManager implements ITagManager, IEventListener { * @param boolean $includeShared Whether to include tags for items shared with this user by others. * @param string $userId user for which to retrieve the tags, defaults to the currently * logged in user - * @return \OCP\ITags + * @return ?ITags * * since 20.0.0 $includeShared isn't used anymore */ diff --git a/lib/private/Tags.php b/lib/private/Tags.php index f117a3a7f7c..532ef91950d 100644 --- a/lib/private/Tags.php +++ b/lib/private/Tags.php @@ -18,7 +18,9 @@ use OCP\Files\Folder; use OCP\IDBConnection; use OCP\ITags; use OCP\IUserSession; +use OCP\Server; use OCP\Share_Backend; +use OCP\Util; use Psr\Log\LoggerInterface; class Tags implements ITags { @@ -212,7 +214,7 @@ class Tags implements ITags { } if ($tagId === false) { - $l10n = \OCP\Util::getL10N('core'); + $l10n = Util::getL10N('core'); throw new \Exception( $l10n->t('Could not find category "%s"', [$tag]) ); @@ -461,7 +463,7 @@ class Tags implements ITags { try { return $this->getIdsForTag(ITags::TAG_FAVORITE); } catch (\Exception $e) { - \OCP\Server::get(LoggerInterface::class)->error( + Server::get(LoggerInterface::class)->error( $e->getMessage(), [ 'app' => 'core', @@ -522,7 +524,7 @@ class Tags implements ITags { try { $qb->executeStatement(); } catch (\Exception $e) { - \OCP\Server::get(LoggerInterface::class)->error($e->getMessage(), [ + Server::get(LoggerInterface::class)->error($e->getMessage(), [ 'app' => 'core', 'exception' => $e, ]); diff --git a/lib/private/Talk/Broker.php b/lib/private/Talk/Broker.php index 86e7e7ff4c1..eaf5fad96c6 100644 --- a/lib/private/Talk/Broker.php +++ b/lib/private/Talk/Broker.php @@ -21,22 +21,15 @@ use RuntimeException; use Throwable; class Broker implements IBroker { - private Coordinator $coordinator; - - private IServerContainer $container; - - private LoggerInterface $logger; - private ?bool $hasBackend = null; private ?ITalkBackend $backend = null; - public function __construct(Coordinator $coordinator, - IServerContainer $container, - LoggerInterface $logger) { - $this->coordinator = $coordinator; - $this->container = $container; - $this->logger = $logger; + public function __construct( + private Coordinator $coordinator, + private IServerContainer $container, + private LoggerInterface $logger, + ) { } public function hasBackend(): bool { diff --git a/lib/private/Talk/ConversationOptions.php b/lib/private/Talk/ConversationOptions.php index f167fa6d164..a71f9822d52 100644 --- a/lib/private/Talk/ConversationOptions.php +++ b/lib/private/Talk/ConversationOptions.php @@ -12,10 +12,9 @@ namespace OC\Talk; use OCP\Talk\IConversationOptions; class ConversationOptions implements IConversationOptions { - private bool $isPublic; - - private function __construct(bool $isPublic) { - $this->isPublic = $isPublic; + private function __construct( + private bool $isPublic, + ) { } public static function default(): self { diff --git a/lib/private/TaskProcessing/Manager.php b/lib/private/TaskProcessing/Manager.php index 165cde87bf0..884499d34b0 100644 --- a/lib/private/TaskProcessing/Manager.php +++ b/lib/private/TaskProcessing/Manager.php @@ -14,6 +14,8 @@ use GuzzleHttp\Exception\ServerException; use OC\AppFramework\Bootstrap\Coordinator; use OC\Files\SimpleFS\SimpleFile; use OC\TaskProcessing\Db\TaskMapper; +use OCA\AppAPI\PublicFunctions; +use OCA\Guests\UserBackend; use OCP\App\IAppManager; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Db\MultipleObjectsReturnedException; @@ -41,13 +43,16 @@ use OCP\IUserManager; use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Lock\LockedException; +use OCP\Server; use OCP\SpeechToText\ISpeechToTextProvider; use OCP\SpeechToText\ISpeechToTextProviderWithId; +use OCP\SpeechToText\ISpeechToTextProviderWithUserId; use OCP\TaskProcessing\EShapeType; use OCP\TaskProcessing\Events\GetTaskProcessingProvidersEvent; use OCP\TaskProcessing\Events\TaskFailedEvent; use OCP\TaskProcessing\Events\TaskSuccessfulEvent; use OCP\TaskProcessing\Exception\NotFoundException; +use OCP\TaskProcessing\Exception\PreConditionNotMetException; use OCP\TaskProcessing\Exception\ProcessingException; use OCP\TaskProcessing\Exception\UnauthorizedException; use OCP\TaskProcessing\Exception\UserFacingProcessingException; @@ -62,12 +67,35 @@ use OCP\TaskProcessing\ITriggerableProvider; use OCP\TaskProcessing\ShapeDescriptor; use OCP\TaskProcessing\ShapeEnumValue; use OCP\TaskProcessing\Task; +use OCP\TaskProcessing\TaskTypes\AnalyzeImages; +use OCP\TaskProcessing\TaskTypes\AudioToAudioChat; use OCP\TaskProcessing\TaskTypes\AudioToText; +use OCP\TaskProcessing\TaskTypes\ContextAgentAudioInteraction; +use OCP\TaskProcessing\TaskTypes\ContextAgentInteraction; +use OCP\TaskProcessing\TaskTypes\ContextWrite; +use OCP\TaskProcessing\TaskTypes\GenerateEmoji; +use OCP\TaskProcessing\TaskTypes\ImageToTextOpticalCharacterRecognition; use OCP\TaskProcessing\TaskTypes\TextToImage; +use OCP\TaskProcessing\TaskTypes\TextToSpeech; use OCP\TaskProcessing\TaskTypes\TextToText; +use OCP\TaskProcessing\TaskTypes\TextToTextChangeTone; +use OCP\TaskProcessing\TaskTypes\TextToTextChat; +use OCP\TaskProcessing\TaskTypes\TextToTextChatWithTools; +use OCP\TaskProcessing\TaskTypes\TextToTextFormalization; use OCP\TaskProcessing\TaskTypes\TextToTextHeadline; +use OCP\TaskProcessing\TaskTypes\TextToTextProofread; +use OCP\TaskProcessing\TaskTypes\TextToTextReformulation; +use OCP\TaskProcessing\TaskTypes\TextToTextSimplification; use OCP\TaskProcessing\TaskTypes\TextToTextSummary; use OCP\TaskProcessing\TaskTypes\TextToTextTopics; +use OCP\TaskProcessing\TaskTypes\TextToTextTranslate; +use OCP\TextProcessing\FreePromptTaskType; +use OCP\TextProcessing\HeadlineTaskType; +use OCP\TextProcessing\IProviderWithExpectedRuntime; +use OCP\TextProcessing\IProviderWithId; +use OCP\TextProcessing\IProviderWithUserId; +use OCP\TextProcessing\SummaryTaskType; +use OCP\TextProcessing\TopicsTaskType; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; use Psr\Log\LoggerInterface; @@ -164,14 +192,13 @@ class Manager implements IManager { $newProviders = []; foreach ($oldProviders as $oldProvider) { $provider = new class($oldProvider) implements IProvider, ISynchronousProvider { - private \OCP\TextProcessing\IProvider $provider; - - public function __construct(\OCP\TextProcessing\IProvider $provider) { - $this->provider = $provider; + public function __construct( + private \OCP\TextProcessing\IProvider $provider, + ) { } public function getId(): string { - if ($this->provider instanceof \OCP\TextProcessing\IProviderWithId) { + if ($this->provider instanceof IProviderWithId) { return $this->provider->getId(); } return Manager::LEGACY_PREFIX_TEXTPROCESSING . $this->provider::class; @@ -183,16 +210,16 @@ class Manager implements IManager { public function getTaskTypeId(): string { return match ($this->provider->getTaskType()) { - \OCP\TextProcessing\FreePromptTaskType::class => TextToText::ID, - \OCP\TextProcessing\HeadlineTaskType::class => TextToTextHeadline::ID, - \OCP\TextProcessing\TopicsTaskType::class => TextToTextTopics::ID, - \OCP\TextProcessing\SummaryTaskType::class => TextToTextSummary::ID, + FreePromptTaskType::class => TextToText::ID, + HeadlineTaskType::class => TextToTextHeadline::ID, + TopicsTaskType::class => TextToTextTopics::ID, + SummaryTaskType::class => TextToTextSummary::ID, default => Manager::LEGACY_PREFIX_TEXTPROCESSING . $this->provider->getTaskType(), }; } public function getExpectedRuntime(): int { - if ($this->provider instanceof \OCP\TextProcessing\IProviderWithExpectedRuntime) { + if ($this->provider instanceof IProviderWithExpectedRuntime) { return $this->provider->getExpectedRuntime(); } return 60; @@ -207,7 +234,7 @@ class Manager implements IManager { } public function process(?string $userId, array $input, callable $reportProgress): array { - if ($this->provider instanceof \OCP\TextProcessing\IProviderWithUserId) { + if ($this->provider instanceof IProviderWithUserId) { $this->provider->setUserId($userId); } try { @@ -256,22 +283,22 @@ class Manager implements IManager { foreach ($oldProviders as $oldProvider) { // These are already implemented in the TaskProcessing realm if (in_array($oldProvider->getTaskType(), [ - \OCP\TextProcessing\FreePromptTaskType::class, - \OCP\TextProcessing\HeadlineTaskType::class, - \OCP\TextProcessing\TopicsTaskType::class, - \OCP\TextProcessing\SummaryTaskType::class + FreePromptTaskType::class, + HeadlineTaskType::class, + TopicsTaskType::class, + SummaryTaskType::class ], true)) { continue; } $taskType = new class($oldProvider->getTaskType()) implements ITaskType { - private string $oldTaskTypeClass; private \OCP\TextProcessing\ITaskType $oldTaskType; private IL10N $l; - public function __construct(string $oldTaskTypeClass) { - $this->oldTaskTypeClass = $oldTaskTypeClass; - $this->oldTaskType = \OCP\Server::get($oldTaskTypeClass); - $this->l = \OCP\Server::get(IFactory::class)->get('core'); + public function __construct( + private string $oldTaskTypeClass, + ) { + $this->oldTaskType = Server::get($this->oldTaskTypeClass); + $this->l = Server::get(IFactory::class)->get('core'); } public function getId(): string { @@ -308,17 +335,12 @@ class Manager implements IManager { $newProviders = []; foreach ($oldProviders as $oldProvider) { $newProvider = new class($oldProvider, $this->appData, $this->l10nFactory, $this->userManager) implements IProvider, ISynchronousProvider { - private \OCP\TextToImage\IProvider $provider; - private IAppData $appData; - private IFactory $l10nFactory; - - private IUserManager $userManager; - - public function __construct(\OCP\TextToImage\IProvider $provider, IAppData $appData, IFactory $l10nFactory, IUserManager $userManager) { - $this->provider = $provider; - $this->appData = $appData; - $this->l10nFactory = $l10nFactory; - $this->userManager = $userManager; + public function __construct( + private readonly \OCP\TextToImage\IProvider $provider, + private readonly IAppData $appData, + private readonly IFactory $l10nFactory, + private readonly IUserManager $userManager, + ) { } public function getId(): string { @@ -457,15 +479,11 @@ class Manager implements IManager { $newProviders = []; foreach ($oldProviders as $oldProvider) { $newProvider = new class($oldProvider, $this->rootFolder, $this->appData) implements IProvider, ISynchronousProvider { - private ISpeechToTextProvider $provider; - private IAppData $appData; - - private IRootFolder $rootFolder; - - public function __construct(ISpeechToTextProvider $provider, IRootFolder $rootFolder, IAppData $appData) { - $this->provider = $provider; - $this->rootFolder = $rootFolder; - $this->appData = $appData; + public function __construct( + private ISpeechToTextProvider $provider, + private IRootFolder $rootFolder, + private IAppData $appData, + ) { } public function getId(): string { @@ -496,7 +514,7 @@ class Manager implements IManager { } public function process(?string $userId, array $input, callable $reportProgress): array { - if ($this->provider instanceof \OCP\SpeechToText\ISpeechToTextProviderWithUserId) { + if ($this->provider instanceof ISpeechToTextProviderWithUserId) { $this->provider->setUserId($userId); } try { @@ -610,28 +628,28 @@ class Manager implements IManager { // Default task types $taskTypes = [ - \OCP\TaskProcessing\TaskTypes\TextToText::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToText::class), - \OCP\TaskProcessing\TaskTypes\TextToTextTopics::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextTopics::class), - \OCP\TaskProcessing\TaskTypes\TextToTextHeadline::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextHeadline::class), - \OCP\TaskProcessing\TaskTypes\TextToTextSummary::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextSummary::class), - \OCP\TaskProcessing\TaskTypes\TextToTextFormalization::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextFormalization::class), - \OCP\TaskProcessing\TaskTypes\TextToTextSimplification::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextSimplification::class), - \OCP\TaskProcessing\TaskTypes\TextToTextChat::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextChat::class), - \OCP\TaskProcessing\TaskTypes\TextToTextTranslate::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextTranslate::class), - \OCP\TaskProcessing\TaskTypes\TextToTextReformulation::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextReformulation::class), - \OCP\TaskProcessing\TaskTypes\TextToImage::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToImage::class), - \OCP\TaskProcessing\TaskTypes\AudioToText::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\AudioToText::class), - \OCP\TaskProcessing\TaskTypes\ContextWrite::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\ContextWrite::class), - \OCP\TaskProcessing\TaskTypes\GenerateEmoji::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\GenerateEmoji::class), - \OCP\TaskProcessing\TaskTypes\TextToTextChangeTone::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextChangeTone::class), - \OCP\TaskProcessing\TaskTypes\TextToTextChatWithTools::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextChatWithTools::class), - \OCP\TaskProcessing\TaskTypes\ContextAgentInteraction::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\ContextAgentInteraction::class), - \OCP\TaskProcessing\TaskTypes\TextToTextProofread::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextProofread::class), - \OCP\TaskProcessing\TaskTypes\TextToSpeech::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToSpeech::class), - \OCP\TaskProcessing\TaskTypes\AudioToAudioChat::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\AudioToAudioChat::class), - \OCP\TaskProcessing\TaskTypes\ContextAgentAudioInteraction::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\ContextAgentAudioInteraction::class), - \OCP\TaskProcessing\TaskTypes\AnalyzeImages::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\AnalyzeImages::class), - \OCP\TaskProcessing\TaskTypes\ImageToTextOpticalCharacterRecognition::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\ImageToTextOpticalCharacterRecognition::class), + TextToText::ID => Server::get(TextToText::class), + TextToTextTopics::ID => Server::get(TextToTextTopics::class), + TextToTextHeadline::ID => Server::get(TextToTextHeadline::class), + TextToTextSummary::ID => Server::get(TextToTextSummary::class), + TextToTextFormalization::ID => Server::get(TextToTextFormalization::class), + TextToTextSimplification::ID => Server::get(TextToTextSimplification::class), + TextToTextChat::ID => Server::get(TextToTextChat::class), + TextToTextTranslate::ID => Server::get(TextToTextTranslate::class), + TextToTextReformulation::ID => Server::get(TextToTextReformulation::class), + TextToImage::ID => Server::get(TextToImage::class), + AudioToText::ID => Server::get(AudioToText::class), + ContextWrite::ID => Server::get(ContextWrite::class), + GenerateEmoji::ID => Server::get(GenerateEmoji::class), + TextToTextChangeTone::ID => Server::get(TextToTextChangeTone::class), + TextToTextChatWithTools::ID => Server::get(TextToTextChatWithTools::class), + ContextAgentInteraction::ID => Server::get(ContextAgentInteraction::class), + TextToTextProofread::ID => Server::get(TextToTextProofread::class), + TextToSpeech::ID => Server::get(TextToSpeech::class), + AudioToAudioChat::ID => Server::get(AudioToAudioChat::class), + ContextAgentAudioInteraction::ID => Server::get(ContextAgentAudioInteraction::class), + AnalyzeImages::ID => Server::get(AnalyzeImages::class), + ImageToTextOpticalCharacterRecognition::ID => Server::get(ImageToTextOpticalCharacterRecognition::class), ]; foreach ($context->getTaskProcessingTaskTypes() as $providerServiceRegistration) { @@ -979,7 +997,7 @@ class Manager implements IManager { } $guestsAllowed = $this->appConfig->getValueString('core', 'ai.taskprocessing_guests', 'false'); - if ($guestsAllowed == 'true' || !class_exists(\OCA\Guests\UserBackend::class) || !($user->getBackend() instanceof \OCA\Guests\UserBackend)) { + if ($guestsAllowed == 'true' || !class_exists(UserBackend::class) || !($user->getBackend() instanceof UserBackend)) { return true; } return false; @@ -987,10 +1005,10 @@ class Manager implements IManager { public function scheduleTask(Task $task): void { if (!$this->checkGuestAccess($task->getUserId())) { - throw new \OCP\TaskProcessing\Exception\PreConditionNotMetException('Access to this resource is forbidden for guests.'); + throw new PreConditionNotMetException('Access to this resource is forbidden for guests.'); } if (!$this->canHandleTask($task)) { - throw new \OCP\TaskProcessing\Exception\PreConditionNotMetException('No task processing provider is installed that can handle this task type: ' . $task->getTaskTypeId()); + throw new PreConditionNotMetException('No task processing provider is installed that can handle this task type: ' . $task->getTaskTypeId()); } $this->prepareTask($task); $task->setStatus(Task::STATUS_SCHEDULED); @@ -1026,10 +1044,10 @@ class Manager implements IManager { public function runTask(Task $task): Task { if (!$this->checkGuestAccess($task->getUserId())) { - throw new \OCP\TaskProcessing\Exception\PreConditionNotMetException('Access to this resource is forbidden for guests.'); + throw new PreConditionNotMetException('Access to this resource is forbidden for guests.'); } if (!$this->canHandleTask($task)) { - throw new \OCP\TaskProcessing\Exception\PreConditionNotMetException('No task processing provider is installed that can handle this task type: ' . $task->getTaskTypeId()); + throw new PreConditionNotMetException('No task processing provider is installed that can handle this task type: ' . $task->getTaskTypeId()); } $provider = $this->getPreferredProvider($task->getTaskTypeId()); @@ -1239,7 +1257,7 @@ class Manager implements IManager { $taskEntity = $this->taskMapper->findOldestScheduledByType($taskTypeIds, $taskIdsToIgnore); return $taskEntity->toPublicTask(); } catch (DoesNotExistException $e) { - throw new \OCP\TaskProcessing\Exception\NotFoundException('Could not find the task', previous: $e); + throw new NotFoundException('Could not find the task', previous: $e); } catch (\OCP\DB\Exception $e) { throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', previous: $e); } catch (\JsonException $e) { @@ -1251,7 +1269,7 @@ class Manager implements IManager { try { return array_map(fn ($taskEntity) => $taskEntity->toPublicTask(), $this->taskMapper->findNOldestScheduledByType($taskTypeIds, $taskIdsToIgnore, $numberOfTasks)); } catch (DoesNotExistException $e) { - throw new \OCP\TaskProcessing\Exception\NotFoundException('Could not find the task', previous: $e); + throw new NotFoundException('Could not find the task', previous: $e); } catch (\OCP\DB\Exception $e) { throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', previous: $e); } catch (\JsonException $e) { @@ -1306,7 +1324,7 @@ class Manager implements IManager { $taskEntity = $this->taskMapper->findByIdAndUser($id, $userId); return $taskEntity->toPublicTask(); } catch (DoesNotExistException $e) { - throw new \OCP\TaskProcessing\Exception\NotFoundException('Could not find the task', 0, $e); + throw new NotFoundException('Could not find the task', 0, $e); } catch (MultipleObjectsReturnedException|\OCP\DB\Exception $e) { throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e); } catch (\JsonException $e) { @@ -1703,7 +1721,7 @@ class Manager implements IManager { return; } try { - $appApiFunctions = \OCP\Server::get(\OCA\AppAPI\PublicFunctions::class); + $appApiFunctions = Server::get(PublicFunctions::class); } catch (ContainerExceptionInterface|NotFoundExceptionInterface) { $this->logger->warning('Task processing AppAPI webhook failed for task ' . $task->getId() . '. Could not get AppAPI public functions.'); return; diff --git a/lib/private/TaskProcessing/RemoveOldTasksBackgroundJob.php b/lib/private/TaskProcessing/RemoveOldTasksBackgroundJob.php index 52fc204b752..1f1f991de3f 100644 --- a/lib/private/TaskProcessing/RemoveOldTasksBackgroundJob.php +++ b/lib/private/TaskProcessing/RemoveOldTasksBackgroundJob.php @@ -10,10 +10,12 @@ use OC\TaskProcessing\Db\TaskMapper; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\TimedJob; use OCP\Files\AppData\IAppDataFactory; +use OCP\Files\IAppData; +use OCP\Files\NotFoundException; use Psr\Log\LoggerInterface; class RemoveOldTasksBackgroundJob extends TimedJob { - private \OCP\Files\IAppData $appData; + private IAppData $appData; public function __construct( ITimeFactory $timeFactory, @@ -45,12 +47,12 @@ class RemoveOldTasksBackgroundJob extends TimedJob { } try { iterator_to_array($this->taskProcessingManager->clearFilesOlderThan($this->appData->getFolder('text2image'))); - } catch (\OCP\Files\NotFoundException $e) { + } catch (NotFoundException $e) { // noop } try { iterator_to_array($this->taskProcessingManager->clearFilesOlderThan($this->appData->getFolder('audio2text'))); - } catch (\OCP\Files\NotFoundException $e) { + } catch (NotFoundException $e) { // noop } } diff --git a/lib/private/TempManager.php b/lib/private/TempManager.php index 4c0ffcf43d7..29c4ea7ccfa 100644 --- a/lib/private/TempManager.php +++ b/lib/private/TempManager.php @@ -12,6 +12,7 @@ use OCP\Files; use OCP\IConfig; use OCP\ITempManager; use OCP\Security\ISecureRandom; +use OCP\Server; use Psr\Log\LoggerInterface; class TempManager implements ITempManager { @@ -19,25 +20,23 @@ class TempManager implements ITempManager { protected $current = []; /** @var string i.e. /tmp on linux systems */ protected $tmpBaseDir; - /** @var LoggerInterface */ - protected $log; - /** @var IConfig */ - protected $config; /** @var IniGetWrapper */ protected $iniGetWrapper; /** Prefix */ public const TMP_PREFIX = 'oc_tmp_'; - public function __construct(LoggerInterface $logger, IConfig $config, IniGetWrapper $iniGetWrapper) { - $this->log = $logger; - $this->config = $config; + public function __construct( + protected LoggerInterface $log, + protected IConfig $config, + IniGetWrapper $iniGetWrapper, + ) { $this->iniGetWrapper = $iniGetWrapper; $this->tmpBaseDir = $this->getTempBaseDir(); } private function generateTemporaryPath(string $postFix): string { - $secureRandom = \OCP\Server::get(ISecureRandom::class); + $secureRandom = Server::get(ISecureRandom::class); $absolutePath = $this->tmpBaseDir . '/' . self::TMP_PREFIX . $secureRandom->generate(32, ISecureRandom::CHAR_ALPHANUMERIC); if ($postFix !== '') { diff --git a/lib/private/TemplateLayout.php b/lib/private/TemplateLayout.php index 6c1fe71e4e9..f3109ba8cb5 100644 --- a/lib/private/TemplateLayout.php +++ b/lib/private/TemplateLayout.php @@ -17,17 +17,21 @@ use OC\Core\AppInfo\Application; use OC\Core\AppInfo\ConfigLexicon; use OC\Files\FilenameValidator; use OC\Search\SearchQuery; +use OC\Security\CSP\ContentSecurityPolicyNonceManager; use OC\Template\CSSResourceLocator; use OC\Template\JSConfigHelper; use OC\Template\JSResourceLocator; +use OCA\Theming\Service\ThemesService; use OCP\App\IAppManager; use OCP\AppFramework\Http\TemplateResponse; use OCP\Defaults; use OCP\IAppConfig; use OCP\IConfig; +use OCP\IGroupManager; use OCP\IInitialStateService; use OCP\INavigationManager; use OCP\IRequest; +use OCP\ISession; use OCP\IURLGenerator; use OCP\IUserSession; use OCP\L10N\IFactory; @@ -198,7 +202,7 @@ class TemplateLayout { // Set body data-theme try { - $themesService = Server::get(\OCA\Theming\Service\ThemesService::class); + $themesService = Server::get(ThemesService::class); } catch (\Exception) { $themesService = null; } @@ -222,26 +226,26 @@ class TemplateLayout { // see https://github.com/nextcloud/server/pull/22636 for details $jsConfigHelper = new JSConfigHelper( $this->serverVersion, - \OCP\Util::getL10N('lib'), - \OCP\Server::get(Defaults::class), + Util::getL10N('lib'), + Server::get(Defaults::class), $this->appManager, - \OC::$server->getSession(), - \OC::$server->getUserSession()->getUser(), + Server::get(ISession::class), + Server::get(IUserSession::class)->getUser(), $this->config, $this->appConfig, - \OC::$server->getGroupManager(), - \OC::$server->get(IniGetWrapper::class), - \OC::$server->getURLGenerator(), - \OC::$server->get(CapabilitiesManager::class), - \OCP\Server::get(IInitialStateService::class), - \OCP\Server::get(IProvider::class), - \OCP\Server::get(FilenameValidator::class), + Server::get(IGroupManager::class), + Server::get(IniGetWrapper::class), + Server::get(IURLGenerator::class), + Server::get(CapabilitiesManager::class), + Server::get(IInitialStateService::class), + Server::get(IProvider::class), + Server::get(FilenameValidator::class), ); $config = $jsConfigHelper->getConfig(); - if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) { + if (Server::get(ContentSecurityPolicyNonceManager::class)->browserSupportsCspV3()) { $page->assign('inline_ocjs', $config); } else { - $page->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash])); + $page->append('jsfiles', Server::get(IURLGenerator::class)->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash])); } } foreach ($jsFiles as $info) { @@ -250,7 +254,7 @@ class TemplateLayout { $page->append('jsfiles', $web . '/' . $file . $this->getVersionHashSuffix()); } - $request = \OCP\Server::get(IRequest::class); + $request = Server::get(IRequest::class); try { $pathInfo = $request->getPathInfo(); @@ -261,7 +265,7 @@ class TemplateLayout { // Do not initialise scss appdata until we have a fully installed instance // Do not load scss for update, errors, installation or login page if ($this->config->getSystemValueBool('installed', false) - && !\OCP\Util::needUpgrade() + && !Util::needUpgrade() && $pathInfo !== '' && !preg_match('/^\/login/', $pathInfo) && $renderAs !== TemplateResponse::RENDER_AS_ERROR @@ -368,7 +372,7 @@ class TemplateLayout { private function findStylesheetFiles(array $styles): array { if ($this->cssLocator === null) { - $this->cssLocator = \OCP\Server::get(CSSResourceLocator::class); + $this->cssLocator = Server::get(CSSResourceLocator::class); } $this->cssLocator->find($styles); return $this->cssLocator->getResources(); @@ -390,7 +394,7 @@ class TemplateLayout { private function findJavascriptFiles(array $scripts): array { if ($this->jsLocator === null) { - $this->jsLocator = \OCP\Server::get(JSResourceLocator::class); + $this->jsLocator = Server::get(JSResourceLocator::class); } $this->jsLocator->find($scripts); return $this->jsLocator->getResources(); diff --git a/lib/private/TextToImage/Db/Task.php b/lib/private/TextToImage/Db/Task.php index cc92c865220..48a8bcc6c40 100644 --- a/lib/private/TextToImage/Db/Task.php +++ b/lib/private/TextToImage/Db/Task.php @@ -12,6 +12,7 @@ namespace OC\TextToImage\Db; use DateTime; use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Server; use OCP\TextToImage\Task as OCPTask; /** @@ -79,7 +80,7 @@ class Task extends Entity { /** @var Task $dbTask */ $dbTask = Task::fromParams([ 'id' => $task->getId(), - 'lastUpdated' => \OCP\Server::get(ITimeFactory::class)->getDateTime(), + 'lastUpdated' => Server::get(ITimeFactory::class)->getDateTime(), 'status' => $task->getStatus(), 'numberOfImages' => $task->getNumberOfImages(), 'input' => $task->getInput(), diff --git a/lib/private/URLGenerator.php b/lib/private/URLGenerator.php index b6c4b49469d..5269f31019a 100644 --- a/lib/private/URLGenerator.php +++ b/lib/private/URLGenerator.php @@ -18,45 +18,32 @@ use OCP\INavigationManager; use OCP\IRequest; use OCP\IURLGenerator; use OCP\IUserSession; +use OCP\Server; use RuntimeException; /** * Class to generate URLs */ class URLGenerator implements IURLGenerator { - /** @var IConfig */ - private $config; - /** @var IUserSession */ - public $userSession; - /** @var ICacheFactory */ - private $cacheFactory; - /** @var IRequest */ - private $request; - /** @var Router */ - private $router; /** @var null|string */ private $baseUrl = null; private ?IAppManager $appManager = null; private ?INavigationManager $navigationManager = null; - public function __construct(IConfig $config, - IUserSession $userSession, - ICacheFactory $cacheFactory, - IRequest $request, - Router $router, + public function __construct( + private IConfig $config, + public IUserSession $userSession, + private ICacheFactory $cacheFactory, + private IRequest $request, + private Router $router, ) { - $this->config = $config; - $this->userSession = $userSession; - $this->cacheFactory = $cacheFactory; - $this->request = $request; - $this->router = $router; } private function getAppManager(): IAppManager { if ($this->appManager !== null) { return $this->appManager; } - $this->appManager = \OCP\Server::get(IAppManager::class); + $this->appManager = Server::get(IAppManager::class); return $this->appManager; } @@ -64,7 +51,7 @@ class URLGenerator implements IURLGenerator { if ($this->navigationManager !== null) { return $this->navigationManager; } - $this->navigationManager = \OCP\Server::get(INavigationManager::class); + $this->navigationManager = Server::get(INavigationManager::class); return $this->navigationManager; } @@ -204,7 +191,7 @@ class URLGenerator implements IURLGenerator { $themingEnabled = $this->config->getSystemValueBool('installed', false) && $this->getAppManager()->isEnabledForUser('theming'); $themingImagePath = false; if ($themingEnabled) { - $themingDefaults = \OC::$server->get('ThemingDefaults'); + $themingDefaults = Server::get('ThemingDefaults'); if ($themingDefaults instanceof ThemingDefaults) { $themingImagePath = $themingDefaults->replaceImagePath($appName, $file); } @@ -277,7 +264,7 @@ class URLGenerator implements IURLGenerator { * @return string url to the online documentation */ public function linkToDocs(string $key): string { - $theme = \OC::$server->get('ThemingDefaults'); + $theme = Server::get('ThemingDefaults'); return $theme->buildDocLinkToKey($key); } diff --git a/lib/private/Updater.php b/lib/private/Updater.php index da7b52e5493..8c0a3f363d3 100644 --- a/lib/private/Updater.php +++ b/lib/private/Updater.php @@ -30,6 +30,7 @@ use OCP\HintException; use OCP\IAppConfig; use OCP\IConfig; use OCP\ILogger; +use OCP\Server; use OCP\ServerVersion; use OCP\Util; use Psr\Log\LoggerInterface; @@ -218,7 +219,7 @@ class Updater extends BasicEmitter { ); // pre-upgrade repairs - $repair = \OCP\Server::get(Repair::class); + $repair = Server::get(Repair::class); $repair->setRepairSteps(Repair::getBeforeUpgradeRepairSteps()); $repair->run(); @@ -236,7 +237,7 @@ class Updater extends BasicEmitter { $this->doAppUpgrade(); // Update the appfetchers version so it downloads the correct list from the appstore - \OC::$server->get(AppFetcher::class)->setVersion($currentVersion); + Server::get(AppFetcher::class)->setVersion($currentVersion); // upgrade appstore apps $this->upgradeAppStoreApps($this->appManager->getEnabledApps()); @@ -258,7 +259,7 @@ class Updater extends BasicEmitter { } // post-upgrade repairs - $repair = \OCP\Server::get(Repair::class); + $repair = Server::get(Repair::class); $repair->setRepairSteps(Repair::getRepairSteps()); $repair->run(); @@ -266,7 +267,7 @@ class Updater extends BasicEmitter { $this->appConfig->setValueInt('core', 'lastupdatedat', 0); // Check for code integrity if not disabled - if (\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) { + if (Server::get(Checker::class)->isCodeCheckEnforced()) { $this->emit('\OC\Updater', 'startCheckCodeIntegrity'); $this->checker->runInstanceVerification(); $this->emit('\OC\Updater', 'finishedCheckCodeIntegrity'); @@ -281,7 +282,7 @@ class Updater extends BasicEmitter { $this->emit('\OC\Updater', 'dbUpgradeBefore'); // execute core migrations - $ms = new MigrationService('core', \OC::$server->get(Connection::class)); + $ms = new MigrationService('core', Server::get(Connection::class)); $ms->migrate(); $this->emit('\OC\Updater', 'dbUpgrade'); @@ -408,7 +409,7 @@ class Updater extends BasicEmitter { $log = $this->log; /** @var IEventDispatcher $dispatcher */ - $dispatcher = \OC::$server->get(IEventDispatcher::class); + $dispatcher = Server::get(IEventDispatcher::class); $dispatcher->addListener( MigratorExecuteSqlEvent::class, function (MigratorExecuteSqlEvent $event) use ($log): void { @@ -447,62 +448,62 @@ class Updater extends BasicEmitter { $dispatcher->addListener(RepairErrorEvent::class, $repairListener); - $this->listen('\OC\Updater', 'maintenanceEnabled', function () use ($log) { + $this->listen('\OC\Updater', 'maintenanceEnabled', function () use ($log): void { $log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'maintenanceDisabled', function () use ($log) { + $this->listen('\OC\Updater', 'maintenanceDisabled', function () use ($log): void { $log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'maintenanceActive', function () use ($log) { + $this->listen('\OC\Updater', 'maintenanceActive', function () use ($log): void { $log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'updateEnd', function ($success) use ($log) { + $this->listen('\OC\Updater', 'updateEnd', function ($success) use ($log): void { if ($success) { $log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']); } else { $log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']); } }); - $this->listen('\OC\Updater', 'dbUpgradeBefore', function () use ($log) { + $this->listen('\OC\Updater', 'dbUpgradeBefore', function () use ($log): void { $log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'dbUpgrade', function () use ($log) { + $this->listen('\OC\Updater', 'dbUpgrade', function () use ($log): void { $log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use ($log) { + $this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use ($log): void { $log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($log) { + $this->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($log): void { $log->debug('\OC\Updater::checkAppStoreAppBefore: Checking for update of app "' . $app . '" in appstore', ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($log) { + $this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($log): void { $log->info('\OC\Updater::upgradeAppStoreApp: Update app "' . $app . '" from appstore', ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($log) { + $this->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($log): void { $log->debug('\OC\Updater::checkAppStoreApp: Checked for update of app "' . $app . '" in appstore', ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) { + $this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log): void { $log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <' . $app . '> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) { + $this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log): void { $log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) { + $this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log): void { $log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'failure', function ($message) use ($log) { + $this->listen('\OC\Updater', 'failure', function ($message) use ($log): void { $log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'setDebugLogLevel', function () use ($log) { + $this->listen('\OC\Updater', 'setDebugLogLevel', function () use ($log): void { $log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use ($log) { + $this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use ($log): void { $log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use ($log) { + $this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use ($log): void { $log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']); }); - $this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use ($log) { + $this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use ($log): void { $log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']); }); } diff --git a/lib/private/User/BackgroundJobs/CleanupDeletedUsers.php b/lib/private/User/BackgroundJobs/CleanupDeletedUsers.php index f999031a2a9..0adb7861670 100644 --- a/lib/private/User/BackgroundJobs/CleanupDeletedUsers.php +++ b/lib/private/User/BackgroundJobs/CleanupDeletedUsers.php @@ -15,6 +15,7 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\TimedJob; use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; +use OCP\Server; use Psr\Log\LoggerInterface; class CleanupDeletedUsers extends TimedJob { @@ -49,7 +50,7 @@ class CleanupDeletedUsers extends TimedJob { $user = new User( $userId, $backend, - \OCP\Server::get(IEventDispatcher::class), + Server::get(IEventDispatcher::class), $this->userManager, $this->config, ); diff --git a/lib/private/User/Database.php b/lib/private/User/Database.php index 31488247939..e64a1cc88f9 100644 --- a/lib/private/User/Database.php +++ b/lib/private/User/Database.php @@ -17,6 +17,7 @@ use OCP\IDBConnection; use OCP\IUserManager; use OCP\Security\Events\ValidatePasswordPolicyEvent; use OCP\Security\IHasher; +use OCP\Server; use OCP\User\Backend\ABackend; use OCP\User\Backend\ICheckPasswordBackend; use OCP\User\Backend\ICreateUserBackend; @@ -48,7 +49,6 @@ class Database extends ABackend implements private IConfig $config; private ?IDBConnection $dbConnection; private IEventDispatcher $eventDispatcher; - private string $table; use TTransactional; @@ -58,11 +58,13 @@ class Database extends ABackend implements * @param IEventDispatcher $eventDispatcher * @param string $table */ - public function __construct($eventDispatcher = null, $table = 'users') { + public function __construct( + $eventDispatcher = null, + private string $table = 'users', + ) { $this->cache = new CappedMemoryCache(); - $this->table = $table; - $this->eventDispatcher = $eventDispatcher ?? \OCP\Server::get(IEventDispatcher::class); - $this->config = \OCP\Server::get(IConfig::class); + $this->eventDispatcher = $eventDispatcher ?? Server::get(IEventDispatcher::class); + $this->config = Server::get(IConfig::class); $this->dbConnection = null; } @@ -71,7 +73,7 @@ class Database extends ABackend implements */ private function getDbConnection() { if ($this->dbConnection === null) { - $this->dbConnection = \OCP\Server::get(IDBConnection::class); + $this->dbConnection = Server::get(IDBConnection::class); } return $this->dbConnection; } @@ -99,7 +101,7 @@ class Database extends ABackend implements $qb->insert($this->table) ->values([ 'uid' => $qb->createNamedParameter($uid), - 'password' => $qb->createNamedParameter(\OCP\Server::get(IHasher::class)->hash($password)), + 'password' => $qb->createNamedParameter(Server::get(IHasher::class)->hash($password)), 'uid_lower' => $qb->createNamedParameter(mb_strtolower($uid)), ]); @@ -168,7 +170,7 @@ class Database extends ABackend implements $this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password)); - $hasher = \OCP\Server::get(IHasher::class); + $hasher = Server::get(IHasher::class); $hashedPassword = $hasher->hash($password); $return = $this->updatePassword($uid, $hashedPassword); @@ -204,7 +206,7 @@ class Database extends ABackend implements } public function setPasswordHash(string $userId, string $passwordHash): bool { - if (!\OCP\Server::get(IHasher::class)->validate($passwordHash)) { + if (!Server::get(IHasher::class)->validate($passwordHash)) { throw new InvalidArgumentException(); } @@ -355,7 +357,7 @@ class Database extends ABackend implements if ($found && is_array($this->cache[$loginName])) { $storedHash = $this->cache[$loginName]['password']; $newHash = ''; - if (\OCP\Server::get(IHasher::class)->verify($password, $storedHash, $newHash)) { + if (Server::get(IHasher::class)->verify($password, $storedHash, $newHash)) { if (!empty($newHash)) { $this->updatePassword($loginName, $newHash); } @@ -523,10 +525,10 @@ class Database extends ABackend implements throw new \Exception('key uid is expected to be set in $param'); } - $backends = \OCP\Server::get(IUserManager::class)->getBackends(); + $backends = Server::get(IUserManager::class)->getBackends(); foreach ($backends as $backend) { if ($backend instanceof Database) { - /** @var \OC\User\Database $backend */ + /** @var Database $backend */ $uid = $backend->loginName2UserName($param['uid']); if ($uid !== false) { $param['uid'] = $uid; diff --git a/lib/private/User/DisplayNameCache.php b/lib/private/User/DisplayNameCache.php index 4321d95f88e..96386ca35f2 100644 --- a/lib/private/User/DisplayNameCache.php +++ b/lib/private/User/DisplayNameCache.php @@ -29,11 +29,12 @@ class DisplayNameCache implements IEventListener { private array $cache = []; private ICache $memCache; - private IUserManager $userManager; - public function __construct(ICacheFactory $cacheFactory, IUserManager $userManager) { + public function __construct( + ICacheFactory $cacheFactory, + private IUserManager $userManager, + ) { $this->memCache = $cacheFactory->createDistributed('displayNameMappingCache'); - $this->userManager = $userManager; } public function getDisplayName(string $userId): ?string { diff --git a/lib/private/User/LazyUser.php b/lib/private/User/LazyUser.php index 093a1824026..a3a681a8fcf 100644 --- a/lib/private/User/LazyUser.php +++ b/lib/private/User/LazyUser.php @@ -14,16 +14,13 @@ use OCP\UserInterface; class LazyUser implements IUser { private ?IUser $user = null; - private string $uid; - private ?string $displayName; - private IUserManager $userManager; - private ?UserInterface $backend; - public function __construct(string $uid, IUserManager $userManager, ?string $displayName = null, ?UserInterface $backend = null) { - $this->uid = $uid; - $this->userManager = $userManager; - $this->displayName = $displayName; - $this->backend = $backend; + public function __construct( + private string $uid, + private IUserManager $userManager, + private ?string $displayName = null, + private ?UserInterface $backend = null, + ) { } private function getUser(): IUser { diff --git a/lib/private/User/Listeners/BeforeUserDeletedListener.php b/lib/private/User/Listeners/BeforeUserDeletedListener.php index 50dc9835400..c5d7efa767a 100644 --- a/lib/private/User/Listeners/BeforeUserDeletedListener.php +++ b/lib/private/User/Listeners/BeforeUserDeletedListener.php @@ -20,14 +20,11 @@ use Psr\Log\LoggerInterface; * @template-implements IEventListener */ class BeforeUserDeletedListener implements IEventListener { - private IAvatarManager $avatarManager; - private ICredentialsManager $credentialsManager; - private LoggerInterface $logger; - - public function __construct(LoggerInterface $logger, IAvatarManager $avatarManager, ICredentialsManager $credentialsManager) { - $this->avatarManager = $avatarManager; - $this->credentialsManager = $credentialsManager; - $this->logger = $logger; + public function __construct( + private LoggerInterface $logger, + private IAvatarManager $avatarManager, + private ICredentialsManager $credentialsManager, + ) { } public function handle(Event $event): void { diff --git a/lib/private/User/Listeners/UserChangedListener.php b/lib/private/User/Listeners/UserChangedListener.php index 8f618950255..4dd4439574d 100644 --- a/lib/private/User/Listeners/UserChangedListener.php +++ b/lib/private/User/Listeners/UserChangedListener.php @@ -18,10 +18,9 @@ use OCP\User\Events\UserChangedEvent; * @template-implements IEventListener */ class UserChangedListener implements IEventListener { - private IAvatarManager $avatarManager; - - public function __construct(IAvatarManager $avatarManager) { - $this->avatarManager = $avatarManager; + public function __construct( + private IAvatarManager $avatarManager, + ) { } public function handle(Event $event): void { diff --git a/lib/private/User/Manager.php b/lib/private/User/Manager.php index cf832148c92..6fae93226da 100644 --- a/lib/private/User/Manager.php +++ b/lib/private/User/Manager.php @@ -18,6 +18,7 @@ use OCP\ICacheFactory; use OCP\IConfig; use OCP\IDBConnection; use OCP\IGroup; +use OCP\IRequest; use OCP\IUser; use OCP\IUserBackend; use OCP\IUserManager; @@ -34,6 +35,7 @@ use OCP\User\Backend\ISearchKnownUsersBackend; use OCP\User\Events\BeforeUserCreatedEvent; use OCP\User\Events\UserCreatedEvent; use OCP\UserInterface; +use OCP\Util; use Psr\Log\LoggerInterface; /** @@ -60,7 +62,7 @@ class Manager extends PublicEmitter implements IUserManager { private array $backends = []; /** - * @var array $cachedUsers + * @var array $cachedUsers */ private array $cachedUsers = []; @@ -110,7 +112,7 @@ class Manager extends PublicEmitter implements IUserManager { * get a user by user id * * @param string $uid - * @return \OC\User\User|null Either the user or null if the specified user does not exist + * @return User|null Either the user or null if the specified user does not exist */ public function get($uid) { if (is_null($uid) || $uid === '' || $uid === false) { @@ -156,9 +158,9 @@ class Manager extends PublicEmitter implements IUserManager { * get or construct the user object * * @param string $uid - * @param \OCP\UserInterface $backend + * @param UserInterface $backend * @param bool $cacheUser If false the newly created user object will not be cached - * @return \OC\User\User + * @return User */ public function getUserObject($uid, $backend, $cacheUser = true) { if ($backend instanceof IGetRealUIDBackend) { @@ -202,7 +204,7 @@ class Manager extends PublicEmitter implements IUserManager { $result = $this->checkPasswordNoLogging($loginName, $password); if ($result === false) { - $this->logger->warning('Login failed: \'' . $loginName . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']); + $this->logger->warning('Login failed: \'' . $loginName . '\' (Remote IP: \'' . Server::get(IRequest::class)->getRemoteAddress() . '\')', ['app' => 'core']); } return $result; @@ -376,7 +378,7 @@ class Manager extends PublicEmitter implements IUserManager { public function createUser($uid, $password) { // DI injection is not used here as IRegistry needs the user manager itself for user count and thus it would create a cyclic dependency /** @var IAssertion $assertion */ - $assertion = \OC::$server->get(IAssertion::class); + $assertion = Server::get(IAssertion::class); $assertion->createUserIsLegit(); $localBackends = []; @@ -409,7 +411,7 @@ class Manager extends PublicEmitter implements IUserManager { * @throws \InvalidArgumentException */ public function createUserFromBackend($uid, $password, UserInterface $backend) { - $l = \OCP\Util::getL10N('lib'); + $l = Util::getL10N('lib'); $this->validateUserId($uid, true); @@ -530,7 +532,7 @@ class Manager extends PublicEmitter implements IUserManager { * The callback is executed for each user on each backend. * If the callback returns false no further users will be retrieved. * - * @psalm-param \Closure(\OCP\IUser):?bool $callback + * @psalm-param \Closure(IUser):?bool $callback * @param string $search * @param boolean $onlySeen when true only users that have a lastLogin entry * in the preferences table will be affected diff --git a/lib/private/User/Session.php b/lib/private/User/Session.php index 27c9d42d198..811c5ba4bc3 100644 --- a/lib/private/User/Session.php +++ b/lib/private/User/Session.php @@ -8,6 +8,7 @@ namespace OC\User; use OC; +use OC\Authentication\Events\LoginFailed; use OC\Authentication\Exceptions\PasswordlessTokenException; use OC\Authentication\Exceptions\PasswordLoginForbiddenException; use OC\Authentication\Token\IProvider; @@ -16,6 +17,7 @@ use OC\Authentication\Token\PublicKeyToken; use OC\Authentication\TwoFactorAuth\Manager as TwoFactorAuthManager; use OC\Hooks\Emitter; use OC\Hooks\PublicEmitter; +use OC\Http\CookieHelper; use OC\Security\CSRF\CsrfTokenManager; use OC_User; use OC_Util; @@ -36,6 +38,7 @@ use OCP\IUserSession; use OCP\Lockdown\ILockdownManager; use OCP\Security\Bruteforce\IThrottler; use OCP\Security\ISecureRandom; +use OCP\Server; use OCP\Session\Exceptions\SessionNotAvailableException; use OCP\User\Events\PostLoginEvent; use OCP\User\Events\UserFirstTimeLoggedInEvent; @@ -275,7 +278,7 @@ class Session implements IUserSession, Emitter { $currentUser = $this->getUser(); if ($currentUser === null) { - throw new \OC\User\NoUserException(); + throw new NoUserException(); } $this->session->set('oldUserId', $currentUser->getUID()); } @@ -319,7 +322,7 @@ class Session implements IUserSession, Emitter { if (!$user->isEnabled()) { // disabled users can not log in // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory - $message = \OCP\Util::getL10N('lib')->t('Account disabled'); + $message = Util::getL10N('lib')->t('Account disabled'); throw new DisabledUserException($message); } @@ -359,7 +362,7 @@ class Session implements IUserSession, Emitter { return true; } - $message = \OCP\Util::getL10N('lib')->t('Login canceled by app'); + $message = Util::getL10N('lib')->t('Login canceled by app'); throw new LoginException($message); } @@ -450,7 +453,7 @@ class Session implements IUserSession, Emitter { $this->logger->warning("Login failed: '" . $user . "' (Remote IP: '" . $remoteAddress . "')", ['app' => 'core']); $throttler->registerAttempt('login', $remoteAddress, ['user' => $user]); - $this->dispatcher->dispatchTyped(new OC\Authentication\Events\LoginFailed($user, $password)); + $this->dispatcher->dispatchTyped(new LoginFailed($user, $password)); if ($currentDelay === 0) { $throttler->sleepDelayOrThrowOnMax($remoteAddress, 'login'); @@ -487,7 +490,7 @@ class Session implements IUserSession, Emitter { $user = $users[0]; } // DI not possible due to cyclic dependencies :'-/ - return OC::$server->get(TwoFactorAuthManager::class)->isTwoFactorAuthenticated($user); + return Server::get(TwoFactorAuthManager::class)->isTwoFactorAuthenticated($user); } /** @@ -512,7 +515,7 @@ class Session implements IUserSession, Emitter { if ($refreshCsrfToken) { // TODO: mock/inject/use non-static // Refresh the token - \OC::$server->get(CsrfTokenManager::class)->refreshToken(); + Server::get(CsrfTokenManager::class)->refreshToken(); } if ($firstTimeLogin) { @@ -532,8 +535,8 @@ class Session implements IUserSession, Emitter { } // trigger any other initialization - \OC::$server->get(IEventDispatcher::class)->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser())); - \OC::$server->get(IEventDispatcher::class)->dispatchTyped(new UserFirstTimeLoggedInEvent($this->getUser())); + Server::get(IEventDispatcher::class)->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser())); + Server::get(IEventDispatcher::class)->dispatchTyped(new UserFirstTimeLoggedInEvent($this->getUser())); } } @@ -654,10 +657,10 @@ class Session implements IUserSession, Emitter { $sessionId = $this->session->getId(); $pwd = $this->getPassword($password); // Make sure the current sessionId has no leftover tokens - $this->atomic(function () use ($sessionId, $uid, $loginName, $pwd, $name, $remember) { + $this->atomic(function () use ($sessionId, $uid, $loginName, $pwd, $name, $remember): void { $this->tokenProvider->invalidateToken($sessionId); $this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember); - }, \OCP\Server::get(IDBConnection::class)); + }, Server::get(IDBConnection::class)); return true; } catch (SessionNotAvailableException $ex) { // This can happen with OCC, where a memory session is used @@ -977,7 +980,7 @@ class Session implements IUserSession, Emitter { * @param string $token */ public function setMagicInCookie($username, $token) { - $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https'; + $secureCookie = Server::get(IRequest::class)->getServerProtocol() === 'https'; $webRoot = \OC::$WEBROOT; if ($webRoot === '') { $webRoot = '/'; @@ -985,7 +988,7 @@ class Session implements IUserSession, Emitter { $domain = $this->config->getSystemValueString('cookie_domain'); $maxAge = $this->config->getSystemValueInt('remember_login_cookie_lifetime', 60 * 60 * 24 * 15); - \OC\Http\CookieHelper::setCookie( + CookieHelper::setCookie( 'nc_username', $username, $maxAge, @@ -993,9 +996,9 @@ class Session implements IUserSession, Emitter { $domain, $secureCookie, true, - \OC\Http\CookieHelper::SAMESITE_LAX + CookieHelper::SAMESITE_LAX ); - \OC\Http\CookieHelper::setCookie( + CookieHelper::setCookie( 'nc_token', $token, $maxAge, @@ -1003,10 +1006,10 @@ class Session implements IUserSession, Emitter { $domain, $secureCookie, true, - \OC\Http\CookieHelper::SAMESITE_LAX + CookieHelper::SAMESITE_LAX ); try { - \OC\Http\CookieHelper::setCookie( + CookieHelper::setCookie( 'nc_session_id', $this->session->getId(), $maxAge, @@ -1014,7 +1017,7 @@ class Session implements IUserSession, Emitter { $domain, $secureCookie, true, - \OC\Http\CookieHelper::SAMESITE_LAX + CookieHelper::SAMESITE_LAX ); } catch (SessionNotAvailableException $ex) { // ignore @@ -1026,7 +1029,7 @@ class Session implements IUserSession, Emitter { */ public function unsetMagicInCookie() { //TODO: DI for cookies and IRequest - $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https'; + $secureCookie = Server::get(IRequest::class)->getServerProtocol() === 'https'; $domain = $this->config->getSystemValueString('cookie_domain'); unset($_COOKIE['nc_username']); //TODO: DI diff --git a/lib/private/User/User.php b/lib/private/User/User.php index c5719daf67e..14ac2c48926 100644 --- a/lib/private/User/User.php +++ b/lib/private/User/User.php @@ -14,6 +14,7 @@ use OC\Hooks\Emitter; use OCP\Accounts\IAccountManager; use OCP\Comments\ICommentsManager; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Files\FileInfo; use OCP\Group\Events\BeforeUserRemovedEvent; use OCP\Group\Events\UserRemovedEvent; use OCP\IAvatarManager; @@ -25,6 +26,7 @@ use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserBackend; use OCP\Notification\IManager as INotificationManager; +use OCP\Server; use OCP\User\Backend\IGetHomeBackend; use OCP\User\Backend\IPasswordHashBackend; use OCP\User\Backend\IPropertyPermissionBackend; @@ -39,6 +41,7 @@ use OCP\User\Events\UserChangedEvent; use OCP\User\Events\UserDeletedEvent; use OCP\User\GetQuotaEvent; use OCP\UserInterface; +use OCP\Util; use Psr\Log\LoggerInterface; use function json_decode; @@ -59,9 +62,6 @@ class User implements IUser { /** @var bool|null */ private $enabled; - /** @var Emitter|Manager|null */ - private $emitter; - /** @var string */ private $home; @@ -71,17 +71,19 @@ class User implements IUser { /** @var IAvatarManager */ private $avatarManager; + /** + * @param Emitter|\OC\User\Manager|null $emitter + */ public function __construct( private string $uid, private ?UserInterface $backend, private IEventDispatcher $dispatcher, - $emitter = null, + private $emitter = null, ?IConfig $config = null, $urlGenerator = null, ) { - $this->emitter = $emitter; - $this->config = $config ?? \OCP\Server::get(IConfig::class); - $this->urlGenerator = $urlGenerator ?? \OCP\Server::get(IURLGenerator::class); + $this->config = $config ?? Server::get(IConfig::class); + $this->urlGenerator = $urlGenerator ?? Server::get(IURLGenerator::class); } /** @@ -197,7 +199,7 @@ class User implements IUser { private function ensureAccountManager() { if (!$this->accountManager instanceof IAccountManager) { - $this->accountManager = \OC::$server->get(IAccountManager::class); + $this->accountManager = Server::get(IAccountManager::class); } } @@ -257,7 +259,7 @@ class User implements IUser { */ public function delete() { if ($this->backend === null) { - \OCP\Server::get(LoggerInterface::class)->error('Cannot delete user: No backend set'); + Server::get(LoggerInterface::class)->error('Cannot delete user: No backend set'); return false; } @@ -282,7 +284,7 @@ class User implements IUser { } // We have to delete the user from all groups - $groupManager = \OCP\Server::get(IGroupManager::class); + $groupManager = Server::get(IGroupManager::class); foreach ($groupManager->getUserGroupIds($this) as $groupId) { $group = $groupManager->get($groupId); if ($group) { @@ -292,22 +294,22 @@ class User implements IUser { } } - $commentsManager = \OCP\Server::get(ICommentsManager::class); + $commentsManager = Server::get(ICommentsManager::class); $commentsManager->deleteReferencesOfActor('users', $this->uid); $commentsManager->deleteReadMarksFromUser($this); - $avatarManager = \OCP\Server::get(AvatarManager::class); + $avatarManager = Server::get(AvatarManager::class); $avatarManager->deleteUserAvatar($this->uid); - $notificationManager = \OCP\Server::get(INotificationManager::class); + $notificationManager = Server::get(INotificationManager::class); $notification = $notificationManager->createNotification(); $notification->setUser($this->uid); $notificationManager->markProcessed($notification); - $accountManager = \OCP\Server::get(AccountManager::class); + $accountManager = Server::get(AccountManager::class); $accountManager->deleteUser($this); - $database = \OCP\Server::get(IDBConnection::class); + $database = Server::get(IDBConnection::class); try { // We need to create a transaction to make sure we are in a defined state // because if all user values are removed also the flag is gone, but if an exception happens (e.g. database lost connection on the set operation) @@ -572,12 +574,12 @@ class User implements IUser { public function getQuotaBytes(): int|float { $quota = $this->getQuota(); if ($quota === 'none') { - return \OCP\Files\FileInfo::SPACE_UNLIMITED; + return FileInfo::SPACE_UNLIMITED; } - $bytes = \OCP\Util::computerFileSize($quota); + $bytes = Util::computerFileSize($quota); if ($bytes === false) { - return \OCP\Files\FileInfo::SPACE_UNKNOWN; + return FileInfo::SPACE_UNKNOWN; } return $bytes; } @@ -593,11 +595,11 @@ class User implements IUser { public function setQuota($quota) { $oldQuota = $this->config->getUserValue($this->uid, 'files', 'quota', ''); if ($quota !== 'none' && $quota !== 'default') { - $bytesQuota = \OCP\Util::computerFileSize($quota); + $bytesQuota = Util::computerFileSize($quota); if ($bytesQuota === false) { throw new InvalidArgumentException('Failed to set quota to invalid value ' . $quota); } - $quota = \OCP\Util::humanFileSize($bytesQuota); + $quota = Util::humanFileSize($bytesQuota); } if ($quota !== $oldQuota) { $this->config->setUserValue($this->uid, 'files', 'quota', $quota); @@ -637,7 +639,7 @@ class User implements IUser { public function getAvatarImage($size) { // delay the initialization if (is_null($this->avatarManager)) { - $this->avatarManager = \OC::$server->get(IAvatarManager::class); + $this->avatarManager = Server::get(IAvatarManager::class); } $avatar = $this->avatarManager->getAvatar($this->uid); diff --git a/lib/private/legacy/OC_App.php b/lib/private/legacy/OC_App.php index f18e6064bfa..2529c1dce5c 100644 --- a/lib/private/legacy/OC_App.php +++ b/lib/private/legacy/OC_App.php @@ -1,6 +1,7 @@ get(IAppManager::class)->isAppLoaded($app); + return Server::get(IAppManager::class)->isAppLoaded($app); } /** @@ -73,11 +86,11 @@ class OC_App { * @deprecated 29.0.0 use IAppManager::loadApps instead */ public static function loadApps(array $types = []): bool { - if (!\OC::$server->getSystemConfig()->getValue('installed', false)) { + if (!Server::get(SystemConfig::class)->getValue('installed', false)) { // This should be done before calling this method so that appmanager can be used return false; } - return \OC::$server->get(IAppManager::class)->loadApps($types); + return Server::get(IAppManager::class)->loadApps($types); } /** @@ -88,7 +101,7 @@ class OC_App { * @deprecated 27.0.0 use IAppManager::loadApp */ public static function loadApp(string $app): void { - \OC::$server->get(IAppManager::class)->loadApp($app); + Server::get(IAppManager::class)->loadApp($app); } /** @@ -106,7 +119,7 @@ class OC_App { self::$alreadyRegistered[$key] = true; // Register on PSR-4 composer autoloader - $appNamespace = \OC\AppFramework\App::buildAppNamespace($app); + $appNamespace = App::buildAppNamespace($app); \OC::$server->registerNamespace($app, $appNamespace); if (file_exists($path . '/composer/autoload.php')) { @@ -130,14 +143,14 @@ class OC_App { * @deprecated 27.0.0 use IAppManager::isType */ public static function isType(string $app, array $types): bool { - return \OC::$server->get(IAppManager::class)->isType($app, $types); + return Server::get(IAppManager::class)->isType($app, $types); } /** * read app types from info.xml and cache them in the database */ public static function setAppTypes(string $app) { - $appManager = \OC::$server->getAppManager(); + $appManager = Server::get(IAppManager::class); $appData = $appManager->getAppInfo($app); if (!is_array($appData)) { return; @@ -150,7 +163,7 @@ class OC_App { $appData['types'] = []; } - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); $config->setAppValue($app, 'types', $appTypes); if ($appManager->hasProtectedAppType($appData['types'])) { @@ -170,16 +183,16 @@ class OC_App { * @return list */ public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array { - if (!\OC::$server->getSystemConfig()->getValue('installed', false)) { + if (!Server::get(SystemConfig::class)->getValue('installed', false)) { return []; } // in incognito mode or when logged out, $user will be false, // which is also the case during an upgrade - $appManager = \OC::$server->getAppManager(); + $appManager = Server::get(IAppManager::class); if ($all) { $user = null; } else { - $user = \OC::$server->getUserSession()->getUser(); + $user = Server::get(IUserSession::class)->getUser(); } if (is_null($user)) { @@ -219,13 +232,13 @@ class OC_App { $installer->installApp($appId); - $appManager = \OC::$server->getAppManager(); + $appManager = Server::get(IAppManager::class); if ($groups !== []) { - $groupManager = \OC::$server->getGroupManager(); + $groupManager = Server::get(IGroupManager::class); $groupsList = []; foreach ($groups as $group) { $groupItem = $groupManager->get($group); - if ($groupItem instanceof \OCP\IGroup) { + if ($groupItem instanceof IGroup) { $groupsList[] = $groupManager->get($group); } } @@ -269,7 +282,7 @@ class OC_App { return ''; } - $request = \OC::$server->getRequest(); + $request = Server::get(IRequest::class); $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1); $topFolder = substr($script, 0, strpos($script, '/') ?: 0); if (empty($topFolder)) { @@ -277,7 +290,7 @@ class OC_App { $path_info = $request->getPathInfo(); } catch (Exception $e) { // Can happen from unit tests because the script name is `./vendor/bin/phpunit` or something a like then. - \OC::$server->get(LoggerInterface::class)->error('Failed to detect current app from script path', ['exception' => $e]); + Server::get(LoggerInterface::class)->error('Failed to detect current app from script path', ['exception' => $e]); return ''; } if ($path_info) { @@ -367,7 +380,7 @@ class OC_App { * @deprecated 32.0.0 Use \OCP\Support\Subscription\IRegistry::delegateGetSupportedApps instead */ public function getSupportedApps(): array { - $subscriptionRegistry = Server::get(\OCP\Support\Subscription\IRegistry::class); + $subscriptionRegistry = Server::get(IRegistry::class); $supportedApps = $subscriptionRegistry->delegateGetSupportedApps(); return $supportedApps; } @@ -378,14 +391,14 @@ class OC_App { * @return array */ public function listAllApps(): array { - $appManager = \OC::$server->getAppManager(); + $appManager = Server::get(IAppManager::class); $installedApps = $appManager->getAllAppsInAppsFolders(); //we don't want to show configuration for these $blacklist = $appManager->getAlwaysEnabledApps(); $appList = []; $langCode = \OC::$server->getL10N('core')->getLanguageCode(); - $urlGenerator = \OC::$server->getURLGenerator(); + $urlGenerator = Server::get(IURLGenerator::class); $supportedApps = $this->getSupportedApps(); foreach ($installedApps as $app) { @@ -401,7 +414,7 @@ class OC_App { continue; } - $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no'); + $enabled = Server::get(IConfig::class)->getAppValue($app, 'enabled', 'no'); $info['groups'] = null; if ($enabled === 'yes') { $active = true; @@ -470,7 +483,7 @@ class OC_App { * @deprecated 32.0.0 Use IAppManager::isUpgradeRequired instead */ public static function shouldUpgrade(string $app): bool { - return Server::get(\OCP\App\IAppManager::class)->isUpgradeRequired($app); + return Server::get(IAppManager::class)->isUpgradeRequired($app); } /** @@ -491,7 +504,7 @@ class OC_App { * @deprecated 32.0.0 Use IAppManager::isAppCompatible instead */ public static function isAppCompatible(string $ocVersion, array $appInfo, bool $ignoreMax = false): bool { - return Server::get(\OCP\App\IAppManager::class)->isAppCompatible($ocVersion, $appInfo, $ignoreMax); + return Server::get(IAppManager::class)->isAppCompatible($ocVersion, $appInfo, $ignoreMax); } /** @@ -509,8 +522,8 @@ class OC_App { */ public static function updateApp(string $appId): bool { try { - return Server::get(\OC\App\AppManager::class)->upgradeApp($appId); - } catch (\OCP\App\AppPathNotFoundException $e) { + return Server::get(AppManager::class)->upgradeApp($appId); + } catch (AppPathNotFoundException $e) { return false; } } @@ -518,7 +531,7 @@ class OC_App { /** * @param string $appId * @param string[] $steps - * @throws \OC\NeedsUpdateException + * @throws NeedsUpdateException */ public static function executeRepairSteps(string $appId, array $steps) { if (empty($steps)) { @@ -547,19 +560,19 @@ class OC_App { * @deprecated 32.0.0 Use the IJobList directly instead */ public static function setupBackgroundJobs(array $jobs) { - $queue = \OC::$server->getJobList(); + $queue = Server::get(IJobList::class); foreach ($jobs as $job) { $queue->add($job); } } /** - * @param \OCP\IConfig $config - * @param \OCP\IL10N $l + * @param IConfig $config + * @param IL10N $l * @param array $info * @throws \Exception */ - public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info, bool $ignoreMax) { + public static function checkAppDependencies(IConfig $config, IL10N $l, array $info, bool $ignoreMax) { $dependencyAnalyzer = Server::get(DependencyAnalyzer::class); $missing = $dependencyAnalyzer->analyze($info, $ignoreMax); if (!empty($missing)) { diff --git a/lib/private/legacy/OC_Defaults.php b/lib/private/legacy/OC_Defaults.php index 0d460ff966d..b62bb65ddab 100644 --- a/lib/private/legacy/OC_Defaults.php +++ b/lib/private/legacy/OC_Defaults.php @@ -5,10 +5,11 @@ * SPDX-FileCopyrightText: 2016 ownCloud, Inc. * SPDX-License-Identifier: AGPL-3.0-only */ - use OCP\IConfig; +use OCP\IURLGenerator; use OCP\Server; use OCP\ServerVersion; +use OCP\Util; class OC_Defaults { private $theme; @@ -312,11 +313,11 @@ class OC_Defaults { } if ($useSvg) { - $logo = \OC::$server->getURLGenerator()->imagePath('core', 'logo/logo.svg'); + $logo = Server::get(IURLGenerator::class)->imagePath('core', 'logo/logo.svg'); } else { - $logo = \OC::$server->getURLGenerator()->imagePath('core', 'logo/logo.png'); + $logo = Server::get(IURLGenerator::class)->imagePath('core', 'logo/logo.png'); } - return $logo . '?v=' . hash('sha1', implode('.', \OCP\Util::getVersion())); + return $logo . '?v=' . hash('sha1', implode('.', Util::getVersion())); } public function getTextColorPrimary() { diff --git a/lib/private/legacy/OC_Helper.php b/lib/private/legacy/OC_Helper.php index 65f4300f850..3dc7470811d 100644 --- a/lib/private/legacy/OC_Helper.php +++ b/lib/private/legacy/OC_Helper.php @@ -8,10 +8,19 @@ use bantu\IniGetWrapper\IniGetWrapper; use OC\Files\FilenameValidator; use OC\Files\Filesystem; +use OC\Files\Storage\Home; +use OC\Files\Storage\Wrapper\Quota; +use OC\SystemConfig; +use OCA\Files_Sharing\External\Storage; +use OCP\Files\FileInfo; use OCP\Files\Mount\IMountPoint; +use OCP\Files\NotFoundException; use OCP\IBinaryFinder; use OCP\ICacheFactory; +use OCP\IConfig; use OCP\IUser; +use OCP\IUserManager; +use OCP\IUserSession; use OCP\Server; use OCP\Util; use Psr\Log\LoggerInterface; @@ -58,7 +67,7 @@ class OC_Helper { } } } else { - $validator = \OCP\Server::get(FilenameValidator::class); + $validator = Server::get(FilenameValidator::class); if (!$validator->isForbidden($src)) { copy($src, $dest); } @@ -86,7 +95,7 @@ class OC_Helper { // Default check will be done with $path directories : $dirs = explode(PATH_SEPARATOR, (string)$path); // WARNING : We have to check if open_basedir is enabled : - $obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir'); + $obd = Server::get(IniGetWrapper::class)->getString('open_basedir'); if ($obd != 'none') { $obd_values = explode(PATH_SEPARATOR, $obd); if (count($obd_values) > 0 && $obd_values[0]) { @@ -130,12 +139,12 @@ class OC_Helper { * already ! * * @param string $path - * @param \OCP\Files\FileInfo $rootInfo (optional) + * @param FileInfo $rootInfo (optional) * @param bool $includeMountPoints whether to include mount points in the size calculation * @param bool $useCache whether to use the cached quota values * @psalm-suppress LessSpecificReturnStatement Legacy code outputs weird types - manually validated that they are correct * @return StorageInfo - * @throws \OCP\Files\NotFoundException + * @throws NotFoundException */ public static function getStorageInfo($path, $rootInfo = null, $includeMountPoints = true, $useCache = true) { if (!self::$cacheFactory) { @@ -145,12 +154,12 @@ class OC_Helper { // return storage info without adding mount points if (self::$quotaIncludeExternalStorage === null) { - self::$quotaIncludeExternalStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false); + self::$quotaIncludeExternalStorage = Server::get(SystemConfig::class)->getValue('quota_include_external_storage', false); } $view = Filesystem::getView(); if (!$view) { - throw new \OCP\Files\NotFoundException(); + throw new NotFoundException(); } $fullPath = Filesystem::normalizePath($view->getAbsolutePath($path)); @@ -163,17 +172,17 @@ class OC_Helper { } if (!$rootInfo) { - $rootInfo = \OC\Files\Filesystem::getFileInfo($path, self::$quotaIncludeExternalStorage ? 'ext' : false); + $rootInfo = Filesystem::getFileInfo($path, self::$quotaIncludeExternalStorage ? 'ext' : false); } - if (!$rootInfo instanceof \OCP\Files\FileInfo) { - throw new \OCP\Files\NotFoundException('The root directory of the user\'s files is missing'); + if (!$rootInfo instanceof FileInfo) { + throw new NotFoundException('The root directory of the user\'s files is missing'); } $used = $rootInfo->getSize($includeMountPoints); if ($used < 0) { $used = 0.0; } /** @var int|float $quota */ - $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED; + $quota = FileInfo::SPACE_UNLIMITED; $mount = $rootInfo->getMountPoint(); $storage = $mount->getStorage(); $sourceStorage = $storage; @@ -184,13 +193,13 @@ class OC_Helper { if ($storage->instanceOfStorage('\OC\Files\Storage\Home') || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage') ) { - /** @var \OC\Files\Storage\Home $storage */ + /** @var Home $storage */ $user = $storage->getUser(); } else { - $user = \OC::$server->getUserSession()->getUser(); + $user = Server::get(IUserSession::class)->getUser(); } - $quota = $user?->getQuotaBytes() ?? \OCP\Files\FileInfo::SPACE_UNKNOWN; - if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) { + $quota = $user?->getQuotaBytes() ?? FileInfo::SPACE_UNKNOWN; + if ($quota !== FileInfo::SPACE_UNLIMITED) { // always get free space / total space from root + mount points return self::getGlobalStorageInfo($quota, $user, $mount); } @@ -198,7 +207,7 @@ class OC_Helper { // TODO: need a better way to get total space from storage if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) { - /** @var \OC\Files\Storage\Wrapper\Quota $storage */ + /** @var Quota $storage */ $quota = $sourceStorage->getQuota(); } try { @@ -211,7 +220,7 @@ class OC_Helper { throw $e; } /** @var LoggerInterface $logger */ - $logger = \OC::$server->get(LoggerInterface::class); + $logger = Server::get(LoggerInterface::class); $logger->warning('Error while getting quota info, using root quota', ['exception' => $e]); $rootInfo = self::getStorageInfo(''); $memcache->set($cacheKey, $rootInfo, 5 * 60); @@ -236,13 +245,13 @@ class OC_Helper { * \OCA\Files_Sharing\External\Storage returns the cloud ID as the owner for the storage. * It is unnecessary to query the user manager for the display name, as it won't have this information. */ - $isRemoteShare = $storage->instanceOfStorage(\OCA\Files_Sharing\External\Storage::class); + $isRemoteShare = $storage->instanceOfStorage(Storage::class); $ownerId = $storage->getOwner($path); $ownerDisplayName = ''; if ($isRemoteShare === false && $ownerId !== false) { - $ownerDisplayName = \OC::$server->getUserManager()->getDisplayName($ownerId) ?? ''; + $ownerDisplayName = Server::get(IUserManager::class)->getDisplayName($ownerId) ?? ''; } if (substr_count($mount->getMountPoint(), '/') < 3) { @@ -265,7 +274,7 @@ class OC_Helper { if ($isRemoteShare === false && $ownerId !== false && $path === '/') { // If path is root, store this as last known quota usage for this user - \OCP\Server::get(\OCP\IConfig::class)->setUserValue($ownerId, 'files', 'lastSeenQuotaUsage', (string)$relative); + Server::get(IConfig::class)->setUserValue($ownerId, 'files', 'lastSeenQuotaUsage', (string)$relative); } $memcache->set($cacheKey, $info, 5 * 60); @@ -280,7 +289,7 @@ class OC_Helper { * @return StorageInfo */ private static function getGlobalStorageInfo(int|float $quota, IUser $user, IMountPoint $mount): array { - $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext'); + $rootInfo = Filesystem::getFileInfo('', 'ext'); /** @var int|float $used */ $used = $rootInfo['size']; if ($used < 0) { @@ -322,7 +331,7 @@ class OC_Helper { public static function clearStorageInfo(string $absolutePath): void { /** @var ICacheFactory $cacheFactory */ - $cacheFactory = \OC::$server->get(ICacheFactory::class); + $cacheFactory = Server::get(ICacheFactory::class); $memcache = $cacheFactory->createLocal('storage_info'); $cacheKeyPrefix = Filesystem::normalizePath($absolutePath) . '::'; $memcache->remove($cacheKeyPrefix . 'include'); @@ -335,6 +344,6 @@ class OC_Helper { * @deprecated 32.0.0 use the `config_is_read_only` system config directly */ public static function isReadOnlyConfigEnabled() { - return \OC::$server->getConfig()->getSystemValueBool('config_is_read_only', false); + return Server::get(IConfig::class)->getSystemValueBool('config_is_read_only', false); } } diff --git a/lib/private/legacy/OC_Hook.php b/lib/private/legacy/OC_Hook.php index d14c34899a9..888057a7aca 100644 --- a/lib/private/legacy/OC_Hook.php +++ b/lib/private/legacy/OC_Hook.php @@ -5,7 +5,9 @@ * SPDX-FileCopyrightText: 2016 ownCloud, Inc. * SPDX-License-Identifier: AGPL-3.0-only */ - +use OC\ServerNotAvailableException; +use OCP\HintException; +use OCP\Server; use Psr\Log\LoggerInterface; class OC_Hook { @@ -61,8 +63,8 @@ class OC_Hook { * @param string $signalName name of signal * @param mixed $params default: array() array with additional data * @return bool true if slots exists or false if not - * @throws \OCP\HintException - * @throws \OC\ServerNotAvailableException Emits a signal. To get data from the slot use references! + * @throws HintException + * @throws ServerNotAvailableException Emits a signal. To get data from the slot use references! * * TODO: write example */ @@ -85,11 +87,11 @@ class OC_Hook { call_user_func([ $i['class'], $i['name'] ], $params); } catch (Exception $e) { self::$thrownExceptions[] = $e; - \OCP\Server::get(LoggerInterface::class)->error($e->getMessage(), ['exception' => $e]); - if ($e instanceof \OCP\HintException) { + Server::get(LoggerInterface::class)->error($e->getMessage(), ['exception' => $e]); + if ($e instanceof HintException) { throw $e; } - if ($e instanceof \OC\ServerNotAvailableException) { + if ($e instanceof ServerNotAvailableException) { throw $e; } } diff --git a/lib/private/legacy/OC_JSON.php b/lib/private/legacy/OC_JSON.php index 6daef18dd61..03ac83a0581 100644 --- a/lib/private/legacy/OC_JSON.php +++ b/lib/private/legacy/OC_JSON.php @@ -5,8 +5,12 @@ * SPDX-FileCopyrightText: 2016 ownCloud, Inc. * SPDX-License-Identifier: AGPL-3.0-only */ - use OC\Authentication\TwoFactorAuth\Manager as TwoFactorAuthManager; +use OCP\App\IAppManager; +use OCP\AppFramework\Http; +use OCP\IRequest; +use OCP\IUserSession; +use OCP\Server; class OC_JSON { /** @@ -16,7 +20,7 @@ class OC_JSON { * @suppress PhanDeprecatedFunction */ public static function checkAppEnabled($app) { - if (!\OC::$server->getAppManager()->isEnabledForUser($app)) { + if (!Server::get(IAppManager::class)->isEnabledForUser($app)) { $l = \OC::$server->getL10N('lib'); self::error([ 'data' => [ 'message' => $l->t('Application is not enabled'), 'error' => 'application_not_enabled' ]]); exit(); @@ -29,11 +33,11 @@ class OC_JSON { * @suppress PhanDeprecatedFunction */ public static function checkLoggedIn() { - $twoFactorAuthManger = \OC::$server->get(TwoFactorAuthManager::class); - if (!\OC::$server->getUserSession()->isLoggedIn() - || $twoFactorAuthManger->needsSecondFactor(\OC::$server->getUserSession()->getUser())) { + $twoFactorAuthManger = Server::get(TwoFactorAuthManager::class); + if (!Server::get(IUserSession::class)->isLoggedIn() + || $twoFactorAuthManger->needsSecondFactor(Server::get(IUserSession::class)->getUser())) { $l = \OC::$server->getL10N('lib'); - http_response_code(\OCP\AppFramework\Http::STATUS_UNAUTHORIZED); + http_response_code(Http::STATUS_UNAUTHORIZED); self::error([ 'data' => [ 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' ]]); exit(); } @@ -45,12 +49,12 @@ class OC_JSON { * @suppress PhanDeprecatedFunction */ public static function callCheck() { - if (!\OC::$server->getRequest()->passesStrictCookieCheck()) { + if (!Server::get(IRequest::class)->passesStrictCookieCheck()) { header('Location: ' . \OC::$WEBROOT); exit(); } - if (!\OC::$server->getRequest()->passesCSRFCheck()) { + if (!Server::get(IRequest::class)->passesCSRFCheck()) { $l = \OC::$server->getL10N('lib'); self::error([ 'data' => [ 'message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired' ]]); exit(); diff --git a/lib/private/legacy/OC_Template.php b/lib/private/legacy/OC_Template.php index bccf99af65e..5ddcce2db06 100644 --- a/lib/private/legacy/OC_Template.php +++ b/lib/private/legacy/OC_Template.php @@ -5,6 +5,7 @@ * SPDX-FileCopyrightText: 2016 ownCloud, Inc. * SPDX-License-Identifier: AGPL-3.0-only */ +use OC\Template\Template; use OCP\Server; use OCP\Template\ITemplateManager; @@ -12,7 +13,7 @@ use OCP\Template\ITemplateManager; * This class provides the templates for ownCloud. * @deprecated 32.0.0 Use \OCP\Template\ITemplateManager instead */ -class OC_Template extends \OC\Template\Template { +class OC_Template extends Template { /** * Shortcut to print a simple page for guests * @param string $application The application we render the template for diff --git a/lib/private/legacy/OC_User.php b/lib/private/legacy/OC_User.php index 7d56b94704a..8d0f7033208 100644 --- a/lib/private/legacy/OC_User.php +++ b/lib/private/legacy/OC_User.php @@ -6,19 +6,29 @@ * SPDX-License-Identifier: AGPL-3.0-only */ use OC\Authentication\Token\IProvider; +use OC\SystemConfig; +use OC\User\Database; use OC\User\DisabledUserException; use OCP\Authentication\Exceptions\InvalidTokenException; use OCP\Authentication\Exceptions\WipeTokenException; +use OCP\Authentication\IApacheBackend; +use OCP\Authentication\IProvideUserSecretBackend; use OCP\Authentication\Token\IToken; use OCP\EventDispatcher\IEventDispatcher; use OCP\IGroupManager; +use OCP\IRequest; use OCP\ISession; +use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserManager; +use OCP\IUserSession; use OCP\Server; use OCP\Session\Exceptions\SessionNotAvailableException; +use OCP\User\Backend\ICustomLogout; use OCP\User\Events\BeforeUserLoggedInEvent; use OCP\User\Events\UserLoggedInEvent; +use OCP\UserInterface; +use OCP\Util; use Psr\Log\LoggerInterface; /** @@ -48,14 +58,14 @@ class OC_User { /** * Adds the backend to the list of used backends * - * @param string|\OCP\UserInterface $backend default: database The backend to use for user management + * @param string|UserInterface $backend default: database The backend to use for user management * @return bool * @deprecated 32.0.0 Use IUserManager::registerBackend instead * * Set the User Authentication Module */ public static function useBackend($backend = 'database') { - if ($backend instanceof \OCP\UserInterface) { + if ($backend instanceof UserInterface) { Server::get(IUserManager::class)->registerBackend($backend); } else { // You'll never know what happens @@ -69,7 +79,7 @@ class OC_User { case 'mysql': case 'sqlite': Server::get(LoggerInterface::class)->debug('Adding user backend ' . $backend . '.', ['app' => 'core']); - Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); + Server::get(IUserManager::class)->registerBackend(new Database()); break; case 'dummy': Server::get(IUserManager::class)->registerBackend(new \Test\Util\User\Dummy()); @@ -98,7 +108,7 @@ class OC_User { */ public static function setupBackends() { OC_App::loadApps(['prelogin']); - $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []); + $backends = Server::get(SystemConfig::class)->getValue('user_backends', []); if (isset($backends['default']) && !$backends['default']) { // clear default backends self::clearBackends(); @@ -133,10 +143,10 @@ class OC_User { * * Log in a user and regenerate a new session. * - * @param \OCP\Authentication\IApacheBackend $backend + * @param IApacheBackend $backend * @return bool */ - public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) { + public static function loginWithApache(IApacheBackend $backend) { $uid = $backend->getCurrentUserId(); $run = true; OC_Hook::emit('OC_User', 'pre_login', ['run' => &$run, 'uid' => $uid, 'backend' => $backend]); @@ -144,19 +154,20 @@ class OC_User { if ($uid) { if (self::getUser() !== $uid) { self::setUserId($uid); - $userSession = \OC::$server->getUserSession(); + /** @var \OC\User\Session $userSession */ + $userSession = Server::get(IUserSession::class); /** @var IEventDispatcher $dispatcher */ - $dispatcher = \OC::$server->get(IEventDispatcher::class); + $dispatcher = Server::get(IEventDispatcher::class); if ($userSession->getUser() && !$userSession->getUser()->isEnabled()) { $message = \OC::$server->getL10N('lib')->t('Account disabled'); throw new DisabledUserException($message); } $userSession->setLoginName($uid); - $request = OC::$server->getRequest(); + $request = Server::get(IRequest::class); $password = null; - if ($backend instanceof \OCP\Authentication\IProvideUserSecretBackend) { + if ($backend instanceof IProvideUserSecretBackend) { $password = $backend->getCurrentUserSecret(); } @@ -167,7 +178,7 @@ class OC_User { $userSession->createRememberMeToken($userSession->getUser()); if (empty($password)) { - $tokenProvider = \OC::$server->get(IProvider::class); + $tokenProvider = Server::get(IProvider::class); try { $token = $tokenProvider->getToken($userSession->getSession()->getId()); $token->setScope([ @@ -197,7 +208,7 @@ class OC_User { ] ); $dispatcher->dispatchTyped(new UserLoggedInEvent( - \OC::$server->get(IUserManager::class)->get($uid), + Server::get(IUserManager::class)->get($uid), $uid, null, false) @@ -226,7 +237,9 @@ class OC_User { //setup extra user backends self::setupBackends(); - \OC::$server->getUserSession()->unsetMagicInCookie(); + /** @var \OC\User\Session $session */ + $session = Server::get(IUserSession::class); + $session->unsetMagicInCookie(); return self::loginWithApache($backend); } @@ -241,12 +254,12 @@ class OC_User { * @param string $uid */ public static function setUserId($uid) { - $userSession = \OC::$server->getUserSession(); + $userSession = Server::get(IUserSession::class); $userManager = Server::get(IUserManager::class); if ($user = $userManager->get($uid)) { $userSession->setUser($user); } else { - \OC::$server->getSession()->set('user_id', $uid); + Server::get(ISession::class)->set('user_id', $uid); } } @@ -271,25 +284,25 @@ class OC_User { /** * Returns the current logout URL valid for the currently logged-in user * - * @param \OCP\IURLGenerator $urlGenerator + * @param IURLGenerator $urlGenerator * @return string */ - public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) { + public static function getLogoutUrl(IURLGenerator $urlGenerator) { $backend = self::findFirstActiveUsedBackend(); if ($backend) { return $backend->getLogoutUrl(); } - $user = \OC::$server->getUserSession()->getUser(); + $user = Server::get(IUserSession::class)->getUser(); if ($user instanceof IUser) { $backend = $user->getBackend(); - if ($backend instanceof \OCP\User\Backend\ICustomLogout) { + if ($backend instanceof ICustomLogout) { return $backend->getLogoutUrl(); } } $logoutUrl = $urlGenerator->linkToRoute('core.login.logout'); - $logoutUrl .= '?requesttoken=' . urlencode(\OCP\Util::callRegister()); + $logoutUrl .= '?requesttoken=' . urlencode(Util::callRegister()); return $logoutUrl; } @@ -343,11 +356,11 @@ class OC_User { /** * Returns the first active backend from self::$_usedBackends. * - * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend + * @return IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend */ private static function findFirstActiveUsedBackend() { foreach (Server::get(IUserManager::class)->getBackends() as $backend) { - if ($backend instanceof OCP\Authentication\IApacheBackend) { + if ($backend instanceof IApacheBackend) { if ($backend->isSessionActive()) { return $backend; } diff --git a/lib/private/legacy/OC_Util.php b/lib/private/legacy/OC_Util.php index 155e9037524..0a38062e553 100644 --- a/lib/private/legacy/OC_Util.php +++ b/lib/private/legacy/OC_Util.php @@ -7,15 +7,30 @@ */ use bantu\IniGetWrapper\IniGetWrapper; use OC\Authentication\TwoFactorAuth\Manager as TwoFactorAuthManager; +use OC\Files\Cache\Scanner; +use OC\Files\Filesystem; use OC\Files\SetupManager; +use OC\Setup; +use OC\SystemConfig; +use OCP\Files\FileInfo; +use OCP\Files\Folder; +use OCP\Files\NotFoundException; +use OCP\Files\NotPermittedException; use OCP\Files\Template\ITemplateManager; +use OCP\HintException; use OCP\IConfig; use OCP\IGroupManager; +use OCP\IRequest; +use OCP\ISession; use OCP\IURLGenerator; use OCP\IUser; +use OCP\IUserManager; +use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Security\ISecureRandom; +use OCP\Server; use OCP\Share\IManager; +use OCP\Util; use Psr\Log\LoggerInterface; /** @@ -37,13 +52,13 @@ class OC_Util { public static function setupFS(?string $user = '') { // If we are not forced to load a specific user we load the one that is logged in if ($user === '') { - $userObject = \OC::$server->get(\OCP\IUserSession::class)->getUser(); + $userObject = Server::get(IUserSession::class)->getUser(); } else { - $userObject = \OC::$server->get(\OCP\IUserManager::class)->get($user); + $userObject = Server::get(IUserManager::class)->get($user); } /** @var SetupManager $setupManager */ - $setupManager = \OC::$server->get(SetupManager::class); + $setupManager = Server::get(SetupManager::class); if ($userObject) { $setupManager->setupForUser($userObject); @@ -62,7 +77,7 @@ class OC_Util { */ public static function isPublicLinkPasswordRequired(bool $checkGroupMembership = true) { /** @var IManager $shareManager */ - $shareManager = \OC::$server->get(IManager::class); + $shareManager = Server::get(IManager::class); return $shareManager->shareApiLinkEnforcePassword($checkGroupMembership); } @@ -76,7 +91,7 @@ class OC_Util { */ public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) { /** @var IManager $shareManager */ - $shareManager = \OC::$server->get(IManager::class); + $shareManager = Server::get(IManager::class); $userId = $user ? $user->getUID() : null; return $shareManager->sharingDisabledForUser($userId); } @@ -89,7 +104,7 @@ class OC_Util { */ public static function isDefaultExpireDateEnforced() { /** @var IManager $shareManager */ - $shareManager = \OC::$server->get(IManager::class); + $shareManager = Server::get(IManager::class); return $shareManager->shareApiLinkDefaultExpireDateEnforced(); } @@ -97,17 +112,17 @@ class OC_Util { * copies the skeleton to the users /files * * @param string $userId - * @param \OCP\Files\Folder $userDirectory - * @throws \OCP\Files\NotFoundException - * @throws \OCP\Files\NotPermittedException + * @param Folder $userDirectory + * @throws NotFoundException + * @throws NotPermittedException * @suppress PhanDeprecatedFunction */ - public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) { + public static function copySkeleton($userId, Folder $userDirectory) { /** @var LoggerInterface $logger */ - $logger = \OC::$server->get(LoggerInterface::class); + $logger = Server::get(LoggerInterface::class); - $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValueString('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton'); - $userLang = \OC::$server->get(IFactory::class)->findLanguage(); + $plainSkeletonDirectory = Server::get(IConfig::class)->getSystemValueString('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton'); + $userLang = Server::get(IFactory::class)->findLanguage(); $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory); if (!file_exists($skeletonDirectory)) { @@ -123,7 +138,7 @@ class OC_Util { } } - $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', ''); + $instanceId = Server::get(IConfig::class)->getSystemValue('instanceid', ''); if ($instanceId === null) { throw new \RuntimeException('no instance id!'); @@ -137,10 +152,10 @@ class OC_Util { $logger->debug('copying skeleton for ' . $userId . ' from ' . $skeletonDirectory . ' to ' . $userDirectory->getFullPath('/'), ['app' => 'files_skeleton']); self::copyr($skeletonDirectory, $userDirectory); // update the file cache - $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE); + $userDirectory->getStorage()->getScanner()->scan('', Scanner::SCAN_RECURSIVE); /** @var ITemplateManager $templateManager */ - $templateManager = \OC::$server->get(ITemplateManager::class); + $templateManager = Server::get(ITemplateManager::class); $templateManager->initializeTemplateDirectory(null, $userId); } } @@ -149,11 +164,11 @@ class OC_Util { * copies a directory recursively by using streams * * @param string $source - * @param \OCP\Files\Folder $target + * @param Folder $target * @return void */ - public static function copyr($source, \OCP\Files\Folder $target) { - $logger = \OCP\Server::get(LoggerInterface::class); + public static function copyr($source, Folder $target) { + $logger = Server::get(LoggerInterface::class); // Verify if folder exists $dir = opendir($source); @@ -164,7 +179,7 @@ class OC_Util { // Copy the files while (false !== ($file = readdir($dir))) { - if (!\OC\Files\Filesystem::isIgnoredDir($file)) { + if (!Filesystem::isIgnoredDir($file)) { if (is_dir($source . '/' . $file)) { $child = $target->newFolder($file); self::copyr($source . '/' . $file, $child); @@ -186,7 +201,7 @@ class OC_Util { * @deprecated 32.0.0 Call tearDown directly on SetupManager */ public static function tearDownFS(): void { - $setupManager = \OCP\Server::get(SetupManager::class); + $setupManager = Server::get(SetupManager::class); $setupManager->tearDown(); } @@ -283,7 +298,7 @@ class OC_Util { * * @return array arrays with error messages and hints */ - public static function checkServer(\OC\SystemConfig $config) { + public static function checkServer(SystemConfig $config) { $l = \OC::$server->getL10N('lib'); $errors = []; $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data'); @@ -294,14 +309,14 @@ class OC_Util { } // Assume that if checkServer() succeeded before in this session, then all is fine. - if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) { + if (Server::get(ISession::class)->exists('checkServer_succeeded') && Server::get(ISession::class)->get('checkServer_succeeded')) { return $errors; } $webServerRestart = false; - $setup = \OCP\Server::get(\OC\Setup::class); + $setup = Server::get(Setup::class); - $urlGenerator = \OC::$server->getURLGenerator(); + $urlGenerator = Server::get(IURLGenerator::class); $availableDatabases = $setup->getSupportedDatabases(); if (empty($availableDatabases)) { @@ -403,7 +418,7 @@ class OC_Util { $missingDependencies = []; $invalidIniSettings = []; - $iniWrapper = \OC::$server->get(IniGetWrapper::class); + $iniWrapper = Server::get(IniGetWrapper::class); foreach ($dependencies['classes'] as $class => $module) { if (!class_exists($class)) { $missingDependencies[] = $module; @@ -464,7 +479,7 @@ class OC_Util { } // Cache the result of this function - \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0); + Server::get(ISession::class)->set('checkServer_succeeded', count($errors) == 0); return $errors; } @@ -477,7 +492,7 @@ class OC_Util { * @internal */ public static function checkDataDirectoryPermissions($dataDirectory) { - if (!\OC::$server->getConfig()->getSystemValueBool('check_data_directory_permissions', true)) { + if (!Server::get(IConfig::class)->getSystemValueBool('check_data_directory_permissions', true)) { return []; } @@ -532,19 +547,19 @@ class OC_Util { */ public static function checkLoggedIn(): void { // Check if we are a user - if (!\OC::$server->getUserSession()->isLoggedIn()) { - header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute( + if (!Server::get(IUserSession::class)->isLoggedIn()) { + header('Location: ' . Server::get(IURLGenerator::class)->linkToRoute( 'core.login.showLoginForm', [ - 'redirect_url' => \OC::$server->getRequest()->getRequestUri(), + 'redirect_url' => Server::get(IRequest::class)->getRequestUri(), ] ) ); exit(); } // Redirect to 2FA challenge selection if 2FA challenge was not solved yet - if (\OC::$server->get(TwoFactorAuthManager::class)->needsSecondFactor(\OC::$server->getUserSession()->getUser())) { - header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge')); + if (Server::get(TwoFactorAuthManager::class)->needsSecondFactor(Server::get(IUserSession::class)->getUser())) { + header('Location: ' . Server::get(IURLGenerator::class)->linkToRoute('core.TwoFactorChallenge.selectChallenge')); exit(); } } @@ -557,7 +572,7 @@ class OC_Util { public static function checkAdminUser(): void { self::checkLoggedIn(); if (!OC_User::isAdminUser(OC_User::getUser())) { - header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php')); + header('Location: ' . Util::linkToAbsolute('', 'index.php')); exit(); } } @@ -572,7 +587,7 @@ class OC_Util { */ public static function getDefaultPageUrl() { /** @var IURLGenerator $urlGenerator */ - $urlGenerator = \OC::$server->get(IURLGenerator::class); + $urlGenerator = Server::get(IURLGenerator::class); return $urlGenerator->linkToDefaultPageUrl(); } @@ -593,11 +608,11 @@ class OC_Util { * @return string */ public static function getInstanceId(): string { - $id = \OC::$server->getSystemConfig()->getValue('instanceid', null); + $id = Server::get(SystemConfig::class)->getValue('instanceid', null); if (is_null($id)) { // We need to guarantee at least one letter in instanceid so it can be used as the session_name - $id = 'oc' . \OC::$server->get(ISecureRandom::class)->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_DIGITS); - \OC::$server->getSystemConfig()->setValue('instanceid', $id); + $id = 'oc' . Server::get(ISecureRandom::class)->generate(10, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS); + Server::get(SystemConfig::class)->setValue('instanceid', $id); } return $id; } @@ -721,7 +736,7 @@ class OC_Util { * @return string the theme */ public static function getTheme() { - $theme = \OC::$server->getSystemConfig()->getValue('theme', ''); + $theme = Server::get(SystemConfig::class)->getValue('theme', ''); if ($theme === '') { if (is_dir(OC::$SERVERROOT . '/themes/default')) { @@ -745,7 +760,7 @@ class OC_Util { $normalizedValue = Normalizer::normalize($value); if ($normalizedValue === false) { - \OCP\Server::get(LoggerInterface::class)->warning('normalizing failed for "' . $value . '"', ['app' => 'core']); + Server::get(LoggerInterface::class)->warning('normalizing failed for "' . $value . '"', ['app' => 'core']); return $value; } @@ -766,9 +781,9 @@ class OC_Util { * whether an upgrade path is supported (e.g., skipping major versions like 28->30). * Callers are expected to check that on their own. * - * @param \OC\SystemConfig $config System configuration (reads 'installed', 'version', 'debug'). + * @param SystemConfig $config System configuration (reads 'installed', 'version', 'debug'). * @return bool True if a core or app upgrade is required, false otherwise. - * @throws \OCP\HintException If a downgrade is detected and not allowed. + * @throws HintException If a downgrade is detected and not allowed. * @deprecated 32.0.0 Use \OCP\Util::needUpgrade() instead. * @see \OCP\Util::needUpgrade */ diff --git a/lib/public/AppFramework/IAppContainer.php b/lib/public/AppFramework/IAppContainer.php index c20b252b0ce..9d656c6faa4 100644 --- a/lib/public/AppFramework/IAppContainer.php +++ b/lib/public/AppFramework/IAppContainer.php @@ -31,7 +31,7 @@ interface IAppContainer extends ContainerInterface, IContainer { public function getAppName(); /** - * @return \OCP\IServerContainer + * @return \OC\ServerContainer * @since 6.0.0 * @deprecated 20.0.0 */ diff --git a/lib/public/IServerContainer.php b/lib/public/IServerContainer.php index 6d5095c92da..1d314f72dc8 100644 --- a/lib/public/IServerContainer.php +++ b/lib/public/IServerContainer.php @@ -57,7 +57,7 @@ interface IServerContainer extends ContainerInterface, IContainer { * Returns a view to ownCloud's files folder * * @param string $userId user ID - * @return \OCP\Files\Folder + * @return \OCP\Files\Folder|null * @since 6.0.0 - parameter $userId was added in 8.0.0 * @see getUserFolder in \OCP\Files\IRootFolder * @deprecated 20.0.0 have it injected or fetch it through \Psr\Container\ContainerInterface::get @@ -145,14 +145,14 @@ interface IServerContainer extends ContainerInterface, IContainer { public function getL10N($app, $lang = null); /** - * @return \OC\Encryption\Manager + * @return \OCP\Encryption\IManager * @since 8.1.0 * @deprecated 20.0.0 have it injected or fetch it through \Psr\Container\ContainerInterface::get */ public function getEncryptionManager(); /** - * @return \OC\Encryption\File + * @return \OCP\Encryption\IFile * @since 8.1.0 * @deprecated 20.0.0 have it injected or fetch it through \Psr\Container\ContainerInterface::get */ diff --git a/lib/public/ITagManager.php b/lib/public/ITagManager.php index 8c37104828f..04e13403f27 100644 --- a/lib/public/ITagManager.php +++ b/lib/public/ITagManager.php @@ -31,7 +31,7 @@ interface ITagManager { * @param boolean $includeShared Whether to include tags for items shared with this user by others. - always false since 20.0.0 * @param string $userId user for which to retrieve the tags, defaults to the currently * logged in user - * @return \OCP\ITags + * @return \OCP\ITags|null * @since 6.0.0 - parameter $includeShared and $userId were added in 8.0.0 - $includeShared is always false since 20.0.0 */ public function load($type, $defaultTags = [], $includeShared = false, $userId = null); diff --git a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php index 9c4379e6f28..0e8f279c9dd 100644 --- a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php +++ b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php @@ -12,6 +12,7 @@ namespace Test\DB\QueryBuilder; use Doctrine\DBAL\Query\Expression\CompositeExpression; use Doctrine\DBAL\Query\QueryException; +use OC\DB\ConnectionAdapter; use OC\DB\QueryBuilder\Literal; use OC\DB\QueryBuilder\Parameter; use OC\DB\QueryBuilder\QueryBuilder; @@ -1221,21 +1222,16 @@ class QueryBuilderTest extends \Test\TestCase { ]; } - /** - * @param string $column - * @param string $prefix - * @param string $expected - */ #[DataProvider('dataGetColumnName')] - public function testGetColumnName($column, $prefix, $expected): void { + public function testGetColumnName(string $column, string $prefix, string $expected): void { $this->assertSame( $expected, $this->queryBuilder->getColumnName($column, $prefix) ); } - private function getConnection(): IDBConnection { - $connection = $this->createMock(IDBConnection::class); + private function getConnection(): MockObject&ConnectionAdapter { + $connection = $this->createMock(ConnectionAdapter::class); $connection->method('executeStatement') ->willReturn(3); $connection->method('executeQuery')