aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJulius Härtl <jus@bitgrid.net>2022-12-19 11:05:02 +0100
committerGitHub <noreply@github.com>2022-12-19 11:05:02 +0100
commit26e413b78d52d0b0b7b19a2e1d615f408f9ff77a (patch)
tree1b988f32adeaa1d08315454748f38bb1538cd76a
parentcbbb0712db0f33a41ef66ae59d5c70ba1e23748f (diff)
parent585cf0022c589f85c05de67e82f0234f77dd9dd9 (diff)
downloadnextcloud-server-26e413b78d52d0b0b7b19a2e1d615f408f9ff77a.tar.gz
nextcloud-server-26e413b78d52d0b0b7b19a2e1d615f408f9ff77a.zip
Merge pull request #35496 from nextcloud/fix/strict-typing-in-base
-rw-r--r--build/psalm-baseline.xml3
-rw-r--r--lib/base.php240
-rw-r--r--lib/private/AppFramework/Http/Request.php25
-rw-r--r--lib/public/Log/functions.php1
4 files changed, 120 insertions, 149 deletions
diff --git a/build/psalm-baseline.xml b/build/psalm-baseline.xml
index e77d3cbee80..fce42b059b5 100644
--- a/build/psalm-baseline.xml
+++ b/build/psalm-baseline.xml
@@ -1792,9 +1792,6 @@
<InvalidArgument occurrences="1">
<code>$restrictions</code>
</InvalidArgument>
- <RedundantCondition occurrences="1">
- <code>((array)$request-&gt;getParam('appid')) !== ''</code>
- </RedundantCondition>
</file>
<file src="lib/private/Accounts/AccountManager.php">
<InvalidArgument occurrences="1">
diff --git a/lib/base.php b/lib/base.php
index 7098fb19fdd..a847373ea2b 100644
--- a/lib/base.php
+++ b/lib/base.php
@@ -1,4 +1,7 @@
<?php
+
+declare(strict_types=1);
+
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
@@ -10,6 +13,7 @@
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
+ * @author Côme Chilliet <come.chilliet@nextcloud.com>
* @author Damjan Georgievski <gdamjan@gmail.com>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author davidgumberg <davidnoizgumberg@gmail.com>
@@ -62,16 +66,19 @@
*
*/
+use OC\Encryption\HookManager;
use OC\EventDispatcher\SymfonyAdapter;
+use OC\Files\Filesystem;
+use OC\Share20\Hooks;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Group\Events\UserRemovedEvent;
use OCP\ILogger;
+use OCP\IURLGenerator;
+use OCP\IUserSession;
use OCP\Server;
use OCP\Share;
-use OC\Encryption\HookManager;
-use OC\Files\Filesystem;
-use OC\Share20\Hooks;
use OCP\User\Events\UserChangedEvent;
+use Psr\Log\LoggerInterface;
use function OCP\Log\logger;
require_once 'public/Constants.php';
@@ -85,63 +92,50 @@ class OC {
/**
* Associative array for autoloading. classname => filename
*/
- public static $CLASSPATH = [];
+ public static array $CLASSPATH = [];
/**
* The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud)
*/
- public static $SERVERROOT = '';
+ public static string $SERVERROOT = '';
/**
* the current request path relative to the Nextcloud root (e.g. files/index.php)
*/
- private static $SUBURI = '';
+ private static string $SUBURI = '';
/**
* the Nextcloud root path for http requests (e.g. nextcloud/)
*/
- public static $WEBROOT = '';
+ public static string $WEBROOT = '';
/**
* The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
* web path in 'url'
*/
- public static $APPSROOTS = [];
+ public static array $APPSROOTS = [];
- /**
- * @var string
- */
- public static $configDir;
+ public static string $configDir;
/**
* requested app
*/
- public static $REQUESTEDAPP = '';
+ public static string $REQUESTEDAPP = '';
/**
* check if Nextcloud runs in cli mode
*/
- public static $CLI = false;
+ public static bool $CLI = false;
- /**
- * @var \OC\Autoloader $loader
- */
- public static $loader = null;
+ public static \OC\Autoloader $loader;
- /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
- public static $composerAutoloader = null;
+ public static \Composer\Autoload\ClassLoader $composerAutoloader;
- /**
- * @var \OC\Server
- */
- public static $server = null;
+ public static \OC\Server $server;
- /**
- * @var \OC\Config
- */
- private static $config = null;
+ private static \OC\Config $config;
/**
* @throws \RuntimeException when the 3rdparty directory is missing or
* the app path list is empty or contains an invalid path
*/
- public static function initPaths() {
+ public static function initPaths(): void {
if (defined('PHPUNIT_CONFIG_DIR')) {
self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
@@ -153,15 +147,15 @@ class OC {
}
self::$config = new \OC\Config(self::$configDir);
- OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
+ OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"] ?? ''), strlen(OC::$SERVERROOT)));
/**
* FIXME: The following lines are required because we can't yet instantiate
- * \OC::$server->getRequest() since \OC::$server does not yet exist.
+ * Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist.
*/
$params = [
'server' => [
- 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
- 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
+ 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null,
+ 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null,
],
];
$fakeRequest = new \OC\AppFramework\Http\Request(
@@ -241,8 +235,8 @@ class OC {
);
}
- public static function checkConfig() {
- $l = \OC::$server->getL10N('lib');
+ public static function checkConfig(): void {
+ $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
// Create config if it does not already exist
$configFilePath = self::$configDir .'/config.php';
@@ -254,7 +248,7 @@ class OC {
$configFileWritable = is_writable($configFilePath);
if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
|| !$configFileWritable && \OCP\Util::needUpgrade()) {
- $urlGenerator = \OC::$server->getURLGenerator();
+ $urlGenerator = Server::get(IURLGenerator::class);
if (self::$CLI) {
echo $l->t('Cannot write into "config" directory!')."\n";
@@ -275,7 +269,7 @@ class OC {
}
}
- public static function checkInstalled(\OC\SystemConfig $systemConfig) {
+ public static function checkInstalled(\OC\SystemConfig $systemConfig): void {
if (defined('OC_CONSOLE')) {
return;
}
@@ -291,7 +285,7 @@ class OC {
}
}
- public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig) {
+ public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void {
// Allow ajax update script to execute without being stopped
if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
// send http status 503
@@ -310,31 +304,29 @@ class OC {
/**
* Prints the upgrade page
- *
- * @param \OC\SystemConfig $systemConfig
*/
- private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
+ private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
$tooBig = false;
if (!$disableWebUpdater) {
- $apps = \OC::$server->getAppManager();
+ $apps = Server::get(\OCP\App\IAppManager::class);
if ($apps->isInstalled('user_ldap')) {
- $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
$result = $qb->select($qb->func()->count('*', 'user_count'))
->from('ldap_user_mapping')
- ->execute();
+ ->executeQuery();
$row = $result->fetch();
$result->closeCursor();
$tooBig = ($row['user_count'] > 50);
}
if (!$tooBig && $apps->isInstalled('user_saml')) {
- $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
$result = $qb->select($qb->func()->count('*', 'user_count'))
->from('user_saml_users')
- ->execute();
+ ->executeQuery();
$row = $result->fetch();
$result->closeCursor();
@@ -342,7 +334,7 @@ class OC {
}
if (!$tooBig) {
// count users
- $stats = \OC::$server->getUserManager()->countUsers();
+ $stats = Server::get(\OCP\IUserManager::class)->countUsers();
$totalUsers = array_sum($stats);
$tooBig = ($totalUsers > 50);
}
@@ -380,7 +372,7 @@ class OC {
\OCP\Util::addScript('core', 'update');
/** @var \OC\App\AppManager $appManager */
- $appManager = \OC::$server->getAppManager();
+ $appManager = Server::get(\OCP\App\IAppManager::class);
$tmpl = new OC_Template('', 'update.admin', 'guest');
$tmpl->assign('version', OC_Util::getVersionString());
@@ -398,7 +390,7 @@ class OC {
}
if (!empty($incompatibleShippedApps)) {
- $l = \OC::$server->getL10N('core');
+ $l = Server::get(\OCP\L10N\IFactory::class)->get('core');
$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
throw new \OCP\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
}
@@ -415,8 +407,8 @@ class OC {
$tmpl->printPage();
}
- public static function initSession() {
- if (self::$server->getRequest()->getServerProtocol() === 'https') {
+ public static function initSession(): void {
+ if (Server::get(\OCP\IRequest::class)->getServerProtocol() === 'https') {
ini_set('session.cookie_secure', 'true');
}
@@ -434,13 +426,13 @@ class OC {
// set the session name to the instance id - which is unique
$session = new \OC\Session\Internal($sessionName);
- $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
+ $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class);
$session = $cryptoWrapper->wrapSession($session);
self::$server->setSession($session);
// if session can't be started break with http 500 error
} catch (Exception $e) {
- \OC::$server->getLogger()->logException($e, ['app' => 'base']);
+ Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
//show the user a detailed error page
OC_Template::printExceptionErrorPage($e, 500);
die();
@@ -455,7 +447,7 @@ class OC {
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
}
- \OC::$server->getUserSession()->logout();
+ Server::get(IUserSession::class)->logout();
}
if (!self::hasSessionRelaxedExpiry()) {
@@ -464,24 +456,21 @@ class OC {
$session->close();
}
- /**
- * @return string
- */
- private static function getSessionLifeTime() {
- return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
+ private static function getSessionLifeTime(): int {
+ return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24);
}
/**
* @return bool true if the session expiry should only be done by gc instead of an explicit timeout
*/
public static function hasSessionRelaxedExpiry(): bool {
- return \OC::$server->getConfig()->getSystemValue('session_relaxed_expiry', false);
+ return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false);
}
/**
* Try to set some values to the required Nextcloud default
*/
- public static function setRequiredIniValues() {
+ public static function setRequiredIniValues(): void {
@ini_set('default_charset', 'UTF-8');
@ini_set('gd.jpeg_ignore_warning', '1');
}
@@ -489,7 +478,7 @@ class OC {
/**
* Send the same site cookies
*/
- private static function sendSameSiteCookies() {
+ private static function sendSameSiteCookies(): void {
$cookieParams = session_get_cookie_params();
$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
$policies = [
@@ -526,8 +515,8 @@ class OC {
* We use an additional cookie since we want to protect logout CSRF and
* also we can't directly interfere with PHP's session mechanism.
*/
- private static function performSameSiteCookieProtection(\OCP\IConfig $config) {
- $request = \OC::$server->getRequest();
+ private static function performSameSiteCookieProtection(\OCP\IConfig $config): void {
+ $request = Server::get(\OCP\IRequest::class);
// Some user agents are notorious and don't really properly follow HTTP
// specifications. For those, have an automated opt-out. Since the protection
@@ -574,7 +563,7 @@ class OC {
}
}
- public static function init() {
+ public static function init(): void {
// calculate the root directories
OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
@@ -618,7 +607,7 @@ class OC {
self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
self::$server->boot();
- $eventLogger = \OC::$server->getEventLogger();
+ $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
$eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
$eventLogger->start('boot', 'Initialize');
@@ -655,13 +644,13 @@ class OC {
self::setRequiredIniValues();
self::handleAuthHeaders();
- $systemConfig = \OC::$server->get(\OC\SystemConfig::class);
+ $systemConfig = Server::get(\OC\SystemConfig::class);
self::registerAutoloaderCache($systemConfig);
// initialize intl fallback if necessary
OC_Util::isSetLocaleWorking();
- $config = \OC::$server->get(\OCP\IConfig::class);
+ $config = Server::get(\OCP\IConfig::class);
if (!defined('PHPUNIT_RUN')) {
$errorHandler = new OC\Log\ErrorHandler(
\OCP\Server::get(\Psr\Log\LoggerInterface::class),
@@ -680,7 +669,7 @@ class OC {
}
/** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
- $bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
+ $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
$bootstrapCoordinator->runInitialRegistration();
$eventLogger->start('init_session', 'Initialize session');
@@ -739,7 +728,7 @@ class OC {
}
OC_User::useBackend(new \OC\User\Database());
- \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
+ Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
// Subscribe to the hook
\OCP\Util::connectHook(
@@ -769,18 +758,18 @@ class OC {
if ($systemConfig->getValue("installed", false)) {
OC_App::loadApp('settings');
/* Build core application to make sure that listeners are registered */
- self::$server->get(\OC\Core\Application::class);
+ Server::get(\OC\Core\Application::class);
}
//make sure temporary files are cleaned up
- $tmpManager = \OC::$server->getTempManager();
+ $tmpManager = Server::get(\OCP\ITempManager::class);
register_shutdown_function([$tmpManager, 'clean']);
- $lockProvider = \OC::$server->getLockingProvider();
+ $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
register_shutdown_function([$lockProvider, 'releaseAll']);
// Check whether the sample configuration has been copied
if ($systemConfig->getValue('copied_sample_config', false)) {
- $l = \OC::$server->getL10N('lib');
+ $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
OC_Template::printErrorPage(
$l->t('Sample configuration detected'),
$l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
@@ -789,19 +778,19 @@ class OC {
return;
}
- $request = \OC::$server->getRequest();
+ $request = Server::get(\OCP\IRequest::class);
$host = $request->getInsecureServerHost();
/**
* if the host passed in headers isn't trusted
* FIXME: Should not be in here at all :see_no_evil:
*/
if (!OC::$CLI
- && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
+ && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
&& $config->getSystemValue('installed', false)
) {
// Allow access to CSS resources
$isScssRequest = false;
- if (strpos($request->getPathInfo(), '/css/') === 0) {
+ if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
$isScssRequest = true;
}
@@ -814,8 +803,7 @@ class OC {
if (!$isScssRequest) {
http_response_code(400);
-
- \OC::$server->getLogger()->info(
+ Server::get(LoggerInterface::class)->info(
'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
[
'app' => 'core',
@@ -825,7 +813,7 @@ class OC {
);
$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
- $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
+ $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
$tmpl->printPage();
exit();
@@ -843,18 +831,17 @@ class OC {
/**
* register hooks for the cleanup of cache and bruteforce protection
*/
- public static function registerCleanupHooks(\OC\SystemConfig $systemConfig) {
+ public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
//don't try to do this before we are properly setup
if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
-
// NOTE: This will be replaced to use OCP
- $userSession = self::$server->getUserSession();
+ $userSession = Server::get(\OC\User\Session::class);
$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
// reset brute force delay for this IP address and username
- $uid = \OC::$server->getUserSession()->getUser()->getUID();
- $request = \OC::$server->getRequest();
- $throttler = \OC::$server->getBruteForceThrottler();
+ $uid = $userSession->getUser()->getUID();
+ $request = Server::get(\OCP\IRequest::class);
+ $throttler = Server::get(\OC\Security\Bruteforce\Throttler::class);
$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
}
@@ -869,18 +856,17 @@ class OC {
} catch (\Exception $e) {
// a GC exception should not prevent users from using OC,
// so log the exception
- \OC::$server->getLogger()->logException($e, [
- 'message' => 'Exception when running cache gc.',
- 'level' => ILogger::WARN,
+ Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
'app' => 'core',
+ 'exception' => $e,
]);
}
});
}
}
- private static function registerEncryptionWrapperAndHooks() {
- $manager = self::$server->getEncryptionManager();
+ private static function registerEncryptionWrapperAndHooks(): void {
+ $manager = Server::get(\OCP\Encryption\IManager::class);
\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
$enabled = $manager->isEnabled();
@@ -892,17 +878,17 @@ class OC {
}
}
- private static function registerAccountHooks() {
+ private static function registerAccountHooks(): void {
/** @var IEventDispatcher $dispatcher */
- $dispatcher = \OC::$server->get(IEventDispatcher::class);
+ $dispatcher = Server::get(IEventDispatcher::class);
$dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
}
- private static function registerAppRestrictionsHooks() {
+ private static function registerAppRestrictionsHooks(): void {
/** @var \OC\Group\Manager $groupManager */
- $groupManager = self::$server->query(\OCP\IGroupManager::class);
+ $groupManager = Server::get(\OCP\IGroupManager::class);
$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
- $appManager = self::$server->getAppManager();
+ $appManager = Server::get(\OCP\App\IAppManager::class);
$apps = $appManager->getEnabledAppsForGroup($group);
foreach ($apps as $appId) {
$restrictions = $appManager->getAppRestriction($appId);
@@ -921,29 +907,29 @@ class OC {
});
}
- private static function registerResourceCollectionHooks() {
+ private static function registerResourceCollectionHooks(): void {
\OC\Collaboration\Resources\Listener::register(Server::get(SymfonyAdapter::class), Server::get(IEventDispatcher::class));
}
- private static function registerFileReferenceEventListener() {
+ private static function registerFileReferenceEventListener(): void {
\OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
}
/**
* register hooks for sharing
*/
- public static function registerShareHooks(\OC\SystemConfig $systemConfig) {
+ public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
if ($systemConfig->getValue('installed')) {
OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
/** @var IEventDispatcher $dispatcher */
- $dispatcher = \OC::$server->get(IEventDispatcher::class);
+ $dispatcher = Server::get(IEventDispatcher::class);
$dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
}
}
- protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig) {
+ protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
// The class loader takes an optional low-latency cache, which MUST be
// namespaced. The instanceid is used for namespacing, but might be
// unavailable at this point. Furthermore, it might not be possible to
@@ -953,7 +939,7 @@ class OC {
$instanceId = $systemConfig->getValue('instanceid', null);
if ($instanceId) {
try {
- $memcacheFactory = \OC::$server->getMemCacheFactory();
+ $memcacheFactory = Server::get(\OCP\ICacheFactory::class);
self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
} catch (\Exception $ex) {
}
@@ -963,28 +949,28 @@ class OC {
/**
* Handle the request
*/
- public static function handleRequest() {
- \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
- $systemConfig = \OC::$server->getSystemConfig();
+ public static function handleRequest(): void {
+ Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
+ $systemConfig = Server::get(\OC\SystemConfig::class);
// Check if Nextcloud is installed or in maintenance (update) mode
if (!$systemConfig->getValue('installed', false)) {
\OC::$server->getSession()->clear();
$setupHelper = new OC\Setup(
$systemConfig,
- \OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
- \OC::$server->getL10N('lib'),
- \OC::$server->query(\OCP\Defaults::class),
- \OC::$server->get(\Psr\Log\LoggerInterface::class),
- \OC::$server->getSecureRandom(),
- \OC::$server->query(\OC\Installer::class)
+ Server::get(\bantu\IniGetWrapper\IniGetWrapper::class),
+ Server::get(\OCP\L10N\IFactory::class)->get('lib'),
+ Server::get(\OCP\Defaults::class),
+ Server::get(\Psr\Log\LoggerInterface::class),
+ Server::get(\OCP\Security\ISecureRandom::class),
+ Server::get(\OC\Installer::class)
);
$controller = new OC\Core\Controller\SetupController($setupHelper);
$controller->run($_POST);
exit();
}
- $request = \OC::$server->getRequest();
+ $request = Server::get(\OCP\IRequest::class);
$requestPath = $request->getRawPathInfo();
if ($requestPath === '/heartbeat') {
return;
@@ -1006,14 +992,13 @@ class OC {
// emergency app disabling
if ($requestPath === '/disableapp'
&& $request->getMethod() === 'POST'
- && ((array)$request->getParam('appid')) !== ''
) {
\OC_JSON::callCheck();
\OC_JSON::checkAdminUser();
$appIds = (array)$request->getParam('appid');
foreach ($appIds as $appId) {
$appId = \OC_App::cleanAppId($appId);
- \OC::$server->getAppManager()->disableApp($appId);
+ Server::get(\OCP\App\IAppManager::class)->disableApp($appId);
}
\OC_JSON::success();
exit();
@@ -1026,7 +1011,7 @@ class OC {
if (!\OCP\Util::needUpgrade()
&& !((bool) $systemConfig->getValue('maintenance', false))) {
// For logged-in users: Load everything
- if (\OC::$server->getUserSession()->isLoggedIn()) {
+ if (Server::get(IUserSession::class)->isLoggedIn()) {
OC_App::loadApps();
} else {
// For guests: Load only filesystem and logging
@@ -1047,7 +1032,7 @@ class OC {
OC_App::loadApps(['filesystem', 'logging']);
OC_App::loadApps();
}
- OC::$server->get(\OC\Route\Router::class)->match($request->getRawPathInfo());
+ Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
return;
} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
//header('HTTP/1.0 404 Not Found');
@@ -1085,20 +1070,20 @@ class OC {
// Redirect to the default app or login only as an entry point
if ($requestPath === '') {
// Someone is logged in
- if (\OC::$server->getUserSession()->isLoggedIn()) {
- header('Location: ' . \OC::$server->getURLGenerator()->linkToDefaultPageUrl());
+ if (Server::get(IUserSession::class)->isLoggedIn()) {
+ header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
} else {
// Not handled and not logged in
- header('Location: ' . \OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
+ header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
}
return;
}
try {
- return OC::$server->get(\OC\Route\Router::class)->match('/error/404');
+ Server::get(\OC\Route\Router::class)->match('/error/404');
} catch (\Exception $e) {
logger('core')->emergency($e->getMessage(), ['exception' => $e]);
- $l = \OC::$server->getL10N('lib');
+ $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
OC_Template::printErrorPage(
$l->t('404'),
$l->t('The page could not be found on the server.'),
@@ -1109,12 +1094,9 @@ class OC {
/**
* Check login: apache auth, auth token, basic auth
- *
- * @param OCP\IRequest $request
- * @return boolean
*/
- public static function handleLogin(OCP\IRequest $request) {
- $userSession = self::$server->getUserSession();
+ public static function handleLogin(OCP\IRequest $request): bool {
+ $userSession = Server::get(\OC\User\Session::class);
if (OC_User::handleApacheAuth()) {
return true;
}
@@ -1127,13 +1109,13 @@ class OC {
&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
return true;
}
- if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
+ if ($userSession->tryBasicAuthLogin($request, Server::get(\OC\Security\Bruteforce\Throttler::class))) {
return true;
}
return false;
}
- protected static function handleAuthHeaders() {
+ protected static function handleAuthHeaders(): void {
//copy http auth headers for apache+php-fcgid work around
if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
@@ -1145,7 +1127,7 @@ class OC {
'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
];
foreach ($vars as $var) {
- if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
+ if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
$credentials = explode(':', base64_decode($matches[1]), 2);
if (count($credentials) === 2) {
$_SERVER['PHP_AUTH_USER'] = $credentials[0];
diff --git a/lib/private/AppFramework/Http/Request.php b/lib/private/AppFramework/Http/Request.php
index 286187c696c..32cce8a88e1 100644
--- a/lib/private/AppFramework/Http/Request.php
+++ b/lib/private/AppFramework/Http/Request.php
@@ -50,7 +50,6 @@ use OC\Security\TrustedDomainHelper;
use OCP\IConfig;
use OCP\IRequest;
use OCP\IRequestId;
-use OCP\Security\ICrypto;
use Symfony\Component\HttpFoundation\IpUtils;
/**
@@ -79,10 +78,10 @@ class Request implements \ArrayAccess, \Countable, IRequest {
public const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
public const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|\[::1\])$/';
- protected $inputStream;
+ protected string $inputStream;
protected $content;
- protected $items = [];
- protected $allowedKeys = [
+ protected array $items = [];
+ protected array $allowedKeys = [
'get',
'post',
'files',
@@ -94,17 +93,11 @@ class Request implements \ArrayAccess, \Countable, IRequest {
'method',
'requesttoken',
];
- /** @var RequestId */
- protected $requestId;
- /** @var IConfig */
- protected $config;
- /** @var ICrypto */
- protected $crypto;
- /** @var CsrfTokenManager|null */
- protected $csrfTokenManager;
+ protected IRequestId $requestId;
+ protected IConfig $config;
+ protected ?CsrfTokenManager $csrfTokenManager;
- /** @var bool */
- protected $contentDecoded = false;
+ protected bool $contentDecoded = false;
/**
* @param array $vars An associative array with the following optional values:
@@ -139,9 +132,7 @@ class Request implements \ArrayAccess, \Countable, IRequest {
}
foreach ($this->allowedKeys as $name) {
- $this->items[$name] = isset($vars[$name])
- ? $vars[$name]
- : [];
+ $this->items[$name] = $vars[$name] ?? [];
}
$this->items['parameters'] = array_merge(
diff --git a/lib/public/Log/functions.php b/lib/public/Log/functions.php
index cc6961d8fba..ac043b4d958 100644
--- a/lib/public/Log/functions.php
+++ b/lib/public/Log/functions.php
@@ -49,6 +49,7 @@ use function class_exists;
* @since 24.0.0
*/
function logger(string $appId = null): LoggerInterface {
+ /** @psalm-suppress TypeDoesNotContainNull false-positive, it may contain null if we are logging from initialization */
if (!class_exists(OC::class) || OC::$server === null) {
// If someone calls this log before Nextcloud is initialized, there is
// no logging available. In that case we return a noop implementation