diff options
author | Christoph Wurst <christoph@winzerhof-wurst.at> | 2020-04-10 14:19:56 +0200 |
---|---|---|
committer | Christoph Wurst <christoph@winzerhof-wurst.at> | 2020-04-10 14:19:56 +0200 |
commit | caff1023ea72bb2ea94130e18a2a6e2ccf819e5f (patch) | |
tree | 186d494c2aea5dea7255d3584ef5d595fc6e6194 /lib/private | |
parent | edf8ce32cffdb920e8171207b342abbd7f1fbe73 (diff) | |
download | nextcloud-server-caff1023ea72bb2ea94130e18a2a6e2ccf819e5f.tar.gz nextcloud-server-caff1023ea72bb2ea94130e18a2a6e2ccf819e5f.zip |
Format control structures, classes, methods and function
To continue this formatting madness, here's a tiny patch that adds
unified formatting for control structures like if and loops as well as
classes, their methods and anonymous functions. This basically forces
the constructs to start on the same line. This is not exactly what PSR2
wants, but I think we can have a few exceptions with "our" style. The
starting of braces on the same line is pracrically standard for our
code.
This also removes and empty lines from method/function bodies at the
beginning and end.
Signed-off-by: Christoph Wurst <christoph@winzerhof-wurst.at>
Diffstat (limited to 'lib/private')
364 files changed, 819 insertions, 1255 deletions
diff --git a/lib/private/Accounts/AccountManager.php b/lib/private/Accounts/AccountManager.php index 5f2ea465ed7..8b0cb972c59 100644 --- a/lib/private/Accounts/AccountManager.php +++ b/lib/private/Accounts/AccountManager.php @@ -191,7 +191,6 @@ class AccountManager implements IAccountManager { * @return array */ protected function addMissingDefaultValues(array $userData) { - foreach ($userData as $key => $value) { if (!isset($userData[$key]['verified'])) { $userData[$key]['verified'] = self::NOT_VERIFIED; @@ -216,45 +215,44 @@ class AccountManager implements IAccountManager { $emailVerified = isset($oldData[self::PROPERTY_EMAIL]['verified']) && $oldData[self::PROPERTY_EMAIL]['verified'] === self::VERIFIED; // keep old verification status if we don't have a new one - if(!isset($newData[self::PROPERTY_TWITTER]['verified'])) { + if (!isset($newData[self::PROPERTY_TWITTER]['verified'])) { // keep old verification status if value didn't changed and an old value exists $keepOldStatus = $newData[self::PROPERTY_TWITTER]['value'] === $oldData[self::PROPERTY_TWITTER]['value'] && isset($oldData[self::PROPERTY_TWITTER]['verified']); $newData[self::PROPERTY_TWITTER]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_TWITTER]['verified'] : self::NOT_VERIFIED; } - if(!isset($newData[self::PROPERTY_WEBSITE]['verified'])) { + if (!isset($newData[self::PROPERTY_WEBSITE]['verified'])) { // keep old verification status if value didn't changed and an old value exists $keepOldStatus = $newData[self::PROPERTY_WEBSITE]['value'] === $oldData[self::PROPERTY_WEBSITE]['value'] && isset($oldData[self::PROPERTY_WEBSITE]['verified']); $newData[self::PROPERTY_WEBSITE]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_WEBSITE]['verified'] : self::NOT_VERIFIED; } - if(!isset($newData[self::PROPERTY_EMAIL]['verified'])) { + if (!isset($newData[self::PROPERTY_EMAIL]['verified'])) { // keep old verification status if value didn't changed and an old value exists $keepOldStatus = $newData[self::PROPERTY_EMAIL]['value'] === $oldData[self::PROPERTY_EMAIL]['value'] && isset($oldData[self::PROPERTY_EMAIL]['verified']); $newData[self::PROPERTY_EMAIL]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_EMAIL]['verified'] : self::VERIFICATION_IN_PROGRESS; } // reset verification status if a value from a previously verified data was changed - if($twitterVerified && + if ($twitterVerified && $oldData[self::PROPERTY_TWITTER]['value'] !== $newData[self::PROPERTY_TWITTER]['value'] ) { $newData[self::PROPERTY_TWITTER]['verified'] = self::NOT_VERIFIED; } - if($websiteVerified && + if ($websiteVerified && $oldData[self::PROPERTY_WEBSITE]['value'] !== $newData[self::PROPERTY_WEBSITE]['value'] ) { $newData[self::PROPERTY_WEBSITE]['verified'] = self::NOT_VERIFIED; } - if($emailVerified && + if ($emailVerified && $oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value'] ) { $newData[self::PROPERTY_EMAIL]['verified'] = self::NOT_VERIFIED; } return $newData; - } /** @@ -346,7 +344,7 @@ class AccountManager implements IAccountManager { private function parseAccountData(IUser $user, $data): Account { $account = new Account($user); - foreach($data as $property => $accountData) { + foreach ($data as $property => $accountData) { $account->setProperty($property, $accountData['value'] ?? '', $accountData['scope'] ?? self::VISIBILITY_PRIVATE, $accountData['verified'] ?? self::NOT_VERIFIED); } return $account; @@ -355,5 +353,4 @@ class AccountManager implements IAccountManager { public function getAccount(IUser $user): IAccount { return $this->parseAccountData($user, $this->getUser($user)); } - } diff --git a/lib/private/Accounts/Hooks.php b/lib/private/Accounts/Hooks.php index 17eb7a3cf5a..2288b884c5c 100644 --- a/lib/private/Accounts/Hooks.php +++ b/lib/private/Accounts/Hooks.php @@ -50,7 +50,6 @@ class Hooks { * @param array $params */ public function changeUserHook($params) { - $accountManager = $this->getAccountManager(); /** @var IUser $user */ @@ -79,7 +78,6 @@ class Hooks { } break; } - } /** @@ -93,5 +91,4 @@ class Hooks { } return $this->accountManager; } - } diff --git a/lib/private/Activity/Manager.php b/lib/private/Activity/Manager.php index fc1c32a475f..ffe6c335b27 100644 --- a/lib/private/Activity/Manager.php +++ b/lib/private/Activity/Manager.php @@ -90,7 +90,7 @@ class Manager implements IManager { } $this->consumers = []; - foreach($this->consumersClosures as $consumer) { + foreach ($this->consumersClosures as $consumer) { $c = $consumer(); if ($c instanceof IConsumer) { $this->consumers[] = $c; @@ -385,5 +385,4 @@ class Manager implements IManager { // Token found login as that user return array_shift($users); } - } diff --git a/lib/private/AllConfig.php b/lib/private/AllConfig.php index e1517440b46..8834ac9b592 100644 --- a/lib/private/AllConfig.php +++ b/lib/private/AllConfig.php @@ -90,7 +90,7 @@ class AllConfig implements \OCP\IConfig { * because the database connection was created with an uninitialized config */ private function fixDIInit() { - if($this->connection === null) { + if ($this->connection === null) { $this->connection = \OC::$server->getDatabaseConnection(); } } @@ -485,7 +485,7 @@ class AllConfig implements \OCP\IConfig { $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' . 'WHERE `appid` = ? AND `configkey` = ? '; - if($this->getSystemValue('dbtype', 'sqlite') === 'oci') { + if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') { //oracle hack: need to explicitly cast CLOB to CHAR for comparison $sql .= 'AND to_char(`configvalue`) = ?'; } else { @@ -517,7 +517,7 @@ class AllConfig implements \OCP\IConfig { $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' . 'WHERE `appid` = ? AND `configkey` = ? '; - if($this->getSystemValue('dbtype', 'sqlite') === 'oci') { + if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') { //oracle hack: need to explicitly cast CLOB to CHAR for comparison $sql .= 'AND LOWER(to_char(`configvalue`)) = LOWER(?)'; } else { diff --git a/lib/private/App/AppManager.php b/lib/private/App/AppManager.php index bf1e8492aa3..f756664e457 100644 --- a/lib/private/App/AppManager.php +++ b/lib/private/App/AppManager.php @@ -136,7 +136,7 @@ class AppManager implements IAppManager { $values = $this->appConfig->getValues(false, 'enabled'); $alwaysEnabledApps = $this->getAlwaysEnabledApps(); - foreach($alwaysEnabledApps as $appId) { + foreach ($alwaysEnabledApps as $appId) { $values[$appId] = 'yes'; } @@ -241,7 +241,7 @@ class AppManager implements IAppManager { } elseif ($user === null) { return false; } else { - if(empty($enabled)){ + if (empty($enabled)) { return false; } @@ -385,7 +385,6 @@ class AppManager implements IAppManager { ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups )); $this->clearAppsCache(); - } /** @@ -428,7 +427,7 @@ class AppManager implements IAppManager { */ public function getAppPath($appId) { $appPath = \OC_App::getAppPath($appId); - if($appPath === false) { + if ($appPath === false) { throw new AppPathNotFoundException('Could not find path for ' . $appId); } return $appPath; @@ -443,7 +442,7 @@ class AppManager implements IAppManager { */ public function getAppWebPath(string $appId): string { $appWebPath = \OC_App::getAppWebPath($appId); - if($appWebPath === false) { + if ($appWebPath === false) { throw new AppPathNotFoundException('Could not find web path for ' . $appId); } return $appWebPath; @@ -523,7 +522,7 @@ class AppManager implements IAppManager { } public function getAppVersion(string $appId, bool $useCache = true): string { - if(!$useCache || !isset($this->appVersions[$appId])) { + if (!$useCache || !isset($this->appVersions[$appId])) { $appInfo = $this->getAppInfo($appId); $this->appVersions[$appId] = ($appInfo !== null && isset($appInfo['version'])) ? $appInfo['version'] : '0'; } diff --git a/lib/private/App/AppStore/Bundles/BundleFetcher.php b/lib/private/App/AppStore/Bundles/BundleFetcher.php index 3925042a09e..cff3368d042 100644 --- a/lib/private/App/AppStore/Bundles/BundleFetcher.php +++ b/lib/private/App/AppStore/Bundles/BundleFetcher.php @@ -74,8 +74,8 @@ class BundleFetcher { $this->getBundles(), $this->getDefaultInstallationBundle() ); - foreach($bundles as $bundle) { - if($bundle->getIdentifier() === $identifier) { + foreach ($bundles as $bundle) { + if ($bundle->getIdentifier() === $identifier) { return $bundle; } } diff --git a/lib/private/App/AppStore/Bundles/CoreBundle.php b/lib/private/App/AppStore/Bundles/CoreBundle.php index 6dcaedab3e1..4e28d673883 100644 --- a/lib/private/App/AppStore/Bundles/CoreBundle.php +++ b/lib/private/App/AppStore/Bundles/CoreBundle.php @@ -40,5 +40,4 @@ class CoreBundle extends Bundle { 'bruteforcesettings', ]; } - } diff --git a/lib/private/App/AppStore/Bundles/EducationBundle.php b/lib/private/App/AppStore/Bundles/EducationBundle.php index 2d1968772d4..01296cd0536 100644 --- a/lib/private/App/AppStore/Bundles/EducationBundle.php +++ b/lib/private/App/AppStore/Bundles/EducationBundle.php @@ -47,5 +47,4 @@ class EducationBundle extends Bundle { 'user_saml', ]; } - } diff --git a/lib/private/App/AppStore/Bundles/EnterpriseBundle.php b/lib/private/App/AppStore/Bundles/EnterpriseBundle.php index 63faaf8e308..37213fe5a39 100644 --- a/lib/private/App/AppStore/Bundles/EnterpriseBundle.php +++ b/lib/private/App/AppStore/Bundles/EnterpriseBundle.php @@ -47,5 +47,4 @@ class EnterpriseBundle extends Bundle { 'terms_of_service', ]; } - } diff --git a/lib/private/App/AppStore/Bundles/GroupwareBundle.php b/lib/private/App/AppStore/Bundles/GroupwareBundle.php index d1726c7fa5f..49ae1068b10 100644 --- a/lib/private/App/AppStore/Bundles/GroupwareBundle.php +++ b/lib/private/App/AppStore/Bundles/GroupwareBundle.php @@ -44,5 +44,4 @@ class GroupwareBundle extends Bundle { 'mail' ]; } - } diff --git a/lib/private/App/AppStore/Bundles/HubBundle.php b/lib/private/App/AppStore/Bundles/HubBundle.php index cf2f44b7ea4..18dd9093623 100644 --- a/lib/private/App/AppStore/Bundles/HubBundle.php +++ b/lib/private/App/AppStore/Bundles/HubBundle.php @@ -27,7 +27,6 @@ declare(strict_types=1); namespace OC\App\AppStore\Bundles; class HubBundle extends Bundle { - public function getName() { return $this->l10n->t('Hub bundle'); } diff --git a/lib/private/App/AppStore/Bundles/SocialSharingBundle.php b/lib/private/App/AppStore/Bundles/SocialSharingBundle.php index 860f983eaa1..8ce4d1080ff 100644 --- a/lib/private/App/AppStore/Bundles/SocialSharingBundle.php +++ b/lib/private/App/AppStore/Bundles/SocialSharingBundle.php @@ -43,5 +43,4 @@ class SocialSharingBundle extends Bundle { 'socialsharing_diaspora', ]; } - } diff --git a/lib/private/App/AppStore/Fetcher/AppFetcher.php b/lib/private/App/AppStore/Fetcher/AppFetcher.php index 889facb3709..e4c2ba4e85e 100644 --- a/lib/private/App/AppStore/Fetcher/AppFetcher.php +++ b/lib/private/App/AppStore/Fetcher/AppFetcher.php @@ -88,11 +88,11 @@ class AppFetcher extends Fetcher { $allowPreReleases = $this->getChannel() === 'beta' || $this->getChannel() === 'daily'; $allowNightly = $this->getChannel() === 'daily'; - foreach($response['data'] as $dataKey => $app) { + foreach ($response['data'] as $dataKey => $app) { $releases = []; // Filter all compatible releases - foreach($app['releases'] as $release) { + foreach ($app['releases'] as $release) { // Exclude all nightly and pre-releases if required if (($allowNightly || $release['isNightly'] === false) && ($allowPreReleases || strpos($release['version'], '-') === false)) { @@ -123,12 +123,12 @@ class AppFetcher extends Fetcher { // Get the highest version $versions = []; - foreach($releases as $release) { + foreach ($releases as $release) { $versions[] = $release['version']; } usort($versions, 'version_compare'); $versions = array_reverse($versions); - if(isset($versions[0])) { + if (isset($versions[0])) { $highestVersion = $versions[0]; foreach ($releases as $release) { if ((string)$release['version'] === (string)$highestVersion) { diff --git a/lib/private/App/AppStore/Version/VersionParser.php b/lib/private/App/AppStore/Version/VersionParser.php index 36bc255175c..e851ecc31d1 100644 --- a/lib/private/App/AppStore/Version/VersionParser.php +++ b/lib/private/App/AppStore/Version/VersionParser.php @@ -47,7 +47,7 @@ class VersionParser { */ public function getVersion($versionSpec) { // * indicates that the version is compatible with all versions - if($versionSpec === '*') { + if ($versionSpec === '*') { return new Version('', ''); } @@ -59,17 +59,17 @@ class VersionParser { $secondVersion = isset($versionElements[1]) ? $versionElements[1] : ''; $secondVersionNumber = substr($secondVersion, 2); - switch(count($versionElements)) { + switch (count($versionElements)) { case 1: - if(!$this->isValidVersionString($firstVersionNumber)) { + if (!$this->isValidVersionString($firstVersionNumber)) { break; } - if(strpos($firstVersion, '>') === 0) { + if (strpos($firstVersion, '>') === 0) { return new Version($firstVersionNumber, ''); } return new Version('', $firstVersionNumber); case 2: - if(!$this->isValidVersionString($firstVersionNumber) || !$this->isValidVersionString($secondVersionNumber)) { + if (!$this->isValidVersionString($firstVersionNumber) || !$this->isValidVersionString($secondVersionNumber)) { break; } return new Version($firstVersionNumber, $secondVersionNumber); diff --git a/lib/private/App/CodeChecker/CodeChecker.php b/lib/private/App/CodeChecker/CodeChecker.php index 60276d5bfcc..aa8f43e6af2 100644 --- a/lib/private/App/CodeChecker/CodeChecker.php +++ b/lib/private/App/CodeChecker/CodeChecker.php @@ -37,7 +37,6 @@ use RegexIterator; use SplFileInfo; class CodeChecker extends BasicEmitter { - const CLASS_EXTENDS_NOT_ALLOWED = 1000; const CLASS_IMPLEMENTS_NOT_ALLOWED = 1001; const STATIC_CALL_NOT_ALLOWED = 1002; @@ -96,7 +95,7 @@ class CodeChecker extends BasicEmitter { $iterator = new RecursiveDirectoryIterator($folder, RecursiveDirectoryIterator::SKIP_DOTS); $iterator = new RecursiveCallbackFilterIterator($iterator, function ($item) use ($excludes) { /** @var SplFileInfo $item */ - foreach($excludes as $exclude) { + foreach ($excludes as $exclude) { if (substr($item->getPath(), 0, strlen($exclude)) === $exclude) { return false; } diff --git a/lib/private/App/CodeChecker/MigrationSchemaChecker.php b/lib/private/App/CodeChecker/MigrationSchemaChecker.php index 63e35e0647c..778bbfc2f31 100644 --- a/lib/private/App/CodeChecker/MigrationSchemaChecker.php +++ b/lib/private/App/CodeChecker/MigrationSchemaChecker.php @@ -53,7 +53,6 @@ class MigrationSchemaChecker extends NodeVisitorAbstract { $node->expr instanceof Node\Expr\MethodCall && $node->expr->var instanceof Node\Expr\Variable && $node->expr->var->name === $this->schemaVariableName) { - if ($node->expr->name === 'createTable') { if (isset($node->expr->args[0]) && $node->expr->args[0]->value instanceof Node\Scalar\String_) { if (!$this->checkNameLength($node->expr->args[0]->value->value)) { @@ -75,7 +74,6 @@ class MigrationSchemaChecker extends NodeVisitorAbstract { $node instanceof Node\Expr\MethodCall && $node->var instanceof Node\Expr\Variable && $node->var->name === $this->schemaVariableName) { - if ($node->name === 'renameTable') { $this->errors[] = [ 'line' => $node->getLine(), @@ -87,14 +85,13 @@ class MigrationSchemaChecker extends NodeVisitorAbstract { ]; } - /** - * Check columns and Indexes - */ + /** + * Check columns and Indexes + */ } elseif (!empty($this->tableVariableNames) && $node instanceof Node\Expr\MethodCall && $node->var instanceof Node\Expr\Variable && isset($this->tableVariableNames[$node->var->name])) { - if ($node->name === 'addColumn' || $node->name === 'changeColumn') { if (isset($node->args[0]) && $node->args[0]->value instanceof Node\Scalar\String_) { if (!$this->checkNameLength($node->args[0]->value->value)) { @@ -163,9 +160,9 @@ class MigrationSchemaChecker extends NodeVisitorAbstract { ]; } - /** - * Find the schema - */ + /** + * Find the schema + */ } elseif ($node instanceof Node\Expr\Assign && $node->expr instanceof Node\Expr\FuncCall && $node->var instanceof Node\Expr\Variable && diff --git a/lib/private/App/CompareVersion.php b/lib/private/App/CompareVersion.php index 314db1eadd6..12cd7615769 100644 --- a/lib/private/App/CompareVersion.php +++ b/lib/private/App/CompareVersion.php @@ -26,7 +26,6 @@ namespace OC\App; use InvalidArgumentException; class CompareVersion { - const REGEX_MAJOR = '/^\d+$/'; const REGEX_MAJOR_MINOR = '/^\d+.\d+$/'; const REGEX_MAJOR_MINOR_PATCH = '/^\d+.\d+.\d+$/'; @@ -46,7 +45,6 @@ class CompareVersion { */ public function isCompatible(string $actual, string $required, string $comparator = '>='): bool { - if (!preg_match(self::REGEX_SERVER, $actual)) { throw new InvalidArgumentException('server version is invalid'); } @@ -92,5 +90,4 @@ class CompareVersion { return version_compare("$actualMajor.$actualMinor.$actualPatch", "$requiredMajor.$requiredMinor.$requiredPatch", $comparator); } - } diff --git a/lib/private/App/InfoParser.php b/lib/private/App/InfoParser.php index 3d5bec2e829..6a56259a3f5 100644 --- a/lib/private/App/InfoParser.php +++ b/lib/private/App/InfoParser.php @@ -246,7 +246,7 @@ class InfoParser { $data = [ '@attributes' => [], ]; - if (!count($node->children())){ + if (!count($node->children())) { $value = (string)$node; if (!empty($value)) { $data['@value'] = (string)$node; diff --git a/lib/private/AppFramework/App.php b/lib/private/AppFramework/App.php index 382425ad046..c250a6e2d5d 100644 --- a/lib/private/AppFramework/App.php +++ b/lib/private/AppFramework/App.php @@ -107,7 +107,7 @@ class App { // first try $controllerName then go for \OCA\AppName\Controller\$controllerName try { $controller = $container->query($controllerName); - } catch(QueryException $e) { + } catch (QueryException $e) { if (strpos($controllerName, '\\Controller\\') !== false) { // This is from a global registered app route that is not enabled. [/*OC(A)*/, $app, /* Controller/Name*/] = explode('\\', $controllerName, 3); @@ -137,17 +137,17 @@ class App { $io = $container[IOutput::class]; - if(!is_null($httpHeaders)) { + if (!is_null($httpHeaders)) { $io->setHeader($httpHeaders); } - foreach($responseHeaders as $name => $value) { + foreach ($responseHeaders as $name => $value) { $io->setHeader($name . ': ' . $value); } - foreach($responseCookies as $name => $value) { + foreach ($responseCookies as $name => $value) { $expireDate = null; - if($value['expireDate'] instanceof \DateTime) { + if ($value['expireDate'] instanceof \DateTime) { $expireDate = $value['expireDate']->getTimestamp(); } $io->setCookie( @@ -183,7 +183,6 @@ class App { $io->setOutput($output); } } - } /** @@ -200,7 +199,6 @@ class App { */ public static function part(string $controllerName, string $methodName, array $urlParams, DIContainer $container) { - $container['urlParams'] = $urlParams; $controller = $container[$controllerName]; @@ -209,5 +207,4 @@ class App { list(, , $output) = $dispatcher->dispatch($controller, $methodName); return $output; } - } diff --git a/lib/private/AppFramework/DependencyInjection/DIContainer.php b/lib/private/AppFramework/DependencyInjection/DIContainer.php index 2ce504304dc..6654d3849b2 100644 --- a/lib/private/AppFramework/DependencyInjection/DIContainer.php +++ b/lib/private/AppFramework/DependencyInjection/DIContainer.php @@ -278,7 +278,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { $c->query(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class) ); - foreach($this->middleWares as $middleWare) { + foreach ($this->middleWares as $middleWare) { $dispatcher->registerMiddleware($c->query($middleWare)); } @@ -298,8 +298,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { /** * @return \OCP\IServerContainer */ - public function getServer() - { + public function getServer() { return $this->server; } @@ -350,7 +349,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { * @return mixed */ public function log($message, $level) { - switch($level){ + switch ($level) { case 'debug': $level = ILogger::DEBUG; break; diff --git a/lib/private/AppFramework/Http.php b/lib/private/AppFramework/Http.php index 4b08812b6cf..3c4a52fe37c 100644 --- a/lib/private/AppFramework/Http.php +++ b/lib/private/AppFramework/Http.php @@ -33,7 +33,6 @@ namespace OC\AppFramework; use OCP\AppFramework\Http as BaseHttp; class Http extends BaseHttp { - private $server; private $protocolVersion; protected $headers; @@ -119,8 +118,7 @@ class Http extends BaseHttp { */ public function getStatusHeader($status, \DateTime $lastModified=null, $ETag=null) { - - if(!is_null($lastModified)) { + if (!is_null($lastModified)) { $lastModified = $lastModified->format(\DateTime::RFC2822); } @@ -133,22 +131,18 @@ class Http extends BaseHttp { (isset($this->server['HTTP_IF_MODIFIED_SINCE']) && trim($this->server['HTTP_IF_MODIFIED_SINCE']) === $lastModified)) { - $status = self::STATUS_NOT_MODIFIED; } // we have one change currently for the http 1.0 header that differs // from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND // if this differs any more, we want to create childclasses for this - if($status === self::STATUS_TEMPORARY_REDIRECT + if ($status === self::STATUS_TEMPORARY_REDIRECT && $this->protocolVersion === 'HTTP/1.0') { - $status = self::STATUS_FOUND; } return $this->protocolVersion . ' ' . $status . ' ' . $this->headers[$status]; } - - } diff --git a/lib/private/AppFramework/Http/Dispatcher.php b/lib/private/AppFramework/Http/Dispatcher.php index 33ce8741acf..f1871e84c08 100644 --- a/lib/private/AppFramework/Http/Dispatcher.php +++ b/lib/private/AppFramework/Http/Dispatcher.php @@ -102,10 +102,10 @@ class Dispatcher { // exception and creates a response. If no response is created, it is // assumed that theres no middleware who can handle it and the error is // thrown again - } catch(\Exception $exception){ + } catch (\Exception $exception) { $response = $this->middlewareDispatcher->afterException( $controller, $methodName, $exception); - } catch(\Throwable $throwable) { + } catch (\Throwable $throwable) { $exception = new \Exception($throwable->getMessage(), $throwable->getCode(), $throwable); $response = $this->middlewareDispatcher->afterException( $controller, $methodName, $exception); @@ -141,7 +141,7 @@ class Dispatcher { // valid types that will be casted $types = ['int', 'integer', 'bool', 'boolean', 'float']; - foreach($this->reflector->getParameters() as $param => $default) { + foreach ($this->reflector->getParameters() as $param => $default) { // try to get the parameter from the request object and cast // it to the type annotated in the @param annotation @@ -150,7 +150,7 @@ class Dispatcher { // if this is submitted using GET or a POST form, 'false' should be // converted to false - if(($type === 'bool' || $type === 'boolean') && + if (($type === 'bool' || $type === 'boolean') && $value === 'false' && ( $this->request->method === 'GET' || @@ -159,8 +159,7 @@ class Dispatcher { ) ) { $value = false; - - } elseif($value !== null && \in_array($type, $types, true)) { + } elseif ($value !== null && \in_array($type, $types, true)) { settype($value, $type); } @@ -170,13 +169,13 @@ class Dispatcher { $response = \call_user_func_array([$controller, $methodName], $arguments); // format response - if($response instanceof DataResponse || !($response instanceof Response)) { + if ($response instanceof DataResponse || !($response instanceof Response)) { // get format from the url format or request format parameter $format = $this->request->getParam('format'); // if none is given try the first Accept header - if($format === null) { + if ($format === null) { $headers = $this->request->getHeader('Accept'); $format = $controller->getResponderByHTTPHeader($headers, null); } @@ -190,5 +189,4 @@ class Dispatcher { return $response; } - } diff --git a/lib/private/AppFramework/Http/Output.php b/lib/private/AppFramework/Http/Output.php index d96898b2521..fd95f370360 100644 --- a/lib/private/AppFramework/Http/Output.php +++ b/lib/private/AppFramework/Http/Output.php @@ -96,5 +96,4 @@ class Output implements IOutput { $path = $this->webRoot ? : '/'; setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly); } - } diff --git a/lib/private/AppFramework/Http/Request.php b/lib/private/AppFramework/Http/Request.php index 5430d1ae922..1dcec3c3b98 100644 --- a/lib/private/AppFramework/Http/Request.php +++ b/lib/private/AppFramework/Http/Request.php @@ -64,7 +64,6 @@ use OCP\Security\ISecureRandom; * @property mixed[] server */ class Request implements \ArrayAccess, \Countable, IRequest { - const USER_AGENT_IE = '/(MSIE)|(Trident)/'; // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx const USER_AGENT_MS_EDGE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+ Edge\/[0-9.]+$/'; @@ -149,11 +148,11 @@ class Request implements \ArrayAccess, \Countable, IRequest { $this->config = $config; $this->csrfTokenManager = $csrfTokenManager; - if(!array_key_exists('method', $vars)) { + if (!array_key_exists('method', $vars)) { $vars['method'] = 'GET'; } - foreach($this->allowedKeys as $name) { + foreach ($this->allowedKeys as $name) { $this->items[$name] = isset($vars[$name]) ? $vars[$name] : []; @@ -165,7 +164,6 @@ class Request implements \ArrayAccess, \Countable, IRequest { $this->items['urlParams'], $this->items['params'] ); - } /** * @param array $parameters @@ -263,12 +261,12 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @return mixed|null */ public function __get($name) { - switch($name) { + switch ($name) { case 'put': case 'patch': case 'get': case 'post': - if($this->method !== strtoupper($name)) { + if ($this->method !== strtoupper($name)) { throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method)); } return $this->getContent(); @@ -318,7 +316,6 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @return string */ public function getHeader(string $name): string { - $name = strtoupper(str_replace('-', '_',$name)); if (isset($this->server['HTTP_' . $name])) { return $this->server['HTTP_' . $name]; @@ -447,21 +444,20 @@ class Request implements \ArrayAccess, \Countable, IRequest { // 'application/json' must be decoded manually. if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) { $params = json_decode(file_get_contents($this->inputStream), true); - if($params !== null && \count($params) > 0) { + if ($params !== null && \count($params) > 0) { $this->items['params'] = $params; - if($this->method === 'POST') { + if ($this->method === 'POST') { $this->items['post'] = $params; } } - // Handle application/x-www-form-urlencoded for methods other than GET + // Handle application/x-www-form-urlencoded for methods other than GET // or post correctly - } elseif($this->method !== 'GET' + } elseif ($this->method !== 'GET' && $this->method !== 'POST' && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) { - parse_str(file_get_contents($this->inputStream), $params); - if(\is_array($params)) { + if (\is_array($params)) { $this->items['params'] = $params; } } @@ -478,11 +474,11 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @return bool true if CSRF check passed */ public function passesCSRFCheck(): bool { - if($this->csrfTokenManager === null) { + if ($this->csrfTokenManager === null) { return false; } - if(!$this->passesStrictCookieCheck()) { + if (!$this->passesStrictCookieCheck()) { return false; } @@ -510,7 +506,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { if ($this->getHeader('OCS-APIREQUEST')) { return false; } - if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) { + if ($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) { return false; } @@ -535,7 +531,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { protected function getProtectedCookieName(string $name): string { $cookieParams = $this->getCookieParams(); $prefix = ''; - if($cookieParams['secure'] === true && $cookieParams['path'] === '/') { + if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { $prefix = '__Host-'; } @@ -550,12 +546,12 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @since 9.1.0 */ public function passesStrictCookieCheck(): bool { - if(!$this->cookieCheckRequired()) { + if (!$this->cookieCheckRequired()) { return true; } $cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict'); - if($this->getCookie($cookieName) === 'true' + if ($this->getCookie($cookieName) === 'true' && $this->passesLaxCookieCheck()) { return true; } @@ -570,12 +566,12 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @since 9.1.0 */ public function passesLaxCookieCheck(): bool { - if(!$this->cookieCheckRequired()) { + if (!$this->cookieCheckRequired()) { return true; } $cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax'); - if($this->getCookie($cookieName) === 'true') { + if ($this->getCookie($cookieName) === 'true') { return true; } return false; @@ -588,11 +584,11 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @return string */ public function getId(): string { - if(isset($this->server['UNIQUE_ID'])) { + if (isset($this->server['UNIQUE_ID'])) { return $this->server['UNIQUE_ID']; } - if(empty($this->requestId)) { + if (empty($this->requestId)) { $validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS; $this->requestId = $this->secureRandom->generate(20, $validChars); } @@ -649,15 +645,15 @@ class Request implements \ArrayAccess, \Countable, IRequest { $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : ''; $trustedProxies = $this->config->getSystemValue('trusted_proxies', []); - if(\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) { + if (\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) { $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [ 'HTTP_X_FORWARDED_FOR' // only have one default, so we cannot ship an insecure product out of the box ]); - foreach($forwardedForHeaders as $header) { - if(isset($this->server[$header])) { - foreach(explode(',', $this->server[$header]) as $IP) { + foreach ($forwardedForHeaders as $header) { + if (isset($this->server[$header])) { + foreach (explode(',', $this->server[$header]) as $IP) { $IP = trim($IP); if (filter_var($IP, FILTER_VALIDATE_IP) !== false) { return $IP; @@ -688,7 +684,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @return string Server protocol (http or https) */ public function getServerProtocol(): string { - if($this->config->getSystemValue('overwriteprotocol') !== '' + if ($this->config->getSystemValue('overwriteprotocol') !== '' && $this->isOverwriteCondition('protocol')) { return $this->config->getSystemValue('overwriteprotocol'); } @@ -734,7 +730,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { 'HTTP/2', ]; - if(\in_array($claimedProtocol, $validProtocols, true)) { + if (\in_array($claimedProtocol, $validProtocols, true)) { return $claimedProtocol; } @@ -748,7 +744,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { */ public function getRequestUri(): string { $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : ''; - if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) { + if ($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) { $uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME'])); } return $uri; @@ -776,7 +772,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { // FIXME: Sabre does not really belong here list($path, $name) = \Sabre\Uri\split($scriptName); if (!empty($path)) { - if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) { + if ($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) { $pathInfo = substr($pathInfo, \strlen($path)); } else { throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')"); @@ -792,7 +788,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { if ($name !== '' && strpos($pathInfo, $name) === 0) { $pathInfo = substr($pathInfo, \strlen($name)); } - if($pathInfo === false || $pathInfo === '/'){ + if ($pathInfo === false || $pathInfo === '/') { return ''; } else { return $pathInfo; @@ -810,7 +806,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { $pathInfo = rawurldecode($pathInfo); $encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']); - switch($encoding) { + switch ($encoding) { case 'ISO-8859-1': $pathInfo = utf8_encode($pathInfo); } @@ -921,7 +917,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { * isn't met */ private function getOverwriteHost() { - if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) { + if ($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) { return $this->config->getSystemValue('overwritehost'); } return null; diff --git a/lib/private/AppFramework/Middleware/AdditionalScriptsMiddleware.php b/lib/private/AppFramework/Middleware/AdditionalScriptsMiddleware.php index 605422ffefe..b9f238eecb3 100644 --- a/lib/private/AppFramework/Middleware/AdditionalScriptsMiddleware.php +++ b/lib/private/AppFramework/Middleware/AdditionalScriptsMiddleware.php @@ -66,5 +66,4 @@ class AdditionalScriptsMiddleware extends Middleware { return $response; } - } diff --git a/lib/private/AppFramework/Middleware/MiddlewareDispatcher.php b/lib/private/AppFramework/Middleware/MiddlewareDispatcher.php index 47b9a62af81..388e86c1e15 100644 --- a/lib/private/AppFramework/Middleware/MiddlewareDispatcher.php +++ b/lib/private/AppFramework/Middleware/MiddlewareDispatcher.php @@ -91,7 +91,7 @@ class MiddlewareDispatcher { // we need to count so that we know which middlewares we have to ask in // case there is an exception $middlewareCount = \count($this->middlewares); - for($i = 0; $i < $middlewareCount; $i++){ + for ($i = 0; $i < $middlewareCount; $i++) { $this->middlewareCounter++; $middleware = $this->middlewares[$i]; $middleware->beforeController($controller, $methodName); @@ -115,11 +115,11 @@ class MiddlewareDispatcher { * @throws \Exception the passed in exception if it can't handle it */ public function afterException(Controller $controller, string $methodName, \Exception $exception): Response { - for($i=$this->middlewareCounter-1; $i>=0; $i--){ + for ($i=$this->middlewareCounter-1; $i>=0; $i--) { $middleware = $this->middlewares[$i]; try { return $middleware->afterException($controller, $methodName, $exception); - } catch(\Exception $exception){ + } catch (\Exception $exception) { continue; } } @@ -138,7 +138,7 @@ class MiddlewareDispatcher { * @return Response a Response object */ public function afterController(Controller $controller, string $methodName, Response $response): Response { - for($i= \count($this->middlewares)-1; $i>=0; $i--){ + for ($i= \count($this->middlewares)-1; $i>=0; $i--) { $middleware = $this->middlewares[$i]; $response = $middleware->afterController($controller, $methodName, $response); } @@ -157,11 +157,10 @@ class MiddlewareDispatcher { * @return string the output that should be printed */ public function beforeOutput(Controller $controller, string $methodName, string $output): string { - for($i= \count($this->middlewares)-1; $i>=0; $i--){ + for ($i= \count($this->middlewares)-1; $i>=0; $i--) { $middleware = $this->middlewares[$i]; $output = $middleware->beforeOutput($controller, $methodName, $output); } return $output; } - } diff --git a/lib/private/AppFramework/Middleware/OCSMiddleware.php b/lib/private/AppFramework/Middleware/OCSMiddleware.php index fe0f58c1ab5..875c743e972 100644 --- a/lib/private/AppFramework/Middleware/OCSMiddleware.php +++ b/lib/private/AppFramework/Middleware/OCSMiddleware.php @@ -102,7 +102,6 @@ class OCSMiddleware extends Middleware { if ($controller instanceof OCSController && !($response instanceof BaseResponse)) { if ($response->getStatus() === Http::STATUS_UNAUTHORIZED || $response->getStatus() === Http::STATUS_FORBIDDEN) { - $message = ''; if ($response instanceof JSONResponse) { /** @var DataResponse $response */ @@ -145,7 +144,7 @@ class OCSMiddleware extends Middleware { $format = $this->request->getParam('format'); // if none is given try the first Accept header - if($format === null) { + if ($format === null) { $headers = $this->request->getHeader('Accept'); $format = $controller->getResponderByHTTPHeader($headers, 'xml'); } diff --git a/lib/private/AppFramework/Middleware/PublicShare/Exceptions/NeedAuthenticationException.php b/lib/private/AppFramework/Middleware/PublicShare/Exceptions/NeedAuthenticationException.php index cd6337470b9..b362a38bc74 100644 --- a/lib/private/AppFramework/Middleware/PublicShare/Exceptions/NeedAuthenticationException.php +++ b/lib/private/AppFramework/Middleware/PublicShare/Exceptions/NeedAuthenticationException.php @@ -24,5 +24,4 @@ namespace OC\AppFramework\Middleware\PublicShare\Exceptions; class NeedAuthenticationException extends \Exception { - } diff --git a/lib/private/AppFramework/Middleware/PublicShare/PublicShareMiddleware.php b/lib/private/AppFramework/Middleware/PublicShare/PublicShareMiddleware.php index b6e2611179f..4b2dd25a257 100644 --- a/lib/private/AppFramework/Middleware/PublicShare/PublicShareMiddleware.php +++ b/lib/private/AppFramework/Middleware/PublicShare/PublicShareMiddleware.php @@ -89,7 +89,6 @@ class PublicShareMiddleware extends Middleware { } throw new NotFoundException(); - } public function afterException($controller, $methodName, \Exception $exception) { @@ -123,7 +122,7 @@ class PublicShareMiddleware extends Middleware { } // Check whether public sharing is enabled - if($this->config->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') { + if ($this->config->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') { return false; } diff --git a/lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php b/lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php index 46c33083e42..c2d1d7783ed 100644 --- a/lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php @@ -63,7 +63,7 @@ class BruteForceMiddleware extends Middleware { public function beforeController($controller, $methodName) { parent::beforeController($controller, $methodName); - if($this->reflector->hasAnnotation('BruteForceProtection')) { + if ($this->reflector->hasAnnotation('BruteForceProtection')) { $action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action'); $this->throttler->sleepDelay($this->request->getRemoteAddress(), $action); } @@ -73,7 +73,7 @@ class BruteForceMiddleware extends Middleware { * {@inheritDoc} */ public function afterController($controller, $methodName, Response $response) { - if($this->reflector->hasAnnotation('BruteForceProtection') && $response->isThrottled()) { + if ($this->reflector->hasAnnotation('BruteForceProtection') && $response->isThrottled()) { $action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action'); $ip = $this->request->getRemoteAddress(); $this->throttler->sleepDelay($ip, $action); diff --git a/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php b/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php index acfbab25ed4..af6d3de6570 100644 --- a/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php @@ -84,7 +84,7 @@ class CORSMiddleware extends Middleware { // ensure that @CORS annotated API routes are not used in conjunction // with session authentication since this enables CSRF attack vectors if ($this->reflector->hasAnnotation('CORS') && - !$this->reflector->hasAnnotation('PublicPage')) { + !$this->reflector->hasAnnotation('PublicPage')) { $user = $this->request->server['PHP_AUTH_USER']; $pass = $this->request->server['PHP_AUTH_PW']; @@ -113,13 +113,13 @@ class CORSMiddleware extends Middleware { public function afterController($controller, $methodName, Response $response) { // only react if its a CORS request and if the request sends origin and - if(isset($this->request->server['HTTP_ORIGIN']) && + if (isset($this->request->server['HTTP_ORIGIN']) && $this->reflector->hasAnnotation('CORS')) { // allow credentials headers must not be true or CSRF is possible // otherwise - foreach($response->getHeaders() as $header => $value) { - if(strtolower($header) === 'access-control-allow-credentials' && + foreach ($response->getHeaders() as $header => $value) { + if (strtolower($header) === 'access-control-allow-credentials' && strtolower(trim($value)) === 'true') { $msg = 'Access-Control-Allow-Credentials must not be '. 'set to true in order to prevent CSRF'; @@ -144,9 +144,9 @@ class CORSMiddleware extends Middleware { * @return Response a Response object or null in case that the exception could not be handled */ public function afterException($controller, $methodName, \Exception $exception) { - if($exception instanceof SecurityException){ + if ($exception instanceof SecurityException) { $response = new JSONResponse(['message' => $exception->getMessage()]); - if($exception->getCode() !== 0) { + if ($exception->getCode() !== 0) { $response->setStatus($exception->getCode()); } else { $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR); @@ -156,5 +156,4 @@ class CORSMiddleware extends Middleware { throw $exception; } - } diff --git a/lib/private/AppFramework/Middleware/Security/CSPMiddleware.php b/lib/private/AppFramework/Middleware/Security/CSPMiddleware.php index 3b9723cb6b9..057aa1529dc 100644 --- a/lib/private/AppFramework/Middleware/Security/CSPMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/CSPMiddleware.php @@ -71,7 +71,7 @@ class CSPMiddleware extends Middleware { $defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy(); $defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy); - if($this->cspNonceManager->browserSupportsCspV3()) { + if ($this->cspNonceManager->browserSupportsCspV3()) { $defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue()); } diff --git a/lib/private/AppFramework/Middleware/Security/Exceptions/ReloadExecutionException.php b/lib/private/AppFramework/Middleware/Security/Exceptions/ReloadExecutionException.php index 46673a7e5ee..934cae991b4 100644 --- a/lib/private/AppFramework/Middleware/Security/Exceptions/ReloadExecutionException.php +++ b/lib/private/AppFramework/Middleware/Security/Exceptions/ReloadExecutionException.php @@ -27,5 +27,4 @@ declare(strict_types=1); namespace OC\AppFramework\Middleware\Security\Exceptions; class ReloadExecutionException extends SecurityException { - } diff --git a/lib/private/AppFramework/Middleware/Security/Exceptions/SecurityException.php b/lib/private/AppFramework/Middleware/Security/Exceptions/SecurityException.php index e55f8e3f50a..bfa4116d12e 100644 --- a/lib/private/AppFramework/Middleware/Security/Exceptions/SecurityException.php +++ b/lib/private/AppFramework/Middleware/Security/Exceptions/SecurityException.php @@ -30,4 +30,5 @@ namespace OC\AppFramework\Middleware\Security\Exceptions; * * @package OC\AppFramework\Middleware\Security\Exceptions */ -class SecurityException extends \Exception {} +class SecurityException extends \Exception { +} diff --git a/lib/private/AppFramework/Middleware/Security/RateLimitingMiddleware.php b/lib/private/AppFramework/Middleware/Security/RateLimitingMiddleware.php index c7bf8e2c947..2a7cf982ff8 100644 --- a/lib/private/AppFramework/Middleware/Security/RateLimitingMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/RateLimitingMiddleware.php @@ -86,7 +86,7 @@ class RateLimitingMiddleware extends Middleware { $userLimit = $this->reflector->getAnnotationParameter('UserRateThrottle', 'limit'); $userPeriod = $this->reflector->getAnnotationParameter('UserRateThrottle', 'period'); $rateLimitIdentifier = get_class($controller) . '::' . $methodName; - if($userLimit !== '' && $userPeriod !== '' && $this->userSession->isLoggedIn()) { + if ($userLimit !== '' && $userPeriod !== '' && $this->userSession->isLoggedIn()) { $this->limiter->registerUserRequest( $rateLimitIdentifier, $userLimit, @@ -107,7 +107,7 @@ class RateLimitingMiddleware extends Middleware { * {@inheritDoc} */ public function afterException($controller, $methodName, \Exception $exception) { - if($exception instanceof RateLimitExceededException) { + if ($exception instanceof RateLimitExceededException) { if (stripos($this->request->getHeader('Accept'),'html') === false) { $response = new JSONResponse( [ @@ -116,7 +116,7 @@ class RateLimitingMiddleware extends Middleware { $exception->getCode() ); } else { - $response = new TemplateResponse( + $response = new TemplateResponse( 'core', '403', [ @@ -124,7 +124,7 @@ class RateLimitingMiddleware extends Middleware { ], 'guest' ); - $response->setStatus($exception->getCode()); + $response->setStatus($exception->getCode()); } return $response; diff --git a/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php b/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php index af34ed57182..12b0ef4e27a 100644 --- a/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php @@ -65,6 +65,4 @@ class ReloadExecutionMiddleware extends Middleware { return parent::afterException($controller, $methodName, $exception); } - - } diff --git a/lib/private/AppFramework/Middleware/Security/SameSiteCookieMiddleware.php b/lib/private/AppFramework/Middleware/Security/SameSiteCookieMiddleware.php index 5519b8705d9..70d4d4b88df 100644 --- a/lib/private/AppFramework/Middleware/Security/SameSiteCookieMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/SameSiteCookieMiddleware.php @@ -87,11 +87,11 @@ class SameSiteCookieMiddleware extends Middleware { // Append __Host to the cookie if it meets the requirements $cookiePrefix = ''; - if($cookieParams['secure'] === true && $cookieParams['path'] === '/') { + if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { $cookiePrefix = '__Host-'; } - foreach($policies as $policy) { + foreach ($policies as $policy) { header( sprintf( 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', diff --git a/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php b/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php index 0ae2d37b374..5eb1d7f30be 100644 --- a/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php @@ -137,17 +137,17 @@ class SecurityMiddleware extends Middleware { // security checks $isPublicPage = $this->reflector->hasAnnotation('PublicPage'); - if(!$isPublicPage) { - if(!$this->isLoggedIn) { + if (!$isPublicPage) { + if (!$this->isLoggedIn) { throw new NotLoggedInException(); } - if($this->reflector->hasAnnotation('SubAdminRequired') + if ($this->reflector->hasAnnotation('SubAdminRequired') && !$this->isSubAdmin && !$this->isAdminUser) { throw new NotAdminException($this->l10n->t('Logged in user must be an admin or sub admin')); } - if(!$this->reflector->hasAnnotation('SubAdminRequired') + if (!$this->reflector->hasAnnotation('SubAdminRequired') && !$this->reflector->hasAnnotation('NoAdminRequired') && !$this->isAdminUser) { throw new NotAdminException($this->l10n->t('Logged in user must be an admin')); @@ -155,14 +155,14 @@ class SecurityMiddleware extends Middleware { } // Check for strict cookie requirement - if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) { - if(!$this->request->passesStrictCookieCheck()) { + if ($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) { + if (!$this->request->passesStrictCookieCheck()) { throw new StrictCookieMissingException(); } } // CSRF check - also registers the CSRF token since the session may be closed later Util::callRegister(); - if(!$this->reflector->hasAnnotation('NoCSRFRequired')) { + if (!$this->reflector->hasAnnotation('NoCSRFRequired')) { /* * Only allow the CSRF check to fail on OCS Requests. This kind of * hacks around that we have no full token auth in place yet and we @@ -171,7 +171,7 @@ class SecurityMiddleware extends Middleware { * Additionally we allow Bearer authenticated requests to pass on OCS routes. * This allows oauth apps (e.g. moodle) to use the OCS endpoints */ - if(!$this->request->passesCSRFCheck() && !( + if (!$this->request->passesCSRFCheck() && !( $controller instanceof OCSController && ( $this->request->getHeader('OCS-APIREQUEST') === 'true' || strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0 @@ -209,8 +209,8 @@ class SecurityMiddleware extends Middleware { * @return Response a Response object or null in case that the exception could not be handled */ public function afterException($controller, $methodName, \Exception $exception): Response { - if($exception instanceof SecurityException) { - if($exception instanceof StrictCookieMissingException) { + if ($exception instanceof SecurityException) { + if ($exception instanceof StrictCookieMissingException) { return new RedirectResponse(\OC::$WEBROOT); } if (stripos($this->request->getHeader('Accept'),'html') === false) { @@ -219,7 +219,7 @@ class SecurityMiddleware extends Middleware { $exception->getCode() ); } else { - if($exception instanceof NotLoggedInException) { + if ($exception instanceof NotLoggedInException) { $params = []; if (isset($this->request->server['REQUEST_URI'])) { $params['redirect_url'] = $this->request->server['REQUEST_URI']; @@ -241,5 +241,4 @@ class SecurityMiddleware extends Middleware { throw $exception; } - } diff --git a/lib/private/AppFramework/Middleware/SessionMiddleware.php b/lib/private/AppFramework/Middleware/SessionMiddleware.php index d2787dde745..88b85468252 100644 --- a/lib/private/AppFramework/Middleware/SessionMiddleware.php +++ b/lib/private/AppFramework/Middleware/SessionMiddleware.php @@ -69,5 +69,4 @@ class SessionMiddleware extends Middleware { } return $response; } - } diff --git a/lib/private/AppFramework/OCS/BaseResponse.php b/lib/private/AppFramework/OCS/BaseResponse.php index 6c49a685985..55410c8910b 100644 --- a/lib/private/AppFramework/OCS/BaseResponse.php +++ b/lib/private/AppFramework/OCS/BaseResponse.php @@ -30,7 +30,7 @@ use OCP\AppFramework\Http; use OCP\AppFramework\Http\DataResponse; use OCP\AppFramework\Http\Response; -abstract class BaseResponse extends Response { +abstract class BaseResponse extends Response { /** @var array */ protected $data; @@ -118,7 +118,6 @@ abstract class BaseResponse extends Response { $this->toXML($response, $writer); $writer->endDocument(); return $writer->outputMemory(true); - } /** diff --git a/lib/private/AppFramework/OCS/V2Response.php b/lib/private/AppFramework/OCS/V2Response.php index 693d58a4d43..1d4eb741210 100644 --- a/lib/private/AppFramework/OCS/V2Response.php +++ b/lib/private/AppFramework/OCS/V2Response.php @@ -35,7 +35,6 @@ class V2Response extends BaseResponse { * @return int */ public function getStatus() { - $status = parent::getStatus(); if ($status === API::RESPOND_UNAUTHORISED) { return Http::STATUS_UNAUTHORIZED; diff --git a/lib/private/AppFramework/Routing/RouteConfig.php b/lib/private/AppFramework/Routing/RouteConfig.php index 999412979b0..eb9991fbe69 100644 --- a/lib/private/AppFramework/Routing/RouteConfig.php +++ b/lib/private/AppFramework/Routing/RouteConfig.php @@ -125,13 +125,13 @@ class RouteConfig { // optionally register requirements for route. This is used to // tell the route parser how url parameters should be matched - if(array_key_exists('requirements', $ocsRoute)) { + if (array_key_exists('requirements', $ocsRoute)) { $router->requirements($ocsRoute['requirements']); } // optionally register defaults for route. This is used to // tell the route parser how url parameters should be default valued - if(array_key_exists('defaults', $ocsRoute)) { + if (array_key_exists('defaults', $ocsRoute)) { $router->defaults($ocsRoute['defaults']); } } @@ -183,13 +183,13 @@ class RouteConfig { // optionally register requirements for route. This is used to // tell the route parser how url parameters should be matched - if(array_key_exists('requirements', $simpleRoute)) { + if (array_key_exists('requirements', $simpleRoute)) { $router->requirements($simpleRoute['requirements']); } // optionally register defaults for route. This is used to // tell the route parser how url parameters should be default valued - if(array_key_exists('defaults', $simpleRoute)) { + if (array_key_exists('defaults', $simpleRoute)) { $router->defaults($simpleRoute['defaults']); } } @@ -220,7 +220,7 @@ class RouteConfig { $root = $config['root'] ?? '/apps/' . $this->appName; // the url parameter used as id to the resource - foreach($actions as $action) { + foreach ($actions as $action) { $url = $root . $config['url']; $method = $action['name']; $verb = strtoupper($action['verb'] ?? 'GET'); @@ -270,7 +270,7 @@ class RouteConfig { foreach ($resources as $resource => $config) { // the url parameter used as id to the resource - foreach($actions as $action) { + foreach ($actions as $action) { $url = $config['url']; $method = $action['name']; $verb = strtoupper($action['verb'] ?? 'GET'); diff --git a/lib/private/AppFramework/Utility/ControllerMethodReflector.php b/lib/private/AppFramework/Utility/ControllerMethodReflector.php index 31f1892772f..2b7420cd41b 100644 --- a/lib/private/AppFramework/Utility/ControllerMethodReflector.php +++ b/lib/private/AppFramework/Utility/ControllerMethodReflector.php @@ -82,7 +82,7 @@ class ControllerMethodReflector implements IControllerMethodReflector { } $default = null; - if($param->isOptional()) { + if ($param->isOptional()) { $default = $param->getDefaultValue(); } $this->parameters[$param->name] = $default; @@ -97,7 +97,7 @@ class ControllerMethodReflector implements IControllerMethodReflector { * would return int or null if not existing */ public function getType(string $parameter) { - if(array_key_exists($parameter, $this->types)) { + if (array_key_exists($parameter, $this->types)) { return $this->types[$parameter]; } @@ -128,7 +128,7 @@ class ControllerMethodReflector implements IControllerMethodReflector { * @return string */ public function getAnnotationParameter(string $name, string $key): string { - if(isset($this->annotations[$name][$key])) { + if (isset($this->annotations[$name][$key])) { return $this->annotations[$name][$key]; } diff --git a/lib/private/AppFramework/Utility/SimpleContainer.php b/lib/private/AppFramework/Utility/SimpleContainer.php index 1703df3ea73..44bda1c3e6b 100644 --- a/lib/private/AppFramework/Utility/SimpleContainer.php +++ b/lib/private/AppFramework/Utility/SimpleContainer.php @@ -102,7 +102,7 @@ class SimpleContainer extends Container implements IContainer { throw new QueryException($baseMsg . ' Class can not be instantiated'); } - } catch(ReflectionException $e) { + } catch (ReflectionException $e) { throw new QueryException($baseMsg . ' ' . $e->getMessage()); } } @@ -140,7 +140,7 @@ class SimpleContainer extends Container implements IContainer { */ public function registerService($name, Closure $closure, $shared = true) { $name = $this->sanitizeName($name); - if (isset($this[$name])) { + if (isset($this[$name])) { unset($this[$name]); } if ($shared) { diff --git a/lib/private/AppFramework/Utility/TimeFactory.php b/lib/private/AppFramework/Utility/TimeFactory.php index b3d5ec831d1..30ab9bd3098 100644 --- a/lib/private/AppFramework/Utility/TimeFactory.php +++ b/lib/private/AppFramework/Utility/TimeFactory.php @@ -52,5 +52,4 @@ class TimeFactory implements ITimeFactory { public function getDateTime(string $time = 'now', \DateTimeZone $timezone = null): \DateTime { return new \DateTime($time, $timezone); } - } diff --git a/lib/private/Archive/Archive.php b/lib/private/Archive/Archive.php index 94956561c3e..5150e6ddee3 100644 --- a/lib/private/Archive/Archive.php +++ b/lib/private/Archive/Archive.php @@ -123,15 +123,15 @@ abstract class Archive { */ public function addRecursive($path, $source) { $dh = opendir($source); - if(is_resource($dh)) { + if (is_resource($dh)) { $this->addFolder($path); while (($file = readdir($dh)) !== false) { - if($file === '.' || $file === '..') { + if ($file === '.' || $file === '..') { continue; } - if(is_dir($source.'/'.$file)) { + if (is_dir($source.'/'.$file)) { $this->addRecursive($path.'/'.$file, $source.'/'.$file); - }else{ + } else { $this->addFile($path.'/'.$file, $source.'/'.$file); } } diff --git a/lib/private/Archive/ZIP.php b/lib/private/Archive/ZIP.php index cca6fd68c4e..31aea420a3d 100644 --- a/lib/private/Archive/ZIP.php +++ b/lib/private/Archive/ZIP.php @@ -35,7 +35,7 @@ namespace OC\Archive; use Icewind\Streams\CallbackWrapper; use OCP\ILogger; -class ZIP extends Archive{ +class ZIP extends Archive { /** * @var \ZipArchive zip */ @@ -48,8 +48,8 @@ class ZIP extends Archive{ public function __construct($source) { $this->path=$source; $this->zip=new \ZipArchive(); - if($this->zip->open($source, \ZipArchive::CREATE)) { - }else{ + if ($this->zip->open($source, \ZipArchive::CREATE)) { + } else { \OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, ILogger::WARN); } } @@ -68,12 +68,12 @@ class ZIP extends Archive{ * @return bool */ public function addFile($path, $source='') { - if($source and $source[0]=='/' and file_exists($source)) { + if ($source and $source[0]=='/' and file_exists($source)) { $result=$this->zip->addFile($source, $path); - }else{ + } else { $result=$this->zip->addFromString($path, $source); } - if($result) { + if ($result) { $this->zip->close();//close and reopen to save the zip $this->zip->open($this->path); } @@ -116,9 +116,9 @@ class ZIP extends Archive{ $files=$this->getFiles(); $folderContent=[]; $pathLength=strlen($path); - foreach($files as $file) { - if(substr($file, 0, $pathLength)==$path and $file!=$path) { - if(strrpos(substr($file, 0, -1), '/')<=$pathLength) { + foreach ($files as $file) { + if (substr($file, 0, $pathLength)==$path and $file!=$path) { + if (strrpos(substr($file, 0, -1), '/')<=$pathLength) { $folderContent[]=substr($file, $pathLength); } } @@ -132,7 +132,7 @@ class ZIP extends Archive{ public function getFiles() { $fileCount=$this->zip->numFiles; $files=[]; - for($i=0;$i<$fileCount;$i++) { + for ($i=0;$i<$fileCount;$i++) { $files[]=$this->zip->getNameIndex($i); } return $files; @@ -177,9 +177,9 @@ class ZIP extends Archive{ * @return bool */ public function remove($path) { - if($this->fileExists($path.'/')) { + if ($this->fileExists($path.'/')) { return $this->zip->deleteName($path.'/'); - }else{ + } else { return $this->zip->deleteName($path); } } @@ -190,19 +190,19 @@ class ZIP extends Archive{ * @return resource */ public function getStream($path, $mode) { - if($mode=='r' or $mode=='rb') { + if ($mode=='r' or $mode=='rb') { return $this->zip->getStream($path); } else { //since we can't directly get a writable stream, //make a temp copy of the file and put it back //in the archive when the stream is closed - if(strrpos($path, '.')!==false) { + if (strrpos($path, '.')!==false) { $ext=substr($path, strrpos($path, '.')); - }else{ + } else { $ext=''; } $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext); - if($this->fileExists($path)) { + if ($this->fileExists($path)) { $this->extractFile($path, $tmpFile); } $handle = fopen($tmpFile, $mode); @@ -225,9 +225,9 @@ class ZIP extends Archive{ * @return string */ private function stripPath($path) { - if(!$path || $path[0]=='/') { + if (!$path || $path[0]=='/') { return substr($path, 1); - }else{ + } else { return $path; } } diff --git a/lib/private/Authentication/Events/ARemoteWipeEvent.php b/lib/private/Authentication/Events/ARemoteWipeEvent.php index 111c6cfeeef..8d28cc5c783 100644 --- a/lib/private/Authentication/Events/ARemoteWipeEvent.php +++ b/lib/private/Authentication/Events/ARemoteWipeEvent.php @@ -42,5 +42,4 @@ abstract class ARemoteWipeEvent extends Event { public function getToken(): IToken { return $this->token; } - } diff --git a/lib/private/Authentication/Events/RemoteWipeFinished.php b/lib/private/Authentication/Events/RemoteWipeFinished.php index 0a33ebf635f..d50b7d28077 100644 --- a/lib/private/Authentication/Events/RemoteWipeFinished.php +++ b/lib/private/Authentication/Events/RemoteWipeFinished.php @@ -27,5 +27,4 @@ declare(strict_types=1); namespace OC\Authentication\Events; class RemoteWipeFinished extends ARemoteWipeEvent { - } diff --git a/lib/private/Authentication/Events/RemoteWipeStarted.php b/lib/private/Authentication/Events/RemoteWipeStarted.php index 565c9660de6..89b560511a7 100644 --- a/lib/private/Authentication/Events/RemoteWipeStarted.php +++ b/lib/private/Authentication/Events/RemoteWipeStarted.php @@ -27,5 +27,4 @@ declare(strict_types=1); namespace OC\Authentication\Events; class RemoteWipeStarted extends ARemoteWipeEvent { - } diff --git a/lib/private/Authentication/Exceptions/InvalidProviderException.php b/lib/private/Authentication/Exceptions/InvalidProviderException.php index 090150e4a33..970096540c4 100644 --- a/lib/private/Authentication/Exceptions/InvalidProviderException.php +++ b/lib/private/Authentication/Exceptions/InvalidProviderException.php @@ -30,9 +30,7 @@ use Exception; use Throwable; class InvalidProviderException extends Exception { - public function __construct(string $providerId, Throwable $previous = null) { parent::__construct("The provider '$providerId' does not exist'", 0, $previous); } - } diff --git a/lib/private/Authentication/Exceptions/InvalidTokenException.php b/lib/private/Authentication/Exceptions/InvalidTokenException.php index badcbba28e2..efc6096da88 100644 --- a/lib/private/Authentication/Exceptions/InvalidTokenException.php +++ b/lib/private/Authentication/Exceptions/InvalidTokenException.php @@ -25,5 +25,4 @@ namespace OC\Authentication\Exceptions; use Exception; class InvalidTokenException extends Exception { - } diff --git a/lib/private/Authentication/Exceptions/LoginRequiredException.php b/lib/private/Authentication/Exceptions/LoginRequiredException.php index 1c55e122d01..9d9ce055788 100644 --- a/lib/private/Authentication/Exceptions/LoginRequiredException.php +++ b/lib/private/Authentication/Exceptions/LoginRequiredException.php @@ -25,5 +25,4 @@ namespace OC\Authentication\Exceptions; use Exception; class LoginRequiredException extends Exception { - } diff --git a/lib/private/Authentication/Exceptions/PasswordLoginForbiddenException.php b/lib/private/Authentication/Exceptions/PasswordLoginForbiddenException.php index 05815cab9f4..02ddd06020d 100644 --- a/lib/private/Authentication/Exceptions/PasswordLoginForbiddenException.php +++ b/lib/private/Authentication/Exceptions/PasswordLoginForbiddenException.php @@ -25,5 +25,4 @@ namespace OC\Authentication\Exceptions; use Exception; class PasswordLoginForbiddenException extends Exception { - } diff --git a/lib/private/Authentication/Exceptions/PasswordlessTokenException.php b/lib/private/Authentication/Exceptions/PasswordlessTokenException.php index e5ba5d87ad5..5c59dd35366 100644 --- a/lib/private/Authentication/Exceptions/PasswordlessTokenException.php +++ b/lib/private/Authentication/Exceptions/PasswordlessTokenException.php @@ -25,5 +25,4 @@ namespace OC\Authentication\Exceptions; use Exception; class PasswordlessTokenException extends Exception { - } diff --git a/lib/private/Authentication/Exceptions/TokenPasswordExpiredException.php b/lib/private/Authentication/Exceptions/TokenPasswordExpiredException.php index b4691a7a0c4..2850d3de7e1 100644 --- a/lib/private/Authentication/Exceptions/TokenPasswordExpiredException.php +++ b/lib/private/Authentication/Exceptions/TokenPasswordExpiredException.php @@ -27,5 +27,4 @@ declare(strict_types=1); namespace OC\Authentication\Exceptions; class TokenPasswordExpiredException extends ExpiredTokenException { - } diff --git a/lib/private/Authentication/Exceptions/TwoFactorAuthRequiredException.php b/lib/private/Authentication/Exceptions/TwoFactorAuthRequiredException.php index c9c5a03e021..6db87b3516c 100644 --- a/lib/private/Authentication/Exceptions/TwoFactorAuthRequiredException.php +++ b/lib/private/Authentication/Exceptions/TwoFactorAuthRequiredException.php @@ -25,5 +25,4 @@ namespace OC\Authentication\Exceptions; use Exception; class TwoFactorAuthRequiredException extends Exception { - } diff --git a/lib/private/Authentication/Exceptions/UserAlreadyLoggedInException.php b/lib/private/Authentication/Exceptions/UserAlreadyLoggedInException.php index 9c1c2a9a441..878bf59e4e9 100644 --- a/lib/private/Authentication/Exceptions/UserAlreadyLoggedInException.php +++ b/lib/private/Authentication/Exceptions/UserAlreadyLoggedInException.php @@ -25,5 +25,4 @@ namespace OC\Authentication\Exceptions; use Exception; class UserAlreadyLoggedInException extends Exception { - } diff --git a/lib/private/Authentication/Listeners/LoginFailedListener.php b/lib/private/Authentication/Listeners/LoginFailedListener.php index 8086194eab3..d56e24cce70 100644 --- a/lib/private/Authentication/Listeners/LoginFailedListener.php +++ b/lib/private/Authentication/Listeners/LoginFailedListener.php @@ -57,9 +57,8 @@ class LoginFailedListener implements IEventListener { 'preLoginNameUsedAsUserName', ['uid' => &$uid] ); - if($this->userManager->userExists($uid)) { + if ($this->userManager->userExists($uid)) { $this->dispatcher->dispatchTyped(new LoginFailedEvent($uid)); } } - } diff --git a/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php b/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php index 5acd228b133..0ab2dcf4837 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php @@ -76,5 +76,4 @@ class RemoteWipeActivityListener implements IEventListener { ]); } } - } diff --git a/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php b/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php index 6c0ca16859b..799c4ea4cf5 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php @@ -170,5 +170,4 @@ class RemoteWipeEmailListener implements IEventListener { return $message; } - } diff --git a/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php b/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php index 4b021d67c75..831107a05cd 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php @@ -68,5 +68,4 @@ class RemoteWipeNotificationsListener implements IEventListener { ]); $this->notificationManager->notify($notification); } - } diff --git a/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php b/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php index dc0be4e2e9b..c8f2da82db6 100644 --- a/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php +++ b/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php @@ -47,5 +47,4 @@ class UserDeletedStoreCleanupListener implements IEventListener { $this->registry->deleteUserData($event->getUser()); } - } diff --git a/lib/private/Authentication/Login/ALoginCommand.php b/lib/private/Authentication/Login/ALoginCommand.php index e27b0db173e..8ad162842bf 100644 --- a/lib/private/Authentication/Login/ALoginCommand.php +++ b/lib/private/Authentication/Login/ALoginCommand.php @@ -44,5 +44,4 @@ abstract class ALoginCommand { } public abstract function process(LoginData $loginData): LoginResult; - } diff --git a/lib/private/Authentication/Login/Chain.php b/lib/private/Authentication/Login/Chain.php index c86a932d6b6..1fc94fe9637 100644 --- a/lib/private/Authentication/Login/Chain.php +++ b/lib/private/Authentication/Login/Chain.php @@ -107,5 +107,4 @@ class Chain { return $chain->process($loginData); } - } diff --git a/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php b/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php index 9f4e970c9cc..f4e1ad11dd0 100644 --- a/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php +++ b/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php @@ -48,5 +48,4 @@ class ClearLostPasswordTokensCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/CompleteLoginCommand.php b/lib/private/Authentication/Login/CompleteLoginCommand.php index 210b3ba9a88..d0cddba595c 100644 --- a/lib/private/Authentication/Login/CompleteLoginCommand.php +++ b/lib/private/Authentication/Login/CompleteLoginCommand.php @@ -47,5 +47,4 @@ class CompleteLoginCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/EmailLoginCommand.php b/lib/private/Authentication/Login/EmailLoginCommand.php index c281ddc6737..24b5a00196b 100644 --- a/lib/private/Authentication/Login/EmailLoginCommand.php +++ b/lib/private/Authentication/Login/EmailLoginCommand.php @@ -57,5 +57,4 @@ class EmailLoginCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/FinishRememberedLoginCommand.php b/lib/private/Authentication/Login/FinishRememberedLoginCommand.php index 4c4b37b0801..1d33f103fdf 100644 --- a/lib/private/Authentication/Login/FinishRememberedLoginCommand.php +++ b/lib/private/Authentication/Login/FinishRememberedLoginCommand.php @@ -43,5 +43,4 @@ class FinishRememberedLoginCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/LoggedInCheckCommand.php b/lib/private/Authentication/Login/LoggedInCheckCommand.php index 5701f2970a8..5fd1f1af4ba 100644 --- a/lib/private/Authentication/Login/LoggedInCheckCommand.php +++ b/lib/private/Authentication/Login/LoggedInCheckCommand.php @@ -59,5 +59,4 @@ class LoggedInCheckCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/LoginData.php b/lib/private/Authentication/Login/LoginData.php index ec8ebdbab46..162e0f362d8 100644 --- a/lib/private/Authentication/Login/LoginData.php +++ b/lib/private/Authentication/Login/LoginData.php @@ -117,5 +117,4 @@ class LoginData { public function isRememberLogin(): bool { return $this->rememberLogin; } - } diff --git a/lib/private/Authentication/Login/LoginResult.php b/lib/private/Authentication/Login/LoginResult.php index 273e0ee8d5c..60228307135 100644 --- a/lib/private/Authentication/Login/LoginResult.php +++ b/lib/private/Authentication/Login/LoginResult.php @@ -79,5 +79,4 @@ class LoginResult { public function getErrorMessage(): ?string { return $this->errorMessage; } - } diff --git a/lib/private/Authentication/Login/SetUserTimezoneCommand.php b/lib/private/Authentication/Login/SetUserTimezoneCommand.php index d3599880228..0029f2f1677 100644 --- a/lib/private/Authentication/Login/SetUserTimezoneCommand.php +++ b/lib/private/Authentication/Login/SetUserTimezoneCommand.php @@ -58,5 +58,4 @@ class SetUserTimezoneCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/TwoFactorCommand.php b/lib/private/Authentication/Login/TwoFactorCommand.php index 2c3d2fbf2c4..86b85c83fd0 100644 --- a/lib/private/Authentication/Login/TwoFactorCommand.php +++ b/lib/private/Authentication/Login/TwoFactorCommand.php @@ -91,5 +91,4 @@ class TwoFactorCommand extends ALoginCommand { $this->urlGenerator->linkToRoute($url, $urlParams) ); } - } diff --git a/lib/private/Authentication/Login/UidLoginCommand.php b/lib/private/Authentication/Login/UidLoginCommand.php index 76e06fb3e4f..8c9a516c735 100644 --- a/lib/private/Authentication/Login/UidLoginCommand.php +++ b/lib/private/Authentication/Login/UidLoginCommand.php @@ -53,5 +53,4 @@ class UidLoginCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php b/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php index 9e89aa086db..efaf5554c21 100644 --- a/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php +++ b/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php @@ -44,5 +44,4 @@ class UpdateLastPasswordConfirmCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/UserDisabledCheckCommand.php b/lib/private/Authentication/Login/UserDisabledCheckCommand.php index 11f2d5f3a90..e33853ef5bd 100644 --- a/lib/private/Authentication/Login/UserDisabledCheckCommand.php +++ b/lib/private/Authentication/Login/UserDisabledCheckCommand.php @@ -56,5 +56,4 @@ class UserDisabledCheckCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/WebAuthnLoginCommand.php b/lib/private/Authentication/Login/WebAuthnLoginCommand.php index d2f613c59be..6aa35d43f93 100644 --- a/lib/private/Authentication/Login/WebAuthnLoginCommand.php +++ b/lib/private/Authentication/Login/WebAuthnLoginCommand.php @@ -45,5 +45,4 @@ class WebAuthnLoginCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/LoginCredentials/Credentials.php b/lib/private/Authentication/LoginCredentials/Credentials.php index b9542aed354..e4cbdccec50 100644 --- a/lib/private/Authentication/LoginCredentials/Credentials.php +++ b/lib/private/Authentication/LoginCredentials/Credentials.php @@ -67,5 +67,4 @@ class Credentials implements ICredentials { public function getPassword() { return $this->password; } - } diff --git a/lib/private/Authentication/LoginCredentials/Store.php b/lib/private/Authentication/LoginCredentials/Store.php index a16b291f5f5..f4bedd88a18 100644 --- a/lib/private/Authentication/LoginCredentials/Store.php +++ b/lib/private/Authentication/LoginCredentials/Store.php @@ -118,5 +118,4 @@ class Store implements IStore { // If we reach this line, an exception was thrown. throw new CredentialsUnavailableException(); } - } diff --git a/lib/private/Authentication/Token/DefaultToken.php b/lib/private/Authentication/Token/DefaultToken.php index 4af42d07813..7ca05849635 100644 --- a/lib/private/Authentication/Token/DefaultToken.php +++ b/lib/private/Authentication/Token/DefaultToken.php @@ -43,7 +43,6 @@ use OCP\AppFramework\Db\Entity; * @method void setVersion(int $version) */ class DefaultToken extends Entity implements INamedToken { - const VERSION = 1; /** @var string user UID */ diff --git a/lib/private/Authentication/Token/DefaultTokenCleanupJob.php b/lib/private/Authentication/Token/DefaultTokenCleanupJob.php index 25b4aa59a92..0686f40e82f 100644 --- a/lib/private/Authentication/Token/DefaultTokenCleanupJob.php +++ b/lib/private/Authentication/Token/DefaultTokenCleanupJob.php @@ -27,11 +27,9 @@ use OC; use OC\BackgroundJob\Job; class DefaultTokenCleanupJob extends Job { - protected function run($argument) { /* @var $provider IProvider */ $provider = OC::$server->query(IProvider::class); $provider->invalidateOldTokens(); } - } diff --git a/lib/private/Authentication/Token/DefaultTokenMapper.php b/lib/private/Authentication/Token/DefaultTokenMapper.php index 3f11e02d5cd..e51033ed1df 100644 --- a/lib/private/Authentication/Token/DefaultTokenMapper.php +++ b/lib/private/Authentication/Token/DefaultTokenMapper.php @@ -36,7 +36,6 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; class DefaultTokenMapper extends QBMapper { - public function __construct(IDBConnection $db) { parent::__construct($db, 'authtoken'); } @@ -168,5 +167,4 @@ class DefaultTokenMapper extends QBMapper { ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(DefaultToken::VERSION, IQueryBuilder::PARAM_INT))); $qb->execute(); } - } diff --git a/lib/private/Authentication/Token/DefaultTokenProvider.php b/lib/private/Authentication/Token/DefaultTokenProvider.php index 05e601d78a7..3556cfd24b0 100644 --- a/lib/private/Authentication/Token/DefaultTokenProvider.php +++ b/lib/private/Authentication/Token/DefaultTokenProvider.php @@ -286,7 +286,6 @@ class DefaultTokenProvider implements IProvider { $password = $this->getPassword($token, $oldTokenId); $token->setPassword($this->encryptPassword($password, $newTokenId)); } catch (PasswordlessTokenException $e) { - } $token->setToken($this->hashToken($newTokenId)); diff --git a/lib/private/Authentication/Token/IToken.php b/lib/private/Authentication/Token/IToken.php index e2de2b5fbbd..1f7c736f86b 100644 --- a/lib/private/Authentication/Token/IToken.php +++ b/lib/private/Authentication/Token/IToken.php @@ -30,7 +30,6 @@ namespace OC\Authentication\Token; use JsonSerializable; interface IToken extends JsonSerializable { - const TEMPORARY_TOKEN = 0; const PERMANENT_TOKEN = 1; const WIPE_TOKEN = 2; diff --git a/lib/private/Authentication/Token/IWipeableToken.php b/lib/private/Authentication/Token/IWipeableToken.php index 62293e6933b..efc542faa69 100644 --- a/lib/private/Authentication/Token/IWipeableToken.php +++ b/lib/private/Authentication/Token/IWipeableToken.php @@ -33,5 +33,4 @@ interface IWipeableToken extends IToken { * Mark the token for remote wipe */ public function wipe(): void; - } diff --git a/lib/private/Authentication/Token/Manager.php b/lib/private/Authentication/Token/Manager.php index dddc675a428..073569de0cf 100644 --- a/lib/private/Authentication/Token/Manager.php +++ b/lib/private/Authentication/Token/Manager.php @@ -139,7 +139,7 @@ class Manager implements IProvider { throw $e; } catch (ExpiredTokenException $e) { throw $e; - } catch(InvalidTokenException $e) { + } catch (InvalidTokenException $e) { // No worries we try to convert it to a PublicKey Token } @@ -272,6 +272,4 @@ class Manager implements IProvider { $this->defaultTokenProvider->updatePasswords($uid, $password); $this->publicKeyTokenProvider->updatePasswords($uid, $password); } - - } diff --git a/lib/private/Authentication/Token/PublicKeyToken.php b/lib/private/Authentication/Token/PublicKeyToken.php index 221f286ae05..27eda0b6889 100644 --- a/lib/private/Authentication/Token/PublicKeyToken.php +++ b/lib/private/Authentication/Token/PublicKeyToken.php @@ -47,7 +47,6 @@ use OCP\AppFramework\Db\Entity; * @method bool getPasswordInvalid() */ class PublicKeyToken extends Entity implements INamedToken, IWipeableToken { - const VERSION = 2; /** @var string user UID */ diff --git a/lib/private/Authentication/Token/PublicKeyTokenMapper.php b/lib/private/Authentication/Token/PublicKeyTokenMapper.php index 15a161aef64..e05325fec30 100644 --- a/lib/private/Authentication/Token/PublicKeyTokenMapper.php +++ b/lib/private/Authentication/Token/PublicKeyTokenMapper.php @@ -33,7 +33,6 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; class PublicKeyTokenMapper extends QBMapper { - public function __construct(IDBConnection $db) { parent::__construct($db, 'authtoken'); } diff --git a/lib/private/Authentication/Token/RemoteWipe.php b/lib/private/Authentication/Token/RemoteWipe.php index b1fc757f744..cab68357a01 100644 --- a/lib/private/Authentication/Token/RemoteWipe.php +++ b/lib/private/Authentication/Token/RemoteWipe.php @@ -152,5 +152,4 @@ class RemoteWipe { return true; } - } diff --git a/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php b/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php index 4e8f9731d94..a5ddad47e01 100644 --- a/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php +++ b/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php @@ -35,7 +35,6 @@ use OCP\IDBConnection; * 2FA providers */ class ProviderUserAssignmentDao { - const TABLE_NAME = 'twofactor_providers'; /** @var IDBConnection */ @@ -90,7 +89,6 @@ class ProviderUserAssignmentDao { ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid))); $updateQuery->execute(); } - } public function deleteByUser(string $uid) { @@ -110,5 +108,4 @@ class ProviderUserAssignmentDao { $deleteQuery->execute(); } - } diff --git a/lib/private/Authentication/TwoFactorAuth/EnforcementState.php b/lib/private/Authentication/TwoFactorAuth/EnforcementState.php index abd0ec7f2e7..c244843454b 100644 --- a/lib/private/Authentication/TwoFactorAuth/EnforcementState.php +++ b/lib/private/Authentication/TwoFactorAuth/EnforcementState.php @@ -82,5 +82,4 @@ class EnforcementState implements JsonSerializable { 'excludedGroups' => $this->excludedGroups, ]; } - } diff --git a/lib/private/Authentication/TwoFactorAuth/Manager.php b/lib/private/Authentication/TwoFactorAuth/Manager.php index 40e6e4082e1..ec414e67938 100644 --- a/lib/private/Authentication/TwoFactorAuth/Manager.php +++ b/lib/private/Authentication/TwoFactorAuth/Manager.php @@ -46,7 +46,6 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\GenericEvent; class Manager { - const SESSION_UID_KEY = 'two_factor_auth_uid'; const SESSION_UID_DONE = 'two_factor_auth_passed'; const REMEMBER_LOGIN = 'two_factor_remember_login'; @@ -158,7 +157,6 @@ class Manager { */ private function fixMissingProviderStates(array $providerStates, array $providers, IUser $user): array { - foreach ($providers as $provider) { if (isset($providerStates[$provider->getId()])) { // All good @@ -384,5 +382,4 @@ class Manager { $this->tokenProvider->invalidateTokenById($userId, $tokenId); } } - } diff --git a/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php b/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php index 42e5def80de..b06a517ef80 100644 --- a/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php +++ b/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php @@ -110,6 +110,4 @@ class MandatoryTwoFactor { */ return true; } - - } diff --git a/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php b/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php index b287072dde3..0754679adf1 100644 --- a/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php +++ b/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php @@ -35,7 +35,6 @@ use OCP\Authentication\TwoFactorAuth\IProvider; use OCP\IUser; class ProviderLoader { - const BACKUP_CODES_APP_ID = 'twofactor_backupcodes'; /** @var IAppManager */ @@ -86,5 +85,4 @@ class ProviderLoader { OC_App::loadApp($appId); } } - } diff --git a/lib/private/Authentication/TwoFactorAuth/ProviderManager.php b/lib/private/Authentication/TwoFactorAuth/ProviderManager.php index 26c1af0ae17..4d3171e96f7 100644 --- a/lib/private/Authentication/TwoFactorAuth/ProviderManager.php +++ b/lib/private/Authentication/TwoFactorAuth/ProviderManager.php @@ -93,5 +93,4 @@ class ProviderManager { return false; } } - } diff --git a/lib/private/Authentication/TwoFactorAuth/ProviderSet.php b/lib/private/Authentication/TwoFactorAuth/ProviderSet.php index 5b5ac60fd82..c27681c6036 100644 --- a/lib/private/Authentication/TwoFactorAuth/ProviderSet.php +++ b/lib/private/Authentication/TwoFactorAuth/ProviderSet.php @@ -80,5 +80,4 @@ class ProviderSet { public function isProviderMissing(): bool { return $this->providerMissing; } - } diff --git a/lib/private/Authentication/WebAuthn/CredentialRepository.php b/lib/private/Authentication/WebAuthn/CredentialRepository.php index c57af15d2e4..da552b120bf 100644 --- a/lib/private/Authentication/WebAuthn/CredentialRepository.php +++ b/lib/private/Authentication/WebAuthn/CredentialRepository.php @@ -68,7 +68,6 @@ class CredentialRepository implements PublicKeyCredentialSourceRepository { try { $oldEntity = $this->credentialMapper->findOneByCredentialId($publicKeyCredentialSource->getPublicKeyCredentialId()); } catch (IMapperException $e) { - } if ($name === null) { @@ -90,5 +89,4 @@ class CredentialRepository implements PublicKeyCredentialSourceRepository { public function saveCredentialSource(PublicKeyCredentialSource $publicKeyCredentialSource, string $name = null): void { $this->saveAndReturnCredentialSource($publicKeyCredentialSource, $name); } - } diff --git a/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialEntity.php b/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialEntity.php index 0b27c78efbd..c9ebf8ce456 100644 --- a/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialEntity.php +++ b/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialEntity.php @@ -88,5 +88,4 @@ class PublicKeyCredentialEntity extends Entity implements JsonSerializable { 'name' => $this->getName(), ]; } - } diff --git a/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialMapper.php b/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialMapper.php index c931ccbb3f0..a78ebee3072 100644 --- a/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialMapper.php +++ b/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialMapper.php @@ -31,7 +31,6 @@ use OCP\AppFramework\Db\QBMapper; use OCP\IDBConnection; class PublicKeyCredentialMapper extends QBMapper { - public function __construct(IDBConnection $db) { parent::__construct($db, 'webauthn', PublicKeyCredentialEntity::class); } @@ -82,5 +81,4 @@ class PublicKeyCredentialMapper extends QBMapper { return $this->findEntity($qb); } - } diff --git a/lib/private/Authentication/WebAuthn/Manager.php b/lib/private/Authentication/WebAuthn/Manager.php index e33d0e48e9b..7a2e4fc6b8a 100644 --- a/lib/private/Authentication/WebAuthn/Manager.php +++ b/lib/private/Authentication/WebAuthn/Manager.php @@ -170,7 +170,7 @@ class Manager { } public function startAuthentication(string $uid, string $serverHost): PublicKeyCredentialRequestOptions { - // List of registered PublicKeyCredentialDescriptor classes associated to the user + // List of registered PublicKeyCredentialDescriptor classes associated to the user $registeredPublicKeyCredentialDescriptors = array_map(function (PublicKeyCredentialEntity $entity) { $credential = $entity->toPublicKeyCredentialSource(); return new PublicKeyCredentialDescriptor( @@ -230,7 +230,6 @@ class Manager { $request, $uid ); - } catch (\Throwable $e) { throw $e; } diff --git a/lib/private/Avatar/Avatar.php b/lib/private/Avatar/Avatar.php index 4badc8c43f5..02fc04eae36 100644 --- a/lib/private/Avatar/Avatar.php +++ b/lib/private/Avatar/Avatar.php @@ -300,7 +300,7 @@ abstract class Avatar implements IAvatar { $hash = strtolower($hash); // Already a md5 hash? - if(preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) { + if (preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) { $hash = md5($hash); } diff --git a/lib/private/Avatar/AvatarManager.php b/lib/private/Avatar/AvatarManager.php index 2a4f51f0e1c..3bb0c4077e2 100644 --- a/lib/private/Avatar/AvatarManager.php +++ b/lib/private/Avatar/AvatarManager.php @@ -114,7 +114,7 @@ class AvatarManager implements IAvatarManager { */ public function clearCachedAvatars() { $users = $this->config->getUsersForUserValue('avatar', 'generated', 'true'); - foreach($users as $userId) { + foreach ($users as $userId) { try { $folder = $this->appData->getFolder($userId); $folder->delete(); diff --git a/lib/private/Avatar/UserAvatar.php b/lib/private/Avatar/UserAvatar.php index 485e53c249d..a5da4a278fa 100644 --- a/lib/private/Avatar/UserAvatar.php +++ b/lib/private/Avatar/UserAvatar.php @@ -208,7 +208,7 @@ class UserAvatar extends Avatar { $avatar->delete(); } $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true'); - if(!$silent) { + if (!$silent) { $this->user->triggerChange('avatar', ''); } } @@ -273,7 +273,6 @@ class UserAvatar extends Avatar { if (!$data = $this->generateAvatarFromSvg($size)) { $data = $this->generateAvatar($this->getDisplayName(), $size); } - } else { $avatar = new OC_Image(); $file = $this->folder->getFile('avatar.' . $ext); @@ -289,7 +288,6 @@ class UserAvatar extends Avatar { $this->logger->error('Failed to save avatar for ' . $this->user->getUID()); throw new NotFoundException(); } - } if ($this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', null) === null) { diff --git a/lib/private/Broadcast/Events/BroadcastEvent.php b/lib/private/Broadcast/Events/BroadcastEvent.php index f5aa1d8c4b8..7d4d7017af5 100644 --- a/lib/private/Broadcast/Events/BroadcastEvent.php +++ b/lib/private/Broadcast/Events/BroadcastEvent.php @@ -57,5 +57,4 @@ class BroadcastEvent extends Event implements IBroadcastEvent { public function setBroadcasted(): void { $this->event->setBroadcasted(); } - } diff --git a/lib/private/Cache/CappedMemoryCache.php b/lib/private/Cache/CappedMemoryCache.php index 3d843abf5b8..28e08759304 100644 --- a/lib/private/Cache/CappedMemoryCache.php +++ b/lib/private/Cache/CappedMemoryCache.php @@ -30,7 +30,6 @@ use OCP\ICache; * Uses a simple FIFO expiry mechanism */ class CappedMemoryCache implements ICache, \ArrayAccess { - private $capacity; private $cache = []; diff --git a/lib/private/Calendar/Manager.php b/lib/private/Calendar/Manager.php index 3c876c79e9e..3b438dfa113 100644 --- a/lib/private/Calendar/Manager.php +++ b/lib/private/Calendar/Manager.php @@ -53,9 +53,9 @@ class Manager implements \OCP\Calendar\IManager { public function search($pattern, array $searchProperties=[], array $options=[], $limit=null, $offset=null) { $this->loadCalendars(); $result = []; - foreach($this->calendars as $calendar) { + foreach ($this->calendars as $calendar) { $r = $calendar->search($pattern, $searchProperties, $options, $limit, $offset); - foreach($r as $o) { + foreach ($r as $o) { $o['calendar-key'] = $calendar->getKey(); $result[] = $o; } @@ -132,7 +132,7 @@ class Manager implements \OCP\Calendar\IManager { * loads all calendars */ private function loadCalendars() { - foreach($this->calendarLoaders as $callable) { + foreach ($this->calendarLoaders as $callable) { $callable($this); } $this->calendarLoaders = []; diff --git a/lib/private/Calendar/Resource/Manager.php b/lib/private/Calendar/Resource/Manager.php index 0a85f271498..6ae46c9530f 100644 --- a/lib/private/Calendar/Resource/Manager.php +++ b/lib/private/Calendar/Resource/Manager.php @@ -75,7 +75,7 @@ class Manager implements \OCP\Calendar\Resource\IManager { * @since 14.0.0 */ public function getBackends():array { - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { if (isset($this->initializedBackends[$backend])) { continue; } @@ -93,7 +93,7 @@ class Manager implements \OCP\Calendar\Resource\IManager { */ public function getBackend($backendId) { $backends = $this->getBackends(); - foreach($backends as $backend) { + foreach ($backends as $backend) { if ($backend->getBackendIdentifier() === $backendId) { return $backend; } diff --git a/lib/private/Calendar/Room/Manager.php b/lib/private/Calendar/Room/Manager.php index 59406ba0c8c..6c3d02c3597 100644 --- a/lib/private/Calendar/Room/Manager.php +++ b/lib/private/Calendar/Room/Manager.php @@ -75,7 +75,7 @@ class Manager implements \OCP\Calendar\Room\IManager { * @since 14.0.0 */ public function getBackends():array { - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { if (isset($this->initializedBackends[$backend])) { continue; } @@ -93,7 +93,7 @@ class Manager implements \OCP\Calendar\Room\IManager { */ public function getBackend($backendId) { $backends = $this->getBackends(); - foreach($backends as $backend) { + foreach ($backends as $backend) { if ($backend->getBackendIdentifier() === $backendId) { return $backend; } diff --git a/lib/private/CapabilitiesManager.php b/lib/private/CapabilitiesManager.php index 8034b90567f..6a4d97ad159 100644 --- a/lib/private/CapabilitiesManager.php +++ b/lib/private/CapabilitiesManager.php @@ -55,7 +55,7 @@ class CapabilitiesManager { */ public function getCapabilities(bool $public = false) : array { $capabilities = []; - foreach($this->capabilities as $capability) { + foreach ($this->capabilities as $capability) { try { $c = $capability(); } catch (QueryException $e) { @@ -68,7 +68,7 @@ class CapabilitiesManager { } if ($c instanceof ICapability) { - if(!$public || $c instanceof IPublicCapability) { + if (!$public || $c instanceof IPublicCapability) { $capabilities = array_replace_recursive($capabilities, $c->getCapabilities()); } } else { diff --git a/lib/private/Collaboration/AutoComplete/Manager.php b/lib/private/Collaboration/AutoComplete/Manager.php index d2b490f73f5..e8d5732dec7 100644 --- a/lib/private/Collaboration/AutoComplete/Manager.php +++ b/lib/private/Collaboration/AutoComplete/Manager.php @@ -42,8 +42,8 @@ class Manager implements IManager { public function runSorters(array $sorters, array &$sortArray, array $context) { $sorterInstances = $this->getSorters(); - while($sorter = array_shift($sorters)) { - if(isset($sorterInstances[$sorter])) { + while ($sorter = array_shift($sorters)) { + if (isset($sorterInstances[$sorter])) { $sorterInstances[$sorter]->sort($sortArray, $context); } else { $this->c->getLogger()->warning('No sorter for ID "{id}", skipping', [ @@ -58,17 +58,17 @@ class Manager implements IManager { } protected function getSorters() { - if(count($this->sorterInstances) === 0) { + if (count($this->sorterInstances) === 0) { foreach ($this->sorters as $sorter) { /** @var ISorter $instance */ $instance = $this->c->resolve($sorter); - if(!$instance instanceof ISorter) { + if (!$instance instanceof ISorter) { $this->c->getLogger()->notice('Skipping sorter which is not an instance of ISorter. Class name: {class}', ['app' => 'core', 'class' => $sorter]); continue; } $sorterId = trim($instance->getId()); - if(trim($sorterId) === '') { + if (trim($sorterId) === '') { $this->c->getLogger()->notice('Skipping sorter with empty ID. Class name: {class}', ['app' => 'core', 'class' => $sorter]); continue; diff --git a/lib/private/Collaboration/Collaborators/GroupPlugin.php b/lib/private/Collaboration/Collaborators/GroupPlugin.php index 404d4da8ca2..64db97a5235 100644 --- a/lib/private/Collaboration/Collaborators/GroupPlugin.php +++ b/lib/private/Collaboration/Collaborators/GroupPlugin.php @@ -61,7 +61,9 @@ class GroupPlugin implements ISearchPlugin { $result = ['wide' => [], 'exact' => []]; $groups = $this->groupManager->search($search, $limit, $offset); - $groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups); + $groupIds = array_map(function (IGroup $group) { + return $group->getGID(); + }, $groups); if (!$this->shareeEnumeration || count($groups) < $limit) { $hasMoreResults = true; @@ -71,7 +73,9 @@ class GroupPlugin implements ISearchPlugin { if (!empty($groups) && ($this->shareWithGroupOnly || $this->shareeEnumerationInGroupOnly)) { // Intersect all the groups that match with the groups this user is a member of $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser()); - $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups); + $userGroups = array_map(function (IGroup $group) { + return $group->getGID(); + }, $userGroups); $groupIds = array_intersect($groupIds, $userGroups); } diff --git a/lib/private/Collaboration/Collaborators/LookupPlugin.php b/lib/private/Collaboration/Collaborators/LookupPlugin.php index 493c35a46d4..f0d5b92f18a 100644 --- a/lib/private/Collaboration/Collaborators/LookupPlugin.php +++ b/lib/private/Collaboration/Collaborators/LookupPlugin.php @@ -73,7 +73,7 @@ class LookupPlugin implements ISearchPlugin { } $lookupServerUrl = $this->config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com'); - if(empty($lookupServerUrl)) { + if (empty($lookupServerUrl)) { return false; } $lookupServerUrl = rtrim($lookupServerUrl, '/'); diff --git a/lib/private/Collaboration/Collaborators/MailPlugin.php b/lib/private/Collaboration/Collaborators/MailPlugin.php index bafc383f746..e387e38c6dc 100644 --- a/lib/private/Collaboration/Collaborators/MailPlugin.php +++ b/lib/private/Collaboration/Collaborators/MailPlugin.php @@ -65,7 +65,6 @@ class MailPlugin implements ISearchPlugin { $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes'; $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes'; $this->shareeEnumerationInGroupOnly = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes'; - } /** @@ -99,7 +98,7 @@ class MailPlugin implements ISearchPlugin { $emailAddress = $emailAddressData['value']; $emailAddressType = $emailAddressData['type']; } - if (isset($contact['FN'])) { + if (isset($contact['FN'])) { $displayName = $contact['FN'] . ' (' . $emailAddress . ')'; } $exactEmailMatch = strtolower($emailAddress) === $lowerSearch; @@ -179,8 +178,7 @@ class MailPlugin implements ISearchPlugin { } if ($exactEmailMatch - || isset($contact['FN']) && strtolower($contact['FN']) === $lowerSearch) - { + || isset($contact['FN']) && strtolower($contact['FN']) === $lowerSearch) { if ($exactEmailMatch) { $searchResult->markExactIdMatch($emailType); } diff --git a/lib/private/Collaboration/Collaborators/RemoteGroupPlugin.php b/lib/private/Collaboration/Collaborators/RemoteGroupPlugin.php index a922befec76..777af6093db 100644 --- a/lib/private/Collaboration/Collaborators/RemoteGroupPlugin.php +++ b/lib/private/Collaboration/Collaborators/RemoteGroupPlugin.php @@ -90,5 +90,4 @@ class RemoteGroupPlugin implements ISearchPlugin { throw new \InvalidArgumentException('Invalid Federated Cloud ID', 0, $e); } } - } diff --git a/lib/private/Collaboration/Collaborators/Search.php b/lib/private/Collaboration/Collaborators/Search.php index 9b9decfecbe..11c7f87db1d 100644 --- a/lib/private/Collaboration/Collaborators/Search.php +++ b/lib/private/Collaboration/Collaborators/Search.php @@ -56,7 +56,7 @@ class Search implements ISearch { $searchResult = $this->c->resolve(SearchResult::class); foreach ($shareTypes as $type) { - if(!isset($this->pluginList[$type])) { + if (!isset($this->pluginList[$type])) { continue; } foreach ($this->pluginList[$type] as $plugin) { @@ -79,7 +79,7 @@ class Search implements ISearch { // that the exact same email address and federated cloud id exists $emailType = new SearchResultType('emails'); $remoteType = new SearchResultType('remotes'); - if($searchResult->hasExactIdMatch($emailType) && !$searchResult->hasExactIdMatch($remoteType)) { + if ($searchResult->hasExactIdMatch($emailType) && !$searchResult->hasExactIdMatch($remoteType)) { $searchResult->unsetResult($remoteType); } elseif (!$searchResult->hasExactIdMatch($emailType) && $searchResult->hasExactIdMatch($remoteType)) { $searchResult->unsetResult($emailType); @@ -87,7 +87,7 @@ class Search implements ISearch { // if we have an exact local user match, there is no need to show the remote and email matches $userType = new SearchResultType('users'); - if($searchResult->hasExactIdMatch($userType)) { + if ($searchResult->hasExactIdMatch($userType)) { $searchResult->unsetResult($remoteType); $searchResult->unsetResult($emailType); } @@ -97,7 +97,7 @@ class Search implements ISearch { public function registerPlugin(array $pluginInfo) { $shareType = constant(Share::class . '::' . $pluginInfo['shareType']); - if($shareType === null) { + if ($shareType === null) { throw new \InvalidArgumentException('Provided ShareType is invalid'); } $this->pluginList[$shareType][] = $pluginInfo['class']; diff --git a/lib/private/Collaboration/Collaborators/SearchResult.php b/lib/private/Collaboration/Collaborators/SearchResult.php index 1ee37e65589..46d5894b6f0 100644 --- a/lib/private/Collaboration/Collaborators/SearchResult.php +++ b/lib/private/Collaboration/Collaborators/SearchResult.php @@ -28,7 +28,6 @@ use OCP\Collaboration\Collaborators\ISearchResult; use OCP\Collaboration\Collaborators\SearchResultType; class SearchResult implements ISearchResult { - protected $result = [ 'exact' => [], ]; @@ -37,13 +36,13 @@ class SearchResult implements ISearchResult { public function addResultSet(SearchResultType $type, array $matches, array $exactMatches = null) { $type = $type->getLabel(); - if(!isset($this->result[$type])) { + if (!isset($this->result[$type])) { $this->result[$type] = []; $this->result['exact'][$type] = []; } $this->result[$type] = array_merge($this->result[$type], $matches); - if(is_array($exactMatches)) { + if (is_array($exactMatches)) { $this->result['exact'][$type] = array_merge($this->result['exact'][$type], $exactMatches); } } @@ -58,12 +57,12 @@ class SearchResult implements ISearchResult { public function hasResult(SearchResultType $type, $collaboratorId) { $type = $type->getLabel(); - if(!isset($this->result[$type])) { + if (!isset($this->result[$type])) { return false; } $resultArrays = [$this->result['exact'][$type], $this->result[$type]]; - foreach($resultArrays as $resultArray) { + foreach ($resultArrays as $resultArray) { foreach ($resultArray as $result) { if ($result['value']['shareWith'] === $collaboratorId) { return true; @@ -81,7 +80,7 @@ class SearchResult implements ISearchResult { public function unsetResult(SearchResultType $type) { $type = $type->getLabel(); $this->result[$type] = []; - if(isset($this->result['exact'][$type])) { + if (isset($this->result['exact'][$type])) { $this->result['exact'][$type] = []; } } diff --git a/lib/private/Collaboration/Collaborators/UserPlugin.php b/lib/private/Collaboration/Collaborators/UserPlugin.php index 53dd0c66c7f..189ea2f8ff6 100644 --- a/lib/private/Collaboration/Collaborators/UserPlugin.php +++ b/lib/private/Collaboration/Collaborators/UserPlugin.php @@ -197,7 +197,7 @@ class UserPlugin implements ISearchPlugin { public function takeOutCurrentUser(array &$users) { $currentUser = $this->userSession->getUser(); - if(!is_null($currentUser)) { + if (!is_null($currentUser)) { if (isset($users[$currentUser->getUID()])) { unset($users[$currentUser->getUID()]); } diff --git a/lib/private/Collaboration/Resources/Collection.php b/lib/private/Collaboration/Resources/Collection.php index 827f4e6dd1f..7369b44866d 100644 --- a/lib/private/Collaboration/Resources/Collection.php +++ b/lib/private/Collaboration/Resources/Collection.php @@ -174,7 +174,6 @@ class Collection implements ICollection { } else { $this->manager->invalidateAccessCacheForCollection($this); } - } /** diff --git a/lib/private/Collaboration/Resources/Listener.php b/lib/private/Collaboration/Resources/Listener.php index 608f72ebd5d..240ec7c0649 100644 --- a/lib/private/Collaboration/Resources/Listener.php +++ b/lib/private/Collaboration/Resources/Listener.php @@ -34,7 +34,6 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\GenericEvent; class Listener { - public static function register(EventDispatcherInterface $dispatcher): void { $listener = function (GenericEvent $event) { /** @var IUser $user */ diff --git a/lib/private/Collaboration/Resources/Manager.php b/lib/private/Collaboration/Resources/Manager.php index 98cc25916fe..97213c45669 100644 --- a/lib/private/Collaboration/Resources/Manager.php +++ b/lib/private/Collaboration/Resources/Manager.php @@ -42,7 +42,6 @@ use OCP\ILogger; use OCP\IUser; class Manager implements IManager { - public const TABLE_COLLECTIONS = 'collres_collections'; public const TABLE_RESOURCES = 'collres_resources'; public const TABLE_ACCESS_CACHE = 'collres_accesscache'; diff --git a/lib/private/Command/QueueBus.php b/lib/private/Command/QueueBus.php index 275435782be..2ca8f948b69 100644 --- a/lib/private/Command/QueueBus.php +++ b/lib/private/Command/QueueBus.php @@ -56,7 +56,7 @@ class QueueBus implements IBus { if ($command instanceof ICommand) { // ensure the command can be serialized $serialized = serialize($command); - if(strlen($serialized) > 4000) { + if (strlen($serialized) > 4000) { throw new \InvalidArgumentException('Trying to push a command which serialized form can not be stored in the database (>4000 character)'); } $unserialized = unserialize($serialized); diff --git a/lib/private/Comments/Comment.php b/lib/private/Comments/Comment.php index a45b1e05cfe..2fd5f20edb8 100644 --- a/lib/private/Comments/Comment.php +++ b/lib/private/Comments/Comment.php @@ -30,7 +30,6 @@ use OCP\Comments\IllegalIDChangeException; use OCP\Comments\MessageTooLongException; class Comment implements IComment { - protected $data = [ 'id' => '', 'parentId' => '0', @@ -54,7 +53,7 @@ class Comment implements IComment { * the comments database scheme */ public function __construct(array $data = null) { - if(is_array($data)) { + if (is_array($data)) { $this->fromArray($data); } } @@ -87,12 +86,12 @@ class Comment implements IComment { * @since 9.0.0 */ public function setId($id) { - if(!is_string($id)) { + if (!is_string($id)) { throw new \InvalidArgumentException('String expected.'); } $id = trim($id); - if($this->data['id'] === '' || ($this->data['id'] !== '' && $id === '')) { + if ($this->data['id'] === '' || ($this->data['id'] !== '' && $id === '')) { $this->data['id'] = $id; return $this; } @@ -118,7 +117,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setParentId($parentId) { - if(!is_string($parentId)) { + if (!is_string($parentId)) { throw new \InvalidArgumentException('String expected.'); } $this->data['parentId'] = trim($parentId); @@ -144,7 +143,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setTopmostParentId($id) { - if(!is_string($id)) { + if (!is_string($id)) { throw new \InvalidArgumentException('String expected.'); } $this->data['topmostParentId'] = trim($id); @@ -169,7 +168,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setChildrenCount($count) { - if(!is_int($count)) { + if (!is_int($count)) { throw new \InvalidArgumentException('Integer expected.'); } $this->data['childrenCount'] = $count; @@ -196,7 +195,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setMessage($message, $maxLength = self::MAX_MESSAGE_LENGTH) { - if(!is_string($message)) { + if (!is_string($message)) { throw new \InvalidArgumentException('String expected.'); } $message = trim($message); @@ -229,7 +228,7 @@ class Comment implements IComment { */ public function getMentions() { $ok = preg_match_all("/\B(?<![^a-z0-9_\-@\.\'\s])@(\"guest\/[a-f0-9]+\"|\"[a-z0-9_\-@\.\' ]+\"|[a-z0-9_\-@\.\']+)/i", $this->getMessage(), $mentions); - if(!$ok || !isset($mentions[0]) || !is_array($mentions[0])) { + if (!$ok || !isset($mentions[0]) || !is_array($mentions[0])) { return []; } $uids = array_unique($mentions[0]); @@ -263,7 +262,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setVerb($verb) { - if(!is_string($verb) || !trim($verb)) { + if (!is_string($verb) || !trim($verb)) { throw new \InvalidArgumentException('Non-empty String expected.'); } $this->data['verb'] = trim($verb); @@ -299,7 +298,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setActor($actorType, $actorId) { - if( + if ( !is_string($actorType) || !trim($actorType) || !is_string($actorId) || $actorId === '' ) { @@ -385,7 +384,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setObject($objectType, $objectId) { - if( + if ( !is_string($objectType) || !trim($objectType) || !is_string($objectId) || trim($objectId) === '' ) { @@ -434,18 +433,18 @@ class Comment implements IComment { * @return IComment */ protected function fromArray($data) { - foreach(array_keys($data) as $key) { + foreach (array_keys($data) as $key) { // translate DB keys to internal setter names $setter = 'set' . implode('', array_map('ucfirst', explode('_', $key))); $setter = str_replace('Timestamp', 'DateTime', $setter); - if(method_exists($this, $setter)) { + if (method_exists($this, $setter)) { $this->$setter($data[$key]); } } - foreach(['actor', 'object'] as $role) { - if(isset($data[$role . '_type']) && isset($data[$role . '_id'])) { + foreach (['actor', 'object'] as $role) { + if (isset($data[$role . '_type']) && isset($data[$role . '_id'])) { $setter = 'set' . ucfirst($role); $this->$setter($data[$role . '_type'], $data[$role . '_id']); } diff --git a/lib/private/Comments/Manager.php b/lib/private/Comments/Manager.php index d04f3f965b3..a0a670817f4 100644 --- a/lib/private/Comments/Manager.php +++ b/lib/private/Comments/Manager.php @@ -747,7 +747,6 @@ class Manager implements ICommentsManager { * @return bool */ protected function insert(IComment $comment): bool { - try { $result = $this->insertQuery($comment, true); } catch (InvalidFieldNameException $e) { diff --git a/lib/private/Config.php b/lib/private/Config.php index 0c5a9b0320d..1724222f4bb 100644 --- a/lib/private/Config.php +++ b/lib/private/Config.php @@ -42,7 +42,6 @@ namespace OC; * configuration file of Nextcloud. */ class Config { - const ENV_PREFIX = 'NC_'; /** @var array Associative array ($key => $value) */ @@ -200,7 +199,7 @@ class Config { foreach ($configFiles as $file) { $fileExistsAndIsReadable = file_exists($file) && is_readable($file); $filePointer = $fileExistsAndIsReadable ? fopen($file, 'r') : false; - if($file === $this->configFilePath && + if ($file === $this->configFilePath && $filePointer === false) { // Opening the main config might not be possible, e.g. if the wrong // permissions are set (likely on a new installation) @@ -208,13 +207,13 @@ class Config { } // Try to acquire a file lock - if(!flock($filePointer, LOCK_SH)) { + if (!flock($filePointer, LOCK_SH)) { throw new \Exception(sprintf('Could not acquire a shared lock on the config file %s', $file)); } unset($CONFIG); include $file; - if(isset($CONFIG) && is_array($CONFIG)) { + if (isset($CONFIG) && is_array($CONFIG)) { $this->cache = array_merge($this->cache, $CONFIG); } @@ -246,14 +245,14 @@ class Config { chmod($this->configFilePath, 0640); // File does not exist, this can happen when doing a fresh install - if(!is_resource($filePointer)) { + if (!is_resource($filePointer)) { throw new HintException( "Can't write into config directory!", 'This can usually be fixed by giving the webserver write access to the config directory.'); } // Try to acquire a file lock - if(!flock($filePointer, LOCK_EX)) { + if (!flock($filePointer, LOCK_EX)) { throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath)); } diff --git a/lib/private/Console/Application.php b/lib/private/Console/Application.php index 00ab67f93be..94f51c2a4be 100644 --- a/lib/private/Console/Application.php +++ b/lib/private/Console/Application.php @@ -149,7 +149,7 @@ class Application { } elseif ($input->getArgument('command') !== '_completion' && $input->getArgument('command') !== 'maintenance:install') { $output->writeln("Nextcloud is not installed - only a limited number of commands are available"); } - } catch(NeedsUpdateException $e) { + } catch (NeedsUpdateException $e) { if ($input->getArgument('command') !== '_completion') { $output->writeln("Nextcloud or one of the apps require upgrade - only a limited number of commands are available"); $output->writeln("You may use your browser or the occ upgrade command to do the upgrade"); diff --git a/lib/private/Console/TimestampFormatter.php b/lib/private/Console/TimestampFormatter.php index 72e3e392e0b..7f8250a9f3d 100644 --- a/lib/private/Console/TimestampFormatter.php +++ b/lib/private/Console/TimestampFormatter.php @@ -100,7 +100,6 @@ class TimestampFormatter implements OutputFormatterInterface { * log timezone and dateformat, e.g. "2015-06-23T17:24:37+02:00" */ public function format($message) { - $timeZone = $this->config->getSystemValue('logtimezone', 'UTC'); $timeZone = $timeZone !== null ? new \DateTimeZone($timeZone) : null; diff --git a/lib/private/Contacts/ContactsMenu/ActionFactory.php b/lib/private/Contacts/ContactsMenu/ActionFactory.php index 2c216bf2592..0cdd1245b31 100644 --- a/lib/private/Contacts/ContactsMenu/ActionFactory.php +++ b/lib/private/Contacts/ContactsMenu/ActionFactory.php @@ -52,5 +52,4 @@ class ActionFactory implements IActionFactory { public function newEMailAction($icon, $name, $email) { return $this->newLinkAction($icon, $name, 'mailto:' . $email); } - } diff --git a/lib/private/Contacts/ContactsMenu/ActionProviderStore.php b/lib/private/Contacts/ContactsMenu/ActionProviderStore.php index b8ddf9258fa..5513dd06362 100644 --- a/lib/private/Contacts/ContactsMenu/ActionProviderStore.php +++ b/lib/private/Contacts/ContactsMenu/ActionProviderStore.php @@ -109,5 +109,4 @@ class ActionProviderStore { return array_merge($all, $providers); }, []); } - } diff --git a/lib/private/Contacts/ContactsMenu/Actions/LinkAction.php b/lib/private/Contacts/ContactsMenu/Actions/LinkAction.php index b1fd74e5bf9..eac169afb77 100644 --- a/lib/private/Contacts/ContactsMenu/Actions/LinkAction.php +++ b/lib/private/Contacts/ContactsMenu/Actions/LinkAction.php @@ -98,5 +98,4 @@ class LinkAction implements ILinkAction { 'hyperlink' => $this->href, ]; } - } diff --git a/lib/private/Contacts/ContactsMenu/ContactsStore.php b/lib/private/Contacts/ContactsMenu/ContactsStore.php index dfa6db61607..0542d60ad3c 100644 --- a/lib/private/Contacts/ContactsMenu/ContactsStore.php +++ b/lib/private/Contacts/ContactsMenu/ContactsStore.php @@ -137,22 +137,22 @@ class ContactsStore implements IContactsStore { } // Prevent enumerating local users - if($disallowEnumeration && $entry->getProperty('isLocalSystemBook')) { + if ($disallowEnumeration && $entry->getProperty('isLocalSystemBook')) { $filterUser = true; $mailAddresses = $entry->getEMailAddresses(); - foreach($mailAddresses as $mailAddress) { - if($mailAddress === $filter) { + foreach ($mailAddresses as $mailAddress) { + if ($mailAddress === $filter) { $filterUser = false; break; } } - if($entry->getProperty('UID') && $entry->getProperty('UID') === $filter) { + if ($entry->getProperty('UID') && $entry->getProperty('UID') === $filter) { $filterUser = false; } - if($filterUser) { + if ($filterUser) { return false; } } @@ -182,7 +182,7 @@ class ContactsStore implements IContactsStore { * @return IEntry|null */ public function findOne(IUser $user, $shareType, $shareWith) { - switch($shareType) { + switch ($shareType) { case 0: case 6: $filter = ['UID']; @@ -224,7 +224,6 @@ class ContactsStore implements IContactsStore { } else { $match = null; } - } return $match; @@ -262,5 +261,4 @@ class ContactsStore implements IContactsStore { return $entry; } - } diff --git a/lib/private/Contacts/ContactsMenu/Entry.php b/lib/private/Contacts/ContactsMenu/Entry.php index c4b590e9397..675d925134b 100644 --- a/lib/private/Contacts/ContactsMenu/Entry.php +++ b/lib/private/Contacts/ContactsMenu/Entry.php @@ -164,5 +164,4 @@ class Entry implements IEntry { 'lastMessage' => '', ]; } - } diff --git a/lib/private/Contacts/ContactsMenu/Manager.php b/lib/private/Contacts/ContactsMenu/Manager.php index ba761c5ece8..293f1366b05 100644 --- a/lib/private/Contacts/ContactsMenu/Manager.php +++ b/lib/private/Contacts/ContactsMenu/Manager.php @@ -118,5 +118,4 @@ class Manager { } } } - } diff --git a/lib/private/Contacts/ContactsMenu/Providers/EMailProvider.php b/lib/private/Contacts/ContactsMenu/Providers/EMailProvider.php index adf09065a45..bb5e64d15aa 100644 --- a/lib/private/Contacts/ContactsMenu/Providers/EMailProvider.php +++ b/lib/private/Contacts/ContactsMenu/Providers/EMailProvider.php @@ -59,5 +59,4 @@ class EMailProvider implements IProvider { $entry->addAction($action); } } - } diff --git a/lib/private/ContactsManager.php b/lib/private/ContactsManager.php index 6ccedca77b9..c28e7f6ad4b 100644 --- a/lib/private/ContactsManager.php +++ b/lib/private/ContactsManager.php @@ -45,10 +45,10 @@ namespace OC { public function search($pattern, $searchProperties = [], $options = []) { $this->loadAddressBooks(); $result = []; - foreach($this->addressBooks as $addressBook) { + foreach ($this->addressBooks as $addressBook) { $r = $addressBook->search($pattern, $searchProperties, $options); $contacts = []; - foreach($r as $c){ + foreach ($r as $c) { $c['addressbook-key'] = $addressBook->getKey(); $contacts[] = $c; } @@ -133,7 +133,7 @@ namespace OC { public function getAddressBooks() { $this->loadAddressBooks(); $result = []; - foreach($this->addressBooks as $addressBook) { + foreach ($this->addressBooks as $addressBook) { $result[$addressBook->getKey()] = $addressBook->getDisplayName(); } @@ -175,8 +175,7 @@ namespace OC { * * @param \Closure $callable */ - public function register(\Closure $callable) - { + public function register(\Closure $callable) { $this->addressBookLoaders[] = $callable; } @@ -186,8 +185,7 @@ namespace OC { * @param string $addressBookKey * @return \OCP\IAddressBook */ - protected function getAddressBook($addressBookKey) - { + protected function getAddressBook($addressBookKey) { $this->loadAddressBooks(); if (!array_key_exists($addressBookKey, $this->addressBooks)) { return null; @@ -199,9 +197,8 @@ namespace OC { /** * Load all address books registered with 'register' */ - protected function loadAddressBooks() - { - foreach($this->addressBookLoaders as $callable) { + protected function loadAddressBooks() { + foreach ($this->addressBookLoaders as $callable) { $callable($this); } $this->addressBookLoaders = []; diff --git a/lib/private/DB/Adapter.php b/lib/private/DB/Adapter.php index f93f5aaf481..0755fa14619 100644 --- a/lib/private/DB/Adapter.php +++ b/lib/private/DB/Adapter.php @@ -106,7 +106,7 @@ class Adapter { . 'FROM `' . $table . '` WHERE '; $inserts = array_values($input); - foreach($compare as $key) { + foreach ($compare as $key) { $query .= '`' . $key . '`'; if (is_null($input[$key])) { $query .= ' IS NULL AND '; @@ -136,11 +136,11 @@ class Adapter { try { $builder = $this->conn->getQueryBuilder(); $builder->insert($table); - foreach($values as $key => $value) { + foreach ($values as $key => $value) { $builder->setValue($key, $builder->createNamedParameter($value)); } return $builder->execute(); - } catch(UniqueConstraintViolationException $e) { + } catch (UniqueConstraintViolationException $e) { return 0; } } diff --git a/lib/private/DB/AdapterPgSql.php b/lib/private/DB/AdapterPgSql.php index dd9c7dc9680..7457ab9a77d 100644 --- a/lib/private/DB/AdapterPgSql.php +++ b/lib/private/DB/AdapterPgSql.php @@ -44,7 +44,7 @@ class AdapterPgSql extends Adapter { * @suppress SqlInjectionChecker */ public function insertIgnoreConflict(string $table,array $values) : int { - if($this->isPre9_5CompatMode() === true) { + if ($this->isPre9_5CompatMode() === true) { return parent::insertIgnoreConflict($table, $values); } @@ -60,7 +60,7 @@ class AdapterPgSql extends Adapter { } protected function isPre9_5CompatMode(): bool { - if($this->compatModePre9_5 !== null) { + if ($this->compatModePre9_5 !== null) { return $this->compatModePre9_5; } diff --git a/lib/private/DB/AdapterSqlite.php b/lib/private/DB/AdapterSqlite.php index 2d8715e90f5..66c3aca1d9c 100644 --- a/lib/private/DB/AdapterSqlite.php +++ b/lib/private/DB/AdapterSqlite.php @@ -74,7 +74,7 @@ class AdapterSqlite extends Adapter { . " WHERE NOT EXISTS (SELECT 1 FROM `$table` WHERE "; $inserts = array_values($input); - foreach($compare as $key) { + foreach ($compare as $key) { $query .= '`' . $key . '`'; if (is_null($input[$key])) { $query .= ' IS NULL AND '; diff --git a/lib/private/DB/Connection.php b/lib/private/DB/Connection.php index 15c0272915a..3b24703d434 100644 --- a/lib/private/DB/Connection.php +++ b/lib/private/DB/Connection.php @@ -139,8 +139,7 @@ class Connection extends ReconnectWrapper implements IDBConnection { * @throws \Exception */ public function __construct(array $params, Driver $driver, Configuration $config = null, - EventManager $eventManager = null) - { + EventManager $eventManager = null) { if (!isset($params['adapter'])) { throw new \Exception('adapter not set'); } @@ -189,8 +188,7 @@ class Connection extends ReconnectWrapper implements IDBConnection { * * @throws \Doctrine\DBAL\DBALException */ - public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null) - { + public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null) { $query = $this->replaceTablePrefix($query); $query = $this->adapter->fixupStatement($query); return parent::executeQuery($query, $params, $types, $qcp); @@ -210,8 +208,7 @@ class Connection extends ReconnectWrapper implements IDBConnection { * * @throws \Doctrine\DBAL\DBALException */ - public function executeUpdate($query, array $params = [], array $types = []) - { + public function executeUpdate($query, array $params = [], array $types = []) { $query = $this->replaceTablePrefix($query); $query = $this->adapter->fixupStatement($query); return parent::executeUpdate($query, $params, $types); @@ -372,7 +369,7 @@ class Connection extends ReconnectWrapper implements IDBConnection { public function dropTable($table) { $table = $this->tablePrefix . trim($table); $schema = $this->getSchemaManager(); - if($schema->tablesExist([$table])) { + if ($schema->tablesExist([$table])) { $schema->dropTable($table); } } diff --git a/lib/private/DB/MDB2SchemaReader.php b/lib/private/DB/MDB2SchemaReader.php index 66a45fb5fc5..b371e1a16b2 100644 --- a/lib/private/DB/MDB2SchemaReader.php +++ b/lib/private/DB/MDB2SchemaReader.php @@ -344,5 +344,4 @@ class MDB2SchemaReader { } return (bool)$result; } - } diff --git a/lib/private/DB/MDB2SchemaWriter.php b/lib/private/DB/MDB2SchemaWriter.php index cccab28f78e..3cabff9d8f1 100644 --- a/lib/private/DB/MDB2SchemaWriter.php +++ b/lib/private/DB/MDB2SchemaWriter.php @@ -43,7 +43,7 @@ class MDB2SchemaWriter { $xml->addChild('name', $config->getSystemValue('dbname', 'owncloud')); $xml->addChild('create', 'true'); $xml->addChild('overwrite', 'false'); - if($config->getSystemValue('dbtype', 'sqlite') === 'mysql' && $config->getSystemValue('mysql.utf8mb4', false)) { + if ($config->getSystemValue('dbtype', 'sqlite') === 'mysql' && $config->getSystemValue('mysql.utf8mb4', false)) { $xml->addChild('charset', 'utf8mb4'); } else { $xml->addChild('charset', 'utf8'); @@ -71,13 +71,13 @@ class MDB2SchemaWriter { private static function saveTable($table, $xml) { $xml->addChild('name', $table->getName()); $declaration = $xml->addChild('declaration'); - foreach($table->getColumns() as $column) { + foreach ($table->getColumns() as $column) { self::saveColumn($column, $declaration->addChild('field')); } - foreach($table->getIndexes() as $index) { + foreach ($table->getIndexes() as $index) { if ($index->getName() == 'PRIMARY') { $autoincrement = false; - foreach($index->getColumns() as $column) { + foreach ($index->getColumns() as $column) { if ($table->getColumn($column)->getAutoincrement()) { $autoincrement = true; } @@ -96,7 +96,7 @@ class MDB2SchemaWriter { */ private static function saveColumn($column, $xml) { $xml->addChild('name', $column->getName()); - switch($column->getType()) { + switch ($column->getType()) { case 'SmallInt': case 'Integer': case 'BigInt': @@ -116,8 +116,7 @@ class MDB2SchemaWriter { $length = '4'; if ($column->getType() == 'SmallInt') { $length = '2'; - } - elseif ($column->getType() == 'BigInt') { + } elseif ($column->getType() == 'BigInt') { $length = '8'; } $xml->addChild('length', $length); @@ -165,15 +164,13 @@ class MDB2SchemaWriter { $xml->addChild('name', $index->getName()); if ($index->isPrimary()) { $xml->addChild('primary', 'true'); - } - elseif ($index->isUnique()) { + } elseif ($index->isUnique()) { $xml->addChild('unique', 'true'); } - foreach($index->getColumns() as $column) { + foreach ($index->getColumns() as $column) { $field = $xml->addChild('field'); $field->addChild('name', $column); $field->addChild('sorting', 'ascending'); - } } diff --git a/lib/private/DB/MigrationService.php b/lib/private/DB/MigrationService.php index 0104c1be367..18993cadd50 100644 --- a/lib/private/DB/MigrationService.php +++ b/lib/private/DB/MigrationService.php @@ -159,7 +159,6 @@ class MigrationService { // Recreate the schema after the table was dropped. $schema = new SchemaWrapper($this->connection); - } catch (SchemaException $e) { // Table not found, no need to panic, we will create it. } @@ -329,7 +328,7 @@ class MigrationService { * @return mixed|null|string */ public function getMigration($alias) { - switch($alias) { + switch ($alias) { case 'current': return $this->getCurrentVersion(); case 'next': diff --git a/lib/private/DB/Migrator.php b/lib/private/DB/Migrator.php index bda0720b3bb..2ea365ab294 100644 --- a/lib/private/DB/Migrator.php +++ b/lib/private/DB/Migrator.php @@ -302,14 +302,14 @@ class Migrator { if ($this->noEmit) { return; } - if(is_null($this->dispatcher)) { + if (is_null($this->dispatcher)) { return; } $this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max])); } private function emitCheckStep($tableName, $step, $max) { - if(is_null($this->dispatcher)) { + if (is_null($this->dispatcher)) { return; } $this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max])); diff --git a/lib/private/DB/MissingColumnInformation.php b/lib/private/DB/MissingColumnInformation.php index bcf585848fd..d1c81c2e199 100644 --- a/lib/private/DB/MissingColumnInformation.php +++ b/lib/private/DB/MissingColumnInformation.php @@ -27,7 +27,6 @@ declare(strict_types=1); namespace OC\DB; class MissingColumnInformation { - private $listOfMissingColumns = []; public function addHintForMissingColumn(string $tableName, string $columnName): void { diff --git a/lib/private/DB/MissingIndexInformation.php b/lib/private/DB/MissingIndexInformation.php index ae8be7934d9..04853dcac2d 100644 --- a/lib/private/DB/MissingIndexInformation.php +++ b/lib/private/DB/MissingIndexInformation.php @@ -28,7 +28,6 @@ declare(strict_types=1); namespace OC\DB; class MissingIndexInformation { - private $listOfMissingIndexes = []; public function addHintForMissingSubject(string $tableName, string $indexName) { diff --git a/lib/private/DB/MySQLMigrator.php b/lib/private/DB/MySQLMigrator.php index fe56a9563e2..58c54683a3a 100644 --- a/lib/private/DB/MySQLMigrator.php +++ b/lib/private/DB/MySQLMigrator.php @@ -53,25 +53,24 @@ class MySQLMigrator extends Migrator { return $schemaDiff; } - /** - * Speed up migration test by disabling autocommit and unique indexes check - * - * @param \Doctrine\DBAL\Schema\Table $table - * @throws \OC\DB\MigrationException - */ - protected function checkTableMigrate(Table $table) { - $this->connection->exec('SET autocommit=0'); - $this->connection->exec('SET unique_checks=0'); + /** + * Speed up migration test by disabling autocommit and unique indexes check + * + * @param \Doctrine\DBAL\Schema\Table $table + * @throws \OC\DB\MigrationException + */ + protected function checkTableMigrate(Table $table) { + $this->connection->exec('SET autocommit=0'); + $this->connection->exec('SET unique_checks=0'); - try { - parent::checkTableMigrate($table); - } catch (\Exception $e) { - $this->connection->exec('SET unique_checks=1'); - $this->connection->exec('SET autocommit=1'); - throw new MigrationException($table->getName(), $e->getMessage()); - } - $this->connection->exec('SET unique_checks=1'); - $this->connection->exec('SET autocommit=1'); + try { + parent::checkTableMigrate($table); + } catch (\Exception $e) { + $this->connection->exec('SET unique_checks=1'); + $this->connection->exec('SET autocommit=1'); + throw new MigrationException($table->getName(), $e->getMessage()); } - + $this->connection->exec('SET unique_checks=1'); + $this->connection->exec('SET autocommit=1'); + } } diff --git a/lib/private/DB/OCSqlitePlatform.php b/lib/private/DB/OCSqlitePlatform.php index 5649b14d233..be33629e885 100644 --- a/lib/private/DB/OCSqlitePlatform.php +++ b/lib/private/DB/OCSqlitePlatform.php @@ -23,5 +23,4 @@ namespace OC\DB; class OCSqlitePlatform extends \Doctrine\DBAL\Platforms\SqlitePlatform { - } diff --git a/lib/private/DB/OracleConnection.php b/lib/private/DB/OracleConnection.php index 93a52d1772d..b53ee850149 100644 --- a/lib/private/DB/OracleConnection.php +++ b/lib/private/DB/OracleConnection.php @@ -34,7 +34,7 @@ class OracleConnection extends Connection { private function quoteKeys(array $data) { $return = []; $c = $this->getDatabasePlatform()->getIdentifierQuoteCharacter(); - foreach($data as $key => $value) { + foreach ($data as $key => $value) { if ($key[0] !== $c) { $return[$this->quoteIdentifier($key)] = $value; } else { @@ -87,7 +87,7 @@ class OracleConnection extends Connection { $table = $this->tablePrefix . trim($table); $table = $this->quoteIdentifier($table); $schema = $this->getSchemaManager(); - if($schema->tablesExist([$table])) { + if ($schema->tablesExist([$table])) { $schema->dropTable($table); } } diff --git a/lib/private/DB/OracleMigrator.php b/lib/private/DB/OracleMigrator.php index 86d1f71c2b7..8c8a91f9b1b 100644 --- a/lib/private/DB/OracleMigrator.php +++ b/lib/private/DB/OracleMigrator.php @@ -228,5 +228,4 @@ class OracleMigrator extends Migrator { protected function getFilterExpression() { return '/^"' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/'; } - } diff --git a/lib/private/DB/QueryBuilder/CompositeExpression.php b/lib/private/DB/QueryBuilder/CompositeExpression.php index b6546f3c806..512343662ad 100644 --- a/lib/private/DB/QueryBuilder/CompositeExpression.php +++ b/lib/private/DB/QueryBuilder/CompositeExpression.php @@ -87,8 +87,7 @@ class CompositeExpression implements ICompositeExpression, \Countable { * * @return string */ - public function __toString() - { + public function __toString() { return (string) $this->compositeExpression; } } diff --git a/lib/private/DB/QueryBuilder/ExpressionBuilder/MySqlExpressionBuilder.php b/lib/private/DB/QueryBuilder/ExpressionBuilder/MySqlExpressionBuilder.php index e7df321b102..899f9277439 100644 --- a/lib/private/DB/QueryBuilder/ExpressionBuilder/MySqlExpressionBuilder.php +++ b/lib/private/DB/QueryBuilder/ExpressionBuilder/MySqlExpressionBuilder.php @@ -52,5 +52,4 @@ class MySqlExpressionBuilder extends ExpressionBuilder { $y = $this->helper->quoteColumnName($y); return $this->expressionBuilder->comparison($x, ' COLLATE ' . $this->charset . '_general_ci LIKE', $y); } - } diff --git a/lib/private/DB/QueryBuilder/ExpressionBuilder/PgSqlExpressionBuilder.php b/lib/private/DB/QueryBuilder/ExpressionBuilder/PgSqlExpressionBuilder.php index fbf76da8690..141a93ff75a 100644 --- a/lib/private/DB/QueryBuilder/ExpressionBuilder/PgSqlExpressionBuilder.php +++ b/lib/private/DB/QueryBuilder/ExpressionBuilder/PgSqlExpressionBuilder.php @@ -55,5 +55,4 @@ class PgSqlExpressionBuilder extends ExpressionBuilder { $y = $this->helper->quoteColumnName($y); return $this->expressionBuilder->comparison($x, 'ILIKE', $y); } - } diff --git a/lib/private/DB/QueryBuilder/FunctionBuilder/SqliteFunctionBuilder.php b/lib/private/DB/QueryBuilder/FunctionBuilder/SqliteFunctionBuilder.php index 774769bfdbb..6d8e947c407 100644 --- a/lib/private/DB/QueryBuilder/FunctionBuilder/SqliteFunctionBuilder.php +++ b/lib/private/DB/QueryBuilder/FunctionBuilder/SqliteFunctionBuilder.php @@ -38,5 +38,4 @@ class SqliteFunctionBuilder extends FunctionBuilder { public function least($x, $y) { return new QueryFunction('MIN(' . $this->helper->quoteColumnName($x) . ', ' . $this->helper->quoteColumnName($y) . ')'); } - } diff --git a/lib/private/DB/QueryBuilder/Literal.php b/lib/private/DB/QueryBuilder/Literal.php index f2e169e7faf..8c8114209ff 100644 --- a/lib/private/DB/QueryBuilder/Literal.php +++ b/lib/private/DB/QueryBuilder/Literal.php @@ -24,7 +24,7 @@ namespace OC\DB\QueryBuilder; use OCP\DB\QueryBuilder\ILiteral; -class Literal implements ILiteral{ +class Literal implements ILiteral { /** @var mixed */ protected $literal; diff --git a/lib/private/DB/QueryBuilder/QueryBuilder.php b/lib/private/DB/QueryBuilder/QueryBuilder.php index 4845b8b1aa4..a2941950d5c 100644 --- a/lib/private/DB/QueryBuilder/QueryBuilder.php +++ b/lib/private/DB/QueryBuilder/QueryBuilder.php @@ -413,7 +413,6 @@ class QueryBuilder implements IQueryBuilder { * @return $this This QueryBuilder instance. */ public function selectAlias($select, $alias) { - $this->queryBuilder->addSelect( $this->helper->quoteColumnName($select) . ' AS ' . $this->helper->quoteColumnName($alias) ); @@ -435,7 +434,6 @@ class QueryBuilder implements IQueryBuilder { * @return $this This QueryBuilder instance. */ public function selectDistinct($select) { - $this->queryBuilder->addSelect( 'DISTINCT ' . $this->helper->quoteColumnName($select) ); diff --git a/lib/private/Dashboard/DashboardManager.php b/lib/private/Dashboard/DashboardManager.php index 6491779bce7..4501e3cc544 100644 --- a/lib/private/Dashboard/DashboardManager.php +++ b/lib/private/Dashboard/DashboardManager.php @@ -137,5 +137,4 @@ class DashboardManager implements IDashboardManager { return $this->eventsService; } - } diff --git a/lib/private/Diagnostics/EventLogger.php b/lib/private/Diagnostics/EventLogger.php index 0c058c30798..eccdd037f95 100644 --- a/lib/private/Diagnostics/EventLogger.php +++ b/lib/private/Diagnostics/EventLogger.php @@ -41,7 +41,7 @@ class EventLogger implements IEventLogger { * @inheritdoc */ public function start($id, $description) { - if ($this->activated){ + if ($this->activated) { $this->events[$id] = new Event($id, $description, microtime(true)); } } diff --git a/lib/private/DirectEditing/Manager.php b/lib/private/DirectEditing/Manager.php index d2c927360b6..c3098fb1a97 100644 --- a/lib/private/DirectEditing/Manager.php +++ b/lib/private/DirectEditing/Manager.php @@ -49,7 +49,6 @@ use function array_key_exists; use function in_array; class Manager implements IManager { - private const TOKEN_CLEANUP_TIME = 12 * 60 * 60 ; public const TABLE_TOKENS = 'direct_edit'; @@ -172,7 +171,6 @@ class Manager implements IManager { } $editor = $this->getEditor($tokenObject->getEditor()); $this->accessToken($token); - } catch (\Throwable $throwable) { $this->invalidateToken($token); return new NotFoundResponse(); @@ -277,5 +275,4 @@ class Manager implements IManager { } return $files[0]; } - } diff --git a/lib/private/DirectEditing/Token.php b/lib/private/DirectEditing/Token.php index 1c0b99b757d..eb98f3c7123 100644 --- a/lib/private/DirectEditing/Token.php +++ b/lib/private/DirectEditing/Token.php @@ -71,5 +71,4 @@ class Token implements IToken { public function getUser(): string { return $this->data['user_id']; } - } diff --git a/lib/private/Encryption/DecryptAll.php b/lib/private/Encryption/DecryptAll.php index 3f6e4131d64..19bd2f81378 100644 --- a/lib/private/Encryption/DecryptAll.php +++ b/lib/private/Encryption/DecryptAll.php @@ -83,7 +83,6 @@ class DecryptAll { * @throws \Exception */ public function decryptAll(InputInterface $input, OutputInterface $output, $user = '') { - $this->input = $input; $this->output = $output; @@ -147,12 +146,10 @@ class DecryptAll { * @param string $user which users files should be decrypted, default = all users */ protected function decryptAllUsersFiles($user = '') { - $this->output->writeln("\n"); $userList = []; if ($user === '') { - $fetchUsersProgress = new ProgressBar($this->output); $fetchUsersProgress->setFormat(" %message% \n [%bar%]"); $fetchUsersProgress->start(); @@ -197,7 +194,6 @@ class DecryptAll { $progress->finish(); $this->output->writeln("\n\n"); - } /** @@ -208,7 +204,6 @@ class DecryptAll { * @param string $userCount */ protected function decryptUsersFiles($uid, ProgressBar $progress, $userCount) { - $this->setupUserFS($uid); $directories = []; $directories[] = '/' . $uid . '/files'; @@ -217,7 +212,7 @@ class DecryptAll { $content = $this->rootView->getDirectoryContent($root); foreach ($content as $file) { // only decrypt files owned by the user - if($file->getStorage()->instanceOfStorage('OCA\Files_Sharing\SharedStorage')) { + if ($file->getStorage()->instanceOfStorage('OCA\Files_Sharing\SharedStorage')) { continue; } $path = $root . '/' . $file['name']; @@ -299,5 +294,4 @@ class DecryptAll { \OC_Util::tearDownFS(); \OC_Util::setupFS($uid); } - } diff --git a/lib/private/Encryption/EncryptionWrapper.php b/lib/private/Encryption/EncryptionWrapper.php index 6389e996c1d..edbdc692b45 100644 --- a/lib/private/Encryption/EncryptionWrapper.php +++ b/lib/private/Encryption/EncryptionWrapper.php @@ -82,7 +82,6 @@ class EncryptionWrapper { ]; if (!$storage->instanceOfStorage(Storage\IDisableEncryptionStorage::class)) { - $user = \OC::$server->getUserSession()->getUser(); $mountManager = Filesystem::getMountManager(); $uid = $user ? $user->getUID() : null; @@ -119,5 +118,4 @@ class EncryptionWrapper { return $storage; } } - } diff --git a/lib/private/Encryption/Exceptions/DecryptionFailedException.php b/lib/private/Encryption/Exceptions/DecryptionFailedException.php index 5542082bf4d..048732d62a9 100644 --- a/lib/private/Encryption/Exceptions/DecryptionFailedException.php +++ b/lib/private/Encryption/Exceptions/DecryptionFailedException.php @@ -26,5 +26,4 @@ namespace OC\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; class DecryptionFailedException extends GenericEncryptionException { - } diff --git a/lib/private/Encryption/Exceptions/EmptyEncryptionDataException.php b/lib/private/Encryption/Exceptions/EmptyEncryptionDataException.php index dd976b22bda..7a3be2a01bd 100644 --- a/lib/private/Encryption/Exceptions/EmptyEncryptionDataException.php +++ b/lib/private/Encryption/Exceptions/EmptyEncryptionDataException.php @@ -25,6 +25,5 @@ namespace OC\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; -class EmptyEncryptionDataException extends GenericEncryptionException{ - +class EmptyEncryptionDataException extends GenericEncryptionException { } diff --git a/lib/private/Encryption/Exceptions/EncryptionFailedException.php b/lib/private/Encryption/Exceptions/EncryptionFailedException.php index 2b1672c2cb6..581d8fb7b56 100644 --- a/lib/private/Encryption/Exceptions/EncryptionFailedException.php +++ b/lib/private/Encryption/Exceptions/EncryptionFailedException.php @@ -25,6 +25,5 @@ namespace OC\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; -class EncryptionFailedException extends GenericEncryptionException{ - +class EncryptionFailedException extends GenericEncryptionException { } diff --git a/lib/private/Encryption/Exceptions/EncryptionHeaderToLargeException.php b/lib/private/Encryption/Exceptions/EncryptionHeaderToLargeException.php index 3a9b8d6d33d..c44ea9d7db0 100644 --- a/lib/private/Encryption/Exceptions/EncryptionHeaderToLargeException.php +++ b/lib/private/Encryption/Exceptions/EncryptionHeaderToLargeException.php @@ -26,9 +26,7 @@ namespace OC\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; class EncryptionHeaderToLargeException extends GenericEncryptionException { - public function __construct() { parent::__construct('max header size exceeded'); } - } diff --git a/lib/private/Encryption/Exceptions/ModuleAlreadyExistsException.php b/lib/private/Encryption/Exceptions/ModuleAlreadyExistsException.php index c9da35d9c5d..824dce48007 100644 --- a/lib/private/Encryption/Exceptions/ModuleAlreadyExistsException.php +++ b/lib/private/Encryption/Exceptions/ModuleAlreadyExistsException.php @@ -34,5 +34,4 @@ class ModuleAlreadyExistsException extends GenericEncryptionException { public function __construct($id, $name) { parent::__construct('Id "' . $id . '" already used by encryption module "' . $name . '"'); } - } diff --git a/lib/private/Encryption/Exceptions/ModuleDoesNotExistsException.php b/lib/private/Encryption/Exceptions/ModuleDoesNotExistsException.php index 841ead4ac16..24192e6e8d6 100644 --- a/lib/private/Encryption/Exceptions/ModuleDoesNotExistsException.php +++ b/lib/private/Encryption/Exceptions/ModuleDoesNotExistsException.php @@ -26,5 +26,4 @@ namespace OC\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; class ModuleDoesNotExistsException extends GenericEncryptionException { - } diff --git a/lib/private/Encryption/Exceptions/UnknownCipherException.php b/lib/private/Encryption/Exceptions/UnknownCipherException.php index eb16f9c2fbc..7a8bd76d936 100644 --- a/lib/private/Encryption/Exceptions/UnknownCipherException.php +++ b/lib/private/Encryption/Exceptions/UnknownCipherException.php @@ -26,5 +26,4 @@ namespace OC\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; class UnknownCipherException extends GenericEncryptionException { - } diff --git a/lib/private/Encryption/File.php b/lib/private/Encryption/File.php index 578fdeea5e6..13879c02cdc 100644 --- a/lib/private/Encryption/File.php +++ b/lib/private/Encryption/File.php @@ -124,5 +124,4 @@ class File implements \OCP\Encryption\IFile { return ['users' => $uniqueUserIds, 'public' => $public]; } - } diff --git a/lib/private/Encryption/Keys/Storage.php b/lib/private/Encryption/Keys/Storage.php index f71017bc4aa..2030f26f8f5 100644 --- a/lib/private/Encryption/Keys/Storage.php +++ b/lib/private/Encryption/Keys/Storage.php @@ -188,7 +188,6 @@ class Storage implements IStorage { * @return string */ protected function constructUserKeyPath($encryptionModuleId, $keyId, $uid) { - if ($uid === null) { $path = $this->root_dir . '/' . $this->encryption_base_dir . '/' . $encryptionModuleId . '/' . $keyId; } else { @@ -206,7 +205,6 @@ class Storage implements IStorage { * @return string */ private function getKey($path) { - $key = ''; if ($this->view->file_exists($path)) { @@ -250,7 +248,6 @@ class Storage implements IStorage { * @return string */ private function getFileKeyDir($encryptionModuleId, $path) { - list($owner, $filename) = $this->util->getUidAndFilename($path); // in case of system wide mount points the keys are stored directly in the data directory @@ -271,7 +268,6 @@ class Storage implements IStorage { * @return boolean */ public function renameKeys($source, $target) { - $sourcePath = $this->getPathToKeys($source); $targetPath = $this->getPathToKeys($target); @@ -294,7 +290,6 @@ class Storage implements IStorage { * @return boolean */ public function copyKeys($source, $target) { - $sourcePath = $this->getPathToKeys($source); $targetPath = $this->getPathToKeys($target); @@ -375,5 +370,4 @@ class Storage implements IStorage { } } } - } diff --git a/lib/private/Encryption/Manager.php b/lib/private/Encryption/Manager.php index 52fc23de947..f160a16a995 100644 --- a/lib/private/Encryption/Manager.php +++ b/lib/private/Encryption/Manager.php @@ -84,7 +84,6 @@ class Manager implements IManager { * @return bool true if enabled, false if not */ public function isEnabled() { - $installed = $this->config->getSystemValue('installed', false); if (!$installed) { return false; @@ -101,7 +100,6 @@ class Manager implements IManager { * @throws ServiceUnavailableException */ public function isReady() { - if ($this->isKeyStorageReady() === false) { throw new ServiceUnavailableException('Key Storage is not ready'); } @@ -137,7 +135,6 @@ class Manager implements IManager { * @throws Exceptions\ModuleAlreadyExistsException */ public function registerEncryptionModule($id, $displayName, callable $callback) { - if (isset($this->encryptionModules[$id])) { throw new Exceptions\ModuleAlreadyExistsException($id, $displayName); } @@ -213,7 +210,6 @@ class Manager implements IManager { $message = 'No default encryption module defined'; throw new Exceptions\ModuleDoesNotExistsException($message); } - } /** @@ -260,7 +256,6 @@ class Manager implements IManager { * @return bool */ protected function isKeyStorageReady() { - $rootDir = $this->util->getKeyStorageRoot(); // the default root is always valid @@ -275,6 +270,4 @@ class Manager implements IManager { return false; } - - } diff --git a/lib/private/Encryption/Update.php b/lib/private/Encryption/Update.php index f5128abd0b0..beb76a223b7 100644 --- a/lib/private/Encryption/Update.php +++ b/lib/private/Encryption/Update.php @@ -41,7 +41,7 @@ class Update { /** @var \OC\Encryption\Util */ protected $util; - /** @var \OC\Files\Mount\Manager */ + /** @var \OC\Files\Mount\Manager */ protected $mountManager; /** @var \OC\Encryption\Manager */ @@ -70,7 +70,6 @@ class Update { File $file, $uid ) { - $this->view = $view; $this->util = $util; $this->mountManager = $mountManager; @@ -133,13 +132,13 @@ class Update { public function postRename($params) { $source = $params['oldpath']; $target = $params['newpath']; - if( + if ( $this->encryptionManager->isEnabled() && dirname($source) !== dirname($target) ) { - list($owner, $ownerPath) = $this->getOwnerPath($target); - $absPath = '/' . $owner . '/files/' . $ownerPath; - $this->update($absPath); + list($owner, $ownerPath) = $this->getOwnerPath($target); + $absPath = '/' . $owner . '/files/' . $ownerPath; + $this->update($absPath); } } @@ -169,7 +168,6 @@ class Update { * @throws Exceptions\ModuleDoesNotExistsException */ public function update($path) { - $encryptionModule = $this->encryptionManager->getEncryptionModule(); // if the encryption module doesn't encrypt the files on a per-user basis @@ -192,5 +190,4 @@ class Update { $encryptionModule->update($file, $this->uid, $usersSharing); } } - } diff --git a/lib/private/Encryption/Util.php b/lib/private/Encryption/Util.php index 937a77bca7a..a5414a66796 100644 --- a/lib/private/Encryption/Util.php +++ b/lib/private/Encryption/Util.php @@ -38,7 +38,6 @@ use OCP\IConfig; use OCP\IUser; class Util { - const HEADER_START = 'HBEGIN'; const HEADER_END = 'HEND'; const HEADER_PADDING_CHAR = '-'; @@ -89,7 +88,6 @@ class Util { \OC\User\Manager $userManager, \OC\Group\Manager $groupManager, IConfig $config) { - $this->ocHeaderKeys = [ self::HEADER_ENCRYPTION_MODULE_KEY ]; @@ -179,7 +177,6 @@ class Util { $result[] = $c->getPath(); } } - } return $result; @@ -226,7 +223,6 @@ class Util { * @throws \BadMethodCallException */ public function getUidAndFilename($path) { - $parts = explode('/', $path); $uid = ''; if (count($parts) > 2) { @@ -241,7 +237,6 @@ class Util { $ownerPath = implode('/', array_slice($parts, 2)); return [$uid, Filesystem::normalizePath($ownerPath)]; - } /** @@ -254,18 +249,16 @@ class Util { $extension = pathinfo($path, PATHINFO_EXTENSION); if ($extension === 'part') { - $newLength = strlen($path) - 5; // 5 = strlen(".part") $fPath = substr($path, 0, $newLength); // if path also contains a transaction id, we remove it too $extension = pathinfo($fPath, PATHINFO_EXTENSION); - if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId") + if (substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId") $newLength = strlen($fPath) - strlen($extension) -1; $fPath = substr($fPath, 0, $newLength); } return $fPath; - } else { return $path; } @@ -372,7 +365,6 @@ class Util { // detect user specific folders if ($this->userManager->userExists($root[1]) && in_array($root[2], $this->excludedPaths)) { - return true; } } @@ -408,5 +400,4 @@ class Util { public function getKeyStorageRoot() { return $this->config->getAppValue('core', 'encryption_key_storage_root', ''); } - } diff --git a/lib/private/EventDispatcher/EventDispatcher.php b/lib/private/EventDispatcher/EventDispatcher.php index 91b3e078b25..b81b4741306 100644 --- a/lib/private/EventDispatcher/EventDispatcher.php +++ b/lib/private/EventDispatcher/EventDispatcher.php @@ -104,5 +104,4 @@ class EventDispatcher implements IEventDispatcher { public function getSymfonyDispatcher(): SymfonyDispatcher { return $this->dispatcher; } - } diff --git a/lib/private/EventDispatcher/ServiceEventListener.php b/lib/private/EventDispatcher/ServiceEventListener.php index b10e3d534d6..a648884d6f7 100644 --- a/lib/private/EventDispatcher/ServiceEventListener.php +++ b/lib/private/EventDispatcher/ServiceEventListener.php @@ -75,5 +75,4 @@ final class ServiceEventListener { $this->service->handle($event); } - } diff --git a/lib/private/EventDispatcher/SymfonyAdapter.php b/lib/private/EventDispatcher/SymfonyAdapter.php index 4d473854962..b1a39a79131 100644 --- a/lib/private/EventDispatcher/SymfonyAdapter.php +++ b/lib/private/EventDispatcher/SymfonyAdapter.php @@ -147,5 +147,4 @@ class SymfonyAdapter implements EventDispatcherInterface { public function hasListeners($eventName = null) { return $this->eventDispatcher->getSymfonyDispatcher()->hasListeners($eventName); } - } diff --git a/lib/private/Federation/CloudFederationNotification.php b/lib/private/Federation/CloudFederationNotification.php index c8ec13e1954..ad1d689dcd0 100644 --- a/lib/private/Federation/CloudFederationNotification.php +++ b/lib/private/Federation/CloudFederationNotification.php @@ -33,7 +33,6 @@ use OCP\Federation\ICloudFederationNotification; * @since 14.0.0 */ class CloudFederationNotification implements ICloudFederationNotification { - private $message = []; /** @@ -53,7 +52,6 @@ class CloudFederationNotification implements ICloudFederationNotification { 'providerId' => $providerId, 'notification' => $notification, ]; - } /** diff --git a/lib/private/Federation/CloudFederationProviderManager.php b/lib/private/Federation/CloudFederationProviderManager.php index cad72abaf79..459d82c5bfb 100644 --- a/lib/private/Federation/CloudFederationProviderManager.php +++ b/lib/private/Federation/CloudFederationProviderManager.php @@ -96,7 +96,6 @@ class CloudFederationProviderManager implements ICloudFederationProviderManager 'displayName' => $displayName, 'callback' => $callback, ]; - } /** @@ -152,7 +151,6 @@ class CloudFederationProviderManager implements ICloudFederationProviderManager $result = json_decode($response->getBody(), true); return (is_array($result)) ? $result : []; } - } catch (\Exception $e) { // if flat re-sharing is not supported by the remote server // we re-throw the exception and fall back to the old behaviour. @@ -164,7 +162,6 @@ class CloudFederationProviderManager implements ICloudFederationProviderManager } return false; - } /** @@ -214,7 +211,6 @@ class CloudFederationProviderManager implements ICloudFederationProviderManager * @return string */ protected function getOCMEndPoint($url) { - if (isset($this->ocmEndPoints[$url])) { return $this->ocmEndPoints[$url]; } @@ -240,6 +236,4 @@ class CloudFederationProviderManager implements ICloudFederationProviderManager $this->ocmEndPoints[$url] = ''; return ''; } - - } diff --git a/lib/private/Federation/CloudFederationShare.php b/lib/private/Federation/CloudFederationShare.php index 50a01d46b3f..16f4216d65e 100644 --- a/lib/private/Federation/CloudFederationShare.php +++ b/lib/private/Federation/CloudFederationShare.php @@ -26,7 +26,6 @@ namespace OC\Federation; use OCP\Federation\ICloudFederationShare; class CloudFederationShare implements ICloudFederationShare { - private $share = [ 'shareWith' => '', 'shareType' => '', @@ -85,7 +84,6 @@ class CloudFederationShare implements ICloudFederationShare { ]); $this->setShareType($shareType); $this->setResourceType($resourceType); - } /** diff --git a/lib/private/Files/AppData/AppData.php b/lib/private/Files/AppData/AppData.php index 32f97034050..5f917afe207 100644 --- a/lib/private/Files/AppData/AppData.php +++ b/lib/private/Files/AppData/AppData.php @@ -65,7 +65,6 @@ class AppData implements IAppData { public function __construct(IRootFolder $rootFolder, SystemConfig $systemConfig, string $appId) { - $this->rootFolder = $rootFolder; $this->config = $systemConfig; $this->appId = $appId; diff --git a/lib/private/Files/AppData/Factory.php b/lib/private/Files/AppData/Factory.php index 085c17f3589..4801b241c0b 100644 --- a/lib/private/Files/AppData/Factory.php +++ b/lib/private/Files/AppData/Factory.php @@ -42,7 +42,6 @@ class Factory { public function __construct(IRootFolder $rootFolder, SystemConfig $systemConfig) { - $this->rootFolder = $rootFolder; $this->config = $systemConfig; } diff --git a/lib/private/Files/Cache/Cache.php b/lib/private/Files/Cache/Cache.php index bce9a1d88e0..2dfefeff662 100644 --- a/lib/private/Files/Cache/Cache.php +++ b/lib/private/Files/Cache/Cache.php @@ -331,7 +331,6 @@ class Cache implements ICache { * @param array $data [$key => $value] the metadata to update, only the fields provided in the array will be updated, non-provided values will remain unchanged */ public function update($id, array $data) { - if (isset($data['path'])) { // normalize path $data['path'] = $this->normalize($data['path']); @@ -990,7 +989,6 @@ class Cache implements ICache { * @return string */ public function normalize($path) { - return trim(\OC_Util::normalizeUnicode($path), '/'); } } diff --git a/lib/private/Files/Cache/Propagator.php b/lib/private/Files/Cache/Propagator.php index 7a1eae3498a..92fa6436548 100644 --- a/lib/private/Files/Cache/Propagator.php +++ b/lib/private/Files/Cache/Propagator.php @@ -200,6 +200,4 @@ class Propagator implements IPropagator { $this->connection->commit(); } - - } diff --git a/lib/private/Files/Cache/Scanner.php b/lib/private/Files/Cache/Scanner.php index 87f32538ec7..2a5a6536697 100644 --- a/lib/private/Files/Cache/Scanner.php +++ b/lib/private/Files/Cache/Scanner.php @@ -238,7 +238,6 @@ class Scanner extends BasicEmitter implements IScanner { $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', [$file, $this->storageId]); \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', ['path' => $file, 'storage' => $this->storageId]); } - } else { $this->removeFromCache($file); } diff --git a/lib/private/Files/Cache/Storage.php b/lib/private/Files/Cache/Storage.php index ca573be798a..62228e16290 100644 --- a/lib/private/Files/Cache/Storage.php +++ b/lib/private/Files/Cache/Storage.php @@ -126,7 +126,6 @@ class Storage { * @return string|null either the storage id string or null if the numeric id is not known */ public static function getStorageId($numericId) { - $sql = 'SELECT `id` FROM `*PREFIX*storages` WHERE `numeric_id` = ?'; $result = \OC_DB::executeAudited($sql, [$numericId]); if ($row = $result->fetchRow()) { diff --git a/lib/private/Files/Cache/Updater.php b/lib/private/Files/Cache/Updater.php index 378cadfcace..60534a153dd 100644 --- a/lib/private/Files/Cache/Updater.php +++ b/lib/private/Files/Cache/Updater.php @@ -167,7 +167,6 @@ class Updater implements IUpdater { $this->cache->correctFolderSize($parent); } } - } /** diff --git a/lib/private/Files/Cache/Watcher.php b/lib/private/Files/Cache/Watcher.php index 6270f03ca92..d6291ca71e9 100644 --- a/lib/private/Files/Cache/Watcher.php +++ b/lib/private/Files/Cache/Watcher.php @@ -34,7 +34,6 @@ 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 = []; diff --git a/lib/private/Files/Cache/Wrapper/CacheJail.php b/lib/private/Files/Cache/Wrapper/CacheJail.php index 8c30eeda2cf..8d4f412868e 100644 --- a/lib/private/Files/Cache/Wrapper/CacheJail.php +++ b/lib/private/Files/Cache/Wrapper/CacheJail.php @@ -273,7 +273,6 @@ class CacheJail extends CacheWrapper { } else { return 0; } - } /** diff --git a/lib/private/Files/Mount/ObjectHomeMountProvider.php b/lib/private/Files/Mount/ObjectHomeMountProvider.php index e49b704fe96..9b243d7f8f2 100644 --- a/lib/private/Files/Mount/ObjectHomeMountProvider.php +++ b/lib/private/Files/Mount/ObjectHomeMountProvider.php @@ -57,7 +57,6 @@ class ObjectHomeMountProvider implements IHomeMountProvider { * @return \OCP\Files\Mount\IMountPoint */ public function getHomeMountForUser(IUser $user, IStorageFactory $loader) { - $config = $this->getMultiBucketObjectStoreConfig($user); if ($config === null) { $config = $this->getSingleBucketObjectStoreConfig($user); diff --git a/lib/private/Files/Node/Folder.php b/lib/private/Files/Node/Folder.php index b24abf34f33..d9639e9f1ab 100644 --- a/lib/private/Files/Node/Folder.php +++ b/lib/private/Files/Node/Folder.php @@ -161,7 +161,7 @@ class Folder extends Node implements \OCP\Files\Folder { $fullPath = $this->getFullPath($path); $nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath); $this->sendHooks(['preWrite', 'preCreate'], [$nonExisting]); - if(!$this->view->mkdir($fullPath)) { + if (!$this->view->mkdir($fullPath)) { throw new NotPermittedException('Could not create folder'); } $node = new Folder($this->root, $this->view, $fullPath); diff --git a/lib/private/Files/Node/HookConnector.php b/lib/private/Files/Node/HookConnector.php index 67fadf19863..1f7f194c5f7 100644 --- a/lib/private/Files/Node/HookConnector.php +++ b/lib/private/Files/Node/HookConnector.php @@ -170,7 +170,6 @@ class HookConnector { private function getNodeForPath($path) { $info = Filesystem::getView()->getFileInfo($path); if (!$info) { - $fullPath = Filesystem::getView()->getAbsolutePath($path); if (isset($this->deleteMetaCache[$fullPath])) { $info = $this->deleteMetaCache[$fullPath]; diff --git a/lib/private/Files/Node/Node.php b/lib/private/Files/Node/Node.php index f8591080840..70821e685f8 100644 --- a/lib/private/Files/Node/Node.php +++ b/lib/private/Files/Node/Node.php @@ -465,5 +465,4 @@ class Node implements \OCP\Files\Node { public function getUploadTime(): int { return $this->getFileInfo()->getUploadTime(); } - } diff --git a/lib/private/Files/ObjectStore/HomeObjectStoreStorage.php b/lib/private/Files/ObjectStore/HomeObjectStoreStorage.php index 98b99efcb5a..efe3f7c12d0 100644 --- a/lib/private/Files/ObjectStore/HomeObjectStoreStorage.php +++ b/lib/private/Files/ObjectStore/HomeObjectStoreStorage.php @@ -65,6 +65,4 @@ class HomeObjectStoreStorage extends ObjectStoreStorage implements \OCP\Files\IH public function getUser($path = null) { return $this->user; } - - } diff --git a/lib/private/Files/ObjectStore/NoopScanner.php b/lib/private/Files/ObjectStore/NoopScanner.php index 7a253c82c5b..57a94aba294 100644 --- a/lib/private/Files/ObjectStore/NoopScanner.php +++ b/lib/private/Files/ObjectStore/NoopScanner.php @@ -31,7 +31,6 @@ use OC\Files\Cache\Scanner; use OC\Files\Storage\Storage; class NoopScanner extends Scanner { - public function __construct(Storage $storage) { //we don't need the storage, so do nothing here } diff --git a/lib/private/Files/ObjectStore/ObjectStoreStorage.php b/lib/private/Files/ObjectStore/ObjectStoreStorage.php index 7224f075d82..1faa44ad888 100644 --- a/lib/private/Files/ObjectStore/ObjectStoreStorage.php +++ b/lib/private/Files/ObjectStore/ObjectStoreStorage.php @@ -182,7 +182,7 @@ class ObjectStoreStorage extends \OC\Files\Storage\Common { return false; } } else { - if(!$this->unlink($child['path'])) { + if (!$this->unlink($child['path'])) { return false; } } diff --git a/lib/private/Files/ObjectStore/S3Signature.php b/lib/private/Files/ObjectStore/S3Signature.php index 6216992ad7a..f9ea2e22aad 100644 --- a/lib/private/Files/ObjectStore/S3Signature.php +++ b/lib/private/Files/ObjectStore/S3Signature.php @@ -33,8 +33,7 @@ use Psr\Http\Message\RequestInterface; /** * Legacy Amazon S3 signature implementation */ -class S3Signature implements SignatureInterface -{ +class S3Signature implements SignatureInterface { /** @var array Query string values that must be signed */ private $signableQueryString = [ 'acl', 'cors', 'delete', 'lifecycle', 'location', 'logging', @@ -52,8 +51,7 @@ class S3Signature implements SignatureInterface /** @var \Aws\S3\S3UriParser S3 URI parser */ private $parser; - public function __construct() - { + public function __construct() { $this->parser = new S3UriParser(); // Ensure that the signable query string parameters are sorted sort($this->signableQueryString); @@ -140,8 +138,7 @@ class S3Signature implements SignatureInterface return Psr7\modify_request($request, $modify); } - private function signString($string, CredentialsInterface $credentials) - { + private function signString($string, CredentialsInterface $credentials) { return base64_encode( hash_hmac('sha1', $string, $credentials->getSecretKey(), true) ); @@ -166,8 +163,7 @@ class S3Signature implements SignatureInterface return $buffer; } - private function createCanonicalizedAmzHeaders(RequestInterface $request) - { + private function createCanonicalizedAmzHeaders(RequestInterface $request) { $headers = []; foreach ($request->getHeaders() as $name => $header) { $name = strtolower($name); @@ -188,8 +184,7 @@ class S3Signature implements SignatureInterface return implode("\n", $headers) . "\n"; } - private function createCanonicalizedResource(RequestInterface $request) - { + private function createCanonicalizedResource(RequestInterface $request) { $data = $this->parser->parse($request->getUri()); $buffer = '/'; diff --git a/lib/private/Files/SimpleFS/SimpleFile.php b/lib/private/Files/SimpleFS/SimpleFile.php index dbc5f06f22b..e3a581b25d7 100644 --- a/lib/private/Files/SimpleFS/SimpleFile.php +++ b/lib/private/Files/SimpleFS/SimpleFile.php @@ -29,7 +29,7 @@ use OCP\Files\NotFoundException; use OCP\Files\NotPermittedException; use OCP\Files\SimpleFS\ISimpleFile; -class SimpleFile implements ISimpleFile { +class SimpleFile implements ISimpleFile { /** @var File $file */ private $file; @@ -179,5 +179,4 @@ class SimpleFile implements ISimpleFile { public function write() { return $this->file->fopen('w'); } - } diff --git a/lib/private/Files/SimpleFS/SimpleFolder.php b/lib/private/Files/SimpleFS/SimpleFolder.php index 7196b55ea12..aa5c200f5bd 100644 --- a/lib/private/Files/SimpleFS/SimpleFolder.php +++ b/lib/private/Files/SimpleFS/SimpleFolder.php @@ -30,7 +30,7 @@ use OCP\Files\Node; use OCP\Files\NotFoundException; use OCP\Files\SimpleFS\ISimpleFolder; -class SimpleFolder implements ISimpleFolder { +class SimpleFolder implements ISimpleFolder { /** @var Folder */ private $folder; diff --git a/lib/private/Files/Storage/Common.php b/lib/private/Files/Storage/Common.php index 456980db538..edad9cc874c 100644 --- a/lib/private/Files/Storage/Common.php +++ b/lib/private/Files/Storage/Common.php @@ -76,7 +76,6 @@ use OCP\Lock\LockedException; * in classes which extend it, e.g. $this->stat() . */ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage { - use LocalTempFileTrait; protected $cache; @@ -301,7 +300,9 @@ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage { $dh = $this->opendir($dir); if (is_resource($dh)) { while (($item = readdir($dh)) !== false) { - if (\OC\Files\Filesystem::isIgnoredDir($item)) continue; + if (\OC\Files\Filesystem::isIgnoredDir($item)) { + continue; + } if (strstr(strtolower($item), strtolower($query)) !== false) { $files[] = $dir . '/' . $item; } diff --git a/lib/private/Files/Storage/CommonTest.php b/lib/private/Files/Storage/CommonTest.php index 164738d9478..f3a127b635a 100644 --- a/lib/private/Files/Storage/CommonTest.php +++ b/lib/private/Files/Storage/CommonTest.php @@ -32,7 +32,7 @@ namespace OC\Files\Storage; -class CommonTest extends \OC\Files\Storage\Common{ +class CommonTest extends \OC\Files\Storage\Common { /** * underlying local storage used for missing functions * @var \OC\Files\Storage\Local diff --git a/lib/private/Files/Storage/DAV.php b/lib/private/Files/Storage/DAV.php index 3100a14a570..2974064f3a5 100644 --- a/lib/private/Files/Storage/DAV.php +++ b/lib/private/Files/Storage/DAV.php @@ -98,8 +98,11 @@ class DAV extends Common { if (isset($params['host']) && isset($params['user']) && isset($params['password'])) { $host = $params['host']; //remove leading http[s], will be generated in createBaseUri() - if (substr($host, 0, 8) == "https://") $host = substr($host, 8); - elseif (substr($host, 0, 7) == "http://") $host = substr($host, 7); + if (substr($host, 0, 8) == "https://") { + $host = substr($host, 8); + } elseif (substr($host, 0, 7) == "http://") { + $host = substr($host, 7); + } $this->host = $host; $this->user = $params['user']; $this->password = $params['password']; @@ -153,7 +156,7 @@ class DAV extends Common { $this->client = new Client($settings); $this->client->setThrowExceptions(true); - if($this->secure === true) { + if ($this->secure === true) { $certPath = $this->certManager->getAbsoluteBundlePath(); if (file_exists($certPath)) { $this->certPath = $certPath; @@ -853,7 +856,7 @@ class DAV extends Common { } elseif ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) { // ignore exception for MethodNotAllowed, false will be returned return; - } elseif ($e->getHttpStatus() === Http::STATUS_FORBIDDEN){ + } elseif ($e->getHttpStatus() === Http::STATUS_FORBIDDEN) { // The operation is forbidden. Fail somewhat gracefully throw new ForbiddenException(get_class($e) . ':' . $e->getMessage()); } diff --git a/lib/private/Files/Storage/Local.php b/lib/private/Files/Storage/Local.php index 05dd8c4d68f..89b318b4770 100644 --- a/lib/private/Files/Storage/Local.php +++ b/lib/private/Files/Storage/Local.php @@ -280,7 +280,6 @@ class Local extends \OC\Files\Storage\Common { } else { return false; } - } private function treeContainsBlacklistedFile(string $path): bool { @@ -393,8 +392,9 @@ class Local extends \OC\Files\Storage\Common { $files = []; $physicalDir = $this->getSourcePath($dir); foreach (scandir($physicalDir) as $item) { - if (\OC\Files\Filesystem::isIgnoredDir($item)) + if (\OC\Files\Filesystem::isIgnoredDir($item)) { continue; + } $physicalItem = $physicalDir . '/' . $item; if (strstr(strtolower($item), strtolower($query)) !== false) { diff --git a/lib/private/Files/Storage/Temporary.php b/lib/private/Files/Storage/Temporary.php index 5e4f834990b..5e4024286c5 100644 --- a/lib/private/Files/Storage/Temporary.php +++ b/lib/private/Files/Storage/Temporary.php @@ -29,7 +29,7 @@ namespace OC\Files\Storage; /** * local storage backend in temporary folder for testing purpose */ -class Temporary extends Local{ +class Temporary extends Local { public function __construct($arguments = null) { parent::__construct(['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]); } diff --git a/lib/private/Files/Storage/Wrapper/Availability.php b/lib/private/Files/Storage/Wrapper/Availability.php index 1540ac98a4b..b949c9103a7 100644 --- a/lib/private/Files/Storage/Wrapper/Availability.php +++ b/lib/private/Files/Storage/Wrapper/Availability.php @@ -451,7 +451,7 @@ class Availability extends Wrapper { */ protected function setUnavailable(StorageNotAvailableException $e) { $delay = self::RECHECK_TTL_SEC; - if($e instanceof StorageAuthException) { + if ($e instanceof StorageAuthException) { $delay = max( // 30min $this->config->getSystemValueInt('external_storage.auth_availability_delay', 1800), diff --git a/lib/private/Files/Storage/Wrapper/Encryption.php b/lib/private/Files/Storage/Wrapper/Encryption.php index 850b6205412..1ea2664877b 100644 --- a/lib/private/Files/Storage/Wrapper/Encryption.php +++ b/lib/private/Files/Storage/Wrapper/Encryption.php @@ -51,7 +51,6 @@ use OCP\Files\Storage; use OCP\ILogger; class Encryption extends Wrapper { - use LocalTempFileTrait; /** @var string */ @@ -117,7 +116,6 @@ class Encryption extends Wrapper { Manager $mountManager = null, ArrayCache $arrayCache = null ) { - $this->mountPoint = $parameters['mountPoint']; $this->mount = $parameters['mount']; $this->encryptionManager = $encryptionManager; @@ -207,7 +205,6 @@ class Encryption extends Wrapper { * @return string */ public function file_get_contents($path) { - $encryptionModule = $this->getEncryptionModule($path); if ($encryptionModule) { @@ -269,7 +266,6 @@ class Encryption extends Wrapper { * @return bool */ public function rename($path1, $path2) { - $result = $this->storage->rename($path1, $path2); if ($result && @@ -320,7 +316,6 @@ class Encryption extends Wrapper { * @return bool */ public function isReadable($path) { - $isReadable = true; $metaData = $this->getMetaData($path); @@ -345,7 +340,6 @@ class Encryption extends Wrapper { * @return bool */ public function copy($path1, $path2) { - $source = $this->getFullPath($path1); if ($this->util->isExcluded($source)) { @@ -386,7 +380,6 @@ class Encryption extends Wrapper { $encryptionModuleId = $this->util->getEncryptionModuleId($header); if ($this->util->isExcluded($fullPath) === false) { - $size = $unencryptedSize = 0; $realFile = $this->util->stripPartialFileExtension($path); $targetExists = $this->file_exists($realFile) || $this->file_exists($path); @@ -409,7 +402,6 @@ class Encryption extends Wrapper { } try { - if ( $mode === 'w' || $mode === 'w+' @@ -472,7 +464,6 @@ class Encryption extends Wrapper { $size, $unencryptedSize, $headerSize, $signed); return $handle; } - } return $this->storage->fopen($path, $mode); @@ -489,7 +480,6 @@ class Encryption extends Wrapper { * @return int unencrypted size */ protected function verifyUnencryptedSize($path, $unencryptedSize) { - $size = $this->storage->filesize($path); $result = $unencryptedSize; @@ -523,7 +513,6 @@ class Encryption extends Wrapper { * @return int calculated unencrypted size */ protected function fixUnencryptedSize($path, $size, $unencryptedSize) { - $headerSize = $this->getHeaderSize($path); $header = $this->getHeader($path); $encryptionModule = $this->getEncryptionModule($path); @@ -572,7 +561,7 @@ class Encryption extends Wrapper { $data=fread($stream, $blockSize); $count=strlen($data); $lastChunkContentEncrypted .= $data; - if(strlen($lastChunkContentEncrypted) > $blockSize) { + if (strlen($lastChunkContentEncrypted) > $blockSize) { $newUnencryptedSize += $unencryptedBlockSize; $lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize); } @@ -667,7 +656,7 @@ class Encryption extends Wrapper { $cacheInformation = [ 'encrypted' => $isEncrypted, ]; - if($isEncrypted) { + if ($isEncrypted) { $encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion']; // In case of a move operation from an unencrypted to an encrypted @@ -675,7 +664,7 @@ class Encryption extends Wrapper { // correct value would be "1". Thus we manually set the value to "1" // for those cases. // See also https://github.com/owncloud/core/issues/23078 - if($encryptedVersion === 0 || !$keepEncryptionVersion) { + if ($encryptedVersion === 0 || !$keepEncryptionVersion) { $encryptedVersion = 1; } @@ -762,7 +751,7 @@ class Encryption extends Wrapper { fclose($target); throw $e; } - if($result) { + if ($result) { if ($preserveMtime) { $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath)); } @@ -775,7 +764,6 @@ class Encryption extends Wrapper { } } return (bool)$result; - } /** @@ -1030,7 +1018,6 @@ class Encryption extends Wrapper { } return $encryptionModule->shouldEncrypt($fullPath); - } public function writeStream(string $path, $stream, int $size = null): int { @@ -1040,5 +1027,4 @@ class Encryption extends Wrapper { fclose($target); return $count; } - } diff --git a/lib/private/Files/Storage/Wrapper/Quota.php b/lib/private/Files/Storage/Wrapper/Quota.php index d4e4be41f71..62d3335987c 100644 --- a/lib/private/Files/Storage/Wrapper/Quota.php +++ b/lib/private/Files/Storage/Wrapper/Quota.php @@ -229,5 +229,4 @@ class Quota extends Wrapper { return parent::touch($path, $mtime); } - } diff --git a/lib/private/Files/Stream/Encryption.php b/lib/private/Files/Stream/Encryption.php index 527453c32e9..1fc14daacbd 100644 --- a/lib/private/Files/Stream/Encryption.php +++ b/lib/private/Files/Stream/Encryption.php @@ -165,7 +165,6 @@ class Encryption extends Wrapper { $headerSize, $signed, $wrapper = Encryption::class) { - $context = stream_context_create([ 'ocencryption' => [ 'source' => $source, @@ -233,7 +232,6 @@ class Encryption extends Wrapper { } } return $context; - } public function stream_open($path, $mode, $options, &$opened_path) { @@ -285,7 +283,6 @@ class Encryption extends Wrapper { } return true; - } public function stream_eof() { @@ -293,7 +290,6 @@ class Encryption extends Wrapper { } public function stream_read($count) { - $result = ''; $count = min($count, $this->unencryptedSize - $this->position); @@ -308,7 +304,7 @@ class Encryption extends Wrapper { $result .= substr($this->cache, $blockPosition, $remainingLength); $this->position += $remainingLength; $count = 0; - // otherwise remainder of current block is fetched, the block is flushed and the position updated + // otherwise remainder of current block is fetched, the block is flushed and the position updated } else { $result .= substr($this->cache, $blockPosition); $this->flush(); @@ -317,7 +313,6 @@ class Encryption extends Wrapper { } } return $result; - } /** @@ -378,7 +373,7 @@ class Encryption extends Wrapper { $this->position += $remainingLength; $length += $remainingLength; $data = ''; - // if $data doesn't fit the current block, the fill the current block and reiterate + // if $data doesn't fit the current block, the fill the current block and reiterate // after the block is filled, it is flushed and $data is updatedxxx } else { $this->cache = substr($this->cache, 0, $blockPosition) . @@ -401,7 +396,6 @@ class Encryption extends Wrapper { } public function stream_seek($offset, $whence = SEEK_SET) { - $return = false; switch ($whence) { @@ -434,7 +428,6 @@ class Encryption extends Wrapper { $return = true; } return $return; - } public function stream_close() { @@ -442,7 +435,7 @@ class Encryption extends Wrapper { $position = (int)floor($this->position/$this->unencryptedBlockSize); $remainingData = $this->encryptionModule->end($this->fullPath, $position . 'end'); if ($this->readOnly === false) { - if(!empty($remainingData)) { + if (!empty($remainingData)) { parent::stream_write($remainingData); } $this->encryptionStorage->updateUnencryptedSize($this->fullPath, $this->unencryptedSize); @@ -502,7 +495,7 @@ class Encryption extends Wrapper { $data = $this->stream_read_block($this->util->getBlockSize()); $position = (int)floor($this->position/$this->unencryptedBlockSize); $numberOfChunks = (int)($this->unencryptedSize / $this->unencryptedBlockSize); - if($numberOfChunks === $position) { + if ($numberOfChunks === $position) { $position .= 'end'; } $this->cache = $this->encryptionModule->decrypt($data, $position); @@ -545,5 +538,4 @@ class Encryption extends Wrapper { public function dir_opendir($path, $options) { return false; } - } diff --git a/lib/private/Files/Stream/Quota.php b/lib/private/Files/Stream/Quota.php index 877a05e6aa9..d0609d7e459 100644 --- a/lib/private/Files/Stream/Quota.php +++ b/lib/private/Files/Stream/Quota.php @@ -67,17 +67,16 @@ class Quota extends Wrapper { } public function stream_seek($offset, $whence = SEEK_SET) { - if ($whence === SEEK_END){ + if ($whence === SEEK_END) { // go to the end to find out last position's offset $oldOffset = $this->stream_tell(); - if (fseek($this->source, 0, $whence) !== 0){ + if (fseek($this->source, 0, $whence) !== 0) { return false; } $whence = SEEK_SET; $offset = $this->stream_tell() + $offset; $this->limit += $oldOffset - $offset; - } - elseif ($whence === SEEK_SET) { + } elseif ($whence === SEEK_SET) { $this->limit += $this->stream_tell() - $offset; } else { $this->limit -= $offset; diff --git a/lib/private/Files/Type/Detection.php b/lib/private/Files/Type/Detection.php index b36f8a70b99..e8825037666 100644 --- a/lib/private/Files/Type/Detection.php +++ b/lib/private/Files/Type/Detection.php @@ -51,7 +51,6 @@ use OCP\IURLGenerator; * @package OC\Files\Type */ class Detection implements IMimeTypeDetector { - private const CUSTOM_MIMETYPEMAPPING = 'mimetypemapping.json'; private const CUSTOM_MIMETYPEALIASES = 'mimetypealiases.json'; @@ -279,7 +278,6 @@ class Detection implements IMimeTypeDetector { return $mimeType; } } - } return 'application/octet-stream'; } diff --git a/lib/private/Files/Type/Loader.php b/lib/private/Files/Type/Loader.php index fded04b5466..d128bc724b6 100644 --- a/lib/private/Files/Type/Loader.php +++ b/lib/private/Files/Type/Loader.php @@ -173,5 +173,4 @@ class Loader implements IMimeTypeLoader { )); return $update->execute(); } - } diff --git a/lib/private/Files/Utils/Scanner.php b/lib/private/Files/Utils/Scanner.php index 49f8177834a..a729da89fb0 100644 --- a/lib/private/Files/Utils/Scanner.php +++ b/lib/private/Files/Utils/Scanner.php @@ -223,7 +223,6 @@ class Scanner extends PublicEmitter { } else {// if the root exists in neither the cache nor the storage the user isn't setup yet break; } - } // don't scan received local shares, these can be scanned when scanning the owner's storage diff --git a/lib/private/Files/View.php b/lib/private/Files/View.php index da67fc461b5..20c0fd3ed1b 100644 --- a/lib/private/Files/View.php +++ b/lib/private/Files/View.php @@ -829,7 +829,7 @@ class View { $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2); } } - } catch(\Exception $e) { + } catch (\Exception $e) { throw $e; } finally { $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true); @@ -853,7 +853,7 @@ class View { } } } - } catch(\Exception $e) { + } catch (\Exception $e) { throw $e; } finally { $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true); @@ -895,7 +895,6 @@ class View { $lockTypePath2 = ILockingProvider::LOCK_SHARED; try { - $exists = $this->file_exists($path2); if ($this->shouldEmitHooks()) { \OC_Hook::emit( @@ -946,7 +945,6 @@ class View { ); $this->emit_file_hooks_post($exists, $path2); } - } } catch (\Exception $e) { $this->unlockFile($path2, $lockTypePath2); @@ -956,7 +954,6 @@ class View { $this->unlockFile($path2, $lockTypePath2); $this->unlockFile($path1, $lockTypePath1); - } return $result; } diff --git a/lib/private/FullTextSearch/FullTextSearchManager.php b/lib/private/FullTextSearch/FullTextSearchManager.php index 4af70d97260..119c97fa95b 100644 --- a/lib/private/FullTextSearch/FullTextSearchManager.php +++ b/lib/private/FullTextSearch/FullTextSearchManager.php @@ -230,6 +230,4 @@ class FullTextSearchManager implements IFullTextSearchManager { return $this->getSearchService()->search($userId, $searchRequest); } - - } diff --git a/lib/private/FullTextSearch/Model/IndexDocument.php b/lib/private/FullTextSearch/Model/IndexDocument.php index 7c7847b7463..252aa66395a 100644 --- a/lib/private/FullTextSearch/Model/IndexDocument.php +++ b/lib/private/FullTextSearch/Model/IndexDocument.php @@ -922,7 +922,6 @@ class IndexDocument implements IIndexDocument, JsonSerializable { * @return array */ final public function getInfoAll(): array { - $info = []; foreach ($this->info as $k => $v) { if (substr($k, 0, 1) === '_') { @@ -989,5 +988,4 @@ class IndexDocument implements IIndexDocument, JsonSerializable { 'score' => $this->getScore() ]; } - } diff --git a/lib/private/FullTextSearch/Model/SearchRequestSimpleQuery.php b/lib/private/FullTextSearch/Model/SearchRequestSimpleQuery.php index 19be494d82f..c015c4c1579 100644 --- a/lib/private/FullTextSearch/Model/SearchRequestSimpleQuery.php +++ b/lib/private/FullTextSearch/Model/SearchRequestSimpleQuery.php @@ -178,5 +178,4 @@ final class SearchRequestSimpleQuery implements ISearchRequestSimpleQuery, JsonS 'values' => $this->getValues() ]; } - } diff --git a/lib/private/GlobalScale/Config.php b/lib/private/GlobalScale/Config.php index f886ac8ff84..d4bde44a5fa 100644 --- a/lib/private/GlobalScale/Config.php +++ b/lib/private/GlobalScale/Config.php @@ -67,5 +67,4 @@ class Config implements \OCP\GlobalScale\IConfig { return $enabled === 'internal'; } - } diff --git a/lib/private/Group/Backend.php b/lib/private/Group/Backend.php index 4e2f912e7fc..0f0e2c743e8 100644 --- a/lib/private/Group/Backend.php +++ b/lib/private/Group/Backend.php @@ -53,8 +53,8 @@ abstract class Backend implements \OCP\GroupInterface { */ public function getSupportedActions() { $actions = 0; - foreach($this->possibleActions as $action => $methodName) { - if(method_exists($this, $methodName)) { + foreach ($this->possibleActions as $action => $methodName) { + if (method_exists($this, $methodName)) { $actions |= $action; } } diff --git a/lib/private/Group/Database.php b/lib/private/Group/Database.php index 99654b5d1f2..b75dc097c97 100644 --- a/lib/private/Group/Database.php +++ b/lib/private/Group/Database.php @@ -113,7 +113,7 @@ class Database extends ABackend ->setValue('gid', $builder->createNamedParameter($gid)) ->setValue('displayname', $builder->createNamedParameter($gid)) ->execute(); - } catch(UniqueConstraintViolationException $e) { + } catch (UniqueConstraintViolationException $e) { $result = 0; } @@ -194,14 +194,14 @@ class Database extends ABackend $this->fixDI(); // No duplicate entries! - if(!$this->inGroup($uid, $gid)) { + if (!$this->inGroup($uid, $gid)) { $qb = $this->dbConn->getQueryBuilder(); $qb->insert('group_user') ->setValue('uid', $qb->createNamedParameter($uid)) ->setValue('gid', $qb->createNamedParameter($gid)) ->execute(); return true; - }else{ + } else { return false; } } @@ -250,7 +250,7 @@ class Database extends ABackend ->execute(); $groups = []; - while($row = $cursor->fetch()) { + while ($row = $cursor->fetch()) { $groups[] = $row['gid']; $this->groupCache[$row['gid']] = $row['gid']; } @@ -473,5 +473,4 @@ class Database extends ABackend return true; } - } diff --git a/lib/private/Group/Group.php b/lib/private/Group/Group.php index 9eb1b616609..2e16d5f1242 100644 --- a/lib/private/Group/Group.php +++ b/lib/private/Group/Group.php @@ -265,8 +265,8 @@ class Group implements IGroup { public function count($search = '') { $users = false; foreach ($this->backends as $backend) { - if($backend->implementsActions(\OC\Group\Backend::COUNT_USERS)) { - if($users === false) { + if ($backend->implementsActions(\OC\Group\Backend::COUNT_USERS)) { + if ($users === false) { //we could directly add to a bool variable, but this would //be ugly $users = 0; @@ -285,8 +285,8 @@ class Group implements IGroup { public function countDisabled() { $users = false; foreach ($this->backends as $backend) { - if($backend instanceof ICountDisabledInGroup) { - if($users === false) { + if ($backend instanceof ICountDisabledInGroup) { + if ($users === false) { //we could directly add to a bool variable, but this would //be ugly $users = 0; diff --git a/lib/private/Group/MetaData.php b/lib/private/Group/MetaData.php index 335bf43c16b..880dbf6437c 100644 --- a/lib/private/Group/MetaData.php +++ b/lib/private/Group/MetaData.php @@ -83,7 +83,7 @@ class MetaData { */ public function get($groupSearch = '', $userSearch = '') { $key = $groupSearch . '::' . $userSearch; - if(isset($this->metaData[$key])) { + if (isset($this->metaData[$key])) { return $this->metaData[$key]; } @@ -94,7 +94,7 @@ class MetaData { $sortAdminGroupsIndex = 0; $sortAdminGroupsKeys = []; - foreach($this->getGroups($groupSearch) as $group) { + foreach ($this->getGroups($groupSearch) as $group) { $groupMetaData = $this->generateGroupMetaData($group, $userSearch); if (strtolower($group->getGID()) !== 'admin') { $this->addEntry( @@ -194,11 +194,11 @@ class MetaData { * @return \OCP\IGroup[] */ public function getGroups($search = '') { - if($this->isAdmin) { + if ($this->isAdmin) { return $this->groupManager->search($search); } else { $userObject = $this->userSession->getUser(); - if($userObject !== null) { + if ($userObject !== null) { $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($userObject); } else { $groups = []; diff --git a/lib/private/HintException.php b/lib/private/HintException.php index 4b51a565f7b..acb8df414a3 100644 --- a/lib/private/HintException.php +++ b/lib/private/HintException.php @@ -35,7 +35,6 @@ namespace OC; * @package OC */ class HintException extends \Exception { - private $hint; /** diff --git a/lib/private/Http/Client/Client.php b/lib/private/Http/Client/Client.php index a73ae2c2be5..19d5877f9fb 100644 --- a/lib/private/Http/Client/Client.php +++ b/lib/private/Http/Client/Client.php @@ -76,7 +76,7 @@ class Client implements IClient { // Only add RequestOptions::PROXY if Nextcloud is explicitly // configured to use a proxy. This is needed in order not to override // Guzzle default values. - if($proxy !== null) { + if ($proxy !== null) { $defaults[RequestOptions::PROXY] = $proxy; } diff --git a/lib/private/Http/CookieHelper.php b/lib/private/Http/CookieHelper.php index 7d2acc7a193..7083584bffa 100644 --- a/lib/private/Http/CookieHelper.php +++ b/lib/private/Http/CookieHelper.php @@ -27,7 +27,6 @@ declare(strict_types=1); namespace OC\Http; class CookieHelper { - const SAMESITE_NONE = 0; const SAMESITE_LAX = 1; const SAMESITE_STRICT = 2; diff --git a/lib/private/InitialStateService.php b/lib/private/InitialStateService.php index 6c8c242b662..55ce9c41726 100644 --- a/lib/private/InitialStateService.php +++ b/lib/private/InitialStateService.php @@ -89,5 +89,4 @@ class InitialStateService implements IInitialStateService { } return $appStates; } - } diff --git a/lib/private/Installer.php b/lib/private/Installer.php index 78925a56a2e..d5c9d076eda 100644 --- a/lib/private/Installer.php +++ b/lib/private/Installer.php @@ -106,7 +106,7 @@ class Installer { */ public function installApp(string $appId, bool $forceEnable = false): string { $app = \OC_App::findAppInDirectories($appId); - if($app === false) { + if ($app === false) { throw new \Exception('App not found in any app directory'); } @@ -115,7 +115,7 @@ class Installer { $l = \OC::$server->getL10N('core'); - if(!is_array($info)) { + if (!is_array($info)) { throw new \Exception( $l->t('App "%s" cannot be installed because appinfo file cannot be read.', [$appId] @@ -146,7 +146,7 @@ class Installer { } //install the database - if(is_file($basedir.'/appinfo/database.xml')) { + if (is_file($basedir.'/appinfo/database.xml')) { if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) { OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml'); } else { @@ -173,10 +173,10 @@ class Installer { \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no'); //set remote/public handlers - foreach($info['remote'] as $name=>$path) { + foreach ($info['remote'] as $name=>$path) { \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path); } - foreach($info['public'] as $name=>$path) { + foreach ($info['public'] as $name=>$path) { \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path); } @@ -192,7 +192,7 @@ class Installer { * @return bool */ public function updateAppstoreApp($appId) { - if($this->isUpdateAvailable($appId)) { + if ($this->isUpdateAvailable($appId)) { try { $this->downloadApp($appId); } catch (\Exception $e) { @@ -219,8 +219,8 @@ class Installer { $appId = strtolower($appId); $apps = $this->appFetcher->get(); - foreach($apps as $app) { - if($app['id'] === $appId) { + foreach ($apps as $app) { + if ($app['id'] === $appId) { // Load the certificate $certificate = new X509(); $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt')); @@ -230,7 +230,7 @@ class Installer { $crl = new X509(); $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt')); $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl')); - if($crl->validateSignature() !== true) { + if ($crl->validateSignature() !== true) { throw new \Exception('Could not validate CRL signature'); } $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString(); @@ -245,7 +245,7 @@ class Installer { } // Verify if the certificate has been issued by the Nextcloud Code Authority CA - if($certificate->validateSignature() !== true) { + if ($certificate->validateSignature() !== true) { throw new \Exception( sprintf( 'App with id %s has a certificate not issued by a trusted Code Signing Authority', @@ -256,7 +256,7 @@ class Installer { // Verify if the certificate is issued for the requested app id $certInfo = openssl_x509_parse($app['certificate']); - if(!isset($certInfo['subject']['CN'])) { + if (!isset($certInfo['subject']['CN'])) { throw new \Exception( sprintf( 'App with id %s has a cert with no CN', @@ -264,7 +264,7 @@ class Installer { ) ); } - if($certInfo['subject']['CN'] !== $appId) { + if ($certInfo['subject']['CN'] !== $appId) { throw new \Exception( sprintf( 'App with id %s has a cert issued to %s', @@ -285,12 +285,12 @@ class Installer { $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512); openssl_free_key($certificate); - if($verified === true) { + if ($verified === true) { // Seems to match, let's proceed $extractDir = $this->tempManager->getTemporaryFolder(); $archive = new TAR($tempFile); - if($archive) { + if ($archive) { if (!$archive->extract($extractDir)) { throw new \Exception( sprintf( @@ -303,7 +303,7 @@ class Installer { $folders = array_diff($allFiles, ['.', '..']); $folders = array_values($folders); - if(count($folders) > 1) { + if (count($folders) > 1) { throw new \Exception( sprintf( 'Extracted app %s has more than 1 folder', @@ -316,7 +316,7 @@ class Installer { $loadEntities = libxml_disable_entity_loader(false); $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml'); libxml_disable_entity_loader($loadEntities); - if((string)$xml->id !== $appId) { + if ((string)$xml->id !== $appId) { throw new \Exception( sprintf( 'App for id %s has a wrong app ID in info.xml: %s', @@ -329,7 +329,7 @@ class Installer { // Check if the version is lower than before $currentVersion = OC_App::getAppVersion($appId); $newVersion = (string)$xml->version; - if(version_compare($currentVersion, $newVersion) === 1) { + if (version_compare($currentVersion, $newVersion) === 1) { throw new \Exception( sprintf( 'App for id %s has version %s and tried to update to lower version %s', @@ -344,7 +344,7 @@ class Installer { // Remove old app with the ID if existent OC_Helper::rmdirr($baseDir); // Move to app folder - if(@mkdir($baseDir)) { + if (@mkdir($baseDir)) { $extractDir .= '/' . $folders[0]; OC_Helper::copyr($extractDir, $baseDir); } @@ -408,8 +408,8 @@ class Installer { $this->apps = $this->appFetcher->get(); } - foreach($this->apps as $app) { - if($app['id'] === $appId) { + foreach ($this->apps as $app) { + if ($app['id'] === $appId) { $currentVersion = OC_App::getAppVersion($appId); if (!isset($app['releases'][0]['version'])) { @@ -436,7 +436,7 @@ class Installer { */ private function isInstalledFromGit($appId) { $app = \OC_App::findAppInDirectories($appId); - if($app === false) { + if ($app === false) { return false; } $basedir = $app['path'].'/'.$appId; @@ -451,7 +451,7 @@ class Installer { * The function will check if the app is already downloaded in the apps repository */ public function isDownloaded($name) { - foreach(\OC::$APPSROOTS as $dir) { + foreach (\OC::$APPSROOTS as $dir) { $dirToTest = $dir['path']; $dirToTest .= '/'; $dirToTest .= $name; @@ -479,19 +479,18 @@ class Installer { * this has to be done by the function oc_app_uninstall(). */ public function removeApp($appId) { - if($this->isDownloaded($appId)) { + if ($this->isDownloaded($appId)) { if (\OC::$server->getAppManager()->isShipped($appId)) { return false; } $appDir = OC_App::getInstallPath() . '/' . $appId; OC_Helper::rmdirr($appDir); return true; - }else{ + } else { \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', ILogger::ERROR); return false; } - } /** @@ -502,8 +501,8 @@ class Installer { */ public function installAppBundle(Bundle $bundle) { $appIds = $bundle->getAppIdentifiers(); - foreach($appIds as $appId) { - if(!$this->isDownloaded($appId)) { + foreach ($appIds as $appId) { + if (!$this->isDownloaded($appId)) { $this->downloadApp($appId); } $this->installApp($appId); @@ -527,12 +526,12 @@ class Installer { $appManager = \OC::$server->getAppManager(); $config = \OC::$server->getConfig(); $errors = []; - foreach(\OC::$APPSROOTS as $app_dir) { - if($dir = opendir($app_dir['path'])) { - while(false !== ($filename = readdir($dir))) { - if($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) { - if(file_exists($app_dir['path']."/$filename/appinfo/info.xml")) { - if($config->getAppValue($filename, "installed_version", null) === null) { + foreach (\OC::$APPSROOTS as $app_dir) { + if ($dir = opendir($app_dir['path'])) { + while (false !== ($filename = readdir($dir))) { + if ($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) { + if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) { + if ($config->getAppValue($filename, "installed_version", null) === null) { $info=OC_App::getAppInfo($filename); $enabled = isset($info['default_enable']); if (($enabled || in_array($filename, $appManager->getAlwaysEnabledApps())) @@ -573,7 +572,7 @@ class Installer { $appPath = OC_App::getAppPath($app); \OC_App::registerAutoloading($app, $appPath); - if(is_file("$appPath/appinfo/database.xml")) { + if (is_file("$appPath/appinfo/database.xml")) { try { OC_DB::createDbFromStructure("$appPath/appinfo/database.xml"); } catch (TableExistsException $e) { @@ -607,10 +606,10 @@ class Installer { } //set remote/public handlers - foreach($info['remote'] as $name=>$path) { + foreach ($info['remote'] as $name=>$path) { $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path); } - foreach($info['public'] as $name=>$path) { + foreach ($info['public'] as $name=>$path) { $config->setAppValue('core', 'public_'.$name, $app.'/'.$path); } @@ -623,7 +622,7 @@ class Installer { * @param string $script */ private static function includeAppScript($script) { - if (file_exists($script)){ + if (file_exists($script)) { include $script; } } diff --git a/lib/private/IntegrityCheck/Checker.php b/lib/private/IntegrityCheck/Checker.php index 725d72d9c79..1084a9e1dd5 100644 --- a/lib/private/IntegrityCheck/Checker.php +++ b/lib/private/IntegrityCheck/Checker.php @@ -144,7 +144,7 @@ class Checker { $folderToIterate, \RecursiveDirectoryIterator::SKIP_DOTS ); - if($root === '') { + if ($root === '') { $root = \OC::$SERVERROOT; } $root = rtrim($root, '/'); @@ -171,9 +171,9 @@ class Checker { $hashes = []; $baseDirectoryLength = \strlen($path); - foreach($iterator as $filename => $data) { + foreach ($iterator as $filename => $data) { /** @var \DirectoryIterator $data */ - if($data->isDir()) { + if ($data->isDir()) { continue; } @@ -181,11 +181,11 @@ class Checker { $relativeFileName = ltrim($relativeFileName, '/'); // Exclude signature.json files in the appinfo and root folder - if($relativeFileName === 'appinfo/signature.json') { + if ($relativeFileName === 'appinfo/signature.json') { continue; } // Exclude signature.json files in the appinfo and core folder - if($relativeFileName === 'core/signature.json') { + if ($relativeFileName === 'core/signature.json') { continue; } @@ -196,10 +196,10 @@ class Checker { // Thus we ignore everything below the first occurrence of // "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####" and have the // hash generated based on this. - if($filename === $this->environmentHelper->getServerRoot() . '/.htaccess') { + if ($filename === $this->environmentHelper->getServerRoot() . '/.htaccess') { $fileContent = file_get_contents($filename); $explodedArray = explode('#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####', $fileContent); - if(\count($explodedArray) === 2) { + if (\count($explodedArray) === 2) { $hashes[$relativeFileName] = hash('sha512', $explodedArray[0]); continue; } @@ -207,7 +207,7 @@ class Checker { if ($filename === $this->environmentHelper->getServerRoot() . '/core/js/mimetypelist.js') { $oldMimetypeList = new GenerateMimetypeFileBuilder(); $newFile = $oldMimetypeList->generateFile($this->mimeTypeDetector->getAllAliases()); - if($newFile === file_get_contents($filename)) { + if ($newFile === file_get_contents($filename)) { $hashes[$relativeFileName] = hash('sha512', $oldMimetypeList->generateFile($this->mimeTypeDetector->getOnlyDefaultAliases())); continue; } @@ -263,11 +263,11 @@ class Checker { $iterator = $this->getFolderIterator($path); $hashes = $this->generateHashes($iterator, $path); $signature = $this->createSignatureData($hashes, $certificate, $privateKey); - $this->fileAccessHelper->file_put_contents( + $this->fileAccessHelper->file_put_contents( $appInfoDir . '/signature.json', json_encode($signature, JSON_PRETTY_PRINT) ); - } catch (\Exception $e){ + } catch (\Exception $e) { if (!$this->fileAccessHelper->is_writable($appInfoDir)) { throw new \Exception($appInfoDir . ' is not writable'); } @@ -288,7 +288,6 @@ class Checker { $path) { $coreDir = $path . '/core'; try { - $this->fileAccessHelper->assertDirectoryExists($coreDir); $iterator = $this->getFolderIterator($path, $path); $hashes = $this->generateHashes($iterator, $path); @@ -297,7 +296,7 @@ class Checker { $coreDir . '/signature.json', json_encode($signatureData, JSON_PRETTY_PRINT) ); - } catch (\Exception $e){ + } catch (\Exception $e) { if (!$this->fileAccessHelper->is_writable($coreDir)) { throw new \Exception($coreDir . ' is not writable'); } @@ -316,7 +315,7 @@ class Checker { * @throws \Exception */ private function verify(string $signaturePath, string $basePath, string $certificateCN): array { - if(!$this->isCodeCheckEnforced()) { + if (!$this->isCodeCheckEnforced()) { return []; } @@ -326,7 +325,7 @@ class Checker { if (\is_string($content)) { $signatureData = json_decode($content, true); } - if(!\is_array($signatureData)) { + if (!\is_array($signatureData)) { throw new InvalidSignatureException('Signature data not found.'); } @@ -340,11 +339,11 @@ class Checker { $rootCertificatePublicKey = $this->fileAccessHelper->file_get_contents($this->environmentHelper->getServerRoot().'/resources/codesigning/root.crt'); $x509->loadCA($rootCertificatePublicKey); $x509->loadX509($certificate); - if(!$x509->validateSignature()) { + if (!$x509->validateSignature()) { throw new InvalidSignatureException('Certificate is not valid.'); } // Verify if certificate has proper CN. "core" CN is always trusted. - if($x509->getDN(X509::DN_OPENSSL)['CN'] !== $certificateCN && $x509->getDN(X509::DN_OPENSSL)['CN'] !== 'core') { + if ($x509->getDN(X509::DN_OPENSSL)['CN'] !== $certificateCN && $x509->getDN(X509::DN_OPENSSL)['CN'] !== 'core') { throw new InvalidSignatureException( sprintf('Certificate is not valid for required scope. (Requested: %s, current: CN=%s)', $certificateCN, $x509->getDN(true)['CN']) ); @@ -357,7 +356,7 @@ class Checker { $rsa->setMGFHash('sha512'); // See https://tools.ietf.org/html/rfc3447#page-38 $rsa->setSaltLength(0); - if(!$rsa->verify(json_encode($expectedHashes), $signature)) { + if (!$rsa->verify(json_encode($expectedHashes), $signature)) { throw new InvalidSignatureException('Signature could not get verified.'); } @@ -366,9 +365,9 @@ class Checker { // // Due to this reason we exclude the whole updater/ folder from the code // integrity check. - if($basePath === $this->environmentHelper->getServerRoot()) { - foreach($expectedHashes as $fileName => $hash) { - if(strpos($fileName, 'updater/') === 0) { + if ($basePath === $this->environmentHelper->getServerRoot()) { + foreach ($expectedHashes as $fileName => $hash) { + if (strpos($fileName, 'updater/') === 0) { unset($expectedHashes[$fileName]); } } @@ -380,23 +379,23 @@ class Checker { $differencesB = array_diff($currentInstanceHashes, $expectedHashes); $differences = array_unique(array_merge($differencesA, $differencesB)); $differenceArray = []; - foreach($differences as $filename => $hash) { + foreach ($differences as $filename => $hash) { // Check if file should not exist in the new signature table - if(!array_key_exists($filename, $expectedHashes)) { + if (!array_key_exists($filename, $expectedHashes)) { $differenceArray['EXTRA_FILE'][$filename]['expected'] = ''; $differenceArray['EXTRA_FILE'][$filename]['current'] = $hash; continue; } // Check if file is missing - if(!array_key_exists($filename, $currentInstanceHashes)) { + if (!array_key_exists($filename, $currentInstanceHashes)) { $differenceArray['FILE_MISSING'][$filename]['expected'] = $expectedHashes[$filename]; $differenceArray['FILE_MISSING'][$filename]['current'] = ''; continue; } // Check if hash does mismatch - if($expectedHashes[$filename] !== $currentInstanceHashes[$filename]) { + if ($expectedHashes[$filename] !== $currentInstanceHashes[$filename]) { $differenceArray['INVALID_HASH'][$filename]['expected'] = $expectedHashes[$filename]; $differenceArray['INVALID_HASH'][$filename]['current'] = $currentInstanceHashes[$filename]; continue; @@ -416,7 +415,7 @@ class Checker { */ public function hasPassedCheck(): bool { $results = $this->getResults(); - if(empty($results)) { + if (empty($results)) { return true; } @@ -428,7 +427,7 @@ class Checker { */ public function getResults(): array { $cachedResults = $this->cache->get(self::CACHE_KEY); - if(!\is_null($cachedResults)) { + if (!\is_null($cachedResults)) { return json_decode($cachedResults, true); } @@ -447,7 +446,7 @@ class Checker { private function storeResults(string $scope, array $result) { $resultArray = $this->getResults(); unset($resultArray[$scope]); - if(!empty($result)) { + if (!empty($result)) { $resultArray[$scope] = $result; } if ($this->config !== null) { @@ -499,7 +498,7 @@ class Checker { */ public function verifyAppSignature(string $appId, string $path = ''): array { try { - if($path === '') { + if ($path === '') { $path = $this->appLocator->getAppPath($appId); } $result = $this->verify( @@ -578,7 +577,7 @@ class Checker { $this->cleanResults(); $this->verifyCoreSignature(); $appIds = $this->appLocator->getAllApps(); - foreach($appIds as $appId) { + foreach ($appIds as $appId) { // If an application is shipped a valid signature is required $isShipped = $this->appManager->isShipped($appId); $appNeedsToBeChecked = false; @@ -589,7 +588,7 @@ class Checker { $appNeedsToBeChecked = true; } - if($appNeedsToBeChecked) { + if ($appNeedsToBeChecked) { $this->verifyAppSignature($appId); } } diff --git a/lib/private/IntegrityCheck/Exceptions/InvalidSignatureException.php b/lib/private/IntegrityCheck/Exceptions/InvalidSignatureException.php index 8a7f5129dce..0e55afa9a40 100644 --- a/lib/private/IntegrityCheck/Exceptions/InvalidSignatureException.php +++ b/lib/private/IntegrityCheck/Exceptions/InvalidSignatureException.php @@ -28,4 +28,5 @@ namespace OC\IntegrityCheck\Exceptions; * * @package OC\IntegrityCheck\Exceptions */ -class InvalidSignatureException extends \Exception {} +class InvalidSignatureException extends \Exception { +} diff --git a/lib/private/IntegrityCheck/Helpers/AppLocator.php b/lib/private/IntegrityCheck/Helpers/AppLocator.php index 75a64bfe0b8..6faff0a8982 100644 --- a/lib/private/IntegrityCheck/Helpers/AppLocator.php +++ b/lib/private/IntegrityCheck/Helpers/AppLocator.php @@ -43,8 +43,7 @@ class AppLocator { */ public function getAppPath(string $appId): string { $path = \OC_App::getAppPath($appId); - if($path === false) { - + if ($path === false) { throw new \Exception('App not found'); } return $path; diff --git a/lib/private/IntegrityCheck/Helpers/FileAccessHelper.php b/lib/private/IntegrityCheck/Helpers/FileAccessHelper.php index 322b6ada9e1..de2a560223c 100644 --- a/lib/private/IntegrityCheck/Helpers/FileAccessHelper.php +++ b/lib/private/IntegrityCheck/Helpers/FileAccessHelper.php @@ -64,7 +64,7 @@ class FileAccessHelper { */ public function file_put_contents(string $filename, string $data): int { $bytesWritten = @file_put_contents($filename, $data); - if ($bytesWritten === false || $bytesWritten !== \strlen($data)){ + if ($bytesWritten === false || $bytesWritten !== \strlen($data)) { throw new \Exception('Failed to write into ' . $filename); } return $bytesWritten; diff --git a/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php b/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php index 3a713954a79..7127742b531 100644 --- a/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php +++ b/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php @@ -34,7 +34,7 @@ class ExcludeFoldersByPathFilterIterator extends \RecursiveFilterIterator { parent::__construct($iterator); $appFolders = \OC::$APPSROOTS; - foreach($appFolders as $key => $appFolder) { + foreach ($appFolders as $key => $appFolder) { $appFolders[$key] = rtrim($appFolder['path'], '/'); } @@ -52,7 +52,7 @@ class ExcludeFoldersByPathFilterIterator extends \RecursiveFilterIterator { rtrim($root . '/_oc_upgrade', '/'), ]; $customDataDir = \OC::$server->getConfig()->getSystemValue('datadirectory', ''); - if($customDataDir !== '') { + if ($customDataDir !== '') { $excludedFolders[] = rtrim($customDataDir, '/'); } diff --git a/lib/private/L10N/Factory.php b/lib/private/L10N/Factory.php index a5b208cfb3c..a1afb1f4f0a 100644 --- a/lib/private/L10N/Factory.php +++ b/lib/private/L10N/Factory.php @@ -115,7 +115,6 @@ class Factory implements IFactory { */ public function get($app, $lang = null, $locale = null) { return new LazyL10N(function () use ($app, $lang, $locale) { - $app = \OC_App::cleanAppId($app); if ($lang !== null) { $lang = str_replace(['\0', '/', '\\', '..'], '', (string)$lang); @@ -353,7 +352,7 @@ class Factory implements IFactory { public function getLanguageIterator(IUser $user = null): ILanguageIterator { $user = $user ?? $this->userSession->getUser(); - if($user === null) { + if ($user === null) { throw new \RuntimeException('Failed to get an IUser instance'); } return new LanguageIterator($user, $this->config); @@ -543,7 +542,7 @@ class Factory implements IFactory { $res = ''; $p = 0; $length = strlen($body); - for($i = 0; $i < $length; $i++) { + for ($i = 0; $i < $length; $i++) { $ch = $body[$i]; switch ($ch) { case '?': @@ -594,7 +593,7 @@ class Factory implements IFactory { $commonLanguages = []; $languages = []; - foreach($languageCodes as $lang) { + foreach ($languageCodes as $lang) { $l = $this->get('lib', $lang); // TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version $potentialName = (string) $l->t('__language_name__'); diff --git a/lib/private/L10N/L10NString.php b/lib/private/L10N/L10NString.php index 47635cf67fc..683cd902ab6 100644 --- a/lib/private/L10N/L10NString.php +++ b/lib/private/L10N/L10NString.php @@ -63,13 +63,12 @@ class L10NString implements \JsonSerializable { $translations = $this->l10n->getTranslations(); $text = $this->text; - if(array_key_exists($this->text, $translations)) { - if(is_array($translations[$this->text])) { + if (array_key_exists($this->text, $translations)) { + if (is_array($translations[$this->text])) { $fn = $this->l10n->getPluralFormFunction(); $id = $fn($this->count); $text = $translations[$this->text][$id]; - } - else{ + } else { $text = $translations[$this->text]; } } diff --git a/lib/private/L10N/LanguageIterator.php b/lib/private/L10N/LanguageIterator.php index 8c9624d7d53..0670ac56503 100644 --- a/lib/private/L10N/LanguageIterator.php +++ b/lib/private/L10N/LanguageIterator.php @@ -55,18 +55,18 @@ class LanguageIterator implements ILanguageIterator { * @since 14.0.0 */ public function current(): string { - switch($this->i) { + switch ($this->i) { /** @noinspection PhpMissingBreakStatementInspection */ case 0: $forcedLang = $this->config->getSystemValue('force_language', false); - if(is_string($forcedLang)) { + if (is_string($forcedLang)) { return $forcedLang; } $this->next(); /** @noinspection PhpMissingBreakStatementInspection */ case 1: $forcedLang = $this->config->getSystemValue('force_language', false); - if(is_string($forcedLang) + if (is_string($forcedLang) && ($truncated = $this->getTruncatedLanguage($forcedLang)) !== $forcedLang ) { return $truncated; @@ -75,14 +75,14 @@ class LanguageIterator implements ILanguageIterator { /** @noinspection PhpMissingBreakStatementInspection */ case 2: $userLang = $this->config->getUserValue($this->user->getUID(), 'core', 'lang', null); - if(is_string($userLang)) { + if (is_string($userLang)) { return $userLang; } $this->next(); /** @noinspection PhpMissingBreakStatementInspection */ case 3: $userLang = $this->config->getUserValue($this->user->getUID(), 'core', 'lang', null); - if(is_string($userLang) + if (is_string($userLang) && ($truncated = $this->getTruncatedLanguage($userLang)) !== $userLang ) { return $truncated; @@ -93,7 +93,7 @@ class LanguageIterator implements ILanguageIterator { /** @noinspection PhpMissingBreakStatementInspection */ case 5: $defaultLang = $this->config->getSystemValue('default_language', 'en'); - if(($truncated = $this->getTruncatedLanguage($defaultLang)) !== $defaultLang) { + if (($truncated = $this->getTruncatedLanguage($defaultLang)) !== $defaultLang) { return $truncated; } $this->next(); @@ -131,7 +131,7 @@ class LanguageIterator implements ILanguageIterator { protected function getTruncatedLanguage(string $lang):string { $pos = strpos($lang, '_'); - if($pos !== false) { + if ($pos !== false) { $lang = substr($lang, 0, $pos); } return $lang; diff --git a/lib/private/L10N/LanguageNotFoundException.php b/lib/private/L10N/LanguageNotFoundException.php index b7c407f6ee9..20b22a8b5ec 100644 --- a/lib/private/L10N/LanguageNotFoundException.php +++ b/lib/private/L10N/LanguageNotFoundException.php @@ -24,5 +24,4 @@ namespace OC\L10N; class LanguageNotFoundException extends \Exception { - } diff --git a/lib/private/L10N/LazyL10N.php b/lib/private/L10N/LazyL10N.php index 2b47de55dd9..9ffcb4df98f 100644 --- a/lib/private/L10N/LazyL10N.php +++ b/lib/private/L10N/LazyL10N.php @@ -68,5 +68,4 @@ class LazyL10N implements IL10N { public function getLocaleCode(): string { return $this->getL()->getLocaleCode(); } - } diff --git a/lib/private/LargeFileHelper.php b/lib/private/LargeFileHelper.php index 603fe7e461f..c24657a5c9c 100755 --- a/lib/private/LargeFileHelper.php +++ b/lib/private/LargeFileHelper.php @@ -201,8 +201,6 @@ class LargeFileHelper { } } return $result; - - } protected function exec($cmd) { diff --git a/lib/private/Lockdown/Filesystem/NullCache.php b/lib/private/Lockdown/Filesystem/NullCache.php index 83b0d744913..396bf68d5df 100644 --- a/lib/private/Lockdown/Filesystem/NullCache.php +++ b/lib/private/Lockdown/Filesystem/NullCache.php @@ -122,5 +122,4 @@ class NullCache implements ICache { public function normalize($path) { return $path; } - } diff --git a/lib/private/Log.php b/lib/private/Log.php index d288e724179..2048d60a53b 100644 --- a/lib/private/Log.php +++ b/lib/private/Log.php @@ -373,7 +373,7 @@ class Log implements ILogger, IDataLogger { } public function getLogPath():string { - if($this->logger instanceof IFileBased) { + if ($this->logger instanceof IFileBased) { return $this->logger->getLogFilePath(); } throw new \RuntimeException('Log implementation has no path'); diff --git a/lib/private/Log/ErrorHandler.php b/lib/private/Log/ErrorHandler.php index 2d2cf7abd67..d37af8212a0 100644 --- a/lib/private/Log/ErrorHandler.php +++ b/lib/private/Log/ErrorHandler.php @@ -63,7 +63,7 @@ class ErrorHandler { //Fatal errors handler public static function onShutdown() { $error = error_get_last(); - if($error && self::$logger) { + if ($error && self::$logger) { //ob_end_clean(); $msg = $error['message'] . ' at ' . $error['file'] . '#' . $error['line']; self::$logger->critical(self::removePassword($msg), ['app' => 'PHP']); @@ -89,14 +89,11 @@ class ErrorHandler { } $msg = $message . ' at ' . $file . '#' . $line; self::$logger->error(self::removePassword($msg), ['app' => 'PHP']); - } //Recoverable handler which catch all errors, warnings and notices public static function onAll($number, $message, $file, $line) { $msg = $message . ' at ' . $file . '#' . $line; self::$logger->debug(self::removePassword($msg), ['app' => 'PHP']); - } - } diff --git a/lib/private/Log/File.php b/lib/private/Log/File.php index 57b4e9353ef..6be200f6d3e 100644 --- a/lib/private/Log/File.php +++ b/lib/private/Log/File.php @@ -59,7 +59,7 @@ class File extends LogDetails implements IWriter, IFileBased { parent::__construct($config); $this->logFile = $path; if (!file_exists($this->logFile)) { - if( + if ( ( !is_writable(dirname($this->logFile)) || !touch($this->logFile) diff --git a/lib/private/Log/LogDetails.php b/lib/private/Log/LogDetails.php index 5ed486195cf..dcaa5919d73 100644 --- a/lib/private/Log/LogDetails.php +++ b/lib/private/Log/LogDetails.php @@ -58,7 +58,7 @@ abstract class LogDetails { $time = $time->format($format); $url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--'; $method = is_string($request->getMethod()) ? $request->getMethod() : '--'; - if($this->config->getValue('installed', false)) { + if ($this->config->getValue('installed', false)) { $user = \OC_User::getUser() ? \OC_User::getUser() : '--'; } else { $user = '--'; @@ -82,7 +82,7 @@ abstract class LogDetails { 'version' ); - if(is_array($message) && !array_key_exists('Exception', $message)) { + if (is_array($message) && !array_key_exists('Exception', $message)) { // Exception messages should stay as they are, // anything else modern is split to 'message' (string) and // data (array) fields @@ -99,10 +99,10 @@ abstract class LogDetails { // PHP's json_encode only accept proper UTF-8 strings, loop over all // elements to ensure that they are properly UTF-8 compliant or convert // them manually. - foreach($entry as $key => $value) { - if(is_string($value)) { + foreach ($entry as $key => $value) { + if (is_string($value)) { $testEncode = json_encode($value, JSON_UNESCAPED_SLASHES); - if($testEncode === false) { + if ($testEncode === false) { $entry[$key] = utf8_encode($value); } } diff --git a/lib/private/Log/LogFactory.php b/lib/private/Log/LogFactory.php index 901ff382d8b..9a55b155f39 100644 --- a/lib/private/Log/LogFactory.php +++ b/lib/private/Log/LogFactory.php @@ -71,7 +71,7 @@ class LogFactory implements ILogFactory { protected function buildLogFile(string $logFile = ''):File { $defaultLogFile = $this->systemConfig->getValue('datadirectory', \OC::$SERVERROOT.'/data').'/nextcloud.log'; - if($logFile === '') { + if ($logFile === '') { $logFile = $this->systemConfig->getValue('logfile', $defaultLogFile); } $fallback = $defaultLogFile !== $logFile ? $defaultLogFile : ''; diff --git a/lib/private/Log/PsrLoggerAdapter.php b/lib/private/Log/PsrLoggerAdapter.php index 4bfd9a2a246..bdaeda9f129 100644 --- a/lib/private/Log/PsrLoggerAdapter.php +++ b/lib/private/Log/PsrLoggerAdapter.php @@ -162,5 +162,4 @@ final class PsrLoggerAdapter implements LoggerInterface { } $this->logger->log($level, $message, $context); } - } diff --git a/lib/private/Log/Rotate.php b/lib/private/Log/Rotate.php index a5fc7d5a0cd..8cafc6e639c 100644 --- a/lib/private/Log/Rotate.php +++ b/lib/private/Log/Rotate.php @@ -41,7 +41,7 @@ class Rotate extends \OC\BackgroundJob\Job { $this->filePath = $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', \OC::$SERVERROOT . '/data') . '/nextcloud.log'); $this->maxSize = \OC::$server->getConfig()->getSystemValue('log_rotate_size', 100 * 1024 * 1024); - if($this->shouldRotateBySize()) { + if ($this->shouldRotateBySize()) { $rotatedFile = $this->rotate(); $msg = 'Log file "'.$this->filePath.'" was over '.$this->maxSize.' bytes, moved to "'.$rotatedFile.'"'; \OC::$server->getLogger()->warning($msg, ['app' => Rotate::class]); diff --git a/lib/private/Log/Systemdlog.php b/lib/private/Log/Systemdlog.php index e74cab40fd6..692af7d8ecf 100644 --- a/lib/private/Log/Systemdlog.php +++ b/lib/private/Log/Systemdlog.php @@ -58,11 +58,10 @@ class Systemdlog extends LogDetails implements IWriter { public function __construct(SystemConfig $config) { parent::__construct($config); - if(!function_exists('sd_journal_send')) { + if (!function_exists('sd_journal_send')) { throw new HintException( 'PHP extension php-systemd is not available.', 'Please install and enable PHP extension systemd if you wish to log to the Systemd journal.'); - } $this->syslogId = $config->getValue('syslog_tag', 'Nextcloud'); } diff --git a/lib/private/Mail/Attachment.php b/lib/private/Mail/Attachment.php index 3f80b065d5a..1f88c875565 100644 --- a/lib/private/Mail/Attachment.php +++ b/lib/private/Mail/Attachment.php @@ -80,5 +80,4 @@ class Attachment implements IAttachment { public function getSwiftAttachment(): \Swift_Mime_Attachment { return $this->swiftAttachment; } - } diff --git a/lib/private/Mail/EMailTemplate.php b/lib/private/Mail/EMailTemplate.php index c3da61c707b..9e2f099259c 100644 --- a/lib/private/Mail/EMailTemplate.php +++ b/lib/private/Mail/EMailTemplate.php @@ -191,7 +191,7 @@ EOF; </table> EOF; - // note: listBegin (like bodyBegin) is not processed through sprintf, so "%" is not escaped as "%%". (bug #12151) + // note: listBegin (like bodyBegin) is not processed through sprintf, so "%" is not escaped as "%%". (bug #12151) protected $listBegin = <<<EOF <table class="row description" style="border-collapse:collapse;border-spacing:0;display:table;padding:0;position:relative;text-align:left;vertical-align:top;width:100%"> <tbody> @@ -550,7 +550,6 @@ EOF; $this->htmlBody .= vsprintf($this->buttonGroup, [$color, $color, $urlLeft, $color, $textColor, $textColor, $textLeft, $urlRight, $textRight]); $this->plainBody .= $plainTextLeft . ': ' . $urlLeft . PHP_EOL; $this->plainBody .= $plainTextRight . ': ' . $urlRight . PHP_EOL . PHP_EOL; - } /** @@ -585,7 +584,6 @@ EOF; } $this->plainBody .= $url . PHP_EOL; - } /** @@ -608,7 +606,7 @@ EOF; * @param string $text If the text is empty the default "Name - Slogan<br>This is an automatically sent email" will be used */ public function addFooter(string $text = '') { - if($text === '') { + if ($text === '') { $text = $this->themingDefaults->getName() . ' - ' . $this->themingDefaults->getSlogan() . '<br>' . $this->l10n->t('This is an automatically sent email, please do not reply.'); } diff --git a/lib/private/Mail/Mailer.php b/lib/private/Mail/Mailer.php index c07556b6a62..57778e263d7 100644 --- a/lib/private/Mail/Mailer.php +++ b/lib/private/Mail/Mailer.php @@ -186,7 +186,7 @@ class Mailer implements IMailer { $mailer = $this->getInstance(); // Enable logger if debug mode is enabled - if($debugMode) { + if ($debugMode) { $mailLogger = new \Swift_Plugins_Loggers_ArrayLogger(); $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($mailLogger)); } @@ -199,7 +199,7 @@ class Mailer implements IMailer { // Debugging logging $logMessage = sprintf('Sent mail to "%s" with subject "%s"', print_r($message->getTo(), true), $message->getSubject()); $this->logger->debug($logMessage, ['app' => 'core']); - if($debugMode && isset($mailLogger)) { + if ($debugMode && isset($mailLogger)) { $this->logger->debug($mailLogger->dump(), ['app' => 'core']); } diff --git a/lib/private/Mail/Message.php b/lib/private/Mail/Message.php index e5a31b5cbe1..c8c48518d52 100644 --- a/lib/private/Mail/Message.php +++ b/lib/private/Mail/Message.php @@ -77,8 +77,8 @@ class Message implements IMessage { $convertedAddresses = []; - foreach($addresses as $email => $readableName) { - if(!is_numeric($email)) { + foreach ($addresses as $email => $readableName) { + if (!is_numeric($email)) { list($name, $domain) = explode('@', $email, 2); $domain = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); $convertedAddresses[$name.'@'.$domain] = $readableName; diff --git a/lib/private/Memcache/APCu.php b/lib/private/Memcache/APCu.php index e1aec896db2..3523ea2a86b 100644 --- a/lib/private/Memcache/APCu.php +++ b/lib/private/Memcache/APCu.php @@ -59,7 +59,7 @@ class APCu extends Cache implements IMemcache { public function clear($prefix = '') { $ns = $this->getPrefix() . $prefix; $ns = preg_quote($ns, '/'); - if(class_exists('\APCIterator')) { + if (class_exists('\APCIterator')) { $iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY); } else { $iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY); diff --git a/lib/private/Memcache/Factory.php b/lib/private/Memcache/Factory.php index 675c1088dee..0e6552ba436 100644 --- a/lib/private/Memcache/Factory.php +++ b/lib/private/Memcache/Factory.php @@ -71,8 +71,7 @@ class Factory implements ICacheFactory { * @param string|null $lockingCacheClass */ public function __construct(string $globalPrefix, ILogger $logger, - $localCacheClass = null, $distributedCacheClass = null, $lockingCacheClass = null) - { + $localCacheClass = null, $distributedCacheClass = null, $lockingCacheClass = null) { $this->logger = $logger; $this->globalPrefix = $globalPrefix; diff --git a/lib/private/MemoryInfo.php b/lib/private/MemoryInfo.php index 37bf98fef59..520225fc6d1 100644 --- a/lib/private/MemoryInfo.php +++ b/lib/private/MemoryInfo.php @@ -30,7 +30,6 @@ namespace OC; * Helper class that covers memory info. */ class MemoryInfo { - const RECOMMENDED_MEMORY_LIMIT = 512 * 1024 * 1024; /** @@ -70,7 +69,7 @@ class MemoryInfo { $memoryLimit = (int)substr($memoryLimit, 0, -1); // intended fall trough - switch($last) { + switch ($last) { case 'g': $memoryLimit *= 1024; case 'm': diff --git a/lib/private/NaturalSort.php b/lib/private/NaturalSort.php index aefa5d5a92a..31829a84e6a 100644 --- a/lib/private/NaturalSort.php +++ b/lib/private/NaturalSort.php @@ -91,8 +91,7 @@ class NaturalSort { // German umlauts, so using en_US instead if (class_exists('Collator')) { $this->collator = new \Collator('en_US'); - } - else { + } else { $this->collator = new \OC\NaturalSort_DefaultCollator(); } } diff --git a/lib/private/NavigationManager.php b/lib/private/NavigationManager.php index b71e194398f..b40f403c056 100644 --- a/lib/private/NavigationManager.php +++ b/lib/private/NavigationManager.php @@ -93,13 +93,13 @@ class NavigationManager implements INavigationManager { } $entry['active'] = false; - if(!isset($entry['icon'])) { + if (!isset($entry['icon'])) { $entry['icon'] = ''; } - if(!isset($entry['classes'])) { + if (!isset($entry['classes'])) { $entry['classes'] = ''; } - if(!isset($entry['type'])) { + if (!isset($entry['type'])) { $entry['type'] = 'link'; } $this->entries[$entry['id']] = $entry; @@ -231,7 +231,7 @@ class NavigationManager implements INavigationManager { ]); $logoutUrl = \OC_User::getLogoutUrl($this->urlGenerator); - if($logoutUrl !== '') { + if ($logoutUrl !== '') { // Logout $this->add([ 'type' => 'settings', diff --git a/lib/private/OCS/DiscoveryService.php b/lib/private/OCS/DiscoveryService.php index caad064a48b..d30cf1d980c 100644 --- a/lib/private/OCS/DiscoveryService.php +++ b/lib/private/OCS/DiscoveryService.php @@ -85,7 +85,7 @@ class DiscoveryService implements IDiscoveryService { 'timeout' => 10, 'connect_timeout' => 10, ]); - if($response->getStatusCode() === Http::STATUS_OK) { + if ($response->getStatusCode() === Http::STATUS_OK) { $decodedServices = json_decode($response->getBody(), true); if (\is_array($decodedServices)) { $discoveredServices = $this->getEndpoints($decodedServices, $service); @@ -108,12 +108,11 @@ class DiscoveryService implements IDiscoveryService { * @return array */ protected function getEndpoints(array $decodedServices, string $service): array { - $discoveredServices = []; - if(isset($decodedServices['services'][$service]['endpoints'])) { + if (isset($decodedServices['services'][$service]['endpoints'])) { foreach ($decodedServices['services'][$service]['endpoints'] as $endpoint => $url) { - if($this->isSafeUrl($url)) { + if ($this->isSafeUrl($url)) { $discoveredServices[$endpoint] = $url; } } @@ -132,5 +131,4 @@ class DiscoveryService implements IDiscoveryService { protected function isSafeUrl(string $url): bool { return (bool)preg_match('/^[\/\.\-A-Za-z0-9]+$/', $url); } - } diff --git a/lib/private/OCS/Exception.php b/lib/private/OCS/Exception.php index 704b9160f32..63a7bdb54ea 100644 --- a/lib/private/OCS/Exception.php +++ b/lib/private/OCS/Exception.php @@ -36,5 +36,4 @@ class Exception extends \Exception { public function getResult() { return $this->result; } - } diff --git a/lib/private/OCS/Provider.php b/lib/private/OCS/Provider.php index f4322d23028..33386c0e946 100644 --- a/lib/private/OCS/Provider.php +++ b/lib/private/OCS/Provider.php @@ -55,7 +55,7 @@ class Provider extends \OCP\AppFramework\Controller { ], ]; - if($this->appManager->isEnabledForUser('files_sharing')) { + if ($this->appManager->isEnabledForUser('files_sharing')) { $services['SHARING'] = [ 'version' => 1, 'endpoints' => [ @@ -88,7 +88,7 @@ class Provider extends \OCP\AppFramework\Controller { } } - if($this->appManager->isEnabledForUser('activity')) { + if ($this->appManager->isEnabledForUser('activity')) { $services['ACTIVITY'] = [ 'version' => 1, 'endpoints' => [ @@ -97,7 +97,7 @@ class Provider extends \OCP\AppFramework\Controller { ]; } - if($this->appManager->isEnabledForUser('provisioning_api')) { + if ($this->appManager->isEnabledForUser('provisioning_api')) { $services['PROVISIONING'] = [ 'version' => 1, 'endpoints' => [ diff --git a/lib/private/OCS/Result.php b/lib/private/OCS/Result.php index b16d83e0410..0199783b47d 100644 --- a/lib/private/OCS/Result.php +++ b/lib/private/OCS/Result.php @@ -104,14 +104,13 @@ class Result { $meta['status'] = $this->succeeded() ? 'ok' : 'failure'; $meta['statuscode'] = $this->statusCode; $meta['message'] = $this->message; - if(isset($this->items)) { + if (isset($this->items)) { $meta['totalitems'] = $this->items; } - if(isset($this->perPage)) { + if (isset($this->perPage)) { $meta['itemsperpage'] = $this->perPage; } return $meta; - } /** @@ -141,7 +140,7 @@ class Result { // to be able to reliably check for security // headers - if(is_null($value)) { + if (is_null($value)) { unset($this->headers[$name]); } else { $this->headers[$name] = $value; @@ -157,5 +156,4 @@ class Result { public function getHeaders() { return $this->headers; } - } diff --git a/lib/private/Preview/Bitmap.php b/lib/private/Preview/Bitmap.php index fccb176c737..7322e07ab34 100644 --- a/lib/private/Preview/Bitmap.php +++ b/lib/private/Preview/Bitmap.php @@ -43,7 +43,6 @@ abstract class Bitmap extends ProviderV2 { * {@inheritDoc} */ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { - $tmpPath = $this->getLocalFile($file); // Creates \Imagick object from bitmap or vector file @@ -117,5 +116,4 @@ abstract class Bitmap extends ProviderV2 { return $bp; } - } diff --git a/lib/private/Preview/Bundled.php b/lib/private/Preview/Bundled.php index afd286d895b..4e89682dc6c 100644 --- a/lib/private/Preview/Bundled.php +++ b/lib/private/Preview/Bundled.php @@ -31,7 +31,6 @@ use OCP\IImage; * Extracts a preview from files that embed them in an ZIP archive */ abstract class Bundled extends ProviderV2 { - protected function extractThumbnail(File $file, $path): ?IImage { $sourceTmp = \OC::$server->getTempManager()->getTemporaryFile(); $targetTmp = \OC::$server->getTempManager()->getTemporaryFile(); @@ -52,5 +51,4 @@ abstract class Bundled extends ProviderV2 { return null; } } - } diff --git a/lib/private/Preview/HEIC.php b/lib/private/Preview/HEIC.php index 166e1cc3074..c2b9b541ad3 100644 --- a/lib/private/Preview/HEIC.php +++ b/lib/private/Preview/HEIC.php @@ -141,5 +141,4 @@ class HEIC extends ProviderV2 { return $bp; } - } diff --git a/lib/private/Preview/Image.php b/lib/private/Preview/Image.php index 3180ee853ec..eea471a2356 100644 --- a/lib/private/Preview/Image.php +++ b/lib/private/Preview/Image.php @@ -61,5 +61,4 @@ abstract class Image extends ProviderV2 { } return null; } - } diff --git a/lib/private/Preview/MP3.php b/lib/private/Preview/MP3.php index db06733a892..0986cf8c5c3 100644 --- a/lib/private/Preview/MP3.php +++ b/lib/private/Preview/MP3.php @@ -51,11 +51,11 @@ class MP3 extends ProviderV2 { $tags = $getID3->analyze($tmpPath); $this->cleanTmpFiles(); $picture = isset($tags['id3v2']['APIC'][0]['data']) ? $tags['id3v2']['APIC'][0]['data'] : null; - if(is_null($picture) && isset($tags['id3v2']['PIC'][0]['data'])) { + if (is_null($picture) && isset($tags['id3v2']['PIC'][0]['data'])) { $picture = $tags['id3v2']['PIC'][0]['data']; } - if(!is_null($picture)) { + if (!is_null($picture)) { $image = new \OC_Image(); $image->loadFromData($picture); diff --git a/lib/private/Preview/MarkDown.php b/lib/private/Preview/MarkDown.php index 0cf096148e5..91e276eb170 100644 --- a/lib/private/Preview/MarkDown.php +++ b/lib/private/Preview/MarkDown.php @@ -31,5 +31,4 @@ class MarkDown extends TXT { public function getMimeType(): string { return '/text\/(x-)?markdown/'; } - } diff --git a/lib/private/Preview/Office.php b/lib/private/Preview/Office.php index bdf8c528135..6719aeace8f 100644 --- a/lib/private/Preview/Office.php +++ b/lib/private/Preview/Office.php @@ -86,7 +86,6 @@ abstract class Office extends ProviderV2 { return $image; } return null; - } private function initCmd() { diff --git a/lib/private/Preview/ProviderV1Adapter.php b/lib/private/Preview/ProviderV1Adapter.php index 645905517cb..f09b0f47583 100644 --- a/lib/private/Preview/ProviderV1Adapter.php +++ b/lib/private/Preview/ProviderV1Adapter.php @@ -61,5 +61,4 @@ class ProviderV1Adapter implements IProviderV2 { return [$view, $path]; } - } diff --git a/lib/private/Preview/TXT.php b/lib/private/Preview/TXT.php index 3090446ac4d..d116726c683 100644 --- a/lib/private/Preview/TXT.php +++ b/lib/private/Preview/TXT.php @@ -61,7 +61,7 @@ class TXT extends ProviderV2 { $content = stream_get_contents($content,3000); //don't create previews of empty text files - if(trim($content) === '') { + if (trim($content) === '') { return null; } @@ -81,7 +81,7 @@ class TXT extends ProviderV2 { $canUseTTF = function_exists('imagettftext'); - foreach($lines as $index => $line) { + foreach ($lines as $index => $line) { $index = $index + 1; $x = (int) 1; @@ -94,7 +94,7 @@ class TXT extends ProviderV2 { imagestring($image, 1, $x, $y, $line, $textColor); } - if(($index * $lineSize) >= $maxY) { + if (($index * $lineSize) >= $maxY) { break; } } diff --git a/lib/private/PreviewManager.php b/lib/private/PreviewManager.php index adfc04199e3..b71865de545 100644 --- a/lib/private/PreviewManager.php +++ b/lib/private/PreviewManager.php @@ -229,7 +229,7 @@ class PreviewManager implements IPreview { } $mount = $file->getMountPoint(); - if ($mount and !$mount->getOption('previews', true)){ + if ($mount and !$mount->getOption('previews', true)) { return false; } diff --git a/lib/private/RedisFactory.php b/lib/private/RedisFactory.php index 9aa822c40c8..cd3ab39bdd7 100644 --- a/lib/private/RedisFactory.php +++ b/lib/private/RedisFactory.php @@ -68,7 +68,6 @@ class RedisFactory { $this->instance->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, $config['failover_mode']); } } else { - $this->instance = new \Redis(); $config = $this->config->getValue('redis', []); if (isset($config['host'])) { diff --git a/lib/private/Remote/Api/NotFoundException.php b/lib/private/Remote/Api/NotFoundException.php index 51ecfabd402..fadf4a4d324 100644 --- a/lib/private/Remote/Api/NotFoundException.php +++ b/lib/private/Remote/Api/NotFoundException.php @@ -24,5 +24,4 @@ namespace OC\Remote\Api; class NotFoundException extends \Exception { - } diff --git a/lib/private/Repair/ClearGeneratedAvatarCache.php b/lib/private/Repair/ClearGeneratedAvatarCache.php index 656dbcafaca..44a390d66a1 100644 --- a/lib/private/Repair/ClearGeneratedAvatarCache.php +++ b/lib/private/Repair/ClearGeneratedAvatarCache.php @@ -66,7 +66,6 @@ class ClearGeneratedAvatarCache implements IRepairStep { } catch (\Exception $e) { $output->warning('Unable to clear the avatar cache'); } - } } } diff --git a/lib/private/Repair/MoveUpdaterStepFile.php b/lib/private/Repair/MoveUpdaterStepFile.php index 481cff47e15..6be54bbb576 100644 --- a/lib/private/Repair/MoveUpdaterStepFile.php +++ b/lib/private/Repair/MoveUpdaterStepFile.php @@ -43,24 +43,23 @@ class MoveUpdaterStepFile implements IRepairStep { } public function run(IOutput $output) { - $dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data'); $instanceId = $this->config->getSystemValue('instanceid', null); - if(!is_string($instanceId) || empty($instanceId)) { + if (!is_string($instanceId) || empty($instanceId)) { return; } $updaterFolderPath = $dataDir . '/updater-' . $instanceId; $stepFile = $updaterFolderPath . '/.step'; - if(file_exists($stepFile)) { + if (file_exists($stepFile)) { $output->info('.step file exists'); $previousStepFile = $updaterFolderPath . '/.step-previous-update'; // cleanup - if(file_exists($previousStepFile)) { - if(\OC_Helper::rmdirr($previousStepFile)) { + if (file_exists($previousStepFile)) { + if (\OC_Helper::rmdirr($previousStepFile)) { $output->info('.step-previous-update removed'); } else { $output->info('.step-previous-update can\'t be removed - abort move of .step file'); @@ -69,7 +68,7 @@ class MoveUpdaterStepFile implements IRepairStep { } // move step file - if(rename($stepFile, $previousStepFile)) { + if (rename($stepFile, $previousStepFile)) { $output->info('.step file moved to .step-previous-update'); } else { $output->warning('.step file can\'t be moved'); diff --git a/lib/private/Repair/NC13/AddLogRotateJob.php b/lib/private/Repair/NC13/AddLogRotateJob.php index ceef8d0c7ee..7bd290894a4 100644 --- a/lib/private/Repair/NC13/AddLogRotateJob.php +++ b/lib/private/Repair/NC13/AddLogRotateJob.php @@ -44,5 +44,4 @@ class AddLogRotateJob implements IRepairStep { public function run(IOutput $output) { $this->jobList->add(Rotate::class); } - } diff --git a/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php b/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php index f76e106dfac..f2958de5b96 100644 --- a/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php +++ b/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php @@ -47,5 +47,4 @@ class AddPreviewBackgroundCleanupJob implements IRepairStep { public function run(IOutput $output) { $this->jobList->add(BackgroundCleanupJob::class); } - } diff --git a/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php b/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php index 5b8712fff85..34afd5dea60 100644 --- a/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php +++ b/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php @@ -47,5 +47,4 @@ class AddClenupLoginFlowV2BackgroundJob implements IRepairStep { public function run(IOutput $output) { $this->jobList->add(CleanupLoginFlowV2::class); } - } diff --git a/lib/private/Repair/Owncloud/SaveAccountsTableData.php b/lib/private/Repair/Owncloud/SaveAccountsTableData.php index 12515f2e882..6dd49e6c9fd 100644 --- a/lib/private/Repair/Owncloud/SaveAccountsTableData.php +++ b/lib/private/Repair/Owncloud/SaveAccountsTableData.php @@ -35,7 +35,6 @@ use OCP\PreConditionNotMetException; * before the data structure is changed and the information is gone */ class SaveAccountsTableData implements IRepairStep { - const BATCH_SIZE = 75; /** @var IDBConnection */ @@ -186,6 +185,5 @@ class SaveAccountsTableData implements IRepairStep { ->setParameter('userid', $userdata['user_id']); $update->execute(); } - } } diff --git a/lib/private/Repair/RemoveLinkShares.php b/lib/private/Repair/RemoveLinkShares.php index 580c9567f34..319fb80277c 100644 --- a/lib/private/Repair/RemoveLinkShares.php +++ b/lib/private/Repair/RemoveLinkShares.php @@ -210,7 +210,7 @@ class RemoveLinkShares implements IRepairStep { $output->startProgress($total); $shareCursor = $this->getShares(); - while($data = $shareCursor->fetch()) { + while ($data = $shareCursor->fetch()) { $this->processShare($data); $output->advance(); } diff --git a/lib/private/Repair/RepairInvalidShares.php b/lib/private/Repair/RepairInvalidShares.php index cb71bef9ffa..becf8ba7594 100644 --- a/lib/private/Repair/RepairInvalidShares.php +++ b/lib/private/Repair/RepairInvalidShares.php @@ -32,7 +32,6 @@ use OCP\Migration\IRepairStep; * Repairs shares with invalid data */ class RepairInvalidShares implements IRepairStep { - const CHUNK_SIZE = 200; /** @var \OCP\IConfig */ diff --git a/lib/private/Repair/RepairMimeTypes.php b/lib/private/Repair/RepairMimeTypes.php index 67dd1ca971d..b6b6ceed104 100644 --- a/lib/private/Repair/RepairMimeTypes.php +++ b/lib/private/Repair/RepairMimeTypes.php @@ -195,7 +195,6 @@ class RepairMimeTypes implements IRepairStep { * Fix mime types */ public function run(IOutput $out) { - $ocVersionFromBeforeUpdate = $this->config->getSystemValue('version', '0.0.0'); // NOTE TO DEVELOPERS: when adding new mime types, please make sure to diff --git a/lib/private/Route/Router.php b/lib/private/Route/Router.php index b125fd60164..ccb1578f8d3 100644 --- a/lib/private/Route/Router.php +++ b/lib/private/Route/Router.php @@ -73,7 +73,7 @@ class Router implements IRouter { public function __construct(ILogger $logger) { $this->logger = $logger; $baseUrl = \OC::$WEBROOT; - if(!(\OC::$server->getConfig()->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true')) { + if (!(\OC::$server->getConfig()->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true')) { $baseUrl = \OC::$server->getURLGenerator()->linkTo('', 'index.php'); } if (!\OC::$CLI && isset($_SERVER['REQUEST_METHOD'])) { @@ -99,7 +99,7 @@ class Router implements IRouter { $this->routingFiles = []; foreach (\OC_APP::getEnabledApps() as $app) { $appPath = \OC_App::getAppPath($app); - if($appPath !== false) { + if ($appPath !== false) { $file = $appPath . '/appinfo/routes.php'; if (file_exists($file)) { $this->routingFiles[$app] = $file; @@ -116,7 +116,7 @@ class Router implements IRouter { * @param null|string $app */ public function loadRoutes($app = null) { - if(is_string($app)) { + if (is_string($app)) { $app = \OC_App::cleanAppId($app); } diff --git a/lib/private/Search.php b/lib/private/Search.php index f58822d68f6..ae22a6d9f19 100644 --- a/lib/private/Search.php +++ b/lib/private/Search.php @@ -36,7 +36,6 @@ use OCP\Search\Provider; * Provide an interface to all search providers */ class Search implements ISearch { - private $providers = []; private $registeredProviders = []; @@ -51,7 +50,7 @@ class Search implements ISearch { public function searchPaged($query, array $inApps = [], $page = 1, $size = 30) { $this->initProviders(); $results = []; - foreach($this->providers as $provider) { + foreach ($this->providers as $provider) { /** @var $provider Provider */ if (! $provider->providesResultsFor($inApps)) { continue; @@ -109,14 +108,13 @@ class Search implements ISearch { * Create instances of all the registered search providers */ private function initProviders() { - if(! empty($this->providers)) { + if (! empty($this->providers)) { return; } - foreach($this->registeredProviders as $provider) { + foreach ($this->registeredProviders as $provider) { $class = $provider['class']; $options = $provider['options']; $this->providers[] = new $class($options); } } - } diff --git a/lib/private/Search/Provider/File.php b/lib/private/Search/Provider/File.php index 734878be982..02521460d8c 100644 --- a/lib/private/Search/Provider/File.php +++ b/lib/private/Search/Provider/File.php @@ -54,19 +54,19 @@ class File extends \OCP\Search\Provider { continue; } // create audio result - if($fileData['mimepart'] === 'audio'){ + if ($fileData['mimepart'] === 'audio') { $result = new \OC\Search\Result\Audio($fileData); } // create image result - elseif($fileData['mimepart'] === 'image'){ + elseif ($fileData['mimepart'] === 'image') { $result = new \OC\Search\Result\Image($fileData); } // create folder result - elseif($fileData['mimetype'] === 'httpd/unix-directory'){ + elseif ($fileData['mimetype'] === 'httpd/unix-directory') { $result = new \OC\Search\Result\Folder($fileData); } // or create file result - else{ + else { $result = new \OC\Search\Result\File($fileData); } // add to results @@ -75,5 +75,4 @@ class File extends \OCP\Search\Provider { // return return $results; } - } diff --git a/lib/private/Search/Result/File.php b/lib/private/Search/Result/File.php index cd605c49821..b0f6b3df622 100644 --- a/lib/private/Search/Result/File.php +++ b/lib/private/Search/Result/File.php @@ -75,7 +75,6 @@ class File extends \OCP\Search\Result { * @param FileInfo $data file data given by provider */ public function __construct(FileInfo $data) { - $path = $this->getRelativePath($data->getPath()); $info = pathinfo($path); @@ -113,5 +112,4 @@ class File extends \OCP\Search\Result { } return self::$userFolderCache->getRelativePath($path); } - } diff --git a/lib/private/Search/Result/Folder.php b/lib/private/Search/Result/Folder.php index 0a746221ee0..aa166cff8fc 100644 --- a/lib/private/Search/Result/Folder.php +++ b/lib/private/Search/Result/Folder.php @@ -34,5 +34,4 @@ class Folder extends File { * @var string */ public $type = 'folder'; - } diff --git a/lib/private/Security/Bruteforce/Throttler.php b/lib/private/Security/Bruteforce/Throttler.php index d8e06032ef1..c04e0e1b383 100644 --- a/lib/private/Security/Bruteforce/Throttler.php +++ b/lib/private/Security/Bruteforce/Throttler.php @@ -100,7 +100,7 @@ class Throttler { $ip, array $metadata = []) { // No need to log if the bruteforce protection is disabled - if($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) { + if ($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) { return; } @@ -126,7 +126,7 @@ class Throttler { $qb = $this->db->getQueryBuilder(); $qb->insert('bruteforce_attempts'); - foreach($values as $column => $value) { + foreach ($values as $column => $value) { $qb->setValue($column, $qb->createNamedParameter($value)); } $qb->execute(); @@ -139,7 +139,7 @@ class Throttler { * @return bool */ private function isIPWhitelisted($ip) { - if($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) { + if ($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) { return true; } @@ -175,7 +175,7 @@ class Throttler { $addr = inet_pton($addr); $valid = true; - for($i = 0; $i < $mask; $i++) { + for ($i = 0; $i < $mask; $i++) { $part = ord($addr[(int)($i/8)]); $orig = ord($ip[(int)($i/8)]); @@ -196,7 +196,6 @@ class Throttler { } return false; - } /** @@ -234,7 +233,7 @@ class Throttler { $maxDelay = 25; $firstDelay = 0.1; - if ($attempts > (8 * PHP_INT_SIZE - 1)) { + if ($attempts > (8 * PHP_INT_SIZE - 1)) { // Don't ever overflow. Just assume the maxDelay time:s $firstDelay = $maxDelay; } else { diff --git a/lib/private/Security/CSP/ContentSecurityPolicy.php b/lib/private/Security/CSP/ContentSecurityPolicy.php index 4db1314e782..4d41bd56206 100644 --- a/lib/private/Security/CSP/ContentSecurityPolicy.php +++ b/lib/private/Security/CSP/ContentSecurityPolicy.php @@ -245,5 +245,4 @@ class ContentSecurityPolicy extends \OCP\AppFramework\Http\ContentSecurityPolicy public function setReportTo(array $reportTo) { $this->reportTo = $reportTo; } - } diff --git a/lib/private/Security/CSP/ContentSecurityPolicyManager.php b/lib/private/Security/CSP/ContentSecurityPolicyManager.php index 9f1a480ccce..4245fdcb2de 100644 --- a/lib/private/Security/CSP/ContentSecurityPolicyManager.php +++ b/lib/private/Security/CSP/ContentSecurityPolicyManager.php @@ -59,7 +59,7 @@ class ContentSecurityPolicyManager implements IContentSecurityPolicyManager { $this->dispatcher->dispatch(AddContentSecurityPolicyEvent::class, $event); $defaultPolicy = new \OC\Security\CSP\ContentSecurityPolicy(); - foreach($this->policies as $policy) { + foreach ($this->policies as $policy) { $defaultPolicy = $this->mergePolicies($defaultPolicy, $policy); } return $defaultPolicy; @@ -74,9 +74,9 @@ class ContentSecurityPolicyManager implements IContentSecurityPolicyManager { */ public function mergePolicies(ContentSecurityPolicy $defaultPolicy, EmptyContentSecurityPolicy $originalPolicy): ContentSecurityPolicy { - foreach((object)(array)$originalPolicy as $name => $value) { + foreach ((object)(array)$originalPolicy as $name => $value) { $setter = 'set'.ucfirst($name); - if(\is_array($value)) { + if (\is_array($value)) { $getter = 'get'.ucfirst($name); $currentValues = \is_array($defaultPolicy->$getter()) ? $defaultPolicy->$getter() : []; $defaultPolicy->$setter(array_values(array_unique(array_merge($currentValues, $value)))); diff --git a/lib/private/Security/CSP/ContentSecurityPolicyNonceManager.php b/lib/private/Security/CSP/ContentSecurityPolicyNonceManager.php index 9dec2907b2f..06f8faece13 100644 --- a/lib/private/Security/CSP/ContentSecurityPolicyNonceManager.php +++ b/lib/private/Security/CSP/ContentSecurityPolicyNonceManager.php @@ -61,7 +61,7 @@ class ContentSecurityPolicyNonceManager { * @return string */ public function getNonce(): string { - if($this->nonce === '') { + if ($this->nonce === '') { if (empty($this->request->server['CSP_NONCE'])) { $this->nonce = base64_encode($this->csrfTokenManager->getToken()->getEncryptedValue()); } else { @@ -86,7 +86,7 @@ class ContentSecurityPolicyNonceManager { '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/(?:1[2-9]|[2-9][0-9])\.[0-9]+(?:\.[0-9]+)? Safari\/[0-9.A-Z]+$/', ]; - if($this->request->isUserAgent($browserWhitelist)) { + if ($this->request->isUserAgent($browserWhitelist)) { return true; } diff --git a/lib/private/Security/CSRF/CsrfToken.php b/lib/private/Security/CSRF/CsrfToken.php index 9b6b249e20f..a0ecdbd1008 100644 --- a/lib/private/Security/CSRF/CsrfToken.php +++ b/lib/private/Security/CSRF/CsrfToken.php @@ -55,7 +55,7 @@ class CsrfToken { * @return string */ public function getEncryptedValue(): string { - if($this->encryptedValue === '') { + if ($this->encryptedValue === '') { $sharedSecret = random_bytes(\strlen($this->value)); $this->encryptedValue = base64_encode($this->value ^ $sharedSecret) . ':' . base64_encode($sharedSecret); } diff --git a/lib/private/Security/CSRF/CsrfTokenManager.php b/lib/private/Security/CSRF/CsrfTokenManager.php index 8314639e8ef..2f64aeb24f4 100644 --- a/lib/private/Security/CSRF/CsrfTokenManager.php +++ b/lib/private/Security/CSRF/CsrfTokenManager.php @@ -57,11 +57,11 @@ class CsrfTokenManager { * @return CsrfToken */ public function getToken(): CsrfToken { - if(!\is_null($this->csrfToken)) { + if (!\is_null($this->csrfToken)) { return $this->csrfToken; } - if($this->sessionStorage->hasToken()) { + if ($this->sessionStorage->hasToken()) { $value = $this->sessionStorage->getToken(); } else { $value = $this->tokenGenerator->generateToken(); @@ -99,7 +99,7 @@ class CsrfTokenManager { * @return bool */ public function isTokenValid(CsrfToken $token): bool { - if(!$this->sessionStorage->hasToken()) { + if (!$this->sessionStorage->hasToken()) { return false; } diff --git a/lib/private/Security/CSRF/TokenStorage/SessionStorage.php b/lib/private/Security/CSRF/TokenStorage/SessionStorage.php index d73c8d94206..34adc566bf7 100644 --- a/lib/private/Security/CSRF/TokenStorage/SessionStorage.php +++ b/lib/private/Security/CSRF/TokenStorage/SessionStorage.php @@ -60,7 +60,7 @@ class SessionStorage { */ public function getToken(): string { $token = $this->session->get('requesttoken'); - if(empty($token)) { + if (empty($token)) { throw new \Exception('Session does not contain a requesttoken'); } diff --git a/lib/private/Security/Certificate.php b/lib/private/Security/Certificate.php index 5e6c425dbf7..cc4baeaa658 100644 --- a/lib/private/Security/Certificate.php +++ b/lib/private/Security/Certificate.php @@ -54,12 +54,12 @@ class Certificate implements ICertificate { // If string starts with "file://" ignore the certificate $query = 'file://'; - if(strtolower(substr($data, 0, strlen($query))) === $query) { + if (strtolower(substr($data, 0, strlen($query))) === $query) { throw new \Exception('Certificate could not get parsed.'); } $info = openssl_x509_parse($data); - if(!is_array($info)) { + if (!is_array($info)) { throw new \Exception('Certificate could not get parsed.'); } diff --git a/lib/private/Security/CertificateManager.php b/lib/private/Security/CertificateManager.php index 86df38625e0..e69132ff4df 100644 --- a/lib/private/Security/CertificateManager.php +++ b/lib/private/Security/CertificateManager.php @@ -87,7 +87,6 @@ class CertificateManager implements ICertificateManager { * @return \OCP\ICertificate[] */ public function listCertificates() { - if (!$this->config->getSystemValue('installed', false)) { return []; } @@ -187,7 +186,6 @@ class CertificateManager implements ICertificateManager { } catch (\Exception $e) { throw $e; } - } /** @@ -287,5 +285,4 @@ class CertificateManager implements ICertificateManager { protected function getFilemtimeOfCaBundle() { return filemtime(\OC::$SERVERROOT . '/resources/config/ca-bundle.crt'); } - } diff --git a/lib/private/Security/CredentialsManager.php b/lib/private/Security/CredentialsManager.php index 0120f69e431..ab06a807613 100644 --- a/lib/private/Security/CredentialsManager.php +++ b/lib/private/Security/CredentialsManager.php @@ -33,7 +33,6 @@ use OCP\Security\ICrypto; * @package OC\Security */ class CredentialsManager implements ICredentialsManager { - const DB_TABLE = 'credentials'; /** @var ICrypto */ @@ -122,5 +121,4 @@ class CredentialsManager implements ICredentialsManager { ; return $qb->execute(); } - } diff --git a/lib/private/Security/Crypto.php b/lib/private/Security/Crypto.php index ca17b6e2b8a..19258d2018e 100644 --- a/lib/private/Security/Crypto.php +++ b/lib/private/Security/Crypto.php @@ -70,7 +70,7 @@ class Crypto implements ICrypto { * @return string Calculated HMAC */ public function calculateHMAC(string $message, string $password = ''): string { - if($password === '') { + if ($password === '') { $password = $this->config->getSystemValue('secret'); } @@ -89,7 +89,7 @@ class Crypto implements ICrypto { * @return string Authenticated ciphertext */ public function encrypt(string $plaintext, string $password = ''): string { - if($password === '') { + if ($password === '') { $password = $this->config->getSystemValue('secret'); } $this->cipher->setPassword($password); @@ -139,5 +139,4 @@ class Crypto implements ICrypto { return $result; } - } diff --git a/lib/private/Security/FeaturePolicy/FeaturePolicy.php b/lib/private/Security/FeaturePolicy/FeaturePolicy.php index b59d873b533..93556708789 100644 --- a/lib/private/Security/FeaturePolicy/FeaturePolicy.php +++ b/lib/private/Security/FeaturePolicy/FeaturePolicy.php @@ -27,7 +27,6 @@ declare(strict_types=1); namespace OC\Security\FeaturePolicy; class FeaturePolicy extends \OCP\AppFramework\Http\FeaturePolicy { - public function getAutoplayDomains(): array { return $this->autoplayDomains; } diff --git a/lib/private/Security/Hasher.php b/lib/private/Security/Hasher.php index 9850dbe1467..8c081414353 100644 --- a/lib/private/Security/Hasher.php +++ b/lib/private/Security/Hasher.php @@ -79,7 +79,7 @@ class Hasher implements IHasher { } $hashingCost = $this->config->getSystemValue('hashingCost', null); - if(!\is_null($hashingCost)) { + if (!\is_null($hashingCost)) { $this->options['cost'] = $hashingCost; } } @@ -113,8 +113,8 @@ class Hasher implements IHasher { */ protected function splitHash(string $prefixedHash) { $explodedString = explode('|', $prefixedHash, 2); - if(\count($explodedString) === 2) { - if((int)$explodedString[0] > 0) { + if (\count($explodedString) === 2) { + if ((int)$explodedString[0] > 0) { return ['version' => (int)$explodedString[0], 'hash' => $explodedString[1]]; } } @@ -130,13 +130,13 @@ class Hasher implements IHasher { * @return bool Whether $hash is a valid hash of $message */ protected function legacyHashVerify($message, $hash, &$newHash = null): bool { - if(empty($this->legacySalt)) { + if (empty($this->legacySalt)) { $this->legacySalt = $this->config->getSystemValue('passwordsalt', ''); } // Verify whether it matches a legacy PHPass or SHA1 string $hashLength = \strlen($hash); - if(($hashLength === 60 && password_verify($message.$this->legacySalt, $hash)) || + if (($hashLength === 60 && password_verify($message.$this->legacySalt, $hash)) || ($hashLength === 40 && hash_equals($hash, sha1($message)))) { $newHash = $this->hash($message); return true; @@ -155,7 +155,7 @@ class Hasher implements IHasher { * @return bool Whether $hash is a valid hash of $message */ protected function verifyHash(string $message, string $hash, &$newHash = null): bool { - if(password_verify($message, $hash)) { + if (password_verify($message, $hash)) { if ($this->needsRehash($hash)) { $newHash = $this->hash($message); } @@ -174,7 +174,7 @@ class Hasher implements IHasher { public function verify(string $message, string $hash, &$newHash = null): bool { $splittedHash = $this->splitHash($hash); - if(isset($splittedHash['version'])) { + if (isset($splittedHash['version'])) { switch ($splittedHash['version']) { case 3: case 2: @@ -211,5 +211,4 @@ class Hasher implements IHasher { return $default; } - } diff --git a/lib/private/Security/IdentityProof/Manager.php b/lib/private/Security/IdentityProof/Manager.php index 2c101769f18..abbda2f11eb 100644 --- a/lib/private/Security/IdentityProof/Manager.php +++ b/lib/private/Security/IdentityProof/Manager.php @@ -104,7 +104,8 @@ class Manager { // Write the private and public key to the disk try { $this->appData->newFolder($id); - } catch (\Exception $e) {} + } catch (\Exception $e) { + } $folder = $this->appData->getFolder($id); $folder->newFile('private') ->putContent($this->crypto->encrypt($privateKey)); @@ -167,6 +168,4 @@ class Manager { } $this->logger->critical('Something is wrong with your openssl setup: ' . implode(', ', $errors)); } - - } diff --git a/lib/private/Security/IdentityProof/Signer.php b/lib/private/Security/IdentityProof/Signer.php index c5410397a27..9f6b27d358f 100644 --- a/lib/private/Security/IdentityProof/Signer.php +++ b/lib/private/Security/IdentityProof/Signer.php @@ -83,7 +83,7 @@ class Signer { * @return bool */ public function verify(array $data): bool { - if(isset($data['message']) + if (isset($data['message']) && isset($data['signature']) && isset($data['message']['signer']) ) { @@ -91,7 +91,7 @@ class Signer { $userId = substr($data['message']['signer'], 0, $location); $user = $this->userManager->get($userId); - if($user !== null) { + if ($user !== null) { $key = $this->keyManager->getKey($user); return (bool)openssl_verify( json_encode($data['message']), diff --git a/lib/private/Security/RateLimiting/Backend/MemoryCache.php b/lib/private/Security/RateLimiting/Backend/MemoryCache.php index 2d4ff9812f5..ce8bacfb588 100644 --- a/lib/private/Security/RateLimiting/Backend/MemoryCache.php +++ b/lib/private/Security/RateLimiting/Backend/MemoryCache.php @@ -75,7 +75,7 @@ class MemoryCache implements IBackend { } $cachedAttempts = json_decode($cachedAttempts, true); - if(\is_array($cachedAttempts)) { + if (\is_array($cachedAttempts)) { return $cachedAttempts; } @@ -95,7 +95,7 @@ class MemoryCache implements IBackend { $currentTime = $this->timeFactory->getTime(); /** @var array $existingAttempts */ foreach ($existingAttempts as $attempt) { - if(($attempt + $seconds) > $currentTime) { + if (($attempt + $seconds) > $currentTime) { $count++; } } @@ -115,7 +115,7 @@ class MemoryCache implements IBackend { // Unset all attempts older than $period foreach ($existingAttempts as $key => $attempt) { - if(($attempt + $period) < $currentTime) { + if (($attempt + $period) < $currentTime) { unset($existingAttempts[$key]); } } diff --git a/lib/private/Security/SecureRandom.php b/lib/private/Security/SecureRandom.php index 0e3411f8ab6..4826399ff5b 100644 --- a/lib/private/Security/SecureRandom.php +++ b/lib/private/Security/SecureRandom.php @@ -51,7 +51,7 @@ class SecureRandom implements ISecureRandom { $maxCharIndex = \strlen($characters) - 1; $randomString = ''; - while($length > 0) { + while ($length > 0) { $randomNumber = \random_int(0, $maxCharIndex); $randomString .= $characters[$randomNumber]; $length--; diff --git a/lib/private/Security/TrustedDomainHelper.php b/lib/private/Security/TrustedDomainHelper.php index c1789da6ad7..320646e1b7f 100644 --- a/lib/private/Security/TrustedDomainHelper.php +++ b/lib/private/Security/TrustedDomainHelper.php @@ -98,7 +98,9 @@ class TrustedDomainHelper { if (gettype($trusted) !== 'string') { break; } - $regex = '/^' . implode('[-\.a-zA-Z0-9]*', array_map(function ($v) { return preg_quote($v, '/'); }, explode('*', $trusted))) . '$/i'; + $regex = '/^' . implode('[-\.a-zA-Z0-9]*', array_map(function ($v) { + return preg_quote($v, '/'); + }, explode('*', $trusted))) . '$/i'; if (preg_match($regex, $domain) || preg_match($regex, $domainWithPort)) { return true; } diff --git a/lib/private/Server.php b/lib/private/Server.php index 026dcdf9a85..629673418f7 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -651,7 +651,6 @@ class Server extends ServerContainer implements IServerContainer { $this->registerDeprecatedAlias('UserCache', ICache::class); $this->registerService(Factory::class, function (Server $c) { - $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(), ArrayCache::class, ArrayCache::class, @@ -673,7 +672,6 @@ class Server extends ServerContainer implements IServerContainer { ); } return $arrayCacheFactory; - }); $this->registerDeprecatedAlias('MemCacheFactory', Factory::class); $this->registerAlias(ICacheFactory::class, Factory::class); @@ -1088,7 +1086,7 @@ class Server extends ServerContainer implements IServerContainer { $manager->registerDisplayNameResolver('user', function ($id) use ($c) { $manager = $c->getUserManager(); $user = $manager->get($id); - if(is_null($user)) { + if (is_null($user)) { $l = $c->getL10N('core'); $displayName = $l->t('Unknown user'); } else { diff --git a/lib/private/ServerNotAvailableException.php b/lib/private/ServerNotAvailableException.php index 1dd93aefb20..d0618883107 100644 --- a/lib/private/ServerNotAvailableException.php +++ b/lib/private/ServerNotAvailableException.php @@ -23,5 +23,4 @@ namespace OC; class ServerNotAvailableException extends \Exception { - } diff --git a/lib/private/Session/CryptoSessionData.php b/lib/private/Session/CryptoSessionData.php index da9bf950ba2..892c2436040 100644 --- a/lib/private/Session/CryptoSessionData.php +++ b/lib/private/Session/CryptoSessionData.php @@ -72,7 +72,7 @@ class CryptoSessionData implements \ArrayAccess, ISession { public function __destruct() { try { $this->close(); - } catch (SessionNotAvailableException $e){ + } catch (SessionNotAvailableException $e) { // This exception can occur if session is already closed // So it is safe to ignore it and let the garbage collector to proceed } @@ -108,7 +108,7 @@ class CryptoSessionData implements \ArrayAccess, ISession { * @return string|null Either the value or null */ public function get(string $key) { - if(isset($this->sessionValues[$key])) { + if (isset($this->sessionValues[$key])) { return $this->sessionValues[$key]; } @@ -175,7 +175,7 @@ class CryptoSessionData implements \ArrayAccess, ISession { * Close the session and release the lock, also writes all changed data in batch */ public function close() { - if($this->isModified) { + if ($this->isModified) { $encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase); $this->session->set(self::encryptedSessionName, $encryptedValue); $this->isModified = false; diff --git a/lib/private/Session/CryptoWrapper.php b/lib/private/Session/CryptoWrapper.php index b9dbc90edd6..bb82652a01d 100644 --- a/lib/private/Session/CryptoWrapper.php +++ b/lib/private/Session/CryptoWrapper.php @@ -83,7 +83,7 @@ class CryptoWrapper { // FIXME: Required for CI if (!defined('PHPUNIT_RUN')) { $webRoot = \OC::$WEBROOT; - if($webRoot === '') { + if ($webRoot === '') { $webRoot = '/'; } diff --git a/lib/private/Session/Internal.php b/lib/private/Session/Internal.php index 7990c4a7dae..ffe16537874 100644 --- a/lib/private/Session/Internal.php +++ b/lib/private/Session/Internal.php @@ -203,12 +203,12 @@ class Internal extends Session { */ private function invoke(string $functionName, array $parameters = [], bool $silence = false) { try { - if($silence) { + if ($silence) { return @call_user_func_array($functionName, $parameters); } else { return call_user_func_array($functionName, $parameters); } - } catch(\Error $e) { + } catch (\Error $e) { $this->trapError($e->getCode(), $e->getMessage()); } } diff --git a/lib/private/Session/Memory.php b/lib/private/Session/Memory.php index a7b1cd07ead..abbf026899b 100644 --- a/lib/private/Session/Memory.php +++ b/lib/private/Session/Memory.php @@ -94,7 +94,8 @@ class Memory extends Session { * * @param bool $deleteOldSession */ - public function regenerateId(bool $deleteOldSession = true, bool $updateToken = false) {} + public function regenerateId(bool $deleteOldSession = true, bool $updateToken = false) { + } /** * Wrapper around session_id diff --git a/lib/private/Setup/AbstractDatabase.php b/lib/private/Setup/AbstractDatabase.php index d509a6b8722..649afbe27cb 100644 --- a/lib/private/Setup/AbstractDatabase.php +++ b/lib/private/Setup/AbstractDatabase.php @@ -69,14 +69,14 @@ abstract class AbstractDatabase { public function validate($config) { $errors = []; - if(empty($config['dbuser']) && empty($config['dbname'])) { + if (empty($config['dbuser']) && empty($config['dbname'])) { $errors[] = $this->trans->t("%s enter the database username and name.", [$this->dbprettyname]); - } elseif(empty($config['dbuser'])) { + } elseif (empty($config['dbuser'])) { $errors[] = $this->trans->t("%s enter the database username.", [$this->dbprettyname]); - } elseif(empty($config['dbname'])) { + } elseif (empty($config['dbname'])) { $errors[] = $this->trans->t("%s enter the database name.", [$this->dbprettyname]); } - if(substr_count($config['dbname'], '.') >= 1) { + if (substr_count($config['dbname'], '.') >= 1) { $errors[] = $this->trans->t("%s you may not use dots in the database name", [$this->dbprettyname]); } return $errors; diff --git a/lib/private/Setup/MySQL.php b/lib/private/Setup/MySQL.php index 7371c7aeab2..9d48bbca488 100644 --- a/lib/private/Setup/MySQL.php +++ b/lib/private/Setup/MySQL.php @@ -74,7 +74,7 @@ class MySQL extends AbstractDatabase { * @param \OC\DB\Connection $connection */ private function createDatabase($connection) { - try{ + try { $name = $this->dbName; $user = $this->dbUser; //we can't use OC_DB functions here because we need to connect as the administrative user. @@ -108,7 +108,7 @@ class MySQL extends AbstractDatabase { * @throws \OC\DatabaseSetupException */ private function createDBUser($connection) { - try{ + try { $name = $this->dbUser; $password = $this->dbPassword; // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one, @@ -125,8 +125,7 @@ class MySQL extends AbstractDatabase { $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'"; $connection->executeUpdate($query); } - } - catch (\Exception $ex){ + } catch (\Exception $ex) { $this->logger->logException($ex, [ 'message' => 'Database user creation failed.', 'level' => ILogger::ERROR, diff --git a/lib/private/Share/Helper.php b/lib/private/Share/Helper.php index a3b8da44c4c..ec5136040e8 100644 --- a/lib/private/Share/Helper.php +++ b/lib/private/Share/Helper.php @@ -159,7 +159,6 @@ class Helper extends \OC\Share\Constants { * @return array contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays' */ public static function getDefaultExpireSetting() { - $config = \OC::$server->getConfig(); $defaultExpireSettings = ['defaultExpireDateSet' => false]; @@ -185,7 +184,6 @@ class Helper extends \OC\Share\Constants { //$dateString = $date->format('Y-m-d') . ' 00:00:00'; return $date; - } /** @@ -196,7 +194,6 @@ class Helper extends \OC\Share\Constants { * @return mixed integer timestamp or False */ public static function calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate = null) { - $expires = false; $defaultExpires = null; diff --git a/lib/private/Share/SearchResultSorter.php b/lib/private/Share/SearchResultSorter.php index 54232b828ca..2151eb2acb6 100644 --- a/lib/private/Share/SearchResultSorter.php +++ b/lib/private/Share/SearchResultSorter.php @@ -54,8 +54,8 @@ class SearchResultSorter { * Callback function for usort. http://php.net/usort */ public function sort($a, $b) { - if(!isset($a[$this->key]) || !isset($b[$this->key])) { - if(!is_null($this->log)) { + if (!isset($a[$this->key]) || !isset($b[$this->key])) { + if (!is_null($this->log)) { $this->log->error('Sharing dialogue: cannot sort due to ' . 'missing array key', ['app' => 'core']); } @@ -66,7 +66,7 @@ class SearchResultSorter { $i = mb_strpos($nameA, $this->search, 0, $this->encoding); $j = mb_strpos($nameB, $this->search, 0, $this->encoding); - if($i === $j || $i > 0 && $j > 0) { + if ($i === $j || $i > 0 && $j > 0) { return strcmp(mb_strtolower($nameA, $this->encoding), mb_strtolower($nameB, $this->encoding)); } elseif ($i === 0) { diff --git a/lib/private/Share/Share.php b/lib/private/Share/Share.php index 319bd5bec38..8ea97cd69a7 100644 --- a/lib/private/Share/Share.php +++ b/lib/private/Share/Share.php @@ -195,7 +195,7 @@ class Share extends Constants { } //if didn't found a result than let's look for a group share. - if(empty($shares) && $user !== null) { + if (empty($shares) && $user !== null) { $userObject = \OC::$server->getUserManager()->get($user); $groups = []; if ($userObject) { @@ -229,7 +229,6 @@ class Share extends Constants { } return $shares; - } /** @@ -353,7 +352,7 @@ class Share extends Constants { // delete the item with the expected share_type and owner if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) { $toDelete = $item; - // if there is more then one result we don't have to delete the children + // if there is more then one result we don't have to delete the children // but update their parent. For group shares the new parent should always be // the original group share and not the db entry with the unique name } elseif ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) { @@ -376,7 +375,6 @@ class Share extends Constants { * @return boolean True if item was expired, false otherwise. */ protected static function expireItem(array $item) { - $result = false; // only use default expiration date for link shares @@ -414,7 +412,6 @@ class Share extends Constants { * @return null */ protected static function unshareItem(array $item, $newParent = null) { - $shareType = (int)$item['share_type']; $shareWith = null; if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) { @@ -431,7 +428,7 @@ class Share extends Constants { 'itemParent' => $item['parent'], 'uidOwner' => $item['uid_owner'], ]; - if($item['item_type'] === 'file' || $item['item_type'] === 'folder') { + if ($item['item_type'] === 'file' || $item['item_type'] === 'folder') { $hookParams['fileSource'] = $item['file_source']; $hookParams['fileTarget'] = $item['file_target']; } @@ -605,7 +602,7 @@ class Share extends Constants { // Get filesystem root to add it to the file target and remove from the // file source, match file_source with the file cache if ($itemType == 'file' || $itemType == 'folder') { - if(!is_null($uidOwner)) { + if (!is_null($uidOwner)) { $root = \OC\Files\Filesystem::getRoot(); } else { $root = ''; @@ -800,7 +797,6 @@ class Share extends Constants { $id = $row['id']; } $items[$id]['permissions'] |= (int)$row['permissions']; - } continue; } elseif (!empty($row['parent'])) { @@ -843,7 +839,7 @@ class Share extends Constants { } } - if($checkExpireDate) { + if ($checkExpireDate) { if (self::expireItem($row)) { continue; } @@ -858,7 +854,7 @@ class Share extends Constants { $row['share_type'] === self::SHARE_TYPE_USER) { $shareWithUser = \OC::$server->getUserManager()->get($row['share_with']); $row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName(); - } elseif(isset($row['share_with']) && $row['share_with'] != '' && + } elseif (isset($row['share_with']) && $row['share_with'] != '' && $row['share_type'] === self::SHARE_TYPE_REMOTE) { $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']); foreach ($addressBookEntries as $entry) { @@ -877,7 +873,6 @@ class Share extends Constants { if ($row['permissions'] > 0) { $items[$row['id']] = $row; } - } // group items if we are looking for items shared with the current user @@ -1007,7 +1002,6 @@ class Share extends Constants { * @return array of grouped items */ protected static function groupItems($items, $itemType) { - $fileSharing = $itemType === 'file' || $itemType === 'folder'; $result = []; @@ -1034,7 +1028,6 @@ class Share extends Constants { if (!$grouped) { $result[] = $item; } - } return $result; @@ -1056,14 +1049,13 @@ class Share extends Constants { */ private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions) { - $queriesToExecute = []; $suggestedItemTarget = null; $groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = ''; $groupItemTarget = $itemTarget = $fileSource = $parent = 0; $result = self::checkReshare('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions, null, null); - if(!empty($result)) { + if (!empty($result)) { $parent = $result['parent']; $itemSource = $result['itemSource']; $fileSource = $result['fileSource']; @@ -1073,8 +1065,8 @@ class Share extends Constants { } $isGroupShare = false; - $users = [$shareWith]; - $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, + $users = [$shareWith]; + $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $suggestedItemTarget); $run = true; @@ -1110,18 +1102,15 @@ class Share extends Constants { if ($sourceExists && $sourceExists['item_source'] === $itemSource) { $fileTarget = $sourceExists['file_target']; $itemTarget = $sourceExists['item_target']; - - } elseif(!$sourceExists) { - + } elseif (!$sourceExists) { $itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user, $uidOwner, $suggestedItemTarget, $parent); if (isset($fileSource)) { - $fileTarget = Helper::generateTarget('file', $filePath, $userShareType, + $fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user, $uidOwner, $suggestedFileTarget, $parent); } else { $fileTarget = null; } - } else { // group share which doesn't exists until now, check if we need a unique target for this user @@ -1158,7 +1147,6 @@ class Share extends Constants { 'parent' => $parent, 'expiration' => null, ]; - } $id = false; @@ -1232,7 +1220,7 @@ class Share extends Constants { $result['expirationDate'] = $expirationDate; // $checkReshare['expiration'] could be null and then is always less than any value - if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) { + if (isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) { $result['expirationDate'] = $checkReshare['expiration']; } @@ -1269,8 +1257,8 @@ class Share extends Constants { } if ($backend instanceof \OCP\Share_Backend_File_Dependent) { $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner); - $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']); - $result['fileSource'] = $meta['fileid']; + $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']); + $result['fileSource'] = $meta['fileid']; if ($result['fileSource'] == -1) { $message = 'Sharing %s failed, because the file could not be found in the file cache'; throw new \Exception(sprintf($message, $itemSource)); @@ -1290,7 +1278,6 @@ class Share extends Constants { * @return mixed false in case of a failure or the id of the new share */ private static function insertShare(array $shareData) { - $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (' .' `item_type`, `item_source`, `item_target`, `share_type`,' .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,' @@ -1316,7 +1303,6 @@ class Share extends Constants { } return $id; - } /** diff --git a/lib/private/Share20/DefaultShareProvider.php b/lib/private/Share20/DefaultShareProvider.php index ad002a1fc96..41a727593b3 100644 --- a/lib/private/Share20/DefaultShareProvider.php +++ b/lib/private/Share20/DefaultShareProvider.php @@ -249,7 +249,6 @@ class DefaultShareProvider implements IShareProvider { * @throws \OCP\Files\NotFoundException */ public function update(\OCP\Share\IShare $share) { - $originalShare = $this->getShareById($share->getId()); if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { @@ -306,7 +305,6 @@ class DefaultShareProvider implements IShareProvider { ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0))) ->set('permissions', $qb->createNamedParameter($share->getPermissions())) ->execute(); - } elseif ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { $qb = $this->dbConn->getQueryBuilder(); $qb->update('share') @@ -380,7 +378,6 @@ class DefaultShareProvider implements IShareProvider { } else { $id = $data['id']; } - } elseif ($share->getShareType() === IShare::TYPE_USER) { if ($share->getSharedWith() !== $recipient) { throw new ProviderException('Recipient does not match'); @@ -431,7 +428,7 @@ class DefaultShareProvider implements IShareProvider { ->orderBy('id'); $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $children[] = $this->createShare($data); } $cursor->closeCursor(); @@ -471,7 +468,6 @@ class DefaultShareProvider implements IShareProvider { */ public function deleteFromSelf(IShare $share, $recipient) { if ($share->getShareType() === IShare::TYPE_GROUP) { - $group = $this->groupManager->get($share->getSharedWith()); $user = $this->userManager->get($recipient); @@ -518,9 +514,7 @@ class DefaultShareProvider implements IShareProvider { ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))) ->execute(); } - } elseif ($share->getShareType() === IShare::TYPE_USER) { - if ($share->getSharedWith() !== $recipient) { throw new ProviderException('Recipient does not match'); } @@ -600,7 +594,6 @@ class DefaultShareProvider implements IShareProvider { ->set('file_target', $qb->createNamedParameter($share->getTarget())) ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))) ->execute(); - } elseif ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { // Check if there is a usergroup share @@ -737,7 +730,7 @@ class DefaultShareProvider implements IShareProvider { $cursor = $qb->execute(); $shares = []; - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $shares[] = $this->createShare($data); } $cursor->closeCursor(); @@ -816,7 +809,7 @@ class DefaultShareProvider implements IShareProvider { ->execute(); $shares = []; - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $shares[] = $this->createShare($data); } $cursor->closeCursor(); @@ -887,13 +880,12 @@ class DefaultShareProvider implements IShareProvider { $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { if ($this->isAccessibleResult($data)) { $shares[] = $this->createShare($data); } } $cursor->closeCursor(); - } elseif ($shareType === \OCP\Share::SHARE_TYPE_GROUP) { $user = $this->userManager->get($userId); $allGroups = $this->groupManager->getUserGroups($user); @@ -902,7 +894,7 @@ class DefaultShareProvider implements IShareProvider { $shares2 = []; $start = 0; - while(true) { + while (true) { $groups = array_slice($allGroups, $start, 100); $start += 100; @@ -933,8 +925,12 @@ class DefaultShareProvider implements IShareProvider { } - $groups = array_filter($groups, function ($group) { return $group instanceof IGroup; }); - $groups = array_map(function (IGroup $group) { return $group->getGID(); }, $groups); + $groups = array_filter($groups, function ($group) { + return $group instanceof IGroup; + }); + $groups = array_map(function (IGroup $group) { + return $group->getGID(); + }, $groups); $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))) ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter( @@ -947,7 +943,7 @@ class DefaultShareProvider implements IShareProvider { )); $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { if ($offset > 0) { $offset--; continue; @@ -1077,7 +1073,7 @@ class DefaultShareProvider implements IShareProvider { $result = []; $start = 0; - while(true) { + while (true) { /** @var Share[] $shareSlice */ $shareSlice = array_slice($shares, $start, 100); $start += 100; @@ -1109,7 +1105,7 @@ class DefaultShareProvider implements IShareProvider { $stmt = $query->execute(); - while($data = $stmt->fetch()) { + while ($data = $stmt->fetch()) { $shareMap[$data['parent']]->setPermissions((int)$data['permissions']); $shareMap[$data['parent']]->setStatus((int)$data['accepted']); $shareMap[$data['parent']]->setTarget($data['file_target']); @@ -1212,7 +1208,7 @@ class DefaultShareProvider implements IShareProvider { $cursor = $qb->execute(); $ids = []; - while($row = $cursor->fetch()) { + while ($row = $cursor->fetch()) { $ids[] = (int)$row['id']; } $cursor->closeCursor(); @@ -1255,7 +1251,7 @@ class DefaultShareProvider implements IShareProvider { $cursor = $qb->execute(); $ids = []; - while($row = $cursor->fetch()) { + while ($row = $cursor->fetch()) { $ids[] = (int)$row['id']; } $cursor->closeCursor(); @@ -1310,7 +1306,7 @@ class DefaultShareProvider implements IShareProvider { $users = []; $link = false; - while($row = $cursor->fetch()) { + while ($row = $cursor->fetch()) { $type = (int)$row['share_type']; if ($type === \OCP\Share::SHARE_TYPE_USER) { $uid = $row['share_with']; @@ -1411,7 +1407,6 @@ class DefaultShareProvider implements IShareProvider { * @throws \OCP\Files\NotFoundException */ private function sendNote(array $recipients, IShare $share) { - $toList = []; foreach ($recipients as $recipient) { @@ -1423,7 +1418,6 @@ class DefaultShareProvider implements IShareProvider { } if (!empty($toList)) { - $filename = $share->getNode()->getName(); $initiator = $share->getSharedBy(); $note = $share->getNote(); @@ -1475,7 +1469,6 @@ class DefaultShareProvider implements IShareProvider { $message->useTemplate($emailTemplate); $this->mailer->send($message); } - } public function getAllShares(): iterable { @@ -1492,7 +1485,7 @@ class DefaultShareProvider implements IShareProvider { ); $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { try { $share = $this->createShare($data); } catch (InvalidShare $e) { diff --git a/lib/private/Share20/Exception/BackendError.php b/lib/private/Share20/Exception/BackendError.php index b36cc1a9111..5ba17b7a458 100644 --- a/lib/private/Share20/Exception/BackendError.php +++ b/lib/private/Share20/Exception/BackendError.php @@ -23,5 +23,4 @@ namespace OC\Share20\Exception; class BackendError extends \Exception { - } diff --git a/lib/private/Share20/Exception/InvalidShare.php b/lib/private/Share20/Exception/InvalidShare.php index 908049ae75a..1216bfa9aea 100644 --- a/lib/private/Share20/Exception/InvalidShare.php +++ b/lib/private/Share20/Exception/InvalidShare.php @@ -23,5 +23,4 @@ namespace OC\Share20\Exception; class InvalidShare extends \Exception { - } diff --git a/lib/private/Share20/Exception/ProviderException.php b/lib/private/Share20/Exception/ProviderException.php index 7d3f79f7120..f60f5a8f385 100644 --- a/lib/private/Share20/Exception/ProviderException.php +++ b/lib/private/Share20/Exception/ProviderException.php @@ -23,5 +23,4 @@ namespace OC\Share20\Exception; class ProviderException extends \Exception { - } diff --git a/lib/private/Share20/LegacyHooks.php b/lib/private/Share20/LegacyHooks.php index f292499584e..1e2391f0bd0 100644 --- a/lib/private/Share20/LegacyHooks.php +++ b/lib/private/Share20/LegacyHooks.php @@ -173,6 +173,5 @@ class LegacyHooks { ]; \OC_Hook::emit(Share::class, 'post_shared', $postHookData); - } } diff --git a/lib/private/Share20/Manager.php b/lib/private/Share20/Manager.php index 7ec678b07fb..b9a97e4225f 100644 --- a/lib/private/Share20/Manager.php +++ b/lib/private/Share20/Manager.php @@ -234,7 +234,7 @@ class Manager implements IManager { if ($share->getSharedWith() === null) { throw new \InvalidArgumentException('SharedWith should not be empty'); } - } elseif ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) { + } elseif ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) { if ($share->getSharedWith() === null) { throw new \InvalidArgumentException('SharedWith should not be empty'); } @@ -442,7 +442,6 @@ class Manager implements IManager { * @throws \Exception */ protected function validateExpirationDate(\OCP\Share\IShare $share) { - $expirationDate = $share->getExpirationDate(); if ($expirationDate !== null) { @@ -532,7 +531,7 @@ class Manager implements IManager { */ $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER); $existingShares = $provider->getSharesByPath($share->getNode()); - foreach($existingShares as $existingShare) { + foreach ($existingShares as $existingShare) { // Ignore if it is the same share try { if ($existingShare->getFullId() === $share->getFullId()) { @@ -589,7 +588,7 @@ class Manager implements IManager { */ $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP); $existingShares = $provider->getSharesByPath($share->getNode()); - foreach($existingShares as $existingShare) { + foreach ($existingShares as $existingShare) { try { if ($existingShare->getFullId() === $share->getFullId()) { continue; @@ -658,7 +657,7 @@ class Manager implements IManager { // Make sure that we do not share a path that contains a shared mountpoint if ($path instanceof \OCP\Files\Folder) { $mounts = $this->mountManager->findIn($path->getPath()); - foreach($mounts as $mount) { + foreach ($mounts as $mount) { if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { throw new \InvalidArgumentException('Path contains files shared with you'); } @@ -706,7 +705,7 @@ class Manager implements IManager { $storage = $share->getNode()->getStorage(); if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { $parent = $share->getNode()->getParent(); - while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { + while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { $parent = $parent->getParent(); } $share->setShareOwner($parent->getOwner()->getUID()); @@ -720,13 +719,11 @@ class Manager implements IManager { //Verify the expiration date $share = $this->validateExpirationDateInternal($share); - } elseif ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { $this->groupCreateChecks($share); //Verify the expiration date $share = $this->validateExpirationDateInternal($share); - } elseif ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { $this->linkCreateChecks($share); $this->setLinkParent($share); @@ -797,7 +794,7 @@ class Manager implements IManager { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { $mailSend = $share->getMailSend(); - if($mailSend === true) { + if ($mailSend === true) { $user = $this->userManager->get($share->getSharedWith()); if ($user !== null) { $emailAddress = $user->getEMailAddress(); @@ -888,7 +885,7 @@ class Manager implements IManager { // 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. $initiatorEmail = $initiatorUser->getEMailAddress(); - if($initiatorEmail !== null) { + if ($initiatorEmail !== null) { $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]); $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')); } else { @@ -898,7 +895,7 @@ class Manager implements IManager { $message->useTemplate($emailTemplate); try { $failedRecipients = $this->mailer->send($message); - if(!empty($failedRecipients)) { + if (!empty($failedRecipients)) { $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients)); return; } @@ -1117,7 +1114,6 @@ class Manager implements IManager { * @throws \InvalidArgumentException */ public function deleteShare(\OCP\Share\IShare $share) { - try { $share->getFullId(); } catch (\UnexpectedValueException $e) { @@ -1238,10 +1234,9 @@ class Manager implements IManager { $shares2 = []; - while(true) { + while (true) { $added = 0; foreach ($shares as $share) { - try { $this->checkExpireDate($share); } catch (ShareNotFound $e) { @@ -1381,7 +1376,7 @@ class Manager implements IManager { } $share = null; try { - if($this->shareApiAllowLinks()) { + if ($this->shareApiAllowLinks()) { $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK); $share = $provider->getShareByToken($token); } @@ -1450,7 +1445,6 @@ class Manager implements IManager { $this->deleteShare($share); throw new ShareNotFound($this->l->t('The requested share does not exist anymore')); } - } /** diff --git a/lib/private/Share20/ProviderFactory.php b/lib/private/Share20/ProviderFactory.php index cf23779a8b9..6186d1c37cf 100644 --- a/lib/private/Share20/ProviderFactory.php +++ b/lib/private/Share20/ProviderFactory.php @@ -197,7 +197,6 @@ class ProviderFactory implements IProviderFactory { * @suppress PhanUndeclaredClassMethod */ protected function getShareByCircleProvider() { - if ($this->circlesAreNotAvailable) { return null; } @@ -210,7 +209,6 @@ class ProviderFactory implements IProviderFactory { } if ($this->shareByCircleProvider === null) { - $this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider( $this->serverContainer->getDatabaseConnection(), $this->serverContainer->getSecureRandom(), diff --git a/lib/private/Share20/Share.php b/lib/private/Share20/Share.php index b05b72e7ada..fb4fc4c4078 100644 --- a/lib/private/Share20/Share.php +++ b/lib/private/Share20/Share.php @@ -112,7 +112,7 @@ class Share implements \OCP\Share\IShare { $id = (string)$id; } - if(!is_string($id)) { + if (!is_string($id)) { throw new \InvalidArgumentException('String expected.'); } @@ -145,7 +145,7 @@ class Share implements \OCP\Share\IShare { * @inheritdoc */ public function setProviderId($id) { - if(!is_string($id)) { + if (!is_string($id)) { throw new \InvalidArgumentException('String expected.'); } @@ -172,14 +172,13 @@ class Share implements \OCP\Share\IShare { */ public function getNode() { if ($this->node === null) { - if ($this->shareOwner === null || $this->fileId === null) { throw new NotFoundException(); } // for federated shares the owner can be a remote user, in this // case we use the initiator - if($this->userManager->userExists($this->shareOwner)) { + if ($this->userManager->userExists($this->shareOwner)) { $userFolder = $this->rootFolder->getUserFolder($this->shareOwner); } else { $userFolder = $this->rootFolder->getUserFolder($this->sharedBy); diff --git a/lib/private/Streamer.php b/lib/private/Streamer.php index 7ae03532a83..f4d5cc221ac 100644 --- a/lib/private/Streamer.php +++ b/lib/private/Streamer.php @@ -117,8 +117,8 @@ class Streamer { $dirNode = $userFolder->get($dir); $files = $dirNode->getDirectoryListing(); - foreach($files as $file) { - if($file instanceof File) { + foreach ($files as $file) { + if ($file instanceof File) { try { $fh = $file->fopen('r'); } catch (NotPermittedException $e) { @@ -132,7 +132,7 @@ class Streamer { ); fclose($fh); } elseif ($file instanceof Folder) { - if($file->isReadable()) { + if ($file->isReadable()) { $this->addDirRecursive($dir . '/' . $file->getName(), $internalDir); } } diff --git a/lib/private/SubAdmin.php b/lib/private/SubAdmin.php index 8a8cbdb9813..d292e998ab9 100644 --- a/lib/private/SubAdmin.php +++ b/lib/private/SubAdmin.php @@ -118,9 +118,9 @@ class SubAdmin extends PublicEmitter implements ISubAdmin { ->execute(); $groups = []; - while($row = $result->fetch()) { + while ($row = $result->fetch()) { $group = $this->groupManager->get($row['gid']); - if(!is_null($group)) { + if (!is_null($group)) { $groups[$group->getGID()] = $group; } } @@ -154,9 +154,9 @@ class SubAdmin extends PublicEmitter implements ISubAdmin { ->execute(); $users = []; - while($row = $result->fetch()) { + while ($row = $result->fetch()) { $user = $this->userManager->get($row['uid']); - if(!is_null($user)) { + if (!is_null($user)) { $users[] = $user; } } @@ -177,10 +177,10 @@ class SubAdmin extends PublicEmitter implements ISubAdmin { ->execute(); $subadmins = []; - while($row = $result->fetch()) { + while ($row = $result->fetch()) { $user = $this->userManager->get($row['uid']); $group = $this->groupManager->get($row['gid']); - if(!is_null($user) && !is_null($group)) { + if (!is_null($user) && !is_null($group)) { $subadmins[] = [ 'user' => $user, 'group' => $group @@ -249,15 +249,15 @@ class SubAdmin extends PublicEmitter implements ISubAdmin { * @return bool */ public function isUserAccessible(IUser $subadmin, IUser $user): bool { - if(!$this->isSubAdmin($subadmin)) { + if (!$this->isSubAdmin($subadmin)) { return false; } - if($this->groupManager->isAdmin($user->getUID())) { + if ($this->groupManager->isAdmin($user->getUID())) { return false; } $accessibleGroups = $this->getSubAdminsGroups($subadmin); - foreach($accessibleGroups as $accessibleGroup) { - if($accessibleGroup->inGroup($user)) { + foreach ($accessibleGroups as $accessibleGroup) { + if ($accessibleGroup->inGroup($user)) { return true; } } diff --git a/lib/private/Support/CrashReport/Registry.php b/lib/private/Support/CrashReport/Registry.php index f81ac36a8a6..44a6d290678 100644 --- a/lib/private/Support/CrashReport/Registry.php +++ b/lib/private/Support/CrashReport/Registry.php @@ -90,5 +90,4 @@ class Registry implements IRegistry { } } } - } diff --git a/lib/private/SystemTag/SystemTagManager.php b/lib/private/SystemTag/SystemTagManager.php index 75f12e59fce..2d7b1bc3ae4 100644 --- a/lib/private/SystemTag/SystemTagManager.php +++ b/lib/private/SystemTag/SystemTagManager.php @@ -44,7 +44,6 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; * Manager class for system tags */ class SystemTagManager implements ISystemTagManager { - const TAG_TABLE = 'systemtag'; const TAG_GROUP_TABLE = 'systemtag_group'; diff --git a/lib/private/SystemTag/SystemTagObjectMapper.php b/lib/private/SystemTag/SystemTagObjectMapper.php index e9df865ee96..eb33d2d30bb 100644 --- a/lib/private/SystemTag/SystemTagObjectMapper.php +++ b/lib/private/SystemTag/SystemTagObjectMapper.php @@ -38,7 +38,6 @@ use OCP\SystemTag\TagNotFoundException; use Symfony\Component\EventDispatcher\EventDispatcherInterface; class SystemTagObjectMapper implements ISystemTagObjectMapper { - const RELATION_TABLE = 'systemtag_object_mapping'; /** @var ISystemTagManager */ diff --git a/lib/private/TagManager.php b/lib/private/TagManager.php index 52d000f8c94..ecc80b271fa 100644 --- a/lib/private/TagManager.php +++ b/lib/private/TagManager.php @@ -64,7 +64,6 @@ class TagManager implements \OCP\ITagManager { public function __construct(TagMapper $mapper, \OCP\IUserSession $userSession) { $this->mapper = $mapper; $this->userSession = $userSession; - } /** @@ -89,5 +88,4 @@ class TagManager implements \OCP\ITagManager { } return new Tags($this->mapper, $userId, $type, $defaultTags, $includeShared); } - } diff --git a/lib/private/Tagging/Tag.php b/lib/private/Tagging/Tag.php index f818a115b25..73b3f57ca15 100644 --- a/lib/private/Tagging/Tag.php +++ b/lib/private/Tagging/Tag.php @@ -37,7 +37,6 @@ use OCP\AppFramework\Db\Entity; * @method void setName(string $name) */ class Tag extends Entity { - protected $owner; protected $type; protected $name; diff --git a/lib/private/Tagging/TagMapper.php b/lib/private/Tagging/TagMapper.php index 2ffb663aeff..d9c8a7fb470 100644 --- a/lib/private/Tagging/TagMapper.php +++ b/lib/private/Tagging/TagMapper.php @@ -52,7 +52,7 @@ class TagMapper extends Mapper { * @return array An array of Tag objects. */ public function loadTags($owners, $type) { - if(!is_array($owners)) { + if (!is_array($owners)) { $owners = [$owners]; } diff --git a/lib/private/Tags.php b/lib/private/Tags.php index 4d05beb259c..a176967bd2b 100644 --- a/lib/private/Tags.php +++ b/lib/private/Tags.php @@ -136,7 +136,7 @@ class Tags implements ITags { } $this->tags = $this->mapper->loadTags($this->owners, $this->type); - if(count($defaultTags) > 0 && count($this->tags) === 0) { + if (count($defaultTags) > 0 && count($this->tags) === 0) { $this->addMultiple($defaultTags, true); } } @@ -177,7 +177,7 @@ class Tags implements ITags { * @return array */ public function getTags() { - if(!count($this->tags)) { + if (!count($this->tags)) { return []; } @@ -186,13 +186,12 @@ class Tags implements ITags { }); $tagMap = []; - foreach($this->tags as $tag) { - if($tag->getName() !== ITags::TAG_FAVORITE) { + foreach ($this->tags as $tag) { + if ($tag->getName() !== ITags::TAG_FAVORITE) { $tagMap[] = $this->tagMap($tag); } } return $tagMap; - } /** @@ -243,7 +242,7 @@ class Tags implements ITags { return false; } } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -267,18 +266,18 @@ class Tags implements ITags { public function getIdsForTag($tag) { $result = null; $tagId = false; - if(is_numeric($tag)) { + if (is_numeric($tag)) { $tagId = $tag; - } elseif(is_string($tag)) { + } elseif (is_string($tag)) { $tag = trim($tag); - if($tag === '') { + if ($tag === '') { \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG); return false; } $tagId = $this->getTagId($tag); } - if($tagId === false) { + if ($tagId === false) { $l10n = \OC::$server->getL10N('core'); throw new \Exception( $l10n->t('Could not find category "%s"', [$tag]) @@ -296,7 +295,7 @@ class Tags implements ITags { \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR); return false; } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -305,8 +304,8 @@ class Tags implements ITags { return false; } - if(!is_null($result)) { - while($row = $result->fetchRow()) { + if (!is_null($result)) { + while ($row = $result->fetchRow()) { $id = (int)$row['objid']; if ($this->includeShared) { @@ -361,11 +360,11 @@ class Tags implements ITags { public function add($name) { $name = trim($name); - if($name === '') { + if ($name === '') { \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG); return false; } - if($this->userHasTag($name, $this->user)) { + if ($this->userHasTag($name, $this->user)) { \OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', ILogger::DEBUG); return false; } @@ -373,7 +372,7 @@ class Tags implements ITags { $tag = new Tag($this->user, $this->type, $name); $tag = $this->mapper->insert($tag); $this->tags[] = $tag; - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -396,7 +395,7 @@ class Tags implements ITags { $from = trim($from); $to = trim($to); - if($to === '' || $from === '') { + if ($to === '' || $from === '') { \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG); return false; } @@ -406,13 +405,13 @@ class Tags implements ITags { } else { $key = $this->getTagByName($from); } - if($key === false) { + if ($key === false) { \OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', ILogger::DEBUG); return false; } $tag = $this->tags[$key]; - if($this->userHasTag($to, $tag->getOwner())) { + if ($this->userHasTag($to, $tag->getOwner())) { \OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', ILogger::DEBUG); return false; } @@ -420,7 +419,7 @@ class Tags implements ITags { try { $tag->setName($to); $this->tags[$key] = $this->mapper->update($tag); - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -441,24 +440,24 @@ class Tags implements ITags { * @return bool Returns false on error. */ public function addMultiple($names, $sync=false, $id = null) { - if(!is_array($names)) { + if (!is_array($names)) { $names = [$names]; } $names = array_map('trim', $names); array_filter($names); $newones = []; - foreach($names as $name) { - if(!$this->hasTag($name) && $name !== '') { + foreach ($names as $name) { + if (!$this->hasTag($name) && $name !== '') { $newones[] = new Tag($this->user, $this->type, $name); } - if(!is_null($id)) { + if (!is_null($id)) { // Insert $objectid, $categoryid pairs if not exist. self::$relations[] = ['objid' => $id, 'tag' => $name]; } } $this->tags = array_merge($this->tags, $newones); - if($sync === true) { + if ($sync === true) { $this->save(); } @@ -469,13 +468,13 @@ class Tags implements ITags { * Save the list of tags and their object relations */ protected function save() { - if(is_array($this->tags)) { - foreach($this->tags as $tag) { + if (is_array($this->tags)) { + foreach ($this->tags as $tag) { try { if (!$this->mapper->tagExists($tag)) { $this->mapper->insert($tag); } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -494,10 +493,10 @@ class Tags implements ITags { // For some reason this is needed or array_search(i) will return 0..? ksort($tags); $dbConnection = \OC::$server->getDatabaseConnection(); - foreach(self::$relations as $relation) { + foreach (self::$relations as $relation) { $tagId = $this->getTagId($relation['tag']); \OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, ILogger::DEBUG); - if($tagId) { + if ($tagId) { try { $dbConnection->insertIfNotExist(self::RELATION_TABLE, [ @@ -505,7 +504,7 @@ class Tags implements ITags { 'categoryid' => $tagId, 'type' => $this->type, ]); - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -538,7 +537,7 @@ class Tags implements ITags { if ($result === null) { \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR); } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -546,14 +545,14 @@ class Tags implements ITags { ]); } - if(!is_null($result)) { + if (!is_null($result)) { try { $stmt = \OC_DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` ' . 'WHERE `categoryid` = ?'); - while($row = $result->fetchRow()) { + while ($row = $result->fetchRow()) { try { $stmt->execute([$row['id']]); - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -561,7 +560,7 @@ class Tags implements ITags { ]); } } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -576,7 +575,7 @@ class Tags implements ITags { if ($result === null) { \OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR); } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -592,7 +591,7 @@ class Tags implements ITags { * @return boolean Returns false on error. */ public function purgeObjects(array $ids) { - if(count($ids) === 0) { + if (count($ids) === 0) { // job done ;) return true; } @@ -608,7 +607,7 @@ class Tags implements ITags { \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR); return false; } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -625,13 +624,13 @@ class Tags implements ITags { * @return array|false An array of object ids. */ public function getFavorites() { - if(!$this->userHasTag(ITags::TAG_FAVORITE, $this->user)) { + if (!$this->userHasTag(ITags::TAG_FAVORITE, $this->user)) { return []; } try { return $this->getIdsForTag(ITags::TAG_FAVORITE); - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -648,7 +647,7 @@ class Tags implements ITags { * @return boolean */ public function addToFavorites($objid) { - if(!$this->userHasTag(ITags::TAG_FAVORITE, $this->user)) { + if (!$this->userHasTag(ITags::TAG_FAVORITE, $this->user)) { $this->add(ITags::TAG_FAVORITE); } return $this->tagAs($objid, ITags::TAG_FAVORITE); @@ -672,13 +671,13 @@ class Tags implements ITags { * @return boolean Returns false on error. */ public function tagAs($objid, $tag) { - if(is_string($tag) && !is_numeric($tag)) { + if (is_string($tag) && !is_numeric($tag)) { $tag = trim($tag); - if($tag === '') { + if ($tag === '') { \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG); return false; } - if(!$this->hasTag($tag)) { + if (!$this->hasTag($tag)) { $this->add($tag); } $tagId = $this->getTagId($tag); @@ -692,7 +691,7 @@ class Tags implements ITags { 'categoryid' => $tagId, 'type' => $this->type, ]); - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -711,9 +710,9 @@ class Tags implements ITags { * @return boolean */ public function unTag($objid, $tag) { - if(is_string($tag) && !is_numeric($tag)) { + if (is_string($tag) && !is_numeric($tag)) { $tag = trim($tag); - if($tag === '') { + if ($tag === '') { \OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', ILogger::DEBUG); return false; } @@ -727,7 +726,7 @@ class Tags implements ITags { . 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?'; $stmt = \OC_DB::prepare($sql); $stmt->execute([$objid, $tagId, $this->type]); - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -745,7 +744,7 @@ class Tags implements ITags { * @return bool Returns false on error */ public function delete($names) { - if(!is_array($names)) { + if (!is_array($names)) { $names = [$names]; } @@ -754,7 +753,7 @@ class Tags implements ITags { \OCP\Util::writeLog('core', __METHOD__ . ', before: ' . print_r($this->tags, true), ILogger::DEBUG); - foreach($names as $name) { + foreach ($names as $name) { $id = null; if (is_numeric($name)) { @@ -771,7 +770,7 @@ class Tags implements ITags { \OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name . ': not found.', ILogger::ERROR); } - if(!is_null($id) && $id !== false) { + if (!is_null($id) && $id !== false) { try { $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` ' . 'WHERE `categoryid` = ?'; @@ -783,7 +782,7 @@ class Tags implements ITags { ILogger::ERROR); return false; } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -798,7 +797,7 @@ class Tags implements ITags { // case-insensitive array_search protected function array_searchi($needle, $haystack, $mem='getName') { - if(!is_array($haystack)) { + if (!is_array($haystack)) { return false; } return array_search(strtolower($needle), array_map( diff --git a/lib/private/TempManager.php b/lib/private/TempManager.php index cb5f51582ac..13735d69d47 100644 --- a/lib/private/TempManager.php +++ b/lib/private/TempManager.php @@ -66,7 +66,7 @@ class TempManager implements ITempManager { * @return string */ private function buildFileNameWithSuffix($absolutePath, $postFix = '') { - if($postFix !== '') { + if ($postFix !== '') { $postFix = '.' . ltrim($postFix, '.'); $postFix = str_replace(['\\', '/'], '', $postFix); $absolutePath .= '-'; @@ -92,7 +92,7 @@ class TempManager implements ITempManager { // If a postfix got specified sanitize it and create a postfixed // temporary file - if($postFix !== '') { + if ($postFix !== '') { $fileNameWithPostfix = $this->buildFileNameWithSuffix($file, $postFix); touch($fileNameWithPostfix); chmod($fileNameWithPostfix, 0600); @@ -276,5 +276,4 @@ class TempManager implements ITempManager { public function overrideTempBaseDir($directory) { $this->tmpBaseDir = $directory; } - } diff --git a/lib/private/Template/Base.php b/lib/private/Template/Base.php index d07cf2249f7..04d03b6e6f5 100644 --- a/lib/private/Template/Base.php +++ b/lib/private/Template/Base.php @@ -65,7 +65,7 @@ class Base { */ protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) { // Check if the app is in the app folder or in the root - if(file_exists($app_dir.'/templates/')) { + if (file_exists($app_dir.'/templates/')) { return [ $serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/', $app_dir.'/templates/', @@ -115,10 +115,9 @@ class Base { * $_[$key][$position] in the template. */ public function append($key, $value) { - if(array_key_exists($key, $this->vars)) { + if (array_key_exists($key, $this->vars)) { $this->vars[$key][] = $value; - } - else{ + } else { $this->vars[$key] = [ $value ]; } } @@ -131,10 +130,9 @@ class Base { */ public function printPage() { $data = $this->fetchPage(); - if($data === false) { + if ($data === false) { return false; - } - else{ + } else { print $data; return true; } @@ -167,7 +165,7 @@ class Base { $l = $this->l10n; $theme = $this->theme; - if(!is_null($additionalParams)) { + if (!is_null($additionalParams)) { $_ = array_merge($additionalParams, $this->vars); foreach ($_ as $var => $value) { ${$var} = $value; @@ -188,5 +186,4 @@ class Base { // Return data return $data; } - } diff --git a/lib/private/Template/CSSResourceLocator.php b/lib/private/Template/CSSResourceLocator.php index c931a62420a..750d33fd726 100644 --- a/lib/private/Template/CSSResourceLocator.php +++ b/lib/private/Template/CSSResourceLocator.php @@ -83,7 +83,7 @@ class CSSResourceLocator extends ResourceLocator { // turned into cwd. $app_path = realpath($app_path); - if(!$this->cacheAndAppendScssIfExist($app_path, $style.'.scss', $app)) { + if (!$this->cacheAndAppendScssIfExist($app_path, $style.'.scss', $app)) { $this->append($app_path, $style.'.css', $app_url); } } @@ -107,9 +107,8 @@ class CSSResourceLocator extends ResourceLocator { */ protected function cacheAndAppendScssIfExist($root, $file, $app = 'core') { if (is_file($root.'/'.$file)) { - if($this->scssCacher !== null) { - if($this->scssCacher->process($root, $file, $app)) { - + if ($this->scssCacher !== null) { + if ($this->scssCacher->process($root, $file, $app)) { $this->append($root, $this->scssCacher->getCachedSCSS($app, $file), \OC::$WEBROOT, true, true); return true; } else { diff --git a/lib/private/Template/IconsCacher.php b/lib/private/Template/IconsCacher.php index 3315f29d98f..00654b5f8fc 100644 --- a/lib/private/Template/IconsCacher.php +++ b/lib/private/Template/IconsCacher.php @@ -107,7 +107,6 @@ class IconsCacher { * @throws \OCP\Files\NotPermittedException */ public function setIconsCss(string $css): string { - $cachedFile = $this->getCachedList(); if (!$cachedFile) { $currentData = ''; @@ -169,14 +168,13 @@ class IconsCacher { $location = \OC::$SERVERROOT . '/core/img/' . $cleanUrl . '.svg'; } } elseif (\strpos($url, $base) === 0) { - if(\preg_match('/([A-z0-9\_\-]+)\/([a-zA-Z0-9-_\~\/\.\=\:\;\+\,]+)\?color=([0-9a-fA-F]{3,6})/', $cleanUrl, $matches)) { + if (\preg_match('/([A-z0-9\_\-]+)\/([a-zA-Z0-9-_\~\/\.\=\:\;\+\,]+)\?color=([0-9a-fA-F]{3,6})/', $cleanUrl, $matches)) { list(,$app,$cleanUrl, $color) = $matches; $location = \OC_App::getAppPath($app) . '/img/' . $cleanUrl . '.svg'; if ($app === 'settings') { $location = \OC::$SERVERROOT . '/settings/img/' . $cleanUrl . '.svg'; } } - } return [ $location, @@ -265,5 +263,4 @@ class IconsCacher { $linkToCSS = $this->urlGenerator->linkToRoute('core.Css.getCss', ['appName' => 'icons', 'fileName' => $this->fileName, 'v' => $mtime]); \OC_Util::addHeader('link', ['rel' => 'stylesheet', 'href' => $linkToCSS], null, true); } - } diff --git a/lib/private/Template/JSCombiner.php b/lib/private/Template/JSCombiner.php index 96d5a1e7779..48f6dadfd6a 100644 --- a/lib/private/Template/JSCombiner.php +++ b/lib/private/Template/JSCombiner.php @@ -95,12 +95,12 @@ class JSCombiner { try { $folder = $this->appData->getFolder($app); - } catch(NotFoundException $e) { + } catch (NotFoundException $e) { // creating css appdata folder $folder = $this->appData->newFolder($app); } - if($this->isCached($fileName, $folder)) { + if ($this->isCached($fileName, $folder)) { return true; } return $this->cache($path, $fileName, $folder); @@ -145,7 +145,7 @@ class JSCombiner { } return true; - } catch(NotFoundException $e) { + } catch (NotFoundException $e) { return false; } } @@ -176,7 +176,7 @@ class JSCombiner { $fileName = str_replace('.json', '.js', $fileName); try { $cachedfile = $folder->getFile($fileName); - } catch(NotFoundException $e) { + } catch (NotFoundException $e) { $cachedfile = $folder->newFile($fileName); } @@ -228,7 +228,7 @@ class JSCombiner { public function getContent($root, $file) { /** @var array $data */ $data = json_decode(file_get_contents($root . '/' . $file)); - if(!is_array($data)) { + if (!is_array($data)) { return []; } diff --git a/lib/private/Template/JSConfigHelper.php b/lib/private/Template/JSConfigHelper.php index 24573d71fe0..70d6f73628d 100644 --- a/lib/private/Template/JSConfigHelper.php +++ b/lib/private/Template/JSConfigHelper.php @@ -113,7 +113,6 @@ class JSConfigHelper { } public function getConfig() { - $userBackendAllowsPasswordConfirmation = true; if ($this->currentUser !== null) { $uid = $this->currentUser->getUID(); @@ -137,7 +136,7 @@ class JSConfigHelper { $apps = $this->appManager->getEnabledAppsForUser($this->currentUser); } - foreach($apps as $app) { + foreach ($apps as $app) { $apps_paths[$app] = \OC_App::getAppWebPath($app); } @@ -161,7 +160,7 @@ class JSConfigHelper { $countOfDataLocation = 0; $dataLocation = str_replace(\OC::$SERVERROOT .'/', '', $this->config->getSystemValue('datadirectory', ''), $countOfDataLocation); - if($countOfDataLocation !== 1 || !$this->groupManager->isAdmin($uid)) { + if ($countOfDataLocation !== 1 || !$this->groupManager->isAdmin($uid)) { $dataLocation = false; } diff --git a/lib/private/Template/ResourceLocator.php b/lib/private/Template/ResourceLocator.php index c99df063588..1d9f60cf5dd 100755 --- a/lib/private/Template/ResourceLocator.php +++ b/lib/private/Template/ResourceLocator.php @@ -164,7 +164,6 @@ abstract class ResourceLocator { * @throws ResourceNotFoundException Only thrown when $throw is true and the resource is missing */ protected function append($root, $file, $webRoot = null, $throw = true) { - if (!is_string($root)) { if ($throw) { throw new ResourceNotFoundException($file, $webRoot); diff --git a/lib/private/Template/TemplateFileLocator.php b/lib/private/Template/TemplateFileLocator.php index afeddd6b544..3c7631ba2b5 100644 --- a/lib/private/Template/TemplateFileLocator.php +++ b/lib/private/Template/TemplateFileLocator.php @@ -46,7 +46,7 @@ class TemplateFileLocator { throw new \InvalidArgumentException('Empty template name'); } - foreach($this->dirs as $dir) { + foreach ($this->dirs as $dir) { $file = $dir.$template.'.php'; if (is_file($file)) { $this->path = $dir; diff --git a/lib/private/TemplateLayout.php b/lib/private/TemplateLayout.php index cdab4c25693..89904827b2a 100644 --- a/lib/private/TemplateLayout.php +++ b/lib/private/TemplateLayout.php @@ -52,7 +52,6 @@ use OCP\Defaults; use OCP\Support\Subscription\IRegistry; class TemplateLayout extends \OC_Template { - private static $versionHash = ''; /** @@ -69,16 +68,16 @@ class TemplateLayout extends \OC_Template { // yes - should be injected .... $this->config = \OC::$server->getConfig(); - if(\OCP\Util::isIE()) { + if (\OCP\Util::isIE()) { \OC_Util::addStyle('ie'); } // Decide which page we show - if($renderAs === 'user') { + if ($renderAs === 'user') { parent::__construct('core', 'layout.user'); - if(in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) { + if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) { $this->assign('bodyid', 'body-settings'); - }else{ + } else { $this->assign('bodyid', 'body-user'); } @@ -89,14 +88,14 @@ class TemplateLayout extends \OC_Template { $this->assign('navigation', $navigation); $settingsNavigation = \OC::$server->getNavigationManager()->getAll('settings'); $this->assign('settingsnavigation', $settingsNavigation); - foreach($navigation as $entry) { + foreach ($navigation as $entry) { if ($entry['active']) { $this->assign('application', $entry['name']); break; } } - foreach($settingsNavigation as $entry) { + foreach ($settingsNavigation as $entry) { if ($entry['active']) { $this->assign('application', $entry['name']); break; @@ -123,7 +122,6 @@ class TemplateLayout extends \OC_Template { } catch (\OCP\AutoloadNotAllowedException $e) { $this->assign('themingInvertMenu', false); } - } elseif ($renderAs === 'error') { parent::__construct('core', 'layout.guest', '', false); $this->assign('bodyid', 'body-login'); @@ -151,7 +149,6 @@ class TemplateLayout extends \OC_Template { $this->assign('showSimpleSignUpLink', $showSimpleSignup); } else { parent::__construct('core', 'layout.base'); - } // Send the language and the locale to our layouts $lang = \OC::$server->getL10NFactory()->findLanguage(); @@ -161,7 +158,7 @@ class TemplateLayout extends \OC_Template { $this->assign('language', $lang); $this->assign('locale', $locale); - if(\OC::$server->getSystemConfig()->getValue('installed', false)) { + if (\OC::$server->getSystemConfig()->getValue('installed', false)) { if (empty(self::$versionHash)) { $v = \OC_App::getAppVersions(); $v['core'] = implode('.', \OCP\Util::getVersion()); @@ -193,7 +190,7 @@ class TemplateLayout extends \OC_Template { $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash])); } } - foreach($jsFiles as $info) { + foreach ($jsFiles as $info) { $web = $info[1]; $file = $info[2]; $this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix()); @@ -207,7 +204,7 @@ class TemplateLayout extends \OC_Template { // Do not initialise scss appdata until we have a fully installed instance // Do not load scss for update, errors, installation or login page - if(\OC::$server->getSystemConfig()->getValue('installed', false) + if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade() && $pathInfo !== '' && !preg_match('/^\/login/', $pathInfo) @@ -224,7 +221,7 @@ class TemplateLayout extends \OC_Template { $this->assign('cssfiles', []); $this->assign('printcssfiles', []); $this->assign('versionHash', self::$versionHash); - foreach($cssFiles as $info) { + foreach ($cssFiles as $info) { $web = $info[1]; $file = $info[2]; @@ -238,7 +235,6 @@ class TemplateLayout extends \OC_Template { } else { $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3)); } - } } @@ -270,7 +266,7 @@ class TemplateLayout extends \OC_Template { // Try the webroot path for a match if ($path !== false && $path !== '') { $appName = $this->getAppNamefromPath($path); - if(array_key_exists($appName, $v)) { + if (array_key_exists($appName, $v)) { $appVersion = $v[$appName]; return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix; } @@ -278,7 +274,7 @@ class TemplateLayout extends \OC_Template { // fallback to the file path instead if ($file !== false && $file !== '') { $appName = $this->getAppNamefromPath($file); - if(array_key_exists($appName, $v)) { + if (array_key_exists($appName, $v)) { $appVersion = $v[$appName]; return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix; } @@ -295,7 +291,7 @@ class TemplateLayout extends \OC_Template { // Read the selected theme from the config file $theme = \OC_Util::getTheme(); - if($compileScss) { + if ($compileScss) { $SCSSCacher = \OC::$server->query(SCSSCacher::class); } else { $SCSSCacher = null; @@ -326,7 +322,6 @@ class TemplateLayout extends \OC_Template { return end($pathParts); } return false; - } /** @@ -356,7 +351,7 @@ class TemplateLayout extends \OC_Template { */ public static function convertToRelativePath($filePath) { $relativePath = explode(\OC::$SERVERROOT, $filePath); - if(count($relativePath) !== 2) { + if (count($relativePath) !== 2) { throw new \Exception('$filePath is not under the \OC::$SERVERROOT'); } diff --git a/lib/private/URLGenerator.php b/lib/private/URLGenerator.php index c0896ec3516..b432b0b69ca 100644 --- a/lib/private/URLGenerator.php +++ b/lib/private/URLGenerator.php @@ -122,12 +122,11 @@ class URLGenerator implements IURLGenerator { public function linkTo(string $app, string $file, array $args = []): string { $frontControllerActive = ($this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true'); - if($app !== '') { + if ($app !== '') { $app_path = \OC_App::getAppPath($app); // Check if the app is in the app folder if ($app_path && file_exists($app_path . '/' . $file)) { if (substr($file, -3) === 'php') { - $urlLinkTo = \OC::$WEBROOT . '/index.php/apps/' . $app; if ($frontControllerActive) { $urlLinkTo = \OC::$WEBROOT . '/apps/' . $app; @@ -170,7 +169,7 @@ class URLGenerator implements IURLGenerator { public function imagePath(string $app, string $image): string { $cache = $this->cacheFactory->createDistributed('imagePath-'.md5($this->getBaseUrl()).'-'); $cacheKey = $app.'-'.$image; - if($key = $cache->get($cacheKey)) { + if ($key = $cache->get($cacheKey)) { return $key; } @@ -186,7 +185,7 @@ class URLGenerator implements IURLGenerator { $path = ''; $themingEnabled = $this->config->getSystemValue('installed', false) && \OCP\App::isEnabled('theming') && \OC_App::isAppLoaded('theming'); $themingImagePath = false; - if($themingEnabled) { + if ($themingEnabled) { $themingDefaults = \OC::$server->getThemingDefaults(); if ($themingDefaults instanceof ThemingDefaults) { $themingImagePath = $themingDefaults->replaceImagePath($app, $image); @@ -208,7 +207,7 @@ class URLGenerator implements IURLGenerator { } elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.svg") && file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.png")) { $path = \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png"; - } elseif($themingEnabled && $themingImagePath) { + } elseif ($themingEnabled && $themingImagePath) { $path = $themingImagePath; } elseif ($appPath && file_exists($appPath . "/img/$image")) { $path = \OC_App::getAppWebPath($app) . "/img/$image"; @@ -227,7 +226,7 @@ class URLGenerator implements IURLGenerator { $path = \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png"; } - if($path !== '') { + if ($path !== '') { $cache->set($cacheKey, $path); return $path; } @@ -248,7 +247,7 @@ class URLGenerator implements IURLGenerator { return rtrim($this->config->getSystemValue('overwrite.cli.url'), '/') . '/' . ltrim($url, '/'); } // The ownCloud web root can already be prepended. - if(\OC::$WEBROOT !== '' && strpos($url, \OC::$WEBROOT) === 0) { + if (\OC::$WEBROOT !== '' && strpos($url, \OC::$WEBROOT) === 0) { $url = substr($url, \strlen(\OC::$WEBROOT)); } diff --git a/lib/private/Updater.php b/lib/private/Updater.php index e94f36554d7..edbf43ea972 100644 --- a/lib/private/Updater.php +++ b/lib/private/Updater.php @@ -109,7 +109,7 @@ class Updater extends BasicEmitter { $wasMaintenanceModeEnabled = $this->config->getSystemValueBool('maintenance'); - if(!$wasMaintenanceModeEnabled) { + if (!$wasMaintenanceModeEnabled) { $this->config->setSystemValue('maintenance', true); $this->emit('\OC\Updater', 'maintenanceEnabled'); } @@ -141,7 +141,7 @@ class Updater extends BasicEmitter { $this->emit('\OC\Updater', 'updateEnd', [$success]); - if(!$wasMaintenanceModeEnabled && $success) { + if (!$wasMaintenanceModeEnabled && $success) { $this->config->setSystemValue('maintenance', false); $this->emit('\OC\Updater', 'maintenanceDisabled'); } else { @@ -279,7 +279,7 @@ class Updater extends BasicEmitter { $this->config->setAppValue('core', 'lastupdatedat', 0); // Check for code integrity if not disabled - if(\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) { + if (\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) { $this->emit('\OC\Updater', 'startCheckCodeIntegrity'); $this->checker->runInstanceVerification(); $this->emit('\OC\Updater', 'finishedCheckCodeIntegrity'); @@ -356,7 +356,7 @@ class Updater extends BasicEmitter { foreach ($apps as $appId) { $priorityType = false; foreach ($priorityTypes as $type) { - if(!isset($stacks[$type])) { + if (!isset($stacks[$type])) { $stacks[$type] = []; } if (\OC_App::isType($appId, [$type])) { @@ -376,7 +376,7 @@ class Updater extends BasicEmitter { \OC_App::updateApp($appId); $this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]); } - if($type !== $pseudoOtherType) { + if ($type !== $pseudoOtherType) { // load authentication, filesystem and logging apps after // upgrading them. Other apps my need to rely on modifying // user and/or filesystem aspects. @@ -404,7 +404,7 @@ class Updater extends BasicEmitter { foreach ($apps as $app) { // check if the app is compatible with this version of ownCloud $info = OC_App::getAppInfo($app); - if($info === null || !OC_App::isAppCompatible($version, $info)) { + if ($info === null || !OC_App::isAppCompatible($version, $info)) { if ($appManager->isShipped($app)) { throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update'); } @@ -445,7 +445,7 @@ class Updater extends BasicEmitter { * @throws \Exception */ private function upgradeAppStoreApps(array $disabledApps, $reenable = false) { - foreach($disabledApps as $app) { + foreach ($disabledApps as $app) { try { $this->emit('\OC\Updater', 'checkAppStoreAppBefore', [$app]); if ($this->installer->isUpdateAvailable($app)) { @@ -621,7 +621,5 @@ class Updater extends BasicEmitter { $this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use ($log) { $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 2dd18467cd9..8700b9609d2 100644 --- a/lib/private/Updater/ChangesCheck.php +++ b/lib/private/Updater/ChangesCheck.php @@ -70,7 +70,7 @@ class ChangesCheck { try { $version = $this->normalizeVersion($version); $changesInfo = $this->mapper->getChanges($version); - if($changesInfo->getLastCheck() + 1800 > time()) { + if ($changesInfo->getLastCheck() + 1800 > time()) { return json_decode($changesInfo->getData(), true); } } catch (DoesNotExistException $e) { @@ -79,7 +79,7 @@ class ChangesCheck { $response = $this->queryChangesServer($uri, $changesInfo); - switch($this->evaluateResponse($response)) { + switch ($this->evaluateResponse($response)) { case self::RESPONSE_NO_CONTENT: return []; case self::RESPONSE_USE_CACHE: @@ -96,11 +96,11 @@ class ChangesCheck { } protected function evaluateResponse(IResponse $response): int { - if($response->getStatusCode() === 304) { + if ($response->getStatusCode() === 304) { return self::RESPONSE_USE_CACHE; - } elseif($response->getStatusCode() === 404) { + } elseif ($response->getStatusCode() === 404) { return self::RESPONSE_NO_CONTENT; - } elseif($response->getStatusCode() === 200) { + } elseif ($response->getStatusCode() === 200) { return self::RESPONSE_HAS_CONTENT; } $this->logger->debug('Unexpected return code {code} from changelog server', [ @@ -111,7 +111,7 @@ class ChangesCheck { } protected function cacheResult(ChangesResult $entry, string $version) { - if($entry->getVersion() === $version) { + if ($entry->getVersion() === $version) { $this->mapper->update($entry); } else { $entry->setVersion($version); @@ -124,7 +124,7 @@ class ChangesCheck { */ protected function queryChangesServer(string $uri, ChangesResult $entry): IResponse { $headers = []; - if($entry->getEtag() !== '') { + if ($entry->getEtag() !== '') { $headers['If-None-Match'] = [$entry->getEtag()]; } @@ -144,7 +144,7 @@ class ChangesCheck { if ($xml !== false) { $data['changelogURL'] = (string)$xml->changelog['href']; $data['whatsNew'] = []; - foreach($xml->whatsNew as $infoSet) { + foreach ($xml->whatsNew as $infoSet) { $data['whatsNew'][(string)$infoSet['lang']] = [ 'regular' => (array)$infoSet->regular->item, 'admin' => (array)$infoSet->admin->item, @@ -164,7 +164,7 @@ class ChangesCheck { public function normalizeVersion(string $version): string { $versionNumbers = array_slice(explode('.', $version), 0, 3); $versionNumbers[0] = $versionNumbers[0] ?: '0'; // deal with empty input - while(count($versionNumbers) < 3) { + while (count($versionNumbers) < 3) { // changelog server expects x.y.z, pad 0 if it is too short $versionNumbers[] = 0; } diff --git a/lib/private/User/Backend.php b/lib/private/User/Backend.php index e90cfdc2e3d..354e1c3fd71 100644 --- a/lib/private/User/Backend.php +++ b/lib/private/User/Backend.php @@ -68,8 +68,8 @@ abstract class Backend implements UserInterface { */ public function getSupportedActions() { $actions = 0; - foreach($this->possibleActions as $action => $methodName) { - if(method_exists($this, $methodName)) { + foreach ($this->possibleActions as $action => $methodName) { + if (method_exists($this, $methodName)) { $actions |= $action; } } diff --git a/lib/private/User/Database.php b/lib/private/User/Database.php index c89d3ce3690..d5098483d61 100644 --- a/lib/private/User/Database.php +++ b/lib/private/User/Database.php @@ -324,7 +324,6 @@ class Database extends ABackend } return (string)$row['uid']; } - } return false; diff --git a/lib/private/User/Manager.php b/lib/private/User/Manager.php index 1ab335eeea6..303050a7716 100644 --- a/lib/private/User/Manager.php +++ b/lib/private/User/Manager.php @@ -368,7 +368,7 @@ class Manager extends PublicEmitter implements IUserManager { $this->emit('\OC\User', 'preCreateUser', [$uid, $password]); $this->eventDispatcher->dispatchTyped(new CreateUserEvent($uid, $password)); $state = $backend->createUser($uid, $password); - if($state === false) { + if ($state === false) { throw new \InvalidArgumentException($l->t('Could not create user')); } $user = $this->getUserObject($uid, $backend); @@ -395,13 +395,13 @@ class Manager extends PublicEmitter implements IUserManager { foreach ($this->backends as $backend) { if ($backend->implementsActions(Backend::COUNT_USERS)) { $backendUsers = $backend->countUsers(); - if($backendUsers !== false) { - if($backend instanceof IUserBackend) { + if ($backendUsers !== false) { + if ($backend instanceof IUserBackend) { $name = $backend->getBackendName(); } else { $name = get_class($backend); } - if(isset($userCountStatistics[$name])) { + if (isset($userCountStatistics[$name])) { $userCountStatistics[$name] += $backendUsers; } else { $userCountStatistics[$name] = $backendUsers; @@ -421,7 +421,7 @@ class Manager extends PublicEmitter implements IUserManager { */ public function countUsersOfGroups(array $groups) { $users = []; - foreach($groups as $group) { + foreach ($groups as $group) { $usersIds = array_map(function ($user) { return $user->getUID(); }, $group->getUsers()); diff --git a/lib/private/User/NoUserException.php b/lib/private/User/NoUserException.php index 697776115be..6ae22eb1e58 100644 --- a/lib/private/User/NoUserException.php +++ b/lib/private/User/NoUserException.php @@ -23,4 +23,5 @@ namespace OC\User; -class NoUserException extends \Exception {} +class NoUserException extends \Exception { +} diff --git a/lib/private/User/Session.php b/lib/private/User/Session.php index d908a3d78b2..817dcbf4c33 100644 --- a/lib/private/User/Session.php +++ b/lib/private/User/Session.php @@ -321,9 +321,7 @@ class Session implements IUserSession, Emitter { * @return null|string */ public function getImpersonatingUserID(): ?string { - return $this->session->get('oldUserId'); - } public function setImpersonatingUserID(bool $useCurrentUser = true): void { @@ -338,7 +336,6 @@ class Session implements IUserSession, Emitter { throw new \OC\User\NoUserException(); } $this->session->set('oldUserId', $currentUser->getUID()); - } /** * set the token id @@ -384,7 +381,7 @@ class Session implements IUserSession, Emitter { throw new LoginException($message); } - if($regenerateSessionId) { + if ($regenerateSessionId) { $this->session->regenerateId(); } @@ -411,7 +408,7 @@ class Session implements IUserSession, Emitter { $loginDetails['password'], $isToken, ]); - if($this->isLoggedIn()) { + if ($this->isLoggedIn()) { $this->prepareUserLogin($firstTimeLogin, $regenerateSessionId); return true; } @@ -464,7 +461,6 @@ class Session implements IUserSession, Emitter { // Failed, maybe the user used their email address $users = $this->manager->getByEmail($user); if (!(\count($users) === 1 && $this->login($users[0]->getUID(), $password))) { - $this->logger->warning('Login failed: \'' . $user . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']); $throttler->registerAttempt('login', $request->getRemoteAddress(), ['user' => $user]); @@ -480,7 +476,7 @@ class Session implements IUserSession, Emitter { if ($isTokenPassword) { $this->session->set('app_password', $password); - } elseif($this->supportsCookies($request)) { + } elseif ($this->supportsCookies($request)) { // Password login, but cookies supported -> create (browser) session token $this->createSessionToken($request, $this->getUser()->getUID(), $user, $password); } @@ -592,7 +588,7 @@ class Session implements IUserSession, Emitter { ); // Set the last-password-confirm session to make the sudo mode work - $this->session->set('last-password-confirm', $this->timeFactory->getTime()); + $this->session->set('last-password-confirm', $this->timeFactory->getTime()); return true; } @@ -825,7 +821,7 @@ class Session implements IUserSession, Emitter { if (!$this->loginWithToken($token)) { return false; } - if(!$this->validateToken($token)) { + if (!$this->validateToken($token)) { return false; } @@ -910,7 +906,6 @@ class Session implements IUserSession, Emitter { try { $this->tokenProvider->invalidateToken($this->session->getId()); } catch (SessionNotAvailableException $ex) { - } } $this->setUser(null); @@ -1011,6 +1006,4 @@ class Session implements IUserSession, Emitter { public function updateTokens(string $uid, string $password) { $this->tokenProvider->updatePasswords($uid, $password); } - - } diff --git a/lib/private/User/User.php b/lib/private/User/User.php index 6bd86bbc516..dd451c8eb3f 100644 --- a/lib/private/User/User.php +++ b/lib/private/User/User.php @@ -87,7 +87,7 @@ class User implements IUser { $this->backend = $backend; $this->dispatcher = $dispatcher; $this->emitter = $emitter; - if(is_null($config)) { + if (is_null($config)) { $config = \OC::$server->getConfig(); } $this->config = $config; @@ -163,8 +163,8 @@ class User implements IUser { */ public function setEMailAddress($mailAddress) { $oldMailAddress = $this->getEMailAddress(); - if($oldMailAddress !== $mailAddress) { - if($mailAddress === '') { + if ($oldMailAddress !== $mailAddress) { + if ($mailAddress === '') { $this->config->deleteUserValue($this->uid, 'settings', 'email'); } else { $this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress); @@ -308,7 +308,7 @@ class User implements IUser { * @return string */ public function getBackendClassName() { - if($this->backend instanceof IUserBackend) { + if ($this->backend instanceof IUserBackend) { return $this->backend->getBackendName(); } return get_class($this->backend); @@ -393,7 +393,7 @@ class User implements IUser { */ public function getQuota() { $quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default'); - if($quota === 'default') { + if ($quota === 'default') { $quota = $this->config->getAppValue('files', 'default_quota', 'none'); } return $quota; @@ -408,11 +408,11 @@ class User implements IUser { */ public function setQuota($quota) { $oldQuota = $this->config->getUserValue($this->uid, 'files', 'quota', ''); - if($quota !== 'none' and $quota !== 'default') { + if ($quota !== 'none' and $quota !== 'default') { $quota = OC_Helper::computerFileSize($quota); $quota = OC_Helper::humanFileSize($quota); } - if($quota !== $oldQuota) { + if ($quota !== $oldQuota) { $this->config->setUserValue($this->uid, 'files', 'quota', $quota); $this->triggerChange('quota', $quota, $oldQuota); } diff --git a/lib/private/legacy/OC_API.php b/lib/private/legacy/OC_API.php index b9960c70777..37a496a38fe 100644 --- a/lib/private/legacy/OC_API.php +++ b/lib/private/legacy/OC_API.php @@ -48,9 +48,9 @@ class OC_API { $request = \OC::$server->getRequest(); // Send 401 headers if unauthorised - if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) { + if ($result->getStatusCode() === API::RESPOND_UNAUTHORISED) { // If request comes from JS return dummy auth request - if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') { + if ($request->getHeader('X-Requested-With') === 'XMLHttpRequest') { header('WWW-Authenticate: DummyBasic realm="Authorisation Required"'); } else { header('WWW-Authenticate: Basic realm="Authorisation Required"'); @@ -58,7 +58,7 @@ class OC_API { http_response_code(401); } - foreach($result->getHeaders() as $name => $value) { + foreach ($result->getHeaders() as $name => $value) { header($name . ': ' . $value); } @@ -81,14 +81,14 @@ class OC_API { * @param XMLWriter $writer */ private static function toXML($array, $writer) { - foreach($array as $k => $v) { + foreach ($array as $k => $v) { if ($k[0] === '@') { $writer->writeAttribute(substr($k, 1), $v); continue; } elseif (is_numeric($k)) { $k = 'element'; } - if(is_array($v)) { + if (is_array($v)) { $writer->startElement($k); self::toXML($v, $writer); $writer->endElement(); diff --git a/lib/private/legacy/OC_App.php b/lib/private/legacy/OC_App.php index 3cc194cc03d..5c06f66a20a 100644 --- a/lib/private/legacy/OC_App.php +++ b/lib/private/legacy/OC_App.php @@ -114,9 +114,9 @@ class OC_App { $apps = self::getEnabledApps(); // Add each apps' folder as allowed class path - foreach($apps as $app) { + foreach ($apps as $app) { $path = self::getAppPath($app); - if($path !== false) { + if ($path !== false) { self::registerAutoloading($app, $path); } } @@ -142,7 +142,7 @@ class OC_App { public static function loadApp(string $app) { self::$loadedApps[] = $app; $appPath = self::getAppPath($app); - if($appPath === false) { + if ($appPath === false) { return; } @@ -154,7 +154,7 @@ class OC_App { try { self::requireAppFile($app); } catch (Throwable $ex) { - if($ex instanceof ServerNotAvailableException) { + if ($ex instanceof ServerNotAvailableException) { throw $ex; } \OC::$server->getLogger()->logException($ex); @@ -210,7 +210,7 @@ class OC_App { $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ? [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin']; foreach ($plugins as $plugin) { - if($plugin['@attributes']['type'] === 'collaborator-search') { + if ($plugin['@attributes']['type'] === 'collaborator-search') { $pluginInfo = [ 'shareType' => $plugin['@attributes']['share-type'], 'class' => $plugin['@value'], @@ -308,7 +308,7 @@ class OC_App { public static function setAppTypes(string $app) { $appManager = \OC::$server->getAppManager(); $appData = $appManager->getAppInfo($app); - if(!is_array($appData)) { + if (!is_array($appData)) { return; } @@ -395,7 +395,7 @@ class OC_App { $installer = \OC::$server->query(Installer::class); $isDownloaded = $installer->isDownloaded($appId); - if(!$isDownloaded) { + if (!$isDownloaded) { $installer->downloadApp($appId); } @@ -446,7 +446,7 @@ class OC_App { */ public static function findAppInDirectories(string $appId) { $sanitizedAppId = self::cleanAppId($appId); - if($sanitizedAppId !== $appId) { + if ($sanitizedAppId !== $appId) { return false; } static $app_dir = []; @@ -671,7 +671,6 @@ class OC_App { * @todo: change the name of this method to getInstalledApps, which is more accurate */ public static function getAllApps(): array { - $apps = []; foreach (OC::$APPSROOTS as $apps_dir) { @@ -683,9 +682,7 @@ class OC_App { if (is_resource($dh)) { while (($file = readdir($dh)) !== false) { - if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) { - $apps[] = $file; } } @@ -717,7 +714,6 @@ class OC_App { foreach ($installedApps as $app) { if (array_search($app, $blacklist) === false) { - $info = OC_App::getAppInfo($app, false, $langCode); if (!is_array($info)) { \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR); @@ -756,7 +752,7 @@ class OC_App { } $appPath = self::getAppPath($app); - if($appPath !== false) { + if ($appPath !== false) { $appIcon = $appPath . '/img/' . $app . '.svg'; if (file_exists($appIcon)) { $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg'); @@ -864,7 +860,6 @@ class OC_App { if (!empty($requireMin) && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<') ) { - return false; } @@ -883,7 +878,7 @@ class OC_App { public static function getAppVersions() { static $versions; - if(!$versions) { + if (!$versions) { $appConfig = \OC::$server->getAppConfig(); $versions = $appConfig->getValues(false, 'installed_version'); } @@ -898,7 +893,7 @@ class OC_App { */ public static function updateApp(string $appId): bool { $appPath = self::getAppPath($appId); - if($appPath === false) { + if ($appPath === false) { return false; } @@ -931,7 +926,7 @@ class OC_App { //set remote/public handlers if (array_key_exists('ocsid', $appData)) { \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']); - } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) { + } elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) { \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid'); } foreach ($appData['remote'] as $name => $path) { @@ -1081,7 +1076,6 @@ class OC_App { * @return array improved app data */ public static function parseAppInfo(array $data, $lang = null): array { - if ($lang && isset($data['name']) && is_array($data['name'])) { $data['name'] = self::findBestL10NOption($data['name'], $lang); } @@ -1092,7 +1086,7 @@ class OC_App { $data['description'] = trim(self::findBestL10NOption($data['description'], $lang)); } elseif (isset($data['description']) && is_string($data['description'])) { $data['description'] = trim($data['description']); - } else { + } else { $data['description'] = ''; } diff --git a/lib/private/legacy/OC_DB.php b/lib/private/legacy/OC_DB.php index cf45faae314..63f1447ad91 100644 --- a/lib/private/legacy/OC_DB.php +++ b/lib/private/legacy/OC_DB.php @@ -212,7 +212,7 @@ class OC_DB { * @throws \OC\DatabaseException */ public static function raiseExceptionOnError($result, $message = null) { - if($result === false) { + if ($result === false) { if ($message === null) { $message = self::getErrorMessage(); } else { diff --git a/lib/private/legacy/OC_Defaults.php b/lib/private/legacy/OC_Defaults.php index d5a4b5eecee..f90cae61bd7 100644 --- a/lib/private/legacy/OC_Defaults.php +++ b/lib/private/legacy/OC_Defaults.php @@ -36,7 +36,6 @@ * */ class OC_Defaults { - private $theme; private $defaultEntity; @@ -282,7 +281,6 @@ class OC_Defaults { * @return string */ public function getColorPrimary() { - if ($this->themeExist('getColorPrimary')) { return $this->theme->getColorPrimary(); } @@ -296,7 +294,7 @@ class OC_Defaults { * @return array scss variables to overwrite */ public function getScssVariables() { - if($this->themeExist('getScssVariables')) { + if ($this->themeExist('getScssVariables')) { return $this->theme->getScssVariables(); } return []; @@ -317,7 +315,7 @@ class OC_Defaults { return $this->theme->getLogo($useSvg); } - if($useSvg) { + if ($useSvg) { $logo = \OC::$server->getURLGenerator()->imagePath('core', 'logo/logo.svg'); } else { $logo = \OC::$server->getURLGenerator()->imagePath('core', 'logo/logo.png'); diff --git a/lib/private/legacy/OC_EventSource.php b/lib/private/legacy/OC_EventSource.php index 7191028295a..b8c4389f985 100644 --- a/lib/private/legacy/OC_EventSource.php +++ b/lib/private/legacy/OC_EventSource.php @@ -77,7 +77,7 @@ class OC_EventSource implements \OCP\IEventSource { } else { header("Content-Type: text/event-stream"); } - if(!\OC::$server->getRequest()->passesStrictCookieCheck()) { + if (!\OC::$server->getRequest()->passesStrictCookieCheck()) { header('Location: '.\OC::$WEBROOT); exit(); } diff --git a/lib/private/legacy/OC_FileChunking.php b/lib/private/legacy/OC_FileChunking.php index 048bd085bb5..37cf42a31cb 100644 --- a/lib/private/legacy/OC_FileChunking.php +++ b/lib/private/legacy/OC_FileChunking.php @@ -87,7 +87,7 @@ class OC_FileChunking { $cache = $this->getCache(); $chunkcount = (int)$this->info['chunkcount']; - for($i=($chunkcount-1); $i >= 0; $i--) { + for ($i=($chunkcount-1); $i >= 0; $i--) { if (!$cache->hasKey($prefix.$i)) { return false; } @@ -143,7 +143,7 @@ class OC_FileChunking { public function cleanup() { $cache = $this->getCache(); $prefix = $this->getPrefix(); - for($i=0; $i < $this->info['chunkcount']; $i++) { + for ($i=0; $i < $this->info['chunkcount']; $i++) { $cache->remove($prefix.$i); } } diff --git a/lib/private/legacy/OC_Files.php b/lib/private/legacy/OC_Files.php index 710e0882010..e046a577026 100644 --- a/lib/private/legacy/OC_Files.php +++ b/lib/private/legacy/OC_Files.php @@ -87,15 +87,13 @@ class OC_Files { http_response_code(206); header('Accept-Ranges: bytes', true); if (count($rangeArray) > 1) { - $type = 'multipart/byteranges; boundary='.self::getBoundary(); + $type = 'multipart/byteranges; boundary='.self::getBoundary(); // no Content-Length header here + } else { + header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true); + OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1); } - else { - header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true); - OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1); - } - } - else { + } else { OC_Response::setContentLengthHeader($fileSize); } } @@ -110,12 +108,10 @@ class OC_Files { * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header */ public static function get($dir, $files, $params = null) { - $view = \OC\Files\Filesystem::getView(); $getType = self::FILE; $filename = $dir; try { - if (is_array($files) && count($files) === 1) { $files = $files[0]; } @@ -180,7 +176,7 @@ class OC_Files { if (\OC\Files\Filesystem::is_file($file)) { $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot()); $file = $userFolder->get($file); - if($file instanceof \OC\Files\Node\File) { + if ($file instanceof \OC\Files\Node\File) { try { $fh = $file->fopen('r'); } catch (\OCP\Files\NotPermittedException $e) { @@ -263,13 +259,11 @@ class OC_Files { if ($minOffset >= $fileSize) { break; } - } - elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) { + } elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) { // case: x- $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize ]; break; - } - elseif (is_numeric($ranges[1])) { + } elseif (is_numeric($ranges[1])) { // case: -x if ($ranges[1] > $fileSize) { $ranges[1] = $fileSize; @@ -294,7 +288,7 @@ class OC_Files { try { $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot()); $file = $userFolder->get($filename); - if(!$file instanceof \OC\Files\Node\File || !$file->isReadable()) { + if (!$file instanceof \OC\Files\Node\File || !$file->isReadable()) { http_response_code(403); die('403 Forbidden'); } @@ -330,22 +324,21 @@ class OC_Files { if (!empty($rangeArray)) { try { if (count($rangeArray) == 1) { - $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']); - } - else { - // check if file is seekable (if not throw UnseekableException) - // we have to check it before body contents - $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']); + $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']); + } else { + // check if file is seekable (if not throw UnseekableException) + // we have to check it before body contents + $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']); - $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename)); + $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename)); - foreach ($rangeArray as $range) { - echo "\r\n--".self::getBoundary()."\r\n". + foreach ($rangeArray as $range) { + echo "\r\n--".self::getBoundary()."\r\n". "Content-type: ".$type."\r\n". "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n"; - $view->readfilePart($filename, $range['from'], $range['to']); - } - echo "\r\n--".self::getBoundary()."--\r\n"; + $view->readfilePart($filename, $range['from'], $range['to']); + } + echo "\r\n--".self::getBoundary()."--\r\n"; } } catch (\OCP\Files\UnseekableException $ex) { // file is unseekable @@ -355,8 +348,7 @@ class OC_Files { self::sendHeaders($filename, $name, []); $view->readfile($filename); } - } - else { + } else { $view->readfile($filename); } } @@ -430,5 +422,4 @@ class OC_Files { $view->unlockFile($file, ILockingProvider::LOCK_SHARED); } } - } diff --git a/lib/private/legacy/OC_Helper.php b/lib/private/legacy/OC_Helper.php index 1c4ce50f4ef..3439d1f8936 100644 --- a/lib/private/legacy/OC_Helper.php +++ b/lib/private/legacy/OC_Helper.php @@ -231,8 +231,9 @@ class OC_Helper { } foreach ($dirs as $dir) { foreach ($exts as $ext) { - if ($check_fn("$dir/$name" . $ext)) + if ($check_fn("$dir/$name" . $ext)) { return true; + } } } return false; @@ -385,7 +386,7 @@ class OC_Helper { * @return int number of bytes representing */ public static function maxUploadFilesize($dir, $freeSpace = null) { - if (is_null($freeSpace) || $freeSpace < 0){ + if (is_null($freeSpace) || $freeSpace < 0) { $freeSpace = self::freeSpace($dir); } return min($freeSpace, self::uploadLimit()); @@ -540,7 +541,7 @@ class OC_Helper { $ownerId = $storage->getOwner($path); $ownerDisplayName = ''; $owner = \OC::$server->getUserManager()->get($ownerId); - if($owner) { + if ($owner) { $ownerDisplayName = $owner->getDisplayName(); } diff --git a/lib/private/legacy/OC_Hook.php b/lib/private/legacy/OC_Hook.php index b98424711dd..fe08266fe5b 100644 --- a/lib/private/legacy/OC_Hook.php +++ b/lib/private/legacy/OC_Hook.php @@ -54,12 +54,12 @@ class OC_Hook { static public function connect($signalClass, $signalName, $slotClass, $slotName) { // If we're trying to connect to an emitting class that isn't // yet registered, register it - if(!array_key_exists($signalClass, self::$registered)) { + if (!array_key_exists($signalClass, self::$registered)) { self::$registered[$signalClass] = []; } // If we're trying to connect to an emitting method that isn't // yet registered, register it with the emitting class - if(!array_key_exists($signalName, self::$registered[$signalClass])) { + if (!array_key_exists($signalName, self::$registered[$signalClass])) { self::$registered[$signalClass][$signalName] = []; } @@ -95,27 +95,27 @@ class OC_Hook { // Return false if no hook handlers are listening to this // emitting class - if(!array_key_exists($signalClass, self::$registered)) { + if (!array_key_exists($signalClass, self::$registered)) { return false; } // Return false if no hook handlers are listening to this // emitting method - if(!array_key_exists($signalName, self::$registered[$signalClass])) { + if (!array_key_exists($signalName, self::$registered[$signalClass])) { return false; } // Call all slots - foreach(self::$registered[$signalClass][$signalName] as $i) { + foreach (self::$registered[$signalClass][$signalName] as $i) { try { call_user_func([ $i["class"], $i["name"] ], $params); - } catch (Exception $e){ + } catch (Exception $e) { self::$thrownExceptions[] = $e; \OC::$server->getLogger()->logException($e); - if($e instanceof \OC\HintException) { + if ($e instanceof \OC\HintException) { throw $e; } - if($e instanceof \OC\ServerNotAvailableException) { + if ($e instanceof \OC\ServerNotAvailableException) { throw $e; } } @@ -133,10 +133,10 @@ class OC_Hook { if ($signalClass) { if ($signalName) { self::$registered[$signalClass][$signalName]=[]; - }else{ + } else { self::$registered[$signalClass]=[]; } - }else{ + } else { self::$registered=[]; } } diff --git a/lib/private/legacy/OC_Image.php b/lib/private/legacy/OC_Image.php index 829a9b81652..a3ac82c216d 100644 --- a/lib/private/legacy/OC_Image.php +++ b/lib/private/legacy/OC_Image.php @@ -489,7 +489,7 @@ class OC_Image implements \OCP\IImage { $rotate = 90; break; } - if($flip && function_exists('imageflip')) { + if ($flip && function_exists('imageflip')) { imageflip($this->resource, IMG_FLIP_HORIZONTAL); } if ($rotate) { diff --git a/lib/private/legacy/OC_JSON.php b/lib/private/legacy/OC_JSON.php index 5b4b97e6fd0..d3a33e3a0f3 100644 --- a/lib/private/legacy/OC_JSON.php +++ b/lib/private/legacy/OC_JSON.php @@ -33,7 +33,7 @@ * Class OC_JSON * @deprecated Use a AppFramework JSONResponse instead */ -class OC_JSON{ +class OC_JSON { /** * Check if the app is enabled, send json error msg if not @@ -42,7 +42,7 @@ class OC_JSON{ * @suppress PhanDeprecatedFunction */ public static function checkAppEnabled($app) { - if(!\OC::$server->getAppManager()->isEnabledForUser($app)) { + if (!\OC::$server->getAppManager()->isEnabledForUser($app)) { $l = \OC::$server->getL10N('lib'); self::error([ 'data' => [ 'message' => $l->t('Application is not enabled'), 'error' => 'application_not_enabled' ]]); exit(); @@ -56,7 +56,7 @@ class OC_JSON{ */ public static function checkLoggedIn() { $twoFactorAuthManger = \OC::$server->getTwoFactorAuthManager(); - if(!\OC::$server->getUserSession()->isLoggedIn() + if (!\OC::$server->getUserSession()->isLoggedIn() || $twoFactorAuthManger->needsSecondFactor(\OC::$server->getUserSession()->getUser())) { $l = \OC::$server->getL10N('lib'); http_response_code(\OCP\AppFramework\Http::STATUS_UNAUTHORIZED); @@ -71,12 +71,12 @@ class OC_JSON{ * @suppress PhanDeprecatedFunction */ public static function callCheck() { - if(!\OC::$server->getRequest()->passesStrictCookieCheck()) { + if (!\OC::$server->getRequest()->passesStrictCookieCheck()) { header('Location: '.\OC::$WEBROOT); exit(); } - if(!\OC::$server->getRequest()->passesCSRFCheck()) { + if (!\OC::$server->getRequest()->passesCSRFCheck()) { $l = \OC::$server->getL10N('lib'); self::error([ 'data' => [ 'message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired' ]]); exit(); @@ -89,7 +89,7 @@ class OC_JSON{ * @suppress PhanDeprecatedFunction */ public static function checkAdminUser() { - if(!OC_User::isAdminUser(OC_User::getUser())) { + if (!OC_User::isAdminUser(OC_User::getUser())) { $l = \OC::$server->getL10N('lib'); self::error([ 'data' => [ 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' ]]); exit(); diff --git a/lib/private/legacy/OC_Response.php b/lib/private/legacy/OC_Response.php index 45fea27d61d..bbeb6258109 100644 --- a/lib/private/legacy/OC_Response.php +++ b/lib/private/legacy/OC_Response.php @@ -94,7 +94,7 @@ class OC_Response { // Send fallback headers for installations that don't have the possibility to send // custom headers on the webserver side - if(getenv('modHeadersAvailable') !== 'true') { + if (getenv('modHeadersAvailable') !== 'true') { header('Referrer-Policy: no-referrer'); // https://www.w3.org/TR/referrer-policy/ header('X-Content-Type-Options: nosniff'); // Disable sniffing the content type for IE header('X-Download-Options: noopen'); // https://msdn.microsoft.com/en-us/library/jj542450(v=vs.85).aspx @@ -104,5 +104,4 @@ class OC_Response { header('X-XSS-Protection: 1; mode=block'); // Enforce browser based XSS filters } } - } diff --git a/lib/private/legacy/OC_Template.php b/lib/private/legacy/OC_Template.php index 08f23b55a0f..736011b4359 100644 --- a/lib/private/legacy/OC_Template.php +++ b/lib/private/legacy/OC_Template.php @@ -99,7 +99,7 @@ class OC_Template extends \OC\Template\Base { * @param string $renderAs */ public static function initTemplateEngine($renderAs) { - if (self::$initTemplateEngineFirstRun){ + if (self::$initTemplateEngineFirstRun) { //apps that started before the template initialization can load their own scripts/styles //so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true @@ -130,7 +130,6 @@ class OC_Template extends \OC\Template\Base { self::$initTemplateEngineFirstRun = false; } - } @@ -146,7 +145,7 @@ class OC_Template extends \OC\Template\Base { */ protected function findTemplate($theme, $app, $name) { // Check if it is a app template or not. - if($app !== '') { + if ($app !== '') { $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app)); } else { $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT); @@ -182,10 +181,10 @@ class OC_Template extends \OC\Template\Base { public function fetchPage($additionalParams = null) { $data = parent::fetchPage($additionalParams); - if($this->renderAs) { + if ($this->renderAs) { $page = new TemplateLayout($this->renderAs, $this->app); - if(is_array($additionalParams)) { + if (is_array($additionalParams)) { foreach ($additionalParams as $key => $value) { $page->assign($key, $value); } @@ -193,12 +192,12 @@ class OC_Template extends \OC\Template\Base { // Add custom headers $headers = ''; - foreach(OC_Util::$headers as $header) { + foreach (OC_Util::$headers as $header) { $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']); if (strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes'])))) { $headers .= ' defer'; } - foreach($header['attributes'] as $name=>$value) { + foreach ($header['attributes'] as $name=>$value) { $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"'; } if ($header['text'] !== null) { @@ -240,7 +239,7 @@ class OC_Template extends \OC\Template\Base { */ public static function printUserPage($application, $name, $parameters = []) { $content = new OC_Template($application, $name, "user"); - foreach($parameters as $key => $value) { + foreach ($parameters as $key => $value) { $content->assign($key, $value); } print $content->printPage(); @@ -255,7 +254,7 @@ class OC_Template extends \OC\Template\Base { */ public static function printAdminPage($application, $name, $parameters = []) { $content = new OC_Template($application, $name, "admin"); - foreach($parameters as $key => $value) { + foreach ($parameters as $key => $value) { $content->assign($key, $value); } return $content->printPage(); @@ -270,7 +269,7 @@ class OC_Template extends \OC\Template\Base { */ public static function printGuestPage($application, $name, $parameters = []) { $content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest'); - foreach($parameters as $key => $value) { + foreach ($parameters as $key => $value) { $content->assign($key, $value); } return $content->printPage(); diff --git a/lib/private/legacy/OC_User.php b/lib/private/legacy/OC_User.php index a9de5cdef9f..c61d99eee74 100644 --- a/lib/private/legacy/OC_User.php +++ b/lib/private/legacy/OC_User.php @@ -57,7 +57,6 @@ use OCP\ILogger; * logout() */ class OC_User { - private static $_usedBackends = []; private static $_setupedBackends = []; @@ -161,7 +160,6 @@ class OC_User { * @return bool */ public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) { - $uid = $backend->getCurrentUserId(); $run = true; OC_Hook::emit("OC_User", "pre_login", ["run" => &$run, "uid" => $uid, 'backend' => $backend]); diff --git a/lib/private/legacy/OC_Util.php b/lib/private/legacy/OC_Util.php index 9322ef07a79..71f6edba0bf 100644 --- a/lib/private/legacy/OC_Util.php +++ b/lib/private/legacy/OC_Util.php @@ -302,7 +302,6 @@ class OC_Util { //if we aren't logged in, there is no use to set up the filesystem if ($user != "") { - $userDir = '/' . $user . '/files'; //jail the user into his "home" directory @@ -382,7 +381,7 @@ class OC_Util { return \OCP\Files\FileInfo::SPACE_UNLIMITED; } $userQuota = $user->getQuota(); - if($userQuota === 'none') { + if ($userQuota === 'none') { return \OCP\Files\FileInfo::SPACE_UNLIMITED; } return OC_Helper::computerFileSize($userQuota); @@ -398,7 +397,6 @@ class OC_Util { * @suppress PhanDeprecatedFunction */ public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) { - $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton'); $userLang = \OC::$server->getL10NFactory()->findLanguage(); $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory); @@ -450,7 +448,7 @@ class OC_Util { // Verify if folder exists $dir = opendir($source); - if($dir === false) { + if ($dir === false) { $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']); return; } @@ -464,7 +462,7 @@ class OC_Util { } else { $child = $target->newFile($file); $sourceStream = fopen($source . '/' . $file, 'r'); - if($sourceStream === false) { + if ($sourceStream === false) { $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']); closedir($dir); return; @@ -663,7 +661,6 @@ class OC_Util { * @return void */ private static function addExternalResource($application, $prepend, $path, $type = "script") { - if ($type === "style") { if (!in_array($path, self::$styles)) { if ($prepend === true) { @@ -700,7 +697,6 @@ class OC_Util { ]; if ($prepend === true) { array_unshift(self::$headers, $header); - } else { self::$headers[] = $header; } @@ -750,7 +746,7 @@ class OC_Util { } // Check if config folder is writable. - if(!OC_Helper::isReadOnlyConfigEnabled()) { + if (!OC_Helper::isReadOnlyConfigEnabled()) { if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) { $errors[] = [ 'error' => $l->t('Cannot write into "config" directory'), @@ -890,15 +886,15 @@ class OC_Util { } } - foreach($missingDependencies as $missingDependency) { + foreach ($missingDependencies as $missingDependency) { $errors[] = [ 'error' => $l->t('PHP module %s not installed.', [$missingDependency]), 'hint' => $moduleHint ]; $webServerRestart = true; } - foreach($invalidIniSettings as $setting) { - if(is_bool($setting[1])) { + foreach ($invalidIniSettings as $setting) { + if (is_bool($setting[1])) { $setting[1] = $setting[1] ? 'on' : 'off'; } $errors[] = [ @@ -916,7 +912,7 @@ class OC_Util { * TODO: Should probably be implemented in the above generic dependency * check somehow in the long-term. */ - if($iniWrapper->getBool('mbstring.func_overload') !== null && + if ($iniWrapper->getBool('mbstring.func_overload') !== null && $iniWrapper->getBool('mbstring.func_overload') === true) { $errors[] = [ 'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]), @@ -924,7 +920,7 @@ class OC_Util { ]; } - if(function_exists('xml_parser_create') && + if (function_exists('xml_parser_create') && LIBXML_LOADED_VERSION < 20700) { $version = LIBXML_LOADED_VERSION; $major = floor($version/10000); @@ -999,7 +995,7 @@ class OC_Util { * @return array arrays with error messages and hints */ public static function checkDataDirectoryPermissions($dataDirectory) { - if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) { + if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) { return []; } $l = \OC::$server->getL10N('lib'); @@ -1116,7 +1112,7 @@ class OC_Util { } } - if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') { + if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') { $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/'); } else { $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/'); @@ -1226,7 +1222,6 @@ class OC_Util { * @throws \OC\HintException If the test file can't get written. */ public function isHtaccessWorking(\OCP\IConfig $config) { - if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) { return true; } @@ -1349,7 +1344,7 @@ class OC_Util { * @return bool|string */ public static function normalizeUnicode($value) { - if(Normalizer::isNormalized($value)) { + if (Normalizer::isNormalized($value)) { return $value; } @@ -1466,5 +1461,4 @@ class OC_Util { return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1; } - } diff --git a/lib/private/legacy/template/functions.php b/lib/private/legacy/template/functions.php index 83751db1e31..e2a1c476433 100644 --- a/lib/private/legacy/template/functions.php +++ b/lib/private/legacy/template/functions.php @@ -62,10 +62,10 @@ function emit_css_tag($href, $opts = '') { * @param array $obj all the script information from template */ function emit_css_loading_tags($obj) { - foreach($obj['cssfiles'] as $css) { + foreach ($obj['cssfiles'] as $css) { emit_css_tag($css); } - foreach($obj['printcssfiles'] as $css) { + foreach ($obj['printcssfiles'] as $css) { emit_css_tag($css, 'media="print"'); } } @@ -79,7 +79,7 @@ function emit_script_tag($src, $script_content='') { $defer_str=' defer'; $s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"'; if (!empty($src)) { - // emit script tag for deferred loading from $src + // emit script tag for deferred loading from $src $s.=$defer_str.' src="' . $src .'">'; } elseif (!empty($script_content)) { // emit script tag for inline script from $script_content without defer (see MDN) @@ -97,7 +97,7 @@ function emit_script_tag($src, $script_content='') { * @param array $obj all the script information from template */ function emit_script_loading_tags($obj) { - foreach($obj['jsfiles'] as $jsfile) { + foreach ($obj['jsfiles'] as $jsfile) { emit_script_tag($jsfile, ''); } if (!empty($obj['inline_ocjs'])) { @@ -121,8 +121,8 @@ function print_unescaped($string) { * if an array is given it will add all scripts */ function script($app, $file = null) { - if(is_array($file)) { - foreach($file as $f) { + if (is_array($file)) { + foreach ($file as $f) { OC_Util::addScript($app, $f); } } else { @@ -137,8 +137,8 @@ function script($app, $file = null) { * if an array is given it will add all scripts */ function vendor_script($app, $file = null) { - if(is_array($file)) { - foreach($file as $f) { + if (is_array($file)) { + foreach ($file as $f) { OC_Util::addVendorScript($app, $f); } } else { @@ -153,8 +153,8 @@ function vendor_script($app, $file = null) { * if an array is given it will add all styles */ function style($app, $file = null) { - if(is_array($file)) { - foreach($file as $f) { + if (is_array($file)) { + foreach ($file as $f) { OC_Util::addStyle($app, $f); } } else { @@ -169,8 +169,8 @@ function style($app, $file = null) { * if an array is given it will add all styles */ function vendor_style($app, $file = null) { - if(is_array($file)) { - foreach($file as $f) { + if (is_array($file)) { + foreach ($file as $f) { OC_Util::addVendorStyle($app, $f); } } else { @@ -194,8 +194,8 @@ function translation($app) { * if an array is given it will add all components */ function component($app, $file) { - if(is_array($file)) { - foreach($file as $f) { + if (is_array($file)) { + foreach ($file as $f) { $url = link_to($app, 'component/' . $f . '.html'); OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]); } @@ -300,7 +300,7 @@ function relative_modified_date($timestamp, $fromTime = null, $dateOnly = false) /** @var \OC\DateTimeFormatter $formatter */ $formatter = \OC::$server->query('DateTimeFormatter'); - if ($dateOnly){ + if ($dateOnly) { return $formatter->formatDateSpan($timestamp, $fromTime); } return $formatter->formatTimeSpan($timestamp, $fromTime); @@ -321,7 +321,7 @@ function html_select_options($options, $selected, $params=[]) { $label_name = $params['label']; } $html = ''; - foreach($options as $value => $label) { + foreach ($options as $value => $label) { if ($value_name && is_array($label)) { $value = $label[$value_name]; } |