diff --git a/apps/dav/lib/CalDAV/Security/RateLimitingPlugin.php b/apps/dav/lib/CalDAV/Security/RateLimitingPlugin.php index 311157994e25c..ca5b0174166a6 100644 --- a/apps/dav/lib/CalDAV/Security/RateLimitingPlugin.php +++ b/apps/dav/lib/CalDAV/Security/RateLimitingPlugin.php @@ -24,17 +24,14 @@ class RateLimitingPlugin extends ServerPlugin { - private Limiter $limiter; - public function __construct( - Limiter $limiter, + private Limiter $limiter, private IUserManager $userManager, private CalDavBackend $calDavBackend, private LoggerInterface $logger, private IAppConfig $config, private ?string $userId, ) { - $this->limiter = $limiter; } public function initialize(DAV\Server $server): void { diff --git a/apps/dav/lib/Connector/Sabre/Principal.php b/apps/dav/lib/Connector/Sabre/Principal.php index 7f6941d44cdfa..75451d3b35fe8 100644 --- a/apps/dav/lib/Connector/Sabre/Principal.php +++ b/apps/dav/lib/Connector/Sabre/Principal.php @@ -42,9 +42,6 @@ class Principal implements BackendInterface { /** @var bool */ private $hasCircles; - /** @var KnownUserService */ - private $knownUserService; - public function __construct( private IUserManager $userManager, private IGroupManager $groupManager, @@ -53,14 +50,13 @@ public function __construct( private IUserSession $userSession, private IAppManager $appManager, private ProxyMapper $proxyMapper, - KnownUserService $knownUserService, + private KnownUserService $knownUserService, private IConfig $config, private IFactory $languageFactory, string $principalPrefix = 'principals/users/', ) { $this->principalPrefix = trim($principalPrefix, '/'); $this->hasGroups = $this->hasCircles = ($principalPrefix === 'principals/users/'); - $this->knownUserService = $knownUserService; } use PrincipalProxyTrait { diff --git a/apps/dav/lib/Connector/Sabre/TagsPlugin.php b/apps/dav/lib/Connector/Sabre/TagsPlugin.php index b883673e58253..41d38f4a4e77d 100644 --- a/apps/dav/lib/Connector/Sabre/TagsPlugin.php +++ b/apps/dav/lib/Connector/Sabre/TagsPlugin.php @@ -49,11 +49,7 @@ class TagsPlugin extends \Sabre\DAV\ServerPlugin { * @var \Sabre\DAV\Server */ private $server; - - /** - * @var ITags - */ - private $tagger; + private ?ITags $tagger = null; /** * Array of file id to tags array @@ -105,11 +101,17 @@ public function initialize(\Sabre\DAV\Server $server) { * * @return ITags tagger */ - private function getTagger() { - if (!$this->tagger) { - $this->tagger = $this->tagManager->load('files'); + private function getTagger(): ITags { + if ($this->tagger) { + return $this->tagger; + } + + $tagger = $this->tagManager->load('files'); + if ($tagger === null) { + throw new \RuntimeException('Tagger not found for files'); } - return $this->tagger; + $this->tagger = $tagger; + return $tagger; } /** diff --git a/apps/dav/lib/Migration/RemoveObjectProperties.php b/apps/dav/lib/Migration/RemoveObjectProperties.php index f09293ae0bbfa..8304accb51cac 100644 --- a/apps/dav/lib/Migration/RemoveObjectProperties.php +++ b/apps/dav/lib/Migration/RemoveObjectProperties.php @@ -16,27 +16,16 @@ class RemoveObjectProperties implements IRepairStep { private const ME_CARD_PROPERTY = '{http://calendarserver.org/ns/}me-card'; private const CALENDAR_TRANSP_PROPERTY = '{urn:ietf:params:xml:ns:caldav}schedule-calendar-transp'; - /** - * RemoveObjectProperties constructor. - * - * @param IDBConnection $connection - */ public function __construct( - private IDBConnection $connection, + private readonly IDBConnection $connection, ) { } - /** - * @inheritdoc - */ - public function getName() { + public function getName(): string { return 'Remove invalid object properties'; } - /** - * @inheritdoc - */ - public function run(IOutput $output) { + public function run(IOutput $output): void { $query = $this->connection->getQueryBuilder(); $updated = $query->delete('properties') ->where($query->expr()->in('propertyname', $query->createNamedParameter([self::RESOURCE_TYPE_PROPERTY, self::ME_CARD_PROPERTY, self::CALENDAR_TRANSP_PROPERTY], IQueryBuilder::PARAM_STR_ARRAY))) diff --git a/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php b/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php index 258138caa42be..31621cbc97c85 100644 --- a/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php +++ b/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php @@ -22,23 +22,17 @@ class AppleProvisioningPlugin extends ServerPlugin { */ protected $server; - /** - * @var \OC_Defaults - */ - protected $themingDefaults; - /** * AppleProvisioningPlugin constructor. */ public function __construct( protected IUserSession $userSession, protected IURLGenerator $urlGenerator, - \OC_Defaults $themingDefaults, + protected \OC_Defaults $themingDefaults, protected IRequest $request, protected IL10N $l10n, protected \Closure $uuidClosure, ) { - $this->themingDefaults = $themingDefaults; } /** diff --git a/apps/dav/lib/SystemTag/SystemTagsInUseCollection.php b/apps/dav/lib/SystemTag/SystemTagsInUseCollection.php index f11482b04ee1e..472726c74a782 100644 --- a/apps/dav/lib/SystemTag/SystemTagsInUseCollection.php +++ b/apps/dav/lib/SystemTag/SystemTagsInUseCollection.php @@ -22,18 +22,15 @@ use Sabre\DAV\SimpleCollection; class SystemTagsInUseCollection extends SimpleCollection { - protected SystemTagsInFilesDetector $systemTagsInFilesDetector; - /** @noinspection PhpMissingParentConstructorInspection */ public function __construct( protected IUserSession $userSession, protected IRootFolder $rootFolder, protected ISystemTagManager $systemTagManager, protected ISystemTagObjectMapper $tagMapper, - SystemTagsInFilesDetector $systemTagsInFilesDetector, + protected SystemTagsInFilesDetector $systemTagsInFilesDetector, protected string $mediaType = '', ) { - $this->systemTagsInFilesDetector = $systemTagsInFilesDetector; $this->name = 'systemtags-assigned'; if ($this->mediaType != '') { $this->name .= '/' . $this->mediaType; diff --git a/apps/dav/tests/unit/Connector/LegacyPublicAuthTest.php b/apps/dav/tests/unit/Connector/LegacyPublicAuthTest.php index 2c25b32fa0291..92a4e6503a4a6 100644 --- a/apps/dav/tests/unit/Connector/LegacyPublicAuthTest.php +++ b/apps/dav/tests/unit/Connector/LegacyPublicAuthTest.php @@ -15,16 +15,12 @@ use OCP\Share\Exceptions\ShareNotFound; use OCP\Share\IManager; use OCP\Share\IShare; +use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; -/** - * Class LegacyPublicAuthTest - * - * - * @package OCA\DAV\Tests\unit\Connector - */ -#[\PHPUnit\Framework\Attributes\Group('DB')] -class LegacyPublicAuthTest extends \Test\TestCase { +#[Group('DB')] +class LegacyPublicAuthTest extends TestCase { private ISession&MockObject $session; private IRequest&MockObject $request; private IManager&MockObject $shareManager; @@ -55,7 +51,7 @@ protected function tearDown(): void { \OC_User::setIncognitoMode(false); // Set old user - \OC_User::setUserId($this->oldUser); + \OC_User::setUserId($this->oldUser ?: null); if ($this->oldUser !== false) { \OC_Util::setupFS($this->oldUser); } diff --git a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php index e32d267106383..562c086c68608 100644 --- a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php @@ -78,7 +78,7 @@ public function testGetPrincipalsByPrefixWithoutPrefix(): void { } public function testGetPrincipalsByPrefixWithUsers(): void { - $fooUser = $this->createMock(User::class); + $fooUser = $this->createMock(IUser::class); $fooUser ->expects($this->once()) ->method('getUID') @@ -91,7 +91,7 @@ public function testGetPrincipalsByPrefixWithUsers(): void { ->expects($this->once()) ->method('getSystemEMailAddress') ->willReturn(''); - $barUser = $this->createMock(User::class); + $barUser = $this->createMock(IUser::class); $barUser ->expects($this->once()) ->method('getUID') @@ -183,7 +183,7 @@ public function testGetPrincipalsByPrefixEmpty(): void { } public function testGetPrincipalsByPathWithoutMail(): void { - $fooUser = $this->createMock(User::class); + $fooUser = $this->createMock(IUser::class); $fooUser ->expects($this->once()) ->method('getUID') @@ -211,7 +211,7 @@ public function testGetPrincipalsByPathWithoutMail(): void { } public function testGetPrincipalsByPathWithMail(): void { - $fooUser = $this->createMock(User::class); + $fooUser = $this->createMock(IUser::class); $fooUser ->expects($this->once()) ->method('getSystemEMailAddress') diff --git a/apps/federatedfilesharing/lib/Notifications.php b/apps/federatedfilesharing/lib/Notifications.php index 613c05613efb1..4a909048a95d6 100644 --- a/apps/federatedfilesharing/lib/Notifications.php +++ b/apps/federatedfilesharing/lib/Notifications.php @@ -7,6 +7,7 @@ */ namespace OCA\FederatedFileSharing; +use OC\ServerNotAvailableException; use OCA\FederatedFileSharing\Events\FederatedShareAddedEvent; use OCP\AppFramework\Http; use OCP\BackgroundJob\IJobList; @@ -47,7 +48,7 @@ public function __construct( * @param int $shareType (can be a remote user or group share) * @return bool * @throws HintException - * @throws \OC\ServerNotAvailableException + * @throws ServerNotAvailableException */ public function sendRemoteShare($token, $shareWith, $name, $remoteId, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId, $shareType) { [$user, $remote] = $this->addressHandler->splitUserRemote($shareWith); @@ -106,7 +107,7 @@ public function sendRemoteShare($token, $shareWith, $name, $remoteId, $owner, $o * @param string $filename * @return array|false * @throws HintException - * @throws \OC\ServerNotAvailableException + * @throws ServerNotAvailableException */ public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename, $shareType) { $fields = [ diff --git a/apps/federation/lib/SyncFederationAddressBooks.php b/apps/federation/lib/SyncFederationAddressBooks.php index d11f92b76efa8..51af00310e8c6 100644 --- a/apps/federation/lib/SyncFederationAddressBooks.php +++ b/apps/federation/lib/SyncFederationAddressBooks.php @@ -7,22 +7,18 @@ */ namespace OCA\Federation; -use OC\OCS\DiscoveryService; use OCA\DAV\CardDAV\SyncService; use OCP\AppFramework\Http; use OCP\OCS\IDiscoveryService; use Psr\Log\LoggerInterface; class SyncFederationAddressBooks { - private DiscoveryService $ocsDiscoveryService; - public function __construct( protected DbHandler $dbHandler, private SyncService $syncService, - IDiscoveryService $ocsDiscoveryService, + private IDiscoveryService $ocsDiscoveryService, private LoggerInterface $logger, ) { - $this->ocsDiscoveryService = $ocsDiscoveryService; } /** diff --git a/apps/files_external/lib/Lib/Notify/SMBNotifyHandler.php b/apps/files_external/lib/Lib/Notify/SMBNotifyHandler.php index 2812df6ad6a88..39472a7f9484e 100644 --- a/apps/files_external/lib/Lib/Notify/SMBNotifyHandler.php +++ b/apps/files_external/lib/Lib/Notify/SMBNotifyHandler.php @@ -110,21 +110,16 @@ private function mapChange(\Icewind\SMB\Change $change) { return $result; } - private function mapNotifyType($smbType) { - switch ($smbType) { - case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED: - return IChange::ADDED; - case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED: - return IChange::REMOVED; - case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED: - case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED_STREAM: - case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED_STREAM: - case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED_STREAM: - return IChange::MODIFIED; - case \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_NEW: - return IChange::RENAMED; - default: - return null; - } + /** + * @return IChange::ADDED|IChange::REMOVED|IChange::MODIFIED|IChange::RENAMED|null + */ + private function mapNotifyType($smbType): ?int { + return match ($smbType) { + \Icewind\SMB\INotifyHandler::NOTIFY_ADDED => IChange::ADDED, + \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED => IChange::REMOVED, + \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED, \Icewind\SMB\INotifyHandler::NOTIFY_ADDED_STREAM, \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED_STREAM, \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED_STREAM => IChange::MODIFIED, + \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_NEW => IChange::RENAMED, + default => null, + }; } } diff --git a/apps/files_sharing/lib/Controller/ShareController.php b/apps/files_sharing/lib/Controller/ShareController.php index 3c51a95f1d501..a7efca84c21bf 100644 --- a/apps/files_sharing/lib/Controller/ShareController.php +++ b/apps/files_sharing/lib/Controller/ShareController.php @@ -8,6 +8,7 @@ namespace OCA\Files_Sharing\Controller; use OC\Security\CSP\ContentSecurityPolicy; +use OC\ServerNotAvailableException; use OCA\DAV\Connector\Sabre\PublicAuth; use OCA\FederatedFileSharing\FederatedShareProvider; use OCA\Files_Sharing\Event\BeforeTemplateRenderedEvent; @@ -219,7 +220,7 @@ protected function authFailed() { * @param string $errorMessage * * @throws HintException - * @throws \OC\ServerNotAvailableException + * @throws ServerNotAvailableException * * @deprecated use OCP\Files_Sharing\Event\ShareLinkAccessedEvent */ diff --git a/apps/files_sharing/lib/External/Scanner.php b/apps/files_sharing/lib/External/Scanner.php index 0d57248595bdd..e6f96a846d6d7 100644 --- a/apps/files_sharing/lib/External/Scanner.php +++ b/apps/files_sharing/lib/External/Scanner.php @@ -13,10 +13,10 @@ 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 28972c1b4628b..c15a5ea03110d 100644 --- a/apps/files_sharing/lib/Scanner.php +++ b/apps/files_sharing/lib/Scanner.php @@ -10,17 +10,14 @@ 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 @@ public function getData($path) { return $data; } - private function getSourceScanner() { + private function getSourceScanner(): ?IScanner { if ($this->sourceScanner) { return $this->sourceScanner; } diff --git a/apps/files_sharing/lib/SharedMount.php b/apps/files_sharing/lib/SharedMount.php index 7dc95533d7497..099d586515ccd 100644 --- a/apps/files_sharing/lib/SharedMount.php +++ b/apps/files_sharing/lib/SharedMount.php @@ -28,9 +28,7 @@ * Shared mount points can be moved by the user */ class SharedMount extends MountPoint implements MoveableMount, ISharedMountPoint { - /** - * @var SharedStorage $storage - */ + /** @var ?SharedStorage $storage */ protected $storage = null; /** @var IShare */ diff --git a/apps/files_sharing/tests/Controller/ShareAPIControllerTest.php b/apps/files_sharing/tests/Controller/ShareAPIControllerTest.php index 93c9d6e817d97..770c0c40e3f30 100644 --- a/apps/files_sharing/tests/Controller/ShareAPIControllerTest.php +++ b/apps/files_sharing/tests/Controller/ShareAPIControllerTest.php @@ -125,6 +125,8 @@ protected function setUp(): void { return $fileInfo->getMimeType() === 'mimeWithPreview'; }); $this->dateTimeZone = $this->createMock(IDateTimeZone::class); + $this->dateTimeZone->method('getTimeZone') + ->willReturn(new \DateTimeZone('UTC')); $this->logger = $this->createMock(LoggerInterface::class); $this->factory = $this->createMock(IProviderFactory::class); $this->mailer = $this->createMock(IMailer::class); @@ -158,10 +160,7 @@ protected function setUp(): void { } - /** - * @return ShareAPIController&MockObject - */ - private function mockFormatShare() { + private function mockFormatShare(): ShareAPIController&MockObject { return $this->getMockBuilder(ShareAPIController::class) ->setConstructorArgs([ $this->appName, diff --git a/apps/lookup_server_connector/lib/BackgroundJobs/RetryJob.php b/apps/lookup_server_connector/lib/BackgroundJobs/RetryJob.php index 08fe0b3fa2b42..411c02685fca4 100644 --- a/apps/lookup_server_connector/lib/BackgroundJobs/RetryJob.php +++ b/apps/lookup_server_connector/lib/BackgroundJobs/RetryJob.php @@ -20,7 +20,6 @@ class RetryJob extends Job { private string $lookupServer; - private Signer $signer; protected int $retries = 0; protected bool $retainJob = false; @@ -38,10 +37,9 @@ public function __construct( private IConfig $config, private IUserManager $userManager, private IAccountManager $accountManager, - Signer $signer, + private Signer $signer, ) { parent::__construct($time); - $this->signer = $signer; $this->lookupServer = $this->config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com'); if (!empty($this->lookupServer)) { diff --git a/apps/provisioning_api/lib/Controller/VerificationController.php b/apps/provisioning_api/lib/Controller/VerificationController.php index e89d8f1780c82..d5a51a95ad07f 100644 --- a/apps/provisioning_api/lib/Controller/VerificationController.php +++ b/apps/provisioning_api/lib/Controller/VerificationController.php @@ -28,9 +28,6 @@ #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)] class VerificationController extends Controller { - /** @var Crypto */ - private $crypto; - public function __construct( string $appName, IRequest $request, @@ -39,10 +36,9 @@ public function __construct( private IL10N $l10n, private IUserSession $userSession, private IAccountManager $accountManager, - Crypto $crypto, + private Crypto $crypto, ) { parent::__construct($appName, $request); - $this->crypto = $crypto; } /** diff --git a/apps/provisioning_api/lib/Listener/UserDeletedListener.php b/apps/provisioning_api/lib/Listener/UserDeletedListener.php index 099b5593ed7c2..5a2dce249fba5 100644 --- a/apps/provisioning_api/lib/Listener/UserDeletedListener.php +++ b/apps/provisioning_api/lib/Listener/UserDeletedListener.php @@ -16,11 +16,9 @@ /** @template-implements IEventListener */ class UserDeletedListener implements IEventListener { - /** @var KnownUserService */ - private $service; - - public function __construct(KnownUserService $service) { - $this->service = $service; + public function __construct( + private KnownUserService $service, + ) { } public function handle(Event $event): void { diff --git a/apps/settings/lib/AppInfo/Application.php b/apps/settings/lib/AppInfo/Application.php index f2e6036af43e0..1900ec421786f 100644 --- a/apps/settings/lib/AppInfo/Application.php +++ b/apps/settings/lib/AppInfo/Application.php @@ -11,7 +11,7 @@ use OC\AppFramework\Utility\TimeFactory; use OC\Authentication\Events\AppPasswordCreatedEvent; use OC\Authentication\Token\IProvider; -use OC\Server; +use OC\Settings\Manager; use OCA\Settings\ConfigLexicon; use OCA\Settings\Hooks; use OCA\Settings\Listener\AppPasswordCreatedActivityListener; @@ -84,25 +84,28 @@ use OCP\AppFramework\Bootstrap\IBootContext; use OCP\AppFramework\Bootstrap\IBootstrap; use OCP\AppFramework\Bootstrap\IRegistrationContext; -use OCP\AppFramework\IAppContainer; use OCP\Defaults; use OCP\Group\Events\GroupDeletedEvent; use OCP\Group\Events\UserAddedEvent; use OCP\Group\Events\UserRemovedEvent; -use OCP\IServerContainer; +use OCP\IConfig; +use OCP\IURLGenerator; +use OCP\L10N\IFactory; +use OCP\Mail\IMailer; +use OCP\Security\ICrypto; +use OCP\Security\ISecureRandom; +use OCP\Server; use OCP\Settings\Events\DeclarativeSettingsGetValueEvent; use OCP\Settings\Events\DeclarativeSettingsSetValueEvent; use OCP\Settings\IManager; use OCP\User\Events\PasswordUpdatedEvent; use OCP\User\Events\UserChangedEvent; use OCP\Util; +use Psr\Container\ContainerInterface; class Application extends App implements IBootstrap { public const APP_ID = 'settings'; - /** - * @param array $urlParams - */ public function __construct(array $urlParams = []) { parent::__construct(self::APP_ID, $urlParams); } @@ -139,32 +142,23 @@ public function register(IRegistrationContext $context): void { /** * Core class wrappers */ - $context->registerService(IProvider::class, function (IAppContainer $appContainer) { - /** @var IServerContainer $serverContainer */ - $serverContainer = $appContainer->query(IServerContainer::class); - return $serverContainer->query(IProvider::class); + $context->registerService(IProvider::class, function (): IProvider { + return Server::get(IProvider::class); }); - $context->registerService(IManager::class, function (IAppContainer $appContainer) { - /** @var IServerContainer $serverContainer */ - $serverContainer = $appContainer->query(IServerContainer::class); - return $serverContainer->getSettingsManager(); + $context->registerService(IManager::class, function (): Manager { + return Server::get(Manager::class); }); - $context->registerService(NewUserMailHelper::class, function (IAppContainer $appContainer) { - /** @var Server $server */ - $server = $appContainer->query(IServerContainer::class); - /** @var Defaults $defaults */ - $defaults = $server->query(Defaults::class); - + $context->registerService(NewUserMailHelper::class, function (ContainerInterface $appContainer) { return new NewUserMailHelper( - $defaults, - $server->getURLGenerator(), - $server->getL10NFactory(), - $server->getMailer(), - $server->getSecureRandom(), + Server::get(Defaults::class), + $appContainer->get(IURLGenerator::class), + $appContainer->get(IFactory::class), + $appContainer->get(IMailer::class), + $appContainer->get(ISecureRandom::class), new TimeFactory(), - $server->getConfig(), - $server->getCrypto(), + $appContainer->get(IConfig::class), + $appContainer->get(ICrypto::class), Util::getDefaultEmailAddress('no-reply') ); }); diff --git a/apps/settings/lib/Controller/AuthSettingsController.php b/apps/settings/lib/Controller/AuthSettingsController.php index 8652a49fb1d6e..f9f5e3a04382f 100644 --- a/apps/settings/lib/Controller/AuthSettingsController.php +++ b/apps/settings/lib/Controller/AuthSettingsController.php @@ -32,12 +32,6 @@ use Psr\Log\LoggerInterface; class AuthSettingsController extends Controller { - /** @var IProvider */ - private $tokenProvider; - - /** @var RemoteWipe */ - private $remoteWipe; - /** * @param string $appName * @param IRequest $request @@ -53,18 +47,16 @@ class AuthSettingsController extends Controller { public function __construct( string $appName, IRequest $request, - IProvider $tokenProvider, + private IProvider $tokenProvider, private ISession $session, private ISecureRandom $random, private ?string $userId, private IUserSession $userSession, private IManager $activityManager, - RemoteWipe $remoteWipe, + private RemoteWipe $remoteWipe, private LoggerInterface $logger, ) { parent::__construct($appName, $request); - $this->tokenProvider = $tokenProvider; - $this->remoteWipe = $remoteWipe; } /** diff --git a/apps/settings/lib/Controller/ChangePasswordController.php b/apps/settings/lib/Controller/ChangePasswordController.php index a874a47c16aa4..375254470f007 100644 --- a/apps/settings/lib/Controller/ChangePasswordController.php +++ b/apps/settings/lib/Controller/ChangePasswordController.php @@ -25,24 +25,20 @@ use OCP\IRequest; use OCP\IUser; use OCP\IUserManager; -use OCP\IUserSession; use OCP\Server; class ChangePasswordController extends Controller { - private Session $userSession; - public function __construct( string $appName, IRequest $request, private ?string $userId, private IUserManager $userManager, - IUserSession $userSession, + private Session $userSession, private GroupManager $groupManager, private IAppManager $appManager, private IL10N $l, ) { parent::__construct($appName, $request); - $this->userSession = $userSession; } /** diff --git a/apps/settings/lib/Controller/CheckSetupController.php b/apps/settings/lib/Controller/CheckSetupController.php index 3335dede58bef..f54b1d63aab91 100644 --- a/apps/settings/lib/Controller/CheckSetupController.php +++ b/apps/settings/lib/Controller/CheckSetupController.php @@ -27,21 +27,17 @@ #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)] class CheckSetupController extends Controller { - /** @var Checker */ - private $checker; - public function __construct( $appName, IRequest $request, private IConfig $config, private IURLGenerator $urlGenerator, private IL10N $l10n, - Checker $checker, + private Checker $checker, private LoggerInterface $logger, private ISetupCheckManager $setupCheckManager, ) { parent::__construct($appName, $request); - $this->checker = $checker; } /** diff --git a/apps/settings/lib/Controller/LogSettingsController.php b/apps/settings/lib/Controller/LogSettingsController.php index 90cf4549d2fa9..4f4986122d265 100644 --- a/apps/settings/lib/Controller/LogSettingsController.php +++ b/apps/settings/lib/Controller/LogSettingsController.php @@ -17,12 +17,12 @@ class LogSettingsController extends Controller { - /** @var Log */ - private $log; - - public function __construct(string $appName, IRequest $request, Log $logger) { + public function __construct( + string $appName, + IRequest $request, + private Log $log, + ) { parent::__construct($appName, $request); - $this->log = $logger; } /** diff --git a/apps/settings/lib/Controller/TwoFactorSettingsController.php b/apps/settings/lib/Controller/TwoFactorSettingsController.php index e08fca8ec6ce9..62bbb5b1a9fc7 100644 --- a/apps/settings/lib/Controller/TwoFactorSettingsController.php +++ b/apps/settings/lib/Controller/TwoFactorSettingsController.php @@ -16,15 +16,12 @@ class TwoFactorSettingsController extends Controller { - /** @var MandatoryTwoFactor */ - private $mandatoryTwoFactor; - - public function __construct(string $appName, + public function __construct( + string $appName, IRequest $request, - MandatoryTwoFactor $mandatoryTwoFactor) { + private MandatoryTwoFactor $mandatoryTwoFactor, + ) { parent::__construct($appName, $request); - - $this->mandatoryTwoFactor = $mandatoryTwoFactor; } public function index(): JSONResponse { diff --git a/apps/settings/lib/Listener/AppPasswordCreatedActivityListener.php b/apps/settings/lib/Listener/AppPasswordCreatedActivityListener.php index a51eee1a79974..92258b35d3652 100644 --- a/apps/settings/lib/Listener/AppPasswordCreatedActivityListener.php +++ b/apps/settings/lib/Listener/AppPasswordCreatedActivityListener.php @@ -18,7 +18,7 @@ use Psr\Log\LoggerInterface; /** - * @template-implements IEventListener<\OC\Authentication\Events\AppPasswordCreatedEvent> + * @template-implements IEventListener */ class AppPasswordCreatedActivityListener implements IEventListener { public function __construct( diff --git a/apps/settings/lib/Middleware/SubadminMiddleware.php b/apps/settings/lib/Middleware/SubadminMiddleware.php index 02d68e138dae4..d7be892d163c6 100644 --- a/apps/settings/lib/Middleware/SubadminMiddleware.php +++ b/apps/settings/lib/Middleware/SubadminMiddleware.php @@ -19,9 +19,10 @@ use OCP\Group\ISubAdmin; use OCP\IL10N; use OCP\IUserSession; +use Override; /** - * Verifies whether an user has at least subadmin rights. + * Verifies whether a user has at least sub-admin rights. * To bypass use the `@NoSubAdminRequired` annotation */ class SubadminMiddleware extends Middleware { @@ -41,13 +42,8 @@ private function isSubAdmin(): bool { return $this->subAdminManager->isSubAdmin($userObject); } - /** - * Check if sharing is enabled before the controllers is executed - * @param Controller $controller - * @param string $methodName - * @throws \Exception - */ - public function beforeController($controller, $methodName) { + #[Override] + public function beforeController(Controller $controller, string $methodName): void { if (!$this->reflector->hasAnnotation('NoSubAdminRequired') && !$this->reflector->hasAnnotation('AuthorizedAdminSetting')) { if (!$this->isSubAdmin()) { throw new NotAdminException($this->l10n->t('Logged in account must be a sub admin')); @@ -55,15 +51,8 @@ public function beforeController($controller, $methodName) { } } - /** - * Return 403 page in case of an exception - * @param Controller $controller - * @param string $methodName - * @param \Exception $exception - * @return TemplateResponse - * @throws \Exception - */ - public function afterException($controller, $methodName, \Exception $exception) { + #[Override] + public function afterException(Controller $controller, string $methodName, \Exception $exception): TemplateResponse { if ($exception instanceof NotAdminException) { $response = new TemplateResponse('core', '403', [], 'guest'); $response->setStatus(Http::STATUS_FORBIDDEN); diff --git a/apps/settings/lib/Settings/Admin/Security.php b/apps/settings/lib/Settings/Admin/Security.php index c4efdb478c7eb..b21b9cd25127d 100644 --- a/apps/settings/lib/Settings/Admin/Security.php +++ b/apps/settings/lib/Settings/Admin/Security.php @@ -15,16 +15,13 @@ use OCP\Settings\ISettings; class Security implements ISettings { - private MandatoryTwoFactor $mandatoryTwoFactor; - public function __construct( private IManager $manager, private IUserManager $userManager, - MandatoryTwoFactor $mandatoryTwoFactor, + private MandatoryTwoFactor $mandatoryTwoFactor, private IInitialState $initialState, private IURLGenerator $urlGenerator, ) { - $this->mandatoryTwoFactor = $mandatoryTwoFactor; } /** diff --git a/apps/settings/lib/Settings/Personal/PersonalInfo.php b/apps/settings/lib/Settings/Personal/PersonalInfo.php index afa9f076e1a53..867d31073234d 100644 --- a/apps/settings/lib/Settings/Personal/PersonalInfo.php +++ b/apps/settings/lib/Settings/Personal/PersonalInfo.php @@ -33,22 +33,18 @@ class PersonalInfo implements ISettings { - /** @var ProfileManager */ - private $profileManager; - public function __construct( private IConfig $config, private IUserManager $userManager, private IGroupManager $groupManager, private IAccountManager $accountManager, - ProfileManager $profileManager, + private ProfileManager $profileManager, private IAppManager $appManager, private IFactory $l10nFactory, private IL10N $l, private IInitialState $initialStateService, private IManager $manager, ) { - $this->profileManager = $profileManager; } public function getForm(): TemplateResponse { diff --git a/apps/settings/lib/Settings/Personal/Security/TwoFactor.php b/apps/settings/lib/Settings/Personal/Security/TwoFactor.php index 0c419cb6fa74b..04bb003dba51c 100644 --- a/apps/settings/lib/Settings/Personal/Security/TwoFactor.php +++ b/apps/settings/lib/Settings/Personal/Security/TwoFactor.php @@ -24,21 +24,13 @@ class TwoFactor implements ISettings { - /** @var ProviderLoader */ - private $providerLoader; - - /** @var MandatoryTwoFactor */ - private $mandatoryTwoFactor; - public function __construct( - ProviderLoader $providerLoader, - MandatoryTwoFactor $mandatoryTwoFactor, + private ProviderLoader $providerLoader, + private MandatoryTwoFactor $mandatoryTwoFactor, private IUserSession $userSession, private IConfig $config, private ?string $userId, ) { - $this->providerLoader = $providerLoader; - $this->mandatoryTwoFactor = $mandatoryTwoFactor; } public function getForm(): TemplateResponse { diff --git a/apps/settings/lib/Settings/Personal/Security/WebAuthn.php b/apps/settings/lib/Settings/Personal/Security/WebAuthn.php index a6ba4e9522a04..10e5ee7626303 100644 --- a/apps/settings/lib/Settings/Personal/Security/WebAuthn.php +++ b/apps/settings/lib/Settings/Personal/Security/WebAuthn.php @@ -17,20 +17,12 @@ class WebAuthn implements ISettings { - /** @var PublicKeyCredentialMapper */ - private $mapper; - - /** @var Manager */ - private $manager; - public function __construct( - PublicKeyCredentialMapper $mapper, + private PublicKeyCredentialMapper $mapper, private string $userId, private IInitialStateService $initialStateService, - Manager $manager, + private Manager $manager, ) { - $this->mapper = $mapper; - $this->manager = $manager; } public function getForm() { diff --git a/apps/settings/lib/UserMigration/AccountMigrator.php b/apps/settings/lib/UserMigration/AccountMigrator.php index 1c51aec51042c..2670974c52b94 100644 --- a/apps/settings/lib/UserMigration/AccountMigrator.php +++ b/apps/settings/lib/UserMigration/AccountMigrator.php @@ -33,8 +33,6 @@ class AccountMigrator implements IMigrator, ISizeEstimationMigrator { use TAccountsHelper; - private ProfileManager $profileManager; - private const PATH_ROOT = Application::APP_ID . '/'; private const PATH_ACCOUNT_FILE = AccountMigrator::PATH_ROOT . 'account.json'; @@ -46,11 +44,10 @@ class AccountMigrator implements IMigrator, ISizeEstimationMigrator { public function __construct( private IAccountManager $accountManager, private IAvatarManager $avatarManager, - ProfileManager $profileManager, + private ProfileManager $profileManager, private ProfileConfigMapper $configMapper, private IL10N $l10n, ) { - $this->profileManager = $profileManager; } /** diff --git a/apps/theming/lib/Controller/IconController.php b/apps/theming/lib/Controller/IconController.php index e82faf78a798a..5e49467523690 100644 --- a/apps/theming/lib/Controller/IconController.php +++ b/apps/theming/lib/Controller/IconController.php @@ -24,20 +24,16 @@ use OCP\IRequest; class IconController extends Controller { - /** @var FileAccessHelper */ - private $fileAccessHelper; - public function __construct( $appName, IRequest $request, private ThemingDefaults $themingDefaults, private IconBuilder $iconBuilder, private ImageManager $imageManager, - FileAccessHelper $fileAccessHelper, + private FileAccessHelper $fileAccessHelper, private IAppManager $appManager, ) { parent::__construct($appName, $request); - $this->fileAccessHelper = $fileAccessHelper; } /** diff --git a/apps/twofactor_backupcodes/lib/BackgroundJob/CheckBackupCodes.php b/apps/twofactor_backupcodes/lib/BackgroundJob/CheckBackupCodes.php index bc26cb260f408..af80847451af0 100644 --- a/apps/twofactor_backupcodes/lib/BackgroundJob/CheckBackupCodes.php +++ b/apps/twofactor_backupcodes/lib/BackgroundJob/CheckBackupCodes.php @@ -18,18 +18,14 @@ class CheckBackupCodes extends QueuedJob { - /** @var Manager */ - private $twofactorManager; - public function __construct( ITimeFactory $timeFactory, private IUserManager $userManager, private IJobList $jobList, - Manager $twofactorManager, + private Manager $twofactorManager, private IRegistry $registry, ) { parent::__construct($timeFactory); - $this->twofactorManager = $twofactorManager; } protected function run($argument) { diff --git a/apps/user_ldap/lib/Access.php b/apps/user_ldap/lib/Access.php index a6a414d29bf93..3e4efc5b8dbdb 100644 --- a/apps/user_ldap/lib/Access.php +++ b/apps/user_ldap/lib/Access.php @@ -1048,13 +1048,9 @@ public function countObjects(?int $limit = null, ?int $offset = null) { /** * Returns the LDAP handler * - * @throws \OC\ServerNotAvailableException - */ - - /** * @param mixed[] $arguments * @return mixed - * @throws \OC\ServerNotAvailableException + * @throws ServerNotAvailableException */ private function invokeLDAPMethod(string $command, ...$arguments) { if ($command == 'controlPagedResultResponse') { diff --git a/apps/user_ldap/lib/Connection.php b/apps/user_ldap/lib/Connection.php index 71a7a7838182f..367c79d7e5d95 100644 --- a/apps/user_ldap/lib/Connection.php +++ b/apps/user_ldap/lib/Connection.php @@ -663,7 +663,7 @@ private function establishConnection(): ?bool { /** * @param string $host * @param string $port - * @throws \OC\ServerNotAvailableException + * @throws ServerNotAvailableException */ private function doConnect($host, $port): bool { if ($host === '') { diff --git a/apps/user_ldap/lib/User/User.php b/apps/user_ldap/lib/User/User.php index 809067d0737a5..2f928d1b67edb 100644 --- a/apps/user_ldap/lib/User/User.php +++ b/apps/user_ldap/lib/User/User.php @@ -9,6 +9,7 @@ use InvalidArgumentException; use OC\Accounts\AccountManager; +use OC\ServerNotAvailableException; use OCA\User_LDAP\Access; use OCA\User_LDAP\Connection; use OCA\User_LDAP\Exceptions\AttributeNotSet; @@ -693,7 +694,7 @@ private function setNextcloudAvatar(): bool { /** * @throws AttributeNotSet - * @throws \OC\ServerNotAvailableException + * @throws ServerNotAvailableException * @throws PreConditionNotMetException */ public function getExtStorageHome():string { @@ -714,7 +715,7 @@ public function getExtStorageHome():string { /** * @throws PreConditionNotMetException - * @throws \OC\ServerNotAvailableException + * @throws ServerNotAvailableException */ public function updateExtStorageHome(?string $valueFromLDAP = null):string { if ($valueFromLDAP === null) { diff --git a/apps/user_ldap/lib/User_LDAP.php b/apps/user_ldap/lib/User_LDAP.php index 708aeb037fd2b..5191ed6d2e09e 100644 --- a/apps/user_ldap/lib/User_LDAP.php +++ b/apps/user_ldap/lib/User_LDAP.php @@ -260,10 +260,9 @@ public function getUsers($search = '', $limit = 10, $offset = 0) { /** * checks whether a user is still available on LDAP * - * @param string|User $user either the Nextcloud user - * name or an instance of that user + * @param string|User $user either the Nextcloud user id or an instance of that user * @throws \Exception - * @throws \OC\ServerNotAvailableException + * @throws ServerNotAvailableException */ public function userExistsOnLDAP($user, bool $ignoreCache = false): bool { if (is_string($user)) { diff --git a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php index 6726143a44932..a2e8bbb4212c4 100644 --- a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php +++ b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php @@ -7,6 +7,7 @@ */ namespace OCA\User_LDAP\Tests\Integration\Lib\User; +use OC\ServerNotAvailableException; use OCA\User_LDAP\Mapping\UserMapping; use OCA\User_LDAP\Tests\Integration\AbstractIntegrationTest; use OCA\User_LDAP\User\DeletedUsersIndex; @@ -108,7 +109,7 @@ protected function case2() { * * @param string $dn * @param string $image An image read via file_get_contents - * @throws \OC\ServerNotAvailableException + * @throws ServerNotAvailableException */ private function setJpegPhotoAttribute($dn, $image) { $changeSet = ['jpegphoto' => $image]; diff --git a/apps/user_status/lib/Listener/BeforeTemplateRenderedListener.php b/apps/user_status/lib/Listener/BeforeTemplateRenderedListener.php index 794862464301c..0fa165a8d03a3 100644 --- a/apps/user_status/lib/Listener/BeforeTemplateRenderedListener.php +++ b/apps/user_status/lib/Listener/BeforeTemplateRenderedListener.php @@ -23,9 +23,6 @@ /** @template-implements IEventListener */ class BeforeTemplateRenderedListener implements IEventListener { - /** @var ProfileManager */ - private $profileManager; - /** * BeforeTemplateRenderedListener constructor. * @@ -35,12 +32,11 @@ class BeforeTemplateRenderedListener implements IEventListener { * @param JSDataService $jsDataService */ public function __construct( - ProfileManager $profileManager, + private ProfileManager $profileManager, private IUserSession $userSession, private IInitialStateService $initialState, private JSDataService $jsDataService, ) { - $this->profileManager = $profileManager; } /** diff --git a/build/psalm-baseline.xml b/build/psalm-baseline.xml index 75ce3d3bde524..15f76ae780502 100644 --- a/build/psalm-baseline.xml +++ b/build/psalm-baseline.xml @@ -663,7 +663,6 @@ - @@ -2336,31 +2335,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - @@ -3402,14 +3376,6 @@ - - - server]]> - - - - - @@ -3449,9 +3415,6 @@ request->server]]> - - - @@ -3559,16 +3522,16 @@ - - - + + + - - - + + + @@ -3679,16 +3642,6 @@ - - - - - - - - - - @@ -3777,11 +3730,6 @@ getStorageInfo($storageId)]]> - - - cache instanceof Cache]]> - - @@ -3808,18 +3756,6 @@ - - - getStorage()]]> - findByNumericId($id)]]> - findByStorageId($id)]]> - - - - - - - @@ -4000,32 +3936,7 @@ getContent())]]> - - - - - - - - - emitter]]> - emitter]]> - emitter]]> - - - - - - - - - - - - - - @@ -4114,11 +4025,6 @@ - - - - - @@ -4137,16 +4043,6 @@ - - - - - - - - - - userToNotify]]> @@ -4180,25 +4076,6 @@ - - - - - - get(IFile::class)]]> - get(IGroupManager::class)]]> - get(IUserManager::class)]]> - get(IUserSession::class)]]> - get(\OCP\Encryption\IManager::class)]]> - - - - - - - - - hasNoAppContainer]]> @@ -4236,11 +4113,6 @@ dbprettyname]]> - - - - - @@ -4274,14 +4146,6 @@ - - - - - - - - diff --git a/build/rector.php b/build/rector.php index e32a064234afc..374854465313b 100644 --- a/build/rector.php +++ b/build/rector.php @@ -64,11 +64,9 @@ public function shouldSkip(File $file, FullyQualifiedObjectType $fullyQualifiedO $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', ]) ->withSkip([ @@ -76,6 +74,8 @@ public function shouldSkip(File $file, FullyQualifiedObjectType $fullyQualifiedO $nextcloudDir . '/apps/*/build/stubs/*', $nextcloudDir . '/apps/*/composer/*', $nextcloudDir . '/apps/*/config/*', + $nextcloudDir . '/lib/private/AppFramework/Middleware/Security/RateLimitingMiddleware.php', + $nextcloudDir . '/lib/private/Files/Node/*', // The mock classes are excluded, as the tests explicitly test the annotations which should not be migrated to attributes $nextcloudDir . '/tests/lib/AppFramework/Middleware/Mock/*', $nextcloudDir . '/tests/lib/AppFramework/Middleware/Security/Mock/*', diff --git a/core/Command/Maintenance/Repair.php b/core/Command/Maintenance/Repair.php index f0c88f6811b7a..84bfe0b4cb3e4 100644 --- a/core/Command/Maintenance/Repair.php +++ b/core/Command/Maintenance/Repair.php @@ -39,7 +39,7 @@ public function __construct( parent::__construct(); } - protected function configure() { + protected function configure(): void { $this ->setName('maintenance:repair') ->setDescription('repair this installation') @@ -81,20 +81,18 @@ protected function execute(InputInterface $input, OutputInterface $output): int } } - - $maintenanceMode = $this->config->getSystemValueBool('maintenance'); $this->config->setSystemValue('maintenance', true); $this->progress = new ProgressBar($output); $this->output = $output; - $this->dispatcher->addListener(RepairStartEvent::class, [$this, 'handleRepairFeedBack']); - $this->dispatcher->addListener(RepairAdvanceEvent::class, [$this, 'handleRepairFeedBack']); - $this->dispatcher->addListener(RepairFinishEvent::class, [$this, 'handleRepairFeedBack']); - $this->dispatcher->addListener(RepairStepEvent::class, [$this, 'handleRepairFeedBack']); - $this->dispatcher->addListener(RepairInfoEvent::class, [$this, 'handleRepairFeedBack']); - $this->dispatcher->addListener(RepairWarningEvent::class, [$this, 'handleRepairFeedBack']); - $this->dispatcher->addListener(RepairErrorEvent::class, [$this, 'handleRepairFeedBack']); + $this->dispatcher->addListener(RepairStartEvent::class, $this->handleRepairFeedBack(...)); + $this->dispatcher->addListener(RepairAdvanceEvent::class, $this->handleRepairFeedBack(...)); + $this->dispatcher->addListener(RepairFinishEvent::class, $this->handleRepairFeedBack(...)); + $this->dispatcher->addListener(RepairStepEvent::class, $this->handleRepairFeedBack(...)); + $this->dispatcher->addListener(RepairInfoEvent::class, $this->handleRepairFeedBack(...)); + $this->dispatcher->addListener(RepairWarningEvent::class, $this->handleRepairFeedBack(...)); + $this->dispatcher->addListener(RepairErrorEvent::class, $this->handleRepairFeedBack(...)); $this->repair->run(); diff --git a/core/Command/Memcache/RedisCommand.php b/core/Command/Memcache/RedisCommand.php index 429dd28f3b310..1d1a7243d21c5 100644 --- a/core/Command/Memcache/RedisCommand.php +++ b/core/Command/Memcache/RedisCommand.php @@ -44,7 +44,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int return 1; } - $redis->setOption(\Redis::OPT_REPLY_LITERAL, true); + if ($redis instanceof \Redis) { + $redis->setOption(\Redis::OPT_REPLY_LITERAL, true); + } $result = $redis->rawCommand(...$command); if ($result === false) { $output->writeln('Redis command failed'); diff --git a/core/routes.php b/core/routes.php index 086afcdbac848..81f84456d528d 100644 --- a/core/routes.php +++ b/core/routes.php @@ -2,13 +2,14 @@ declare(strict_types=1); +use OC\Route\Router; + /** - * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016-2025 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2012-2016 ownCloud, Inc. * SPDX-License-Identifier: AGPL-3.0-only */ - -/** @var OC\Route\Router $this */ +/** @var Router $this */ // Core ajax actions // Routing $this->create('core_ajax_update', '/core/ajax/update.php') diff --git a/lib/composer/composer/autoload_classmap.php b/lib/composer/composer/autoload_classmap.php index 0b6dd29f2040b..705245f6eba6d 100644 --- a/lib/composer/composer/autoload_classmap.php +++ b/lib/composer/composer/autoload_classmap.php @@ -2122,7 +2122,6 @@ 'OC\\Share20\\UserDeletedListener' => $baseDir . '/lib/private/Share20/UserDeletedListener.php', 'OC\\Share20\\UserRemovedListener' => $baseDir . '/lib/private/Share20/UserRemovedListener.php', 'OC\\Share\\Constants' => $baseDir . '/lib/private/Share/Constants.php', - 'OC\\Share\\Helper' => $baseDir . '/lib/private/Share/Helper.php', 'OC\\Share\\Share' => $baseDir . '/lib/private/Share/Share.php', 'OC\\Snowflake\\APCuSequence' => $baseDir . '/lib/private/Snowflake/APCuSequence.php', 'OC\\Snowflake\\Decoder' => $baseDir . '/lib/private/Snowflake/Decoder.php', diff --git a/lib/composer/composer/autoload_static.php b/lib/composer/composer/autoload_static.php index 9c34d2cd4debd..d78e1f45a118a 100644 --- a/lib/composer/composer/autoload_static.php +++ b/lib/composer/composer/autoload_static.php @@ -2163,7 +2163,6 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2 'OC\\Share20\\UserDeletedListener' => __DIR__ . '/../../..' . '/lib/private/Share20/UserDeletedListener.php', 'OC\\Share20\\UserRemovedListener' => __DIR__ . '/../../..' . '/lib/private/Share20/UserRemovedListener.php', 'OC\\Share\\Constants' => __DIR__ . '/../../..' . '/lib/private/Share/Constants.php', - 'OC\\Share\\Helper' => __DIR__ . '/../../..' . '/lib/private/Share/Helper.php', 'OC\\Share\\Share' => __DIR__ . '/../../..' . '/lib/private/Share/Share.php', 'OC\\Snowflake\\APCuSequence' => __DIR__ . '/../../..' . '/lib/private/Snowflake/APCuSequence.php', 'OC\\Snowflake\\Decoder' => __DIR__ . '/../../..' . '/lib/private/Snowflake/Decoder.php', diff --git a/lib/private/Activity/EventMerger.php b/lib/private/Activity/EventMerger.php index 0e7d318103aab..2b9294f585243 100644 --- a/lib/private/Activity/EventMerger.php +++ b/lib/private/Activity/EventMerger.php @@ -11,14 +11,12 @@ 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 2dfc5c2609769..6623cde14b015 100644 --- a/lib/private/Activity/Manager.php +++ b/lib/private/Activity/Manager.php @@ -26,6 +26,7 @@ use OCP\IUserSession; use OCP\RichObjectStrings\IRichTextFormatter; use OCP\RichObjectStrings\IValidator; +use OCP\Server; class Manager implements IManager { @@ -59,7 +60,7 @@ public function __construct( private $consumers = []; /** - * @return \OCP\Activity\IConsumer[] + * @return IConsumer[] */ protected function getConsumers(): array { if (!empty($this->consumers)) { @@ -183,7 +184,7 @@ public function registerFilter(string $filter): void { 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 @@ public function registerProvider(string $provider): void { 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 @@ public function registerSetting(string $setting): void { 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 6356188bab66f..4f8229a8f991e 100644 --- a/lib/private/AllConfig.php +++ b/lib/private/AllConfig.php @@ -13,6 +13,7 @@ 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 @@ public function __construct( } /** - * 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 @@ public function deleteSystemValue($key) { * @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 @@ public function getAppKeys($appName) { * @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 @@ public function setAppValue($appName, $key, $value) { * @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 @@ public function getAppValue($appName, $key, $default = '') { * @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 @@ public function deleteAppValue($appName, $key) { * @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 @@ public function deleteAppValues($appName) { * @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 @@ public function setUserValue($userId, $appName, $key, $value, $preCondition = nu } /** @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 @@ public function getUserValue($userId, $appName, $key, $default = '') { 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 @@ public function getUserValue($userId, $appName, $key, $default = '') { * @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 @@ public function getUserKeys($userId, $appName) { * @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 @@ public function deleteAllUserValues($userId) { if ($userId === null) { return; } - \OCP\Server::get(IUserConfig::class)->deleteAllUserConfig($userId); + Server::get(IUserConfig::class)->deleteAllUserConfig($userId); } /** @@ -288,7 +289,7 @@ public function deleteAllUserValues($userId) { * @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 @@ public function getAllUserValues(?string $userId): array { 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 @@ public function getAllUserValues(?string $userId): array { * @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 @@ public function getUserValueForUsers($appName, $key, $userIds) { */ 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 8137805ac3488..64b692331e9f1 100644 --- a/lib/private/App/AppManager.php +++ b/lib/private/App/AppManager.php @@ -11,6 +11,7 @@ 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 @@ public function getAllAppsInAppsFolders(): array { /** * 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 @@ public function getAppRestriction(string $appId): array { * 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 @@ public function loadApp(string $app): void { ]); 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 @@ public function loadApp(string $app): void { $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 @@ public function loadApp(string $app): void { } 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 @@ public function loadApp(string $app): void { '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']); } } @@ -1069,7 +1070,7 @@ public function upgradeApp(string $appId): bool { \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 80e4cefed6459..38b0bd58b98f3 100644 --- a/lib/private/App/Platform.php +++ b/lib/private/App/Platform.php @@ -9,6 +9,8 @@ use OCP\IBinaryFinder; use OCP\IConfig; +use OCP\Server; +use OCP\Util; /** * Class Platform @@ -32,7 +34,7 @@ public function getIntSize(): int { } public function getOcVersion(): string { - $v = \OCP\Util::getVersion(); + $v = Util::getVersion(); return implode('.', $v); } @@ -53,7 +55,7 @@ public function getOS(): string { * @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 be701f3da53d8..e4da80b94d94d 100644 --- a/lib/private/AppConfig.php +++ b/lib/private/AppConfig.php @@ -29,6 +29,7 @@ use OCP\IConfig; use OCP\IDBConnection; use OCP\Security\ICrypto; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -85,7 +86,7 @@ public function __construct( 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 @@ private function applyLexiconStrictness(?Strictness $strictness, string $configA 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 7bf328522094b..f6ca284346c9f 100644 --- a/lib/private/AppFramework/App.php +++ b/lib/private/AppFramework/App.php @@ -21,6 +21,7 @@ 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 @@ public static function buildAppNamespace(string $appId, string $topNamespace = ' 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 @@ public static function main( // 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 @@ public static function main( $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 3798466772711..d90e87ae4493b 100644 --- a/lib/private/AppFramework/Bootstrap/ARegistration.php +++ b/lib/private/AppFramework/Bootstrap/ARegistration.php @@ -12,11 +12,9 @@ * @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 b3da08adb079f..5240f18d3b8fc 100644 --- a/lib/private/AppFramework/Bootstrap/BootContext.php +++ b/lib/private/AppFramework/Bootstrap/BootContext.php @@ -13,11 +13,9 @@ 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 92955fc412372..0ceafcaa20a73 100644 --- a/lib/private/AppFramework/Bootstrap/EventListenerRegistration.php +++ b/lib/private/AppFramework/Bootstrap/EventListenerRegistration.php @@ -8,24 +8,20 @@ */ 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 973fc13aa2c19..6177bf0aa063c 100644 --- a/lib/private/AppFramework/Bootstrap/FunctionInjector.php +++ b/lib/private/AppFramework/Bootstrap/FunctionInjector.php @@ -16,11 +16,9 @@ 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 d2ad6bbf0f686..200b0670fd32a 100644 --- a/lib/private/AppFramework/Bootstrap/MiddlewareRegistration.php +++ b/lib/private/AppFramework/Bootstrap/MiddlewareRegistration.php @@ -16,11 +16,12 @@ * @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 cc9a4875e9a18..7398628e62ff2 100644 --- a/lib/private/AppFramework/Bootstrap/ParameterRegistration.php +++ b/lib/private/AppFramework/Bootstrap/ParameterRegistration.php @@ -12,18 +12,15 @@ * @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 7ecc4aac7f2c7..02e67b742a18b 100644 --- a/lib/private/AppFramework/Bootstrap/PreviewProviderRegistration.php +++ b/lib/private/AppFramework/Bootstrap/PreviewProviderRegistration.php @@ -9,19 +9,19 @@ 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 8bd1ff356105b..6b68b4b755285 100644 --- a/lib/private/AppFramework/Bootstrap/RegistrationContext.php +++ b/lib/private/AppFramework/Bootstrap/RegistrationContext.php @@ -25,18 +25,21 @@ 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 @@ public function registerTaskProcessingProvider(string $appId, string $taskProces } /** - * @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 @@ public function getTaskProcessingProviders(): array { } /** - * @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 @@ public function getConfigLexicon(string $appId): ?ILexicon { 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 aa3e38e4c4631..27a1b74759095 100644 --- a/lib/private/AppFramework/Bootstrap/ServiceAliasRegistration.php +++ b/lib/private/AppFramework/Bootstrap/ServiceAliasRegistration.php @@ -13,38 +13,26 @@ */ class ServiceAliasRegistration extends ARegistration { /** - * @var string - * @psalm-var string|class-string + * @param class-string $alias + * @param class-string $target */ - 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, + private readonly string $alias, + private readonly string $target, + ) { parent::__construct($appId); - $this->alias = $alias; - $this->target = $target; } /** - * @psalm-return string|class-string + * @return class-string */ public function getAlias(): string { return $this->alias; } /** - * @psalm-return string|class-string + * @return class-string */ public function getTarget(): string { return $this->target; diff --git a/lib/private/AppFramework/Bootstrap/ServiceFactoryRegistration.php b/lib/private/AppFramework/Bootstrap/ServiceFactoryRegistration.php index 63e73410b5afb..a3195bb1b32f5 100644 --- a/lib/private/AppFramework/Bootstrap/ServiceFactoryRegistration.php +++ b/lib/private/AppFramework/Bootstrap/ServiceFactoryRegistration.php @@ -12,29 +12,23 @@ * @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, + /** + * @param class-string $name + */ + public function __construct( + string $appId, + 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 6eda5e0196f2b..42825816a7e21 100644 --- a/lib/private/AppFramework/Bootstrap/ServiceRegistration.php +++ b/lib/private/AppFramework/Bootstrap/ServiceRegistration.php @@ -13,18 +13,14 @@ * @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 78951d99364db..28833b7ebf508 100644 --- a/lib/private/AppFramework/DependencyInjection/DIContainer.php +++ b/lib/private/AppFramework/DependencyInjection/DIContainer.php @@ -10,6 +10,8 @@ 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; @@ -31,12 +33,15 @@ 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\SimpleContainer; use OC\Core\Middleware\TwoFactorMiddleware; 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; @@ -48,6 +53,7 @@ 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; @@ -59,19 +65,23 @@ 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 */ @@ -81,7 +91,7 @@ public function __construct(string $appName, array $urlParams = [], ?ServerConta $server = \OC::$server; } $this->server = $server; - $this->server->registerAppContainer($appName, $this); + $this->server->registerAppContainer($this->appName, $this); // aliases /** @deprecated 26.0.0 inject $appName */ @@ -98,7 +108,11 @@ public function __construct(string $appName, array $urlParams = [], ?ServerConta $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 { @@ -106,7 +120,7 @@ public function __construct(string $appName, array $urlParams = [], ?ServerConta }); $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 @@ -198,11 +212,11 @@ public function __construct(string $appName, array $urlParams = [], ?ServerConta $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), @@ -217,7 +231,7 @@ public function __construct(string $appName, array $urlParams = [], ?ServerConta $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'); @@ -236,14 +250,11 @@ public function __construct(string $appName, array $urlParams = [], ?ServerConta 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; } @@ -271,7 +282,7 @@ public function getAppName() { * @return boolean */ public function isLoggedIn() { - return \OC::$server->getUserSession()->isLoggedIn(); + return Server::get(IUserSession::class)->isLoggedIn(); } /** @@ -284,7 +295,7 @@ public function isAdminUser() { } private function getUserId(): string { - return $this->getServer()->getSession()->get('user_id'); + return $this->getServer()->get(Session::class)->getSession()->get('user_id'); } /** @@ -293,7 +304,7 @@ private function getUserId(): string { * @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); }); } @@ -356,7 +367,7 @@ public function queryNoFallback($name, array $chain) { 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 08d6259c2a254..ee5a4397952b0 100644 --- a/lib/private/AppFramework/Http.php +++ b/lib/private/AppFramework/Http.php @@ -10,18 +10,16 @@ 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/Dispatcher.php b/lib/private/AppFramework/Http/Dispatcher.php index 9d786992831a9..e7ccd3ea5d5dd 100644 --- a/lib/private/AppFramework/Http/Dispatcher.php +++ b/lib/private/AppFramework/Http/Dispatcher.php @@ -26,32 +26,6 @@ * Class to dispatch the request to the middleware dispatcher */ class Dispatcher { - /** @var MiddlewareDispatcher */ - private $middlewareDispatcher; - - /** @var Http */ - private $protocol; - - /** @var ControllerMethodReflector */ - private $reflector; - - /** @var IRequest */ - private $request; - - /** @var IConfig */ - private $config; - - /** @var ConnectionAdapter */ - private $connection; - - /** @var LoggerInterface */ - private $logger; - - /** @var IEventLogger */ - private $eventLogger; - - private ContainerInterface $appContainer; - /** * @param Http $protocol the http protocol with contains all status headers * @param MiddlewareDispatcher $middlewareDispatcher the dispatcher which @@ -65,25 +39,16 @@ class Dispatcher { * @param IEventLogger $eventLogger */ public function __construct( - Http $protocol, - MiddlewareDispatcher $middlewareDispatcher, - ControllerMethodReflector $reflector, - IRequest $request, - IConfig $config, - ConnectionAdapter $connection, - LoggerInterface $logger, - IEventLogger $eventLogger, - ContainerInterface $appContainer, + private Http $protocol, + private MiddlewareDispatcher $middlewareDispatcher, + private ControllerMethodReflector $reflector, + private IRequest $request, + private IConfig $config, + private ConnectionAdapter $connection, + private LoggerInterface $logger, + private IEventLogger $eventLogger, + private ContainerInterface $appContainer, ) { - $this->protocol = $protocol; - $this->middlewareDispatcher = $middlewareDispatcher; - $this->reflector = $reflector; - $this->request = $request; - $this->config = $config; - $this->connection = $connection; - $this->logger = $logger; - $this->eventLogger = $eventLogger; - $this->appContainer = $appContainer; } diff --git a/lib/private/AppFramework/Http/Request.php b/lib/private/AppFramework/Http/Request.php index 6978d46f2d6a6..5cf2c9582e605 100644 --- a/lib/private/AppFramework/Http/Request.php +++ b/lib/private/AppFramework/Http/Request.php @@ -14,6 +14,7 @@ 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 @@ public function getServerProtocol(): string { 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 c3a99c9359199..1fa2d35145608 100644 --- a/lib/private/AppFramework/Http/RequestId.php +++ b/lib/private/AppFramework/Http/RequestId.php @@ -11,13 +11,10 @@ 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 8bc56beb62efd..1cdd8c19f05ef 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 08b3009215548..e2514916d7da6 100644 --- a/lib/private/AppFramework/Middleware/NotModifiedMiddleware.php +++ b/lib/private/AppFramework/Middleware/NotModifiedMiddleware.php @@ -14,11 +14,9 @@ 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 dd3ae6f268bb0..d592b24a289af 100644 --- a/lib/private/AppFramework/Middleware/OCSMiddleware.php +++ b/lib/private/AppFramework/Middleware/OCSMiddleware.php @@ -20,17 +20,15 @@ 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 @@ public function afterException($controller, $methodName, \Exception $exception) 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 @@ public function afterException($controller, $methodName, \Exception $exception) * @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/CORSMiddleware.php b/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php index 4453f5a7d4b4f..e2ca24b97168e 100644 --- a/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php @@ -31,26 +31,13 @@ * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS */ class CORSMiddleware extends Middleware { - /** @var IRequest */ - private $request; - /** @var ControllerMethodReflector */ - private $reflector; - /** @var Session */ - private $session; - /** @var IThrottler */ - private $throttler; - public function __construct( - IRequest $request, - ControllerMethodReflector $reflector, - Session $session, - IThrottler $throttler, + private IRequest $request, + private ControllerMethodReflector $reflector, + private Session $session, + private IThrottler $throttler, private readonly LoggerInterface $logger, ) { - $this->request = $request; - $this->reflector = $reflector; - $this->session = $session; - $this->throttler = $throttler; } /** diff --git a/lib/private/AppFramework/Middleware/Security/FeaturePolicyMiddleware.php b/lib/private/AppFramework/Middleware/Security/FeaturePolicyMiddleware.php index 921630e632684..632eceaa71b00 100644 --- a/lib/private/AppFramework/Middleware/Security/FeaturePolicyMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/FeaturePolicyMiddleware.php @@ -16,11 +16,9 @@ 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 e770fa4cbfff9..298921eedaadb 100644 --- a/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php @@ -19,14 +19,10 @@ * 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 e3a293e0fd9d0..f711618410b90 100644 --- a/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php @@ -19,6 +19,7 @@ use OC\AppFramework\Utility\ControllerMethodReflector; use OC\Settings\AuthorizedGroupMapper; use OC\User\Session; +use OCA\Talk\Controller\PageController as TalkPageController; use OCP\App\AppPathNotFoundException; use OCP\App\IAppManager; use OCP\AppFramework\Controller; @@ -108,7 +109,8 @@ public function beforeController($controller, $methodName) { // 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) === TalkPageController::class && $methodName === 'showCall') { $this->navigationManager->setActiveEntry('spreed'); } diff --git a/lib/private/AppFramework/Middleware/SessionMiddleware.php b/lib/private/AppFramework/Middleware/SessionMiddleware.php index b7b0fb118c2d3..5b2ef81089830 100644 --- a/lib/private/AppFramework/Middleware/SessionMiddleware.php +++ b/lib/private/AppFramework/Middleware/SessionMiddleware.php @@ -17,16 +17,10 @@ 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 05ce133db24f2..3f0a73f7f2293 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 @@ public function __construct(DataResponse $dataResponse, $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 ec38105a5a061..bbccda74d0b2f 100644 --- a/lib/private/AppFramework/Routing/RouteActionHandler.php +++ b/lib/private/AppFramework/Routing/RouteActionHandler.php @@ -11,18 +11,11 @@ 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 string $controllerName, + private string $actionName, + ) { } public function __invoke($params) { diff --git a/lib/private/AppFramework/ScopedPsrLogger.php b/lib/private/AppFramework/ScopedPsrLogger.php index 0a8e2b0d303fc..a413710a7d7df 100644 --- a/lib/private/AppFramework/ScopedPsrLogger.php +++ b/lib/private/AppFramework/ScopedPsrLogger.php @@ -12,16 +12,10 @@ 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 da225b612cf41..51c5fbe672dd8 100644 --- a/lib/private/AppFramework/Services/InitialState.php +++ b/lib/private/AppFramework/Services/InitialState.php @@ -12,15 +12,10 @@ 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 134dad100dc28..286d63c695c6f 100644 --- a/lib/private/AppScriptSort.php +++ b/lib/private/AppScriptSort.php @@ -14,11 +14,9 @@ * 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 5ef8d233f1dae..e85a8454698b3 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 @@ public static function getTarType(string $file): int { * 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 @@ public function addFile(string $path, string $source = ''): bool { */ 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 @@ public function getFile(string $path) { * 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 @@ public function extractFile(string $path, string $dest): bool { if ($success) { rename($tmp . $path, $dest); } - \OCP\Files::rmdirr($tmp); + Files::rmdirr($tmp); return $success; } @@ -272,9 +274,9 @@ public function remove(string $path): bool { $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 @@ public function getStream(string $path, string $mode) { } 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 @@ public function getStream(string $path, string $mode) { 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 f7deb3f204055..a4f2c52e1da25 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 @@ public function getStream(string $path, string $mode) { } 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 ba1e93d26aed1..438fcd2615dbc 100644 --- a/lib/private/Authentication/Events/ARemoteWipeEvent.php +++ b/lib/private/Authentication/Events/ARemoteWipeEvent.php @@ -12,12 +12,10 @@ 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 23eeaef87ad07..b946afc2afd46 100644 --- a/lib/private/Authentication/Events/LoginFailed.php +++ b/lib/private/Authentication/Events/LoginFailed.php @@ -11,14 +11,11 @@ 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 0358887bb861f..7e46d2e7b246b 100644 --- a/lib/private/Authentication/Listeners/LoginFailedListener.php +++ b/lib/private/Authentication/Listeners/LoginFailedListener.php @@ -18,18 +18,13 @@ 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 457630eff27dd..b071886fd7402 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php @@ -9,6 +9,7 @@ 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 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 96878c4412339..cf18ae2afccbb 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php @@ -9,6 +9,7 @@ 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,18 @@ use function substr; /** - * @template-implements IEventListener<\OC\Authentication\Events\ARemoteWipeEvent> + * @template-implements IEventListener */ class RemoteWipeEmailListener implements IEventListener { - /** @var IMailer */ - private $mailer; + private IL10N $l10n; - /** @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 5781c1edf1600..5e5b0fcaa50bf 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php @@ -8,6 +8,7 @@ */ 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\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 5f21c6407807f..d7a9bf4fb29c0 100644 --- a/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php +++ b/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php @@ -14,14 +14,12 @@ 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 3631c04432c89..6365e973ec6b7 100644 --- a/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php +++ b/lib/private/Authentication/Listeners/UserDeletedTokenCleanupListener.php @@ -16,19 +16,13 @@ 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 67f8ff7cfcd8b..d025a2150a35d 100644 --- a/lib/private/Authentication/Listeners/UserDeletedWebAuthnCleanupListener.php +++ b/lib/private/Authentication/Listeners/UserDeletedWebAuthnCleanupListener.php @@ -16,11 +16,9 @@ /** @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 a8d4baeafa1da..a4fc2d5061168 100644 --- a/lib/private/Authentication/Listeners/UserLoggedInListener.php +++ b/lib/private/Authentication/Listeners/UserLoggedInListener.php @@ -14,14 +14,12 @@ 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/ALoginCommand.php b/lib/private/Authentication/Login/ALoginCommand.php index a9f51f0da9e57..c60fef2019cf6 100644 --- a/lib/private/Authentication/Login/ALoginCommand.php +++ b/lib/private/Authentication/Login/ALoginCommand.php @@ -21,7 +21,7 @@ protected function processNextOrFinishSuccessfully(LoginData $loginData): LoginR if ($this->next !== null) { return $this->next->process($loginData); } else { - return LoginResult::success($loginData); + return LoginResult::success(); } } diff --git a/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php b/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php index 40369c383ac61..cd40348b0563b 100644 --- a/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php +++ b/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php @@ -11,11 +11,9 @@ 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 ec6fdf75f40d5..974775a2a3dcb 100644 --- a/lib/private/Authentication/Login/CompleteLoginCommand.php +++ b/lib/private/Authentication/Login/CompleteLoginCommand.php @@ -11,11 +11,9 @@ 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 21f0433d948c4..806af13eae400 100644 --- a/lib/private/Authentication/Login/CreateSessionTokenCommand.php +++ b/lib/private/Authentication/Login/CreateSessionTokenCommand.php @@ -13,16 +13,10 @@ 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 3eb1f8f1a65a0..e455a67f31d7d 100644 --- a/lib/private/Authentication/Login/FinishRememberedLoginCommand.php +++ b/lib/private/Authentication/Login/FinishRememberedLoginCommand.php @@ -12,14 +12,10 @@ 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 b6b59ced6ce2e..58a076919438a 100644 --- a/lib/private/Authentication/Login/LoggedInCheckCommand.php +++ b/lib/private/Authentication/Login/LoggedInCheckCommand.php @@ -14,15 +14,10 @@ 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 { @@ -35,7 +30,7 @@ public function process(LoginData $loginData): LoginResult { $this->dispatcher->dispatchTyped(new LoginFailed($loginName, $password)); - return LoginResult::failure($loginData, LoginController::LOGIN_MSG_INVALIDPASSWORD); + return LoginResult::failure(LoginController::LOGIN_MSG_INVALIDPASSWORD); } return $this->processNextOrFinishSuccessfully($loginData); diff --git a/lib/private/Authentication/Login/LoginResult.php b/lib/private/Authentication/Login/LoginResult.php index 95e87b520e330..8a4b61db59e32 100644 --- a/lib/private/Authentication/Login/LoginResult.php +++ b/lib/private/Authentication/Login/LoginResult.php @@ -11,33 +11,24 @@ use OC\Core\Controller\LoginController; class LoginResult { - /** @var bool */ - private $success; + private ?string $redirectUrl = null; + private ?string $errorMessage = null; - /** @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 readonly bool $success, + ) { } - private function setRedirectUrl(string $url) { + private function setRedirectUrl(string $url): void { $this->redirectUrl = $url; } - private function setErrorMessage(string $msg) { + private function setErrorMessage(string $msg): void { $this->errorMessage = $msg; } - public static function success(LoginData $data, ?string $redirectUrl = null) { - $result = new static(true, $data); + public static function success(?string $redirectUrl = null): self { + $result = new static(true); if ($redirectUrl !== null) { $result->setRedirectUrl($redirectUrl); } @@ -47,8 +38,8 @@ public static function success(LoginData $data, ?string $redirectUrl = null) { /** * @param LoginController::LOGIN_MSG_*|null $msg */ - public static function failure(LoginData $data, ?string $msg = null): LoginResult { - $result = new static(false, $data); + public static function failure(?string $msg = null): self { + $result = new static(false); if ($msg !== null) { $result->setErrorMessage($msg); } diff --git a/lib/private/Authentication/Login/PreLoginHookCommand.php b/lib/private/Authentication/Login/PreLoginHookCommand.php index d5aa174094d8f..5fd8a9dbaef0a 100644 --- a/lib/private/Authentication/Login/PreLoginHookCommand.php +++ b/lib/private/Authentication/Login/PreLoginHookCommand.php @@ -12,11 +12,9 @@ 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 ea80fbfc7143f..635be70333667 100644 --- a/lib/private/Authentication/Login/SetUserTimezoneCommand.php +++ b/lib/private/Authentication/Login/SetUserTimezoneCommand.php @@ -14,16 +14,10 @@ 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 fc5285221a2b1..af425744122b4 100644 --- a/lib/private/Authentication/Login/TwoFactorCommand.php +++ b/lib/private/Authentication/Login/TwoFactorCommand.php @@ -16,21 +16,11 @@ 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 { @@ -68,7 +58,6 @@ public function process(LoginData $loginData): LoginResult { } return LoginResult::success( - $loginData, $this->urlGenerator->linkToRoute($url, $urlParams) ); } diff --git a/lib/private/Authentication/Login/UidLoginCommand.php b/lib/private/Authentication/Login/UidLoginCommand.php index 511b5f61e0eac..c722a5057cc1c 100644 --- a/lib/private/Authentication/Login/UidLoginCommand.php +++ b/lib/private/Authentication/Login/UidLoginCommand.php @@ -12,11 +12,9 @@ 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 0582239e9de33..a13dd1d6f17c7 100644 --- a/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php +++ b/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php @@ -11,11 +11,9 @@ 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 8777aa6dcea1c..b8977b583047e 100644 --- a/lib/private/Authentication/Login/UserDisabledCheckCommand.php +++ b/lib/private/Authentication/Login/UserDisabledCheckCommand.php @@ -13,16 +13,10 @@ 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 { @@ -33,7 +27,7 @@ public function process(LoginData $loginData): LoginResult { $this->logger->warning("Login failed: $username disabled (Remote IP: $ip)"); - return LoginResult::failure($loginData, LoginController::LOGIN_MSG_USERDISABLED); + return LoginResult::failure(LoginController::LOGIN_MSG_USERDISABLED); } return $this->processNextOrFinishSuccessfully($loginData); diff --git a/lib/private/Authentication/Login/WebAuthnChain.php b/lib/private/Authentication/Login/WebAuthnChain.php index ae523c43da67b..6732a4339fa8c 100644 --- a/lib/private/Authentication/Login/WebAuthnChain.php +++ b/lib/private/Authentication/Login/WebAuthnChain.php @@ -9,57 +9,18 @@ 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 8f14e5b3f6def..3c9dcacbc8fb8 100644 --- a/lib/private/Authentication/Login/WebAuthnLoginCommand.php +++ b/lib/private/Authentication/Login/WebAuthnLoginCommand.php @@ -11,11 +11,9 @@ 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 3414034b33c53..e230f58e9182e 100644 --- a/lib/private/Authentication/LoginCredentials/Credentials.php +++ b/lib/private/Authentication/LoginCredentials/Credentials.php @@ -7,46 +7,28 @@ namespace OC\Authentication\LoginCredentials; use OCP\Authentication\LoginCredentials\ICredentials; +use Override; 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 readonly string $uid, + private readonly string $loginName, + private readonly ?string $password, + ) { } - /** - * @return string - */ - public function getUID() { + #[Override] + public function getUID(): string { return $this->uid; } - /** - * @return string - */ - public function getLoginName() { + #[Override] + public function getLoginName(): string { return $this->loginName; } - /** - * @return string - */ - public function getPassword() { + #[Override] + public function getPassword(): ?string { return $this->password; } } diff --git a/lib/private/Authentication/LoginCredentials/Store.php b/lib/private/Authentication/LoginCredentials/Store.php index 67c5712715c61..45812ba43507e 100644 --- a/lib/private/Authentication/LoginCredentials/Store.php +++ b/lib/private/Authentication/LoginCredentials/Store.php @@ -22,25 +22,12 @@ 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 a81e385d8b179..7742eb95a2bf5 100644 --- a/lib/private/Authentication/Notifications/Notifier.php +++ b/lib/private/Authentication/Notifications/Notifier.php @@ -14,11 +14,9 @@ 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 b55970a497908..f3eb78876b06c 100644 --- a/lib/private/Authentication/Token/Manager.php +++ b/lib/private/Authentication/Token/Manager.php @@ -17,11 +17,9 @@ 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 87063f5ccd1c5..059697dacd46e 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 @@ public function setPassword(OCPIToken $token, string $tokenId, string $password) 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); @@ -524,7 +494,7 @@ public function updatePasswords(string $uid, string $password) { 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 80ba330b66d80..2a023f43b6826 100644 --- a/lib/private/Authentication/Token/RemoteWipe.php +++ b/lib/private/Authentication/Token/RemoteWipe.php @@ -18,21 +18,11 @@ 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 e6d1e69e9b41f..ee6abebc85090 100644 --- a/lib/private/Authentication/Token/TokenCleanupJob.php +++ b/lib/private/Authentication/Token/TokenCleanupJob.php @@ -10,11 +10,11 @@ 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 cc468dbeba024..613185a2aec79 100644 --- a/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php +++ b/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php @@ -18,11 +18,9 @@ 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 e02064bc8f7a5..05014e09128d3 100644 --- a/lib/private/Authentication/TwoFactorAuth/EnforcementState.php +++ b/lib/private/Authentication/TwoFactorAuth/EnforcementState.php @@ -11,15 +11,6 @@ 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 07aa98610ed37..fe6aae0f99f31 100644 --- a/lib/private/Authentication/TwoFactorAuth/Manager.php +++ b/lib/private/Authentication/TwoFactorAuth/Manager.php @@ -11,6 +11,7 @@ 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\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 @@ public function verifyChallenge(string $providerId, IUser $user, string $challen 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 37c9d3fc550cc..bf4c187f1e939 100644 --- a/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php +++ b/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php @@ -13,15 +13,10 @@ 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 7e674a01dd860..9552cee6b0d1b 100644 --- a/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php +++ b/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php @@ -14,6 +14,7 @@ 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'; @@ -42,7 +43,7 @@ public function getProviders(IUser $user): array { 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 @@ -56,7 +57,7 @@ public function getProviders(IUser $user): array { 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 5ce4c5981546f..f82f666ac9db9 100644 --- a/lib/private/Authentication/TwoFactorAuth/ProviderManager.php +++ b/lib/private/Authentication/TwoFactorAuth/ProviderManager.php @@ -16,15 +16,10 @@ 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 15b82be6decad..d417721268c17 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 544f60c4f97ec..6534daa41cac9 100644 --- a/lib/private/Authentication/TwoFactorAuth/Registry.php +++ b/lib/private/Authentication/TwoFactorAuth/Registry.php @@ -20,16 +20,10 @@ 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 203f2ef902011..e6503d1c38ab8 100644 --- a/lib/private/Authentication/WebAuthn/CredentialRepository.php +++ b/lib/private/Authentication/WebAuthn/CredentialRepository.php @@ -16,11 +16,9 @@ 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 96dc0719b54f8..c322c844c9c03 100644 --- a/lib/private/Authentication/WebAuthn/Manager.php +++ b/lib/private/Authentication/WebAuthn/Manager.php @@ -37,28 +37,12 @@ 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 dc65c9d5743ed..987298e04832f 100644 --- a/lib/private/Avatar/Avatar.php +++ b/lib/private/Avatar/Avatar.php @@ -15,6 +15,7 @@ use OCP\Files\NotFoundException; use OCP\IAvatar; use OCP\IConfig; +use OCP\Image; use Psr\Log\LoggerInterface; /** @@ -70,7 +71,7 @@ public function get(int $size = 64, bool $darkTheme = false) { return false; } - $avatar = new \OCP\Image(); + $avatar = new Image(); $avatar->loadFromData($file->getContent()); return $avatar; } @@ -137,7 +138,7 @@ protected function generateAvatarFromSvg(string $userDisplayName, int $size, boo $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 aa515e1ad4b67..6d2e2df19fc44 100644 --- a/lib/private/Avatar/GuestAvatar.php +++ b/lib/private/Avatar/GuestAvatar.php @@ -12,6 +12,7 @@ use OCP\Files\SimpleFS\InMemoryFile; use OCP\Files\SimpleFS\ISimpleFile; use OCP\IConfig; +use OCP\IImage; use Psr\Log\LoggerInterface; /** @@ -49,7 +50,7 @@ public function getDisplayName(): string { /** * 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 f5f49fb7cb24b..8edf4d39a68b9 100644 --- a/lib/private/Avatar/PlaceholderAvatar.php +++ b/lib/private/Avatar/PlaceholderAvatar.php @@ -16,6 +16,7 @@ use OCP\Files\SimpleFS\ISimpleFolder; use OCP\IConfig; use OCP\IImage; +use OCP\PreConditionNotMetException; use Psr\Log\LoggerInterface; /** @@ -70,8 +71,8 @@ public function remove(bool $silent = false): void { * 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 @@ public function getDisplayName(): string { * @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 aca2aa574bc4a..86fd1cf1220a3 100644 --- a/lib/private/Avatar/UserAvatar.php +++ b/lib/private/Avatar/UserAvatar.php @@ -17,6 +17,8 @@ use OCP\IConfig; use OCP\IImage; use OCP\IL10N; +use OCP\Image; +use OCP\PreConditionNotMetException; use Psr\Log\LoggerInterface; /** @@ -80,7 +82,7 @@ private function getAvatarImage($data): IImage { 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 @@ private function validateAvatar(IImage $avatar): void { /** * 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 @@ private function getExtension(bool $generated, bool $darkTheme): string { * 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 @@ public function getFile(int $size, bool $darkTheme = false): ISimpleFile { $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 @@ public function getDisplayName(): string { * @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 846c75626384f..0fd935ace2e18 100644 --- a/lib/private/BackgroundJob/JobList.php +++ b/lib/private/BackgroundJob/JobList.php @@ -12,10 +12,12 @@ 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\IGenerator; use Override; use Psr\Container\ContainerExceptionInterface; @@ -217,7 +219,7 @@ public function getNext(bool $onlyTimeSensitive = false, ?array $jobClasses = nu 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 @@ private function buildJob(array $row): ?IJob { 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 @@ public function setLastRun(IJob $job): void { ->set('last_run', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT)) ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT))); - 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 74e72d1564a96..221d05f5c2772 100644 --- a/lib/private/BinaryFinder.php +++ b/lib/private/BinaryFinder.php @@ -12,6 +12,7 @@ use OCP\ICache; use OCP\ICacheFactory; use OCP\IConfig; +use OCP\Util; use Symfony\Component\Process\ExecutableFinder; /** @@ -47,7 +48,7 @@ public function findBinaryPath(string $program) { 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 d6c2cf4990444..c0227a75c6ab6 100644 --- a/lib/private/Broadcast/Events/BroadcastEvent.php +++ b/lib/private/Broadcast/Events/BroadcastEvent.php @@ -14,13 +14,10 @@ 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 ceddf472ebdc4..708f9b7389010 100644 --- a/lib/private/Cache/File.php +++ b/lib/private/Cache/File.php @@ -9,8 +9,12 @@ 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 @@ protected function getStorage() { 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 @@ public function size($key) { * @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 @@ public function set($key, $value, $ttl = 0) { /** * @param string $key * @return bool - * @throws \OC\ForbiddenException + * @throws ForbiddenException */ public function hasKey($key) { $storage = $this->getStorage(); @@ -120,7 +124,7 @@ public function hasKey($key) { /** * @param string $key * @return bool|mixed - * @throws \OC\ForbiddenException + * @throws ForbiddenException */ public function remove($key) { $storage = $this->getStorage(); @@ -133,7 +137,7 @@ public function remove($key) { /** * @param string $prefix * @return bool - * @throws \OC\ForbiddenException + * @throws ForbiddenException */ public function clear($prefix = '') { $storage = $this->getStorage(); @@ -152,7 +156,7 @@ public function clear($prefix = '') { /** * Runs GC - * @throws \OC\ForbiddenException + * @throws ForbiddenException */ public function gc() { $storage = $this->getStorage(); @@ -171,12 +175,12 @@ public function gc() { 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 db04e6a648a74..221b77d4704aa 100644 --- a/lib/private/Calendar/Resource/Manager.php +++ b/lib/private/Calendar/Resource/Manager.php @@ -10,6 +10,7 @@ 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 @@ private function fetchBootstrapBackends(): void { /** * @return IBackend[] - * @throws \OCP\AppFramework\QueryException + * @throws QueryException * @since 14.0.0 */ public function getBackends():array { @@ -88,7 +89,7 @@ public function getBackends():array { /** * @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 65897010f2a6a..8097fecb2acc2 100644 --- a/lib/private/Calendar/Room/Manager.php +++ b/lib/private/Calendar/Room/Manager.php @@ -10,6 +10,7 @@ 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 @@ private function fetchBootstrapBackends(): void { /** * @return IBackend[] - * @throws \OCP\AppFramework\QueryException + * @throws QueryException * @since 14.0.0 */ public function getBackends():array { @@ -95,7 +96,7 @@ public function getBackends():array { /** * @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 07076d9aacd80..494504af3d80a 100644 --- a/lib/private/CapabilitiesManager.php +++ b/lib/private/CapabilitiesManager.php @@ -12,6 +12,7 @@ use OCP\Capabilities\ICapability; use OCP\Capabilities\IInitialStateExcludedCapability; use OCP\Capabilities\IPublicCapability; +use OCP\ILogger; use Psr\Log\LoggerInterface; class CapabilitiesManager { @@ -22,13 +23,11 @@ class CapabilitiesManager { public const ACCEPTABLE_LOADING_TIME = 0.1; /** @var \Closure[] */ - private $capabilities = []; + private array $capabilities = []; - /** @var LoggerInterface */ - private $logger; - - public function __construct(LoggerInterface $logger) { - $this->logger = $logger; + public function __construct( + private LoggerInterface $logger, + ) { } /** @@ -63,11 +62,11 @@ public function getCapabilities(bool $public = false, bool $initialState = false $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 ea39f885fc66e..4fbfb787996ed 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 @@ public function __construct( * @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 a8219bc633b14..9bee7ea8dc8d6 100644 --- a/lib/private/Collaboration/Resources/Collection.php +++ b/lib/private/Collaboration/Resources/Collection.php @@ -78,7 +78,7 @@ public function getResources(): array { * @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 dfdde24d78e46..1ee792a0b55cf 100644 --- a/lib/private/Collaboration/Resources/Listener.php +++ b/lib/private/Collaboration/Resources/Listener.php @@ -13,37 +13,38 @@ 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 d97c519e5522a..8e5cfb56c8330 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 5ea2b35bf732d..ac73987e59cf9 100644 --- a/lib/private/Command/CommandJob.php +++ b/lib/private/Command/CommandJob.php @@ -7,8 +7,12 @@ */ namespace OC\Command; +use OCA\Files_Trashbin\Command\Expire; use OCP\BackgroundJob\QueuedJob; use OCP\Command\ICommand; +use Test\Command\FilesystemCommand; +use Test\Command\SimpleCommand; +use Test\Command\StateFullCommand; /** * Wrap a command in the background job interface @@ -16,10 +20,10 @@ class CommandJob extends QueuedJob { protected function run($argument) { $command = unserialize($argument, ['allowed_classes' => [ - \Test\Command\SimpleCommand::class, - \Test\Command\StateFullCommand::class, - \Test\Command\FilesystemCommand::class, - \OCA\Files_Trashbin\Command\Expire::class, + SimpleCommand::class, + StateFullCommand::class, + FilesystemCommand::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 2712ef731a4d1..6a355c8ca6be1 100644 --- a/lib/private/Command/QueueBus.php +++ b/lib/private/Command/QueueBus.php @@ -9,8 +9,12 @@ */ namespace OC\Command; +use OCA\Files_Trashbin\Command\Expire; use OCP\Command\IBus; use OCP\Command\ICommand; +use Test\Command\FilesystemCommand; +use Test\Command\SimpleCommand; +use Test\Command\StateFullCommand; class QueueBus implements IBus { /** @@ -38,10 +42,10 @@ private function runCommand(ICommand $command): void { throw new \InvalidArgumentException('Trying to push a command which serialized form can not be stored in the database (>4000 character)'); } $unserialized = unserialize($serialized, ['allowed_classes' => [ - \Test\Command\SimpleCommand::class, - \Test\Command\StateFullCommand::class, - \Test\Command\FilesystemCommand::class, - \OCA\Files_Trashbin\Command\Expire::class, + SimpleCommand::class, + StateFullCommand::class, + FilesystemCommand::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 84737897bb4a2..52be2dea3a8f9 100644 --- a/lib/private/Comments/Manager.php +++ b/lib/private/Comments/Manager.php @@ -1325,7 +1325,7 @@ public function deleteCommentsAtObject($objectType, $objectId): bool { /** * 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 @@ public function resolveDisplayName($type, $id) { /** * 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 2436ca74c661b..ec30fb00d3f9e 100644 --- a/lib/private/Comments/ManagerFactory.php +++ b/lib/private/Comments/ManagerFactory.php @@ -12,20 +12,17 @@ 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 a9eb58a186646..9159adccbac3d 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 @@ -16,27 +17,20 @@ class Config { public const ENV_PREFIX = 'NC_'; - /** @var array Associative array ($key => $value) */ - protected $cache = []; - /** @var array */ - protected $envCache = []; - /** @var string */ - protected $configDir; - /** @var string */ - protected $configFilePath; - /** @var string */ - protected $configFileName; - /** @var bool */ - protected $isReadOnly; + protected array $cache = []; + protected array $envCache = []; + protected string $configFilePath; + protected bool $isReadOnly; /** * @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 + * @param string $configFileName (Optional) Name of the config file. Defaults to config.php */ - public function __construct($configDir, $fileName = 'config.php') { - $this->configDir = $configDir; - $this->configFilePath = $this->configDir . $fileName; - $this->configFileName = $fileName; + public function __construct( + protected string $configDir, + protected string $configFileName = 'config.php', + ) { + $this->configFilePath = $this->configDir . $this->configFileName; $this->readData(); $this->isReadOnly = $this->getValue('config_is_read_only', false); } @@ -48,7 +42,7 @@ public function __construct($configDir, $fileName = 'config.php') { * * @return array an array of key names */ - public function getKeys() { + public function getKeys(): array { return array_merge(array_keys($this->cache), array_keys($this->envCache)); } @@ -237,7 +231,7 @@ private function readData() { // 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 4cf1e0da8ca13..2e4783a11cf1e 100644 --- a/lib/private/Console/Application.php +++ b/lib/private/Console/Application.php @@ -20,6 +20,7 @@ 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 @@ public function loadCommands( 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 e8d9eef6b16c9..2df34a84c874a 100644 --- a/lib/private/Console/TimestampFormatter.php +++ b/lib/private/Console/TimestampFormatter.php @@ -12,19 +12,10 @@ use Symfony\Component\Console\Formatter\OutputFormatterStyleInterface; class TimestampFormatter implements OutputFormatterInterface { - /** @var ?IConfig */ - protected $config; - - /** @var OutputFormatterInterface */ - protected $formatter; - - /** - * @param ?IConfig $config - * @param OutputFormatterInterface $formatter - */ - public function __construct(?IConfig $config, OutputFormatterInterface $formatter) { - $this->config = $config; - $this->formatter = $formatter; + public function __construct( + protected readonly ?IConfig $config, + protected readonly OutputFormatterInterface $formatter, + ) { } /** @@ -32,7 +23,7 @@ public function __construct(?IConfig $config, OutputFormatterInterface $formatte * * @param bool $decorated Whether to decorate the messages or not */ - public function setDecorated(bool $decorated) { + public function setDecorated(bool $decorated): void { $this->formatter->setDecorated($decorated); } @@ -51,7 +42,7 @@ public function isDecorated(): bool { * @param string $name The style name * @param OutputFormatterStyleInterface $style The style instance */ - public function setStyle(string $name, OutputFormatterStyleInterface $style) { + public function setStyle(string $name, OutputFormatterStyleInterface $style): void { $this->formatter->setStyle($name, $style); } diff --git a/lib/private/DB/Adapter.php b/lib/private/DB/Adapter.php index 8f1b8e6d75f48..6ebcfdc34f242 100644 --- a/lib/private/DB/Adapter.php +++ b/lib/private/DB/Adapter.php @@ -16,13 +16,9 @@ * handled by the database abstraction layer. */ class Adapter { - /** - * @var \OC\DB\Connection $conn - */ - protected $conn; - - public function __construct($conn) { - $this->conn = $conn; + public function __construct( + protected readonly Connection $conn, + ) { } /** diff --git a/lib/private/DB/Connection.php b/lib/private/DB/Connection.php index f86cbc341a4d9..081ef017aa301 100644 --- a/lib/private/DB/Connection.php +++ b/lib/private/DB/Connection.php @@ -36,7 +36,9 @@ 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; @@ -50,35 +52,21 @@ use function in_array; class Connection extends PrimaryReadReplicaConnection { - /** @var string */ - protected $tablePrefix; - - /** @var \OC\DB\Adapter $adapter */ - protected $adapter; - - /** @var SystemConfig */ - private $systemConfig; - + protected string $tablePrefix; + protected Adapter $adapter; + private SystemConfig $systemConfig; private ClockInterface $clock; - private LoggerInterface $logger; - protected $lockedTable = null; - - /** @var int */ - protected $queriesBuilt = 0; - - /** @var int */ - protected $queriesExecuted = 0; - - /** @var DbDataCollector|null */ - protected $dbDataCollector = null; + protected int $queriesBuilt = 0; + protected int $queriesExecuted = 0; + protected ?DbDataCollector $dbDataCollector = null; private array $lastConnectionCheck = []; protected ?float $transactionActiveSince = null; /** @var array */ - protected $tableDirtyWrites = []; + protected array $tableDirtyWrites = []; protected bool $logDbException = false; private ?array $transactionBacktrace = null; @@ -143,7 +131,7 @@ public function __construct( $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 +139,7 @@ public function __construct( $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); @@ -326,10 +314,7 @@ protected function getCallerBacktrace() { return ''; } - /** - * @return string - */ - public function getPrefix() { + public function getPrefix(): string { return $this->tablePrefix; } @@ -820,10 +805,10 @@ public function migrateToSchema(Schema $toSchema, bool $dryRun = false) { 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 d9ccb3c54f219..60b549dabcf2d 100644 --- a/lib/private/DB/ConnectionAdapter.php +++ b/lib/private/DB/ConnectionAdapter.php @@ -23,11 +23,9 @@ * 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 e3c7cd3585512..828674586e043 100644 --- a/lib/private/DB/DbDataCollector.php +++ b/lib/private/DB/DbDataCollector.php @@ -12,16 +12,14 @@ 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 2ce6ddf80a645..a34ebfe651d41 100644 --- a/lib/private/DB/Exceptions/DbalException.php +++ b/lib/private/DB/Exceptions/DbalException.php @@ -33,23 +33,17 @@ * @psalm-immutable */ 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( + private \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 5b50f8ed3a464..d7e0d9528f094 100644 --- a/lib/private/DB/MigrationException.php +++ b/lib/private/DB/MigrationException.php @@ -8,17 +8,17 @@ namespace OC\DB; class MigrationException extends \Exception { - private $table; - - public function __construct($table, $message) { - $this->table = $table; + public function __construct( + private string $table, + $message, + ) { parent::__construct($message); } /** * @return string */ - public function getTable() { + public function getTable(): string { return $this->table; } } diff --git a/lib/private/DB/MigrationService.php b/lib/private/DB/MigrationService.php index 985c331570f38..7520462aef888 100644 --- a/lib/private/DB/MigrationService.php +++ b/lib/private/DB/MigrationService.php @@ -20,6 +20,7 @@ use OCP\AppFramework\QueryException; use OCP\DB\ISchemaWrapper; use OCP\DB\Types; +use OCP\IConfig; use OCP\IDBConnection; use OCP\Migration\IMigrationStep; use OCP\Migration\IOutput; @@ -33,40 +34,36 @@ class MigrationService { private string $migrationsNamespace; private IOutput $output; private LoggerInterface $logger; - private Connection $connection; - private string $appName; private bool $checkOracle; /** * @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->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'; @@ -103,7 +100,7 @@ private function createMigrationTable(): bool { return false; } - if ($this->connection->tableExists('migrations') && \OC::$server->getConfig()->getAppValue('core', 'vendor', '') !== 'owncloud') { + if ($this->connection->tableExists('migrations') && Server::get(IConfig::class)->getAppValue('core', 'vendor', '') !== 'owncloud') { $this->migrationTableCreated = true; return false; } @@ -474,7 +471,7 @@ public function describeMigrationStep($to = 'latest') { public function createInstance($version) { $class = $this->getClass($version); try { - $s = \OCP\Server::get($class); + $s = Server::get($class); if (!$s instanceof IMigrationStep) { throw new \InvalidArgumentException('Not a valid migration'); @@ -637,7 +634,7 @@ public function ensureOracleConstraints(Schema $sourceSchema, Schema $targetSche } } elseif (!$primaryKey instanceof Index && !$sourceTable instanceof Table) { /** @var LoggerInterface $logger */ - $logger = \OC::$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 40f8ad9676ac3..0d2f73a9a1df7 100644 --- a/lib/private/DB/Migrator.php +++ b/lib/private/DB/Migrator.php @@ -20,37 +20,24 @@ use function preg_match; class Migrator { - /** @var Connection */ - protected $connection; + private bool $noEmit = false; - /** @var IConfig */ - protected $config; - - private ?IEventDispatcher $dispatcher; - - /** @var bool */ - private $noEmit = false; - - public function __construct(Connection $connection, - IConfig $config, - ?IEventDispatcher $dispatcher = null) { - $this->connection = $connection; - $this->config = $config; - $this->dispatcher = $dispatcher; + public function __construct( + protected Connection $connection, + protected IConfig $config, + private ?IEventDispatcher $dispatcher = null, + ) { } /** * @throws Exception */ - public function migrate(Schema $targetSchema) { + public function migrate(Schema $targetSchema): void { $this->noEmit = true; $this->applySchema($targetSchema); } - /** - * @return string - */ - public function generateChangeScript(Schema $targetSchema) { + public function generateChangeScript(Schema $targetSchema): string { $schemaDiff = $this->getDiff($targetSchema, $this->connection); $script = ''; @@ -65,7 +52,7 @@ public function generateChangeScript(Schema $targetSchema) { /** * @throws Exception */ - public function createSchema() { + public function createSchema(): Schema { $this->connection->getConfiguration()->setSchemaAssetsFilter(function ($asset) { /** @var string|AbstractAsset $asset */ $filterExpression = $this->getFilterExpression(); @@ -77,10 +64,7 @@ public function createSchema() { return $this->connection->createSchemaManager()->introspectSchema(); } - /** - * @return SchemaDiff - */ - protected function getDiff(Schema $targetSchema, Connection $connection) { + protected function getDiff(Schema $targetSchema, Connection $connection): SchemaDiff { // Adjust STRING columns with a length higher than 4000 to TEXT (clob) // for consistency between the supported databases and // old vs. new installations. diff --git a/lib/private/DB/MigratorExecuteSqlEvent.php b/lib/private/DB/MigratorExecuteSqlEvent.php index 340cd63630093..8a5c43cf5e580 100644 --- a/lib/private/DB/MigratorExecuteSqlEvent.php +++ b/lib/private/DB/MigratorExecuteSqlEvent.php @@ -11,18 +11,11 @@ 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 1b013734c9547..04159f818cfc7 100644 --- a/lib/private/DB/ObjectParameter.php +++ b/lib/private/DB/ObjectParameter.php @@ -11,25 +11,18 @@ 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 $object, + private ?\Throwable $error, + ) { + $this->stringable = \is_callable([$this->object, '__toString']); + $this->class = \get_class($this->object); } - /** - * @return object - */ - public function getObject() { + public function getObject(): object { return $this->object; } diff --git a/lib/private/DB/PgSqlTools.php b/lib/private/DB/PgSqlTools.php index d529cb26b09d5..cc8812e202bec 100644 --- a/lib/private/DB/PgSqlTools.php +++ b/lib/private/DB/PgSqlTools.php @@ -16,23 +16,16 @@ * Various PostgreSQL specific helper functions. */ class PgSqlTools { - /** @var \OCP\IConfig */ - private $config; - - /** - * @param \OCP\IConfig $config - */ - public function __construct(IConfig $config) { - $this->config = $config; + public function __construct( + private IConfig $config, + ) { } /** * @brief Resynchronizes all sequences of a database after using INSERTs * without leaving out the auto-incremented column. - * @param \OC\DB\Connection $conn - * @return null */ - public function resynchronizeDatabaseSequences(Connection $conn) { + public function resynchronizeDatabaseSequences(Connection $conn): void { $databaseName = $conn->getDatabase(); $conn->getConfiguration()->setSchemaAssetsFilter(function ($asset) { /** @var string|AbstractAsset $asset */ diff --git a/lib/private/DB/QueryBuilder/CompositeExpression.php b/lib/private/DB/QueryBuilder/CompositeExpression.php index 122998036ae0c..c0da96fb3af0b 100644 --- a/lib/private/DB/QueryBuilder/CompositeExpression.php +++ b/lib/private/DB/QueryBuilder/CompositeExpression.php @@ -9,6 +9,7 @@ namespace OC\DB\QueryBuilder; use OCP\DB\QueryBuilder\ICompositeExpression; +use Override; class CompositeExpression implements ICompositeExpression, \Countable { public const TYPE_AND = 'AND'; @@ -20,13 +21,7 @@ public function __construct( ) { } - /** - * Adds multiple parts to composite expression. - * - * @param array $parts - * - * @return \OCP\DB\QueryBuilder\ICompositeExpression - */ + #[Override] public function addMultiple(array $parts = []): ICompositeExpression { foreach ($parts as $part) { $this->add($part); @@ -35,13 +30,7 @@ public function addMultiple(array $parts = []): ICompositeExpression { return $this; } - /** - * Adds an expression to composite expression. - * - * @param mixed $part - * - * @return \OCP\DB\QueryBuilder\ICompositeExpression - */ + #[Override] public function add($part): ICompositeExpression { if ($part === null) { return $this; diff --git a/lib/private/DB/QueryBuilder/ExpressionBuilder/ExpressionBuilder.php b/lib/private/DB/QueryBuilder/ExpressionBuilder/ExpressionBuilder.php index b922c8616305f..8436fd365a09a 100644 --- a/lib/private/DB/QueryBuilder/ExpressionBuilder/ExpressionBuilder.php +++ b/lib/private/DB/QueryBuilder/ExpressionBuilder/ExpressionBuilder.php @@ -10,40 +10,30 @@ use Doctrine\DBAL\Query\Expression\ExpressionBuilder as DoctrineExpressionBuilder; use OC\DB\ConnectionAdapter; use OC\DB\QueryBuilder\CompositeExpression; -use OC\DB\QueryBuilder\FunctionBuilder\FunctionBuilder; use OC\DB\QueryBuilder\Literal; use OC\DB\QueryBuilder\QueryFunction; use OC\DB\QueryBuilder\QuoteHelper; 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; use OCP\DB\QueryBuilder\IQueryFunction; -use OCP\IDBConnection; use Psr\Log\LoggerInterface; class ExpressionBuilder implements IExpressionBuilder { - /** @var \Doctrine\DBAL\Query\Expression\ExpressionBuilder */ - protected $expressionBuilder; + protected DoctrineExpressionBuilder $expressionBuilder; + protected QuoteHelper $helper; + protected IFunctionBuilder $functionBuilder; - /** @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 +49,7 @@ public function __construct(ConnectionAdapter $connection, IQueryBuilder $queryB * @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 +70,7 @@ public function andX(...$x): ICompositeExpression { * @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 48dc1da6330b8..0fd1d15872f0b 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; @@ -15,19 +14,11 @@ use OCP\IDBConnection; 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 47a8eaa6fd0d0..6959d13b72085 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 @@ 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 3fb897328e56a..8cdb071b52b81 100644 --- a/lib/private/DB/QueryBuilder/Literal.php +++ b/lib/private/DB/QueryBuilder/Literal.php @@ -10,11 +10,12 @@ 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 a272c744d6247..11732c973fc8c 100644 --- a/lib/private/DB/QueryBuilder/Parameter.php +++ b/lib/private/DB/QueryBuilder/Parameter.php @@ -10,11 +10,12 @@ 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 82fc6f84117c8..3ad67ba0af3b2 100644 --- a/lib/private/DB/QueryBuilder/QueryBuilder.php +++ b/lib/private/DB/QueryBuilder/QueryBuilder.php @@ -20,6 +20,8 @@ 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 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 @@ public function automaticTablePrefix($enabled) { * 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 @@ public function expr() { * 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 @@ public function getType() { /** * 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 7f2ab584a73c0..6a91127f5d29e 100644 --- a/lib/private/DB/QueryBuilder/QueryFunction.php +++ b/lib/private/DB/QueryBuilder/QueryFunction.php @@ -10,14 +10,12 @@ use OCP\DB\QueryBuilder\IQueryFunction; class QueryFunction implements IQueryFunction { - /** @var string */ - protected $function; - - public function __construct($function) { - $this->function = $function; + public function __construct( + protected string $function, + ) { } public function __toString(): string { - return (string)$this->function; + return $this->function; } } diff --git a/lib/private/DB/QueryBuilder/Sharded/ShardConnectionManager.php b/lib/private/DB/QueryBuilder/Sharded/ShardConnectionManager.php index 74358e3ca9647..18dcc68fd4c62 100644 --- a/lib/private/DB/QueryBuilder/Sharded/ShardConnectionManager.php +++ b/lib/private/DB/QueryBuilder/Sharded/ShardConnectionManager.php @@ -12,6 +12,7 @@ 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 @@ public function getConnection(ShardDefinition $shardDefinition, int $shard): IDB } 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/SQLiteMigrator.php b/lib/private/DB/SQLiteMigrator.php index 6be17625476a3..40503ae17812d 100644 --- a/lib/private/DB/SQLiteMigrator.php +++ b/lib/private/DB/SQLiteMigrator.php @@ -8,14 +8,10 @@ namespace OC\DB; use Doctrine\DBAL\Schema\Schema; +use Doctrine\DBAL\Schema\SchemaDiff; class SQLiteMigrator extends Migrator { - /** - * @param Schema $targetSchema - * @param \Doctrine\DBAL\Connection $connection - * @return \Doctrine\DBAL\Schema\SchemaDiff - */ - protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) { + protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection): SchemaDiff { foreach ($targetSchema->getTables() as $table) { foreach ($table->getColumns() as $column) { // column comments are not supported on SQLite diff --git a/lib/private/DB/SQLiteSessionInit.php b/lib/private/DB/SQLiteSessionInit.php index 5fe0cb3abf64c..6ad4c121349ba 100644 --- a/lib/private/DB/SQLiteSessionInit.php +++ b/lib/private/DB/SQLiteSessionInit.php @@ -13,31 +13,15 @@ class SQLiteSessionInit implements EventSubscriber { /** - * @var bool + * Configure case-sensitive like for each connection */ - 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 readonly bool $caseSensitiveLike, + private readonly string $journalMode, + ) { } - /** - * @param ConnectionEventArgs $args - * @return void - */ - public function postConnect(ConnectionEventArgs $args) { + public function postConnect(ConnectionEventArgs $args): void { $sensitive = $this->caseSensitiveLike ? 'true' : 'false'; $args->getConnection()->executeUpdate('PRAGMA case_sensitive_like = ' . $sensitive); $args->getConnection()->executeUpdate('PRAGMA journal_mode = ' . $this->journalMode); @@ -47,7 +31,7 @@ public function postConnect(ConnectionEventArgs $args) { $pdo->sqliteCreateFunction('md5', 'md5', 1); } - public function getSubscribedEvents() { + public function getSubscribedEvents(): array { return [Events::postConnect]; } } diff --git a/lib/private/DB/SchemaWrapper.php b/lib/private/DB/SchemaWrapper.php index 19a0bc576f260..57f0caecb8d80 100644 --- a/lib/private/DB/SchemaWrapper.php +++ b/lib/private/DB/SchemaWrapper.php @@ -15,18 +15,16 @@ use Psr\Log\LoggerInterface; class SchemaWrapper implements ISchemaWrapper { - /** @var Connection */ - protected $connection; + protected Schema $schema; - /** @var Schema */ - protected $schema; + /** @var array */ + protected array $tablesToDelete = []; - /** @var array */ - protected $tablesToDelete = []; - - public function __construct(Connection $connection, ?Schema $schema = null) { - $this->connection = $connection; - if ($schema) { + public function __construct( + protected Connection $connection, + ?Schema $schema = null, + ) { + if ($schema !== null) { $this->schema = $schema; } else { $this->schema = $this->connection->createSchema(); @@ -37,7 +35,7 @@ public function getWrappedSchema() { return $this->schema; } - public function performDropTableCalls() { + public function performDropTableCalls(): void { foreach ($this->tablesToDelete as $tableName => $true) { $this->connection->dropTable($tableName); foreach ($this->connection->getShardConnections() as $shardConnection) { diff --git a/lib/private/Dashboard/Manager.php b/lib/private/Dashboard/Manager.php index d4a9eb189ffc9..d6ced08e1bb0d 100644 --- a/lib/private/Dashboard/Manager.php +++ b/lib/private/Dashboard/Manager.php @@ -13,6 +13,7 @@ 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 @@ public function loadLazyPanels(): void { * 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 @@ public function loadLazyPanels(): void { * 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 @@ public function loadLazyPanels(): void { $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 @@ public function loadLazyPanels(): void { ); } } 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 2882a7d8cd73a..2a20c65ada328 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 @@ protected function getTimeZone($timeZone = null) { /** * 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 @@ protected function getDateTime($timestamp, ?\DateTimeZone $timeZone = null) { * 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 @@ public function formatDate($timestamp, $format = 'long', ?\DateTimeZone $timeZon * 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 @@ public function formatDateRelativeDay($timestamp, $format = 'long', ?\DateTimeZo * * @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 @@ public function formatDateSpan($timestamp, $baseTimestamp = null, ?\OCP\IL10N $l * 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 @@ public function formatTime($timestamp, $format = 'medium', ?\DateTimeZone $timeZ * * @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 @@ public function formatTime($timestamp, $format = 'medium', ?\DateTimeZone $timeZ * < 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 @@ public function formatTimeSpan($timestamp, $baseTimestamp = null, ?\OCP\IL10N $l * @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 @@ public function formatDateTime($timestamp, $formatDate = 'long', $formatTime = ' * 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 @@ public function formatDateTimeRelativeDay($timestamp, $formatDate = 'long', $for * @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 75eb3a6b76968..589d2e0a6a977 100644 --- a/lib/private/DateTimeZone.php +++ b/lib/private/DateTimeZone.php @@ -13,27 +13,17 @@ 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 readonly IConfig $config, + protected readonly ISession $session, + protected readonly LoggerInterface $logger, + ) { } /** * @inheritdoc */ - public function getTimeZone($timestamp = false, ?string $userId = null): \DateTimeZone { + public function getTimeZone(int|false $timestamp = false, ?string $userId = null): \DateTimeZone { $uid = $userId ?? $this->session->get('user_id'); $timezoneName = $this->config->getUserValue($uid, 'core', 'timezone', ''); if ($timezoneName === '') { @@ -46,7 +36,7 @@ public function getTimeZone($timestamp = false, ?string $userId = null): \DateTi try { return new \DateTimeZone($timezoneName); } catch (\Exception $e) { - \OCP\Server::get(LoggerInterface::class)->debug('Failed to created DateTimeZone "' . $timezoneName . '"', ['app' => 'datetimezone']); + $this->logger->debug('Failed to created DateTimeZone "' . $timezoneName . '"', ['app' => 'datetimezone']); return $this->getDefaultTimeZone(); } } @@ -69,10 +59,8 @@ public function getDefaultTimeZone(): \DateTimeZone { * we try to find it manually, before falling back to UTC. * * @param mixed $offset - * @param int|false $timestamp - * @return \DateTimeZone */ - protected function guessTimeZoneFromOffset($offset, $timestamp) { + protected function guessTimeZoneFromOffset($offset, int|false $timestamp): \DateTimeZone { try { // Note: the timeZone name is the inverse to the offset, // so a positive offset means negative timeZone @@ -102,7 +90,7 @@ protected function guessTimeZoneFromOffset($offset, $timestamp) { } // No timezone found, fallback to UTC - \OCP\Server::get(LoggerInterface::class)->debug('Failed to find DateTimeZone for offset "' . $offset . '"', ['app' => 'datetimezone']); + $this->logger->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 11d6505a888b5..956d86b2693f3 100644 --- a/lib/private/Diagnostics/Event.php +++ b/lib/private/Diagnostics/Event.php @@ -10,76 +10,36 @@ use OCP\Diagnostics\IEvent; class Event implements IEvent { - /** - * @var string - */ - protected $id; + protected ?float $end = null; - /** - * @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 string $id, + protected string $description, + protected float $start, + ) { } - /** - * @param float $time - */ - public function end($time) { + public function end(float $time): void { $this->end = $time; } - /** - * @return float - */ - public function getStart() { + public function getStart(): float { return $this->start; } - /** - * @return string - */ - public function getId() { + public function getId(): string { return $this->id; } - /** - * @return string - */ - public function getDescription() { + public function getDescription(): string { return $this->description; } - /** - * @return float - */ - public function getEnd() { - return $this->end; + public function getEnd(): float { + return $this->end ?? -1; } - /** - * @return float - */ - public function getDuration() { + public function getDuration(): float { if (!$this->end) { $this->end = microtime(true); } diff --git a/lib/private/Diagnostics/EventLogger.php b/lib/private/Diagnostics/EventLogger.php index 3ec35a5e9ce46..f61b470e83645 100644 --- a/lib/private/Diagnostics/EventLogger.php +++ b/lib/private/Diagnostics/EventLogger.php @@ -15,27 +15,18 @@ class EventLogger implements IEventLogger { /** @var Event[] */ - private $events = []; - - /** @var SystemConfig */ - private $config; - - /** @var LoggerInterface */ - private $logger; - - /** @var Log */ - private $internalLogger; + private array $events = []; /** * @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; + private bool $activated = false; + 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 020fc4bb512ec..fd14b94688328 100644 --- a/lib/private/Diagnostics/Query.php +++ b/lib/private/Diagnostics/Query.php @@ -10,65 +10,41 @@ use OCP\Diagnostics\IQuery; class Query implements IQuery { - private $sql; + private ?float $end = null; - 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 string $sql, + private array $params, + private float $start, + private array $stack, + ) { } - public function end($time) { + public function end($time): void { $this->end = $time; } - /** - * @return array - */ - public function getParams() { + public function getParams(): array { return $this->params; } - /** - * @return string - */ - public function getSql() { + public function getSql(): string { return $this->sql; } - /** - * @return float - */ - public function getStart() { + public function getStart(): float { return $this->start; } - /** - * @return float - */ - public function getDuration() { + public function getDuration(): float { return $this->end - $this->start; } - public function getStartTime() { + public function getStartTime(): float { return $this->start; } - public function getStacktrace() { + public function getStacktrace(): array { return $this->stack; } } diff --git a/lib/private/DirectEditing/Manager.php b/lib/private/DirectEditing/Manager.php index 154002ef340cb..bcb69163dbbab 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\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 @@ public function isEnabled(): bool { 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 ca01265f9dfaa..a816bf18dcc7b 100644 --- a/lib/private/DirectEditing/Token.php +++ b/lib/private/DirectEditing/Token.php @@ -10,13 +10,10 @@ 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 52ab441e73a71..d305fc24799b0 100644 --- a/lib/private/EmojiHelper.php +++ b/lib/private/EmojiHelper.php @@ -12,10 +12,9 @@ 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/EncryptionEventListener.php b/lib/private/Encryption/EncryptionEventListener.php index 4560c4796df81..693dded42b844 100644 --- a/lib/private/Encryption/EncryptionEventListener.php +++ b/lib/private/Encryption/EncryptionEventListener.php @@ -13,14 +13,18 @@ use OC\Files\View; use OCA\Files_Trashbin\Events\NodeRestoredEvent; use OCP\Encryption\IFile; +use OCP\Encryption\IManager; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventDispatcher; use OCP\EventDispatcher\IEventListener; use OCP\Files\Events\Node\NodeRenamedEvent; use OCP\Files\NotFoundException; +use OCP\IConfig; +use OCP\IGroupManager; use OCP\IUser; use OCP\IUserManager; use OCP\IUserSession; +use OCP\Server; use OCP\Share\Events\ShareCreatedEvent; use OCP\Share\Events\ShareDeletedEvent; use Psr\Log\LoggerInterface; @@ -81,11 +85,12 @@ private function getUpdate(?IUser $owner = null): Update { new Util( new View(), $this->userManager, - \OC::$server->getGroupManager(), - \OC::$server->getConfig()), - \OC::$server->getEncryptionManager(), - \OC::$server->get(IFile::class), - \OC::$server->get(LoggerInterface::class), + Server::get(IGroupManager::class), + Server::get(IConfig::class) + ), + Server::get(IManager::class), + Server::get(IFile::class), + Server::get(LoggerInterface::class), ); } diff --git a/lib/private/Encryption/EncryptionWrapper.php b/lib/private/Encryption/EncryptionWrapper.php index b9db9616538a6..68d2efd8b8c0b 100644 --- a/lib/private/Encryption/EncryptionWrapper.php +++ b/lib/private/Encryption/EncryptionWrapper.php @@ -16,6 +16,11 @@ 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 @@ * @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 @@ public function wrapStorage(string $mountPoint, IStorage $storage, IMountPoint $ ]; 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 26e643d10066a..8da0bcfcc0d42 100644 --- a/lib/private/Encryption/File.php +++ b/lib/private/Encryption/File.php @@ -10,15 +10,13 @@ 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 @@ public function getAppManager(): IAppManager { 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 @@ public function getAccessList($path) { // 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 cce22b9138a21..d1d225cd5734c 100644 --- a/lib/private/Encryption/Keys/Storage.php +++ b/lib/private/Encryption/Keys/Storage.php @@ -17,52 +17,26 @@ use OCP\Security\ICrypto; class Storage implements IStorage { - // hidden file which indicate that the folder is a valid key storage + /** @var string 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; - - // root of the key storage default is empty which means that we use the data folder - /** @var string */ - private $root_dir; - - /** @var string */ - private $encryption_base_dir; - - /** @var string */ - private $backup_base_dir; - - /** @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; - + /** @var string base dir where all the file related keys are stored */ + private string $keys_base_dir; + /** @var string root of the key storage default is empty which means that we use the data folder */ + private string $root_dir; + private string $encryption_base_dir; + private string $backup_base_dir; + private array $keyCache = []; + + public function __construct( + private readonly View $view, + private readonly Util $util, + private readonly ICrypto $crypto, + private readonly 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 +167,7 @@ protected function constructUserKeyPath($encryptionModuleId, $keyId, $uid) { . $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 a07c778bfe02a..a357ae0a150d6 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 @@ public function isReadyForUser($user) { */ 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 @@ public function getEncryptionModule($moduleId = '') { } $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 2d7bc28129b28..0fff34cb11192 100644 --- a/lib/private/Encryption/Util.php +++ b/lib/private/Encryption/Util.php @@ -12,6 +12,7 @@ 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; @@ -27,54 +28,32 @@ class Util { public const HEADER_ENCRYPTION_MODULE_KEY = 'oc_encryption_module'; /** - * block size will always be 8192 for a PHP stream + * Block size will always be 8192 for a PHP stream * @see https://bugs.php.net/bug.php?id=21641 - * @var integer */ - protected $headerSize = 8192; + protected int $headerSize = 8192; /** - * block size will always be 8192 for a PHP stream + * Block size will always be 8192 for a PHP stream * @see https://bugs.php.net/bug.php?id=21641 - * @var integer */ - protected $blockSize = 8192; + protected int $blockSize = 8192; - /** @var View */ - protected $rootView; - - /** @var array */ - protected $ocHeaderKeys; - - /** @var IConfig */ - protected $config; - - /** @var array paths excluded from encryption */ + protected array $ocHeaderKeys; protected array $excludedPaths = []; - protected IGroupManager $groupManager; - protected IUserManager $userManager; - /** - * - * @param View $rootView - * @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 +74,7 @@ public function getEncryptionModuleId(?array $header = null) { 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 474c902013bcc..4c87271009a01 100644 --- a/lib/private/EventDispatcher/EventDispatcher.php +++ b/lib/private/EventDispatcher/EventDispatcher.php @@ -10,6 +10,7 @@ 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 @@ public function __construct( ) { // 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 b807c29d812e7..643524b3acd2a 100644 --- a/lib/private/Federation/CloudId.php +++ b/lib/private/Federation/CloudId.php @@ -10,6 +10,7 @@ use OCP\Federation\ICloudId; use OCP\Federation\ICloudIdManager; +use OCP\Server; class CloudId implements ICloudId { public function __construct( @@ -32,7 +33,7 @@ public function getId(): string { 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 c13372ae1d9e7..5bea7ec470c88 100644 --- a/lib/private/Files/AppData/AppData.php +++ b/lib/private/Files/AppData/AppData.php @@ -20,26 +20,15 @@ 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; - /** - * AppData constructor. - * - * @param IRootFolder $rootFolder - * @param SystemConfig $systemConfig - * @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 38b73f370b888..75d20e454e550 100644 --- a/lib/private/Files/AppData/Factory.php +++ b/lib/private/Files/AppData/Factory.php @@ -14,16 +14,13 @@ 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 e85d4793d8e3f..41f27699528d8 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; @@ -33,6 +34,7 @@ use OCP\Files\Storage\IStorage; use OCP\FilesMetadata\IFilesMetadataManager; use OCP\IDBConnection; +use OCP\Server; use OCP\Util; use Psr\Log\LoggerInterface; @@ -76,7 +78,7 @@ public function __construct( $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(); @@ -557,7 +559,7 @@ public function remove($file) { * 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()]; @@ -668,7 +670,7 @@ protected function shouldEncrypt(string $targetPath): bool { * @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) { @@ -745,7 +747,7 @@ public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) { $query->executeStatement(); } break; - } catch (\OC\DatabaseException $e) { + } catch (DatabaseException $e) { $this->connection->rollBack(); throw $e; } catch (DbalException $e) { @@ -1133,7 +1135,7 @@ public function getPathById($id) { * @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/CacheEntry.php b/lib/private/Files/Cache/CacheEntry.php index c558ec7721e8f..ab1df46d68e28 100644 --- a/lib/private/Files/Cache/CacheEntry.php +++ b/lib/private/Files/Cache/CacheEntry.php @@ -13,13 +13,9 @@ * meta data for a file or folder */ class CacheEntry implements ICacheEntry { - /** - * @var array - */ - private $data; - - public function __construct(array $data) { - $this->data = $data; + public function __construct( + private array $data, + ) { } public function offsetSet($offset, $value): void { diff --git a/lib/private/Files/Cache/FailedCache.php b/lib/private/Files/Cache/FailedCache.php index 44c1016ca8ea6..83fb239ecb617 100644 --- a/lib/private/Files/Cache/FailedCache.php +++ b/lib/private/Files/Cache/FailedCache.php @@ -19,16 +19,9 @@ * 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 readonly bool $visible = true, + ) { } diff --git a/lib/private/Files/Cache/FileAccess.php b/lib/private/Files/Cache/FileAccess.php index 86243b9ca255a..ee92c4fdc7acd 100644 --- a/lib/private/Files/Cache/FileAccess.php +++ b/lib/private/Files/Cache/FileAccess.php @@ -8,6 +8,8 @@ */ 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 @@ public function getDistinctMounts(array $mountProviders = [], bool $onlyUserFile $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 @@ public function getDistinctMounts(array $mountProviders = [], bool $onlyUserFile // 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 d5f7d40e1b650..be9f74daf8a1f 100644 --- a/lib/private/Files/Cache/LocalRootScanner.php +++ b/lib/private/Files/Cache/LocalRootScanner.php @@ -8,6 +8,7 @@ */ namespace OC\Files\Cache; +use OC\Files\Storage\Storage; use OCP\IConfig; use OCP\Server; use Override; @@ -15,7 +16,7 @@ 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 db35c6bb7f80d..a13e0d7d00e89 100644 --- a/lib/private/Files/Cache/MoveFromCacheTrait.php +++ b/lib/private/Files/Cache/MoveFromCacheTrait.php @@ -30,7 +30,7 @@ abstract public function copyFromCache(ICache $sourceCache, ICacheEntry $sourceE /** * 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 557d055c67b9f..ec3293c3a4a53 100644 --- a/lib/private/Files/Cache/Propagator.php +++ b/lib/private/Files/Cache/Propagator.php @@ -113,7 +113,7 @@ public function propagateChange(string $internalPath, int $time, int $sizeDiffer } /** @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 2fa0dd09e4fd0..eeed52afe0b3b 100644 --- a/lib/private/Files/Cache/Scanner.php +++ b/lib/private/Files/Cache/Scanner.php @@ -8,17 +8,25 @@ 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\ICache; +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,42 +42,19 @@ * @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 - */ - protected $cache; - - /** - * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache - */ - protected $cacheActive; - - /** - * @var bool $useTransactions whether to use transactions - */ - protected $useTransactions = true; - - /** - * @var \OCP\Lock\ILockingProvider - */ - protected $lockingProvider; - + protected string $storageId; + protected ICache $cache; + /** @var bool $cacheActive Whether to perform cache operations */ + protected bool $cacheActive; + protected bool $useTransactions = true; + protected ILockingProvider $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 +82,7 @@ public function setUseTransactions($useTransactions): void { 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 +97,7 @@ protected function getData($path) { * @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 +192,7 @@ public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = * 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 +367,7 @@ protected function array_diff_assoc_multi(array $array1, array $array2) { * Get the children currently in the cache * * @param int $folderId - * @return array + * @return array */ protected function getExistingChildren($folderId): array { $existingChildren = []; @@ -428,7 +413,9 @@ protected function scanChildren(string $path, $recursive, int $reuse, int $folde // for encrypted storages, we trigger a regular folder size calculation instead of using the calculated size // to make sure we also updated the unencrypted-size where applicable if ($this->storage->instanceOfStorage(Encryption::class)) { - $this->cache->calculateFolderSize($path); + /** @var Cache $cache */ + $cache = $this->cache; + $cache->calculateFolderSize($path); } else { if ($this->cacheActive) { $updatedData = []; @@ -473,10 +460,10 @@ private function handleChildren(string $path, $recursive, int $reuse, int $folde 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 +498,12 @@ private function handleChildren(string $path, $recursive, int $reuse, int $folde $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 +523,7 @@ private function handleChildren(string $path, $recursive, int $reuse, int $folde // 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 +562,14 @@ public function backgroundScan() { } 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,14 +587,8 @@ protected function runBackgroundScanJob(callable $callback, $path) { if ($this->cacheActive && $this->cache instanceof Cache) { $this->cache->correctFolderSize($path, null, true); } - } catch (\OCP\Files\StorageInvalidException $e) { - // skip unavailable storages - } catch (\OCP\Files\StorageNotAvailableException $e) { - // skip unavailable storages - } catch (\OCP\Files\ForbiddenException $e) { - // skip forbidden storages - } catch (\OCP\Lock\LockedException $e) { - // skip unavailable storages + } catch (StorageInvalidException|StorageNotAvailableException|ForbiddenException|LockedException) { + // skip unavailable and forbidden storages } } diff --git a/lib/private/Files/Cache/Storage.php b/lib/private/Files/Cache/Storage.php index a2fdfc76cc70d..51def43a4dcee 100644 --- a/lib/private/Files/Cache/Storage.php +++ b/lib/private/Files/Cache/Storage.php @@ -10,6 +10,7 @@ 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 @@ public function getAvailability() { 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 @@ public static function remove($storageId) { $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 @@ public static function remove($storageId) { * @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 cdbff8b6c9ac0..4f61cb4e0c3b4 100644 --- a/lib/private/Files/Cache/Updater.php +++ b/lib/private/Files/Cache/Updater.php @@ -10,98 +10,62 @@ 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\IPropagator; +use OCP\Files\Cache\IScanner; use OCP\Files\Cache\IUpdater; use OCP\Files\Storage\IStorage; +use OCP\Server; +use Override; use Psr\Log\LoggerInterface; -/** - * Update the cache and propagate changes - * - */ class Updater implements IUpdater { - /** - * @var bool - */ - protected $enabled = true; - - /** - * @var \OC\Files\Storage\Storage - */ - protected $storage; - - /** - * @var \OC\Files\Cache\Propagator - */ - protected $propagator; - - /** - * @var Scanner - */ - protected $scanner; - - /** - * @var Cache - */ - protected $cache; - + protected bool $enabled = true; + protected IPropagator $propagator; + protected IScanner $scanner; + protected ICache $cache; private LoggerInterface $logger; - /** - * @param \OC\Files\Storage\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); } /** * Disable updating the cache through this updater */ - public function disable() { + public function disable(): void { $this->enabled = false; } /** * Re-enable the updating of the cache through this updater */ - public function enable() { + public function enable(): void { $this->enabled = true; } - /** - * Get the propagator for etags and mtime for the view the updater works on - * - * @return Propagator - */ - public function getPropagator() { + #[Override] + public function getPropagator(): IPropagator { return $this->propagator; } - /** - * Propagate etag and mtime changes for the parent folders of $path up to the root of the filesystem - * - * @param string $path the path of the file to propagate the changes for - * @param int|null $time the timestamp to set as mtime for the parent folders, if left out the current time is used - */ - public function propagate($path, $time = null) { + #[Override] + public function propagate(string $path, ?int $time = null): void { if (Scanner::isPartialFile($path)) { return; } $this->propagator->propagateChange($path, $time); } - /** - * Update the cache for $path and update the size, etag and mtime of the parent folders - * - * @param string $path - * @param int $time - */ - public function update($path, $time = null, ?int $sizeDifference = null) { + #[Override] + public function update(string $path, ?int $time = null, ?int $sizeDifference = null): void { if (!$this->enabled || Scanner::isPartialFile($path)) { return; } @@ -128,12 +92,8 @@ public function update($path, $time = null, ?int $sizeDifference = null) { $this->propagator->propagateChange($path, $time, $sizeDifference ?? 0); } - /** - * Remove $path from the cache and update the size, etag and mtime of the parent folders - * - * @param string $path - */ - public function remove($path) { + #[Override] + public function remove(string $path): void { if (!$this->enabled || Scanner::isPartialFile($path)) { return; } @@ -158,15 +118,9 @@ public function remove($path) { } } - /** - * Rename a file or folder in the cache. - * - * @param IStorage $sourceStorage - * @param string $source - * @param string $target - */ - public function renameFromStorage(IStorage $sourceStorage, $source, $target) { - $this->copyOrRenameFromStorage($sourceStorage, $source, $target, function (ICache $sourceCache) use ($sourceStorage, $source, $target) { + #[Override] + public function renameFromStorage(IStorage $sourceStorage, string $source, string $target): void { + $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); @@ -180,11 +134,9 @@ public function renameFromStorage(IStorage $sourceStorage, $source, $target) { }); } - /** - * Copy a file or folder in the cache. - */ + #[Override] 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 = ''; @@ -252,7 +204,7 @@ private function copyOrRenameFromStorage(IStorage $sourceStorage, string $source $this->propagator->propagateChange($target, $time); } - private function updateStorageMTimeOnly($internalPath) { + private function updateStorageMTimeOnly(string $internalPath): void { $fileId = $this->cache->getId($internalPath); if ($fileId !== -1) { $mtime = $this->storage->filemtime($internalPath); @@ -268,11 +220,9 @@ private function updateStorageMTimeOnly($internalPath) { } /** - * update the storage_mtime of the direct parent in the cache to the mtime from the storage - * - * @param string $internalPath + * Update the storage_mtime of the direct parent in the cache to the mtime from the storage */ - private function correctParentStorageMtime($internalPath) { + private function correctParentStorageMtime(string $internalPath): void { $parentId = $this->cache->getParentId($internalPath); $parent = dirname($internalPath); if ($parentId != -1) { diff --git a/lib/private/Files/Cache/Watcher.php b/lib/private/Files/Cache/Watcher.php index dfab51be38b29..37272721fa91c 100644 --- a/lib/private/Files/Cache/Watcher.php +++ b/lib/private/Files/Cache/Watcher.php @@ -7,42 +7,28 @@ */ namespace OC\Files\Cache; +use OC\Files\Storage\Storage; +use OCP\Files\Cache\ICache; use OCP\Files\Cache\ICacheEntry; +use OCP\Files\Cache\IScanner; use OCP\Files\Cache\IWatcher; /** * check the storage backends for updates and change the cache accordingly */ class Watcher implements IWatcher { - protected $watchPolicy = self::CHECK_ONCE; - - protected $checkedPaths = []; - - /** - * @var \OC\Files\Storage\Storage $storage - */ - protected $storage; - - /** - * @var Cache $cache - */ - protected $cache; - - /** - * @var Scanner $scanner ; - */ - protected $scanner; - + protected int $watchPolicy = self::CHECK_ONCE; + protected array $checkedPaths = []; + protected ICache $cache; + protected IScanner $scanner; /** @var callable[] */ - protected $onUpdate = []; + protected array $onUpdate = []; - /** - * @param \OC\Files\Storage\Storage $storage - */ - public function __construct(\OC\Files\Storage\Storage $storage) { - $this->storage = $storage; - $this->cache = $storage->getCache(); - $this->scanner = $storage->getScanner(); + public function __construct( + protected Storage $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 7fc5c8e3191ad..8b7f14b09890e 100644 --- a/lib/private/Files/Cache/Wrapper/CacheJail.php +++ b/lib/private/Files/Cache/Wrapper/CacheJail.php @@ -280,11 +280,10 @@ public function getPathById($id) { * * Note that this should make sure the entries are removed from the source cache * - * @param \OCP\Files\Cache\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 12db55980c509..c2ecaaeaf07d3 100644 --- a/lib/private/Files/Cache/Wrapper/CachePermissionsMask.php +++ b/lib/private/Files/Cache/Wrapper/CachePermissionsMask.php @@ -7,19 +7,14 @@ */ namespace OC\Files\Cache\Wrapper; -class CachePermissionsMask extends CacheWrapper { - /** - * @var int - */ - protected $mask; +use OCP\Files\Cache\ICache; - /** - * @param \OCP\Files\Cache\ICache $cache - * @param int $mask - */ - public function __construct($cache, $mask) { +class CachePermissionsMask extends CacheWrapper { + public function __construct( + ICache $cache, + protected readonly int $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 bf23f1cc30ab0..7d964e135b87a 100644 --- a/lib/private/Files/Cache/Wrapper/CacheWrapper.php +++ b/lib/private/Files/Cache/Wrapper/CacheWrapper.php @@ -16,17 +16,14 @@ 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 b1ae516654a10..18a1c22495c16 100644 --- a/lib/private/Files/Cache/Wrapper/JailWatcher.php +++ b/lib/private/Files/Cache/Wrapper/JailWatcher.php @@ -10,12 +10,10 @@ 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 69bd4e9301ee8..1ea77a53e5fca 100644 --- a/lib/private/Files/Config/CachedMountFileInfo.php +++ b/lib/private/Files/Config/CachedMountFileInfo.php @@ -10,8 +10,6 @@ use OCP\IUser; class CachedMountFileInfo extends CachedMountInfo implements ICachedMountFileInfo { - private string $internalPath; - public function __construct( IUser $user, int $storageId, @@ -20,10 +18,9 @@ public function __construct( ?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/CachedMountInfo.php b/lib/private/Files/Config/CachedMountInfo.php index 79dd6c6ea1da0..431d20b194e8f 100644 --- a/lib/private/Files/Config/CachedMountInfo.php +++ b/lib/private/Files/Config/CachedMountInfo.php @@ -13,50 +13,23 @@ use OCP\IUser; class CachedMountInfo implements ICachedMountInfo { - protected IUser $user; - protected int $storageId; - protected int $rootId; - protected string $mountPoint; - protected ?int $mountId; - protected string $rootInternalPath; - protected string $mountProvider; protected string $key; - /** - * CachedMountInfo constructor. - * - * @param IUser $user - * @param int $storageId - * @param int $rootId - * @param string $mountPoint - * @param int|null $mountId - * @param string $rootInternalPath - */ public function __construct( - IUser $user, - int $storageId, - int $rootId, - string $mountPoint, - string $mountProvider, - ?int $mountId = null, - string $rootInternalPath = '', + protected IUser $user, + protected int $storageId, + protected int $rootId, + protected string $mountPoint, + protected string $mountProvider, + protected ?int $mountId = null, + protected string $rootInternalPath = '', ) { - $this->user = $user; - $this->storageId = $storageId; - $this->rootId = $rootId; - $this->mountPoint = $mountPoint; - $this->mountId = $mountId; - $this->rootInternalPath = $rootInternalPath; if (strlen($mountProvider) > 128) { throw new \Exception("Mount provider $mountProvider name exceeds the limit of 128 characters"); } - $this->mountProvider = $mountProvider; - $this->key = $rootId . '::' . $mountPoint; + $this->key = $this->rootId . '::' . $this->mountPoint; } - /** - * @return IUser - */ public function getUser(): IUser { return $this->user; } diff --git a/lib/private/Files/Config/LazyStorageMountInfo.php b/lib/private/Files/Config/LazyStorageMountInfo.php index eb2c60dfa46ab..186e354aa342f 100644 --- a/lib/private/Files/Config/LazyStorageMountInfo.php +++ b/lib/private/Files/Config/LazyStorageMountInfo.php @@ -11,20 +11,11 @@ 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) { - $this->user = $user; - $this->mount = $mount; - $this->rootId = 0; - $this->storageId = 0; - $this->mountPoint = ''; + public function __construct( + IUser $user, + private IMountPoint $mount, + ) { + parent::__construct($user, 0, 0, '', ''); $this->key = ''; } diff --git a/lib/private/Files/Config/UserMountCache.php b/lib/private/Files/Config/UserMountCache.php index 7079c8a295730..e445bb20fafd3 100644 --- a/lib/private/Files/Config/UserMountCache.php +++ b/lib/private/Files/Config/UserMountCache.php @@ -337,7 +337,7 @@ public function getMountsForRootId($rootFileId) { /** * @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 40995de8986f6..2b1eecde971b8 100644 --- a/lib/private/Files/Config/UserMountCacheListener.php +++ b/lib/private/Files/Config/UserMountCacheListener.php @@ -14,18 +14,9 @@ * 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 a78c6d3cc3c73..987575292d711 100644 --- a/lib/private/Files/FilenameValidator.php +++ b/lib/private/Files/FilenameValidator.php @@ -7,6 +7,7 @@ */ namespace OC\Files; +use OCP\Constants; use OCP\Files\EmptyFileNameException; use OCP\Files\FileNameTooLongException; use OCP\Files\IFilenameValidator; @@ -126,7 +127,7 @@ public function getForbiddenBasenames(): array { 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 @@ public function getForbiddenCharacters(): array { 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 eb374d9326b3d..6e2e8dad11fa6 100644 --- a/lib/private/Files/Filesystem.php +++ b/lib/private/Files/Filesystem.php @@ -8,17 +8,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\Cache\CappedMemoryCache; 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 { @@ -149,7 +154,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; @@ -171,7 +176,7 @@ public static function logWarningWhenAddingStorageWrapper(bool $shouldLog): bool */ 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', ]); @@ -193,7 +198,7 @@ public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) */ public static function getLoader() { if (!self::$loader) { - self::$loader = \OC::$server->get(IStorageFactory::class); + self::$loader = Server::get(IStorageFactory::class); } return self::$loader; } @@ -246,7 +251,7 @@ public static function getMountPoints($path) { * 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); @@ -255,7 +260,7 @@ public static function getStorage($mountPoint) { /** * @param string $id - * @return Mount\MountPoint[] + * @return IMountPoint[] */ public static function getMountByStorageId($id) { return self::getMountManager()->findByStorageId($id); @@ -263,7 +268,7 @@ public static function getMountByStorageId($id) { /** * @param int $id - * @return Mount\MountPoint[] + * @return IMountPoint[] */ public static function getMountByNumericId($id) { return self::getMountManager()->findByNumericId($id); @@ -273,7 +278,7 @@ public static function getMountByNumericId($id) { * 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); @@ -299,8 +304,8 @@ public static function initInternal(string $root): bool { 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; }); @@ -314,23 +319,23 @@ public static function initInternal(string $root): bool { 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(); @@ -343,7 +348,7 @@ public static function initMountPoints(string|IUser|null $user = ''): void { 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'; @@ -377,7 +382,7 @@ public static function getRoot() { /** * 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 */ @@ -385,7 +390,7 @@ public static function mount($class, $arguments, $mountpoint) { 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); } @@ -414,7 +419,7 @@ public static function isValidPath($path) { */ 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); @@ -531,7 +536,7 @@ public static function fopen($path, $mode) { /** * @param string $path - * @throws \OCP\Files\InvalidPathException + * @throws InvalidPathException */ public static function toTmpFile($path): string|false { return self::$defaultInstance->toTmpFile($path); @@ -653,7 +658,7 @@ public static function normalizePath($path, $stripTrailingSlash = true, $isAbsol * @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); @@ -677,7 +682,7 @@ public static function putFileInfo($path, $data) { * * @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 978c378e506a2..4c7e1427d02bc 100644 --- a/lib/private/Files/Lock/LockManager.php +++ b/lib/private/Files/Lock/LockManager.php @@ -11,6 +11,7 @@ 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,8 +42,8 @@ private function getLockProvider(): ?ILockProvider { } if ($this->lockProviderClass) { try { - $this->lockProvider = \OCP\Server::get($this->lockProviderClass); - } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) { + $this->lockProvider = Server::get($this->lockProviderClass); + } catch (NotFoundExceptionInterface|ContainerExceptionInterface) { } } diff --git a/lib/private/Files/Mount/CacheMountProvider.php b/lib/private/Files/Mount/CacheMountProvider.php index 27c7eec9da34f..303ec7761a8b4 100644 --- a/lib/private/Files/Mount/CacheMountProvider.php +++ b/lib/private/Files/Mount/CacheMountProvider.php @@ -8,6 +8,7 @@ namespace OC\Files\Mount; use OCP\Files\Config\IMountProvider; +use OCP\Files\Mount\IMountPoint; use OCP\Files\Storage\IStorageFactory; use OCP\IConfig; use OCP\IUser; @@ -16,28 +17,17 @@ * Mount provider for custom cache storages */ class CacheMountProvider implements IMountProvider { - /** - * @var IConfig - */ - private $config; - - /** - * ObjectStoreHomeMountProvider constructor. - * - * @param IConfig $config - */ - public function __construct(IConfig $config) { - $this->config = $config; + public function __construct( + private IConfig $config, + ) { } /** * Get the cache mount for a user * - * @param IUser $user - * @param IStorageFactory $loader - * @return \OCP\Files\Mount\IMountPoint[] + * @return IMountPoint[] */ - public function getMountsForUser(IUser $user, IStorageFactory $loader) { + public function getMountsForUser(IUser $user, IStorageFactory $loader): array { $cacheBaseDir = $this->config->getSystemValueString('cache_path', ''); if ($cacheBaseDir !== '') { $cacheDir = rtrim($cacheBaseDir, '/') . '/' . $user->getUID(); diff --git a/lib/private/Files/Mount/HomeMountPoint.php b/lib/private/Files/Mount/HomeMountPoint.php index 5a648f08c8978..0c3b387f00f7e 100644 --- a/lib/private/Files/Mount/HomeMountPoint.php +++ b/lib/private/Files/Mount/HomeMountPoint.php @@ -12,10 +12,8 @@ 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 @@ public function __construct( ?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 a2b3d3b2a991f..efd4e63831ccf 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 a50a762c6b9fb..3538a1386c577 100644 --- a/lib/private/Files/Mount/MountPoint.php +++ b/lib/private/Files/Mount/MountPoint.php @@ -11,70 +11,54 @@ use OC\Files\Storage\Storage; use OC\Files\Storage\StorageFactory; use OCP\Files\Mount\IMountPoint; +use OCP\Files\Storage\IStorage; use OCP\Files\Storage\IStorageFactory; +use OCP\Server; use Psr\Log\LoggerInterface; class MountPoint implements IMountPoint { - /** - * @var \OC\Files\Storage\Storage|null $storage - */ + /** @var IStorage|null $storage */ protected $storage = null; - protected $class; - protected $storageId; - protected $numericStorageId = null; - protected $rootId = null; + /** @var class-string */ + protected string $class; + protected ?string $storageId = null; + protected ?int $numericStorageId = null; + protected ?int $rootId = null; /** * Configuration options for the storage backend - * - * @var array */ - protected $arguments = []; - protected $mountPoint; + protected array $arguments = []; + protected string $mountPoint; /** * Mount specific options - * - * @var array */ - protected $mountOptions = []; - - /** - * @var \OC\Files\Storage\StorageFactory $loader - */ - private $loader; + protected array $mountOptions = []; + private IStorageFactory $loader; /** * Specified whether the storage is invalid after failing to * instantiate it. - * - * @var bool */ - private $invalidStorage = false; - - /** @var int|null */ - protected $mountId; - - /** @var string */ - protected $mountProvider; + private bool $invalidStorage = false; + protected string $mountProvider; /** - * @param string|\OC\Files\Storage\Storage $storage - * @param string $mountpoint + * @param IStorage|class-string $storage * @param array $arguments (optional) configuration for the storage backend - * @param \OCP\Files\Storage\IStorageFactory $loader - * @param array $mountOptions mount specific options - * @param int|null $mountId - * @param string|null $mountProvider + * @param ?array $mountOptions mount specific options + * @param ?int $mountId + * @param ?string $mountProvider * @throws \Exception */ public function __construct( - $storage, + string|IStorage $storage, string $mountpoint, ?array $arguments = null, ?IStorageFactory $loader = null, ?array $mountOptions = null, - ?int $mountId = null, + protected ?int $mountId = null, ?string $mountProvider = null, ) { if (is_null($arguments)) { @@ -90,9 +74,7 @@ public function __construct( $this->mountOptions = $mountOptions; } - $mountpoint = $this->formatPath($mountpoint); - $this->mountPoint = $mountpoint; - $this->mountId = $mountId; + $this->mountPoint = $this->formatPath($mountpoint); if ($storage instanceof Storage) { $this->class = get_class($storage); $this->storage = $this->loader->wrap($this, $storage); @@ -143,6 +125,7 @@ private function createStorage() { $class = $this->class; // prevent recursion by setting the storage before applying wrappers $this->storage = new $class($this->arguments); + /** @psalm-suppress UndefinedInterfaceMethod This is a StorageFactory */ $this->storage = $this->loader->wrap($this, $this->storage); } catch (\Exception $exception) { $this->storage = null; @@ -151,19 +134,18 @@ private function createStorage() { // 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 IStorage|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 5e0c924ad382a..a1ab474ba283c 100644 --- a/lib/private/Files/Mount/RootMountProvider.php +++ b/lib/private/Files/Mount/RootMountProvider.php @@ -17,12 +17,10 @@ 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 c8eccd11ae270..6a94673987d47 100644 --- a/lib/private/Files/Notify/Change.php +++ b/lib/private/Files/Notify/Change.php @@ -9,29 +9,21 @@ 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 + * @param IChange::ADDED|IChange::REMOVED|IChange::MODIFIED|IChange::RENAMED $type */ - public function __construct($type, $path) { - $this->type = $type; - $this->path = $path; + public function __construct( + private readonly int $type, + private readonly string $path, + ) { } /** * Get the type of the change * - * @return int IChange::ADDED, IChange::REMOVED, IChange::MODIFIED or IChange::RENAMED + * @return IChange::ADDED|IChange::REMOVED|IChange::MODIFIED|IChange::RENAMED */ - public function getType() { + public function getType(): int { return $this->type; } @@ -39,10 +31,8 @@ public function getType() { * Get the path of the file that was changed relative to the root of the storage * * Note, for rename changes this path is the old path for the file - * - * @return mixed */ - public function getPath() { + public function getPath(): string { return $this->path; } } diff --git a/lib/private/Files/Notify/RenameChange.php b/lib/private/Files/Notify/RenameChange.php index 28554ceaa260b..47e89fe9e16c4 100644 --- a/lib/private/Files/Notify/RenameChange.php +++ b/lib/private/Files/Notify/RenameChange.php @@ -6,30 +6,25 @@ */ namespace OC\Files\Notify; +use OCP\Files\Notify\IChange; use OCP\Files\Notify\IRenameChange; class RenameChange extends Change implements IRenameChange { - /** @var string */ - private $targetPath; - /** - * Change constructor. - * - * @param int $type - * @param string $path - * @param string $targetPath + * @param IChange::ADDED|IChange::REMOVED|IChange::MODIFIED|IChange::RENAMED $type */ - public function __construct($type, $path, $targetPath) { + public function __construct( + int $type, + string $path, + private readonly string $targetPath, + ) { parent::__construct($type, $path); - $this->targetPath = $targetPath; } /** * Get the new path of the renamed file relative to the storage root - * - * @return string */ - public function getTargetPath() { + public function getTargetPath(): string { return $this->targetPath; } } diff --git a/lib/private/Files/ObjectStore/ObjectStoreScanner.php b/lib/private/Files/ObjectStore/ObjectStoreScanner.php index 5c3992b845849..a31947ec8ae87 100644 --- a/lib/private/Files/ObjectStore/ObjectStoreScanner.php +++ b/lib/private/Files/ObjectStore/ObjectStoreScanner.php @@ -29,7 +29,7 @@ public function backgroundScan() { // 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 c151e661939ee..d1b07afbb0535 100644 --- a/lib/private/Files/ObjectStore/ObjectStoreStorage.php +++ b/lib/private/Files/ObjectStore/ObjectStoreStorage.php @@ -14,13 +14,16 @@ 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\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 @@ public function __construct(array $parameters) { $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 @@ public function mkdir(string $path, bool $force = false, array $metadata = []): '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 @@ public function getScanner(string $path = '', ?IStorage $storage = null): IScann if (!isset($this->scanner)) { $this->scanner = new ObjectStoreScanner($storage); } - /** @var \OC\Files\ObjectStore\ObjectStoreScanner */ + /** @var ObjectStoreScanner */ return $this->scanner; } @@ -352,9 +356,9 @@ public function fopen(string $path, string $mode) { 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 @@ public function fopen(string $path, string $mode) { 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 @@ public function writeStream(string $path, $stream, ?int $size = null): int { 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 @@ public function writeStream(string $path, $stream, ?int $size = null): int { $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 @@ public function writeStream(string $path, $stream, ?int $size = null): int { //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 @@ private function copyFile(ICacheEntry $sourceEntry, string $to) { $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 91eff90babb88..1c4acb1a32cb9 100644 --- a/lib/private/Files/ObjectStore/S3ObjectTrait.php +++ b/lib/private/Files/ObjectStore/S3ObjectTrait.php @@ -16,6 +16,7 @@ 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 @@ protected function writeMultiPart(string $urn, StreamInterface $stream, array $m '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 @@ protected function writeMultiPart(string $urn, StreamInterface $stream, array $m $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 c20efb346a17a..f170116a3a6e8 100644 --- a/lib/private/Files/ObjectStore/StorageObjectStore.php +++ b/lib/private/Files/ObjectStore/StorageObjectStore.php @@ -14,14 +14,9 @@ * 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 9006f29160d64..b1fb7e520dbd1 100644 --- a/lib/private/Files/ObjectStore/Swift.php +++ b/lib/private/Files/ObjectStore/Swift.php @@ -14,6 +14,10 @@ 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 @@ public function __construct($params, ?SwiftFactory $connectionFactory = null) { /** * @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 @@ public function getStorageId() { } 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 118724159e5b4..aef25b0c421ce 100644 --- a/lib/private/Files/ObjectStore/SwiftFactory.php +++ b/lib/private/Files/ObjectStore/SwiftFactory.php @@ -28,11 +28,7 @@ use Psr\Log\LoggerInterface; class SwiftFactory { - private $cache; - private $params; - /** @var Container|null */ - private $container = null; - private LoggerInterface $logger; + private ?Container $container = null; public const DEFAULT_OPTIONS = [ 'autocreate' => false, @@ -41,19 +37,19 @@ 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, + ) { } /** * Gets currently cached token id * - * @return string * @throws StorageAuthException */ - public function getCachedTokenId() { + public function getCachedTokenId(): string { if (!isset($this->params['cachedToken'])) { throw new StorageAuthException('Unauthenticated ObjectStore connection'); } @@ -97,10 +93,9 @@ private function cacheToken(Token $token, string $serviceUrl, string $cacheKey) } /** - * @return OpenStack * @throws StorageAuthException */ - private function getClient() { + private function getClient(): OpenStack { if (isset($this->params['bucket'])) { $this->params['container'] = $this->params['bucket']; } @@ -145,12 +140,9 @@ private function getClient() { } /** - * @param IdentityV2Service|IdentityV3Service $authService - * @param string $cacheKey - * @return OpenStack * @throws StorageAuthException */ - private function auth($authService, string $cacheKey) { + private function auth(IdentityV2Service|IdentityV3Service $authService, string $cacheKey): OpenStack { $this->params['identityService'] = $authService; $this->params['authUrl'] = $this->params['url']; @@ -214,11 +206,10 @@ private function auth($authService, string $cacheKey) { } /** - * @return \OpenStack\ObjectStore\v1\Models\Container * @throws StorageAuthException * @throws StorageNotAvailableException */ - public function getContainer() { + public function getContainer(): Container { if (is_null($this->container)) { $this->container = $this->createContainer(); } @@ -227,11 +218,10 @@ public function getContainer() { } /** - * @return \OpenStack\ObjectStore\v1\Models\Container * @throws StorageAuthException * @throws StorageNotAvailableException */ - private function createContainer() { + private function createContainer(): Container { $client = $this->getClient(); $objectStoreService = $client->objectStoreV1(); diff --git a/lib/private/Files/Search/SearchBinaryOperator.php b/lib/private/Files/Search/SearchBinaryOperator.php index 49f599933f44c..3424a044179b5 100644 --- a/lib/private/Files/Search/SearchBinaryOperator.php +++ b/lib/private/Files/Search/SearchBinaryOperator.php @@ -10,10 +10,6 @@ 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 592749cf4a0bc..9c1d7c5df78d2 100644 --- a/lib/private/Files/Search/SearchQuery.php +++ b/lib/private/Files/Search/SearchQuery.php @@ -12,76 +12,39 @@ 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. - * - * @param ISearchOperator $searchOperation - * @param int $limit - * @param int $offset - * @param array $order - * @param ?IUser $user - * @param bool $limitToHome + * @param ISearchOrder[] $order */ 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; } - /** - * @return ISearchOperator - */ - public function getSearchOperation() { + public function getSearchOperation(): ISearchOperator { return $this->searchOperation; } - /** - * @return int - */ - public function getLimit() { + public function getLimit(): int { return $this->limit; } - /** - * @return int - */ - public function getOffset() { + public function getOffset(): int { return $this->offset; } /** * @return ISearchOrder[] */ - public function getOrder() { + public function getOrder(): array { return $this->order; } - /** - * @return ?IUser - */ - public function getUser() { + public function getUser(): ?IUser { return $this->user; } diff --git a/lib/private/Files/SetupManager.php b/lib/private/Files/SetupManager.php index 3c0cdfe21236c..a1bc3417ce6fd 100644 --- a/lib/private/Files/SetupManager.php +++ b/lib/private/Files/SetupManager.php @@ -20,6 +20,7 @@ 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; @@ -47,6 +48,7 @@ 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; @@ -239,7 +241,7 @@ public function setupForUser(IUser $user): void { $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) { @@ -344,13 +346,9 @@ private function afterUserFullySetup(IUser $user, array $previouslySetupProvider * 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); @@ -663,7 +661,7 @@ public function setupForProvider(string $path, array $providers): void { } $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'); @@ -688,7 +686,7 @@ private function listenForNewMountProviders() { $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) { @@ -704,17 +702,17 @@ private function setupListeners() { // 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(InvalidateMountCacheEvent::class, function (InvalidateMountCacheEvent $event, - ) { + ): void { if ($user = $event->getUser()) { $this->cache->remove($user->getUID()); } else { @@ -730,7 +728,7 @@ private function setupListeners() { ]; 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 d0986592c0349..fbbe8a3902cf3 100644 --- a/lib/private/Files/SimpleFS/NewSimpleFile.php +++ b/lib/private/Files/SimpleFS/NewSimpleFile.php @@ -16,16 +16,12 @@ 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 +175,7 @@ public function getExtension(): string { * 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 +190,7 @@ public function read() { * 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 +198,7 @@ public function write() { 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 d9c1b47d2f19f..4f9911a9ce920 100644 --- a/lib/private/Files/SimpleFS/SimpleFile.php +++ b/lib/private/Files/SimpleFS/SimpleFile.php @@ -14,10 +14,9 @@ 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 @@ public function getExtension(): string { * 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 @@ public function read() { * 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 62f3db25e9be8..2f98370069873 100644 --- a/lib/private/Files/SimpleFS/SimpleFolder.php +++ b/lib/private/Files/SimpleFS/SimpleFolder.php @@ -14,16 +14,9 @@ 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 1a2aeb0e0210f..c46f499dd0900 100644 --- a/lib/private/Files/Storage/Common.php +++ b/lib/private/Files/Storage/Common.php @@ -19,15 +19,18 @@ 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\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 @@ public function isSharable(string $path): bool { 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 @@ public function getMimeType(string $path): string|false { 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; } @@ -345,7 +350,7 @@ public function getPropagator(?IStorage $storage = null): IPropagator { /** @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; } @@ -426,7 +431,7 @@ public function test(): bool { } public function free_space(string $path): int|float|false { - return \OCP\Files\FileInfo::SPACE_UNKNOWN; + return FileInfo::SPACE_UNKNOWN; } public function isLocal(): bool { @@ -467,7 +472,7 @@ public function verifyPath(string $path, string $fileName): void { } 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); } } @@ -599,7 +604,7 @@ public function getMetaData(string $path): ?array { } $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 da796130899fc..4bca8f90a38da 100644 --- a/lib/private/Files/Storage/CommonTest.php +++ b/lib/private/Files/Storage/CommonTest.php @@ -7,15 +7,14 @@ */ 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 + * Underlying local storage used for missing functions */ - private $storage; + private Local $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 2d166b5438da1..c1a293f89f3bd 100644 --- a/lib/private/Files/Storage/DAV.php +++ b/lib/private/Files/Storage/DAV.php @@ -24,6 +24,8 @@ 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; @@ -126,7 +128,7 @@ public function __construct(array $parameters) { $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 { @@ -163,12 +165,12 @@ protected function init(): void { } $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'); @@ -344,7 +346,7 @@ public function fopen(string $path, string $mode) { 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']); } @@ -370,7 +372,7 @@ public function fopen(string $path, string $mode) { 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 { @@ -392,7 +394,7 @@ public function fopen(string $path, string $mode) { $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); }); } @@ -784,7 +786,7 @@ protected function convertException(Exception $e, string $path = ''): void { $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 91b8071ac302e..6627437c0ec85 100644 --- a/lib/private/Files/Storage/Home.php +++ b/lib/private/Files/Storage/Home.php @@ -7,25 +7,23 @@ */ 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 { - /** - * @var string - */ - protected $id; - - /** - * @var \OC\User\User $user - */ - protected $user; +class Home extends Local implements IHomeStorage { + protected string $id; + protected IUser $user; /** * Construct a Home storage instance @@ -50,7 +48,7 @@ public function getCache(string $path = '', ?IStorage $storage = null): ICache { $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 +58,7 @@ public function getPropagator(?IStorage $storage = null): IPropagator { $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 260f9218a88e2..c15c644d85376 100644 --- a/lib/private/Files/Storage/Local.php +++ b/lib/private/Files/Storage/Local.php @@ -10,7 +10,10 @@ 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 @@ /** * 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 @@ public function filesize(string $path): int|float|false { } $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 @@ public function filemtime(string $path): int|false { 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 @@ public function free_space(string $path): int|float|false { } $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 @@ protected function searchInDir(string $query, string $dir = ''): array { $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 @@ private function canDoCrossStorageMove(IStorage $sourceStorage): bool { // 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 @@ public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalP // 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 @@ public function moveFromStorage(IStorage $sourceStorage, string $sourceInternalP // 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 fffc3e789f35b..5824189e3d8fc 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 @@ protected function toTmpFile(string $path): string|false { //no longer in the st } 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 2f6167ef85e4a..afb7334afd493 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 @@ protected function copyRecursive(string $source, string $target): bool { $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 603df7fe007b9..24efd3ecc1c45 100644 --- a/lib/private/Files/Storage/StorageFactory.php +++ b/lib/private/Files/Storage/StorageFactory.php @@ -11,6 +11,7 @@ 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 @@ public function removeStorageWrapper(string $wrapperName): void { */ 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 9d184e6a66069..7ae6bbe08beb7 100644 --- a/lib/private/Files/Storage/Wrapper/Availability.php +++ b/lib/private/Files/Storage/Wrapper/Availability.php @@ -11,6 +11,7 @@ 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 3e98be8e55300..08a60a127910b 100644 --- a/lib/private/Files/Storage/Wrapper/Encoding.php +++ b/lib/private/Files/Storage/Wrapper/Encoding.php @@ -9,6 +9,7 @@ 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 @@ public function hasUpdated(string $path, int $time): bool { 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 380ec0f253008..9673ba9575a81 100644 --- a/lib/private/Files/Storage/Wrapper/Encryption.php +++ b/lib/private/Files/Storage/Wrapper/Encryption.php @@ -18,6 +18,7 @@ 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 @@ protected function getHeader(string $path): array { * @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 3ce6e6bb3b6d3..125f5469f926e 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\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 @@ public function getPropagator(?IStorage $storage = null): IPropagator { 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 692824d00bdd5..885fbb259e088 100644 --- a/lib/private/Files/Storage/Wrapper/PermissionsMask.php +++ b/lib/private/Files/Storage/Wrapper/PermissionsMask.php @@ -9,6 +9,8 @@ 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 @@ public function fopen(string $path, string $mode) { } } - 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 @@ public function getMetaData(string $path): ?array { 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 d5454050fcb09..19fe9a6621e2d 100644 --- a/lib/private/Files/Storage/Wrapper/Wrapper.php +++ b/lib/private/Files/Storage/Wrapper/Wrapper.php @@ -23,9 +23,9 @@ 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 73297869f1271..8d33e7ebb1758 100644 --- a/lib/private/Files/Template/TemplateManager.php +++ b/lib/private/Files/Template/TemplateManager.php @@ -11,14 +11,17 @@ 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 @@ public function createFromTemplate(string $filePath, string $templateId = '', st } /** - * @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 @@ private function getTemplateFields(TemplateFileCreator $type, int $fileId): arra /** * @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 6af6ce1a0b1e4..8476172326045 100644 --- a/lib/private/Files/Type/Detection.php +++ b/lib/private/Files/Type/Detection.php @@ -12,6 +12,7 @@ use OCP\IBinaryFinder; use OCP\ITempManager; use OCP\IURLGenerator; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -245,7 +246,7 @@ public function detectContent(string $path): string { } } - $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 @@ public function detectString($data): string { } } - $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 576cb66b3cf9f..4c98f5d0f470b 100644 --- a/lib/private/Files/Utils/Scanner.php +++ b/lib/private/Files/Utils/Scanner.php @@ -9,6 +9,7 @@ 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\IDBConnection; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -44,43 +46,24 @@ 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 - * - * @var bool */ - protected $useTransaction; + protected bool $useTransaction; /** * Number of entries scanned to commit - * - * @var int */ - protected $entriesToCommit; + protected int $entriesToCommit = 0; - /** - * @param string $user - * @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 string $user, + protected ?IDBConnection $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 +89,28 @@ protected function getMounts($dir) { /** * 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 +136,13 @@ public function backgroundScan($dir) { $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 +217,15 @@ public function scan($dir = '', $recursive = \OC\Files\Cache\Scanner::SCAN_RECUR $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 4eb40b58c2af3..b24d319677023 100644 --- a/lib/private/Files/View.php +++ b/lib/private/Files/View.php @@ -8,13 +8,17 @@ namespace OC\Files; use Icewind\Streams\CallbackWrapper; +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; @@ -27,10 +31,16 @@ 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; @@ -39,6 +49,7 @@ use OCP\Server; use OCP\Share\IManager; use OCP\Share\IShare; +use OCP\Util; use Psr\Log\LoggerInterface; /** @@ -76,10 +87,10 @@ public function __construct(string $root = '') { } $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); } /** @@ -175,7 +186,7 @@ public function getMount($path): IMountPoint { * 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); @@ -388,7 +399,7 @@ public function readfile($path) { * @param int $to * @return bool|mixed * @throws InvalidPathException - * @throws \OCP\Files\UnseekableException + * @throws UnseekableException */ public function readfilePart($path, $from, $to) { $this->assertPathLength($path); @@ -432,7 +443,7 @@ public function readfilePart($path, $from, $to) { return ftell($handle) - $from; } - throw new \OCP\Files\UnseekableException('fseek error'); + throw new UnseekableException('fseek error'); } return false; } @@ -712,7 +723,7 @@ public function rename($source, $target, array $options = []) { } /** @var IMountManager $mountManager */ - $mountManager = \OC::$server->get(IMountManager::class); + $mountManager = Server::get(IMountManager::class); $targetParts = explode('/', $absolutePath2); $targetUser = $targetParts[1] ?? null; @@ -741,7 +752,7 @@ public function rename($source, $target, array $options = []) { $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)) { @@ -782,7 +793,7 @@ public function rename($source, $target, array $options = []) { $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); @@ -806,7 +817,7 @@ public function rename($source, $target, array $options = []) { $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) { @@ -821,7 +832,7 @@ public function rename($source, $target, array $options = []) { $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); } @@ -863,7 +874,7 @@ private function validateMountMove(array $mounts, IMountPoint $sourceMount, IMou $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) { @@ -1055,7 +1066,7 @@ public function toTmpFile($path): string|false { $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 { @@ -1238,7 +1249,7 @@ private function basicOperation(string $operation, string $path, array $hooks = $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)) { @@ -1281,7 +1292,7 @@ private function getHookPath($path): ?string { } private function shouldEmitHooks(string $path = ''): bool { - if ($path && Cache\Scanner::isPartialFile($path)) { + if ($path && Scanner::isPartialFile($path)) { return false; } if (!Filesystem::$loaded) { @@ -1382,9 +1393,9 @@ private function getCacheEntry($storage, $internalPath, $relativePath) { } // 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()); @@ -1404,7 +1415,7 @@ private function getCacheEntry($storage, $internalPath, $relativePath) { * @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); @@ -1421,7 +1432,7 @@ public function getFileInfo($path, $includeMountPoints = true) { $data = $this->getCacheEntry($storage, $internalPath, $relativePath); if (!$data instanceof ICacheEntry) { - if (Cache\Scanner::isPartialFile($relativePath)) { + if (Scanner::isPartialFile($relativePath)) { return $this->getPartFileInfo($relativePath); } @@ -1429,7 +1440,7 @@ public function getFileInfo($path, $includeMountPoints = true) { } if ($mount instanceof MoveableMount && $internalPath === '') { - $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE; + $data['permissions'] |= Constants::PERMISSION_DELETE; } if ($internalPath === '' && $data['name']) { $data['name'] = basename($path); @@ -1510,17 +1521,14 @@ public function getDirectoryContent($directory, $mimetype_filter = '', ?\OCP\Fil $folderId = $data->getId(); $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter - $sharingDisabled = \OCP\Util::isSharingDisabledForUser(); + $sharingDisabled = Util::isSharingDisabledForUser(); $fileNames = array_map(function (ICacheEntry $content) { return $content->getName(); }, $contents); - /** - * @var \OC\Files\FileInfo[] $fileInfos - */ - $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) { + $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled): FileInfo { if ($sharingDisabled) { - $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE; + $content['permissions'] = $content['permissions'] & ~Constants::PERMISSION_SHARE; } $ownerId = $storage->getOwner($content['path']); if ($ownerId !== false) { @@ -1553,9 +1561,9 @@ public function getDirectoryContent($directory, $mimetype_filter = '', ?\OCP\Fil $subScanner = $subStorage->getScanner(); try { $subScanner->scanFile(''); - } catch (\OCP\Files\StorageNotAvailableException $e) { + } catch (StorageNotAvailableException $e) { continue; - } catch (\OCP\Files\StorageInvalidException $e) { + } catch (StorageInvalidException $e) { continue; } catch (\Exception $e) { // sometimes when the storage is not available it can be any exception @@ -1609,16 +1617,16 @@ public function getDirectoryContent($directory, $mimetype_filter = '', ?\OCP\Fil // 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(''); @@ -1671,7 +1679,7 @@ public function putFileInfo($path, $data) { 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); @@ -1733,7 +1741,7 @@ private function searchCommon($method, $args) { $mount = $this->getMount(''); $mountPoint = $mount->getMountPoint(); $storage = $mount->getStorage(); - $userManager = \OC::$server->getUserManager(); + $userManager = Server::get(IUserManager::class); if ($storage) { $cache = $storage->getCache(''); @@ -1827,7 +1835,7 @@ public function getETag($path) { */ 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) { @@ -1906,7 +1914,7 @@ private function targetIsNotShared(string $user, string $targetPath): bool { /** * 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)); @@ -1928,7 +1936,7 @@ private function getPartFileInfo(string $path): \OC\Files\FileInfo { 'size' => $storage->filesize($internalPath), 'mtime' => $storage->filemtime($internalPath), 'encrypted' => false, - 'permissions' => \OCP\Constants::PERMISSION_ALL + 'permissions' => Constants::PERMISSION_ALL ], $mount, $owner @@ -1944,15 +1952,15 @@ private function getPartFileInfo(string $path): \OC\Files\FileInfo { 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')); } - // Short cut for read-only validation + // Shortcut for read-only validation 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; @@ -1963,19 +1971,19 @@ public function verifyPath($path, $fileName, $readonly = false): void { [$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')); } } @@ -2245,7 +2253,7 @@ public function getPathRelativeToFiles($absolutePath) { /** * @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 a51447393ed75..2a46c7bee57fe 100644 --- a/lib/private/FullTextSearch/Model/IndexDocument.php +++ b/lib/private/FullTextSearch/Model/IndexDocument.php @@ -30,8 +30,6 @@ * @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 2f729c2702ee1..76753f781625e 100644 --- a/lib/private/GlobalScale/Config.php +++ b/lib/private/GlobalScale/Config.php @@ -7,37 +7,21 @@ namespace OC\GlobalScale; use OCP\IConfig; +use Override; 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 readonly IConfig $config, + ) { } - /** - * check if global scale is enabled - * - * @since 12.0.1 - * @return bool - */ - public function isGlobalScaleEnabled() { + #[Override] + public function isGlobalScaleEnabled(): bool { return $this->config->getSystemValueBool('gs.enabled', false); } - /** - * check if federation should only be used internally in a global scale setup - * - * @since 12.0.1 - * @return bool - */ - public function onlyInternalFederation() { + #[Override] + public function onlyInternalFederation(): bool { // if global scale is disabled federation works always globally $gsEnabled = $this->isGlobalScaleEnabled(); if ($gsEnabled === false) { diff --git a/lib/private/Group/Backend.php b/lib/private/Group/Backend.php index f4a90018b5a98..011ff986143f9 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 62a3990c31999..190eb37348b61 100644 --- a/lib/private/Group/Database.php +++ b/lib/private/Group/Database.php @@ -25,6 +25,7 @@ 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 @@ public function __construct( */ private function fixDI() { if ($this->dbConn === null) { - $this->dbConn = \OC::$server->getDatabaseConnection(); + $this->dbConn = Server::get(IDBConnection::class); } } @@ -411,7 +412,7 @@ public function searchInGroup(string $gid, string $search = '', int $limit = -1, $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 fef8d40a05fc4..8108b3597261d 100644 --- a/lib/private/Group/DisplayNameCache.php +++ b/lib/private/Group/DisplayNameCache.php @@ -25,12 +25,13 @@ 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 a6bb192390f4a..18263b18807c1 100644 --- a/lib/private/Group/Group.php +++ b/lib/private/Group/Group.php @@ -9,11 +9,16 @@ 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,22 @@ 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[] */ - 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; + /** @var User[] */ + private array $users = []; + private bool $usersLoaded = false; + + 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 +90,7 @@ public function setDisplayName(string $displayName): bool { /** * get all users in the group * - * @return \OC\User\User[] + * @return array */ public function getUsers(): array { if ($this->usersLoaded) { @@ -158,6 +149,7 @@ public function addUser(IUser $user): void { } 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 +174,7 @@ public function removeUser(IUser $user): void { } 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 +206,7 @@ public function searchUsers(string $search, ?int $limit = null, ?int $offset = n $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 +230,7 @@ public function count($search = ''): int|bool { $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 +311,7 @@ public function delete(): bool { } foreach ($this->backends as $backend) { if ($backend->implementsActions(\OC\Group\Backend::DELETE_GROUP)) { + /** @var IDeleteGroupBackend $backend */ $result = $result || $backend->deleteGroup($this->gid); } } @@ -332,7 +327,7 @@ public function delete(): bool { /** * 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 f4bbeea3d69bb..e3097e3d7cac0 100644 --- a/lib/private/Group/Manager.php +++ b/lib/private/Group/Manager.php @@ -9,6 +9,8 @@ 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\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; @@ -41,19 +45,13 @@ */ class Manager extends PublicEmitter implements IGroupManager { /** @var GroupInterface[] */ - private $backends = []; - + private array $backends = []; /** @var array */ - private $cachedGroups = []; - + private array $cachedGroups = []; /** @var array> */ - private $cachedUserGroups = []; - - /** @var \OC\SubAdmin */ - private $subAdmin = null; - + private array $cachedUserGroups = []; + private ?SubAdmin $subAdmin = null; private DisplayNameCache $displayNameCache; - private const MAX_GROUP_LENGTH = 255; public function __construct( @@ -96,7 +94,7 @@ public function isBackendUsed($backendClass) { } /** - * @param \OCP\GroupInterface $backend + * @param GroupInterface $backend */ public function addBackend($backend) { $this->backends[] = $backend; @@ -111,7 +109,7 @@ public function clearBackends() { /** * Get the active backends * - * @return \OCP\GroupInterface[] + * @return GroupInterface[] */ public function getBackends() { return $this->backends; @@ -137,7 +135,7 @@ public function get($gid) { /** * @param string $gid * @param string $displayName - * @return \OCP\IGroup|null + * @return IGroup|null */ protected function getGroupObject($gid, $displayName = null) { $backends = []; @@ -181,7 +179,7 @@ protected function getGroupsObjects(array $gids, array $displayNames = []): arra } 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 +279,9 @@ public function search(string $search, ?int $limit = null, ?int $offset = 0) { /** * @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 +290,7 @@ public function getUserGroups(?IUser $user = null) { /** * @param string $uid the user id - * @return \OC\Group\Group[] + * @return array */ public function getUserIdGroups(string $uid): array { $groups = []; @@ -334,10 +332,10 @@ public function isDelegatedAdmin(string $userId): bool { } // 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 +444,14 @@ public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0 } /** - * @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 a50722d55416c..5c3535de54a14 100644 --- a/lib/private/Http/Client/Client.php +++ b/lib/private/Http/Client/Client.php @@ -28,26 +28,14 @@ * @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 { @@ -64,7 +52,7 @@ private function buildRequestOptions(array $options): array { \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 a505dff9aa20c..1e40ef31bc153 100644 --- a/lib/private/Http/Client/ClientService.php +++ b/lib/private/Http/Client/ClientService.php @@ -28,43 +28,26 @@ * @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; } - /** - * @return Client - */ public function newClient(): IClient { $handler = new CurlHandler(); $stack = HandlerStack::create($handler); 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 03a9ed9a5996b..7d1e1e1911274 100644 --- a/lib/private/Http/Client/GuzzlePromiseAdapter.php +++ b/lib/private/Http/Client/GuzzlePromiseAdapter.php @@ -46,7 +46,7 @@ public function then( ?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 @@ public function then( } 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 1e4cb3b8fa2ce..460b5251a5263 100644 --- a/lib/private/Http/Client/Response.php +++ b/lib/private/Http/Client/Response.php @@ -12,12 +12,10 @@ use Psr\Http\Message\ResponseInterface; class Response implements IResponse { - private ResponseInterface $response; - private bool $stream; - - public function __construct(ResponseInterface $response, bool $stream = false) { - $this->response = $response; - $this->stream = $stream; + public function __construct( + private ResponseInterface $response, + private bool $stream = false, + ) { } public function getBody() { diff --git a/lib/private/Http/WellKnown/RequestManager.php b/lib/private/Http/WellKnown/RequestManager.php index 3624bf73962e9..11d5d388f351d 100644 --- a/lib/private/Http/WellKnown/RequestManager.php +++ b/lib/private/Http/WellKnown/RequestManager.php @@ -22,31 +22,19 @@ 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 f2e7b7a78b2be..d135002952211 100644 --- a/lib/private/Installer.php +++ b/lib/private/Installer.php @@ -29,6 +29,7 @@ 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 @@ public function installApp(string $appId, bool $forceEnable = false): string { $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 f6d4c7afd4a5e..1d44ed2ebc0e6 100644 --- a/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php +++ b/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php @@ -8,6 +8,9 @@ */ namespace OC\IntegrityCheck\Iterator; +use OCP\IConfig; +use OCP\Server; + class ExcludeFoldersByPathFilterIterator extends \RecursiveFilterIterator { private $excludedFolders; @@ -32,7 +35,7 @@ public function __construct(\RecursiveIterator $iterator, $root = '') { 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 cd257cf1b12d5..da8260d19875d 100644 --- a/lib/private/KnownUser/KnownUserService.php +++ b/lib/private/KnownUser/KnownUserService.php @@ -9,13 +9,12 @@ namespace OC\KnownUser; class KnownUserService { - /** @var KnownUserMapper */ - protected $mapper; - /** @var array */ - protected $knownUsers = []; + /** @var array> $knownUsers */ + protected array $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 27d29eb3b356e..d8ab646c61911 100644 --- a/lib/private/L10N/Factory.php +++ b/lib/private/L10N/Factory.php @@ -13,6 +13,7 @@ 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 @@ public function __construct( * @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 16bdf88499359..9011183926f73 100644 --- a/lib/private/L10N/L10N.php +++ b/lib/private/L10N/L10N.php @@ -10,42 +10,27 @@ 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; + private ?IdentityTranslator $identityTranslator = null; /** @var string[] */ - private $translations = []; + private array $translations = []; /** - * @param IFactory $factory - * @param string $app - * @param string $lang - * @param string $locale - * @param array $files + * @param string[] $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 string $app, + protected string $lang, + protected ?string $locale, + array $files, + ) { foreach ($files as $languageFile) { $this->load($languageFile); } @@ -66,7 +51,7 @@ public function getLanguageCode(): string { * @return string locale */ public function getLocaleCode(): string { - return $this->locale; + return $this->locale ?? ''; } /** @@ -215,7 +200,7 @@ protected function load(string $translationFile): bool { $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 a6515e78f242d..2bd4f123025e6 100644 --- a/lib/private/L10N/L10NString.php +++ b/lib/private/L10N/L10NString.php @@ -8,29 +8,15 @@ 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 string|array $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 531eea5866bb9..195de54ae4b04 100644 --- a/lib/private/L10N/LanguageIterator.php +++ b/lib/private/L10N/LanguageIterator.php @@ -13,15 +13,12 @@ use OCP\L10N\ILanguageIterator; class LanguageIterator implements ILanguageIterator { - private $i = 0; - /** @var IConfig */ - private $config; - /** @var IUser */ - private $user; + private int $i = 0; - 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 0d72f63863241..b93e0596b7971 100644 --- a/lib/private/L10N/LazyL10N.php +++ b/lib/private/L10N/LazyL10N.php @@ -11,15 +11,11 @@ use OCP\IL10N; class LazyL10N implements IL10N { - /** @var IL10N */ - private $l; + private ?IL10N $l = null; - /** @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 fa4c72da75626..e5c367bac5e43 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 @@ public function getFileSize(string $filename): int|float { * 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 @@ public function getFileSizeViaCurl(string $fileName): null|int|float { * 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 @@ public function getFileMtime(string $fullPath): int { $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 5a27c5d5c6e9e..dde483d7225d0 100644 --- a/lib/private/Lockdown/Filesystem/NullCache.php +++ b/lib/private/Lockdown/Filesystem/NullCache.php @@ -8,6 +8,7 @@ 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 @@ public function getFolderContentsById($fileId) { } 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 @@ public function inCache($file) { } 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 @@ public function normalize($path) { } 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 d10763287c8a6..727259319edaf 100644 --- a/lib/private/Lockdown/Filesystem/NullStorage.php +++ b/lib/private/Lockdown/Filesystem/NullStorage.php @@ -9,6 +9,7 @@ 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 @@ public function getId(): string { } 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 @@ public function is_file(string $path): bool { } 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 @@ public function filetype(string $path): string|false { } 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 @@ public function filemtime(string $path): int|false { } 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 @@ public function free_space(string $path): int { } 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 @@ public function getDirectDownloadById(string $fileId): array|false { } 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 cbdd0f767ad80..45f4589df6730 100644 --- a/lib/private/Log.php +++ b/lib/private/Log.php @@ -20,6 +20,7 @@ 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 @@ public function getLogLevel(array $context, string $message): int { // 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 @@ public function getLogLevel(array $context, string $message): int { } 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 @@ public function getLogLevel(array $context, string $message): int { } 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') @@ -436,7 +437,7 @@ protected function getSerializer(): ExceptionSerializer { $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 ba428ba185b39..580656ee55a39 100644 --- a/lib/private/Log/File.php +++ b/lib/private/Log/File.php @@ -19,17 +19,14 @@ */ 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 ee6054b81f8fd..58c4f433ca6c5 100644 --- a/lib/private/Log/LogFactory.php +++ b/lib/private/Log/LogFactory.php @@ -8,6 +8,7 @@ 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 @@ public function __construct( } /** - * @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 ee1593b87acf6..b433d302ccc41 100644 --- a/lib/private/Log/Rotate.php +++ b/lib/private/Log/Rotate.php @@ -11,6 +11,7 @@ use OCP\BackgroundJob\TimedJob; use OCP\IConfig; use OCP\Log\RotationTrait; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -29,14 +30,14 @@ public function __construct(ITimeFactory $time) { } 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 08efdd282243d..3ba19162546de 100644 --- a/lib/private/Mail/Mailer.php +++ b/lib/private/Mail/Mailer.php @@ -21,6 +21,8 @@ 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 @@ public function send(IMessage $message): array { } 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 @@ public function send(IMessage $message): array { $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 @@ public function send(IMessage $message): array { $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 @@ protected function getSendMailInstance(): SendmailTransport { $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 523a4836760c8..097af11e24c62 100644 --- a/lib/private/Mail/Message.php +++ b/lib/private/Mail/Message.php @@ -75,7 +75,7 @@ protected function convertAddresses(array $addresses): array { 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 6bb2799d723c3..324218797e5ac 100644 --- a/lib/private/Memcache/APCu.php +++ b/lib/private/Memcache/APCu.php @@ -9,6 +9,7 @@ use bantu\IniGetWrapper\IniGetWrapper; use OCP\IMemcache; +use OCP\Server; class APCu extends Cache implements IMemcache { use CASTrait { @@ -111,9 +112,9 @@ public function cas($key, $old, $new) { 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 774769b25fe5c..48013e2fe6bda 100644 --- a/lib/private/Memcache/Cache.php +++ b/lib/private/Memcache/Cache.php @@ -7,20 +7,15 @@ */ namespace OC\Memcache; +use OCP\ICache; + /** * @template-implements \ArrayAccess */ -abstract class Cache implements \ArrayAccess, \OCP\ICache { - /** - * @var string $prefix - */ - protected $prefix; - - /** - * @param string $prefix - */ - public function __construct($prefix = '') { - $this->prefix = $prefix; +abstract class Cache implements \ArrayAccess, ICache { + public function __construct( + protected string $prefix = '', + ) { } /** diff --git a/lib/private/Memcache/Factory.php b/lib/private/Memcache/Factory.php index 23e0550f62eeb..e083a357cbac9 100644 --- a/lib/private/Memcache/Factory.php +++ b/lib/private/Memcache/Factory.php @@ -9,11 +9,13 @@ 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 @@ public function __construct( // 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 @@ public function __construct( // 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 @@ public function __construct( 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 @@ public function withServerVersionPrefix(\Closure $closure): void { $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 c2a06731910a8..a25185eb8c430 100644 --- a/lib/private/Memcache/LoggerWrapperCache.php +++ b/lib/private/Memcache/LoggerWrapperCache.php @@ -14,29 +14,18 @@ * Cache wrapper that logs the cache operation in a log file */ 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( + protected Redis $wrappedCache, + private string $logFile, + ) { parent::__construct($wrappedCache->getPrefix()); - $this->wrappedCache = $wrappedCache; - $this->logFile = $logFile; } - /** - * @return string Prefix used for caching purposes - */ - public function getPrefix() { + public function getPrefix(): string { return $this->prefix; } - protected function getNameSpace() { + protected function getNameSpace(): string { return $this->prefix; } diff --git a/lib/private/Memcache/Memcached.php b/lib/private/Memcache/Memcached.php index ba63b3a48d907..044a0fccd2512 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 @@ public function __construct($prefix = '') { $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 @@ public function __construct($prefix = '') { 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 eac1e6ddadc15..11c17309b8750 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 97d9d828a32d3..c9fb77885b4c6 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 f8c51570c4fc6..1611d428f3016 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 @@ public function __construct($prefix = '', string $logFile = '') { */ 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 @@ public function compareSetTTL(string $key, mixed $value, int $ttl): bool { } 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 0fc5d31080105..334fa4bc75342 100644 --- a/lib/private/Memcache/WithLocalCache.php +++ b/lib/private/Memcache/WithLocalCache.php @@ -13,11 +13,12 @@ * 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 09c043764a7a4..240d4de637a1e 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 @@ public function __construct($injectedCollator = null) { // 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 @@ private function getCollator() { 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 @@ public function compare($a, $b) { /** * 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 fb0795376bbb5..20d2d666d9581 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; @@ -20,59 +19,39 @@ use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Navigation\Events\LoadAdditionalEntriesEvent; +use Override; use Psr\Log\LoggerInterface; /** - * Manages the ownCloud navigation + * Manages the Nextcloud navigation + * @psalm-import-type NavigationEntry from INavigationManager + * @psalm-import-type NavigationEntryOutput from INavigationManager */ - class NavigationManager implements INavigationManager { - protected $entries = []; - protected $closureEntries = []; - protected $activeEntry; - protected $unreadCounters = []; - - /** @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; + /** @var array */ + protected array $entries = []; + /** @var list */ + protected array $closureEntries = []; + protected ?string $activeEntry = null; + protected array $unreadCounters = []; + protected bool $init = false; /** 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; } - /** - * @inheritDoc - */ - public function add($entry) { + #[Override] + public function add(array|callable $entry): void { if ($entry instanceof \Closure) { $this->closureEntries[] = $entry; return; @@ -109,7 +88,7 @@ public function add($entry) { $this->updateDefaultEntries(); } - private function updateDefaultEntries() { + private function updateDefaultEntries(): void { $defaultEntryId = $this->getDefaultEntryIdForUser($this->userSession->getUser(), false); foreach ($this->entries as $id => $entry) { if ($entry['type'] === 'link') { @@ -118,9 +97,7 @@ private function updateDefaultEntries() { } } - /** - * @inheritDoc - */ + #[Override] public function getAll(string $type = 'link'): array { $this->init(); @@ -137,8 +114,8 @@ public function getAll(string $type = 'link'): array { /** * Sort navigation entries default app is always sorted first, then by order, name and set active flag * - * @param array $list - * @return array + * @param array $list + * @return array */ private function proceedNavigation(array $list, string $type): array { uasort($list, function ($a, $b) { @@ -159,7 +136,7 @@ private function proceedNavigation(array $list, string $type): array { if ($type === 'all' || $type === 'link') { // There might be the case that no default app was set, in this case the first app is the default app. - // Otherwise the default app is already the ordered first, so setting the default prop will make no difference. + // Otherwise, the default app is already the ordered first, so setting the default prop will make no difference. foreach ($list as $index => &$navEntry) { if ($navEntry['type'] === 'link') { $navEntry['default'] = true; @@ -188,23 +165,19 @@ private function proceedNavigation(array $list, string $type): array { /** * removes all the entries */ - public function clear($loadDefaultLinks = true) { + public function clear(bool $loadDefaultLinks = true): void { $this->entries = []; $this->closureEntries = []; $this->init = !$loadDefaultLinks; } - /** - * @inheritDoc - */ - public function setActiveEntry($appId) { + #[Override] + public function setActiveEntry(string $appId): void { $this->activeEntry = $appId; } - /** - * @inheritDoc - */ - public function getActiveEntry() { + #[Override] + public function getActiveEntry(): ?string { return $this->activeEntry; } @@ -400,7 +373,7 @@ private function init(bool $resolveClosures = true): void { } } - private function isAdmin() { + private function isAdmin(): bool { $user = $this->userSession->getUser(); if ($user !== null) { return $this->groupManager->isAdmin($user->getUID()); @@ -408,23 +381,26 @@ private function isAdmin() { return false; } - private function isSubadmin() { + private function isSubadmin(): bool { $user = $this->userSession->getUser(); - if ($user !== null) { + if ($user !== null && $this->groupManager instanceof Manager) { return $this->groupManager->getSubAdmin()->isSubAdmin($user); } return false; } + #[Override] public function setUnreadCounter(string $id, int $unreadCounter): void { $this->unreadCounters[$id] = $unreadCounter; } + #[Override] public function get(string $id): ?array { $this->init(); return $this->entries[$id]; } + #[Override] public function getDefaultEntryIdForUser(?IUser $user = null, bool $withFallbacks = true): string { $this->init(); // Disable fallbacks here, as we need to override them with the user defaults if none are configured. @@ -466,6 +442,7 @@ public function getDefaultEntryIdForUser(?IUser $user = null, bool $withFallback return $withFallbacks ? 'files' : ''; } + #[Override] public function getDefaultEntryIds(bool $withFallbacks = true): array { $this->init(); $storedIds = explode(',', $this->config->getSystemValueString('defaultapp', $withFallbacks ? 'dashboard,files' : '')); @@ -480,6 +457,7 @@ public function getDefaultEntryIds(bool $withFallbacks = true): array { return array_filter($ids); } + #[Override] public function setDefaultEntryIds(array $ids): void { $this->init(); $entryIds = array_keys($this->entries); diff --git a/lib/private/Notification/Manager.php b/lib/private/Notification/Manager.php index 62fa66df85cd6..6247f0484df63 100644 --- a/lib/private/Notification/Manager.php +++ b/lib/private/Notification/Manager.php @@ -9,6 +9,7 @@ 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\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 @@ public function __construct( 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 @@ protected function getApps(): array { 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 @@ public function getNotifiers(): array { $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 @@ public function getNotifiers(): array { 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 402b6b7059d0c..3af70b7005722 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 a3d5fbfd4ec2e..9585b8a1f39f6 100644 --- a/lib/private/Preview/Bitmap.php +++ b/lib/private/Preview/Bitmap.php @@ -10,6 +10,8 @@ use Imagick; use OCP\Files\File; use OCP\IImage; +use OCP\Image; +use OCP\Server; use Psr\Log\LoggerInterface; /** @@ -36,7 +38,7 @@ abstract protected function getAllowedMimeTypes(): string; 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 @@ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { 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 @@ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { $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 6100e8262a4ba..39070bd6848bb 100644 --- a/lib/private/Preview/Bundled.php +++ b/lib/private/Preview/Bundled.php @@ -9,6 +9,9 @@ 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 @@ protected function extractThumbnail(File $file, string $path): ?IImage { 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 @@ protected function extractThumbnail(File $file, string $path): ?IImage { $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 8980e0b2d002a..a34b6dc7046dd 100644 --- a/lib/private/Preview/Generator.php +++ b/lib/private/Preview/Generator.php @@ -19,6 +19,7 @@ use OCP\Files\SimpleFS\ISimpleFile; use OCP\IConfig; use OCP\IImage; +use OCP\Image; use OCP\IPreview; use OCP\IStreamImage; use OCP\Preview\BeforePreviewFetchedEvent; @@ -188,7 +189,7 @@ public function generatePreviews(File $file, array $specifications, ?string $mim // 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 64eb48e58dfa8..f2b6cc7254e27 100644 --- a/lib/private/Preview/HEIC.php +++ b/lib/private/Preview/HEIC.php @@ -12,6 +12,7 @@ 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 @@ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { $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 @@ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { $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 78a402c636a1d..25c74b5fdef04 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 d421da74ac824..bd5645d417e8e 100644 --- a/lib/private/Preview/Imaginary.php +++ b/lib/private/Preview/Imaginary.php @@ -12,8 +12,9 @@ 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 add0028738e90..dd3e809a7dede 100644 --- a/lib/private/Preview/MP3.php +++ b/lib/private/Preview/MP3.php @@ -9,6 +9,7 @@ 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 @@ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { } 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 c20433a1ac0e4..d8ae8c48ea9cc 100644 --- a/lib/private/Preview/MarkDown.php +++ b/lib/private/Preview/MarkDown.php @@ -9,6 +9,7 @@ use OCP\Files\File; use OCP\IImage; +use OCP\Image; class MarkDown extends TXT { /** @@ -119,7 +120,7 @@ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { } } - $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 91857effbe1e0..e3a5bf4868dc4 100644 --- a/lib/private/Preview/Movie.php +++ b/lib/private/Preview/Movie.php @@ -12,6 +12,7 @@ use OCP\Files\FileInfo; use OCP\IConfig; use OCP\IImage; +use OCP\Image; use OCP\ITempManager; use OCP\Server; use Psr\Log\LoggerInterface; @@ -321,7 +322,7 @@ private function generateThumbNail(int $maxX, int $maxY, string $absPath, int $s ); 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 ffba0211de2be..c67e4829db85f 100644 --- a/lib/private/Preview/Office.php +++ b/lib/private/Preview/Office.php @@ -10,6 +10,7 @@ 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 @@ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { $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 556d1099d2da7..9e1a6fcefcd65 100644 --- a/lib/private/Preview/ProviderV2.php +++ b/lib/private/Preview/ProviderV2.php @@ -46,7 +46,7 @@ public function isAvailable(FileInfo $file): bool { * @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 d9f7701f411c4..be9b88fcc40fd 100644 --- a/lib/private/Preview/SVG.php +++ b/lib/private/Preview/SVG.php @@ -9,6 +9,8 @@ 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 @@ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { $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 @@ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { } //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 1a1d64f3e0887..2d407d88b56b7 100644 --- a/lib/private/Preview/TXT.php +++ b/lib/private/Preview/TXT.php @@ -10,6 +10,7 @@ use OCP\Files\File; use OCP\Files\FileInfo; use OCP\IImage; +use OCP\Image; class TXT extends ProviderV2 { /** @@ -81,7 +82,7 @@ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { } } - $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 c34dd1dde4d96..1331cd670d05d 100644 --- a/lib/private/Preview/WatcherConnector.php +++ b/lib/private/Preview/WatcherConnector.php @@ -13,8 +13,11 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\IRootFolder; use OCP\Files\Node; +use OCP\Server; class WatcherConnector { + private ?Watcher $watcher = null; + public function __construct( private IRootFolder $root, private SystemConfig $config, @@ -23,17 +26,21 @@ public function __construct( } private function getWatcher(): Watcher { - return \OCP\Server::get(Watcher::class); + if ($this->watcher !== null) { + return $this->watcher; + } + $this->watcher = Server::get(Watcher::class); + return $this->watcher; } 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 0e764100ad1c4..a972d36d94762 100644 --- a/lib/private/PreviewManager.php +++ b/lib/private/PreviewManager.php @@ -9,13 +9,44 @@ 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\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; @@ -34,11 +65,7 @@ * @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; /** @@ -50,40 +77,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); } /** @@ -205,7 +218,7 @@ public function isMimeSupported(string $mimeType = '*'): bool { 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; } @@ -249,22 +262,22 @@ protected function getEnabledDefaultProvider(): array { } $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)); @@ -293,33 +306,33 @@ protected function registerCoreProviders(): void { } $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) { @@ -337,7 +350,7 @@ protected function registerCoreProviders(): void { $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'); @@ -345,19 +358,19 @@ protected function registerCoreProviders(): void { 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 0a62365e901f9..55f261aed6874 100644 --- a/lib/private/Profiler/BuiltInProfiler.php +++ b/lib/private/Profiler/BuiltInProfiler.php @@ -11,6 +11,7 @@ use DateTime; use OCP\IConfig; use OCP\IRequest; +use OCP\Server; class BuiltInProfiler { private \ExcimerProfiler $excimer; @@ -64,7 +65,7 @@ public function handleShutdown(): void { 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 4fa056b0009cc..1636b9d60651e 100644 --- a/lib/private/Profiler/FileProfilerStorage.php +++ b/lib/private/Profiler/FileProfilerStorage.php @@ -14,9 +14,6 @@ * 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, @@ -33,11 +30,12 @@ class FileProfilerStorage { * * Example : "file:/path/to/the/storage/folder" * + * @param string $folder Folder where profiler data are stored. * @throws \RuntimeException */ - public function __construct(string $folder) { - $this->folder = $folder; - + public function __construct( + 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 c611d79e25938..d823a7c8327b7 100644 --- a/lib/private/Profiler/Profile.php +++ b/lib/private/Profiler/Profile.php @@ -12,8 +12,6 @@ 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 c8952c76a38c7..47d4af1149cd6 100644 --- a/lib/private/Profiler/RoutingDataCollector.php +++ b/lib/private/Profiler/RoutingDataCollector.php @@ -14,14 +14,11 @@ 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 29d45ace69625..4c8160d81d1f1 100644 --- a/lib/private/RedisFactory.php +++ b/lib/private/RedisFactory.php @@ -13,24 +13,15 @@ class RedisFactory { public const REDIS_MINIMAL_VERSION = '4.0.0'; public const REDIS_EXTRA_PARAMETERS_MINIMAL_VERSION = '5.3.0'; - /** @var \Redis|\RedisCluster */ - private $instance; + private \Redis|\RedisCluster|null $instance = null; - 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() { + private function create(): void { $isCluster = in_array('redis.cluster', $this->config->getKeys(), true); $config = $isCluster ? $this->config->getValue('redis.cluster', []) @@ -124,10 +115,9 @@ private function create() { * Get the ssl context config * * @param array $config the current config - * @return array|null * @throws \UnexpectedValueException */ - private function getSslContext($config) { + private function getSslContext(array $config): ?array { if (isset($config['ssl_context'])) { if (!$this->isConnectionParametersSupported()) { throw new \UnexpectedValueException(\sprintf( @@ -140,14 +130,18 @@ private function getSslContext($config) { return null; } - public function getInstance() { + public function getInstance(): \Redis|\RedisCluster { if (!$this->isAvailable()) { throw new \Exception('Redis support is not available'); } - if (!$this->instance instanceof \Redis) { + if ($this->instance === null) { $this->create(); } + if ($this->instance === null) { + throw new \Exception('Redis support is not available'); + } + return $this->instance; } diff --git a/lib/private/Remote/Api/ApiBase.php b/lib/private/Remote/Api/ApiBase.php index b2f96fb3c24dc..2801ece60f6e8 100644 --- a/lib/private/Remote/Api/ApiBase.php +++ b/lib/private/Remote/Api/ApiBase.php @@ -11,17 +11,11 @@ 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 f154cd2192643..a846eea08481c 100644 --- a/lib/private/Remote/Api/ApiCollection.php +++ b/lib/private/Remote/Api/ApiCollection.php @@ -12,17 +12,11 @@ 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 795584e566a16..f225ab1689401 100644 --- a/lib/private/Remote/Api/ApiFactory.php +++ b/lib/private/Remote/Api/ApiFactory.php @@ -12,11 +12,9 @@ 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 7f1ffaa727c9a..763e420c8c931 100644 --- a/lib/private/Remote/Credentials.php +++ b/lib/private/Remote/Credentials.php @@ -9,31 +9,17 @@ 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 string $user, + private string $password, + ) { } - /** - * @return string - */ - public function getUsername() { + public function getUsername(): string { return $this->user; } - /** - * @return string - */ - public function getPassword() { + public function getPassword(): string { return $this->password; } } diff --git a/lib/private/Remote/Instance.php b/lib/private/Remote/Instance.php index 10403af4ec729..9807c6b5b1b0f 100644 --- a/lib/private/Remote/Instance.php +++ b/lib/private/Remote/Instance.php @@ -10,81 +10,53 @@ use OCP\Http\Client\IClientService; use OCP\ICache; use OCP\Remote\IInstance; +use Override; /** * Provides some basic info about a remote Nextcloud instance */ class Instance implements IInstance { - /** @var string */ - private $url; - - /** @var ICache */ - private $cache; - - /** @var IClientService */ - private $clientService; - - /** @var array|null */ - private $status; - - /** - * @param string $url - * @param ICache $cache - * @param IClientService $clientService - */ - public function __construct($url, ICache $cache, IClientService $clientService) { + private string $url; + private ?array $status = null; + + public function __construct( + string $url, + private ICache $cache, + private IClientService $clientService, + ) { $url = str_replace('https://', '', $url); $this->url = str_replace('http://', '', $url); - $this->cache = $cache; - $this->clientService = $clientService; } - /** - * @return string The url of the remote server without protocol - */ - public function getUrl() { + #[Override] + public function getUrl(): string { return $this->url; } - /** - * @return string The of the remote server with protocol - */ - public function getFullUrl() { + #[Override] + public function getFullUrl(): string { return $this->getProtocol() . '://' . $this->getUrl(); } - /** - * @return string The full version string in '13.1.2.3' format - */ - public function getVersion() { + #[Override] + public function getVersion(): string { $status = $this->getStatus(); return $status['version']; } - /** - * @return string 'http' or 'https' - */ - public function getProtocol() { + #[Override] + public function getProtocol(): string { $status = $this->getStatus(); return $status['protocol']; } - /** - * Check that the remote server is installed and not in maintenance mode - * - * @return bool - */ - public function isActive() { + #[Override] + public function isActive(): bool { $status = $this->getStatus(); return $status['installed'] && !$status['maintenance']; } - /** - * @return array - * @throws NotFoundException - * @throws \Exception - */ - private function getStatus() { + private function getStatus(): array { if ($this->status) { return $this->status; } @@ -117,11 +89,7 @@ private function getStatus() { return $status; } - /** - * @param string $url - * @return bool|string - */ - private function downloadStatus($url) { + private function downloadStatus(string $url): false|string { try { $request = $this->clientService->newClient()->get($url); $content = $request->getBody(); @@ -131,7 +99,7 @@ private function downloadStatus($url) { assert(is_string($content)); return $content; - } catch (\Exception $e) { + } catch (\Exception) { return false; } } diff --git a/lib/private/Remote/InstanceFactory.php b/lib/private/Remote/InstanceFactory.php index f1b7a1de4baa5..5279d0146cd67 100644 --- a/lib/private/Remote/InstanceFactory.php +++ b/lib/private/Remote/InstanceFactory.php @@ -11,14 +11,10 @@ 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 ae1032cdc1cf2..18a4d8b30b829 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 73f2ae0617818..b88bb1e522872 100644 --- a/lib/private/Repair.php +++ b/lib/private/Repair.php @@ -7,7 +7,6 @@ */ namespace OC; -use OC\DB\ConnectionAdapter; use OC\Repair\AddBruteForceCleanupJob; use OC\Repair\AddCleanupDeletedUsersBackgroundJob; use OC\Repair\AddCleanupUpdaterBackupsJob; @@ -57,36 +56,31 @@ use OC\Repair\RepairInvalidShares; use OC\Repair\RepairLogoDimension; use OC\Repair\RepairMimeTypes; -use OC\Template\JSCombiner; use OCA\DAV\Migration\DeleteSchedulingObjects; use OCA\DAV\Migration\RemoveObjectProperties; -use OCP\AppFramework\QueryException; -use OCP\AppFramework\Utility\ITimeFactory; -use OCP\Collaboration\Resources\IManager; use OCP\EventDispatcher\IEventDispatcher; -use OCP\Files\AppData\IAppDataFactory; -use OCP\IAppConfig; use OCP\IConfig; use OCP\IDBConnection; use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; -use OCP\Notification\IManager as INotificationManager; +use OCP\Server; +use Psr\Container\ContainerExceptionInterface; use Psr\Log\LoggerInterface; use Throwable; class Repair implements IOutput { - /** @var IRepairStep[] */ + /** @var list */ private array $repairSteps = []; private string $currentStep; public function __construct( - private IEventDispatcher $dispatcher, - private LoggerInterface $logger, + private readonly IEventDispatcher $dispatcher, + private readonly LoggerInterface $logger, ) { } - /** @param IRepairStep[] $repairSteps */ + /** @param list $repairSteps */ public function setRepairSteps(array $repairSteps): void { $this->repairSteps = $repairSteps; } @@ -94,7 +88,7 @@ public function setRepairSteps(array $repairSteps): void { /** * Run a series of repair steps for common problems */ - public function run() { + public function run(): void { if (count($this->repairSteps) === 0) { $this->dispatcher->dispatchTyped(new RepairInfoEvent('No repair steps available')); @@ -118,19 +112,19 @@ public function run() { /** * Add repair step * - * @param IRepairStep|string $repairStep repair step + * @param IRepairStep|class-string $repairStep repair step * @throws \Exception */ - public function addStep($repairStep) { + public function addStep(IRepairStep|string $repairStep): void { if (is_string($repairStep)) { try { - $s = \OC::$server->get($repairStep); - } catch (QueryException $e) { + $s = Server::get($repairStep); + } catch (ContainerExceptionInterface $e) { if (class_exists($repairStep)) { try { // Last resort: hope there are no constructor arguments $s = new $repairStep(); - } catch (Throwable $inner) { + } catch (Throwable) { // Well, it was worth a try throw new \Exception("Repair step '$repairStep' can't be instantiated: " . $e->getMessage(), 0, $e); } @@ -153,54 +147,47 @@ public function addStep($repairStep) { * Returns the default repair steps to be run on the * command line or after an upgrade. * - * @return IRepairStep[] + * @return list */ 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 MoveAvatars( - \OC::$server->getJobList(), - \OC::$server->getConfig() - ), - new CleanPreviews( - \OC::$server->getJobList(), - \OC::$server->getUserManager(), - \OC::$server->getConfig() - ), - \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), + new Collation(Server::get(IConfig::class), Server::get(LoggerInterface::class), Server::get(IDBConnection::class), false), + Server::get(CleanTags::class), + Server::get(RepairInvalidShares::class), + Server::get(MoveUpdaterStepFile::class), + Server::get(MoveAvatars::class), + Server::get(CleanPreviews::class), + Server::get(MigratePropertiesTable::class), + Server::get(MigrateOauthTables::class), + Server::get(UpdateLanguageCodes::class), + Server::get(AddLogRotateJob::class), + Server::get(ClearFrontendCaches::class), + Server::get(ClearGeneratedAvatarCache::class), + Server::get(AddPreviewBackgroundCleanupJob::class), + Server::get(AddCleanupUpdaterBackupsJob::class), + Server::get(CleanupCardDAVPhotoCache::class), + Server::get(AddClenupLoginFlowV2BackgroundJob::class), + Server::get(RemoveLinkShares::class), + Server::get(ClearCollectionsAccessCache::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), ]; } @@ -208,19 +195,15 @@ public static function getRepairSteps(): array { * Returns expensive repair steps to be run on the * command line with a special option. * - * @return IRepairStep[] + * @return list */ - public static function getExpensiveRepairSteps() { + public static function getExpensiveRepairSteps(): array { return [ - new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager()), - new RemoveBrokenProperties(\OCP\Server::get(IDBConnection::class)), - new RepairMimeTypes( - \OCP\Server::get(IConfig::class), - \OCP\Server::get(IAppConfig::class), - \OCP\Server::get(IDBConnection::class) - ), - \OCP\Server::get(DeleteSchedulingObjects::class), - \OC::$server->get(RemoveObjectProperties::class), + Server::get(OldGroupMembershipShares::class), + Server::get(RemoveBrokenProperties::class), + Server::get(RepairMimeTypes::class), + Server::get(DeleteSchedulingObjects::class), + Server::get(RemoveObjectProperties::class), ]; } @@ -228,19 +211,14 @@ public static function getExpensiveRepairSteps() { * Returns the repair steps to be run before an * upgrade. * - * @return IRepairStep[] + * @return list */ - public static function getBeforeUpgradeRepairSteps() { - /** @var ConnectionAdapter $connectionAdapter */ - $connectionAdapter = \OC::$server->get(ConnectionAdapter::class); - $config = \OC::$server->getConfig(); - $steps = [ - new Collation(\OC::$server->getConfig(), \OC::$server->get(LoggerInterface::class), $connectionAdapter, true), - new SaveAccountsTableData($connectionAdapter, $config), - new DropAccountTermsTable($connectionAdapter), + public static function getBeforeUpgradeRepairSteps(): array { + return [ + new Collation(Server::get(IConfig::class), Server::get(LoggerInterface::class), Server::get(IDBConnection::class), true), + Server::get(SaveAccountsTableData::class), + Server::get(DropAccountTermsTable::class), ]; - - return $steps; } public function debug(string $message): void { @@ -249,7 +227,7 @@ public function debug(string $message): void { /** * @param string $message */ - public function info($message) { + public function info($message): void { // for now just emit as we did in the past $this->dispatcher->dispatchTyped(new RepairInfoEvent($message)); } @@ -257,7 +235,7 @@ public function info($message) { /** * @param string $message */ - public function warning($message) { + public function warning($message): void { // for now just emit as we did in the past $this->dispatcher->dispatchTyped(new RepairWarningEvent($message)); } @@ -265,7 +243,7 @@ public function warning($message) { /** * @param int $max */ - public function startProgress($max = 0) { + public function startProgress($max = 0): void { // for now just emit as we did in the past $this->dispatcher->dispatchTyped(new RepairStartEvent($max, $this->currentStep)); } @@ -274,15 +252,12 @@ public function startProgress($max = 0) { * @param int $step number of step to advance * @param string $description */ - public function advance($step = 1, $description = '') { + public function advance($step = 1, $description = ''): void { // for now just emit as we did in the past $this->dispatcher->dispatchTyped(new RepairAdvanceEvent($step, $description)); } - /** - * @param int $max - */ - public function finishProgress() { + public function finishProgress(): void { // for now just emit as we did in the past $this->dispatcher->dispatchTyped(new RepairFinishEvent()); } diff --git a/lib/private/Repair/AddBruteForceCleanupJob.php b/lib/private/Repair/AddBruteForceCleanupJob.php index dd08e36a5976e..9473d9031a469 100644 --- a/lib/private/Repair/AddBruteForceCleanupJob.php +++ b/lib/private/Repair/AddBruteForceCleanupJob.php @@ -14,18 +14,16 @@ 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() { + public function getName(): string { return 'Add job to cleanup the bruteforce entries'; } - public function run(IOutput $output) { + public function run(IOutput $output): void { $this->jobList->add(CleanupJob::class); } } diff --git a/lib/private/Repair/AddCleanupDeletedUsersBackgroundJob.php b/lib/private/Repair/AddCleanupDeletedUsersBackgroundJob.php index 9713d8595e774..6d983b8456cf0 100644 --- a/lib/private/Repair/AddCleanupDeletedUsersBackgroundJob.php +++ b/lib/private/Repair/AddCleanupDeletedUsersBackgroundJob.php @@ -14,17 +14,16 @@ 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 { return 'Add cleanup-deleted-users background job'; } - public function run(IOutput $output) { + public function run(IOutput $output): void { $this->jobList->add(CleanupDeletedUsers::class); } } diff --git a/lib/private/Repair/AddCleanupUpdaterBackupsJob.php b/lib/private/Repair/AddCleanupUpdaterBackupsJob.php index e631a3303f1bf..55d703422ff24 100644 --- a/lib/private/Repair/AddCleanupUpdaterBackupsJob.php +++ b/lib/private/Repair/AddCleanupUpdaterBackupsJob.php @@ -12,18 +12,16 @@ use OCP\Migration\IRepairStep; class AddCleanupUpdaterBackupsJob implements IRepairStep { - /** @var IJobList */ - protected $jobList; - - public function __construct(IJobList $jobList) { - $this->jobList = $jobList; + public function __construct( + protected readonly IJobList $jobList, + ) { } - public function getName() { + public function getName(): string { return 'Queue a one-time job to cleanup old backups of the updater'; } - public function run(IOutput $output) { + public function run(IOutput $output): void { $this->jobList->add(BackgroundCleanupUpdaterBackupsJob::class); } } diff --git a/lib/private/Repair/AddMetadataGenerationJob.php b/lib/private/Repair/AddMetadataGenerationJob.php index 76c60f303a7b1..ad5fb129ab1fb 100644 --- a/lib/private/Repair/AddMetadataGenerationJob.php +++ b/lib/private/Repair/AddMetadataGenerationJob.php @@ -17,11 +17,11 @@ public function __construct( ) { } - public function getName() { + public function getName(): string { return 'Queue a job to generate metadata'; } - public function run(IOutput $output) { + public function run(IOutput $output): void { $this->jobList->add(GenerateMetadataJob::class); } } diff --git a/lib/private/Repair/AddMovePreviewJob.php b/lib/private/Repair/AddMovePreviewJob.php index 5edcd64d46e8e..b499bbcbc86ab 100644 --- a/lib/private/Repair/AddMovePreviewJob.php +++ b/lib/private/Repair/AddMovePreviewJob.php @@ -17,11 +17,11 @@ public function __construct( ) { } - public function getName() { + public function getName(): string { return 'Queue a job to move the preview'; } - public function run(IOutput $output) { + public function run(IOutput $output): void { $this->jobList->add(MovePreviewJob::class); } } diff --git a/lib/private/Repair/AddRemoveOldTasksBackgroundJob.php b/lib/private/Repair/AddRemoveOldTasksBackgroundJob.php index 4ad320a031133..eac9d5c3dc136 100644 --- a/lib/private/Repair/AddRemoveOldTasksBackgroundJob.php +++ b/lib/private/Repair/AddRemoveOldTasksBackgroundJob.php @@ -16,10 +16,9 @@ use OCP\Migration\IRepairStep; class AddRemoveOldTasksBackgroundJob implements IRepairStep { - private IJobList $jobList; - - public function __construct(IJobList $jobList) { - $this->jobList = $jobList; + public function __construct( + private readonly IJobList $jobList, + ) { } public function getName(): string { diff --git a/lib/private/Repair/CleanTags.php b/lib/private/Repair/CleanTags.php index ad8fa6235e609..4397f2cf09e5a 100644 --- a/lib/private/Repair/CleanTags.php +++ b/lib/private/Repair/CleanTags.php @@ -20,29 +20,22 @@ */ class CleanTags implements IRepairStep { - protected $deletedTags = 0; + protected int $deletedTags = 0; - /** - * @param IDBConnection $connection - * @param IUserManager $userManager - */ public function __construct( - protected IDBConnection $connection, - protected IUserManager $userManager, + protected readonly IDBConnection $connection, + protected readonly IUserManager $userManager, ) { } - /** - * @return string - */ - public function getName() { + public function getName(): string { return 'Clean tags and favorites'; } /** * Updates the configuration after running an update */ - public function run(IOutput $output) { + public function run(IOutput $output): void { $this->deleteOrphanTags($output); $this->deleteOrphanFileEntries($output); $this->deleteOrphanTagEntries($output); @@ -52,7 +45,7 @@ public function run(IOutput $output) { /** * Delete tags for deleted users */ - protected function deleteOrphanTags(IOutput $output) { + protected function deleteOrphanTags(IOutput $output): void { $offset = 0; while ($this->checkTags($offset)) { $offset += 50; @@ -61,7 +54,7 @@ protected function deleteOrphanTags(IOutput $output) { $output->info(sprintf('%d tags of deleted users have been removed.', $this->deletedTags)); } - protected function checkTags($offset) { + protected function checkTags(int $offset): bool { $query = $this->connection->getQueryBuilder(); $query->select('uid') ->from('vcategory') @@ -98,7 +91,7 @@ protected function checkTags($offset) { /** * Delete tag entries for deleted files */ - protected function deleteOrphanFileEntries(IOutput $output) { + protected function deleteOrphanFileEntries(IOutput $output): void { $this->deleteOrphanEntries( $output, '%d tags for delete files have been removed.', @@ -110,7 +103,7 @@ protected function deleteOrphanFileEntries(IOutput $output) { /** * Delete tag entries for deleted tags */ - protected function deleteOrphanTagEntries(IOutput $output) { + protected function deleteOrphanTagEntries(IOutput $output): void { $this->deleteOrphanEntries( $output, '%d tag entries for deleted tags have been removed.', @@ -122,7 +115,7 @@ protected function deleteOrphanTagEntries(IOutput $output) { /** * Delete tags that have no entries */ - protected function deleteOrphanCategoryEntries(IOutput $output) { + protected function deleteOrphanCategoryEntries(IOutput $output): void { $this->deleteOrphanEntries( $output, '%d tags with no entries have been removed.', @@ -138,15 +131,10 @@ protected function deleteOrphanCategoryEntries(IOutput $output) { * whether $sourceNullColumn is null. If it is null, the entry in $deleteTable * is being deleted. * - * @param string $repairInfo - * @param string $deleteTable - * @param string $deleteId - * @param string $sourceTable - * @param string $sourceId * @param string $sourceNullColumn If this column is null in the source table, * the entry is deleted in the $deleteTable */ - protected function deleteOrphanEntries(IOutput $output, $repairInfo, $deleteTable, $deleteId, $sourceTable, $sourceId, $sourceNullColumn) { + protected function deleteOrphanEntries(IOutput $output, string $repairInfo, string $deleteTable, string $deleteId, string $sourceTable, string $sourceId, string $sourceNullColumn): void { $qb = $this->connection->getQueryBuilder(); $qb->select('d.' . $deleteId) diff --git a/lib/private/Repair/CleanUpAbandonedApps.php b/lib/private/Repair/CleanUpAbandonedApps.php index 718f625be86f8..ce166ebd2b386 100644 --- a/lib/private/Repair/CleanUpAbandonedApps.php +++ b/lib/private/Repair/CleanUpAbandonedApps.php @@ -13,10 +13,10 @@ 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 readonly IConfig $config, + ) { } public function getName(): string { diff --git a/lib/private/Repair/ClearFrontendCaches.php b/lib/private/Repair/ClearFrontendCaches.php index 5c57a63379d5f..60be83efe631b 100644 --- a/lib/private/Repair/ClearFrontendCaches.php +++ b/lib/private/Repair/ClearFrontendCaches.php @@ -12,23 +12,17 @@ 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() { + public function getName(): string { return 'Clear frontend caches'; } - public function run(IOutput $output) { + public function run(IOutput $output): void { try { $c = $this->cacheFactory->createDistributed('imagePath'); $c->clear(); diff --git a/lib/private/Repair/ClearGeneratedAvatarCache.php b/lib/private/Repair/ClearGeneratedAvatarCache.php index 0f743afbb4c85..d48683dfb1e3b 100644 --- a/lib/private/Repair/ClearGeneratedAvatarCache.php +++ b/lib/private/Repair/ClearGeneratedAvatarCache.php @@ -13,14 +13,11 @@ 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 readonly IConfig $config, + protected readonly AvatarManager $avatarManager, + private readonly IJobList $jobList, + ) { } public function getName(): string { diff --git a/lib/private/Repair/ClearGeneratedAvatarCacheJob.php b/lib/private/Repair/ClearGeneratedAvatarCacheJob.php index 524a470e62a04..ff6a67480cd58 100644 --- a/lib/private/Repair/ClearGeneratedAvatarCacheJob.php +++ b/lib/private/Repair/ClearGeneratedAvatarCacheJob.php @@ -11,11 +11,11 @@ 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 4322979221722..346a5abc8153b 100644 --- a/lib/private/Repair/Collation.php +++ b/lib/private/Repair/Collation.php @@ -15,40 +15,22 @@ 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 bool $ignoreFailures, ) { - $this->connection = $connection; - $this->config = $config; - $this->logger = $logger; - $this->ignoreFailures = $ignoreFailures; } - public function getName() { + public function getName(): string { return 'Repair MySQL collation'; } /** * Fix mime types */ - public function run(IOutput $output) { + public function run(IOutput $output): void { if ($this->connection->getDatabaseProvider() !== IDBConnection::PLATFORM_MYSQL) { $output->info('Not a mysql database -> nothing to do'); return; @@ -88,10 +70,9 @@ public function run(IOutput $output) { } /** - * @param IDBConnection $connection * @return string[] */ - protected function getAllNonUTF8BinTables(IDBConnection $connection) { + protected function getAllNonUTF8BinTables(IDBConnection $connection): array { $dbName = $this->config->getSystemValueString('dbname'); $characterSet = $this->config->getSystemValueBool('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8'; diff --git a/lib/private/Repair/ConfigKeyMigration.php b/lib/private/Repair/ConfigKeyMigration.php index dcca43d65dfc7..acdda68dc0a8f 100644 --- a/lib/private/Repair/ConfigKeyMigration.php +++ b/lib/private/Repair/ConfigKeyMigration.php @@ -23,7 +23,7 @@ public function getName(): string { return 'Migrate config keys'; } - public function run(IOutput $output) { + public function run(IOutput $output): void { $this->configManager->migrateConfigLexiconKeys(); $this->configManager->updateLexiconEntries('core'); } diff --git a/lib/private/Repair/Events/RepairAdvanceEvent.php b/lib/private/Repair/Events/RepairAdvanceEvent.php index 476db9e47028c..eb5bdb018058a 100644 --- a/lib/private/Repair/Events/RepairAdvanceEvent.php +++ b/lib/private/Repair/Events/RepairAdvanceEvent.php @@ -11,15 +11,10 @@ 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 e5be8a5a0311c..219a7cd97bb73 100644 --- a/lib/private/Repair/Events/RepairErrorEvent.php +++ b/lib/private/Repair/Events/RepairErrorEvent.php @@ -11,12 +11,9 @@ 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 ce8eb2f99e677..87b2056f8d3e3 100644 --- a/lib/private/Repair/Events/RepairInfoEvent.php +++ b/lib/private/Repair/Events/RepairInfoEvent.php @@ -11,12 +11,9 @@ 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 47e713d57d997..e8e97c5233b47 100644 --- a/lib/private/Repair/Events/RepairStartEvent.php +++ b/lib/private/Repair/Events/RepairStartEvent.php @@ -11,15 +11,10 @@ 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 27e1efbdb08e9..5c68778f2602b 100644 --- a/lib/private/Repair/Events/RepairStepEvent.php +++ b/lib/private/Repair/Events/RepairStepEvent.php @@ -11,12 +11,9 @@ 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 6893a7212eca1..118965739e82c 100644 --- a/lib/private/Repair/Events/RepairWarningEvent.php +++ b/lib/private/Repair/Events/RepairWarningEvent.php @@ -11,12 +11,9 @@ 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 bb8f9d3acfc70..7155eed5689b4 100644 --- a/lib/private/Repair/MoveUpdaterStepFile.php +++ b/lib/private/Repair/MoveUpdaterStepFile.php @@ -7,25 +7,21 @@ 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 - */ - public function __construct($config) { - $this->config = $config; + public function __construct( + protected IConfig $config, + ) { } - public function getName() { + public function getName(): string { return 'Move .step file of updater to backup location'; } - public function run(IOutput $output) { + public function run(IOutput $output): void { $updateDir = $this->config->getSystemValue('updatedirectory', null) ?? $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data'); $instanceId = $this->config->getSystemValueString('instanceid'); diff --git a/lib/private/Repair/NC13/AddLogRotateJob.php b/lib/private/Repair/NC13/AddLogRotateJob.php index bd6c510785ff1..7ad9b3445b3c6 100644 --- a/lib/private/Repair/NC13/AddLogRotateJob.php +++ b/lib/private/Repair/NC13/AddLogRotateJob.php @@ -12,18 +12,16 @@ use OCP\Migration\IRepairStep; class AddLogRotateJob implements IRepairStep { - /** @var IJobList */ - private $jobList; - - public function __construct(IJobList $jobList) { - $this->jobList = $jobList; + public function __construct( + private readonly IJobList $jobList, + ) { } - public function getName() { + public function getName(): string { return 'Add log rotate job'; } - public function run(IOutput $output) { + public function run(IOutput $output): void { $this->jobList->add(Rotate::class); } } diff --git a/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php b/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php index 417bc5e6adc55..c7a957750839a 100644 --- a/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php +++ b/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php @@ -14,11 +14,9 @@ use OCP\Migration\IRepairStep; class AddPreviewBackgroundCleanupJob implements IRepairStep { - /** @var IJobList */ - private $jobList; - - public function __construct(IJobList $jobList) { - $this->jobList = $jobList; + public function __construct( + private readonly IJobList $jobList, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php b/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php index ab5f93415fc88..50dd0050fe14e 100644 --- a/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php +++ b/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php @@ -14,11 +14,9 @@ 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 1627ed40b98fa..e1eef24eedd44 100644 --- a/lib/private/Repair/NC16/ClearCollectionsAccessCache.php +++ b/lib/private/Repair/NC16/ClearCollectionsAccessCache.php @@ -9,21 +9,15 @@ namespace OC\Repair\NC16; use OC\Collaboration\Resources\Manager; -use OCP\Collaboration\Resources\IManager; use OCP\IConfig; 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 readonly IConfig $config, + private readonly Manager $manager, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC18/ResetGeneratedAvatarFlag.php b/lib/private/Repair/NC18/ResetGeneratedAvatarFlag.php index b0dfec295e763..d07bc2d7193ce 100644 --- a/lib/private/Repair/NC18/ResetGeneratedAvatarFlag.php +++ b/lib/private/Repair/NC18/ResetGeneratedAvatarFlag.php @@ -14,15 +14,10 @@ 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 readonly IConfig $config, + private readonly IDBConnection $connection, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC20/EncryptionLegacyCipher.php b/lib/private/Repair/NC20/EncryptionLegacyCipher.php index 89473ffd5e8a8..ca8986e78db14 100644 --- a/lib/private/Repair/NC20/EncryptionLegacyCipher.php +++ b/lib/private/Repair/NC20/EncryptionLegacyCipher.php @@ -14,15 +14,10 @@ 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 6de143747b3e1..91fca99c5d269 100644 --- a/lib/private/Repair/NC20/EncryptionMigration.php +++ b/lib/private/Repair/NC20/EncryptionMigration.php @@ -14,15 +14,10 @@ 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 955011a8c848d..5d505d0c3efbf 100644 --- a/lib/private/Repair/NC20/ShippedDashboardEnable.php +++ b/lib/private/Repair/NC20/ShippedDashboardEnable.php @@ -13,18 +13,16 @@ use OCP\Migration\IRepairStep; class ShippedDashboardEnable implements IRepairStep { - /** @var IConfig */ - private $config; - - public function __construct(IConfig $config) { - $this->config = $config; + public function __construct( + private readonly IConfig $config, + ) { } - public function getName() { + public function getName(): string { return 'Remove old dashboard app config data'; } - public function run(IOutput $output) { + public function run(IOutput $output): void { $version = $this->config->getAppValue('dashboard', 'version', '7.0.0'); if (version_compare($version, '7.0.0', '<')) { $this->config->deleteAppValues('dashboard'); diff --git a/lib/private/Repair/NC21/AddCheckForUserCertificatesJob.php b/lib/private/Repair/NC21/AddCheckForUserCertificatesJob.php index 5cee33b381ce2..e55dce7814d26 100644 --- a/lib/private/Repair/NC21/AddCheckForUserCertificatesJob.php +++ b/lib/private/Repair/NC21/AddCheckForUserCertificatesJob.php @@ -13,28 +13,24 @@ 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() { + public function getName(): string { return 'Queue a one-time job to check for user uploaded certificates'; } - private function shouldRun() { + private function shouldRun(): bool { $versionFromBeforeUpdate = $this->config->getSystemValueString('version', '0.0.0.0'); // was added to 21.0.0.2 return version_compare($versionFromBeforeUpdate, '21.0.0.2', '<'); } - public function run(IOutput $output) { + public function run(IOutput $output): void { if ($this->shouldRun()) { $this->config->setAppValue('files_external', 'user_certificate_scan', 'not-run-yet'); $this->jobList->add(CheckForUserCertificates::class); diff --git a/lib/private/Repair/NC22/LookupServerSendCheck.php b/lib/private/Repair/NC22/LookupServerSendCheck.php index 540dc2a730d43..453e06fd60633 100644 --- a/lib/private/Repair/NC22/LookupServerSendCheck.php +++ b/lib/private/Repair/NC22/LookupServerSendCheck.php @@ -10,17 +10,13 @@ use OC\Core\BackgroundJobs\LookupServerSendCheckBackgroundJob; use OCP\BackgroundJob\IJobList; -use OCP\IConfig; 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 readonly IJobList $jobList, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC24/AddTokenCleanupJob.php b/lib/private/Repair/NC24/AddTokenCleanupJob.php index f1dac2d4e12a8..be6b24b0c1cab 100644 --- a/lib/private/Repair/NC24/AddTokenCleanupJob.php +++ b/lib/private/Repair/NC24/AddTokenCleanupJob.php @@ -14,10 +14,9 @@ use OCP\Migration\IRepairStep; class AddTokenCleanupJob implements IRepairStep { - private IJobList $jobList; - - public function __construct(IJobList $jobList) { - $this->jobList = $jobList; + public function __construct( + private readonly IJobList $jobList, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC25/AddMissingSecretJob.php b/lib/private/Repair/NC25/AddMissingSecretJob.php index 46b89d5f6f7f6..2b8f5934ee8df 100644 --- a/lib/private/Repair/NC25/AddMissingSecretJob.php +++ b/lib/private/Repair/NC25/AddMissingSecretJob.php @@ -15,12 +15,10 @@ 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 readonly IConfig $config, + private readonly ISecureRandom $random, + ) { } public function getName(): string { diff --git a/lib/private/Repair/NC29/SanitizeAccountPropertiesJob.php b/lib/private/Repair/NC29/SanitizeAccountPropertiesJob.php index 55ec445e9daec..530805d3637e2 100644 --- a/lib/private/Repair/NC29/SanitizeAccountPropertiesJob.php +++ b/lib/private/Repair/NC29/SanitizeAccountPropertiesJob.php @@ -38,7 +38,7 @@ public function __construct( 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/OldGroupMembershipShares.php b/lib/private/Repair/OldGroupMembershipShares.php index 003c15cfb8887..a0ae19957e57c 100644 --- a/lib/private/Repair/OldGroupMembershipShares.php +++ b/lib/private/Repair/OldGroupMembershipShares.php @@ -15,26 +15,17 @@ class OldGroupMembershipShares implements IRepairStep { /** - * @var array [gid => [uid => (bool)]] + * @var array> [gid => [uid => (bool)]] */ - protected $memberships; + protected array $memberships = []; - /** - * @param IDBConnection $connection - * @param IGroupManager $groupManager - */ public function __construct( - protected IDBConnection $connection, - protected IGroupManager $groupManager, + protected readonly IDBConnection $connection, + protected readonly IGroupManager $groupManager, ) { } - /** - * Returns the step's name - * - * @return string - */ - public function getName() { + public function getName(): string { return 'Remove shares of old group memberships'; } @@ -44,7 +35,7 @@ public function getName() { * * @throws \Exception in case of failure */ - public function run(IOutput $output) { + public function run(IOutput $output): void { $deletedEntries = 0; $query = $this->connection->getQueryBuilder(); @@ -75,12 +66,7 @@ public function run(IOutput $output) { } } - /** - * @param string $gid - * @param string $uid - * @return bool - */ - protected function isMember($gid, $uid) { + protected function isMember(string $gid, string $uid): bool { if (isset($this->memberships[$gid][$uid])) { return $this->memberships[$gid][$uid]; } diff --git a/lib/private/Repair/Owncloud/CleanPreviews.php b/lib/private/Repair/Owncloud/CleanPreviews.php index 50ee965e087c0..63bec39859b07 100644 --- a/lib/private/Repair/Owncloud/CleanPreviews.php +++ b/lib/private/Repair/Owncloud/CleanPreviews.php @@ -7,50 +7,33 @@ namespace OC\Repair\Owncloud; use OCP\BackgroundJob\IJobList; -use OCP\IConfig; +use OCP\IAppConfig; use OCP\IUser; use OCP\IUserManager; use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; +use Override; class CleanPreviews implements IRepairStep { - /** @var IJobList */ - private $jobList; - - /** @var IUserManager */ - private $userManager; - - /** @var IConfig */ - private $config; - - /** - * MoveAvatars constructor. - * - * @param IJobList $jobList - * @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 readonly IJobList $jobList, + private readonly IUserManager $userManager, + private readonly IAppConfig $appConfig, + ) { } - /** - * @return string - */ - public function getName() { + #[Override] + public function getName(): string { return 'Add preview cleanup background jobs'; } - public function run(IOutput $output) { - if (!$this->config->getAppValue('core', 'previewsCleanedUp', false)) { - $this->userManager->callForSeenUsers(function (IUser $user) { + #[Override] + public function run(IOutput $output): void { + if (!$this->appConfig->getValueBool('core', 'previewsCleanedUp')) { + $this->userManager->callForSeenUsers(function (IUser $user): void { $this->jobList->add(CleanPreviewsBackgroundJob::class, ['uid' => $user->getUID()]); }); - $this->config->setAppValue('core', 'previewsCleanedUp', '1'); + $this->appConfig->setValueBool('core', 'previewsCleanedUp', true); } } } diff --git a/lib/private/Repair/Owncloud/DropAccountTermsTable.php b/lib/private/Repair/Owncloud/DropAccountTermsTable.php index 534825c146ab2..2420327a0372d 100644 --- a/lib/private/Repair/Owncloud/DropAccountTermsTable.php +++ b/lib/private/Repair/Owncloud/DropAccountTermsTable.php @@ -11,27 +11,16 @@ 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, + ) { } - /** - * @return string - */ - public function getName() { + public function getName(): string { return 'Drop account terms table when migrating from ownCloud'; } - /** - * @param IOutput $output - */ - public function run(IOutput $output) { + public function run(IOutput $output): void { if (!$this->db->tableExists('account_terms')) { return; } diff --git a/lib/private/Repair/Owncloud/MigrateOauthTables.php b/lib/private/Repair/Owncloud/MigrateOauthTables.php index de26a907e0205..1d7b630b4e518 100644 --- a/lib/private/Repair/Owncloud/MigrateOauthTables.php +++ b/lib/private/Repair/Owncloud/MigrateOauthTables.php @@ -34,14 +34,11 @@ public function __construct( ) { } - /** - * @return string - */ - public function getName() { + public function getName(): string { return 'Migrate oauth2_clients table to nextcloud schema'; } - public function run(IOutput $output) { + public function run(IOutput $output): void { $schema = new SchemaWrapper($this->db); if (!$schema->hasTable('oauth2_clients')) { $output->info('oauth2_clients table does not exist.'); diff --git a/lib/private/Repair/Owncloud/MigratePropertiesTable.php b/lib/private/Repair/Owncloud/MigratePropertiesTable.php index f7462ebbe5321..60122bbf3d145 100644 --- a/lib/private/Repair/Owncloud/MigratePropertiesTable.php +++ b/lib/private/Repair/Owncloud/MigratePropertiesTable.php @@ -19,7 +19,7 @@ class MigratePropertiesTable implements IRepairStep { public function __construct( - private Connection $db, + private readonly Connection $db, ) { } diff --git a/lib/private/Repair/Owncloud/MoveAvatars.php b/lib/private/Repair/Owncloud/MoveAvatars.php index 9e3f4b89b13a9..f4ee9d751f25e 100644 --- a/lib/private/Repair/Owncloud/MoveAvatars.php +++ b/lib/private/Repair/Owncloud/MoveAvatars.php @@ -12,32 +12,17 @@ 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 readonly IJobList $jobList, + private readonly IConfig $config, + ) { } - /** - * @return string - */ - public function getName() { + public function getName(): string { return 'Add move avatar background job'; } - public function run(IOutput $output) { + public function run(IOutput $output): void { // only run once if ($this->config->getAppValue('core', 'moveavatarsdone') === 'yes') { $output->info('Repair step already executed'); diff --git a/lib/private/Repair/Owncloud/MoveAvatarsBackgroundJob.php b/lib/private/Repair/Owncloud/MoveAvatarsBackgroundJob.php index e5f80eb31bd24..3b8936894e7df 100644 --- a/lib/private/Repair/Owncloud/MoveAvatarsBackgroundJob.php +++ b/lib/private/Repair/Owncloud/MoveAvatarsBackgroundJob.php @@ -49,7 +49,7 @@ private function moveAvatars(): void { } $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 7f8249257658b..61284a09e5de9 100644 --- a/lib/private/Repair/Owncloud/SaveAccountsTableData.php +++ b/lib/private/Repair/Owncloud/SaveAccountsTableData.php @@ -20,34 +20,19 @@ class SaveAccountsTableData implements IRepairStep { public const BATCH_SIZE = 75; - /** @var IDBConnection */ - protected $db; + protected bool $hasForeignKeyOnPersistentLocks = false; - /** @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, + ) { } - /** - * @return string - */ - public function getName() { + public function getName(): string { return 'Copy data from accounts table when migrating from ownCloud'; } - /** - * @param IOutput $output - */ - public function run(IOutput $output) { + public function run(IOutput $output): void { if (!$this->shouldRun()) { return; } @@ -76,10 +61,7 @@ public function run(IOutput $output) { $this->db->dropTable('accounts'); } - /** - * @return bool - */ - protected function shouldRun() { + protected function shouldRun(): bool { $schema = $this->db->createSchema(); $prefix = $this->config->getSystemValueString('dbtableprefix', 'oc_'); @@ -107,10 +89,9 @@ protected function shouldRun() { } /** - * @param int $offset * @return int Number of copied users */ - protected function runStep($offset) { + protected function runStep(int $offset): int { $query = $this->db->getQueryBuilder(); $query->select('*') ->from('accounts') @@ -132,9 +113,7 @@ protected function runStep($offset) { while ($row = $result->fetch()) { try { $this->migrateUserInfo($update, $row); - } catch (PreConditionNotMetException $e) { - // Ignore and continue - } catch (\UnexpectedValueException $e) { + } catch (PreConditionNotMetException|\UnexpectedValueException) { // Ignore and continue } $updatedUsers++; @@ -145,12 +124,10 @@ protected function runStep($offset) { } /** - * @param IQueryBuilder $update - * @param array $userdata * @throws PreConditionNotMetException * @throws \UnexpectedValueException */ - protected function migrateUserInfo(IQueryBuilder $update, $userdata) { + protected function migrateUserInfo(IQueryBuilder $update, array $userdata): void { $state = (int)$userdata['state']; if ($state === 3) { // Deleted user, ignore diff --git a/lib/private/Repair/Owncloud/UpdateLanguageCodes.php b/lib/private/Repair/Owncloud/UpdateLanguageCodes.php index 6bcdd899ec976..611e33602dd95 100644 --- a/lib/private/Repair/Owncloud/UpdateLanguageCodes.php +++ b/lib/private/Repair/Owncloud/UpdateLanguageCodes.php @@ -11,35 +11,22 @@ use OCP\IDBConnection; use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; +use Override; 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 readonly IDBConnection $connection, + private readonly IConfig $config, + ) { } - /** - * {@inheritdoc} - */ - public function getName() { + #[Override] + public function getName(): string { return 'Repair language codes'; } - /** - * {@inheritdoc} - */ - public function run(IOutput $output) { + #[Override] + public function run(IOutput $output): void { $versionFromBeforeUpdate = $this->config->getSystemValueString('version', '0.0.0'); if (version_compare($versionFromBeforeUpdate, '12.0.0.13', '>')) { diff --git a/lib/private/Repair/RemoveBrokenProperties.php b/lib/private/Repair/RemoveBrokenProperties.php index 85939b39e5e65..b993ffaa5e824 100644 --- a/lib/private/Repair/RemoveBrokenProperties.php +++ b/lib/private/Repair/RemoveBrokenProperties.php @@ -12,29 +12,21 @@ use OCP\IDBConnection; use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; +use Override; class RemoveBrokenProperties implements IRepairStep { - /** - * RemoveBrokenProperties constructor. - * - * @param IDBConnection $db - */ public function __construct( - private IDBConnection $db, + private readonly IDBConnection $db, ) { } - /** - * @inheritdoc - */ - public function getName() { + #[Override] + public function getName(): string { return 'Remove broken DAV object properties'; } - /** - * @inheritdoc - */ - public function run(IOutput $output) { + #[Override] + public function run(IOutput $output): void { // retrieve all object properties $qb = $this->db->getQueryBuilder(); $qb->select('id', 'propertyvalue') diff --git a/lib/private/Repair/RemoveLinkShares.php b/lib/private/Repair/RemoveLinkShares.php index a07ebdb72c39e..5ea1d4b925866 100644 --- a/lib/private/Repair/RemoveLinkShares.php +++ b/lib/private/Repair/RemoveLinkShares.php @@ -20,14 +20,14 @@ class RemoveLinkShares implements IRepairStep { /** @var string[] */ - private $userToNotify = []; + private array $userToNotify = []; public function __construct( - private IDBConnection $connection, - private IConfig $config, - private IGroupManager $groupManager, - private IManager $notificationManager, - private ITimeFactory $timeFactory, + private readonly IDBConnection $connection, + private readonly IConfig $config, + private readonly IGroupManager $groupManager, + private readonly IManager $notificationManager, + private readonly ITimeFactory $timeFactory, ) { } @@ -51,11 +51,6 @@ private function shouldRun(): bool { return false; } - /** - * Delete the share - * - * @param int $id - */ private function deleteShare(int $id): void { $qb = $this->connection->getQueryBuilder(); $qb->delete('share') @@ -65,8 +60,6 @@ private function deleteShare(int $id): void { /** * Get the total of affected shares - * - * @return int */ private function getTotal(): int { $subSubQuery = $this->connection->getQueryBuilder(); @@ -130,7 +123,7 @@ private function getShares(): IResult { /** * Process a single share * - * @param array $data + * @param array{id: int|string, uid_owner: string, uid_initiator: string} $data */ private function processShare(array $data): void { $id = $data['id']; @@ -143,8 +136,6 @@ private function processShare(array $data): void { /** * Update list of users to notify - * - * @param string $uid */ private function addToNotify(string $uid): void { if (!isset($this->userToNotify[$uid])) { diff --git a/lib/private/Repair/RepairDavShares.php b/lib/private/Repair/RepairDavShares.php index 8199d3dff2784..c21c0274461db 100644 --- a/lib/private/Repair/RepairDavShares.php +++ b/lib/private/Repair/RepairDavShares.php @@ -23,25 +23,21 @@ class RepairDavShares implements IRepairStep { protected const GROUP_PRINCIPAL_PREFIX = 'principals/groups/'; - /** @var bool */ - private $hintInvalidShares = false; + private bool $hintInvalidShares = false; public function __construct( - private IConfig $config, - private IDBConnection $dbc, - private IGroupManager $groupManager, - private LoggerInterface $logger, + private readonly IConfig $config, + private readonly IDBConnection $dbc, + private readonly IGroupManager $groupManager, + private readonly LoggerInterface $logger, ) { } - /** - * @inheritDoc - */ - public function getName() { + public function getName(): string { return 'Repair DAV shares'; } - protected function repairUnencodedGroupShares() { + protected function repairUnencodedGroupShares(): bool { $qb = $this->dbc->getQueryBuilder(); $qb->select(['id', 'principaluri']) ->from('dav_shares') @@ -92,10 +88,7 @@ protected function repairUnencodedGroupShares() { return true; } - /** - * @inheritDoc - */ - public function run(IOutput $output) { + public function run(IOutput $output): void { $versionFromBeforeUpdate = $this->config->getSystemValueString('version', '0.0.0'); if (version_compare($versionFromBeforeUpdate, '20.0.8', '<') && $this->repairUnencodedGroupShares() diff --git a/lib/private/Repair/RepairInvalidShares.php b/lib/private/Repair/RepairInvalidShares.php index 627ecf6659d06..5939d0d643024 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; @@ -24,7 +25,7 @@ public function __construct( ) { } - public function getName() { + public function getName(): string { return 'Repair invalid shares'; } @@ -32,7 +33,7 @@ public function getName() { * 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/Repair/RepairMimeTypes.php b/lib/private/Repair/RepairMimeTypes.php index 8afaca9c3c615..2303e28e4c09f 100644 --- a/lib/private/Repair/RepairMimeTypes.php +++ b/lib/private/Repair/RepairMimeTypes.php @@ -19,14 +19,12 @@ class RepairMimeTypes implements IRepairStep { private bool $dryRun = false; private int $changeCount = 0; - - /** @var int */ protected int $folderMimeTypeId; public function __construct( - protected IConfig $config, - protected IAppConfig $appConfig, - protected IDBConnection $connection, + protected readonly IConfig $config, + protected readonly IAppConfig $appConfig, + protected readonly IDBConnection $connection, ) { } diff --git a/lib/private/Search/FilterFactory.php b/lib/private/Search/FilterFactory.php index 07063c604f433..7a9baf10b4c35 100644 --- a/lib/private/Search/FilterFactory.php +++ b/lib/private/Search/FilterFactory.php @@ -8,10 +8,19 @@ */ 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 00e1be5bedf96..ab24de33a1de0 100644 --- a/lib/private/Security/CSRF/CsrfTokenManager.php +++ b/lib/private/Security/CSRF/CsrfTokenManager.php @@ -16,14 +16,12 @@ * @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 09e01ff99f72e..81c2b9461a33e 100644 --- a/lib/private/Security/Certificate.php +++ b/lib/private/Security/Certificate.php @@ -11,8 +11,6 @@ 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 d8a988261db6c..5dfeed1c07ab0 100644 --- a/lib/private/Security/CertificateManager.php +++ b/lib/private/Security/CertificateManager.php @@ -32,7 +32,7 @@ public function __construct( /** * 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 eee6489ddd393..70884e6f769a7 100644 --- a/lib/private/Security/Normalizer/IpAddress.php +++ b/lib/private/Security/Normalizer/IpAddress.php @@ -9,6 +9,7 @@ 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 @@ private function getIPv6Subnet(string $ip): string { $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 51682ec36302d..1706a7decb0de 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -16,13 +16,16 @@ 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; @@ -31,14 +34,21 @@ 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\ContextChat\ContentManager; 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; @@ -47,6 +57,8 @@ 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; @@ -59,6 +71,7 @@ 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; @@ -80,22 +93,28 @@ 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; @@ -107,14 +126,17 @@ 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\Decoder; @@ -122,6 +144,7 @@ use OC\Snowflake\Generator; use OC\Snowflake\ISequence; use OC\SpeechToText\SpeechToTextManager; +use OC\Support\Subscription\Assertion; use OC\SystemTag\ManagerFactory as SystemTagManagerFactory; use OC\Talk\Broker; use OC\Teams\TeamManager; @@ -132,22 +155,28 @@ 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; +use OCP\ContextChat\IContentManager; use OCP\Defaults; use OCP\Diagnostics\IEventLogger; use OCP\Diagnostics\IQueryLogger; @@ -162,6 +191,9 @@ 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; @@ -179,9 +211,11 @@ use OCP\ICache; use OCP\ICacheFactory; use OCP\ICertificateManager; +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 +227,7 @@ use OCP\IRequestId; use OCP\IServerContainer; use OCP\ISession; +use OCP\ITagManager; use OCP\ITempManager; use OCP\IURLGenerator; use OCP\IUserManager; @@ -259,16 +294,11 @@ * TODO: hookup all manager classes */ class Server extends ServerContainer implements IServerContainer { - /** @var string */ - private $webRoot; - - /** - * @param string $webRoot - * @param \OC\Config $config - */ - public function __construct($webRoot, \OC\Config $config) { + public function __construct( + private string $webRoot, + Config $config, + ) { parent::__construct(); - $this->webRoot = $webRoot; // To find out if we are running from CLI or not $this->registerParameter('isCLI', \OC::$CLI); @@ -277,7 +307,7 @@ public function __construct($webRoot, \OC\Config $config) { $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); @@ -285,9 +315,9 @@ public function __construct($webRoot, \OC\Config $config) { $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(IContentManager::class, ContentManager::class); $this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class); $this->registerAlias(ITemplateManager::class, TemplateManager::class); @@ -301,7 +331,7 @@ public function __construct($webRoot, \OC\Config $config) { $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 +362,10 @@ public function __construct($webRoot, \OC\Config $config) { $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 +380,9 @@ public function __construct($webRoot, \OC\Config $config) { 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 +395,22 @@ public function __construct($webRoot, \OC\Config $config) { $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 +425,7 @@ public function __construct($webRoot, \OC\Config $config) { }); $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 +441,7 @@ public function __construct($webRoot, \OC\Config $config) { $this->get(IAppConfig::class), ); - $previewConnector = new \OC\Preview\WatcherConnector( + $previewConnector = new WatcherConnector( $root, $c->get(SystemConfig::class), $this->get(IEventDispatcher::class) @@ -435,13 +465,13 @@ public function __construct($webRoot, \OC\Config $config) { }); }); - $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 +484,7 @@ public function __construct($webRoot, \OC\Config $config) { $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 +497,121 @@ public function __construct($webRoot, \OC\Config $config) { $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 +630,7 @@ public function __construct($webRoot, \OC\Config $config) { /** @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 +640,7 @@ public function __construct($webRoot, \OC\Config $config) { ); } - return new \OC\Memcache\Factory( + return new Factory( $logger, $profiler, $serverVersion, @@ -636,7 +666,7 @@ public function __construct($webRoot, \OC\Config $config) { 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 +688,7 @@ public function __construct($webRoot, \OC\Config $config) { $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 +698,10 @@ public function __construct($webRoot, \OC\Config $config) { $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 +716,7 @@ public function __construct($webRoot, \OC\Config $config) { 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 +730,26 @@ public function __construct($webRoot, \OC\Config $config) { $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 +761,10 @@ public function __construct($webRoot, \OC\Config $config) { $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 +795,7 @@ public function __construct($webRoot, \OC\Config $config) { $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 +818,7 @@ public function __construct($webRoot, \OC\Config $config) { // 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 +830,7 @@ public function __construct($webRoot, \OC\Config $config) { }); $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 +849,9 @@ public function __construct($webRoot, \OC\Config $config) { $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 +864,9 @@ public function __construct($webRoot, \OC\Config $config) { $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 +912,12 @@ public function __construct($webRoot, \OC\Config $config) { '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 +931,7 @@ public function __construct($webRoot, \OC\Config $config) { $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 +946,12 @@ public function __construct($webRoot, \OC\Config $config) { $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 +960,13 @@ public function __construct($webRoot, \OC\Config $config) { }); $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 +992,7 @@ public function __construct($webRoot, \OC\Config $config) { $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 +1009,18 @@ public function __construct($webRoot, \OC\Config $config) { $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 +1041,24 @@ public function __construct($webRoot, \OC\Config $config) { $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 +1068,8 @@ public function __construct($webRoot, \OC\Config $config) { ); 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 +1079,7 @@ public function __construct($webRoot, \OC\Config $config) { $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 +1097,11 @@ public function __construct($webRoot, \OC\Config $config) { $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 +1118,7 @@ public function __construct($webRoot, \OC\Config $config) { : null, ], $c->get(IRequestId::class), - $c->get(\OCP\IConfig::class) + $c->get(IConfig::class) ); return new CryptoWrapper( @@ -1100,16 +1133,16 @@ public function __construct($webRoot, \OC\Config $config) { $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 +1158,7 @@ public function __construct($webRoot, \OC\Config $config) { $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 +1179,7 @@ public function __construct($webRoot, \OC\Config $config) { }); }); - $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 +1203,10 @@ public function __construct($webRoot, \OC\Config $config) { 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 +1214,8 @@ public function __construct($webRoot, \OC\Config $config) { ); }); - $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 +1247,19 @@ public function __construct($webRoot, \OC\Config $config) { $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 +1295,7 @@ public function __construct($webRoot, \OC\Config $config) { $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 +1342,16 @@ public function getContactsManager() { } /** - * @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 +1360,7 @@ public function getEncryptionFilesHelper() { * 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,10 +1393,10 @@ public function getLazyRootFolder() { * 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) { + public function getUserFolder($userId = null): ?Folder { if ($userId === null) { $user = $this->get(IUserSession::class)->getUser(); if (!$user) { @@ -1378,68 +1409,57 @@ public function getUserFolder($userId = null) { } /** - * @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 * @deprecated 20.0.0 */ - public function getSession() { + public function getSession(): ISession { return $this->get(Session::class)->getSession(); } - /** - * @param \OCP\ISession $session - * @return void - */ - public function setSession(\OCP\ISession $session) { + public function setSession(ISession $session): void { $this->get(SessionStorage::class)->setSession($session); $this->get(Session::class)->setSession($session); $this->get(Store::class)->setSession($session); } /** - * @return \OCP\IConfig * @deprecated 20.0.0 */ - public function getConfig() { + public function getConfig(): IConfig { return $this->get(AllConfig::class); } /** - * @return \OC\SystemConfig * @deprecated 20.0.0 */ - public function getSystemConfig() { + public function getSystemConfig(): SystemConfig { return $this->get(SystemConfig::class); } /** - * @return IFactory * @deprecated 20.0.0 */ - public function getL10NFactory() { + public function getL10NFactory(): IFactory { return $this->get(IFactory::class); } @@ -1477,7 +1497,7 @@ public function getCache() { /** * Returns an \OCP\CacheFactory instance * - * @return \OCP\ICacheFactory + * @return ICacheFactory * @deprecated 20.0.0 */ public function getMemCacheFactory() { @@ -1487,7 +1507,7 @@ public function getMemCacheFactory() { /** * Returns the current session * - * @return \OCP\IDBConnection + * @return IDBConnection * @deprecated 20.0.0 */ public function getDatabaseConnection() { @@ -1517,7 +1537,7 @@ public function getJobList() { /** * Returns a SecureRandom instance * - * @return \OCP\Security\ISecureRandom + * @return ISecureRandom * @deprecated 20.0.0 */ public function getSecureRandom() { @@ -1547,7 +1567,7 @@ public function getHasher() { /** * Get the certificate manager * - * @return \OCP\ICertificateManager + * @return ICertificateManager */ public function getCertificateManager() { return $this->get(ICertificateManager::class); @@ -1556,7 +1576,7 @@ public function getCertificateManager() { /** * Get the manager for temporary files and folders * - * @return \OCP\ITempManager + * @return ITempManager * @deprecated 20.0.0 */ public function getTempManager() { @@ -1566,7 +1586,7 @@ public function getTempManager() { /** * Get the app manager * - * @return \OCP\App\IAppManager + * @return IAppManager * @deprecated 20.0.0 */ public function getAppManager() { @@ -1636,7 +1656,7 @@ public function getNotificationManager() { } /** - * @return \OCA\Theming\ThemingDefaults + * @return ThemingDefaults * @deprecated 20.0.0 */ public function getThemingDefaults() { @@ -1644,7 +1664,7 @@ public function getThemingDefaults() { } /** - * @return \OC\IntegrityCheck\Checker + * @return Checker * @deprecated 20.0.0 */ public function getIntegrityCodeChecker() { @@ -1676,7 +1696,7 @@ public function getSettingsManager() { } /** - * @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 +1705,7 @@ public function getAppDataDir($app) { } /** - * @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 42cdf37fce92b..a63615d21bbca 100644 --- a/lib/private/ServerContainer.php +++ b/lib/private/ServerContainer.php @@ -172,4 +172,8 @@ public function getAppContainerForService(string $id): ?DIContainer { return null; } } + + public function getWebRoot() { + return ''; + } } diff --git a/lib/private/Session/CryptoSessionData.php b/lib/private/Session/CryptoSessionData.php index 323253af534c7..f25d2234335d1 100644 --- a/lib/private/Session/CryptoSessionData.php +++ b/lib/private/Session/CryptoSessionData.php @@ -21,29 +21,15 @@ * @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 */ - protected $isModified = false; + protected array $sessionValues = []; + protected bool $isModified = false; public const encryptedSessionName = 'encrypted_session_data'; - /** - * @param ISession $session - * @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 40c2ba6adf38b..d269a2f19410b 100644 --- a/lib/private/Session/CryptoWrapper.php +++ b/lib/private/Session/CryptoWrapper.php @@ -10,10 +10,12 @@ 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 @@ public function __construct( [ '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 b465bcd3edadb..77e7bdd9c1d58 100644 --- a/lib/private/Session/Internal.php +++ b/lib/private/Session/Internal.php @@ -12,6 +12,7 @@ use OC\Authentication\Token\IProvider; use OCP\Authentication\Exceptions\InvalidTokenException; use OCP\ILogger; +use OCP\Server; use OCP\Session\Exceptions\SessionNotAvailableException; use Psr\Log\LoggerInterface; use function call_user_func_array; @@ -133,7 +134,7 @@ public function regenerateId(bool $deleteOldSession = true, bool $updateToken = $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 b622459426b16..f59d3fd7fd9cd 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\IGroup; use OCP\IGroupManager; use OCP\IUser; +use OCP\Server; /** * @template-extends QBMapper @@ -30,7 +33,7 @@ public function findAllClassesForUser(IUser $user): array { $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 @@ public function findAllClassesForUser(IUser $user): array { } /** - * @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 6cd8885d2dfe7..c67c4c07708df 100644 --- a/lib/private/Settings/Section.php +++ b/lib/private/Settings/Section.php @@ -7,64 +7,34 @@ namespace OC\Settings; use OCP\Settings\IIconSection; +use Override; 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 string $id, + private string $name, + private int $priority, + private string $icon = '', + ) { } - /** - * @return string The ID of the section. It is supposed to be a lower case string, - * e.g. 'ldap' - */ - public function getID() { + #[Override] + public function getID(): string { return $this->id; } - /** - * @return string The translated name as it should be displayed, e.g. 'LDAP / AD - * integration'. Use the L10N service to translate it. - */ - public function getName() { + #[Override] + public function getName(): string { return $this->name; } - /** - * @return int whether the form should be rather on the top or bottom of - * the settings navigation. The sections are arranged in ascending order of - * the priority values. It is required to return a value between 0 and 99. - * - * E.g.: 70 - */ - public function getPriority() { + #[Override] + public function getPriority(): int { return $this->priority; } - /** - * @return string The relative path to an 16*16 icon describing the section. - * e.g. '/core/img/places/files.svg' - * - * @since 12 - */ - public function getIcon() { + #[Override] + public function getIcon(): string { return $this->icon; } } diff --git a/lib/private/Setup.php b/lib/private/Setup.php index 5f91dc1069261..cefb27e402db9 100644 --- a/lib/private/Setup.php +++ b/lib/private/Setup.php @@ -12,17 +12,26 @@ 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\MovePreviewJob; 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\HintException; use OCP\Http\Client\IClientService; use OCP\IAppConfig; use OCP\IConfig; @@ -38,6 +47,7 @@ use OCP\Security\ISecureRandom; use OCP\Server; use OCP\ServerVersion; +use OCP\Util; use Psr\Log\LoggerInterface; class Setup { @@ -56,11 +66,11 @@ public function __construct( } 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, ]; /** @@ -175,7 +185,7 @@ public function getSystemInfo(bool $allowAllDatabases = false): array { try { $htAccessWorking = $this->isHtaccessWorking($dataDir); - } catch (\OCP\HintException $e) { + } catch (HintException $e) { $errors[] = [ 'error' => $e->getMessage(), 'exception' => $e, @@ -234,7 +244,7 @@ public function createHtaccessTestFile(string $dataDir): string|false { $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); @@ -246,12 +256,10 @@ public function createHtaccessTestFile(string $dataDir): string|false { /** * Check if the .htaccess file is working * - * @param \OCP\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) { + public function isHtaccessWorking(string $dataDir): bool { $config = Server::get(IConfig::class); if (\OC::$CLI || !$config->getSystemValueBool('check_for_working_htaccess', true)) { @@ -326,7 +334,7 @@ public function install(array $options, ?IOutput $output = null): array { $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)); @@ -366,7 +374,7 @@ public function install(array $options, ?IOutput $output = null): array { '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) { @@ -379,7 +387,7 @@ public function install(array $options, ?IOutput $output = null): array { $dbSetup->initialize($options); try { $dbSetup->setupDatabase(); - } catch (\OC\DatabaseSetupException $e) { + } catch (DatabaseSetupException $e) { $error[] = [ 'error' => $e->getMessage(), 'exception' => $e, @@ -468,13 +476,13 @@ public function install(array $options, ?IOutput $output = null): array { 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); @@ -542,8 +550,7 @@ private static function findWebRoot(SystemConfig $config): string { /** * 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); @@ -554,7 +561,7 @@ public static function updateHtaccess(): bool { 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 8f6294faa667d..d07d4af91a6c0 100644 --- a/lib/private/Setup/AbstractDatabase.php +++ b/lib/private/Setup/AbstractDatabase.php @@ -14,40 +14,27 @@ 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 */ - protected $dbPassword; - /** @var string */ - protected $dbName; - /** @var string */ - protected $dbHost; - /** @var string */ - protected $dbPort; - /** @var string */ - protected $tablePrefix; - /** @var SystemConfig */ - protected $config; - /** @var LoggerInterface */ - protected $logger; - /** @var ISecureRandom */ - protected $random; - /** @var bool */ - protected $tryCreateDbUser; + protected string $dbUser; + protected string $dbPassword; + protected string $dbName; + protected string $dbHost; + protected string $dbPort; + protected string $tablePrefix; + protected bool $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) { + public function validate(array $config): array { $errors = []; if (empty($config['dbuser']) && empty($config['dbname'])) { $errors[] = $this->trans->t('Enter the database Login and name for %s', [$this->dbprettyname]); @@ -62,7 +49,7 @@ public function validate($config) { return $errors; } - public function initialize($config) { + public function initialize(array $config): void { $dbUser = $config['dbuser']; $dbPass = $config['dbpass']; $dbName = $config['dbname']; @@ -132,7 +119,7 @@ public function runMigrations(?IOutput $output = null) { 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 c4794a86743e4..24093ae97a40c 100644 --- a/lib/private/Setup/MySQL.php +++ b/lib/private/Setup/MySQL.php @@ -9,15 +9,16 @@ use Doctrine\DBAL\Platforms\MySQL80Platform; use Doctrine\DBAL\Platforms\MySQL84Platform; +use OC\DatabaseSetupException; use OC\DB\ConnectionAdapter; use OC\DB\MySqlTools; use OCP\IDBConnection; use OCP\Security\ISecureRandom; class MySQL extends AbstractDatabase { - public $dbprettyname = 'MySQL/MariaDB'; + public string $dbprettyname = 'MySQL/MariaDB'; - public function setupDatabase() { + public function setupDatabase(): void { //check if the database user has admin right $connection = $this->connect(['dbname' => null]); @@ -52,15 +53,12 @@ public function setupDatabase() { $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); } } - /** - * @param \OC\DB\Connection $connection - */ - private function createDatabase($connection): void { + private function createDatabase(\OC\DB\Connection $connection): void { try { $name = $this->dbName; $user = $this->dbUser; @@ -89,10 +87,9 @@ private function createDatabase($connection): void { } /** - * @param IDBConnection $connection - * @throws \OC\DatabaseSetupException + * @throws DatabaseSetupException */ - private function createDBUser($connection): void { + private function createDBUser(IDBConnection $connection): void { $name = $this->dbUser; $password = $this->dbPassword; @@ -126,11 +123,7 @@ private function createDBUser($connection): void { } } - /** - * @param string $username - * @param IDBConnection $connection - */ - private function createSpecificUser($username, $connection): void { + private function createSpecificUser(string $username, IDBConnection $connection): void { $rootUser = $this->dbUser; $rootPassword = $this->dbPassword; diff --git a/lib/private/Setup/OCI.php b/lib/private/Setup/OCI.php index 61c7f968787de..7bde42c1ace75 100644 --- a/lib/private/Setup/OCI.php +++ b/lib/private/Setup/OCI.php @@ -7,12 +7,14 @@ */ namespace OC\Setup; +use OC\DatabaseSetupException; + class OCI extends AbstractDatabase { public $dbprettyname = 'Oracle'; protected $dbtablespace; - public function initialize($config) { + public function initialize(array $config): void { parent::initialize($config); if (array_key_exists('dbtablespace', $config)) { $this->dbtablespace = $config['dbtablespace']; @@ -28,7 +30,7 @@ public function initialize($config) { ]); } - public function validate($config) { + public function validate(array $config): array { $errors = []; if (empty($config['dbuser']) && empty($config['dbname'])) { $errors[] = $this->trans->t('Enter the database Login and name for %s', [$this->dbprettyname]); @@ -40,20 +42,20 @@ public function validate($config) { return $errors; } - public function setupDatabase() { + public function setupDatabase(): void { try { $this->connect(); } 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') @@ -70,9 +72,8 @@ public function setupDatabase() { /** * @param resource $connection - * @return string */ - protected function getLastError($connection = null) { + protected function getLastError($connection = null): string { if ($connection) { $error = oci_error($connection); } else { diff --git a/lib/private/Setup/PostgreSQL.php b/lib/private/Setup/PostgreSQL.php index 3f8d5e0585447..5ace7f6bcbee3 100644 --- a/lib/private/Setup/PostgreSQL.php +++ b/lib/private/Setup/PostgreSQL.php @@ -8,17 +8,19 @@ 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() { + public function setupDatabase(): void { try { $connection = $this->connect([ 'dbname' => 'postgres' @@ -47,7 +49,7 @@ public function setupDatabase() { //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,12 +98,12 @@ public function setupDatabase() { $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); } } - private function createDatabase(Connection $connection) { + private function createDatabase(Connection $connection): void { if (!$this->databaseExists($connection)) { //The database does not exists... let's create it $query = $connection->prepare('CREATE DATABASE ' . addslashes($this->dbName) . ' OWNER "' . addslashes($this->dbUser) . '"'); @@ -124,7 +126,7 @@ private function createDatabase(Connection $connection) { } } - private function userExists(Connection $connection) { + private function userExists(Connection $connection): bool { $builder = $connection->getQueryBuilder(); $builder->automaticTablePrefix(false); $query = $builder->select('*') @@ -134,7 +136,7 @@ private function userExists(Connection $connection) { return $result->rowCount() > 0; } - private function databaseExists(Connection $connection) { + private function databaseExists(Connection $connection): bool { $builder = $connection->getQueryBuilder(); $builder->automaticTablePrefix(false); $query = $builder->select('datname') @@ -144,7 +146,7 @@ private function databaseExists(Connection $connection) { return $result->rowCount() > 0; } - private function createDBUser(Connection $connection) { + private function createDBUser(Connection $connection): void { $dbUser = $this->dbUser; try { $i = 1; diff --git a/lib/private/Setup/Sqlite.php b/lib/private/Setup/Sqlite.php index b34b1e32ede11..325a26ce89680 100644 --- a/lib/private/Setup/Sqlite.php +++ b/lib/private/Setup/Sqlite.php @@ -10,13 +10,13 @@ use OC\DB\ConnectionFactory; class Sqlite extends AbstractDatabase { - public $dbprettyname = 'Sqlite'; + public string $dbprettyname = 'Sqlite'; - public function validate($config) { + public function validate(array $config): array { return []; } - public function initialize($config) { + public function initialize(array $config): void { /* * Web: When using web based installer its not possible to set dbname * or dbtableprefix. Defaults used from ConnectionFactory and dbtype = 'sqlite' @@ -45,7 +45,7 @@ public function initialize($config) { } } - public function setupDatabase() { + public function setupDatabase(): void { $datadir = $this->config->getValue( 'datadirectory', \OC::$SERVERROOT . '/data' diff --git a/lib/private/Share/Helper.php b/lib/private/Share/Helper.php deleted file mode 100644 index 5f7a8f7b42a7d..0000000000000 --- a/lib/private/Share/Helper.php +++ /dev/null @@ -1,141 +0,0 @@ -getConfig(); - $appConfig = Server::get(IAppConfig::class); - - $defaultExpireSettings = ['defaultExpireDateSet' => false]; - - // get default expire settings - if ($appConfig->getValueBool('core', ConfigLexicon::SHARE_LINK_EXPIRE_DATE_DEFAULT)) { - $defaultExpireSettings['defaultExpireDateSet'] = true; - $defaultExpireSettings['expireAfterDays'] = (int)$config->getAppValue('core', 'shareapi_expire_after_n_days', '7'); - $defaultExpireSettings['enforceExpireDate'] = $appConfig->getValueBool('core', ConfigLexicon::SHARE_LINK_EXPIRE_DATE_ENFORCED); - } - - return $defaultExpireSettings; - } - - public static function calcExpireDate() { - $expireAfter = \OC\Share\Share::getExpireInterval() * 24 * 60 * 60; - $expireAt = time() + $expireAfter; - $date = new \DateTime(); - $date->setTimestamp($expireAt); - $date->setTime(0, 0, 0); - //$dateString = $date->format('Y-m-d') . ' 00:00:00'; - - return $date; - } - - /** - * calculate expire date - * @param array $defaultExpireSettings contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays' - * @param int $creationTime timestamp when the share was created - * @param int $userExpireDate expire timestamp set by the user - * @return mixed integer timestamp or False - */ - public static function calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate = null) { - $expires = false; - $defaultExpires = null; - - if (!empty($defaultExpireSettings['defaultExpireDateSet'])) { - $defaultExpires = $creationTime + $defaultExpireSettings['expireAfterDays'] * 86400; - } - - - if (isset($userExpireDate)) { - // if the admin decided to enforce the default expire date then we only take - // the user defined expire date of it is before the default expire date - if ($defaultExpires && !empty($defaultExpireSettings['enforceExpireDate'])) { - $expires = min($userExpireDate, $defaultExpires); - } else { - $expires = $userExpireDate; - } - } elseif ($defaultExpires && !empty($defaultExpireSettings['enforceExpireDate'])) { - $expires = $defaultExpires; - } - - return $expires; - } - - /** - * Strips away a potential file names and trailing slashes: - * - http://localhost - * - http://localhost/ - * - http://localhost/index.php - * - http://localhost/index.php/s/{shareToken} - * - * all return: http://localhost - * - * @param string $remote - * @return string - */ - protected static function fixRemoteURL($remote) { - $remote = str_replace('\\', '/', $remote); - if ($fileNamePosition = strpos($remote, '/index.php')) { - $remote = substr($remote, 0, $fileNamePosition); - } - $remote = rtrim($remote, '/'); - - return $remote; - } - - /** - * check if two federated cloud IDs refer to the same user - * - * @param string $user1 - * @param string $server1 - * @param string $user2 - * @param string $server2 - * @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)); - - if (rtrim($normalizedServer1, '/') === rtrim($normalizedServer2, '/')) { - // FIXME this should be a method in the user management instead - \OCP\Util::emitHook( - '\OCA\Files_Sharing\API\Server2Server', - 'preLoginNameUsedAsUserName', - ['uid' => &$user1] - ); - \OCP\Util::emitHook( - '\OCA\Files_Sharing\API\Server2Server', - 'preLoginNameUsedAsUserName', - ['uid' => &$user2] - ); - - if ($user1 === $user2) { - return true; - } - } - - return false; - } - - public static function getTokenLength(): int { - $config = Server::get(\OCP\IAppConfig::class); - $tokenLength = $config->getValueInt('core', 'shareapi_token_length', self::DEFAULT_TOKEN_LENGTH); - $tokenLength = $tokenLength ?: self::DEFAULT_TOKEN_LENGTH; - - // Token length should be within the defined min and max limits - return max(self::MIN_TOKEN_LENGTH, min($tokenLength, self::MAX_TOKEN_LENGTH)); - } -} diff --git a/lib/private/Share/Share.php b/lib/private/Share/Share.php index 1121d71e45f21..6f4c373dcf9d5 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 @@ public static function registerBackend($itemType, $class, $collectionOf = null, ]; 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 @@ public static function registerBackend($itemType, $class, $collectionOf = null, * 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 @@ public static function getBackend($itemType) { */ 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 @@ public static function removeProtocolFromUrl($url) { * @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 bc74002fcbc09..304fa1b8ffd7e 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 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\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; @@ -36,6 +42,7 @@ use OCP\Share\IShareProviderSupportsAccept; use OCP\Share\IShareProviderSupportsAllSharesInFolder; use OCP\Share\IShareProviderWithNotification; +use OCP\Util; use Psr\Log\LoggerInterface; use function str_starts_with; @@ -73,12 +80,12 @@ public function identifier() { /** * 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'); @@ -136,7 +143,7 @@ public function create(\OCP\Share\IShare $share) { // 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'); @@ -191,13 +198,13 @@ public function create(\OCP\Share\IShare $share) { /** * 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()); @@ -388,9 +395,9 @@ public function getChildren(IShare $parent): array { /** * 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()))); @@ -483,7 +490,7 @@ protected function createUserSpecificGroupShare(IShare $share, string $recipient } $target = $shareFolder . '/' . $share->getNode()->getName(); - $target = \OC\Files\Filesystem::normalizePath($target); + $target = Filesystem::normalizePath($target); $qb = $this->dbConn->getQueryBuilder(); $qb->insert('share') @@ -542,7 +549,7 @@ public function restore(IShare $share, string $recipient): IShare { /** * @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(); @@ -775,8 +782,8 @@ public function getShareById($id, $recipientId = null) { /** * 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(); @@ -952,7 +959,7 @@ public function getSharedWith($userId, $shareType, $node, $limit, $offset) { * Get a share by token * * @param string $token - * @return \OCP\Share\IShare + * @return IShare * @throws ShareNotFound */ public function getShareByToken($token) { @@ -984,7 +991,7 @@ public function getShareByToken($token) { * Create a share object from a database row * * @param mixed[] $data - * @return \OCP\Share\IShare + * @return IShare * @throws InvalidShare */ private function createShare($data) { @@ -1038,7 +1045,7 @@ private function createShare($data) { $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()); @@ -1400,7 +1407,7 @@ protected function filterSharesOfUser(array $shares) { * 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) { @@ -1509,7 +1516,7 @@ protected function sendUserShareMail( $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. @@ -1538,7 +1545,7 @@ protected function sendUserShareMail( * * @param array $recipients * @param IShare $share - * @throws \OCP\Files\NotFoundException + * @throws NotFoundException */ private function sendNote(array $recipients, IShare $share) { $toListByLanguage = []; @@ -1596,7 +1603,7 @@ private function sendNote(array $recipients, IShare $share) { $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 d54c8e3203d17..5c79ad9b5d0f8 100644 --- a/lib/private/Share20/LegacyHooks.php +++ b/lib/private/Share20/LegacyHooks.php @@ -17,25 +17,22 @@ 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 010765af3c4c1..fea954b130ef5 100644 --- a/lib/private/Share20/Manager.php +++ b/lib/private/Share20/Manager.php @@ -8,13 +8,16 @@ namespace OC\Share20; use OC\Core\AppInfo\ConfigLexicon; +use OC\Files\Filesystem; use OC\Files\Mount\MoveableMount; use OC\KnownUser\KnownUserService; -use OC\Share\Helper; +use OC\Share\Constants as ShareConstants; 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; @@ -39,6 +42,7 @@ 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; @@ -55,6 +59,7 @@ use OCP\Share\IShareProviderSupportsAccept; use OCP\Share\IShareProviderSupportsAllSharesInFolder; use OCP\Share\IShareProviderWithNotification; +use OCP\Util; use Override; use Psr\Log\LoggerInterface; @@ -162,7 +167,8 @@ protected function generalCreateChecks(IShare $share, bool $isUpdate = false): v 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')); } @@ -191,8 +197,8 @@ protected function generalCreateChecks(IShare $share, bool $isUpdate = false): v } // 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')); } @@ -217,13 +223,13 @@ protected function generalCreateChecks(IShare $share, bool $isUpdate = false): v } // 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')); } @@ -250,15 +256,15 @@ protected function generalCreateChecks(IShare $share, bool $isUpdate = false): v $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')); } } @@ -339,7 +345,7 @@ protected function validateExpirationDateInternal(IShare $share): IShare { $accepted = true; $message = ''; - \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [ + Util::emitHook('\OC\Share', 'verifyExpirationDate', [ 'expirationDate' => &$expirationDate, 'accepted' => &$accepted, 'message' => &$message, @@ -422,7 +428,7 @@ protected function validateExpirationDateLink(IShare $share): IShare { $accepted = true; $message = ''; - \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [ + Util::emitHook('\OC\Share', 'verifyExpirationDate', [ 'expirationDate' => &$expirationDate, 'accepted' => &$accepted, 'message' => &$message, @@ -557,7 +563,7 @@ protected function linkCreateChecks(IShare $share): void { // 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')); } } @@ -574,14 +580,14 @@ protected function linkCreateChecks(IShare $share): void { 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')) { @@ -692,11 +698,11 @@ public function createShare(IShare $share): IShare { } $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()); @@ -849,7 +855,7 @@ public function updateShare(IShare $share, bool $onlyValid = true): IShare { 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(), @@ -858,7 +864,7 @@ public function updateShare(IShare $share, bool $onlyValid = true): IShare { 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(), @@ -873,7 +879,7 @@ public function updateShare(IShare $share, bool $onlyValid = true): IShare { $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(), @@ -1185,8 +1191,8 @@ public function getSharesInFolder($userId, Folder $node, bool $reshares = false, #[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')); } @@ -1379,7 +1385,7 @@ public function getShareByToken(string $token): IShare { */ 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; @@ -1833,10 +1839,18 @@ public function getAllShares(): iterable { } } + private function getTokenLength(): int { + $tokenLength = $this->appConfig->getValueInt('core', 'shareapi_token_length', ShareConstants::DEFAULT_TOKEN_LENGTH); + $tokenLength = $tokenLength ?: ShareConstants::DEFAULT_TOKEN_LENGTH; + + // Token length should be within the defined min and max limits + return max(ShareConstants::MIN_TOKEN_LENGTH, min($tokenLength, ShareConstants::MAX_TOKEN_LENGTH)); + } + #[Override] public function generateToken(): string { // Initial token length - $tokenLength = Helper::getTokenLength(); + $tokenLength = $this->getTokenLength(); do { $tokenExists = false; @@ -1864,7 +1878,7 @@ public function generateToken(): string { $tokenLength++; // Check if the token length exceeds the maximum allowed length - if ($tokenLength > \OC\Share\Constants::MAX_TOKEN_LENGTH) { + if ($tokenLength > ShareConstants::MAX_TOKEN_LENGTH) { throw new ShareTokenException('Unable to generate a unique share token. Maximum token length exceeded.'); } } diff --git a/lib/private/Share20/ShareHelper.php b/lib/private/Share20/ShareHelper.php index 3f6bab98a7fa6..d03f89443f5cd 100644 --- a/lib/private/Share20/ShareHelper.php +++ b/lib/private/Share20/ShareHelper.php @@ -14,11 +14,9 @@ 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 f06c945b59171..10cb68f9b9e3c 100644 --- a/lib/private/Share20/UserRemovedListener.php +++ b/lib/private/Share20/UserRemovedListener.php @@ -17,11 +17,9 @@ * @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 34fe590efbd99..00f14212c57a1 100644 --- a/lib/private/StreamImage.php +++ b/lib/private/StreamImage.php @@ -9,6 +9,7 @@ use OCP\IImage; use OCP\IStreamImage; +use Override; /** * Only useful when dealing with transferring streamed previews from an external @@ -18,126 +19,136 @@ * 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 */ + #[Override] public function valid(): bool { return is_resource($this->stream); } - /** @inheritDoc */ + #[Override] public function mimeType(): ?string { return $this->mimeType; } - /** @inheritDoc */ + #[Override] public function width(): int { return $this->width; } - /** @inheritDoc */ + #[Override] public function height(): int { return $this->height; } + #[Override] public function widthTopLeft(): int { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function heightTopLeft(): int { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function show(?string $mimeType = null): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function save(?string $filePath = null, ?string $mimeType = null): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function resource() { return $this->stream; } + #[Override] public function dataMimeType(): ?string { return $this->mimeType; } + #[Override] public function data(): ?string { return ''; } + #[Override] public function getOrientation(): int { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function fixOrientation(): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function resize(int $maxSize): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function preciseResize(int $width, int $height): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function centerCrop(int $size = 0): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function crop(int $x, int $y, int $w, int $h): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function fitIn(int $maxWidth, int $maxHeight): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function scaleDownToFit(int $maxWidth, int $maxHeight): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function copy(): IImage { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function cropCopy(int $x, int $y, int $w, int $h): IImage { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function preciseResizeCopy(int $width, int $height): IImage { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function resizeCopy(int $maxSize): IImage { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function loadFromData(string $str): \GdImage|false { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function readExif(string $data): void { throw new \BadMethodCallException('Not implemented'); } diff --git a/lib/private/Streamer.php b/lib/private/Streamer.php index 7ebb66bf03a2b..eba7f4e98e98e 100644 --- a/lib/private/Streamer.php +++ b/lib/private/Streamer.php @@ -16,6 +16,7 @@ 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 @@ public function addDirRecursive(string $dir, string $internalDir = ''): void { // 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 90756e2d3fdc6..5d97623726b58 100644 --- a/lib/private/SubAdmin.php +++ b/lib/private/SubAdmin.php @@ -25,10 +25,10 @@ public function __construct( 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 04a0dde739f19..7e90b0f2bbceb 100644 --- a/lib/private/Support/Subscription/Assertion.php +++ b/lib/private/Support/Subscription/Assertion.php @@ -14,14 +14,11 @@ 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 34f24d1d0266f..862f5647cf188 100644 --- a/lib/private/Support/Subscription/Registry.php +++ b/lib/private/Support/Subscription/Registry.php @@ -8,54 +8,36 @@ */ namespace OC\Support\Subscription; -use OCP\AppFramework\QueryException; use OCP\IConfig; use OCP\IGroupManager; -use OCP\IServerContainer; use OCP\IUserManager; use OCP\Notification\IManager; use OCP\Support\Subscription\Exception\AlreadyRegisteredException; use OCP\Support\Subscription\IRegistry; use OCP\Support\Subscription\ISubscription; use OCP\Support\Subscription\ISupportedApps; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; class Registry implements IRegistry { - /** @var ISubscription */ - private $subscription = null; - - /** @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; + private ?ISubscription $subscription = null; + private ?string $subscriptionService = null; + + public function __construct( + private IConfig $config, + private ContainerInterface $container, + private IUserManager $userManager, + private IGroupManager $groupManager, + private LoggerInterface $logger, + ) { } private function getSubscription(): ?ISubscription { if ($this->subscription === null && $this->subscriptionService !== null) { try { - $this->subscription = $this->container->query($this->subscriptionService); - } catch (QueryException $e) { + $this->subscription = $this->container->get($this->subscriptionService); + } catch (ContainerExceptionInterface) { // Ignore this } } @@ -67,7 +49,6 @@ private function getSubscription(): ?ISubscription { * Register a subscription instance. In case it is called multiple times the * first one is used. * - * @param ISubscription $subscription * @throws AlreadyRegisteredException * * @since 17.0.0 diff --git a/lib/private/SystemTag/SystemTagObjectMapper.php b/lib/private/SystemTag/SystemTagObjectMapper.php index e0eb68cfa1791..65e3cf7052662 100644 --- a/lib/private/SystemTag/SystemTagObjectMapper.php +++ b/lib/private/SystemTag/SystemTagObjectMapper.php @@ -268,7 +268,7 @@ public function haveTag($objIds, string $objectType, string $tagId, bool $all = * * @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 f9d8d71a5aaf3..e8fd005ff0035 100644 --- a/lib/private/TagManager.php +++ b/lib/private/TagManager.php @@ -45,7 +45,7 @@ public function __construct( * @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 309d373934896..5ab392cc3dedf 100644 --- a/lib/private/Tags.php +++ b/lib/private/Tags.php @@ -18,7 +18,9 @@ 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 @@ public function getIdsForTag($tag) { } 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 @@ public function getFavorites() { 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 @@ public function tagAs($objid, $tag, ?string $path = null) { 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 86e7e7ff4c1ac..eaf5fad96c68e 100644 --- a/lib/private/Talk/Broker.php +++ b/lib/private/Talk/Broker.php @@ -21,22 +21,15 @@ 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 f167fa6d164c7..a71f9822d5251 100644 --- a/lib/private/Talk/ConversationOptions.php +++ b/lib/private/Talk/ConversationOptions.php @@ -12,10 +12,9 @@ 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 3609f309cc47b..13eb88dc49795 100644 --- a/lib/private/TaskProcessing/Manager.php +++ b/lib/private/TaskProcessing/Manager.php @@ -14,6 +14,8 @@ 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\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\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 @@ private function _getTextProcessingProviders(): array { $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 @@ public function getName(): string { 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 @@ public function getOptionalOutputShape(): array { } 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 @@ private function _getTextProcessingTaskTypes(): array { 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,12 +335,10 @@ private function _getTextToImageProviders(): array { $newProviders = []; foreach ($oldProviders as $oldProvider) { $newProvider = new class($oldProvider, $this->appData) implements IProvider, ISynchronousProvider { - private \OCP\TextToImage\IProvider $provider; - private IAppData $appData; - - public function __construct(\OCP\TextToImage\IProvider $provider, IAppData $appData) { - $this->provider = $provider; - $this->appData = $appData; + public function __construct( + private \OCP\TextToImage\IProvider $provider, + private IAppData $appData, + ) { } public function getId(): string { @@ -437,15 +462,11 @@ private function _getSpeechToTextProviders(): array { $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 { @@ -476,7 +497,7 @@ public function getOptionalOutputShape(): array { } 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 { @@ -590,28 +611,28 @@ private function _getTaskTypes(): array { // 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) { @@ -959,7 +980,7 @@ private function checkGuestAccess(?string $userId = null): bool { } $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; @@ -967,10 +988,10 @@ private function checkGuestAccess(?string $userId = null): bool { 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); @@ -1006,10 +1027,10 @@ public function scheduleTask(Task $task): void { 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()); @@ -1219,7 +1240,7 @@ public function getNextScheduledTask(array $taskTypeIds = [], array $taskIdsToIg $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) { @@ -1231,7 +1252,7 @@ public function getNextScheduledTasks(array $taskTypeIds = [], array $taskIdsToI 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) { @@ -1286,7 +1307,7 @@ public function getUserTask(int $id, ?string $userId): Task { $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) { @@ -1683,7 +1704,7 @@ private function runWebhook(Task $task): void { 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 52fc204b7525d..48a2cd256a895 100644 --- a/lib/private/TaskProcessing/RemoveOldTasksBackgroundJob.php +++ b/lib/private/TaskProcessing/RemoveOldTasksBackgroundJob.php @@ -10,10 +10,13 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\TimedJob; use OCP\Files\AppData\IAppDataFactory; +use OCP\Files\IAppData; +use OCP\Files\NotFoundException; +use Override; use Psr\Log\LoggerInterface; class RemoveOldTasksBackgroundJob extends TimedJob { - private \OCP\Files\IAppData $appData; + private IAppData $appData; public function __construct( ITimeFactory $timeFactory, @@ -29,9 +32,7 @@ public function __construct( $this->appData = $appDataFactory->get('core'); } - /** - * @inheritDoc - */ + #[Override] protected function run($argument): void { try { iterator_to_array($this->taskProcessingManager->cleanupTaskProcessingTaskFiles()); @@ -45,12 +46,12 @@ protected function run($argument): void { } try { iterator_to_array($this->taskProcessingManager->clearFilesOlderThan($this->appData->getFolder('text2image'))); - } catch (\OCP\Files\NotFoundException $e) { + } catch (NotFoundException) { // noop } try { iterator_to_array($this->taskProcessingManager->clearFilesOlderThan($this->appData->getFolder('audio2text'))); - } catch (\OCP\Files\NotFoundException $e) { + } catch (NotFoundException) { // noop } } diff --git a/lib/private/TempManager.php b/lib/private/TempManager.php index 4c0ffcf43d7a9..052b1845addb5 100644 --- a/lib/private/TempManager.php +++ b/lib/private/TempManager.php @@ -12,32 +12,28 @@ use OCP\IConfig; use OCP\ITempManager; use OCP\Security\ISecureRandom; +use OCP\Server; use Psr\Log\LoggerInterface; class TempManager implements ITempManager { /** @var string[] Current temporary files and folders, used for cleanup */ - protected $current = []; - /** @var string i.e. /tmp on linux systems */ - protected $tmpBaseDir; - /** @var LoggerInterface */ - protected $log; - /** @var IConfig */ - protected $config; - /** @var IniGetWrapper */ - protected $iniGetWrapper; + protected array $current = []; + /** @var ?string i.e. /tmp on linux systems */ + protected ?string $tmpBaseDir = null; /** Prefix */ public const TMP_PREFIX = 'oc_tmp_'; - public function __construct(LoggerInterface $logger, IConfig $config, IniGetWrapper $iniGetWrapper) { - $this->log = $logger; - $this->config = $config; - $this->iniGetWrapper = $iniGetWrapper; + public function __construct( + protected LoggerInterface $log, + protected IConfig $config, + protected 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 !== '') { @@ -150,7 +146,7 @@ protected function getOldFiles() { * @return string Path to the temporary directory or null * @throws \UnexpectedValueException */ - public function getTempBaseDir() { + public function getTempBaseDir(): string { if ($this->tmpBaseDir) { return $this->tmpBaseDir; } diff --git a/lib/private/TemplateLayout.php b/lib/private/TemplateLayout.php index 6c1fe71e4e9c5..f3109ba8cb5db 100644 --- a/lib/private/TemplateLayout.php +++ b/lib/private/TemplateLayout.php @@ -17,17 +17,21 @@ 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 @@ public function getPageTemplate(string $renderAs, string $appId): ITemplate { // 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 @@ public function getPageTemplate(string $renderAs, string $appId): ITemplate { // 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 @@ public function getPageTemplate(string $renderAs, string $appId): ITemplate { $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 @@ public function getPageTemplate(string $renderAs, string $appId): ITemplate { // 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 @@ private function getVersionHashByPath(string $path): string|false { 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 @@ public function getAppNamefromPath(string $path): string|false { 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 cc92c86522053..48a8bcc6c407d 100644 --- a/lib/private/TextToImage/Db/Task.php +++ b/lib/private/TextToImage/Db/Task.php @@ -12,6 +12,7 @@ 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 @@ public static function fromPublicTask(OCPTask $task): Task { /** @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 b6c4b49469d58..0debd9ba99af8 100644 --- a/lib/private/URLGenerator.php +++ b/lib/private/URLGenerator.php @@ -18,45 +18,28 @@ 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 ?string $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 +47,7 @@ private function getNavigationManager(): INavigationManager { 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 +187,7 @@ public function imagePath(string $appName, string $file): string { $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 +260,7 @@ public function getAbsoluteURL(string $url): string { * @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 da7b52e549306..8c0a3f363d367 100644 --- a/lib/private/Updater.php +++ b/lib/private/Updater.php @@ -30,6 +30,7 @@ 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 @@ private function doUpgrade(string $currentVersion, string $installedVersion): vo ); // pre-upgrade repairs - $repair = \OCP\Server::get(Repair::class); + $repair = Server::get(Repair::class); $repair->setRepairSteps(Repair::getBeforeUpgradeRepairSteps()); $repair->run(); @@ -236,7 +237,7 @@ private function doUpgrade(string $currentVersion, string $installedVersion): vo $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 @@ private function doUpgrade(string $currentVersion, string $installedVersion): vo } // post-upgrade repairs - $repair = \OCP\Server::get(Repair::class); + $repair = Server::get(Repair::class); $repair->setRepairSteps(Repair::getRepairSteps()); $repair->run(); @@ -266,7 +267,7 @@ private function doUpgrade(string $currentVersion, string $installedVersion): vo $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 @@ protected function doCoreUpgrade(): void { $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 @@ private function logAllEvents(): void { $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 @@ function (MigratorExecuteSqlEvent $event) use ($log): void { $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/Updater/ChangesCheck.php b/lib/private/Updater/ChangesCheck.php index e88969f62a84a..665b4e88b8cda 100644 --- a/lib/private/Updater/ChangesCheck.php +++ b/lib/private/Updater/ChangesCheck.php @@ -14,20 +14,15 @@ use Psr\Log\LoggerInterface; class ChangesCheck { - /** @var IClientService */ - protected $clientService; - /** @var ChangesMapper */ - private $mapper; - private LoggerInterface $logger; - public const RESPONSE_NO_CONTENT = 0; public const RESPONSE_USE_CACHE = 1; public const RESPONSE_HAS_CONTENT = 2; - public function __construct(IClientService $clientService, ChangesMapper $mapper, LoggerInterface $logger) { - $this->clientService = $clientService; - $this->mapper = $mapper; - $this->logger = $logger; + public function __construct( + protected IClientService $clientService, + private ChangesMapper $mapper, + private LoggerInterface $logger, + ) { } /** diff --git a/lib/private/User/BackgroundJobs/CleanupDeletedUsers.php b/lib/private/User/BackgroundJobs/CleanupDeletedUsers.php index f999031a2a90a..0adb7861670f3 100644 --- a/lib/private/User/BackgroundJobs/CleanupDeletedUsers.php +++ b/lib/private/User/BackgroundJobs/CleanupDeletedUsers.php @@ -15,6 +15,7 @@ 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 @@ protected function run($argument): void { $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 314882479399a..7877deff62f37 100644 --- a/lib/private/User/Database.php +++ b/lib/private/User/Database.php @@ -17,6 +17,7 @@ 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,21 +49,16 @@ class Database extends ABackend implements private IConfig $config; private ?IDBConnection $dbConnection; private IEventDispatcher $eventDispatcher; - private string $table; use TTransactional; - /** - * \OC\User\Database constructor. - * - * @param IEventDispatcher $eventDispatcher - * @param string $table - */ - public function __construct($eventDispatcher = null, $table = 'users') { + public function __construct( + ?IEventDispatcher $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 +67,7 @@ public function __construct($eventDispatcher = null, $table = 'users') { */ 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 +95,7 @@ public function createUser(string $uid, string $password): bool { $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 +164,7 @@ public function setPassword(string $uid, string $password): bool { $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 +200,7 @@ public function getPasswordHash(string $userId): ?string { } 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 +351,7 @@ public function checkPassword(string $loginName, string $password) { 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 +519,10 @@ public static function preLoginNameUsedAsUserName($param) { 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 4321d95f88e26..96386ca35f29b 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 501169019d4ea..215444fc79bb3 100644 --- a/lib/private/User/LazyUser.php +++ b/lib/private/User/LazyUser.php @@ -14,16 +14,13 @@ 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 { @@ -44,7 +41,7 @@ private function getUser(): IUser { return $this->user; } - public function getUID() { + public function getUID(): string { return $this->uid; } diff --git a/lib/private/User/Listeners/BeforeUserDeletedListener.php b/lib/private/User/Listeners/BeforeUserDeletedListener.php index 50dc983540037..c5d7efa767ae0 100644 --- a/lib/private/User/Listeners/BeforeUserDeletedListener.php +++ b/lib/private/User/Listeners/BeforeUserDeletedListener.php @@ -20,14 +20,11 @@ * @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 8f61895025574..4dd4439574da1 100644 --- a/lib/private/User/Listeners/UserChangedListener.php +++ b/lib/private/User/Listeners/UserChangedListener.php @@ -18,10 +18,9 @@ * @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 4a42a397a8e47..1906292199c48 100644 --- a/lib/private/User/Manager.php +++ b/lib/private/User/Manager.php @@ -18,6 +18,7 @@ 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\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 @@ public function clearBackends(): void { * 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 @@ public function getDisplayName(string $uid): ?string { * 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 @@ public function checkPassword($loginName, $password) { $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; @@ -373,10 +375,10 @@ public function searchKnownUsersByDisplayName(string $searcher, string $pattern, * @throws \InvalidArgumentException * @throws HintException */ - public function createUser($uid, $password) { + public function createUser($uid, $password): IUser|false { // 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 = []; @@ -404,12 +406,10 @@ public function createUser($uid, $password) { /** * @param string $uid * @param string $password - * @param UserInterface $backend - * @return IUser|false * @throws \InvalidArgumentException */ - public function createUserFromBackend($uid, $password, UserInterface $backend) { - $l = \OCP\Util::getL10N('lib'); + public function createUserFromBackend($uid, $password, UserInterface $backend): IUser|false { + $l = Util::getL10N('lib'); $this->validateUserId($uid, true); @@ -528,7 +528,7 @@ public function countUsersAndDisabledUsersOfGroups(array $groups, int $limit): a * 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 e7bfcf56407be..3759ffaf9280f 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\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\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 @@ public function setImpersonatingUserID(bool $useCurrentUser = true): void { $currentUser = $this->getUser(); if ($currentUser === null) { - throw new \OC\User\NoUserException(); + throw new NoUserException(); } $this->session->set('oldUserId', $currentUser->getUID()); } @@ -319,7 +322,7 @@ public function completeLogin(IUser $user, array $loginDetails, $regenerateSessi 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 @@ public function completeLogin(IUser $user, array $loginDetails, $regenerateSessi 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); } @@ -440,7 +443,7 @@ private function handleLoginFailed(IThrottler $throttler, int $currentDelay, str $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'); @@ -477,7 +480,7 @@ protected function isTwoFactorEnforced($username) { $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); } /** @@ -505,7 +508,7 @@ protected function prepareUserLogin($firstTimeLogin, $refreshCsrfToken = true) { if ($refreshCsrfToken) { // TODO: mock/inject/use non-static // Refresh the token - \OC::$server->get(CsrfTokenManager::class)->refreshToken(); + Server::get(CsrfTokenManager::class)->refreshToken(); } if ($firstTimeLogin) { @@ -525,8 +528,8 @@ protected function prepareUserLogin($firstTimeLogin, $refreshCsrfToken = true) { } // 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())); } } @@ -647,10 +650,10 @@ public function createSessionToken(IRequest $request, $uid, $loginName, $passwor $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 @@ -963,7 +966,7 @@ public function logout() { * @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 = '/'; @@ -971,7 +974,7 @@ public function setMagicInCookie($username, $token) { $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, @@ -979,9 +982,9 @@ public function setMagicInCookie($username, $token) { $domain, $secureCookie, true, - \OC\Http\CookieHelper::SAMESITE_LAX + CookieHelper::SAMESITE_LAX ); - \OC\Http\CookieHelper::setCookie( + CookieHelper::setCookie( 'nc_token', $token, $maxAge, @@ -989,10 +992,10 @@ public function setMagicInCookie($username, $token) { $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, @@ -1000,7 +1003,7 @@ public function setMagicInCookie($username, $token) { $domain, $secureCookie, true, - \OC\Http\CookieHelper::SAMESITE_LAX + CookieHelper::SAMESITE_LAX ); } catch (SessionNotAvailableException $ex) { // ignore @@ -1012,7 +1015,7 @@ public function setMagicInCookie($username, $token) { */ 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 1de44193cbc97..0f369bca5a296 100644 --- a/lib/private/User/User.php +++ b/lib/private/User/User.php @@ -14,6 +14,7 @@ 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\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\IProvideAvatarBackend; @@ -38,6 +40,7 @@ use OCP\User\Events\UserDeletedEvent; use OCP\User\GetQuotaEvent; use OCP\UserInterface; +use OCP\Util; use Psr\Log\LoggerInterface; use function json_decode; @@ -48,56 +51,36 @@ class User implements IUser { private IConfig $config; private IURLGenerator $urlGenerator; + protected ?IAccountManager $accountManager = null; - /** @var IAccountManager */ - protected $accountManager; - - /** @var string|null */ - private $displayName; - - /** @var bool|null */ - private $enabled; - - /** @var Emitter|Manager|null */ - private $emitter; - - /** @var string */ - private $home; + private ?string $displayName = null; + private ?bool $enabled = null; + private ?string $home = null; private ?int $lastLogin = null; private ?int $firstLogin = null; - - /** @var IAvatarManager */ - private $avatarManager; + private ?IAvatarManager $avatarManager = null; public function __construct( private string $uid, private ?UserInterface $backend, private IEventDispatcher $dispatcher, - $emitter = null, + private Emitter|Manager|null $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); } - /** - * get the user id - * - * @return string - */ - public function getUID() { + public function getUID(): string { return $this->uid; } /** - * get the display name for the user, if no specific display name is set it will fallback to the user id - * - * @return string + * Get the display name for the user, if no specific display name is set it will fallback to the user id */ - public function getDisplayName() { + public function getDisplayName(): string { if ($this->displayName === null) { $displayName = ''; if ($this->backend && $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) { @@ -118,15 +101,14 @@ public function getDisplayName() { } /** - * set the displayname for the user + * Set the displayname for the user * * @param string $displayName - * @return bool * * @since 25.0.0 Throw InvalidArgumentException * @throws \InvalidArgumentException */ - public function setDisplayName($displayName) { + public function setDisplayName($displayName): bool { $displayName = trim($displayName); $oldDisplayName = $this->getDisplayName(); if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName) && $displayName !== $oldDisplayName) { @@ -145,7 +127,7 @@ public function setDisplayName($displayName) { /** * @inheritDoc */ - public function setEMailAddress($mailAddress) { + public function setEMailAddress($mailAddress): void { $this->setSystemEMailAddress($mailAddress); } @@ -196,7 +178,7 @@ public function setPrimaryEMailAddress(string $mailAddress): void { private function ensureAccountManager() { if (!$this->accountManager instanceof IAccountManager) { - $this->accountManager = \OC::$server->get(IAccountManager::class); + $this->accountManager = Server::get(IAccountManager::class); } } @@ -251,12 +233,10 @@ public function updateLastLoginTimestamp(): bool { /** * Delete the user - * - * @return bool */ - public function delete() { + public function delete(): bool { 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; } @@ -281,7 +261,7 @@ public function delete() { } // 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) { @@ -291,22 +271,22 @@ public function delete() { } } - $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) @@ -341,9 +321,8 @@ public function delete() { * * @param string $password * @param string $recoveryPassword for the encryption app to reset encryption keys - * @return bool */ - public function setPassword($password, $recoveryPassword = null) { + public function setPassword($password, $recoveryPassword = null): bool { $this->dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($this, $password, $recoveryPassword)); if ($this->emitter) { $this->emitter->emit('\OC\User', 'preSetPassword', [$this, $password, $recoveryPassword]); @@ -381,11 +360,9 @@ public function setPasswordHash(string $passwordHash): bool { } /** - * get the users home folder to mount - * - * @return string + * Get the users home folder to mount */ - public function getHome() { + public function getHome(): string { if (!$this->home) { /** @psalm-suppress UndefinedInterfaceMethod Once we get rid of the legacy implementsActions, psalm won't complain anymore */ if (($this->backend instanceof IGetHomeBackend || $this->backend->implementsActions(Backend::GET_HOME)) && $home = $this->backend->getHome($this->uid)) { @@ -399,10 +376,8 @@ public function getHome() { /** * Get the name of the backend class the user is connected with - * - * @return string */ - public function getBackendClassName() { + public function getBackendClassName(): string { if ($this->backend instanceof IUserBackend) { return $this->backend->getBackendName(); } @@ -415,10 +390,8 @@ public function getBackend(): ?UserInterface { /** * Check if the backend allows the user to change their avatar on Personal page - * - * @return bool */ - public function canChangeAvatar() { + public function canChangeAvatar(): bool { if ($this->backend instanceof IProvideAvatarBackend || $this->backend->implementsActions(Backend::PROVIDE_AVATAR)) { /** @var IProvideAvatarBackend $backend */ $backend = $this->backend; @@ -428,20 +401,16 @@ public function canChangeAvatar() { } /** - * check if the backend supports changing passwords - * - * @return bool + * Check if the backend supports changing passwords */ - public function canChangePassword() { + public function canChangePassword(): bool { return $this->backend->implementsActions(Backend::SET_PASSWORD); } /** - * check if the backend supports changing display names - * - * @return bool + * Check if the backend supports changing display names */ - public function canChangeDisplayName() { + public function canChangeDisplayName(): bool { if (!$this->config->getSystemValueBool('allow_user_to_change_display_name', true)) { return false; } @@ -454,11 +423,9 @@ public function canChangeEmail(): bool { } /** - * check if the user is enabled - * - * @return bool + * Check if the user is enabled */ - public function isEnabled() { + public function isEnabled(): bool { $queryDatabaseValue = function (): bool { if ($this->enabled === null) { $enabled = $this->config->getUserValue($this->uid, 'core', 'enabled', 'true'); @@ -503,12 +470,11 @@ public function setEnabled(bool $enabled = true) { } /** - * get the users email address + * Get the users email address * - * @return string|null * @since 9.0.0 */ - public function getEMailAddress() { + public function getEMailAddress(): ?string { return $this->getPrimaryEMailAddress() ?? $this->getSystemEMailAddress(); } @@ -531,10 +497,9 @@ public function getPrimaryEMailAddress(): ?string { /** * get the users' quota * - * @return string * @since 9.0.0 */ - public function getQuota() { + public function getQuota(): string { // allow apps to modify the user quota by hooking into the event $event = new GetQuotaEvent($this); $this->dispatcher->dispatchTyped($event); @@ -565,32 +530,31 @@ public function getQuota() { 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; } /** - * set the users' quota + * Set the users' quota * * @param string $quota - * @return void * @throws InvalidArgumentException * @since 9.0.0 */ - public function setQuota($quota) { + public function setQuota($quota): void { $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); @@ -624,13 +588,12 @@ public function setManagerUids(array $uids): void { * get the avatar image if it exists * * @param int $size - * @return IImage|null * @since 9.0.0 */ - public function getAvatarImage($size) { + public function getAvatarImage($size): ?IImage { // 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); @@ -645,10 +608,9 @@ public function getAvatarImage($size) { /** * get the federation cloud id * - * @return string * @since 9.0.0 */ - public function getCloudId() { + public function getCloudId(): string { $uid = $this->getUID(); $server = rtrim($this->urlGenerator->getAbsoluteURL('/'), '/'); if (str_ends_with($server, '/index.php')) { @@ -666,7 +628,7 @@ private function removeProtocolFromUrl(string $url): string { return $url; } - public function triggerChange($feature, $value = null, $oldValue = null) { + public function triggerChange($feature, $value = null, $oldValue = null): void { $this->dispatcher->dispatchTyped(new UserChangedEvent($this, $feature, $value, $oldValue)); if ($this->emitter) { $this->emitter->emit('\OC\User', 'changeUser', [$this, $feature, $value, $oldValue]); diff --git a/lib/private/legacy/OC_App.php b/lib/private/legacy/OC_App.php index f18e6064bfa23..5dd7bfe3b7dcb 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); } /** * loads all apps * * @param string[] $types - * @return bool * * This function walks through the Nextcloud directory and loads all apps * it can find. A directory contains an app if the file /appinfo/info.xml @@ -73,31 +83,27 @@ public static function isAppLoaded(string $app): bool { * @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); } /** * load a single app * - * @param string $app * @throws Exception * @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); } /** * @internal - * @param string $app - * @param string $path - * @param bool $force */ - public static function registerAutoloading(string $app, string $path, bool $force = false) { + public static function registerAutoloading(string $app, string $path, bool $force = false): void { $key = $app . '-' . $path; if (!$force && isset(self::$alreadyRegistered[$key])) { return; @@ -106,7 +112,7 @@ public static function registerAutoloading(string $app, string $path, bool $forc 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')) { @@ -122,22 +128,19 @@ public static function registerAutoloading(string $app, string $path, bool $forc } /** - * check if an app is of a specific type + * Check if an app is of a specific type * - * @param string $app - * @param array $types - * @return bool * @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(); + public static function setAppTypes(string $app): void { + $appManager = Server::get(IAppManager::class); $appData = $appManager->getAppInfo($app); if (!is_array($appData)) { return; @@ -150,7 +153,7 @@ public static function setAppTypes(string $app) { $appData['types'] = []; } - $config = \OC::$server->getConfig(); + $config = Server::get(IConfig::class); $config->setAppValue($app, 'types', $appTypes); if ($appManager->hasProtectedAppType($appData['types'])) { @@ -170,16 +173,16 @@ public static function setAppTypes(string $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)) { @@ -198,16 +201,13 @@ public static function getEnabledApps(bool $forceRefresh = false, bool $all = fa /** * enables an app * - * @param string $appId * @param array $groups (optional) when set, only these groups will have access to the app * @throws \Exception - * @return void * @deprecated 32.0.0 Use the installer and the app manager instead * * This function set an app as enabled in appconfig. */ - public function enable(string $appId, - array $groups = []) { + public function enable(string $appId, array $groups = []): void { // Check if app is already downloaded /** @var Installer $installer */ $installer = Server::get(Installer::class); @@ -219,13 +219,13 @@ public function enable(string $appId, $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); } } @@ -261,15 +261,13 @@ public static function getAppVersionByPath(string $path): string { /** * get the id of loaded app - * - * @return string */ public static function getCurrentApp(): string { if (\OC::$CLI) { 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 +275,7 @@ public static function getCurrentApp(): string { $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) { @@ -293,10 +291,9 @@ public static function getCurrentApp(): string { } /** - * @param array $entry * @deprecated 20.0.0 Please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface */ - public static function registerLogIn(array $entry) { + public static function registerLogIn(array $entry): void { Server::get(LoggerInterface::class)->debug('OC_App::registerLogIn() is deprecated, please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface'); self::$altLogin[] = $entry; } @@ -367,25 +364,23 @@ public static function getAllApps(): array { * @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; } /** * List all apps, this is used in apps.php - * - * @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 +396,7 @@ public function listAllApps(): array { 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 +465,7 @@ public function listAllApps(): array { * @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 +486,7 @@ public static function shouldUpgrade(string $app): bool { * @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 +504,8 @@ public static function getAppVersions(): array { */ 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 +513,7 @@ public static function updateApp(string $appId): bool { /** * @param string $appId * @param string[] $steps - * @throws \OC\NeedsUpdateException + * @throws NeedsUpdateException */ public static function executeRepairSteps(string $appId, array $steps) { if (empty($steps)) { @@ -546,20 +541,17 @@ public static function executeRepairSteps(string $appId, array $steps) { /** * @deprecated 32.0.0 Use the IJobList directly instead */ - public static function setupBackgroundJobs(array $jobs) { - $queue = \OC::$server->getJobList(); + public static function setupBackgroundJobs(array $jobs): void { + $queue = Server::get(IJobList::class); foreach ($jobs as $job) { $queue->add($job); } } /** - * @param \OCP\IConfig $config - * @param \OCP\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): void { $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 0d460ff966d9c..b62bb65ddabc1 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 @@ public function getLogo($useSvg = true) { } 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 65f4300f850ec..3dc7470811dbc 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 @@ public static function copyr($src, $dest) { } } } else { - $validator = \OCP\Server::get(FilenameValidator::class); + $validator = Server::get(FilenameValidator::class); if (!$validator->isForbidden($src)) { copy($src, $dest); } @@ -86,7 +95,7 @@ public static function canExecute($name, $path = false) { // 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 @@ public static function findBinaryPath(string $program): ?string { * 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 @@ public static function getStorageInfo($path, $rootInfo = null, $includeMountPoin // 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 @@ public static function getStorageInfo($path, $rootInfo = null, $includeMountPoin } 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 @@ public static function getStorageInfo($path, $rootInfo = null, $includeMountPoin 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 @@ public static function getStorageInfo($path, $rootInfo = null, $includeMountPoin // 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 @@ public static function getStorageInfo($path, $rootInfo = null, $includeMountPoin 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 @@ public static function getStorageInfo($path, $rootInfo = null, $includeMountPoin * \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 @@ public static function getStorageInfo($path, $rootInfo = null, $includeMountPoin 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 @@ public static function getStorageInfo($path, $rootInfo = null, $includeMountPoin * @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 @@ private static function getGlobalStorageInfo(int|float $quota, IUser $user, IMou 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 @@ public static function clearStorageInfo(string $absolutePath): void { * @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 d14c34899a9ee..888057a7aca23 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 @@ public static function connect($signalClass, $signalName, $slotClass, $slotName) * @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 @@ public static function emit($signalClass, $signalName, $params = []) { 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 6daef18dd61e5..03ac83a058141 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 @@ public static function checkAppEnabled($app) { * @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 @@ public static function checkLoggedIn() { * @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 bccf99af65e54..5ddcce2db0625 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 @@ * 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 7d56b94704a8d..abdb37b737cc3 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 @@ public static function useBackend($backend = 'database') { 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 @@ public static function clearBackends() { */ 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(); @@ -132,11 +142,8 @@ public static function setupBackends() { * has already happened (e.g. via Single Sign On). * * Log in a user and regenerate a new session. - * - * @param \OCP\Authentication\IApacheBackend $backend - * @return bool */ - public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) { + public static function loginWithApache(IApacheBackend $backend): bool { $uid = $backend->getCurrentUserId(); $run = true; OC_Hook::emit('OC_User', 'pre_login', ['run' => &$run, 'uid' => $uid, 'backend' => $backend]); @@ -144,19 +151,20 @@ public static function loginWithApache(\OCP\Authentication\IApacheBackend $backe 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 +175,7 @@ public static function loginWithApache(\OCP\Authentication\IApacheBackend $backe $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 +205,7 @@ public static function loginWithApache(\OCP\Authentication\IApacheBackend $backe ] ); $dispatcher->dispatchTyped(new UserLoggedInEvent( - \OC::$server->get(IUserManager::class)->get($uid), + Server::get(IUserManager::class)->get($uid), $uid, null, false) @@ -214,19 +222,21 @@ public static function loginWithApache(\OCP\Authentication\IApacheBackend $backe /** * Verify with Apache whether user is authenticated. * - * @return boolean|null - * true: authenticated - * false: not authenticated - * null: not handled / no backend available + * @return bool|null + * true: authenticated + * false: not authenticated + * null: not handled / no backend available */ - public static function handleApacheAuth() { + public static function handleApacheAuth(): ?bool { $backend = self::findFirstActiveUsedBackend(); if ($backend) { OC_App::loadApps(); //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); } @@ -237,59 +247,50 @@ public static function handleApacheAuth() { /** * Sets user id for session and triggers emit - * - * @param string $uid */ - public static function setUserId($uid) { - $userSession = \OC::$server->getUserSession(); + public static function setUserId(?string $uid): void { + $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); } } /** - * set incognito mode, e.g. if a user wants to open a public link - * - * @param bool $status + * Set incognito mode, e.g. if a user wants to open a public link */ - public static function setIncognitoMode($status) { + public static function setIncognitoMode(bool $status): void { self::$incognitoMode = $status; } /** - * get incognito mode status - * - * @return bool + * Get incognito mode status */ - public static function isIncognitoMode() { + public static function isIncognitoMode(): bool { return self::$incognitoMode; } /** * Returns the current logout URL valid for the currently logged-in user - * - * @param \OCP\IURLGenerator $urlGenerator - * @return string */ - public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) { + public static function getLogoutUrl(IURLGenerator $urlGenerator): string { $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; } @@ -298,9 +299,8 @@ public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) { * Check if the user is an admin user * * @param string $uid uid of the admin - * @return bool */ - public static function isAdminUser($uid) { + public static function isAdminUser(string $uid): bool { $user = Server::get(IUserManager::class)->get($uid); $isAdmin = $user && Server::get(IGroupManager::class)->isAdmin($user->getUID()); return $isAdmin && self::$incognitoMode === false; @@ -312,7 +312,7 @@ public static function isAdminUser($uid) { * * @return string|false uid or false */ - public static function getUser() { + public static function getUser(): string|false { $uid = Server::get(ISession::class)?->get('user_id'); if (!is_null($uid) && self::$incognitoMode === false) { return $uid; @@ -327,11 +327,10 @@ public static function getUser() { * @param string $uid The username * @param string $password The new password * @param string $recoveryPassword for the encryption app to reset encryption keys - * @return bool * * Change the password of a user */ - public static function setPassword($uid, $password, $recoveryPassword = null) { + public static function setPassword(string $uid, string $password, ?string $recoveryPassword = null): bool { $user = Server::get(IUserManager::class)->get($uid); if ($user) { return $user->setPassword($password, $recoveryPassword); @@ -343,11 +342,11 @@ public static function setPassword($uid, $password, $recoveryPassword = null) { /** * 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() { + private static function findFirstActiveUsedBackend(): ?IApacheBackend { 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 fd87537cec704..435f44e13ea10 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 @@ public static function setupFS(?string $user = '') { */ 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 @@ public static function isPublicLinkPasswordRequired(bool $checkGroupMembership = */ 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 @@ public static function isSharingDisabledForUser(IConfig $config, IGroupManager $ */ public static function isDefaultExpireDateEnforced() { /** @var IManager $shareManager */ - $shareManager = \OC::$server->get(IManager::class); + $shareManager = Server::get(IManager::class); return $shareManager->shareApiLinkDefaultExpireDateEnforced(); } @@ -102,30 +117,30 @@ public static function isDefaultExpireDateEnforced() { */ public static function getUserQuota(?IUser $user) { if (is_null($user)) { - return \OCP\Files\FileInfo::SPACE_UNLIMITED; + return FileInfo::SPACE_UNLIMITED; } $userQuota = $user->getQuota(); if ($userQuota === 'none') { - return \OCP\Files\FileInfo::SPACE_UNLIMITED; + return FileInfo::SPACE_UNLIMITED; } - return \OCP\Util::computerFileSize($userQuota); + return Util::computerFileSize($userQuota); } /** * 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)) { @@ -141,7 +156,7 @@ public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) { } } - $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', ''); + $instanceId = Server::get(IConfig::class)->getSystemValue('instanceid', ''); if ($instanceId === null) { throw new \RuntimeException('no instance id!'); @@ -155,10 +170,10 @@ public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) { $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); } } @@ -167,11 +182,11 @@ public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) { * 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); @@ -182,7 +197,7 @@ public static function copyr($source, \OCP\Files\Folder $target) { // 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); @@ -204,7 +219,7 @@ public static function copyr($source, \OCP\Files\Folder $target) { * @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(); } @@ -301,7 +316,7 @@ public static function addHeader($tag, $attributes, $text = null, $prepend = fal * * @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'); @@ -312,14 +327,14 @@ public static function checkServer(\OC\SystemConfig $config) { } // 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)) { @@ -421,7 +436,7 @@ public static function checkServer(\OC\SystemConfig $config) { $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; @@ -482,7 +497,7 @@ public static function checkServer(\OC\SystemConfig $config) { } // 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; } @@ -495,7 +510,7 @@ public static function checkServer(\OC\SystemConfig $config) { * @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 []; } @@ -550,19 +565,19 @@ public static function checkDataDirectoryValidity($dataDirectory) { */ 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(); } } @@ -575,7 +590,7 @@ public static function checkLoggedIn(): void { 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(); } } @@ -590,7 +605,7 @@ public static function checkAdminUser(): void { */ public static function getDefaultPageUrl() { /** @var IURLGenerator $urlGenerator */ - $urlGenerator = \OC::$server->get(IURLGenerator::class); + $urlGenerator = Server::get(IURLGenerator::class); return $urlGenerator->linkToDefaultPageUrl(); } @@ -611,11 +626,11 @@ public static function redirectToDefaultPage(): void { * @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; } @@ -739,7 +754,7 @@ public static function obEnd() { * @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')) { @@ -763,7 +778,7 @@ public static function normalizeUnicode(string $value): string { $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; } @@ -775,15 +790,15 @@ public static function normalizeUnicode(string $value): string { * either when the core version is higher or any app requires * an upgrade. * - * @param \OC\SystemConfig $config + * @param SystemConfig $config * @return bool whether the core or any app needs an upgrade - * @throws \OCP\HintException When the upgrade from the given version is not allowed + * @throws HintException When the upgrade from the given version is not allowed * @deprecated 32.0.0 Use \OCP\Util::needUpgrade instead */ - public static function needUpgrade(\OC\SystemConfig $config) { + public static function needUpgrade(SystemConfig $config) { if ($config->getValue('installed', false)) { $installedVersion = $config->getValue('version', '0.0.0'); - $currentVersion = implode('.', \OCP\Util::getVersion()); + $currentVersion = implode('.', Util::getVersion()); $versionDiff = version_compare($currentVersion, $installedVersion); if ($versionDiff > 0) { return true; @@ -798,11 +813,11 @@ public static function needUpgrade(\OC\SystemConfig $config) { return true; } else { // downgrade attempt, throw exception - throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')'); + throw new HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')'); } } elseif ($versionDiff < 0) { // downgrade attempt, throw exception - throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')'); + throw new HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')'); } // also check for upgrades for apps (independently from the user) diff --git a/lib/public/AppFramework/IAppContainer.php b/lib/public/AppFramework/IAppContainer.php index c20b252b0ce3c..dac7926f612a4 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 ContainerInterface * @since 6.0.0 * @deprecated 20.0.0 */ diff --git a/lib/public/Authentication/LoginCredentials/ICredentials.php b/lib/public/Authentication/LoginCredentials/ICredentials.php index 9848bbbe821fe..315ae0ccca5d5 100644 --- a/lib/public/Authentication/LoginCredentials/ICredentials.php +++ b/lib/public/Authentication/LoginCredentials/ICredentials.php @@ -13,30 +13,25 @@ */ interface ICredentials { /** - * Get the user UID + * Get the user UID. * - * @since 12 - * - * @return string + * @since 12.0.0 */ - public function getUID(); + public function getUID(): string; /** - * Get the login name the users used to login - * - * @since 12 + * Get the login name the users used to log in. * - * @return string + * @since 12.0.0 */ - public function getLoginName(); + public function getLoginName(): string; /** - * Get the password + * Get the password. * - * @since 12 + * @since 12.0.0 * - * @return string|null * @throws PasswordUnavailableException */ - public function getPassword(); + public function getPassword(): ?string; } diff --git a/lib/public/Files/Cache/IUpdater.php b/lib/public/Files/Cache/IUpdater.php index 2bc702114b4c5..65c4ce3bfdb09 100644 --- a/lib/public/Files/Cache/IUpdater.php +++ b/lib/public/Files/Cache/IUpdater.php @@ -18,10 +18,9 @@ interface IUpdater { /** * Get the propagator for etags and mtime for the view the updater works on * - * @return IPropagator * @since 9.0.0 */ - public function getPropagator(); + public function getPropagator(): IPropagator; /** * Propagate etag and mtime changes for the parent folders of $path up to the root of the filesystem @@ -30,34 +29,27 @@ public function getPropagator(); * @param int|null $time the timestamp to set as mtime for the parent folders, if left out the current time is used * @since 9.0.0 */ - public function propagate($path, $time = null); + public function propagate(string $path, ?int $time = null): void; /** * Update the cache for $path and update the size, etag and mtime of the parent folders - * - * @param string $path - * @param int $time * @since 9.0.0 */ - public function update($path, $time = null, ?int $sizeDifference = null); + public function update(string $path, ?int $time = null, ?int $sizeDifference = null): void; /** * Remove $path from the cache and update the size, etag and mtime of the parent folders * - * @param string $path * @since 9.0.0 */ - public function remove($path); + public function remove(string $path): void; /** * Rename a file or folder in the cache and update the size, etag and mtime of the parent folders * - * @param IStorage $sourceStorage - * @param string $source - * @param string $target * @since 9.0.0 */ - public function renameFromStorage(IStorage $sourceStorage, $source, $target); + public function renameFromStorage(IStorage $sourceStorage, string $source, string $target): void; /** * Copy a file or folder in the cache and update the size, etag and mtime of the parent folders diff --git a/lib/public/GlobalScale/IConfig.php b/lib/public/GlobalScale/IConfig.php index bae5dd7aa66a3..38efce4b8b55e 100644 --- a/lib/public/GlobalScale/IConfig.php +++ b/lib/public/GlobalScale/IConfig.php @@ -6,6 +6,8 @@ */ namespace OCP\GlobalScale; +use OCP\AppFramework\Attribute\Consumable; + /** * Interface IConfig * @@ -13,20 +15,19 @@ * * @since 12.0.1 */ +#[Consumable(since: '12.0.1')] interface IConfig { /** - * check if global scale is enabled + * Check if global scale is enabled. * * @since 12.0.1 - * @return bool */ - public function isGlobalScaleEnabled(); + public function isGlobalScaleEnabled(): bool; /** - * check if federation should only be used internally in a global scale setup + * Check if federation should only be used internally in a global scale setup. * * @since 12.0.1 - * @return bool */ - public function onlyInternalFederation(); + public function onlyInternalFederation(): bool; } diff --git a/lib/public/IDateTimeZone.php b/lib/public/IDateTimeZone.php index 650f9d6b24383..32b3903b81200 100644 --- a/lib/public/IDateTimeZone.php +++ b/lib/public/IDateTimeZone.php @@ -7,11 +7,14 @@ */ namespace OCP; +use OCP\AppFramework\Attribute\Consumable; + /** * Interface IDateTimeZone * * @since 8.0.0 */ +#[Consumable(since: '8.0.0')] interface IDateTimeZone { /** @@ -19,14 +22,12 @@ interface IDateTimeZone { * If a timestamp is passed the timezone for that given timestamp is retrieved (might differ due to DST). * If no userId is passed the current user is used. * - * @param bool|int $timestamp * @param ?string $userId - The user to fetch the timezone for (defaults to current user) - * @return \DateTimeZone * @since 8.0.0 * @since 8.1.0 - parameter $timestamp was added * @since 32.0.0 - parameter $userId was added */ - public function getTimeZone($timestamp = false, ?string $userId = null); + public function getTimeZone(int|false $timestamp = false, ?string $userId = null): \DateTimeZone; /** * Get the timezone configured as the default for this Nextcloud server. diff --git a/lib/public/INavigationManager.php b/lib/public/INavigationManager.php index 2bd70c04d6500..005c35282f416 100644 --- a/lib/public/INavigationManager.php +++ b/lib/public/INavigationManager.php @@ -10,12 +10,31 @@ namespace OCP; +use OCP\AppFramework\Attribute\Consumable; +use OCP\AppFramework\Attribute\ExceptionalImplementable; + /** - * Manages the ownCloud navigation + * Manages the Nextcloud navigation + * * @since 6.0.0 * * @psalm-type NavigationEntry = array{id: string, order: int, href: string, name: string, app?: string, icon?: string, classes?: string, type?: string} + * @psalm-type NavigationEntryOutput = array{ + * id: string, + * order?: int, + * href: string, + * icon: string, + * type: string, + * name: string, + * app?: string, + * default?: bool, + * active: bool, + * classes: string, + * unread: int, + * } */ +#[Consumable(since: '6.0.0')] +#[ExceptionalImplementable(app: 'guest')] interface INavigationManager { /** * Navigation entries of the app navigation @@ -35,18 +54,22 @@ interface INavigationManager { */ public const TYPE_GUEST = 'guest'; + /** + * All navigation entries + * @since 33.0.0 + */ + public const TYPE_ALL = 'all'; + /** * Creates a new navigation entry * - * @param array array|\Closure $entry Array containing: id, name, order, icon and href key - * If a menu entry (type = 'link') is added, you shall also set app to the app that added the entry. - * The use of a closure is preferred, because it will avoid - * loading the routing of your app, unless required. - * @psalm-param NavigationEntry|callable():NavigationEntry $entry + * @param NavigationEntry|callable():NavigationEntry $entry If a menu entry (type = 'link') is added, you shall also set app to the app that + * added the entry. The use of a closure is preferred, because it will avoid loading + * the routing of your app, unless required. * @return void * @since 6.0.0 */ - public function add($entry); + public function add(array|callable $entry): void; /** * Sets the current navigation entry of the currently running app @@ -54,20 +77,20 @@ public function add($entry); * @return void * @since 6.0.0 */ - public function setActiveEntry($appId); + public function setActiveEntry(string $appId): void; /** * Get the current navigation entry of the currently running app - * @return string + * @return ?string * @since 20.0.0 */ - public function getActiveEntry(); + public function getActiveEntry(): ?string; /** * Get a list of navigation entries * - * @param string $type type of the navigation entries - * @return array + * @param self::TYPE_APPS|self::TYPE_SETTINGS|self::TYPE_GUEST|self::TYPE_ALL $type type of the navigation entries + * @return array * @since 14.0.0 */ public function getAll(string $type = self::TYPE_APPS): array; @@ -92,7 +115,7 @@ public function get(string $id): ?array; /** * Returns the id of the user's default entry * - * If `user` is not passed, the currently logged in user will be used + * If `user` is not passed, the currently logged-in user will be used * * @param ?IUser $user User to query default entry for * @param bool $withFallbacks Include fallback values if no default entry was configured manually diff --git a/lib/public/IServerContainer.php b/lib/public/IServerContainer.php index 6d5095c92daaf..8cab6bc437e70 100644 --- a/lib/public/IServerContainer.php +++ b/lib/public/IServerContainer.php @@ -45,7 +45,7 @@ public function getContactsManager(); public function getRequest(); /** - * Returns the root folder of ownCloud's data directory + * Returns the root folder of Nextcloud's data directory * * @return \OCP\Files\IRootFolder * @since 6.0.0 - between 6.0.0 and 8.0.0 this returned \OCP\Files\Folder @@ -57,7 +57,7 @@ public function getRootFolder(); * 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 @@ public function getL10NFactory(); 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 8c37104828fb9..04e13403f27b5 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/lib/public/Remote/IInstance.php b/lib/public/Remote/IInstance.php index 6186c2e18194b..f25328841c0ed 100644 --- a/lib/public/Remote/IInstance.php +++ b/lib/public/Remote/IInstance.php @@ -6,12 +6,15 @@ */ namespace OCP\Remote; +use OCP\AppFramework\Attribute\Consumable; + /** * Provides some basic info about a remote Nextcloud instance * * @since 13.0.0 * @deprecated 23.0.0 */ +#[Consumable(since: '13.0.0')] interface IInstance { /** * @return string The url of the remote server without protocol @@ -19,7 +22,7 @@ interface IInstance { * @since 13.0.0 * @deprecated 23.0.0 */ - public function getUrl(); + public function getUrl(): string; /** * @return string The of the remote server with protocol @@ -27,7 +30,7 @@ public function getUrl(); * @since 13.0.0 * @deprecated 23.0.0 */ - public function getFullUrl(); + public function getFullUrl(): string; /** * @return string The full version string in '13.1.2.3' format @@ -35,15 +38,15 @@ public function getFullUrl(); * @since 13.0.0 * @deprecated 23.0.0 */ - public function getVersion(); + public function getVersion(): string; /** - * @return string 'http' or 'https' + * @return 'http'|'https' * * @since 13.0.0 * @deprecated 23.0.0 */ - public function getProtocol(); + public function getProtocol(): string; /** * Check that the remote server is installed and not in maintenance mode @@ -53,5 +56,5 @@ public function getProtocol(); * * @return bool */ - public function isActive(); + public function isActive(): bool; } diff --git a/tests/Core/Controller/LoginControllerTest.php b/tests/Core/Controller/LoginControllerTest.php index b4fd95513dfd3..55a510c0c30dc 100644 --- a/tests/Core/Controller/LoginControllerTest.php +++ b/tests/Core/Controller/LoginControllerTest.php @@ -515,7 +515,7 @@ public function testLoginWithInvalidCredentials(bool $rememberme): void { $rememberme, '/apps/files' ); - $loginResult = LoginResult::failure($loginData, LoginController::LOGIN_MSG_INVALIDPASSWORD); + $loginResult = LoginResult::failure(LoginController::LOGIN_MSG_INVALIDPASSWORD); $loginChain->expects($this->once()) ->method('process') ->with($this->equalTo($loginData)) @@ -553,7 +553,7 @@ public function testLoginWithValidCredentials(bool $rememberme): void { $password, $rememberme, ); - $loginResult = LoginResult::success($loginData); + $loginResult = LoginResult::success(); $loginChain->expects($this->once()) ->method('process') ->with($this->equalTo($loginData)) @@ -658,7 +658,7 @@ public function testLoginWithValidCredentialsAndRedirectUrl(bool $rememberme): v $rememberme, '/apps/mail' ); - $loginResult = LoginResult::success($loginData); + $loginResult = LoginResult::success(); $loginChain->expects($this->once()) ->method('process') ->with($this->equalTo($loginData)) @@ -694,7 +694,7 @@ public function testToNotLeakLoginName(bool $rememberme): void { $rememberme, '/apps/files' ); - $loginResult = LoginResult::failure($loginData, LoginController::LOGIN_MSG_INVALIDPASSWORD); + $loginResult = LoginResult::failure(LoginController::LOGIN_MSG_INVALIDPASSWORD); $loginChain->expects($this->once()) ->method('process') ->with($this->equalTo($loginData)) diff --git a/tests/lib/Archive/TestBase.php b/tests/lib/Archive/TestBase.php index 1b7f7d3325a81..f3728dacbade6 100644 --- a/tests/lib/Archive/TestBase.php +++ b/tests/lib/Archive/TestBase.php @@ -8,24 +8,25 @@ namespace Test\Archive; +use OC\Archive\Archive; use OCP\Files; use OCP\ITempManager; use OCP\Server; abstract class TestBase extends \Test\TestCase { /** - * @var \OC\Archive\Archive + * @var Archive */ protected $instance; /** * get the existing test archive - * @return \OC\Archive\Archive + * @return Archive */ abstract protected function getExisting(); /** * get a new archive for write testing - * @return \OC\Archive\Archive + * @return Archive */ abstract protected function getNew(); diff --git a/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php b/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php index 2018dc1a63448..0de94ded0060d 100644 --- a/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php @@ -24,14 +24,9 @@ use Test\TestCase; class RegistryTest extends TestCase { - /** @var ProviderUserAssignmentDao|MockObject */ - private $dao; - - /** @var IEventDispatcher|MockObject */ - private $dispatcher; - - /** @var Registry */ - private $registry; + private ProviderUserAssignmentDao&MockObject $dao; + private IEventDispatcher&MockObject $dispatcher; + private Registry $registry; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Collaboration/Collaborators/MailPluginTest.php b/tests/lib/Collaboration/Collaborators/MailPluginTest.php index 9672bbfcd6bda..cf39642280c20 100644 --- a/tests/lib/Collaboration/Collaborators/MailPluginTest.php +++ b/tests/lib/Collaboration/Collaborators/MailPluginTest.php @@ -23,35 +23,22 @@ use OCP\IUserManager; use OCP\IUserSession; use OCP\Share\IShare; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; use Test\Traits\EmailValidatorTrait; class MailPluginTest extends TestCase { use EmailValidatorTrait; - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ - protected $config; - - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $contactsManager; - - /** @var ICloudIdManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $cloudIdManager; - - /** @var MailPlugin */ - protected $plugin; - - /** @var SearchResult */ - protected $searchResult; - - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $groupManager; - - /** @var KnownUserService|\PHPUnit\Framework\MockObject\MockObject */ - protected $knownUserService; - - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - protected $userSession; + protected IConfig&MockObject $config; + protected IManager&MockObject $contactsManager; + protected ICloudIdManager $cloudIdManager; + protected MailPlugin $plugin; + protected SearchResult $searchResult; + protected IGroupManager&MockObject $groupManager; + protected KnownUserService&MockObject $knownUserService; + protected IUserSession&MockObject $userSession; protected function setUp(): void { parent::setUp(); @@ -86,18 +73,8 @@ public function instantiatePlugin(int $shareType) { ); } - /** - * - * @param string $searchTerm - * @param array $contacts - * @param bool $shareeEnumeration - * @param array $expectedResult - * @param bool $expectedExactIdMatch - * @param bool $expectedMoreResults - * @param bool $validEmail - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchEmail')] - public function testSearchEmail($searchTerm, $contacts, $shareeEnumeration, $expectedResult, $expectedExactIdMatch, $expectedMoreResults, $validEmail): void { + #[DataProvider('dataSearchEmail')] + public function testSearchEmail(string $searchTerm, array $contacts, bool $shareeEnumeration, array $expectedResult, bool $expectedExactIdMatch, bool $expectedMoreResults, bool $validEmail): void { $this->config->expects($this->any()) ->method('getAppValue') ->willReturnCallback( @@ -564,17 +541,8 @@ public static function dataSearchEmail(): array { ]; } - /** - * - * @param string $searchTerm - * @param array $contacts - * @param bool $shareeEnumeration - * @param array $expectedResult - * @param bool $expectedExactIdMatch - * @param bool $expectedMoreResults - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchUser')] - public function testSearchUser($searchTerm, $contacts, $shareeEnumeration, $expectedResult, $expectedExactIdMatch, $expectedMoreResults): void { + #[DataProvider('dataSearchUser')] + public function testSearchUser(string $searchTerm, array $contacts, bool $shareeEnumeration, array $expectedResult, bool $expectedExactIdMatch, bool $expectedMoreResults): void { $this->config->expects($this->any()) ->method('getAppValue') ->willReturnCallback( @@ -860,18 +828,8 @@ public static function dataSearchUser(): array { ]; } - /** - * - * @param string $searchTerm - * @param array $contacts - * @param array $expectedResult - * @param bool $expectedExactIdMatch - * @param bool $expectedMoreResults - * @param array $userToGroupMapping - * @param bool $validEmail - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchEmailGroupsOnly')] - public function testSearchEmailGroupsOnly($searchTerm, $contacts, $expectedResult, $expectedExactIdMatch, $expectedMoreResults, $userToGroupMapping, $validEmail): void { + #[DataProvider('dataSearchEmailGroupsOnly')] + public function testSearchEmailGroupsOnly(string $searchTerm, array $contacts, array $expectedResult, bool $expectedExactIdMatch, bool $expectedMoreResults, array $userToGroupMapping, bool $validEmail): void { $this->config->expects($this->any()) ->method('getAppValue') ->willReturnCallback( @@ -995,17 +953,8 @@ public static function dataSearchEmailGroupsOnly(): array { ]; } - /** - * - * @param string $searchTerm - * @param array $contacts - * @param array $expectedResult - * @param bool $expectedExactIdMatch - * @param bool $expectedMoreResults - * @param array $userToGroupMapping - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchUserGroupsOnly')] - public function testSearchUserGroupsOnly($searchTerm, $contacts, $expectedResult, $expectedExactIdMatch, $expectedMoreResults, $userToGroupMapping): void { + #[DataProvider('dataSearchUserGroupsOnly')] + public function testSearchUserGroupsOnly(string $searchTerm, array $contacts, array $expectedResult, bool $expectedExactIdMatch, bool $expectedMoreResults, array $userToGroupMapping): void { $this->config->expects($this->any()) ->method('getAppValue') ->willReturnCallback( @@ -1021,8 +970,7 @@ function ($appName, $key, $default) { $this->instantiatePlugin(IShare::TYPE_USER); - /** @var IUser|\PHPUnit\Framework\MockObject\MockObject */ - $currentUser = $this->createMock('\OCP\IUser'); + $currentUser = $this->createMock(\OCP\IUser::class); $currentUser->expects($this->any()) ->method('getUID') diff --git a/tests/lib/ContactsManagerTest.php b/tests/lib/ContactsManagerTest.php index d2d46ce43b471..32aa1141ff0ac 100644 --- a/tests/lib/ContactsManagerTest.php +++ b/tests/lib/ContactsManagerTest.php @@ -12,8 +12,7 @@ use OCP\IAddressBook; class ContactsManagerTest extends \Test\TestCase { - /** @var \OC\ContactsManager */ - private $cm; + private ContactsManager $cm; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php b/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php index 5effc2f14692f..bbaaf376ca0d4 100644 --- a/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php +++ b/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php @@ -1,5 +1,7 @@ connection = Server::get(IDBConnection::class); - $this->internalConnection = Server::get(\OC\DB\Connection::class); + $this->internalConnection = Server::get(Connection::class); $this->logger = $this->createMock(LoggerInterface::class); $queryBuilder = $this->createMock(IQueryBuilder::class); + $queryBuilder->method('func') + ->willReturn($this->createMock(IFunctionBuilder::class)); $this->expressionBuilder = new ExpressionBuilder($this->connection, $queryBuilder, $this->logger); @@ -66,16 +66,8 @@ public static function dataComparison(): array { return $testSets; } - /** - * - * @param string $comparison - * @param mixed $input1 - * @param bool $isInput1Literal - * @param mixed $input2 - * @param bool $isInput2Literal - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataComparison')] - public function testComparison($comparison, $input1, $isInput1Literal, $input2, $isInput2Literal): void { + #[DataProvider('dataComparison')] + public function testComparison(string $comparison, string $input1, bool $isInput1Literal, string $input2, bool $isInput2Literal): void { [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); @@ -94,15 +86,8 @@ public static function dataComparisons(): array { ]; } - /** - * - * @param mixed $input1 - * @param bool $isInput1Literal - * @param mixed $input2 - * @param bool $isInput2Literal - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataComparisons')] - public function testEquals($input1, $isInput1Literal, $input2, $isInput2Literal): void { + #[DataProvider('dataComparisons')] + public function testEquals(string $input1, bool $isInput1Literal, string $input2, bool $isInput2Literal): void { [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); @@ -112,15 +97,8 @@ public function testEquals($input1, $isInput1Literal, $input2, $isInput2Literal) ); } - /** - * - * @param mixed $input1 - * @param bool $isInput1Literal - * @param mixed $input2 - * @param bool $isInput2Literal - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataComparisons')] - public function testNotEquals($input1, $isInput1Literal, $input2, $isInput2Literal): void { + #[DataProvider('dataComparisons')] + public function testNotEquals(string $input1, bool $isInput1Literal, string $input2, bool $isInput2Literal): void { [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); @@ -130,15 +108,8 @@ public function testNotEquals($input1, $isInput1Literal, $input2, $isInput2Liter ); } - /** - * - * @param mixed $input1 - * @param bool $isInput1Literal - * @param mixed $input2 - * @param bool $isInput2Literal - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataComparisons')] - public function testLowerThan($input1, $isInput1Literal, $input2, $isInput2Literal): void { + #[DataProvider('dataComparisons')] + public function testLowerThan(string $input1, bool $isInput1Literal, string $input2, bool $isInput2Literal): void { [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); @@ -148,15 +119,8 @@ public function testLowerThan($input1, $isInput1Literal, $input2, $isInput2Liter ); } - /** - * - * @param mixed $input1 - * @param bool $isInput1Literal - * @param mixed $input2 - * @param bool $isInput2Literal - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataComparisons')] - public function testLowerThanEquals($input1, $isInput1Literal, $input2, $isInput2Literal): void { + #[DataProvider('dataComparisons')] + public function testLowerThanEquals(string $input1, bool $isInput1Literal, string $input2, bool $isInput2Literal): void { [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); @@ -166,15 +130,8 @@ public function testLowerThanEquals($input1, $isInput1Literal, $input2, $isInput ); } - /** - * - * @param mixed $input1 - * @param bool $isInput1Literal - * @param mixed $input2 - * @param bool $isInput2Literal - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataComparisons')] - public function testGreaterThan($input1, $isInput1Literal, $input2, $isInput2Literal): void { + #[DataProvider('dataComparisons')] + public function testGreaterThan(string $input1, bool $isInput1Literal, string $input2, bool $isInput2Literal): void { [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); @@ -184,15 +141,8 @@ public function testGreaterThan($input1, $isInput1Literal, $input2, $isInput2Lit ); } - /** - * - * @param mixed $input1 - * @param bool $isInput1Literal - * @param mixed $input2 - * @param bool $isInput2Literal - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataComparisons')] - public function testGreaterThanEquals($input1, $isInput1Literal, $input2, $isInput2Literal): void { + #[DataProvider('dataComparisons')] + public function testGreaterThanEquals(string $input1, bool $isInput1Literal, string $input2, bool $isInput2Literal): void { [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); @@ -223,13 +173,8 @@ public static function dataLike(): array { ]; } - /** - * - * @param mixed $input - * @param bool $isLiteral - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataLike')] - public function testLike($input, $isLiteral): void { + #[DataProvider('dataLike')] + public function testLike(string $input, bool $isLiteral): void { [$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral); $this->assertEquals( @@ -238,13 +183,8 @@ public function testLike($input, $isLiteral): void { ); } - /** - * - * @param mixed $input - * @param bool $isLiteral - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataLike')] - public function testNotLike($input, $isLiteral): void { + #[DataProvider('dataLike')] + public function testNotLike(string $input, bool $isLiteral): void { [$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral); $this->assertEquals( @@ -262,13 +202,8 @@ public static function dataIn(): array { ]; } - /** - * - * @param mixed $input - * @param bool $isLiteral - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataIn')] - public function testIn($input, $isLiteral): void { + #[DataProvider('dataIn')] + public function testIn(string|array $input, bool $isLiteral): void { [$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral); $this->assertEquals( @@ -277,13 +212,8 @@ public function testIn($input, $isLiteral): void { ); } - /** - * - * @param mixed $input - * @param bool $isLiteral - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataIn')] - public function testNotIn($input, $isLiteral): void { + #[DataProvider('dataIn')] + public function testNotIn(string|array $input, bool $isLiteral): void { [$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral); $this->assertEquals( @@ -292,7 +222,7 @@ public function testNotIn($input, $isLiteral): void { ); } - protected function helpWithLiteral($input, $isLiteral) { + protected function helpWithLiteral(string|array $input, bool $isLiteral) { if ($isLiteral) { if (is_array($input)) { $doctrineInput = array_map(function ($ident) { @@ -331,14 +261,9 @@ public static function dataLiteral(): array { ]; } - /** - * - * @param mixed $input - * @param string|null $type - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataLiteral')] - public function testLiteral($input, $type): void { - /** @var \OC\DB\QueryBuilder\Literal $actual */ + #[DataProvider('dataLiteral')] + public function testLiteral(string|int $input, string|int|null $type): void { + /** @var Literal $actual */ $actual = $this->expressionBuilder->literal($input, $type); $this->assertInstanceOf('\OC\DB\QueryBuilder\Literal', $actual); @@ -375,15 +300,8 @@ public static function dataClobComparisons(): array { ]; } - /** - * @param string $function - * @param mixed $value - * @param mixed $type - * @param bool $compareKeyToValue - * @param int $expected - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataClobComparisons')] - public function testClobComparisons($function, $value, $type, $compareKeyToValue, $expected): void { + #[DataProvider('dataClobComparisons')] + public function testClobComparisons(string $function, string|array $value, int $type, bool $compareKeyToValue, int $expected): void { $appId = $this->getUniqueID('testing'); $this->createConfig($appId, 1, 4); $this->createConfig($appId, 2, 5); @@ -418,7 +336,7 @@ public function testClobComparisons($function, $value, $type, $compareKeyToValue ->executeStatement(); } - protected function createConfig($appId, $key, $value) { + protected function createConfig(string $appId, int $key, int|string $value) { $query = $this->connection->getQueryBuilder(); $query->insert('appconfig') ->values([ diff --git a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php index 9c4379e6f28f3..0e8f279c9dda3 100644 --- a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php +++ b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php @@ -12,6 +12,7 @@ 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 @@ public static function dataGetColumnName(): array { ]; } - /** - * @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') diff --git a/tests/lib/DateTimeFormatterTest.php b/tests/lib/DateTimeFormatterTest.php index dce6692f9cb9a..26ff381bf0ac1 100644 --- a/tests/lib/DateTimeFormatterTest.php +++ b/tests/lib/DateTimeFormatterTest.php @@ -12,8 +12,7 @@ use OCP\Util; class DateTimeFormatterTest extends TestCase { - /** @var \OC\DateTimeFormatter */ - protected $formatter; + protected DateTimeFormatter $formatter; protected static $oneMinute = 60; protected static $oneHour = 3600; protected static $oneDay; diff --git a/tests/lib/Diagnostics/EventLoggerTest.php b/tests/lib/Diagnostics/EventLoggerTest.php index ea9e95f80b35a..aca536170dbf1 100644 --- a/tests/lib/Diagnostics/EventLoggerTest.php +++ b/tests/lib/Diagnostics/EventLoggerTest.php @@ -15,8 +15,7 @@ use Test\TestCase; class EventLoggerTest extends TestCase { - /** @var \OC\Diagnostics\EventLogger */ - private $logger; + private EventLogger $logger; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Diagnostics/QueryLoggerTest.php b/tests/lib/Diagnostics/QueryLoggerTest.php index e54775a777fc1..9f869919e5102 100644 --- a/tests/lib/Diagnostics/QueryLoggerTest.php +++ b/tests/lib/Diagnostics/QueryLoggerTest.php @@ -12,8 +12,7 @@ use Test\TestCase; class QueryLoggerTest extends TestCase { - /** @var \OC\Diagnostics\QueryLogger */ - private $logger; + private QueryLogger $logger; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Encryption/Keys/StorageTest.php b/tests/lib/Encryption/Keys/StorageTest.php index 333d8d8ce2199..a1e6f6d351af2 100644 --- a/tests/lib/Encryption/Keys/StorageTest.php +++ b/tests/lib/Encryption/Keys/StorageTest.php @@ -17,20 +17,11 @@ use Test\TestCase; class StorageTest extends TestCase { - /** @var Storage */ - protected $storage; - - /** @var MockObject|\OC\Encryption\Util */ - protected $util; - - /** @var MockObject|View */ - protected $view; - - /** @var MockObject|IConfig */ - protected $config; - - /** @var MockObject|ICrypto */ - protected $crypto; + protected Storage $storage; + protected Util&MockObject $util; + protected View&MockObject $view; + protected IConfig&MockObject $config; + protected ICrypto&MockObject $crypto; private array $mkdirStack = []; diff --git a/tests/lib/Files/Cache/HomeCacheTest.php b/tests/lib/Files/Cache/HomeCacheTest.php index f5afecca8886b..1aa8e93173df8 100644 --- a/tests/lib/Files/Cache/HomeCacheTest.php +++ b/tests/lib/Files/Cache/HomeCacheTest.php @@ -10,57 +10,36 @@ use OC\Files\Storage\Home; use OC\User\User; +use OCP\Files\Cache\ICache; use OCP\ITempManager; use OCP\Server; +use PHPUnit\Framework\Attributes\Group; +use Test\TestCase; class DummyUser extends User { - /** - * @param string $uid - * @param string $home - */ public function __construct( - private $uid, - private $home, + private string $uid, + private string $home, ) { } - /** - * @return string - */ - public function getHome() { + public function getHome(): string { return $this->home; } /** * @return string */ - public function getUID() { + public function getUID(): string { return $this->uid; } } -/** - * Class HomeCacheTest - * - * - * @package Test\Files\Cache - */ -#[\PHPUnit\Framework\Attributes\Group('DB')] -class HomeCacheTest extends \Test\TestCase { - /** - * @var \OC\Files\Storage\Home $storage - */ - private $storage; - - /** - * @var \OC\Files\Cache\HomeCache $cache - */ - private $cache; - - /** - * @var User $user - */ - private $user; +#[Group('DB')] +class HomeCacheTest extends TestCase { + private Home $storage; + private ICache $cache; + private User $user; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/Cache/UpdaterTest.php b/tests/lib/Files/Cache/UpdaterTest.php index f651617e031e2..94fa42d64a417 100644 --- a/tests/lib/Files/Cache/UpdaterTest.php +++ b/tests/lib/Files/Cache/UpdaterTest.php @@ -9,6 +9,7 @@ namespace Test\Files\Cache; use OC\Files\Cache\Cache; +use OC\Files\Cache\Updater; use OC\Files\Filesystem; use OC\Files\ObjectStore\ObjectStoreStorage; use OC\Files\ObjectStore\StorageObjectStore; @@ -41,7 +42,7 @@ class UpdaterTest extends \Test\TestCase { protected $view; /** - * @var \OC\Files\Cache\Updater + * @var Updater */ protected $updater; diff --git a/tests/lib/Files/Node/FileTest.php b/tests/lib/Files/Node/FileTest.php index 36a410887cc67..a7191add2f3cc 100644 --- a/tests/lib/Files/Node/FileTest.php +++ b/tests/lib/Files/Node/FileTest.php @@ -47,7 +47,7 @@ protected function getViewDeleteMethod(): string { } public function testGetContent(): void { - /** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */ + /** @var Root|\PHPUnit\Framework\MockObject\MockObject $root */ $root = $this->getMockBuilder(Root::class) ->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory, $this->appConfig]) ->getMock(); @@ -77,7 +77,7 @@ public function testGetContent(): void { public function testGetContentNotPermitted(): void { $this->expectException(NotPermittedException::class); - /** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */ + /** @var Root|\PHPUnit\Framework\MockObject\MockObject $root */ $root = $this->getMockBuilder(Root::class) ->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory, $this->appConfig]) ->getMock(); @@ -96,7 +96,7 @@ public function testGetContentNotPermitted(): void { } public function testPutContent(): void { - /** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */ + /** @var Root|\PHPUnit\Framework\MockObject\MockObject $root */ $root = $this->getMockBuilder(Root::class) ->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory, $this->appConfig]) ->getMock(); @@ -123,7 +123,7 @@ public function testPutContent(): void { public function testPutContentNotPermitted(): void { $this->expectException(NotPermittedException::class); - /** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */ + /** @var Root|\PHPUnit\Framework\MockObject\MockObject $root */ $root = $this->getMockBuilder(Root::class) ->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory, $this->appConfig]) ->getMock(); @@ -138,7 +138,7 @@ public function testPutContentNotPermitted(): void { } public function testGetMimeType(): void { - /** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */ + /** @var Root|\PHPUnit\Framework\MockObject\MockObject $root */ $root = $this->getMockBuilder(Root::class) ->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory, $this->appConfig]) ->getMock(); diff --git a/tests/lib/Files/Node/FolderTest.php b/tests/lib/Files/Node/FolderTest.php index ad60cb535558c..69849f5ca9d6d 100644 --- a/tests/lib/Files/Node/FolderTest.php +++ b/tests/lib/Files/Node/FolderTest.php @@ -722,7 +722,7 @@ public function testRecent(): void { $manager = $this->createMock(Manager::class); $folderPath = '/bar/foo'; $view = $this->getRootViewMock(); - /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\Node\Root $root */ + /** @var \PHPUnit\Framework\MockObject\MockObject|Root $root */ $root = $this->getMockBuilder(Root::class) ->onlyMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory, $this->appConfig]) @@ -791,7 +791,7 @@ public function testRecentFolder(): void { $manager = $this->createMock(Manager::class); $folderPath = '/bar/foo'; $view = $this->getRootViewMock(); - /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\Node\Root $root */ + /** @var \PHPUnit\Framework\MockObject\MockObject|Root $root */ $root = $this->getMockBuilder(Root::class) ->onlyMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory, $this->appConfig]) @@ -858,7 +858,7 @@ public function testRecentJail(): void { $manager = $this->createMock(Manager::class); $folderPath = '/bar/foo'; $view = $this->getRootViewMock(); - /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\Node\Root $root */ + /** @var \PHPUnit\Framework\MockObject\MockObject|Root $root */ $root = $this->getMockBuilder(Root::class) ->onlyMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory, $this->appConfig]) diff --git a/tests/lib/Files/Node/IntegrationTest.php b/tests/lib/Files/Node/IntegrationTest.php index af54a2e162d0c..32b9a81dff9f9 100644 --- a/tests/lib/Files/Node/IntegrationTest.php +++ b/tests/lib/Files/Node/IntegrationTest.php @@ -8,6 +8,7 @@ namespace Test\Files\Node; +use OC\Files\Node\File; use OC\Files\Node\Root; use OC\Files\Storage\Storage; use OC\Files\Storage\Temporary; @@ -34,7 +35,7 @@ class IntegrationTest extends \Test\TestCase { use UserTrait; /** - * @var \OC\Files\Node\Root $root + * @var Root $root */ private $root; @@ -134,7 +135,7 @@ public function testBasicFolder(): void { $folder->move('/asd'); /** - * @var \OC\Files\Node\File $file + * @var File $file */ $file = $folder->get('/bar'); $this->assertInstanceOf('\OC\Files\Node\File', $file); @@ -143,7 +144,7 @@ public function testBasicFolder(): void { $this->assertEquals('qwerty', $file->getContent()); $folder->move('/substorage/foo'); /** - * @var \OC\Files\Node\File $file + * @var File $file */ $file = $folder->get('/bar'); $this->assertInstanceOf('\OC\Files\Node\File', $file); diff --git a/tests/lib/Files/Node/NodeTestCase.php b/tests/lib/Files/Node/NodeTestCase.php index 56a20c3d7148b..46aa5a206c545 100644 --- a/tests/lib/Files/Node/NodeTestCase.php +++ b/tests/lib/Files/Node/NodeTestCase.php @@ -152,7 +152,7 @@ public function testDeleteHooks(): void { $test = $this; $hooksRun = 0; /** - * @param \OC\Files\Node\File $node + * @param File $node */ $preListener = function ($node) use (&$test, &$hooksRun): void { $test->assertInstanceOf($this->getNodeClass(), $node); @@ -163,7 +163,7 @@ public function testDeleteHooks(): void { }; /** - * @param \OC\Files\Node\File $node + * @param File $node */ $postListener = function ($node) use (&$test, &$hooksRun): void { $test->assertInstanceOf($this->getNonExistingNodeClass(), $node); @@ -407,7 +407,7 @@ public function testTouchHooks(): void { $test = $this; $hooksRun = 0; /** - * @param \OC\Files\Node\File $node + * @param File $node */ $preListener = function ($node) use (&$test, &$hooksRun): void { $test->assertEquals('foo', $node->getInternalPath()); @@ -416,7 +416,7 @@ public function testTouchHooks(): void { }; /** - * @param \OC\Files\Node\File $node + * @param File $node */ $postListener = function ($node) use (&$test, &$hooksRun): void { $test->assertEquals('foo', $node->getInternalPath()); @@ -624,7 +624,7 @@ public function testMoveCopyHooks($operationMethod, $viewMethod, $preHookName, $ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1])); /** - * @var \OC\Files\Node\File|\PHPUnit\Framework\MockObject\MockObject $node + * @var File|\PHPUnit\Framework\MockObject\MockObject $node */ $node = $this->createTestNode($root, $this->view, '/bar/foo'); $parentNode = new Folder($root, $this->view, '/bar'); diff --git a/tests/lib/Files/ObjectStore/S3Test.php b/tests/lib/Files/ObjectStore/S3Test.php index 0a20653f88e3c..d00109cc50283 100644 --- a/tests/lib/Files/ObjectStore/S3Test.php +++ b/tests/lib/Files/ObjectStore/S3Test.php @@ -92,7 +92,7 @@ public function testSeek(): void { } public function assertNoUpload($objectUrn) { - /** @var \OC\Files\ObjectStore\S3 */ + /** @var S3 */ $s3 = $this->getInstance(); $s3client = $s3->getConnection(); $uploads = $s3client->listMultipartUploads([ diff --git a/tests/lib/Files/Storage/HomeTest.php b/tests/lib/Files/Storage/HomeTest.php index 2ca9737bf7980..be1b435afb947 100644 --- a/tests/lib/Files/Storage/HomeTest.php +++ b/tests/lib/Files/Storage/HomeTest.php @@ -15,21 +15,17 @@ use OCP\Server; class DummyUser extends User { - /** - * @param string $uid - * @param string $home - */ public function __construct( - private $uid, - private $home, + private readonly string $uid, + private readonly string $home, ) { } - public function getHome() { + public function getHome(): string { return $this->home; } - public function getUID() { + public function getUID(): string { return $this->uid; } } diff --git a/tests/lib/IntegrityCheck/CheckerTest.php b/tests/lib/IntegrityCheck/CheckerTest.php index 990a632cb8c39..930b0db0700c2 100644 --- a/tests/lib/IntegrityCheck/CheckerTest.php +++ b/tests/lib/IntegrityCheck/CheckerTest.php @@ -38,7 +38,7 @@ class CheckerTest extends TestCase { private $cacheFactory; /** @var IAppManager|\PHPUnit\Framework\MockObject\MockObject */ private $appManager; - /** @var \OC\Files\Type\Detection|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Detection|\PHPUnit\Framework\MockObject\MockObject */ private $mimeTypeDetector; private Checker $checker; diff --git a/tests/lib/LargeFileHelperGetFileSizeTest.php b/tests/lib/LargeFileHelperGetFileSizeTest.php index fbf22f1eb876b..134d5b4307cc4 100644 --- a/tests/lib/LargeFileHelperGetFileSizeTest.php +++ b/tests/lib/LargeFileHelperGetFileSizeTest.php @@ -22,7 +22,7 @@ class LargeFileHelperGetFileSizeTest extends TestCase { protected $filename; /** @var int */ protected $fileSize; - /** @var \OC\LargeFileHelper */ + /** @var LargeFileHelper */ protected $helper; protected function setUp(): void { diff --git a/tests/lib/Lock/DBLockingProviderTest.php b/tests/lib/Lock/DBLockingProviderTest.php index 3e6b7c5198e99..22f6c8f440e14 100644 --- a/tests/lib/Lock/DBLockingProviderTest.php +++ b/tests/lib/Lock/DBLockingProviderTest.php @@ -23,7 +23,7 @@ #[\PHPUnit\Framework\Attributes\Group('DB')] class DBLockingProviderTest extends LockingProvider { /** - * @var \OC\Lock\DBLockingProvider + * @var DBLockingProvider */ protected $instance; diff --git a/tests/lib/Memcache/CasTraitTest.php b/tests/lib/Memcache/CasTraitTest.php index ff60019544e49..1357633ed3e58 100644 --- a/tests/lib/Memcache/CasTraitTest.php +++ b/tests/lib/Memcache/CasTraitTest.php @@ -9,12 +9,13 @@ namespace Test\Memcache; use OC\Memcache\ArrayCache; +use OC\Memcache\CasTrait; use Test\TestCase; #[\PHPUnit\Framework\Attributes\Group('Memcache')] class CasTraitTest extends TestCase { /** - * @return \OC\Memcache\CasTrait + * @return CasTrait */ private function getCache() { $sourceCache = new ArrayCache(); diff --git a/tests/lib/Repair/Owncloud/CleanPreviewsTest.php b/tests/lib/Repair/Owncloud/CleanPreviewsTest.php index e5a4441a4fa98..6e86ee717621f 100644 --- a/tests/lib/Repair/Owncloud/CleanPreviewsTest.php +++ b/tests/lib/Repair/Owncloud/CleanPreviewsTest.php @@ -9,7 +9,7 @@ use OC\Repair\Owncloud\CleanPreviews; use OC\Repair\Owncloud\CleanPreviewsBackgroundJob; use OCP\BackgroundJob\IJobList; -use OCP\IConfig; +use OCP\IAppConfig; use OCP\IUser; use OCP\IUserManager; use OCP\Migration\IOutput; @@ -17,25 +17,22 @@ use Test\TestCase; class CleanPreviewsTest extends TestCase { - private IJobList&MockObject $jobList; private IUserManager&MockObject $userManager; - private IConfig&MockObject $config; - - /** @var CleanPreviews */ - private $repair; + private IAppConfig&MockObject $appConfig; + private CleanPreviews $repair; public function setUp(): void { parent::setUp(); $this->jobList = $this->createMock(IJobList::class); $this->userManager = $this->createMock(IUserManager::class); - $this->config = $this->createMock(IConfig::class); + $this->appConfig = $this->createMock(IAppConfig::class); $this->repair = new CleanPreviews( $this->jobList, $this->userManager, - $this->config + $this->appConfig ); } @@ -65,19 +62,18 @@ public function testRun(): void { $jobListCalls[] = func_get_args(); }); - $this->config->expects($this->once()) - ->method('getAppValue') + $this->appConfig->expects($this->once()) + ->method('getValueBool') ->with( $this->equalTo('core'), $this->equalTo('previewsCleanedUp'), - $this->equalTo(false) )->willReturn(false); - $this->config->expects($this->once()) - ->method('setAppValue') + $this->appConfig->expects($this->once()) + ->method('setValueBool') ->with( $this->equalTo('core'), $this->equalTo('previewsCleanedUp'), - $this->equalTo(1) + $this->equalTo(true) ); $this->repair->run($this->createMock(IOutput::class)); @@ -95,15 +91,14 @@ public function testRunAlreadyDone(): void { $this->jobList->expects($this->never()) ->method($this->anything()); - $this->config->expects($this->once()) - ->method('getAppValue') + $this->appConfig->expects($this->once()) + ->method('getValueBool') ->with( $this->equalTo('core'), $this->equalTo('previewsCleanedUp'), - $this->equalTo(false) - )->willReturn('1'); - $this->config->expects($this->never()) - ->method('setAppValue'); + )->willReturn(true); + $this->appConfig->expects($this->never()) + ->method('setValueBool'); $this->repair->run($this->createMock(IOutput::class)); } diff --git a/tests/lib/Repair/RepairCollationTest.php b/tests/lib/Repair/RepairCollationTest.php index 11fbecb0171bf..969c5b57b7fda 100644 --- a/tests/lib/Repair/RepairCollationTest.php +++ b/tests/lib/Repair/RepairCollationTest.php @@ -20,10 +20,9 @@ class TestCollationRepair extends Collation { /** - * @param IDBConnection $connection * @return string[] */ - public function getAllNonUTF8BinTables(IDBConnection $connection) { + public function getAllNonUTF8BinTables(IDBConnection $connection): array { return parent::getAllNonUTF8BinTables($connection); } } @@ -49,7 +48,6 @@ protected function setUp(): void { $this->connection = Server::get(ConnectionAdapter::class); if ($this->connection->getDatabaseProvider() !== IDBConnection::PLATFORM_MYSQL) { $this->markTestSkipped('Test only relevant on MySql'); - return; } $this->logger = $this->createMock(LoggerInterface::class); diff --git a/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php b/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php index 86f458d8ea8b9..76fc3c281a95f 100644 --- a/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php +++ b/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php @@ -16,7 +16,7 @@ class CsrfTokenGeneratorTest extends \Test\TestCase { /** @var ISecureRandom */ private $random; - /** @var \OC\Security\CSRF\CsrfTokenGenerator */ + /** @var CsrfTokenGenerator */ private $csrfTokenGenerator; protected function setUp(): void { diff --git a/tests/lib/Security/CSRF/CsrfTokenManagerTest.php b/tests/lib/Security/CSRF/CsrfTokenManagerTest.php index 66ee18475a488..bc8291a0eac27 100644 --- a/tests/lib/Security/CSRF/CsrfTokenManagerTest.php +++ b/tests/lib/Security/CSRF/CsrfTokenManagerTest.php @@ -11,14 +11,16 @@ namespace Test\Security\CSRF; use OC\Security\CSRF\CsrfToken; +use OC\Security\CSRF\CsrfTokenGenerator; use OC\Security\CSRF\CsrfTokenManager; +use OC\Security\CSRF\TokenStorage\SessionStorage; class CsrfTokenManagerTest extends \Test\TestCase { - /** @var \OC\Security\CSRF\CsrfTokenManager */ + /** @var CsrfTokenManager */ private $csrfTokenManager; - /** @var \OC\Security\CSRF\CsrfTokenGenerator */ + /** @var CsrfTokenGenerator */ private $tokenGenerator; - /** @var \OC\Security\CSRF\TokenStorage\SessionStorage */ + /** @var SessionStorage */ private $storageInterface; protected function setUp(): void { diff --git a/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php b/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php index 2b2c4af0444c7..ec65732944dcd 100644 --- a/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php +++ b/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php @@ -16,7 +16,7 @@ class SessionStorageTest extends \Test\TestCase { /** @var ISession */ private $session; - /** @var \OC\Security\CSRF\TokenStorage\SessionStorage */ + /** @var SessionStorage */ private $sessionStorage; protected function setUp(): void { diff --git a/tests/lib/Session/CryptoWrappingTest.php b/tests/lib/Session/CryptoWrappingTest.php index 2bc09e0903a43..f377365b6e7cc 100644 --- a/tests/lib/Session/CryptoWrappingTest.php +++ b/tests/lib/Session/CryptoWrappingTest.php @@ -20,7 +20,7 @@ class CryptoWrappingTest extends TestCase { /** @var \PHPUnit\Framework\MockObject\MockObject|ISession */ protected $wrappedSession; - /** @var \OC\Session\CryptoSessionData */ + /** @var CryptoSessionData */ protected $instance; protected function setUp(): void { diff --git a/tests/lib/Share/HelperTest.php b/tests/lib/Share/HelperTest.php deleted file mode 100644 index de3b407612b1a..0000000000000 --- a/tests/lib/Share/HelperTest.php +++ /dev/null @@ -1,74 +0,0 @@ - false], 2000000000, 2000010000, 2000010000], - // no default expire date and no user defined expire date, return false - [['defaultExpireDateSet' => false], 2000000000, null, false], - // unenforced expire data and no user defined expire date, return false (because the default is not enforced) - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false], 2000000000, null, false], - // enforced expire date and no user defined expire date, take default expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true], 2000000000, null, 2000086400], - // unenforced expire date and user defined date > default expire date, take users expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false], 2000000000, 2000100000, 2000100000], - // unenforced expire date and user expire date < default expire date, take users expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false], 2000000000, 2000010000, 2000010000], - // enforced expire date and user expire date < default expire date, take users expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true], 2000000000, 2000010000, 2000010000], - // enforced expire date and users expire date > default expire date, take default expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true], 2000000000, 2000100000, 2000086400], - ]; - } - - #[\PHPUnit\Framework\Attributes\DataProvider('expireDateProvider')] - public function testCalculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate, $expected): void { - $result = Helper::calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate); - $this->assertSame($expected, $result); - } - - /** - * - * @param string $server1 - * @param string $server2 - * @param bool $expected - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCompareServerAddresses')] - public function testIsSameUserOnSameServer($user1, $server1, $user2, $server2, $expected): void { - $this->assertSame($expected, - Helper::isSameUserOnSameServer($user1, $server1, $user2, $server2) - ); - } - - public static function dataTestCompareServerAddresses(): array { - return [ - ['user1', 'http://server1', 'user1', 'http://server1', true], - ['user1', 'https://server1', 'user1', 'http://server1', true], - ['user1', 'http://serVer1', 'user1', 'http://server1', true], - ['user1', 'http://server1/', 'user1', 'http://server1', true], - ['user1', 'server1', 'user1', 'http://server1', true], - ['user1', 'http://server1', 'user1', 'http://server2', false], - ['user1', 'https://server1', 'user1', 'http://server2', false], - ['user1', 'http://serVer1', 'user1', 'http://serer2', false], - ['user1', 'http://server1/', 'user1', 'http://server2', false], - ['user1', 'server1', 'user1', 'http://server2', false], - ['user1', 'http://server1', 'user2', 'http://server1', false], - ['user1', 'https://server1', 'user2', 'http://server1', false], - ['user1', 'http://serVer1', 'user2', 'http://server1', false], - ['user1', 'http://server1/', 'user2', 'http://server1', false], - ['user1', 'server1', 'user2', 'http://server1', false], - ]; - } -} diff --git a/tests/lib/Support/Subscription/RegistryTest.php b/tests/lib/Support/Subscription/RegistryTest.php index e6e83d6038b0b..52014200932f8 100644 --- a/tests/lib/Support/Subscription/RegistryTest.php +++ b/tests/lib/Support/Subscription/RegistryTest.php @@ -11,21 +11,20 @@ use OCP\IConfig; use OCP\IGroup; use OCP\IGroupManager; -use OCP\IServerContainer; use OCP\IUserManager; use OCP\Notification\IManager; use OCP\Support\Subscription\Exception\AlreadyRegisteredException; use OCP\Support\Subscription\ISubscription; use OCP\Support\Subscription\ISupportedApps; use PHPUnit\Framework\MockObject\MockObject; +use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; use Test\TestCase; class RegistryTest extends TestCase { private Registry $registry; - private MockObject&IConfig $config; - private MockObject&IServerContainer $serverContainer; + private MockObject&ContainerInterface $serverContainer; private MockObject&IUserManager $userManager; private MockObject&IGroupManager $groupManager; private MockObject&LoggerInterface $logger; @@ -35,7 +34,7 @@ protected function setUp(): void { parent::setUp(); $this->config = $this->createMock(IConfig::class); - $this->serverContainer = $this->createMock(IServerContainer::class); + $this->serverContainer = $this->createMock(ContainerInterface::class); $this->userManager = $this->createMock(IUserManager::class); $this->groupManager = $this->createMock(IGroupManager::class); $this->logger = $this->createMock(LoggerInterface::class); @@ -119,7 +118,7 @@ public function testDelegateGetSupportedApps(): void { } public function testSubscriptionService(): void { - $this->serverContainer->method('query') + $this->serverContainer->method('get') ->with(DummySubscription::class) ->willReturn(new DummySubscription(true, false, false)); $this->registry->registerService(DummySubscription::class); diff --git a/tests/lib/TagsTest.php b/tests/lib/TagsTest.php index 9528fc291848b..1827870ca6e21 100644 --- a/tests/lib/TagsTest.php +++ b/tests/lib/TagsTest.php @@ -33,7 +33,7 @@ class TagsTest extends \Test\TestCase { /** @var IUserSession */ protected $userSession; protected $backupGlobals = false; - /** @var \OC\Tagging\TagMapper */ + /** @var TagMapper */ protected $tagMapper; /** @var ITagManager */ protected $tagMgr; diff --git a/tests/lib/TempManagerTest.php b/tests/lib/TempManagerTest.php index ee7778c7e8863..f29b7aa6316fe 100644 --- a/tests/lib/TempManagerTest.php +++ b/tests/lib/TempManagerTest.php @@ -37,7 +37,7 @@ protected function tearDown(): void { /** * @param ?LoggerInterface $logger * @param ?IConfig $config - * @return \OC\TempManager + * @return TempManager */ protected function getManager($logger = null, $config = null) { if (!$logger) { diff --git a/tests/lib/TestCase.php b/tests/lib/TestCase.php index 54368c93b8bcb..57a37aa5b3752 100644 --- a/tests/lib/TestCase.php +++ b/tests/lib/TestCase.php @@ -73,7 +73,7 @@ protected function onNotSuccessfulTest(\Throwable $t): void { } abstract class TestCase extends \PHPUnit\Framework\TestCase { - /** @var \OC\Command\QueueBus */ + /** @var QueueBus */ private $commandBus; /** @var IDBConnection */ diff --git a/tests/lib/Traits/MountProviderTrait.php b/tests/lib/Traits/MountProviderTrait.php index b680c71b2d686..6e5ca1d713d0d 100644 --- a/tests/lib/Traits/MountProviderTrait.php +++ b/tests/lib/Traits/MountProviderTrait.php @@ -25,7 +25,7 @@ trait MountProviderTrait { protected $mountProvider; /** - * @var \OC\Files\Storage\StorageFactory + * @var StorageFactory */ protected $storageFactory; diff --git a/tests/lib/User/DatabaseTest.php b/tests/lib/User/DatabaseTest.php index 0afd54c345c41..eae3aed0af58b 100644 --- a/tests/lib/User/DatabaseTest.php +++ b/tests/lib/User/DatabaseTest.php @@ -26,7 +26,7 @@ class DatabaseTest extends Backend { /** @var IEventDispatcher|MockObject */ private $eventDispatcher; - /** @var \OC\User\Database */ + /** @var Database */ protected $backend; public function getUser() { diff --git a/tests/lib/User/ManagerTest.php b/tests/lib/User/ManagerTest.php index 7dadc4e9e8f11..f2e7df53a353a 100644 --- a/tests/lib/User/ManagerTest.php +++ b/tests/lib/User/ManagerTest.php @@ -21,17 +21,12 @@ use OCP\IUser; use OCP\IUserManager; use OCP\Server; +use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; -/** - * Class ManagerTest - * - * - * @package Test\User - */ -#[\PHPUnit\Framework\Attributes\Group('DB')] +#[Group('DB')] class ManagerTest extends TestCase { private IConfig&MockObject $config; private IEventDispatcher&MockObject $eventDispatcher; @@ -151,7 +146,7 @@ public function testCheckPassword(): void { $backend->expects($this->once()) ->method('checkPassword') ->with($this->equalTo('foo'), $this->equalTo('bar')) - ->willReturn(true); + ->willReturn('foo'); $backend->expects($this->any()) ->method('implementsActions') @@ -345,7 +340,8 @@ public function testCreateUserSingleBackendNotExists(): void { $backend->expects($this->once()) ->method('createUser') - ->with($this->equalTo('foo'), $this->equalTo('bar')); + ->with($this->equalTo('foo'), $this->equalTo('bar')) + ->willReturn(true); $backend->expects($this->once()) ->method('userExists') diff --git a/tests/lib/User/UserTest.php b/tests/lib/User/UserTest.php index c1e07a0f153d9..750b99db4204e 100644 --- a/tests/lib/User/UserTest.php +++ b/tests/lib/User/UserTest.php @@ -23,20 +23,14 @@ use OCP\Notification\IManager as INotificationManager; use OCP\Notification\INotification; use OCP\Server; -use OCP\UserInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; -/** - * Class UserTest - * - * - * @package Test\User - */ -#[\PHPUnit\Framework\Attributes\Group('DB')] +#[Group('DB')] class UserTest extends TestCase { - /** @var IEventDispatcher|MockObject */ - protected $dispatcher; + protected IEventDispatcher $dispatcher; protected function setUp(): void { parent::setUp(); @@ -44,9 +38,6 @@ protected function setUp(): void { } public function testDisplayName(): void { - /** - * @var \OC\User\Backend | MockObject $backend - */ $backend = $this->createMock(\OC\User\Backend::class); $backend->expects($this->once()) ->method('getDisplayName') @@ -66,9 +57,6 @@ public function testDisplayName(): void { * if the display name contain whitespaces only, we expect the uid as result */ public function testDisplayNameEmpty(): void { - /** - * @var \OC\User\Backend | MockObject $backend - */ $backend = $this->createMock(\OC\User\Backend::class); $backend->expects($this->once()) ->method('getDisplayName') @@ -85,9 +73,6 @@ public function testDisplayNameEmpty(): void { } public function testDisplayNameNotSupported(): void { - /** - * @var \OC\User\Backend | MockObject $backend - */ $backend = $this->createMock(\OC\User\Backend::class); $backend->expects($this->never()) ->method('getDisplayName'); @@ -102,32 +87,22 @@ public function testDisplayNameNotSupported(): void { } public function testSetPassword(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $backend->expects($this->once()) ->method('setPassword') - ->with($this->equalTo('foo'), $this->equalTo('bar')); + ->with($this->equalTo('foo'), $this->equalTo('bar')) + ->willReturn(true); $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::SET_PASSWORD) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::SET_PASSWORD); $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->setPassword('bar', '')); } public function testSetPasswordNotSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->never()) ->method('setPassword'); @@ -141,9 +116,6 @@ public function testSetPasswordNotSupported(): void { } public function testChangeAvatarSupportedYes(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(AvatarUserDummy::class); $backend->expects($this->once()) ->method('canChangeAvatar') @@ -165,9 +137,6 @@ public function testChangeAvatarSupportedYes(): void { } public function testChangeAvatarSupportedNo(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(AvatarUserDummy::class); $backend->expects($this->once()) ->method('canChangeAvatar') @@ -189,9 +158,6 @@ public function testChangeAvatarSupportedNo(): void { } public function testChangeAvatarNotSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(AvatarUserDummy::class); $backend->expects($this->never()) ->method('canChangeAvatar'); @@ -205,20 +171,18 @@ public function testChangeAvatarNotSupported(): void { } public function testDelete(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $backend->expects($this->once()) ->method('deleteUser') - ->with($this->equalTo('foo')); + ->with($this->equalTo('foo')) + ->willReturn(true); $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->delete()); } public function testDeleteWithDifferentHome(): void { - /** @var ObjectHomeMountProvider $homeProvider */ $homeProvider = Server::get(ObjectHomeMountProvider::class); $user = $this->createMock(IUser::class); $user->method('getUID') @@ -227,20 +191,12 @@ public function testDeleteWithDifferentHome(): void { $this->markTestSkipped('Skipping test for non local home storage'); } - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $backend->expects($this->once()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::GET_HOME) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::GET_HOME); // important: getHome MUST be called before deleteUser because // once the user is deleted, getHome implementations might not @@ -252,16 +208,14 @@ public function testDeleteWithDifferentHome(): void { $backend->expects($this->once()) ->method('deleteUser') - ->with($this->equalTo('foo')); + ->with($this->equalTo('foo')) + ->willReturn(true); $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->delete()); } public function testGetHome(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->once()) ->method('getHome') @@ -270,13 +224,7 @@ public function testGetHome(): void { $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::GET_HOME) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::GET_HOME); $user = new User('foo', $backend, $this->dispatcher); $this->assertEquals('/home/foo', $user->getHome()); @@ -290,9 +238,6 @@ public function testGetBackendClassName(): void { } public function testGetHomeNotSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->never()) ->method('getHome'); @@ -317,29 +262,17 @@ public function testGetHomeNotSupported(): void { } public function testCanChangePassword(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::SET_PASSWORD) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::SET_PASSWORD); $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->canChangePassword()); } public function testCanChangePasswordNotSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->any()) @@ -351,20 +284,11 @@ public function testCanChangePasswordNotSupported(): void { } public function testCanChangeDisplayName(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::SET_DISPLAYNAME) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::SET_DISPLAYNAME); $config = $this->createMock(IConfig::class); $config->method('getSystemValueBool') @@ -376,9 +300,6 @@ public function testCanChangeDisplayName(): void { } public function testCanChangeDisplayNameNotSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->any()) @@ -390,20 +311,11 @@ public function testCanChangeDisplayNameNotSupported(): void { } public function testSetDisplayNameSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(Database::class); $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::SET_DISPLAYNAME) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::SET_DISPLAYNAME); $backend->expects($this->once()) ->method('setDisplayName') @@ -419,20 +331,11 @@ public function testSetDisplayNameSupported(): void { * don't allow display names containing whitespaces only */ public function testSetDisplayNameEmpty(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(Database::class); $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::SET_DISPLAYNAME) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::SET_DISPLAYNAME); $user = new User('foo', $backend, $this->dispatcher); $this->assertFalse($user->setDisplayName(' ')); @@ -440,9 +343,6 @@ public function testSetDisplayNameEmpty(): void { } public function testSetDisplayNameNotSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(Database::class); $backend->expects($this->any()) @@ -461,18 +361,13 @@ public function testSetPasswordHooks(): void { $hooksCalled = 0; $test = $this; - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $backend->expects($this->once()) - ->method('setPassword'); + ->method('setPassword') + ->willReturn(true); - /** - * @param User $user - * @param string $password - */ - $hook = function ($user, $password) use ($test, &$hooksCalled): void { + $hook = function (IUser $user, string $password) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('foo', $user->getUID()); $test->assertEquals('bar', $password); @@ -484,13 +379,7 @@ public function testSetPasswordHooks(): void { $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::SET_PASSWORD) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::SET_PASSWORD); $user = new User('foo', $backend, $this->dispatcher, $emitter); @@ -505,19 +394,13 @@ public static function dataDeleteHooks(): array { ]; } - /** - * @param bool $result - * @param int $expectedHooks - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataDeleteHooks')] - public function testDeleteHooks($result, $expectedHooks): void { + #[DataProvider('dataDeleteHooks')] + public function testDeleteHooks(bool $result, int $expectedHooks): void { $hooksCalled = 0; $test = $this; - /** - * @var UserInterface&MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $backend->expects($this->once()) ->method('deleteUser') ->willReturn($result); @@ -535,10 +418,7 @@ public function testDeleteHooks($result, $expectedHooks): void { $emitter = new PublicEmitter(); $user = new User('foo', $backend, $this->dispatcher, $emitter, $config); - /** - * @param User $user - */ - $hook = function ($user) use ($test, &$hooksCalled): void { + $hook = function (IUser $user) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('foo', $user->getUID()); }; @@ -601,6 +481,7 @@ public function testDeleteHooks($result, $expectedHooks): void { public function testDeleteRecoverState() { $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $backend->expects($this->once()) ->method('deleteUser') ->willReturn(true); @@ -659,9 +540,8 @@ public static function dataGetCloudId(): array { ]; } - #[\PHPUnit\Framework\Attributes\DataProvider('dataGetCloudId')] + #[DataProvider('dataGetCloudId')] public function testGetCloudId(string $absoluteUrl, string $cloudId): void { - /** @var Backend|MockObject $backend */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $urlGenerator = $this->createMock(IURLGenerator::class); $urlGenerator->method('getAbsoluteURL') @@ -672,20 +552,13 @@ public function testGetCloudId(string $absoluteUrl, string $cloudId): void { } public function testSetEMailAddressEmpty(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $test = $this; $hooksCalled = 0; - /** - * @param IUser $user - * @param string $feature - * @param string $value - */ - $hook = function (IUser $user, $feature, $value) use ($test, &$hooksCalled): void { + $hook = function (IUser $user, string $feature, string $value) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('eMailAddress', $feature); $test->assertEquals('', $value); @@ -704,24 +577,17 @@ public function testSetEMailAddressEmpty(): void { ); $user = new User('foo', $backend, $this->dispatcher, $emitter, $config); - $user->setEMailAddress(''); + $user->setSystemEMailAddress(''); } public function testSetEMailAddress(): void { - /** - * @var UserInterface | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $test = $this; $hooksCalled = 0; - /** - * @param IUser $user - * @param string $feature - * @param string $value - */ - $hook = function (IUser $user, $feature, $value) use ($test, &$hooksCalled): void { + $hook = function (IUser $user, string $feature, string $value) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('eMailAddress', $feature); $test->assertEquals('foo@bar.com', $value); @@ -741,16 +607,13 @@ public function testSetEMailAddress(): void { ); $user = new User('foo', $backend, $this->dispatcher, $emitter, $config); - $user->setEMailAddress('foo@bar.com'); + $user->setSystemEMailAddress('foo@bar.com'); } public function testSetEMailAddressNoChange(): void { - /** - * @var UserInterface | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); - /** @var PublicEmitter|MockObject $emitter */ $emitter = $this->createMock(PublicEmitter::class); $emitter->expects($this->never()) ->method('emit'); @@ -767,24 +630,17 @@ public function testSetEMailAddressNoChange(): void { ->method('setUserValue'); $user = new User('foo', $backend, $dispatcher, $emitter, $config); - $user->setEMailAddress('foo@bar.com'); + $user->setSystemEMailAddress('foo@bar.com'); } public function testSetQuota(): void { - /** - * @var UserInterface | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $test = $this; $hooksCalled = 0; - /** - * @param IUser $user - * @param string $feature - * @param string $value - */ - $hook = function (IUser $user, $feature, $value) use ($test, &$hooksCalled): void { + $hook = function (IUser $user, string $feature, string $value) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('quota', $feature); $test->assertEquals('23 TB', $value); @@ -808,10 +664,8 @@ public function testSetQuota(): void { } public function testGetDefaultUnlimitedQuota(): void { - /** - * @var UserInterface | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); /** @var PublicEmitter|MockObject $emitter */ $emitter = $this->createMock(PublicEmitter::class); @@ -839,9 +693,6 @@ public function testGetDefaultUnlimitedQuota(): void { } public function testGetDefaultUnlimitedQuotaForbidden(): void { - /** - * @var UserInterface | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); /** @var PublicEmitter|MockObject $emitter */ @@ -873,9 +724,6 @@ public function testGetDefaultUnlimitedQuotaForbidden(): void { } public function testSetQuotaAddressNoChange(): void { - /** - * @var UserInterface | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); /** @var PublicEmitter|MockObject $emitter */ @@ -895,9 +743,6 @@ public function testSetQuotaAddressNoChange(): void { } public function testGetLastLogin(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $config = $this->createMock(IConfig::class); @@ -915,10 +760,8 @@ public function testGetLastLogin(): void { } public function testSetEnabled(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $config = $this->createMock(IConfig::class); $config->expects($this->once()) @@ -941,9 +784,6 @@ public function testSetEnabled(): void { } public function testSetDisabled(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $config = $this->createMock(IConfig::class); @@ -981,9 +821,6 @@ public function testSetDisabled(): void { } public function testSetDisabledAlreadyDisabled(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $config = $this->createMock(IConfig::class); @@ -1011,9 +848,6 @@ public function testSetDisabledAlreadyDisabled(): void { } public function testGetEMailAddress(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $config = $this->createMock(IConfig::class); diff --git a/tests/lib/Util/User/Dummy.php b/tests/lib/Util/User/Dummy.php index 6ecd378c1deae..4a85f92981ce1 100644 --- a/tests/lib/Util/User/Dummy.php +++ b/tests/lib/Util/User/Dummy.php @@ -15,20 +15,10 @@ * dummy user backend, does not keep state, only for testing use */ class Dummy extends Backend implements IUserBackend { - private $users = []; - private $displayNames = []; - - /** - * Create a new user - * - * @param string $uid The username of the user to create - * @param string $password The password of the new user - * @return bool - * - * Creates a new user. Basic checking of username is done in OC_User - * itself, not in its subclasses. - */ - public function createUser($uid, $password) { + private array $users = []; + private array $displayNames = []; + + public function createUser($uid, $password): bool { if (isset($this->users[$uid])) { return false; } else { @@ -37,15 +27,7 @@ public function createUser($uid, $password) { } } - /** - * delete a user - * - * @param string $uid The username of the user to delete - * @return bool - * - * Deletes a user - */ - public function deleteUser($uid) { + public function deleteUser($uid): bool { if (isset($this->users[$uid])) { unset($this->users[$uid]); return true; @@ -54,16 +36,7 @@ public function deleteUser($uid) { } } - /** - * Set password - * - * @param string $uid The username - * @param string $password The new password - * @return bool - * - * Change the password of a user - */ - public function setPassword($uid, $password) { + public function setPassword($uid, $password): bool { if (isset($this->users[$uid])) { $this->users[$uid] = $password; return true; @@ -72,17 +45,7 @@ public function setPassword($uid, $password) { } } - /** - * Check if the password is correct - * - * @param string $uid The username - * @param string $password The password - * @return string|bool - * - * Check if the password is correct without logging in the user - * returns the user id or false - */ - public function checkPassword($uid, $password) { + public function checkPassword($uid, $password): string|false { if (isset($this->users[$uid]) && $this->users[$uid] === $password) { return $uid; } @@ -90,22 +53,14 @@ public function checkPassword($uid, $password) { return false; } - public function loginName2UserName($loginName) { + public function loginName2UserName($loginName): string|false { if (isset($this->users[strtolower($loginName)])) { return strtolower($loginName); } return false; } - /** - * Get a list of all users - * - * @param string $search - * @param null|int $limit - * @param null|int $offset - * @return string[] an array of all uids - */ - public function getUsers($search = '', $limit = null, $offset = null) { + public function getUsers($search = '', $limit = null, $offset = null): array { if (empty($search)) { return array_keys($this->users); } @@ -118,46 +73,28 @@ public function getUsers($search = '', $limit = null, $offset = null) { return $result; } - /** - * check if a user exists - * - * @param string $uid the username - * @return boolean - */ - public function userExists($uid) { + public function userExists($uid): bool { return isset($this->users[$uid]); } - /** - * @return bool - */ - public function hasUserListings() { + public function hasUserListings(): bool { return true; } - /** - * counts the users in the database - * - * @return int|bool - */ - public function countUsers() { + public function countUsers(): int { return 0; } - public function setDisplayName($uid, $displayName) { + public function setDisplayName($uid, $displayName): bool { $this->displayNames[$uid] = $displayName; return true; } - public function getDisplayName($uid) { + public function getDisplayName($uid): string { return $this->displayNames[$uid] ?? $uid; } - /** - * Backend name to be shown in user management - * @return string the name of the backend to be shown - */ - public function getBackendName() { + public function getBackendName(): string { return 'Dummy'; } }