diff options
Diffstat (limited to 'lib/private')
196 files changed, 1935 insertions, 823 deletions
diff --git a/lib/private/Activity/Manager.php b/lib/private/Activity/Manager.php index 8a3c5b81427..c1b09300033 100644 --- a/lib/private/Activity/Manager.php +++ b/lib/private/Activity/Manager.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com> * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Kesselberg <mail@danielkesselberg.de> * @author Joas Schilling <coding@schilljs.com> * @author Morris Jobke <hey@morrisjobke.de> @@ -76,10 +77,10 @@ class Manager implements IManager { } /** @var \Closure[] */ - private $consumersClosures = array(); + private $consumersClosures = []; /** @var IConsumer[] */ - private $consumers = array(); + private $consumers = []; /** * @return \OCP\Activity\IConsumer[] diff --git a/lib/private/AllConfig.php b/lib/private/AllConfig.php index 2eca9d55b28..a41230e4a97 100644 --- a/lib/private/AllConfig.php +++ b/lib/private/AllConfig.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Loki3000 <github@labcms.ru> @@ -297,7 +298,7 @@ class AllConfig implements \OCP\IConfig { // only add to the cache if we already loaded data for the user if (isset($this->userCache[$userId])) { if (!isset($this->userCache[$userId][$appName])) { - $this->userCache[$userId][$appName] = array(); + $this->userCache[$userId][$appName] = []; } $this->userCache[$userId][$appName][$key] = (string)$value; } @@ -333,7 +334,7 @@ class AllConfig implements \OCP\IConfig { if (isset($data[$appName])) { return array_keys($data[$appName]); } else { - return array(); + return []; } } @@ -350,7 +351,7 @@ class AllConfig implements \OCP\IConfig { $sql = 'DELETE FROM `*PREFIX*preferences` '. 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'; - $this->connection->executeUpdate($sql, array($userId, $appName, $key)); + $this->connection->executeUpdate($sql, [$userId, $appName, $key]); if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) { unset($this->userCache[$userId][$appName][$key]); @@ -368,7 +369,7 @@ class AllConfig implements \OCP\IConfig { $sql = 'DELETE FROM `*PREFIX*preferences` '. 'WHERE `userid` = ?'; - $this->connection->executeUpdate($sql, array($userId)); + $this->connection->executeUpdate($sql, [$userId]); unset($this->userCache[$userId]); } @@ -384,7 +385,7 @@ class AllConfig implements \OCP\IConfig { $sql = 'DELETE FROM `*PREFIX*preferences` '. 'WHERE `appid` = ?'; - $this->connection->executeUpdate($sql, array($appName)); + $this->connection->executeUpdate($sql, [$appName]); foreach ($this->userCache as &$userCache) { unset($userCache[$appName]); @@ -405,20 +406,20 @@ class AllConfig implements \OCP\IConfig { return $this->userCache[$userId]; } if ($userId === null || $userId === '') { - $this->userCache[$userId]=array(); + $this->userCache[$userId]=[]; return $this->userCache[$userId]; } // TODO - FIXME $this->fixDIInit(); - $data = array(); + $data = []; $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'; - $result = $this->connection->executeQuery($query, array($userId)); + $result = $this->connection->executeQuery($query, [$userId]); while ($row = $result->fetch()) { $appId = $row['appid']; if (!isset($data[$appId])) { - $data[$appId] = array(); + $data[$appId] = []; } $data[$appId][$row['configkey']] = $row['configvalue']; } @@ -439,13 +440,13 @@ class AllConfig implements \OCP\IConfig { $this->fixDIInit(); if (empty($userIds) || !is_array($userIds)) { - return array(); + return []; } $chunkedUsers = array_chunk($userIds, 50, true); $placeholders50 = implode(',', array_fill(0, 50, '?')); - $userValues = array(); + $userValues = []; foreach ($chunkedUsers as $chunk) { $queryParams = $chunk; // create [$app, $key, $chunkedUsers] @@ -490,9 +491,9 @@ class AllConfig implements \OCP\IConfig { $sql .= 'AND `configvalue` = ?'; } - $result = $this->connection->executeQuery($sql, array($appName, $key, $value)); + $result = $this->connection->executeQuery($sql, [$appName, $key, $value]); - $userIDs = array(); + $userIDs = []; while ($row = $result->fetch()) { $userIDs[] = $row['userid']; } @@ -522,9 +523,9 @@ class AllConfig implements \OCP\IConfig { $sql .= 'AND LOWER(`configvalue`) = LOWER(?)'; } - $result = $this->connection->executeQuery($sql, array($appName, $key, $value)); + $result = $this->connection->executeQuery($sql, [$appName, $key, $value]); - $userIDs = array(); + $userIDs = []; while ($row = $result->fetch()) { $userIDs[] = $row['userid']; } diff --git a/lib/private/App/AppManager.php b/lib/private/App/AppManager.php index 937cc511985..eaa203417b2 100644 --- a/lib/private/App/AppManager.php +++ b/lib/private/App/AppManager.php @@ -5,6 +5,7 @@ * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bjoern Schiessle <bjoern@schiessle.org> * @author Christoph Schaefer "christophł@wolkesicher.de" + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Kesselberg <mail@danielkesselberg.de> * @author Daniel Rudolf <github.com@daniel-rudolf.de> * @author Greta Doci <gretadoci@gmail.com> @@ -540,7 +541,7 @@ class AppManager implements IAppManager { */ public function getIncompatibleApps(string $version): array { $apps = $this->getInstalledApps(); - $incompatibleApps = array(); + $incompatibleApps = []; foreach ($apps as $appId) { $info = $this->getAppInfo($appId); if ($info === null) { diff --git a/lib/private/App/AppStore/Bundles/BundleFetcher.php b/lib/private/App/AppStore/Bundles/BundleFetcher.php index 5a36907094a..3925042a09e 100644 --- a/lib/private/App/AppStore/Bundles/BundleFetcher.php +++ b/lib/private/App/AppStore/Bundles/BundleFetcher.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch> * + * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Lukas Reschke <lukas@statuscode.ch> * * @license GNU AGPL version 3 or any later version diff --git a/lib/private/App/AppStore/Bundles/EducationBundle.php b/lib/private/App/AppStore/Bundles/EducationBundle.php index d848befc562..2d1968772d4 100644 --- a/lib/private/App/AppStore/Bundles/EducationBundle.php +++ b/lib/private/App/AppStore/Bundles/EducationBundle.php @@ -42,7 +42,6 @@ class EducationBundle extends Bundle { 'circles', 'groupfolders', 'announcementcenter', - 'admin_notifications', 'quota_warning', 'orcid', 'user_saml', diff --git a/lib/private/App/AppStore/Bundles/HubBundle.php b/lib/private/App/AppStore/Bundles/HubBundle.php index cef0c6302e3..cf2f44b7ea4 100644 --- a/lib/private/App/AppStore/Bundles/HubBundle.php +++ b/lib/private/App/AppStore/Bundles/HubBundle.php @@ -1,5 +1,7 @@ <?php + declare(strict_types=1); + /** * @copyright Copyright (c) 2020 Arthur Schiwon <blizzz@arthur-schiwon.de> * @@ -18,7 +20,7 @@ declare(strict_types=1); * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. + * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ diff --git a/lib/private/App/AppStore/Fetcher/AppFetcher.php b/lib/private/App/AppStore/Fetcher/AppFetcher.php index d6affe4f09b..889facb3709 100644 --- a/lib/private/App/AppStore/Fetcher/AppFetcher.php +++ b/lib/private/App/AppStore/Fetcher/AppFetcher.php @@ -4,6 +4,7 @@ * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Christoph Wurst <christoph@winzerhof-wurst.at> + * @author Georg Ehrke <oc.list@georgehrke.com> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> @@ -35,7 +36,6 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\Http\Client\IClientService; use OCP\IConfig; use OCP\ILogger; -use OCP\Util; class AppFetcher extends Fetcher { diff --git a/lib/private/App/AppStore/Fetcher/CategoryFetcher.php b/lib/private/App/AppStore/Fetcher/CategoryFetcher.php index 7fd3969cd04..e34fbee8c58 100644 --- a/lib/private/App/AppStore/Fetcher/CategoryFetcher.php +++ b/lib/private/App/AppStore/Fetcher/CategoryFetcher.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> * + * @author Georg Ehrke <oc.list@georgehrke.com> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> diff --git a/lib/private/App/AppStore/Fetcher/Fetcher.php b/lib/private/App/AppStore/Fetcher/Fetcher.php index e2876dd28c6..fd0600a3ce4 100644 --- a/lib/private/App/AppStore/Fetcher/Fetcher.php +++ b/lib/private/App/AppStore/Fetcher/Fetcher.php @@ -38,7 +38,6 @@ use OCP\Files\NotFoundException; use OCP\Http\Client\IClientService; use OCP\IConfig; use OCP\ILogger; -use OCP\Util; abstract class Fetcher { const INVALIDATE_AFTER_SECONDS = 300; diff --git a/lib/private/App/CodeChecker/InfoChecker.php b/lib/private/App/CodeChecker/InfoChecker.php index 0db9571d48a..038fd34f436 100644 --- a/lib/private/App/CodeChecker/InfoChecker.php +++ b/lib/private/App/CodeChecker/InfoChecker.php @@ -24,8 +24,6 @@ namespace OC\App\CodeChecker; use OC\Hooks\BasicEmitter; -use OCP\App\AppPathNotFoundException; -use OCP\App\IAppManager; class InfoChecker extends BasicEmitter { diff --git a/lib/private/App/DependencyAnalyzer.php b/lib/private/App/DependencyAnalyzer.php index a59e8c21735..f950a5bd91f 100644 --- a/lib/private/App/DependencyAnalyzer.php +++ b/lib/private/App/DependencyAnalyzer.php @@ -4,6 +4,7 @@ * @copyright Copyright (c) 2016, Lukas Reschke <lukas@statuscode.ch> * * @author Bernhard Posselt <dev@bernhard-posselt.com> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> @@ -29,7 +30,6 @@ namespace OC\App; -use OCP\IConfig; use OCP\IL10N; class DependencyAnalyzer { @@ -188,7 +188,7 @@ class DependencyAnalyzer { return $missing; } if (!is_array($supportedDatabases)) { - $supportedDatabases = array($supportedDatabases); + $supportedDatabases = [$supportedDatabases]; } $supportedDatabases = array_map(function ($db) { return $this->getValue($db); @@ -212,7 +212,7 @@ class DependencyAnalyzer { $commands = $dependencies['command']; if (!is_array($commands)) { - $commands = array($commands); + $commands = [$commands]; } if (isset($commands['@value'])) { $commands = [$commands]; @@ -242,7 +242,7 @@ class DependencyAnalyzer { $libs = $dependencies['lib']; if (!is_array($libs)) { - $libs = array($libs); + $libs = [$libs]; } if (isset($libs['@value'])) { $libs = [$libs]; @@ -294,7 +294,7 @@ class DependencyAnalyzer { return $this->getValue($os); }, $oss); } else { - $oss = array($oss); + $oss = [$oss]; } $currentOS = $this->platform->getOS(); if (!in_array($currentOS, $oss)) { diff --git a/lib/private/App/PlatformRepository.php b/lib/private/App/PlatformRepository.php index c285554ae1c..816470e1202 100644 --- a/lib/private/App/PlatformRepository.php +++ b/lib/private/App/PlatformRepository.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> * @@ -38,11 +39,11 @@ class PlatformRepository { protected function initialize() { $loadedExtensions = get_loaded_extensions(); - $packages = array(); + $packages = []; // Extensions scanning foreach ($loadedExtensions as $name) { - if (in_array($name, array('standard', 'Core'))) { + if (in_array($name, ['standard', 'Core'])) { continue; } diff --git a/lib/private/AppFramework/DependencyInjection/DIContainer.php b/lib/private/AppFramework/DependencyInjection/DIContainer.php index 1dbccf7590b..6f4a48d8907 100644 --- a/lib/private/AppFramework/DependencyInjection/DIContainer.php +++ b/lib/private/AppFramework/DependencyInjection/DIContainer.php @@ -83,7 +83,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { * @param array $urlParams * @param ServerContainer|null $server */ - public function __construct($appName, $urlParams = array(), ServerContainer $server = null){ + public function __construct($appName, $urlParams = [], ServerContainer $server = null){ parent::__construct(); $this['AppName'] = $appName; $this['urlParams'] = $urlParams; diff --git a/lib/private/AppFramework/Http.php b/lib/private/AppFramework/Http.php index 383dffb63d3..56503ce9595 100644 --- a/lib/private/AppFramework/Http.php +++ b/lib/private/AppFramework/Http.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Julius Härtl <jus@bitgrid.net> * @author Lukas Reschke <lukas@statuscode.ch> @@ -45,7 +46,7 @@ class Http extends BaseHttp { $this->server = $server; $this->protocolVersion = $protocolVersion; - $this->headers = array( + $this->headers = [ self::STATUS_CONTINUE => 'Continue', self::STATUS_SWITCHING_PROTOCOLS => 'Switching Protocols', self::STATUS_PROCESSING => 'Processing', @@ -105,7 +106,7 @@ class Http extends BaseHttp { self::STATUS_BANDWIDTH_LIMIT_EXCEEDED => 'Bandwidth Limit Exceeded', // non-standard self::STATUS_NOT_EXTENDED => 'Not extended', self::STATUS_NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required', // draft-nottingham-http-new-status - ); + ]; } diff --git a/lib/private/AppFramework/Middleware/PublicShare/PublicShareMiddleware.php b/lib/private/AppFramework/Middleware/PublicShare/PublicShareMiddleware.php index 131612848cb..b6e2611179f 100644 --- a/lib/private/AppFramework/Middleware/PublicShare/PublicShareMiddleware.php +++ b/lib/private/AppFramework/Middleware/PublicShare/PublicShareMiddleware.php @@ -26,7 +26,6 @@ namespace OC\AppFramework\Middleware\PublicShare; use OC\AppFramework\Middleware\PublicShare\Exceptions\NeedAuthenticationException; use OCP\AppFramework\AuthPublicShareController; use OCP\AppFramework\Http\NotFoundResponse; -use OCP\AppFramework\Http\Response; use OCP\AppFramework\Middleware; use OCP\AppFramework\PublicShareController; use OCP\Files\NotFoundException; diff --git a/lib/private/AppFramework/Middleware/Security/FeaturePolicyMiddleware.php b/lib/private/AppFramework/Middleware/Security/FeaturePolicyMiddleware.php index 67d2480a1f2..63f665f512d 100644 --- a/lib/private/AppFramework/Middleware/Security/FeaturePolicyMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/FeaturePolicyMiddleware.php @@ -26,14 +26,9 @@ declare(strict_types=1); namespace OC\AppFramework\Middleware\Security; -use OC\Security\CSP\ContentSecurityPolicyManager; -use OC\Security\CSP\ContentSecurityPolicyNonceManager; -use OC\Security\CSRF\CsrfTokenManager; use OC\Security\FeaturePolicy\FeaturePolicy; use OC\Security\FeaturePolicy\FeaturePolicyManager; use OCP\AppFramework\Controller; -use OCP\AppFramework\Http\ContentSecurityPolicy; -use OCP\AppFramework\Http\EmptyContentSecurityPolicy; use OCP\AppFramework\Http\EmptyFeaturePolicy; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Middleware; diff --git a/lib/private/AppFramework/Middleware/SessionMiddleware.php b/lib/private/AppFramework/Middleware/SessionMiddleware.php index 00ead5f2476..1f4ba123104 100644 --- a/lib/private/AppFramework/Middleware/SessionMiddleware.php +++ b/lib/private/AppFramework/Middleware/SessionMiddleware.php @@ -29,7 +29,6 @@ use OC\AppFramework\Utility\ControllerMethodReflector; use OCP\AppFramework\Controller; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Middleware; -use OCP\IRequest; use OCP\ISession; class SessionMiddleware extends Middleware { diff --git a/lib/private/AppFramework/OCS/BaseResponse.php b/lib/private/AppFramework/OCS/BaseResponse.php index c7aa5ad073b..6c49a685985 100644 --- a/lib/private/AppFramework/OCS/BaseResponse.php +++ b/lib/private/AppFramework/OCS/BaseResponse.php @@ -2,6 +2,8 @@ /** * @copyright 2016 Roeland Jago Douma <roeland@famdouma.nl> * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> + * @author Daniel Kesselberg <mail@danielkesselberg.de> * @author Joas Schilling <coding@schilljs.com> * @author Roeland Jago Douma <roeland@famdouma.nl> * @@ -26,7 +28,6 @@ namespace OC\AppFramework\OCS; use OCP\AppFramework\Http; use OCP\AppFramework\Http\DataResponse; -use OCP\AppFramework\Http\EmptyContentSecurityPolicy; use OCP\AppFramework\Http\Response; abstract class BaseResponse extends Response { diff --git a/lib/private/Archive/TAR.php b/lib/private/Archive/TAR.php index 20bab49adf8..d90e21305c3 100644 --- a/lib/private/Archive/TAR.php +++ b/lib/private/Archive/TAR.php @@ -3,8 +3,8 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bart Visscher <bartv@thisnet.nl> - * @author Christian Weiske <cweiske@cweiske.de> * @author Christopher Schäpers <kondou@ts.unde.re> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Morris Jobke <hey@morrisjobke.de> @@ -52,7 +52,7 @@ class TAR extends Archive { * @param string $source */ public function __construct($source) { - $types = array(null, 'gz', 'bz2'); + $types = [null, 'gz', 'bz2']; $this->path = $source; $this->tar = new \Archive_Tar($source, $types[self::getTarType($source)]); } @@ -103,7 +103,7 @@ class TAR extends Archive { mkdir($folder); } } - $result = $this->tar->addModify(array($tmpBase . $path), '', $tmpBase); + $result = $this->tar->addModify([$tmpBase . $path], '', $tmpBase); rmdir($tmpBase . $path); $this->fileList = false; $this->cachedHeaders = false; @@ -144,9 +144,9 @@ class TAR extends Archive { rename($tmp . $source, $tmp . $dest); $this->tar = null; unlink($this->path); - $types = array(null, 'gz', 'bz'); + $types = [null, 'gz', 'bz']; $this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]); - $this->tar->createModify(array($tmp), '', $tmp . '/'); + $this->tar->createModify([$tmp], '', $tmp . '/'); $this->fileList = false; $this->cachedHeaders = false; return true; @@ -201,7 +201,7 @@ class TAR extends Archive { */ public function getFolder($path) { $files = $this->getFiles(); - $folderContent = array(); + $folderContent = []; $pathLength = strlen($path); foreach ($files as $file) { if ($file[0] == '/') { @@ -232,7 +232,7 @@ class TAR extends Archive { if (!$this->cachedHeaders) { $this->cachedHeaders = $this->tar->listContent(); } - $files = array(); + $files = []; foreach ($this->cachedHeaders as $header) { $files[] = $header['filename']; } @@ -263,9 +263,9 @@ class TAR extends Archive { return false; } if ($this->fileExists('/' . $path)) { - $success = $this->tar->extractList(array('/' . $path), $tmp); + $success = $this->tar->extractList(['/' . $path], $tmp); } else { - $success = $this->tar->extractList(array($path), $tmp); + $success = $this->tar->extractList([$path], $tmp); } if ($success) { rename($tmp . $path, $dest); @@ -329,7 +329,7 @@ class TAR extends Archive { $this->tar = null; unlink($this->path); $this->reopen(); - $this->tar->createModify(array($tmp), '', $tmp); + $this->tar->createModify([$tmp], '', $tmp); return true; } @@ -378,7 +378,7 @@ class TAR extends Archive { $this->tar->_close(); $this->tar = null; } - $types = array(null, 'gz', 'bz'); + $types = [null, 'gz', 'bz']; $this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]); } } diff --git a/lib/private/Archive/ZIP.php b/lib/private/Archive/ZIP.php index 2c3df550f71..cca6fd68c4e 100644 --- a/lib/private/Archive/ZIP.php +++ b/lib/private/Archive/ZIP.php @@ -5,6 +5,7 @@ * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> * @author Christopher Schäpers <kondou@ts.unde.re> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Morris Jobke <hey@morrisjobke.de> @@ -113,7 +114,7 @@ class ZIP extends Archive{ */ public function getFolder($path) { $files=$this->getFiles(); - $folderContent=array(); + $folderContent=[]; $pathLength=strlen($path); foreach($files as $file) { if(substr($file, 0, $pathLength)==$path and $file!=$path) { @@ -130,7 +131,7 @@ class ZIP extends Archive{ */ public function getFiles() { $fileCount=$this->zip->numFiles; - $files=array(); + $files=[]; for($i=0;$i<$fileCount;$i++) { $files[]=$this->zip->getNameIndex($i); } diff --git a/lib/private/Authentication/Events/ARemoteWipeEvent.php b/lib/private/Authentication/Events/ARemoteWipeEvent.php index 9dfd740c220..111c6cfeeef 100644 --- a/lib/private/Authentication/Events/ARemoteWipeEvent.php +++ b/lib/private/Authentication/Events/ARemoteWipeEvent.php @@ -28,7 +28,6 @@ namespace OC\Authentication\Events; use OC\Authentication\Token\IToken; use OCP\EventDispatcher\Event; -use Symfony\Component\EventDispatcher\GenericEvent; abstract class ARemoteWipeEvent extends Event { diff --git a/lib/private/Authentication/Events/LoginFailed.php b/lib/private/Authentication/Events/LoginFailed.php new file mode 100644 index 00000000000..cc5a547fdef --- /dev/null +++ b/lib/private/Authentication/Events/LoginFailed.php @@ -0,0 +1,43 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl> + * + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace OC\Authentication\Events; + +use OCP\EventDispatcher\Event; + +class LoginFailed extends Event { + + /** @var string */ + private $loginName; + + public function __construct(string $loginName) { + parent::__construct(); + + $this->loginName = $loginName; + } + + public function getLoginName(): string { + return $this->loginName; + } +} diff --git a/lib/private/Authentication/Listeners/LoginFailedListener.php b/lib/private/Authentication/Listeners/LoginFailedListener.php new file mode 100644 index 00000000000..d4f46d9547f --- /dev/null +++ b/lib/private/Authentication/Listeners/LoginFailedListener.php @@ -0,0 +1,64 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl> + * + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace OC\Authentication\Listeners; + +use OC\Authentication\Events\LoginFailed; +use OCP\Authentication\Events\LoginFailedEvent; +use OCP\EventDispatcher\Event; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\EventDispatcher\IEventListener; +use OCP\IUserManager; +use OCP\Util; + +class LoginFailedListener implements IEventListener { + + /** @var IEventDispatcher */ + private $dispatcher; + + /** @var IUserManager */ + private $userManager; + + public function __construct(IEventDispatcher $dispatcher, IUserManager $userManager) { + $this->dispatcher = $dispatcher; + $this->userManager = $userManager; + } + + public function handle(Event $event): void { + if (!($event instanceof LoginFailed)) { + return; + } + + $uid = $event->getLoginName(); + Util::emitHook( + '\OCA\Files_Sharing\API\Server2Server', + 'preLoginNameUsedAsUserName', + ['uid' => &$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 57ea002c6ab..f7d3693acc9 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php @@ -27,7 +27,6 @@ declare(strict_types=1); namespace OC\Authentication\Listeners; use BadMethodCallException; -use OC\Authentication\Events\ARemoteWipeEvent; use OC\Authentication\Events\RemoteWipeFinished; use OC\Authentication\Events\RemoteWipeStarted; use OC\Authentication\Token\IToken; diff --git a/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php b/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php index f97d8da7351..9eab3e74e9c 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php @@ -27,7 +27,6 @@ declare(strict_types=1); namespace OC\Authentication\Listeners; -use OC\Authentication\Events\ARemoteWipeEvent; use OC\Authentication\Events\RemoteWipeFinished; use OC\Authentication\Events\RemoteWipeStarted; use OC\Authentication\Token\IToken; diff --git a/lib/private/Authentication/Login/CreateSessionTokenCommand.php b/lib/private/Authentication/Login/CreateSessionTokenCommand.php index fbc8215e67f..05b6c27f565 100644 --- a/lib/private/Authentication/Login/CreateSessionTokenCommand.php +++ b/lib/private/Authentication/Login/CreateSessionTokenCommand.php @@ -51,17 +51,31 @@ class CreateSessionTokenCommand extends ALoginCommand { $tokenType = IToken::DO_NOT_REMEMBER; } - $this->userSession->createSessionToken( - $loginData->getRequest(), - $loginData->getUser()->getUID(), - $loginData->getUsername(), - $loginData->getPassword(), - $tokenType - ); - $this->userSession->updateTokens( - $loginData->getUser()->getUID(), - $loginData->getPassword() - ); + if ($loginData->getPassword() === '') { + $this->userSession->createSessionToken( + $loginData->getRequest(), + $loginData->getUser()->getUID(), + $loginData->getUsername(), + null, + $tokenType + ); + $this->userSession->updateTokens( + $loginData->getUser()->getUID(), + '' + ); + } else { + $this->userSession->createSessionToken( + $loginData->getRequest(), + $loginData->getUser()->getUID(), + $loginData->getUsername(), + $loginData->getPassword(), + $tokenType + ); + $this->userSession->updateTokens( + $loginData->getUser()->getUID(), + $loginData->getPassword() + ); + } return $this->processNextOrFinishSuccessfully($loginData); } diff --git a/lib/private/Authentication/Login/LoggedInCheckCommand.php b/lib/private/Authentication/Login/LoggedInCheckCommand.php index 9c1e45e0db7..78f27bfa937 100644 --- a/lib/private/Authentication/Login/LoggedInCheckCommand.php +++ b/lib/private/Authentication/Login/LoggedInCheckCommand.php @@ -25,24 +25,36 @@ declare(strict_types=1); namespace OC\Authentication\Login; +use OC\Authentication\Events\LoginFailed; use OC\Core\Controller\LoginController; +use OCP\Authentication\Events\LoginFailedEvent; +use OCP\EventDispatcher\IEventDispatcher; use OCP\ILogger; +use OCP\IUserManager; +use OCP\Util; class LoggedInCheckCommand extends ALoginCommand { /** @var ILogger */ private $logger; + /** @var IEventDispatcher */ + private $dispatcher; + /** @var IUserManager */ + private $userManager; - public function __construct(ILogger $logger) { + public function __construct(ILogger $logger, IEventDispatcher $dispatcher) { $this->logger = $logger; + $this->dispatcher = $dispatcher; } public function process(LoginData $loginData): LoginResult { if ($loginData->getUser() === false) { - $username = $loginData->getUsername(); + $loginName = $loginData->getUsername(); $ip = $loginData->getRequest()->getRemoteAddress(); - $this->logger->warning("Login failed: $username (Remote IP: $ip)"); + $this->logger->warning("Login failed: $loginName (Remote IP: $ip)"); + + $this->dispatcher->dispatchTyped(new LoginFailed($loginName)); return LoginResult::failure($loginData, LoginController::LOGIN_MSG_INVALIDPASSWORD); } diff --git a/lib/private/Authentication/Login/LoginData.php b/lib/private/Authentication/Login/LoginData.php index 3249c44a29a..ec8ebdbab46 100644 --- a/lib/private/Authentication/Login/LoginData.php +++ b/lib/private/Authentication/Login/LoginData.php @@ -56,7 +56,7 @@ class LoginData { public function __construct(IRequest $request, string $username, - string $password, + ?string $password, string $redirectUrl = null, string $timeZone = '', string $timeZoneOffset = '') { @@ -80,7 +80,7 @@ class LoginData { return $this->username; } - public function getPassword(): string { + public function getPassword(): ?string { return $this->password; } diff --git a/lib/private/Authentication/Login/WebAuthnChain.php b/lib/private/Authentication/Login/WebAuthnChain.php new file mode 100644 index 00000000000..dfc6943e853 --- /dev/null +++ b/lib/private/Authentication/Login/WebAuthnChain.php @@ -0,0 +1,96 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl> + * + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace OC\Authentication\Login; + +class WebAuthnChain { + /** @var UserDisabledCheckCommand */ + private $userDisabledCheckCommand; + + /** @var LoggedInCheckCommand */ + private $loggedInCheckCommand; + + /** @var CompleteLoginCommand */ + private $completeLoginCommand; + + /** @var CreateSessionTokenCommand */ + private $createSessionTokenCommand; + + /** @var ClearLostPasswordTokensCommand */ + private $clearLostPasswordTokensCommand; + + /** @var UpdateLastPasswordConfirmCommand */ + private $updateLastPasswordConfirmCommand; + + /** @var SetUserTimezoneCommand */ + private $setUserTimezoneCommand; + + /** @var TwoFactorCommand */ + private $twoFactorCommand; + + /** @var FinishRememberedLoginCommand */ + private $finishRememberedLoginCommand; + + /** @var WebAuthnLoginCommand */ + private $webAuthnLoginCommand; + + public function __construct(UserDisabledCheckCommand $userDisabledCheckCommand, + WebAuthnLoginCommand $webAuthnLoginCommand, + LoggedInCheckCommand $loggedInCheckCommand, + CompleteLoginCommand $completeLoginCommand, + CreateSessionTokenCommand $createSessionTokenCommand, + ClearLostPasswordTokensCommand $clearLostPasswordTokensCommand, + UpdateLastPasswordConfirmCommand $updateLastPasswordConfirmCommand, + SetUserTimezoneCommand $setUserTimezoneCommand, + TwoFactorCommand $twoFactorCommand, + FinishRememberedLoginCommand $finishRememberedLoginCommand + ) { + $this->userDisabledCheckCommand = $userDisabledCheckCommand; + $this->webAuthnLoginCommand = $webAuthnLoginCommand; + $this->loggedInCheckCommand = $loggedInCheckCommand; + $this->completeLoginCommand = $completeLoginCommand; + $this->createSessionTokenCommand = $createSessionTokenCommand; + $this->clearLostPasswordTokensCommand = $clearLostPasswordTokensCommand; + $this->updateLastPasswordConfirmCommand = $updateLastPasswordConfirmCommand; + $this->setUserTimezoneCommand = $setUserTimezoneCommand; + $this->twoFactorCommand = $twoFactorCommand; + $this->finishRememberedLoginCommand = $finishRememberedLoginCommand; + } + + public function process(LoginData $loginData): LoginResult { + $chain = $this->userDisabledCheckCommand; + $chain + ->setNext($this->webAuthnLoginCommand) + ->setNext($this->loggedInCheckCommand) + ->setNext($this->completeLoginCommand) + ->setNext($this->createSessionTokenCommand) + ->setNext($this->clearLostPasswordTokensCommand) + ->setNext($this->updateLastPasswordConfirmCommand) + ->setNext($this->setUserTimezoneCommand) + ->setNext($this->twoFactorCommand) + ->setNext($this->finishRememberedLoginCommand); + + return $chain->process($loginData); + } +} diff --git a/lib/private/Authentication/Login/WebAuthnLoginCommand.php b/lib/private/Authentication/Login/WebAuthnLoginCommand.php new file mode 100644 index 00000000000..e477a243c56 --- /dev/null +++ b/lib/private/Authentication/Login/WebAuthnLoginCommand.php @@ -0,0 +1,48 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl> + * + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace OC\Authentication\Login; + +use OCP\IUserManager; + +class WebAuthnLoginCommand extends ALoginCommand { + + /** @var IUserManager */ + private $userManager; + + public function __construct(IUserManager $userManager) { + $this->userManager = $userManager; + } + + public function process(LoginData $loginData): LoginResult { + $user = $this->userManager->get($loginData->getUsername()); + $loginData->setUser($user); + if ($user === null) { + $loginData->setUser(false); + } + + return $this->processNextOrFinishSuccessfully($loginData); + } + +} diff --git a/lib/private/Authentication/Token/RemoteWipe.php b/lib/private/Authentication/Token/RemoteWipe.php index 2285ccd2cd8..b1fc757f744 100644 --- a/lib/private/Authentication/Token/RemoteWipe.php +++ b/lib/private/Authentication/Token/RemoteWipe.php @@ -6,6 +6,7 @@ declare(strict_types=1); * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author Christoph Wurst <christoph@winzerhof-wurst.at> + * @author Joas Schilling <coding@schilljs.com> * @author Roeland Jago Douma <roeland@famdouma.nl> * * @license GNU AGPL version 3 or any later version @@ -30,7 +31,6 @@ namespace OC\Authentication\Token; use function array_filter; use OC\Authentication\Events\RemoteWipeFinished; use OC\Authentication\Events\RemoteWipeStarted; -use OC\Authentication\Exceptions\ExpiredTokenException; use OC\Authentication\Exceptions\InvalidTokenException; use OC\Authentication\Exceptions\WipeTokenException; use OCP\EventDispatcher\IEventDispatcher; @@ -57,18 +57,14 @@ class RemoteWipe { } /** - * @param int $id - * + * @param IToken $token * @return bool * * @throws InvalidTokenException * @throws WipeTokenException - * @throws ExpiredTokenException */ - public function markTokenForWipe(int $id): bool { - $token = $this->tokenProvider->getTokenById($id); - - if (!($token instanceof IWipeableToken)) { + public function markTokenForWipe(IToken $token): bool { + if (!$token instanceof IWipeableToken) { return false; } diff --git a/lib/private/Authentication/TwoFactorAuth/Manager.php b/lib/private/Authentication/TwoFactorAuth/Manager.php index b048d4e1f3c..170048f451b 100644 --- a/lib/private/Authentication/TwoFactorAuth/Manager.php +++ b/lib/private/Authentication/TwoFactorAuth/Manager.php @@ -31,13 +31,11 @@ use function array_diff; use function array_filter; use BadMethodCallException; use Exception; -use OC\Authentication\Exceptions\ExpiredTokenException; use OC\Authentication\Exceptions\InvalidTokenException; use OC\Authentication\Token\IProvider as TokenProvider; use OCP\Activity\IManager; use OCP\AppFramework\Utility\ITimeFactory; use OCP\Authentication\TwoFactorAuth\IActivatableAtLogin; -use OCP\Authentication\TwoFactorAuth\ILoginSetupProvider; use OCP\Authentication\TwoFactorAuth\IProvider; use OCP\Authentication\TwoFactorAuth\IRegistry; use OCP\IConfig; diff --git a/lib/private/Authentication/TwoFactorAuth/ProviderManager.php b/lib/private/Authentication/TwoFactorAuth/ProviderManager.php index 8c41ac30bfd..26c1af0ae17 100644 --- a/lib/private/Authentication/TwoFactorAuth/ProviderManager.php +++ b/lib/private/Authentication/TwoFactorAuth/ProviderManager.php @@ -28,7 +28,6 @@ namespace OC\Authentication\TwoFactorAuth; use OC\Authentication\Exceptions\InvalidProviderException; use OCP\Authentication\TwoFactorAuth\IActivatableByAdmin; -use OCP\Authentication\TwoFactorAuth\IDeactivableByAdmin; use OCP\Authentication\TwoFactorAuth\IDeactivatableByAdmin; use OCP\Authentication\TwoFactorAuth\IProvider; use OCP\Authentication\TwoFactorAuth\IRegistry; diff --git a/lib/private/Authentication/WebAuthn/CredentialRepository.php b/lib/private/Authentication/WebAuthn/CredentialRepository.php new file mode 100644 index 00000000000..c6f8cdfd888 --- /dev/null +++ b/lib/private/Authentication/WebAuthn/CredentialRepository.php @@ -0,0 +1,93 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl> + * + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace OC\Authentication\WebAuthn; + +use OC\Authentication\WebAuthn\Db\PublicKeyCredentialEntity; +use OC\Authentication\WebAuthn\Db\PublicKeyCredentialMapper; +use OCP\AppFramework\Db\IMapperException; +use Webauthn\PublicKeyCredentialSource; +use Webauthn\PublicKeyCredentialSourceRepository; +use Webauthn\PublicKeyCredentialUserEntity; + +class CredentialRepository implements PublicKeyCredentialSourceRepository { + + /** @var PublicKeyCredentialMapper */ + private $credentialMapper; + + public function __construct(PublicKeyCredentialMapper $credentialMapper) { + $this->credentialMapper = $credentialMapper; + } + + public function findOneByCredentialId(string $publicKeyCredentialId): ?PublicKeyCredentialSource { + try { + $entity = $this->credentialMapper->findOneByCredentialId($publicKeyCredentialId); + return $entity->toPublicKeyCredentialSource(); + } catch (IMapperException $e) { + return null; + } + } + + /** + * @return PublicKeyCredentialSource[] + */ + public function findAllForUserEntity(PublicKeyCredentialUserEntity $publicKeyCredentialUserEntity): array { + $uid = $publicKeyCredentialUserEntity->getId(); + $entities = $this->credentialMapper->findAllForUid($uid); + + return array_map(function (PublicKeyCredentialEntity $entity) { + return $entity->toPublicKeyCredentialSource(); + }, $entities); + } + + public function saveAndReturnCredentialSource(PublicKeyCredentialSource $publicKeyCredentialSource, string $name = null): PublicKeyCredentialEntity { + $oldEntity = null; + + try { + $oldEntity = $this->credentialMapper->findOneByCredentialId($publicKeyCredentialSource->getPublicKeyCredentialId()); + } catch (IMapperException $e) { + + } + + if ($name === null) { + $name = 'default'; + } + + $entity = PublicKeyCredentialEntity::fromPublicKeyCrendentialSource($name, $publicKeyCredentialSource); + + if ($oldEntity) { + $entity->setId($oldEntity->getId()); + if ($name === null) { + $entity->setName($oldEntity->getName()); + } + } + + return $this->credentialMapper->insertOrUpdate($entity); + } + + 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 new file mode 100644 index 00000000000..3b0413aef00 --- /dev/null +++ b/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialEntity.php @@ -0,0 +1,92 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl> + * + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace OC\Authentication\WebAuthn\Db; + +use JsonSerializable; +use OCP\AppFramework\Db\Entity; +use Webauthn\PublicKeyCredentialSource; +use Webauthn\TrustPath\TrustPathLoader; + +/** + * @since 19.0.0 + * + * @method string getUid(); + * @method void setUid(string $uid) + * @method string getName(); + * @method void setName(string $name); + * @method string getPublicKeyCredentialId(); + * @method void setPublicKeyCredentialId(string $id); + * @method string getData(); + * @method void setData(string $data); + */ +class PublicKeyCredentialEntity extends Entity implements JsonSerializable { + + /** @var string */ + protected $name; + + /** @var string */ + protected $uid; + + /** @var string */ + protected $publicKeyCredentialId; + + /** @var string */ + protected $data; + + public function __construct() { + $this->addType('name', 'string'); + $this->addType('uid', 'string'); + $this->addType('publicKeyCredentialId', 'string'); + $this->addType('data', 'string'); + } + + static function fromPublicKeyCrendentialSource(string $name, PublicKeyCredentialSource $publicKeyCredentialSource): PublicKeyCredentialEntity { + $publicKeyCredentialEntity = new self(); + + $publicKeyCredentialEntity->setName($name); + $publicKeyCredentialEntity->setUid($publicKeyCredentialSource->getUserHandle()); + $publicKeyCredentialEntity->setPublicKeyCredentialId(base64_encode($publicKeyCredentialSource->getPublicKeyCredentialId())); + $publicKeyCredentialEntity->setData(json_encode($publicKeyCredentialSource)); + + return $publicKeyCredentialEntity; + } + + function toPublicKeyCredentialSource(): PublicKeyCredentialSource { + return PublicKeyCredentialSource::createFromArray( + json_decode($this->getData(), true) + ); + } + + /** + * @inheritDoc + */ + public function jsonSerialize(): array { + return [ + 'id' => $this->getId(), + 'name' => $this->getName(), + ]; + } + +} diff --git a/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialMapper.php b/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialMapper.php new file mode 100644 index 00000000000..c931ccbb3f0 --- /dev/null +++ b/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialMapper.php @@ -0,0 +1,86 @@ +<?php + +declare(strict_types=1); + +/** + * @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl> + * + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace OC\Authentication\WebAuthn\Db; + +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\AppFramework\Db\QBMapper; +use OCP\IDBConnection; + +class PublicKeyCredentialMapper extends QBMapper { + + public function __construct(IDBConnection $db) { + parent::__construct($db, 'webauthn', PublicKeyCredentialEntity::class); + } + + public function findOneByCredentialId(string $publicKeyCredentialId): PublicKeyCredentialEntity { + $qb = $this->db->getQueryBuilder(); + + $qb->select('*') + ->from($this->getTableName()) + ->where( + $qb->expr()->eq('public_key_credential_id', $qb->createNamedParameter(base64_encode($publicKeyCredentialId))) + ); + + return $this->findEntity($qb); + } + + /** + * @return PublicKeyCredentialEntity[] + */ + public function findAllForUid(string $uid): array { + $qb = $this->db->getQueryBuilder(); + + $qb->select('*') + ->from($this->getTableName()) + ->where( + $qb->expr()->eq('uid', $qb->createNamedParameter($uid)) + ); + + return $this->findEntities($qb); + } + + /** + * @param string $uid + * @param int $id + * + * @return PublicKeyCredentialEntity + * @throws DoesNotExistException + */ + public function findById(string $uid, int $id): PublicKeyCredentialEntity { + $qb = $this->db->getQueryBuilder(); + + $qb->select('*') + ->from($this->getTableName()) + ->where($qb->expr()->andX( + $qb->expr()->eq('id', $qb->createNamedParameter($id)), + $qb->expr()->eq('uid', $qb->createNamedParameter($uid)) + )); + + return $this->findEntity($qb); + } + +} diff --git a/lib/private/Authentication/WebAuthn/Manager.php b/lib/private/Authentication/WebAuthn/Manager.php new file mode 100644 index 00000000000..32a90345b5c --- /dev/null +++ b/lib/private/Authentication/WebAuthn/Manager.php @@ -0,0 +1,269 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl> + * + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace OC\Authentication\WebAuthn; + +use Cose\Algorithm\Signature\ECDSA\ES256; +use Cose\Algorithm\Signature\RSA\RS256; +use Cose\Algorithms; +use GuzzleHttp\Psr7\ServerRequest; +use OC\Authentication\WebAuthn\Db\PublicKeyCredentialEntity; +use OC\Authentication\WebAuthn\Db\PublicKeyCredentialMapper; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\IConfig; +use OCP\ILogger; +use OCP\IUser; +use Webauthn\AttestationStatement\AttestationObjectLoader; +use Webauthn\AttestationStatement\AttestationStatementSupportManager; +use Webauthn\AttestationStatement\NoneAttestationStatementSupport; +use Webauthn\AuthenticationExtensions\ExtensionOutputCheckerHandler; +use Webauthn\AuthenticatorAssertionResponse; +use Webauthn\AuthenticatorAssertionResponseValidator; +use Webauthn\AuthenticatorAttestationResponse; +use Webauthn\AuthenticatorAttestationResponseValidator; +use Webauthn\AuthenticatorSelectionCriteria; +use Webauthn\PublicKeyCredentialCreationOptions; +use Webauthn\PublicKeyCredentialDescriptor; +use Webauthn\PublicKeyCredentialLoader; +use Webauthn\PublicKeyCredentialParameters; +use Webauthn\PublicKeyCredentialRequestOptions; +use Webauthn\PublicKeyCredentialRpEntity; +use Webauthn\PublicKeyCredentialSource; +use Webauthn\PublicKeyCredentialUserEntity; +use Webauthn\TokenBinding\TokenBindingNotSupportedHandler; + +class Manager { + + /** @var CredentialRepository */ + private $repository; + + /** @var PublicKeyCredentialMapper */ + private $credentialMapper; + + /** @var ILogger */ + private $logger; + + /** @var IConfig */ + private $config; + + public function __construct( + CredentialRepository $repository, + PublicKeyCredentialMapper $credentialMapper, + ILogger $logger, + IConfig $config + ) { + $this->repository = $repository; + $this->credentialMapper = $credentialMapper; + $this->logger = $logger; + $this->config = $config; + } + + public function startRegistration(IUser $user, string $serverHost): PublicKeyCredentialCreationOptions { + $rpEntity = new PublicKeyCredentialRpEntity( + 'Nextcloud', //Name + $this->stripPort($serverHost), //ID + null //Icon + ); + + $userEntity = new PublicKeyCredentialUserEntity( + $user->getUID(), //Name + $user->getUID(), //ID + $user->getDisplayName() //Display name +// 'https://foo.example.co/avatar/123e4567-e89b-12d3-a456-426655440000' //Icon + ); + + $challenge = random_bytes(32); + + $publicKeyCredentialParametersList = [ + new PublicKeyCredentialParameters('public-key', Algorithms::COSE_ALGORITHM_ES256), + new PublicKeyCredentialParameters('public-key', Algorithms::COSE_ALGORITHM_RS256), + ]; + + $timeout = 60000; + + $excludedPublicKeyDescriptors = [ + ]; + + $authenticatorSelectionCriteria = new AuthenticatorSelectionCriteria(); + + return new PublicKeyCredentialCreationOptions( + $rpEntity, + $userEntity, + $challenge, + $publicKeyCredentialParametersList, + $timeout, + $excludedPublicKeyDescriptors, + $authenticatorSelectionCriteria, + PublicKeyCredentialCreationOptions::ATTESTATION_CONVEYANCE_PREFERENCE_NONE, + null + ); + } + + public function finishRegister(PublicKeyCredentialCreationOptions $publicKeyCredentialCreationOptions, string $name, string $data): PublicKeyCredentialEntity { + $tokenBindingHandler = new TokenBindingNotSupportedHandler(); + + $attestationStatementSupportManager = new AttestationStatementSupportManager(); + $attestationStatementSupportManager->add(new NoneAttestationStatementSupport()); + + $attestationObjectLoader = new AttestationObjectLoader($attestationStatementSupportManager); + $publicKeyCredentialLoader = new PublicKeyCredentialLoader($attestationObjectLoader); + + // Extension Output Checker Handler + $extensionOutputCheckerHandler = new ExtensionOutputCheckerHandler(); + + // Authenticator Attestation Response Validator + $authenticatorAttestationResponseValidator = new AuthenticatorAttestationResponseValidator( + $attestationStatementSupportManager, + $this->repository, + $tokenBindingHandler, + $extensionOutputCheckerHandler + ); + + try { + // Load the data + $publicKeyCredential = $publicKeyCredentialLoader->load($data); + $response = $publicKeyCredential->getResponse(); + + // Check if the response is an Authenticator Attestation Response + if (!$response instanceof AuthenticatorAttestationResponse) { + throw new \RuntimeException('Not an authenticator attestation response'); + } + + // Check the response against the request + $request = ServerRequest::fromGlobals(); + + $publicKeyCredentialSource = $authenticatorAttestationResponseValidator->check( + $response, + $publicKeyCredentialCreationOptions, + $request); + } catch (\Throwable $exception) { + throw $exception; + } + + // Persist the data + return $this->repository->saveAndReturnCredentialSource($publicKeyCredentialSource, $name); + } + + private function stripPort(string $serverHost): string { + return preg_replace('/(:\d+$)/', '', $serverHost); + } + + public function startAuthentication(string $uid, string $serverHost): PublicKeyCredentialRequestOptions { + // List of registered PublicKeyCredentialDescriptor classes associated to the user + $registeredPublicKeyCredentialDescriptors = array_map(function (PublicKeyCredentialEntity $entity) { + $credential = $entity->toPublicKeyCredentialSource(); + return new PublicKeyCredentialDescriptor( + $credential->getType(), + $credential->getPublicKeyCredentialId() + ); + }, $this->credentialMapper->findAllForUid($uid)); + + // Public Key Credential Request Options + return new PublicKeyCredentialRequestOptions( + random_bytes(32), // Challenge + 60000, // Timeout + $this->stripPort($serverHost), // Relying Party ID + $registeredPublicKeyCredentialDescriptors // Registered PublicKeyCredentialDescriptor classes + ); + } + + public function finishAuthentication(PublicKeyCredentialRequestOptions $publicKeyCredentialRequestOptions, string $data, string $uid) { + $attestationStatementSupportManager = new AttestationStatementSupportManager(); + $attestationStatementSupportManager->add(new NoneAttestationStatementSupport()); + + $attestationObjectLoader = new AttestationObjectLoader($attestationStatementSupportManager); + $publicKeyCredentialLoader = new PublicKeyCredentialLoader($attestationObjectLoader); + + $tokenBindingHandler = new TokenBindingNotSupportedHandler(); + $extensionOutputCheckerHandler = new ExtensionOutputCheckerHandler(); + $algorithmManager = new \Cose\Algorithm\Manager(); + $algorithmManager->add(new ES256()); + $algorithmManager->add(new RS256()); + + $authenticatorAssertionResponseValidator = new AuthenticatorAssertionResponseValidator( + $this->repository, + $tokenBindingHandler, + $extensionOutputCheckerHandler, + $algorithmManager + ); + + try { + $this->logger->debug('Loading publickey credentials from: ' . $data); + + // Load the data + $publicKeyCredential = $publicKeyCredentialLoader->load($data); + $response = $publicKeyCredential->getResponse(); + + // Check if the response is an Authenticator Attestation Response + if (!$response instanceof AuthenticatorAssertionResponse) { + throw new \RuntimeException('Not an authenticator attestation response'); + } + + // Check the response against the request + $request = ServerRequest::fromGlobals(); + + $publicKeyCredentialSource = $authenticatorAssertionResponseValidator->check( + $publicKeyCredential->getRawId(), + $response, + $publicKeyCredentialRequestOptions, + $request, + $uid + ); + + } catch (\Throwable $e) { + throw $e; + } + + + + return true; + } + + public function deleteRegistration(IUser $user, int $id): void { + try { + $entry = $this->credentialMapper->findById($user->getUID(), $id); + } catch (DoesNotExistException $e) { + $this->logger->warning("WebAuthn device $id does not exist, can't delete it"); + return; + } + + $this->credentialMapper->delete($entry); + } + + public function isWebAuthnAvailable(): bool { + if (!extension_loaded('bcmath')) { + return false; + } + + if (!extension_loaded('gmp')) { + return false; + } + + if (!$this->config->getSystemValueBool('auth.webauthn.enabled', true)) { + return false; + } + + return true; + } +} diff --git a/lib/private/Avatar/Avatar.php b/lib/private/Avatar/Avatar.php index 8f8e5e449cc..a097db286f2 100644 --- a/lib/private/Avatar/Avatar.php +++ b/lib/private/Avatar/Avatar.php @@ -6,8 +6,8 @@ declare(strict_types=1); * @copyright Copyright (c) 2016, ownCloud, Inc. * @copyright 2018 John Molakvoæ <skjnldsv@protonmail.com> * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Christopher Schäpers <kondou@ts.unde.re> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Jan-Christoph Borchardt <hey@jancborchardt.net> * @author Joas Schilling <coding@schilljs.com> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> @@ -17,6 +17,7 @@ declare(strict_types=1); * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @author Roeland Jago Douma <roeland@famdouma.nl> + * @author Sergey Shliakhov <husband.sergey@gmail.com> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 @@ -232,7 +233,7 @@ abstract class Avatar implements IAvatar { $x = intval(($xi - $xr) / 2); $y = intval(($yi + $yr) / 2); - return array($x, $y); + return [$x, $y]; } /** @@ -242,7 +243,7 @@ abstract class Avatar implements IAvatar { * @return array [r,g,b] steps for each color to go from $steps to $ends */ private function stepCalc($steps, $ends) { - $step = array(); + $step = []; $step[0] = ($ends[1]->r - $ends[0]->r) / $steps; $step[1] = ($ends[1]->g - $ends[0]->g) / $steps; $step[2] = ($ends[1]->b - $ends[0]->b) / $steps; @@ -256,7 +257,7 @@ abstract class Avatar implements IAvatar { * @return int[] between 0 and $maximum */ private function mixPalette($steps, $color1, $color2) { - $palette = array($color1); + $palette = [$color1]; $step = $this->stepCalc($steps, [$color1, $color2]); for ($i = 1; $i < $steps; $i++) { $r = intval($color1->r + ($step[0] * $i)); @@ -275,7 +276,7 @@ abstract class Avatar implements IAvatar { */ private function hashToInt($hash, $maximum) { $final = 0; - $result = array(); + $result = []; // Splitting evenly the string for ($i = 0; $i < strlen($hash); $i++) { diff --git a/lib/private/Avatar/UserAvatar.php b/lib/private/Avatar/UserAvatar.php index fb434fc6947..485e53c249d 100644 --- a/lib/private/Avatar/UserAvatar.php +++ b/lib/private/Avatar/UserAvatar.php @@ -252,7 +252,7 @@ class UserAvatar extends Avatar { $avatar->putContent($data); $ext = 'png'; - $this->folder->newFile('generated'); + $this->folder->newFile('generated', ''); $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true'); } diff --git a/lib/private/BackgroundJob/Job.php b/lib/private/BackgroundJob/Job.php index 26c69a2486c..f0b780d0c70 100644 --- a/lib/private/BackgroundJob/Job.php +++ b/lib/private/BackgroundJob/Job.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Daniel Kesselberg <mail@danielkesselberg.de> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Noveen Sachdeva <noveen.sachdeva@research.iiit.ac.in> diff --git a/lib/private/BackgroundJob/JobList.php b/lib/private/BackgroundJob/JobList.php index 23695bfbe03..1adecb5b32d 100644 --- a/lib/private/BackgroundJob/JobList.php +++ b/lib/private/BackgroundJob/JobList.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Christoph Wurst <christoph@winzerhof-wurst.at> + * @author Georg Ehrke <oc.list@georgehrke.com> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Lukas Reschke <lukas@statuscode.ch> diff --git a/lib/private/BackgroundJob/Legacy/QueuedJob.php b/lib/private/BackgroundJob/Legacy/QueuedJob.php index ba81041c9de..9adaeff89ec 100644 --- a/lib/private/BackgroundJob/Legacy/QueuedJob.php +++ b/lib/private/BackgroundJob/Legacy/QueuedJob.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @@ -28,8 +29,8 @@ class QueuedJob extends \OC\BackgroundJob\QueuedJob { $class = $argument['klass']; $method = $argument['method']; $parameters = $argument['parameters']; - if (is_callable(array($class, $method))) { - call_user_func(array($class, $method), $parameters); + if (is_callable([$class, $method])) { + call_user_func([$class, $method], $parameters); } } } diff --git a/lib/private/Cache/File.php b/lib/private/Cache/File.php index 09ddb78d4f3..be6540ff2d2 100644 --- a/lib/private/Cache/File.php +++ b/lib/private/Cache/File.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Robin Appelman <robin@icewind.nl> @@ -193,11 +194,11 @@ class File implements ICache { } } catch (\OCP\Lock\LockedException $e) { // ignore locked chunks - \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core')); + \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', ['app' => 'core']); } catch (\OCP\Files\ForbiddenException $e) { - \OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core')); + \OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', ['app' => 'core']); } catch (\OCP\Files\LockNotAcquiredException $e) { - \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core')); + \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', ['app' => 'core']); } } } diff --git a/lib/private/CapabilitiesManager.php b/lib/private/CapabilitiesManager.php index 96337627be2..d49c55bb80d 100644 --- a/lib/private/CapabilitiesManager.php +++ b/lib/private/CapabilitiesManager.php @@ -6,6 +6,7 @@ declare(strict_types=1); * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Julius Härtl <jus@bitgrid.net> * @author Morris Jobke <hey@morrisjobke.de> * @author Roeland Jago Douma <roeland@famdouma.nl> @@ -36,7 +37,7 @@ use OCP\ILogger; class CapabilitiesManager { /** @var \Closure[] */ - private $capabilities = array(); + private $capabilities = []; /** @var ILogger */ private $logger; diff --git a/lib/private/Collaboration/Collaborators/GroupPlugin.php b/lib/private/Collaboration/Collaborators/GroupPlugin.php index 694dd161310..404d4da8ca2 100644 --- a/lib/private/Collaboration/Collaborators/GroupPlugin.php +++ b/lib/private/Collaboration/Collaborators/GroupPlugin.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de> * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> + * @author Julius Härtl <jus@bitgrid.net> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * diff --git a/lib/private/Collaboration/Collaborators/UserPlugin.php b/lib/private/Collaboration/Collaborators/UserPlugin.php index cb9d5984016..bf2c1cfeda9 100644 --- a/lib/private/Collaboration/Collaborators/UserPlugin.php +++ b/lib/private/Collaboration/Collaborators/UserPlugin.php @@ -4,8 +4,9 @@ * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Joas Schilling <coding@schilljs.com> + * @author Julius Härtl <jus@bitgrid.net> * @author Morris Jobke <hey@morrisjobke.de> - * @author Thomas Citharel <tcit@tcit.fr> + * @author Thomas Citharel <nextcloud@tcit.fr> * * @license GNU AGPL version 3 or any later version * diff --git a/lib/private/Collaboration/Resources/Manager.php b/lib/private/Collaboration/Resources/Manager.php index 82731cbdb44..35ae0330e51 100644 --- a/lib/private/Collaboration/Resources/Manager.php +++ b/lib/private/Collaboration/Resources/Manager.php @@ -30,7 +30,6 @@ namespace OC\Collaboration\Resources; use Doctrine\DBAL\Exception\UniqueConstraintViolationException; -use OCP\AppFramework\QueryException; use OCP\Collaboration\Resources\CollectionException; use OCP\Collaboration\Resources\ICollection; use OCP\Collaboration\Resources\IManager; diff --git a/lib/private/Comments/Comment.php b/lib/private/Comments/Comment.php index 71687c7a609..3b4a523b884 100644 --- a/lib/private/Comments/Comment.php +++ b/lib/private/Comments/Comment.php @@ -42,6 +42,7 @@ class Comment implements IComment { 'actorId' => '', 'objectType' => '', 'objectId' => '', + 'referenceId' => null, 'creationDT' => null, 'latestChildDT' => null, ]; @@ -396,6 +397,36 @@ class Comment implements IComment { } /** + * returns the reference id of the comment + * + * @return string|null + * @since 19.0.0 + */ + public function getReferenceId(): ?string { + return $this->data['referenceId']; + } + + /** + * sets (overwrites) the reference id of the comment + * + * @param string $referenceId e.g. sha256 hash sum + * @return IComment + * @since 19.0.0 + */ + public function setReferenceId(?string $referenceId): IComment { + if ($referenceId === null) { + $this->data['referenceId'] = $referenceId; + } else { + $referenceId = trim($referenceId); + if ($referenceId === '') { + throw new \InvalidArgumentException('Non empty string expected.'); + } + $this->data['referenceId'] = $referenceId; + } + return $this; + } + + /** * sets the comment data based on an array with keys as taken from the * database. * diff --git a/lib/private/Comments/Manager.php b/lib/private/Comments/Manager.php index f1c72243597..d04f3f965b3 100644 --- a/lib/private/Comments/Manager.php +++ b/lib/private/Comments/Manager.php @@ -29,6 +29,7 @@ namespace OC\Comments; use Doctrine\DBAL\Exception\DriverException; +use Doctrine\DBAL\Exception\InvalidFieldNameException; use OCP\Comments\CommentsEvent; use OCP\Comments\IComment; use OCP\Comments\ICommentsEventHandler; @@ -96,6 +97,7 @@ class Manager implements ICommentsManager { $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']); } $data['children_count'] = (int)$data['children_count']; + $data['reference_id'] = $data['reference_id'] ?? null; return $data; } @@ -744,23 +746,46 @@ class Manager implements ICommentsManager { * @param IComment $comment * @return bool */ - protected function insert(IComment &$comment) { + protected function insert(IComment $comment): bool { + + try { + $result = $this->insertQuery($comment, true); + } catch (InvalidFieldNameException $e) { + // The reference id field was only added in Nextcloud 19. + // In order to not cause too long waiting times on the update, + // it was decided to only add it lazy, as it is also not a critical + // feature, but only helps to have a better experience while commenting. + // So in case the reference_id field is missing, + // we simply save the comment without that field. + $result = $this->insertQuery($comment, false); + } + + return $result; + } + + protected function insertQuery(IComment $comment, bool $tryWritingReferenceId): bool { $qb = $this->dbConn->getQueryBuilder(); - $affectedRows = $qb - ->insert('comments') - ->values([ - 'parent_id' => $qb->createNamedParameter($comment->getParentId()), - 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()), - 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()), - 'actor_type' => $qb->createNamedParameter($comment->getActorType()), - 'actor_id' => $qb->createNamedParameter($comment->getActorId()), - 'message' => $qb->createNamedParameter($comment->getMessage()), - 'verb' => $qb->createNamedParameter($comment->getVerb()), - 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'), - 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'), - 'object_type' => $qb->createNamedParameter($comment->getObjectType()), - 'object_id' => $qb->createNamedParameter($comment->getObjectId()), - ]) + + $values = [ + 'parent_id' => $qb->createNamedParameter($comment->getParentId()), + 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()), + 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()), + 'actor_type' => $qb->createNamedParameter($comment->getActorType()), + 'actor_id' => $qb->createNamedParameter($comment->getActorId()), + 'message' => $qb->createNamedParameter($comment->getMessage()), + 'verb' => $qb->createNamedParameter($comment->getVerb()), + 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'), + 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'), + 'object_type' => $qb->createNamedParameter($comment->getObjectType()), + 'object_id' => $qb->createNamedParameter($comment->getObjectId()), + ]; + + if ($tryWritingReferenceId) { + $values['reference_id'] = $qb->createNamedParameter($comment->getReferenceId()); + } + + $affectedRows = $qb->insert('comments') + ->values($values) ->execute(); if ($affectedRows > 0) { @@ -785,8 +810,21 @@ class Manager implements ICommentsManager { $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId())); $this->uncache($comment->getId()); + try { + $result = $this->updateQuery($comment, true); + } catch (InvalidFieldNameException $e) { + // See function insert() for explanation + $result = $this->updateQuery($comment, false); + } + + $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment); + + return $result; + } + + protected function updateQuery(IComment $comment, bool $tryWritingReferenceId): bool { $qb = $this->dbConn->getQueryBuilder(); - $affectedRows = $qb + $qb ->update('comments') ->set('parent_id', $qb->createNamedParameter($comment->getParentId())) ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId())) @@ -798,17 +836,19 @@ class Manager implements ICommentsManager { ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime')) ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime')) ->set('object_type', $qb->createNamedParameter($comment->getObjectType())) - ->set('object_id', $qb->createNamedParameter($comment->getObjectId())) - ->where($qb->expr()->eq('id', $qb->createParameter('id'))) - ->setParameter('id', $comment->getId()) + ->set('object_id', $qb->createNamedParameter($comment->getObjectId())); + + if ($tryWritingReferenceId) { + $qb->set('reference_id', $qb->createNamedParameter($comment->getReferenceId())); + } + + $affectedRows = $qb->where($qb->expr()->eq('id', $qb->createNamedParameter($comment->getId()))) ->execute(); if ($affectedRows === 0) { throw new NotFoundException('Comment to update does ceased to exist'); } - $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment); - return $affectedRows > 0; } diff --git a/lib/private/Config.php b/lib/private/Config.php index a21c27f1b51..d2ddab5069a 100644 --- a/lib/private/Config.php +++ b/lib/private/Config.php @@ -6,6 +6,7 @@ * @author Aldo "xoen" Giambelluca <xoen@xoen.org> * @author Bart Visscher <bartv@thisnet.nl> * @author Brice Maron <brice@bmaron.net> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Kesselberg <mail@danielkesselberg.de> * @author Frank Karlitschek <frank@karlitschek.de> * @author Jakob Sack <mail@jakobsack.de> @@ -45,7 +46,7 @@ class Config { const ENV_PREFIX = 'NC_'; /** @var array Associative array ($key => $value) */ - protected $cache = array(); + protected $cache = []; /** @var string */ protected $configDir; /** @var string */ @@ -186,7 +187,7 @@ class Config { */ private function readData() { // Default config should always get loaded - $configFiles = array($this->configFilePath); + $configFiles = [$this->configFilePath]; // Add all files in the config dir ending with the same file name $extra = glob($this->configDir.'*.'.$this->configFileName); @@ -246,12 +247,9 @@ class Config { // File does not exist, this can happen when doing a fresh install if(!is_resource ($filePointer)) { - // TODO fix this via DI once it is very clear that this doesn't cause side effects due to initialization order - // currently this breaks app routes but also could have other side effects especially during setup and exception handling - $url = \OC::$server->getURLGenerator()->linkToDocs('admin-dir_permissions'); throw new HintException( "Can't write into config directory!", - 'This can usually be fixed by giving the webserver write access to the config directory. See ' . $url); + 'This can usually be fixed by giving the webserver write access to the config directory.'); } // Try to acquire a file lock diff --git a/lib/private/Contacts/ContactsMenu/ContactsStore.php b/lib/private/Contacts/ContactsMenu/ContactsStore.php index 5b967b4b5cb..8199db952af 100644 --- a/lib/private/Contacts/ContactsMenu/ContactsStore.php +++ b/lib/private/Contacts/ContactsMenu/ContactsStore.php @@ -5,6 +5,7 @@ * * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Georg Ehrke <oc.list@georgehrke.com> + * @author Julius Härtl <jus@bitgrid.net> * @author Lukas Reschke <lukas@statuscode.ch> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Tobia De Koninck <tobia@ledfan.be> @@ -159,7 +160,7 @@ class ContactsStore implements IContactsStore { if ($ownGroupsOnly && $entry->getProperty('isLocalSystemBook') === true) { $uid = $this->userManager->get($entry->getProperty('UID')); - if ($uid === NULL) { + if ($uid === null) { return false; } diff --git a/lib/private/ContactsManager.php b/lib/private/ContactsManager.php index ba709baefe5..2913e2b5864 100644 --- a/lib/private/ContactsManager.php +++ b/lib/private/ContactsManager.php @@ -4,6 +4,7 @@ * * @author Arne Hamann <kontakt+github@arne.email> * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> * @author Morris Jobke <hey@morrisjobke.de> @@ -41,12 +42,12 @@ namespace OC { * - 'escape_like_param' - If set to false wildcards _ and % are not escaped * @return array an array of contacts which are arrays of key-value-pairs */ - public function search($pattern, $searchProperties = array(), $options = array()) { + public function search($pattern, $searchProperties = [], $options = []) { $this->loadAddressBooks(); - $result = array(); + $result = []; foreach($this->addressBooks as $addressBook) { $r = $addressBook->search($pattern, $searchProperties, $options); - $contacts = array(); + $contacts = []; foreach($r as $c){ $c['addressbook-key'] = $addressBook->getKey(); $contacts[] = $c; @@ -131,7 +132,7 @@ namespace OC { */ public function getAddressBooks() { $this->loadAddressBooks(); - $result = array(); + $result = []; foreach($this->addressBooks as $addressBook) { $result[$addressBook->getKey()] = $addressBook->getDisplayName(); } @@ -154,19 +155,19 @@ namespace OC { * removes all registered address book instances */ public function clear() { - $this->addressBooks = array(); - $this->addressBookLoaders = array(); + $this->addressBooks = []; + $this->addressBookLoaders = []; } /** * @var \OCP\IAddressBook[] which holds all registered address books */ - private $addressBooks = array(); + private $addressBooks = []; /** * @var \Closure[] to call to load/register address books */ - private $addressBookLoaders = array(); + private $addressBookLoaders = []; /** * In order to improve lazy loading a closure can be registered which will be called in case @@ -203,7 +204,7 @@ namespace OC { foreach($this->addressBookLoaders as $callable) { $callable($this); } - $this->addressBookLoaders = array(); + $this->addressBookLoaders = []; } } } diff --git a/lib/private/DB/AdapterPgSql.php b/lib/private/DB/AdapterPgSql.php index 6cfd1d458bc..628c91dbb9e 100644 --- a/lib/private/DB/AdapterPgSql.php +++ b/lib/private/DB/AdapterPgSql.php @@ -26,7 +26,6 @@ namespace OC\DB; -use Doctrine\DBAL\DBALException; class AdapterPgSql extends Adapter { protected $compatModePre9_5 = null; diff --git a/lib/private/DB/Connection.php b/lib/private/DB/Connection.php index 8150f08593f..ed00bcd0e04 100644 --- a/lib/private/DB/Connection.php +++ b/lib/private/DB/Connection.php @@ -3,7 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bart Visscher <bartv@thisnet.nl> - * @author Daniel Kesselberg <mail@danielkesselberg.de> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> @@ -41,7 +41,6 @@ use Doctrine\DBAL\Driver; use Doctrine\DBAL\Exception\ConstraintViolationException; use Doctrine\DBAL\Platforms\MySqlPlatform; use Doctrine\DBAL\Schema\Schema; -use Doctrine\DBAL\TransactionIsolationLevel; use OC\DB\QueryBuilder\QueryBuilder; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; @@ -190,7 +189,7 @@ class Connection extends ReconnectWrapper implements IDBConnection { * * @throws \Doctrine\DBAL\DBALException */ - public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null) + public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null) { $query = $this->replaceTablePrefix($query); $query = $this->adapter->fixupStatement($query); @@ -211,7 +210,7 @@ class Connection extends ReconnectWrapper implements IDBConnection { * * @throws \Doctrine\DBAL\DBALException */ - public function executeUpdate($query, array $params = array(), array $types = array()) + public function executeUpdate($query, array $params = [], array $types = []) { $query = $this->replaceTablePrefix($query); $query = $this->adapter->fixupStatement($query); @@ -373,7 +372,7 @@ class Connection extends ReconnectWrapper implements IDBConnection { public function dropTable($table) { $table = $this->tablePrefix . trim($table); $schema = $this->getSchemaManager(); - if($schema->tablesExist(array($table))) { + if($schema->tablesExist([$table])) { $schema->dropTable($table); } } @@ -387,7 +386,7 @@ class Connection extends ReconnectWrapper implements IDBConnection { public function tableExists($table){ $table = $this->tablePrefix . trim($table); $schema = $this->getSchemaManager(); - return $schema->tablesExist(array($table)); + return $schema->tablesExist([$table]); } // internal use diff --git a/lib/private/DB/ConnectionFactory.php b/lib/private/DB/ConnectionFactory.php index 427a292b6b5..fe97048aaac 100644 --- a/lib/private/DB/ConnectionFactory.php +++ b/lib/private/DB/ConnectionFactory.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Andreas Fischer <bantu@owncloud.com> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Kesselberg <mail@danielkesselberg.de> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> @@ -106,9 +107,9 @@ class ConnectionFactory { // \PDO::MYSQL_ATTR_FOUND_ROWS may not be defined, e.g. when the MySQL // driver is missing. In this case, we won't be able to connect anyway. if ($normalizedType === 'mysql' && defined('\PDO::MYSQL_ATTR_FOUND_ROWS')) { - $result['driverOptions'] = array( + $result['driverOptions'] = [ \PDO::MYSQL_ATTR_FOUND_ROWS => true, - ); + ]; } return $result; } diff --git a/lib/private/DB/MDB2SchemaReader.php b/lib/private/DB/MDB2SchemaReader.php index b18929cbd19..7265c978616 100644 --- a/lib/private/DB/MDB2SchemaReader.php +++ b/lib/private/DB/MDB2SchemaReader.php @@ -3,7 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bart Visscher <bartv@thisnet.nl> - * @author Jörn Friedrich Dreyer <jfd@butonic.de> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Oliver Gasser <oliver.gasser@gmail.com> * @author Robin Appelman <robin@icewind.nl> @@ -155,7 +155,7 @@ class MDB2SchemaReader { * @throws \DomainException */ private function loadField($table, $xml) { - $options = array( 'notnull' => false ); + $options = [ 'notnull' => false ]; foreach ($xml->children() as $child) { /** * @var \SimpleXMLElement $child @@ -262,7 +262,7 @@ class MDB2SchemaReader { $table->addColumn($name, $type, $options); if (!empty($options['primary']) && $options['primary']) { - $table->setPrimaryKey(array($name)); + $table->setPrimaryKey([$name]); } } } @@ -274,7 +274,7 @@ class MDB2SchemaReader { */ private function loadIndex($table, $xml) { $name = null; - $fields = array(); + $fields = []; foreach ($xml->children() as $child) { /** * @var \SimpleXMLElement $child diff --git a/lib/private/DB/Migrator.php b/lib/private/DB/Migrator.php index 8b1621a5f55..bda0720b3bb 100644 --- a/lib/private/DB/Migrator.php +++ b/lib/private/DB/Migrator.php @@ -155,7 +155,7 @@ class Migrator { $tmpTable = $this->renameTableSchema($table, $tmpName); $schemaConfig = new SchemaConfig(); $schemaConfig->setName($this->connection->getDatabase()); - $schema = new Schema(array($tmpTable), array(), $schemaConfig); + $schema = new Schema([$tmpTable], [], $schemaConfig); try { $this->applySchema($schema); @@ -180,7 +180,7 @@ class Migrator { * @var \Doctrine\DBAL\Schema\Index[] $indexes */ $indexes = $table->getIndexes(); - $newIndexes = array(); + $newIndexes = []; foreach ($indexes as $index) { if ($index->isPrimary()) { // do not rename primary key @@ -193,7 +193,7 @@ class Migrator { } // foreign keys are not supported so we just set it to an empty array - return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions()); + return new Table($newName, $table->getColumns(), $newIndexes, [], 0, $table->getOptions()); } public function createSchema() { diff --git a/lib/private/DB/MissingColumnInformation.php b/lib/private/DB/MissingColumnInformation.php new file mode 100644 index 00000000000..bcf585848fd --- /dev/null +++ b/lib/private/DB/MissingColumnInformation.php @@ -0,0 +1,43 @@ +<?php + +declare(strict_types=1); + +/** + * @copyright Copyright (c) 2020 Joas Schilling <coding@schilljs.com> + * + * @author Joas Schilling <coding@schilljs.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace OC\DB; + +class MissingColumnInformation { + + private $listOfMissingColumns = []; + + public function addHintForMissingColumn(string $tableName, string $columnName): void { + $this->listOfMissingColumns[] = [ + 'tableName' => $tableName, + 'columnName' => $columnName, + ]; + } + + public function getListOfMissingColumns(): array { + return $this->listOfMissingColumns; + } +} diff --git a/lib/private/DB/MySQLMigrator.php b/lib/private/DB/MySQLMigrator.php index 73122fb0715..e178cfb55d8 100644 --- a/lib/private/DB/MySQLMigrator.php +++ b/lib/private/DB/MySQLMigrator.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> diff --git a/lib/private/DB/OracleConnection.php b/lib/private/DB/OracleConnection.php index 236d462b02c..cc1bf66d874 100644 --- a/lib/private/DB/OracleConnection.php +++ b/lib/private/DB/OracleConnection.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> @@ -46,7 +47,7 @@ class OracleConnection extends Connection { /** * {@inheritDoc} */ - public function insert($tableName, array $data, array $types = array()) { + public function insert($tableName, array $data, array $types = []) { if ($tableName[0] !== $this->getDatabasePlatform()->getIdentifierQuoteCharacter()) { $tableName = $this->quoteIdentifier($tableName); } @@ -57,7 +58,7 @@ class OracleConnection extends Connection { /** * {@inheritDoc} */ - public function update($tableName, array $data, array $identifier, array $types = array()) { + public function update($tableName, array $data, array $identifier, array $types = []) { if ($tableName[0] !== $this->getDatabasePlatform()->getIdentifierQuoteCharacter()) { $tableName = $this->quoteIdentifier($tableName); } @@ -69,7 +70,7 @@ class OracleConnection extends Connection { /** * {@inheritDoc} */ - public function delete($tableExpression, array $identifier, array $types = array()) { + public function delete($tableExpression, array $identifier, array $types = []) { if ($tableExpression[0] !== $this->getDatabasePlatform()->getIdentifierQuoteCharacter()) { $tableExpression = $this->quoteIdentifier($tableExpression); } @@ -86,7 +87,7 @@ class OracleConnection extends Connection { $table = $this->tablePrefix . trim($table); $table = $this->quoteIdentifier($table); $schema = $this->getSchemaManager(); - if($schema->tablesExist(array($table))) { + if($schema->tablesExist([$table])) { $schema->dropTable($table); } } @@ -101,6 +102,6 @@ class OracleConnection extends Connection { $table = $this->tablePrefix . trim($table); $table = $this->quoteIdentifier($table); $schema = $this->getSchemaManager(); - return $schema->tablesExist(array($table)); + return $schema->tablesExist([$table]); } } diff --git a/lib/private/DB/PgSqlTools.php b/lib/private/DB/PgSqlTools.php index d98116292a4..5a9128bc5b2 100644 --- a/lib/private/DB/PgSqlTools.php +++ b/lib/private/DB/PgSqlTools.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Andreas Fischer <bantu@owncloud.com> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author tbelau666 <thomas.belau@gmx.de> * @author Thomas Müller <thomas.mueller@tmit.eu> @@ -57,10 +58,10 @@ class PgSqlTools { $sqlInfo = 'SELECT table_schema, table_name, column_name FROM information_schema.columns WHERE column_default = ? AND table_catalog = ?'; - $sequenceInfo = $conn->fetchAssoc($sqlInfo, array( + $sequenceInfo = $conn->fetchAssoc($sqlInfo, [ "nextval('$sequenceName'::regclass)", $databaseName - )); + ]); $tableName = $sequenceInfo['table_name']; $columnName = $sequenceInfo['column_name']; $sqlMaxId = "SELECT MAX($columnName) FROM $tableName"; diff --git a/lib/private/DB/QueryBuilder/CompositeExpression.php b/lib/private/DB/QueryBuilder/CompositeExpression.php index ba5ee173352..b6546f3c806 100644 --- a/lib/private/DB/QueryBuilder/CompositeExpression.php +++ b/lib/private/DB/QueryBuilder/CompositeExpression.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * * @license AGPL-3.0 @@ -44,7 +45,7 @@ class CompositeExpression implements ICompositeExpression, \Countable { * * @return \OCP\DB\QueryBuilder\ICompositeExpression */ - public function addMultiple(array $parts = array()) { + public function addMultiple(array $parts = []) { $this->compositeExpression->addMultiple($parts); return $this; diff --git a/lib/private/DB/QueryBuilder/QueryBuilder.php b/lib/private/DB/QueryBuilder/QueryBuilder.php index c9fc3eb5f21..bd0869673aa 100644 --- a/lib/private/DB/QueryBuilder/QueryBuilder.php +++ b/lib/private/DB/QueryBuilder/QueryBuilder.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Robin Appelman <robin@icewind.nl> @@ -273,7 +274,7 @@ class QueryBuilder implements IQueryBuilder { * * @return $this This QueryBuilder instance. */ - public function setParameters(array $params, array $types = array()) { + public function setParameters(array $params, array $types = []) { $this->queryBuilder->setParameters($params, $types); return $this; diff --git a/lib/private/DB/SQLiteMigrator.php b/lib/private/DB/SQLiteMigrator.php index bd9504a3fed..16f18be135e 100644 --- a/lib/private/DB/SQLiteMigrator.php +++ b/lib/private/DB/SQLiteMigrator.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> @@ -43,10 +44,10 @@ class SQLiteMigrator extends Migrator { $tmpFile = $this->buildTempDatabase(); copy($dbFile, $tmpFile); - $connectionParams = array( + $connectionParams = [ 'path' => $tmpFile, 'driver' => 'pdo_sqlite', - ); + ]; $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams); try { $this->applySchema($targetSchema, $conn); diff --git a/lib/private/DB/SQLiteSessionInit.php b/lib/private/DB/SQLiteSessionInit.php index a34bd509091..0c53a0587f0 100644 --- a/lib/private/DB/SQLiteSessionInit.php +++ b/lib/private/DB/SQLiteSessionInit.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @author Roeland Jago Douma <roeland@famdouma.nl> @@ -65,6 +66,6 @@ class SQLiteSessionInit implements EventSubscriber { } public function getSubscribedEvents() { - return array(Events::postConnect); + return [Events::postConnect]; } } diff --git a/lib/private/DB/SetTransactionIsolationLevel.php b/lib/private/DB/SetTransactionIsolationLevel.php index 0a65cbbf463..eb15bf11fbe 100644 --- a/lib/private/DB/SetTransactionIsolationLevel.php +++ b/lib/private/DB/SetTransactionIsolationLevel.php @@ -20,7 +20,7 @@ declare(strict_types=1); * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. + * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ diff --git a/lib/private/DateTimeFormatter.php b/lib/private/DateTimeFormatter.php index 4ff3e1e5eaf..bb9e018b584 100644 --- a/lib/private/DateTimeFormatter.php +++ b/lib/private/DateTimeFormatter.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author dartcafe <github@dartcafe.de> * @author Joas Schilling <coding@schilljs.com> * @author Morris Jobke <hey@morrisjobke.de> @@ -311,8 +312,8 @@ class DateTimeFormatter implements \OCP\IDateTimeFormatter { $timeZone = $this->getTimeZone($timeZone); $timestamp = $this->getDateTime($timestamp, $timeZone); - return $l->l($type, $timestamp, array( + return $l->l($type, $timestamp, [ 'width' => $format, - )); + ]); } } diff --git a/lib/private/DirectEditing/Manager.php b/lib/private/DirectEditing/Manager.php index 5e3f7755938..d2c927360b6 100644 --- a/lib/private/DirectEditing/Manager.php +++ b/lib/private/DirectEditing/Manager.php @@ -4,6 +4,7 @@ * * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Julius Härtl <jus@bitgrid.net> + * @author Robin Appelman <robin@icewind.nl> * @author Tobias Kaminsky <tobias@kaminsky.me> * * @license GNU AGPL version 3 or any later version @@ -34,8 +35,6 @@ use OCP\DirectEditing\ACreateFromTemplate; use OCP\DirectEditing\IEditor; use \OCP\DirectEditing\IManager; use OCP\DirectEditing\IToken; -use OCP\DirectEditing\RegisterDirectEditorEvent; -use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\File; use OCP\Files\IRootFolder; use OCP\Files\Node; diff --git a/lib/private/Encryption/DecryptAll.php b/lib/private/Encryption/DecryptAll.php index f7351ec1bed..3f6e4131d64 100644 --- a/lib/private/Encryption/DecryptAll.php +++ b/lib/private/Encryption/DecryptAll.php @@ -5,8 +5,10 @@ * @author Bjoern Schiessle <bjoern@schiessle.org> * @author Björn Schießle <bjoern@schiessle.org> * @author Christian Jürges <christian@eqipe.ch> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Roeland Jago Douma <roeland@famdouma.nl> + * @author sammo2828 <sammo2828@gmail.com> * @author Vincent Petry <pvince81@owncloud.com> * * @license AGPL-3.0 @@ -208,7 +210,7 @@ class DecryptAll { protected function decryptUsersFiles($uid, ProgressBar $progress, $userCount) { $this->setupUserFS($uid); - $directories = array(); + $directories = []; $directories[] = '/' . $uid . '/files'; while ($root = array_pop($directories)) { diff --git a/lib/private/Encryption/File.php b/lib/private/Encryption/File.php index 1c71ec7dd95..578fdeea5e6 100644 --- a/lib/private/Encryption/File.php +++ b/lib/private/Encryption/File.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> @@ -71,10 +72,10 @@ class File implements \OCP\Encryption\IFile { list($owner, $ownerPath) = $this->util->getUidAndFilename($path); // always add owner to the list of users with access to the file - $userIds = array($owner); + $userIds = [$owner]; if (!$this->util->isFile($owner . '/' . $ownerPath)) { - return array('users' => $userIds, 'public' => false); + return ['users' => $userIds, 'public' => false]; } $ownerPath = substr($ownerPath, strlen('/files')); @@ -121,7 +122,7 @@ class File implements \OCP\Encryption\IFile { // Remove duplicate UIDs $uniqueUserIds = array_unique($userIds); - return array('users' => $uniqueUserIds, 'public' => $public); + return ['users' => $uniqueUserIds, 'public' => $public]; } } diff --git a/lib/private/Encryption/Manager.php b/lib/private/Encryption/Manager.php index 183db55c7ea..63d35e6dd86 100644 --- a/lib/private/Encryption/Manager.php +++ b/lib/private/Encryption/Manager.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> @@ -68,7 +69,7 @@ class Manager implements IManager { * @param ArrayCache $arrayCache */ public function __construct(IConfig $config, ILogger $logger, IL10N $l10n, View $rootView, Util $util, ArrayCache $arrayCache) { - $this->encryptionModules = array(); + $this->encryptionModules = []; $this->config = $config; $this->logger = $logger; $this->l = $l10n; @@ -248,7 +249,7 @@ class Manager implements IManager { // If encryption is disabled and there are no loaded modules it makes no sense to load the wrapper if (!empty($this->encryptionModules) || $this->isEnabled()) { $encryptionWrapper = new EncryptionWrapper($this->arrayCache, $this, $this->logger); - Filesystem::addStorageWrapper('oc_encryption', array($encryptionWrapper, 'wrapStorage'), 2); + Filesystem::addStorageWrapper('oc_encryption', [$encryptionWrapper, 'wrapStorage'], 2); } } diff --git a/lib/private/Encryption/Update.php b/lib/private/Encryption/Update.php index 3bb7680989b..f5128abd0b0 100644 --- a/lib/private/Encryption/Update.php +++ b/lib/private/Encryption/Update.php @@ -4,6 +4,7 @@ * * @author Bjoern Schiessle <bjoern@schiessle.org> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> * @@ -158,7 +159,7 @@ class Update { throw new \InvalidArgumentException('No file found for ' . $info->getId()); } - return array($owner, $path); + return [$owner, $path]; } /** @@ -181,7 +182,7 @@ class Update { if ($this->view->is_dir($path)) { $allFiles = $this->util->getAllFiles($path); } else { - $allFiles = array($path); + $allFiles = [$path]; } diff --git a/lib/private/Encryption/Util.php b/lib/private/Encryption/Util.php index b173d1eae5c..9cc78e7ba77 100644 --- a/lib/private/Encryption/Util.php +++ b/lib/private/Encryption/Util.php @@ -4,6 +4,7 @@ * * @author Bjoern Schiessle <bjoern@schiessle.org> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Jan-Christoph Borchardt <hey@jancborchardt.net> * @author Morris Jobke <hey@morrisjobke.de> * @author Roeland Jago Douma <roeland@famdouma.nl> @@ -164,8 +165,8 @@ class Util { * @return array with list of files relative to the users files folder */ public function getAllFiles($dir) { - $result = array(); - $dirList = array($dir); + $result = []; + $dirList = [$dir]; while ($dirList) { $dir = array_pop($dirList); @@ -239,7 +240,7 @@ class Util { $ownerPath = implode('/', array_slice($parts, 2)); - return array($uid, Filesystem::normalizePath($ownerPath)); + return [$uid, Filesystem::normalizePath($ownerPath)]; } @@ -325,7 +326,7 @@ class Util { * @return boolean */ private function isMountPointApplicableToUser($mount, $uid) { - $acceptedUids = array('all', $uid); + $acceptedUids = ['all', $uid]; // check if mount point is applicable for the user $intersection = array_intersect($acceptedUids, $mount['applicable']['users']); if (!empty($intersection)) { diff --git a/lib/private/EventDispatcher/EventDispatcher.php b/lib/private/EventDispatcher/EventDispatcher.php index 4f83d15bffd..91b3e078b25 100644 --- a/lib/private/EventDispatcher/EventDispatcher.php +++ b/lib/private/EventDispatcher/EventDispatcher.php @@ -6,6 +6,7 @@ declare(strict_types=1); * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author Christoph Wurst <christoph@winzerhof-wurst.at> + * @author Joas Schilling <coding@schilljs.com> * @author Roeland Jago Douma <roeland@famdouma.nl> * * @license GNU AGPL version 3 or any later version diff --git a/lib/private/Files/Cache/AbstractCacheEvent.php b/lib/private/Files/Cache/AbstractCacheEvent.php index 741c06f3490..a4029476fa5 100644 --- a/lib/private/Files/Cache/AbstractCacheEvent.php +++ b/lib/private/Files/Cache/AbstractCacheEvent.php @@ -5,6 +5,7 @@ declare(strict_types=1); /** * @copyright Copyright (c) 2019 Robin Appelman <robin@icewind.nl> * + * @author Joas Schilling <coding@schilljs.com> * @author Robin Appelman <robin@icewind.nl> * @author Roeland Jago Douma <roeland@famdouma.nl> * diff --git a/lib/private/Files/Cache/Cache.php b/lib/private/Files/Cache/Cache.php index 92e81cd0f07..11f7eedea26 100644 --- a/lib/private/Files/Cache/Cache.php +++ b/lib/private/Files/Cache/Cache.php @@ -274,7 +274,9 @@ class Cache implements ICache { } $data['path'] = $file; - $data['parent'] = $this->getParentId($file); + if (!isset($data['parent'])) { + $data['parent'] = $this->getParentId($file); + } $data['name'] = basename($file); [$values, $extensionValues] = $this->normalizeData($data); @@ -307,6 +309,10 @@ class Cache implements ICache { } } catch (UniqueConstraintViolationException $e) { // entry exists already + if ($this->connection->inTransaction()) { + $this->connection->commit(); + $this->connection->beginTransaction(); + } } // The file was created in the mean time @@ -609,8 +615,8 @@ class Cache implements ICache { $sourceId = $sourceData['fileid']; $newParentId = $this->getParentId($targetPath); - list($sourceStorageId, $sourcePath) = $sourceCache->getMoveInfo($sourcePath); - list($targetStorageId, $targetPath) = $this->getMoveInfo($targetPath); + [$sourceStorageId, $sourcePath] = $sourceCache->getMoveInfo($sourcePath); + [$targetStorageId, $targetPath] = $this->getMoveInfo($targetPath); if (is_null($sourceStorageId) || $sourceStorageId === false) { throw new \Exception('Invalid source storage id: ' . $sourceStorageId); @@ -880,7 +886,7 @@ class Cache implements ICache { ->whereParent($id); if ($row = $query->execute()->fetch()) { - list($sum, $min) = array_values($row); + [$sum, $min] = array_values($row); $sum = 0 + $sum; $min = 0 + $min; if ($min === -1) { diff --git a/lib/private/Files/Cache/HomeCache.php b/lib/private/Files/Cache/HomeCache.php index ec3c8df519d..b86a31fe4d1 100644 --- a/lib/private/Files/Cache/HomeCache.php +++ b/lib/private/Files/Cache/HomeCache.php @@ -4,6 +4,7 @@ * * @author Andreas Fischer <bantu@owncloud.com> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> @@ -54,14 +55,14 @@ class HomeCache extends Cache { $sql = 'SELECT SUM(`size`) AS f1 ' . 'FROM `*PREFIX*filecache` ' . 'WHERE `parent` = ? AND `storage` = ? AND `size` >= 0'; - $result = \OC_DB::executeAudited($sql, array($id, $this->getNumericStorageId())); + $result = \OC_DB::executeAudited($sql, [$id, $this->getNumericStorageId()]); if ($row = $result->fetchRow()) { $result->closeCursor(); list($sum) = array_values($row); $totalSize = 0 + $sum; $entry['size'] += 0; if ($entry['size'] !== $totalSize) { - $this->update($id, array('size' => $totalSize)); + $this->update($id, ['size' => $totalSize]); } } } diff --git a/lib/private/Files/Cache/Scanner.php b/lib/private/Files/Cache/Scanner.php index 30688a8da3e..f2c998eeeed 100644 --- a/lib/private/Files/Cache/Scanner.php +++ b/lib/private/Files/Cache/Scanner.php @@ -5,6 +5,7 @@ * @author Ari Selseng <ari@selseng.net> * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Jagszent <daniel@jagszent.de> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> @@ -123,7 +124,7 @@ class Scanner extends BasicEmitter implements IScanner { * @param string $file * @param int $reuseExisting * @param int $parentId - * @param array | null $cacheData existing data in the cache for the file to be scanned + * @param array|null|false $cacheData existing data in the cache for the file to be scanned * @param bool $lock set to false to disable getting an additional read lock during scanning * @return array an array of metadata of the scanned file * @throws \OC\ServerNotAvailableException @@ -164,8 +165,8 @@ class Scanner extends BasicEmitter implements IScanner { // pre-emit only if it was a file. By that we avoid counting/treating folders as files if ($data['mimetype'] !== 'httpd/unix-directory') { - $this->emit('\OC\Files\Cache\Scanner', 'scanFile', array($file, $this->storageId)); - \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId)); + $this->emit('\OC\Files\Cache\Scanner', 'scanFile', [$file, $this->storageId]); + \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', ['path' => $file, 'storage' => $this->storageId]); } $parent = dirname($file); @@ -219,22 +220,23 @@ class Scanner extends BasicEmitter implements IScanner { if (!empty($newData)) { // Reset the checksum if the data has changed $newData['checksum'] = ''; + $newData['parent'] = $parentId; $data['fileid'] = $this->addToCache($file, $newData, $fileId); } - if (isset($cacheData['size'])) { + if ($cacheData && isset($cacheData['size'])) { $data['oldSize'] = $cacheData['size']; } else { $data['oldSize'] = 0; } - if (isset($cacheData['encrypted'])) { + if ($cacheData && isset($cacheData['encrypted'])) { $data['encrypted'] = $cacheData['encrypted']; } // post-emit only if it was a file. By that we avoid counting/treating folders as files if ($data['mimetype'] !== 'httpd/unix-directory') { - $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId)); - \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId)); + $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 { @@ -266,8 +268,8 @@ class Scanner extends BasicEmitter implements IScanner { } protected function removeFromCache($path) { - \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path)); - $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path)); + \OC_Hook::emit('Scanner', 'removeFromCache', ['file' => $path]); + $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', [$path]); if ($this->cacheActive) { $this->cache->remove($path); } @@ -283,14 +285,14 @@ class Scanner extends BasicEmitter implements IScanner { if (isset($data['scan_permissions'])) { $data['permissions'] = $data['scan_permissions']; } - \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); - $this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data)); + \OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]); + $this->emit('\OC\Files\Cache\Scanner', 'addToCache', [$path, $this->storageId, $data]); if ($this->cacheActive) { if ($fileId !== -1) { $this->cache->update($fileId, $data); return $fileId; } else { - return $this->cache->put($path, $data); + return $this->cache->insert($path, $data); } } else { return -1; @@ -303,8 +305,8 @@ class Scanner extends BasicEmitter implements IScanner { * @param int $fileId */ protected function updateCache($path, $data, $fileId = -1) { - \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); - $this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data)); + \OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]); + $this->emit('\OC\Files\Cache\Scanner', 'updateCache', [$path, $this->storageId, $data]); if ($this->cacheActive) { if ($fileId !== -1) { $this->cache->update($fileId, $data); @@ -357,7 +359,7 @@ class Scanner extends BasicEmitter implements IScanner { * @return array[] */ protected function getExistingChildren($folderId) { - $existingChildren = array(); + $existingChildren = []; $children = $this->cache->getFolderContentsById($folderId); foreach ($children as $child) { $existingChildren[$child['name']] = $child; @@ -372,7 +374,7 @@ class Scanner extends BasicEmitter implements IScanner { * @return string[] */ protected function getNewChildren($folder) { - $children = array(); + $children = []; if ($dh = $this->storage->opendir($folder)) { if (is_resource($dh)) { while (($file = readdir($dh)) !== false) { @@ -399,7 +401,7 @@ class Scanner extends BasicEmitter implements IScanner { if ($reuse === -1) { $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; } - $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId)); + $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', [$path, $this->storageId]); $size = 0; if (!is_null($folderId)) { $folderId = $this->cache->getId($path); @@ -415,9 +417,9 @@ class Scanner extends BasicEmitter implements IScanner { } } if ($this->cacheActive) { - $this->cache->update($folderId, array('size' => $size)); + $this->cache->update($folderId, ['size' => $size]); } - $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId)); + $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', [$path, $this->storageId]); return $size; } @@ -435,7 +437,7 @@ class Scanner extends BasicEmitter implements IScanner { foreach ($newChildren as $file) { $child = $path ? $path . '/' . $file : $file; try { - $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null; + $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : false; $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock); if ($data) { if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) { @@ -531,7 +533,7 @@ class Scanner extends BasicEmitter implements IScanner { private function runBackgroundScanJob(callable $callback, $path) { try { $callback(); - \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path)); + \OC_Hook::emit('Scanner', 'correctFolderSize', ['path' => $path]); if ($this->cacheActive && $this->cache instanceof Cache) { $this->cache->correctFolderSize($path, null, true); } diff --git a/lib/private/Files/Cache/Storage.php b/lib/private/Files/Cache/Storage.php index 13af41acfea..ca573be798a 100644 --- a/lib/private/Files/Cache/Storage.php +++ b/lib/private/Files/Cache/Storage.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Morris Jobke <hey@morrisjobke.de> @@ -127,7 +128,7 @@ class Storage { public static function getStorageId($numericId) { $sql = 'SELECT `id` FROM `*PREFIX*storages` WHERE `numeric_id` = ?'; - $result = \OC_DB::executeAudited($sql, array($numericId)); + $result = \OC_DB::executeAudited($sql, [$numericId]); if ($row = $result->fetchRow()) { return $row['id']; } else { @@ -194,11 +195,11 @@ class Storage { $storageId = self::adjustStorageId($storageId); $numericId = self::getNumericStorageId($storageId); $sql = 'DELETE FROM `*PREFIX*storages` WHERE `id` = ?'; - \OC_DB::executeAudited($sql, array($storageId)); + \OC_DB::executeAudited($sql, [$storageId]); if (!is_null($numericId)) { $sql = 'DELETE FROM `*PREFIX*filecache` WHERE `storage` = ?'; - \OC_DB::executeAudited($sql, array($numericId)); + \OC_DB::executeAudited($sql, [$numericId]); } } } diff --git a/lib/private/Files/Cache/Updater.php b/lib/private/Files/Cache/Updater.php index 59cff9b3a41..378cadfcace 100644 --- a/lib/private/Files/Cache/Updater.php +++ b/lib/private/Files/Cache/Updater.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Jagszent <daniel@jagszent.de> * @author Michael Gapczynski <GapczynskiM@gmail.com> * @author Morris Jobke <hey@morrisjobke.de> @@ -247,7 +248,7 @@ class Updater implements IUpdater { if ($parentId != -1) { $mtime = $this->storage->filemtime($parent); if ($mtime !== false) { - $this->cache->update($parentId, array('storage_mtime' => $mtime)); + $this->cache->update($parentId, ['storage_mtime' => $mtime]); } } } diff --git a/lib/private/Files/Cache/Watcher.php b/lib/private/Files/Cache/Watcher.php index beb49ff2d65..cd375572b08 100644 --- a/lib/private/Files/Cache/Watcher.php +++ b/lib/private/Files/Cache/Watcher.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Jagszent <daniel@jagszent.de> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> @@ -35,7 +36,7 @@ class Watcher implements IWatcher { protected $watchPolicy = self::CHECK_ONCE; - protected $checkedPaths = array(); + protected $checkedPaths = []; /** * @var \OC\Files\Storage\Storage $storage diff --git a/lib/private/Files/Cache/Wrapper/CacheJail.php b/lib/private/Files/Cache/Wrapper/CacheJail.php index 6f951f978ad..a77270329ad 100644 --- a/lib/private/Files/Cache/Wrapper/CacheJail.php +++ b/lib/private/Files/Cache/Wrapper/CacheJail.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Ari Selseng <ari@selseng.net> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Jagszent <daniel@jagszent.de> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> @@ -209,9 +210,9 @@ class CacheJail extends CacheWrapper { } private function formatSearchResults($results) { - $results = array_filter($results, array($this, 'filterCacheEntry')); + $results = array_filter($results, [$this, 'filterCacheEntry']); $results = array_values($results); - return array_map(array($this, 'formatCacheEntry'), $results); + return array_map([$this, 'formatCacheEntry'], $results); } /** @@ -241,7 +242,7 @@ class CacheJail extends CacheWrapper { $results = $this->getCache()->searchQuery($simpleQuery); $results = $this->formatSearchResults($results); - $limit = $query->getLimit() === 0 ? NULL : $query->getLimit(); + $limit = $query->getLimit() === 0 ? null : $query->getLimit(); $results = array_slice($results, $query->getOffset(), $limit); return $results; @@ -282,7 +283,7 @@ class CacheJail extends CacheWrapper { */ public function getAll() { // not supported - return array(); + return []; } /** diff --git a/lib/private/Files/Cache/Wrapper/CacheWrapper.php b/lib/private/Files/Cache/Wrapper/CacheWrapper.php index 40bac888673..302758bbc22 100644 --- a/lib/private/Files/Cache/Wrapper/CacheWrapper.php +++ b/lib/private/Files/Cache/Wrapper/CacheWrapper.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Ari Selseng <ari@selseng.net> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Jagszent <daniel@jagszent.de> * @author Joas Schilling <coding@schilljs.com> * @author Morris Jobke <hey@morrisjobke.de> @@ -96,7 +97,7 @@ class CacheWrapper extends Cache { */ public function getFolderContentsById($fileId) { $results = $this->getCache()->getFolderContentsById($fileId); - return array_map(array($this, 'formatCacheEntry'), $results); + return array_map([$this, 'formatCacheEntry'], $results); } /** @@ -223,7 +224,7 @@ class CacheWrapper extends Cache { */ public function search($pattern) { $results = $this->getCache()->search($pattern); - return array_map(array($this, 'formatCacheEntry'), $results); + return array_map([$this, 'formatCacheEntry'], $results); } /** @@ -234,12 +235,12 @@ class CacheWrapper extends Cache { */ public function searchByMime($mimetype) { $results = $this->getCache()->searchByMime($mimetype); - return array_map(array($this, 'formatCacheEntry'), $results); + return array_map([$this, 'formatCacheEntry'], $results); } public function searchQuery(ISearchQuery $query) { $results = $this->getCache()->searchQuery($query); - return array_map(array($this, 'formatCacheEntry'), $results); + return array_map([$this, 'formatCacheEntry'], $results); } /** diff --git a/lib/private/Files/Config/MountProviderCollection.php b/lib/private/Files/Config/MountProviderCollection.php index 4ef3f9f8d94..34db652290f 100644 --- a/lib/private/Files/Config/MountProviderCollection.php +++ b/lib/private/Files/Config/MountProviderCollection.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @author Roeland Jago Douma <roeland@famdouma.nl> @@ -46,7 +47,7 @@ class MountProviderCollection implements IMountProviderCollection, Emitter { /** * @var \OCP\Files\Config\IMountProvider[] */ - private $providers = array(); + private $providers = []; /** * @var \OCP\Files\Storage\IStorageFactory @@ -86,7 +87,7 @@ class MountProviderCollection implements IMountProviderCollection, Emitter { }); $mounts = array_reduce($mounts, function (array $mounts, array $providerMounts) { return array_merge($mounts, $providerMounts); - }, array()); + }, []); return $this->filterMounts($user, $mounts); } diff --git a/lib/private/Files/Filesystem.php b/lib/private/Files/Filesystem.php index 24d21ad6049..8fddbf71200 100644 --- a/lib/private/Files/Filesystem.php +++ b/lib/private/Files/Filesystem.php @@ -62,7 +62,6 @@ namespace OC\Files; use OC\Cache\CappedMemoryCache; use OC\Files\Config\MountProviderCollection; use OC\Files\Mount\MountPoint; -use OC\Files\Storage\StorageFactory; use OC\Lockdown\Filesystem\NullStorage; use OCP\Files\Config\IMountProvider; use OCP\Files\NotFoundException; @@ -83,7 +82,7 @@ class Filesystem { */ static private $defaultInstance; - static private $usersSetup = array(); + static private $usersSetup = []; static private $normalizedPathCache = null; @@ -300,7 +299,7 @@ class Filesystem { if (!self::$mounts) { \OC_Util::setupFS(); } - $result = array(); + $result = []; $mounts = self::$mounts->findIn($path); foreach ($mounts as $mount) { $result[] = $mount->getMountPoint(); @@ -356,9 +355,9 @@ class Filesystem { } $mount = self::$mounts->find($path); if ($mount) { - return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/')); + return [$mount->getStorage(), rtrim($mount->getInternalPath($path), '/')]; } else { - return array(null, null); + return [null, null]; } } @@ -461,7 +460,7 @@ class Filesystem { '/' . $user . '/files' )); } - \OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user)); + \OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', ['user' => $user]); } /** @@ -478,7 +477,7 @@ class Filesystem { $userObject = $userManager->get($user); if ($userObject) { $mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader()); - array_walk($mounts, array(self::$mounts, 'addMount')); + array_walk($mounts, [self::$mounts, 'addMount']); } } }); @@ -521,7 +520,7 @@ class Filesystem { */ public static function clearMounts() { if (self::$mounts) { - self::$usersSetup = array(); + self::$usersSetup = []; self::$mounts->clear(); } } @@ -619,7 +618,7 @@ class Filesystem { static public function isFileBlacklisted($filename) { $filename = self::normalizePath($filename); - $blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess')); + $blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', ['.htaccess']); $filename = strtolower(basename($filename)); return in_array($filename, $blacklist); } diff --git a/lib/private/Files/Mount/MountPoint.php b/lib/private/Files/Mount/MountPoint.php index 2b5fa3f7199..2cb25f07044 100644 --- a/lib/private/Files/Mount/MountPoint.php +++ b/lib/private/Files/Mount/MountPoint.php @@ -4,6 +4,7 @@ * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Georg Ehrke <oc.list@georgehrke.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Morris Jobke <hey@morrisjobke.de> @@ -50,7 +51,7 @@ class MountPoint implements IMountPoint { * * @var array */ - protected $arguments = array(); + protected $arguments = []; protected $mountPoint; /** @@ -58,7 +59,7 @@ class MountPoint implements IMountPoint { * * @var array */ - protected $mountOptions = array(); + protected $mountOptions = []; /** * @var \OC\Files\Storage\StorageFactory $loader @@ -87,7 +88,7 @@ class MountPoint implements IMountPoint { */ public function __construct($storage, $mountpoint, $arguments = null, $loader = null, $mountOptions = null, $mountId = null) { if (is_null($arguments)) { - $arguments = array(); + $arguments = []; } if (is_null($loader)) { $this->loader = new StorageFactory(); diff --git a/lib/private/Files/Node/File.php b/lib/private/Files/Node/File.php index dcfa0b93ed1..915e336b996 100644 --- a/lib/private/Files/Node/File.php +++ b/lib/private/Files/Node/File.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Julius Härtl <jus@bitgrid.net> * @author Morris Jobke <hey@morrisjobke.de> @@ -67,12 +68,12 @@ class File extends Node implements \OCP\Files\File { */ public function putContent($data) { if ($this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE)) { - $this->sendHooks(array('preWrite')); + $this->sendHooks(['preWrite']); if ($this->view->file_put_contents($this->path, $data) === false) { throw new GenericFileException('file_put_contents failed'); } $this->fileInfo = null; - $this->sendHooks(array('postWrite')); + $this->sendHooks(['postWrite']); } else { throw new NotPermittedException(); } @@ -85,8 +86,8 @@ class File extends Node implements \OCP\Files\File { * @throws LockedException */ public function fopen($mode) { - $preHooks = array(); - $postHooks = array(); + $preHooks = []; + $postHooks = []; $requiredPermissions = \OCP\Constants::PERMISSION_READ; switch ($mode) { case 'r+': @@ -126,7 +127,7 @@ class File extends Node implements \OCP\Files\File { */ public function delete() { if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) { - $this->sendHooks(array('preDelete')); + $this->sendHooks(['preDelete']); $fileInfo = $this->getFileInfo(); $this->view->unlink($this->path); $nonExisting = new NonExistingFile($this->root, $this->view, $this->path, $fileInfo); diff --git a/lib/private/Files/Node/Folder.php b/lib/private/Files/Node/Folder.php index 727b08e9335..c005e4f7770 100644 --- a/lib/private/Files/Node/Folder.php +++ b/lib/private/Files/Node/Folder.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Julius Härtl <jus@bitgrid.net> * @author Morris Jobke <hey@morrisjobke.de> @@ -205,9 +206,9 @@ class Folder extends Node implements \OCP\Files\Folder { */ public function search($query) { if (is_string($query)) { - return $this->searchCommon('search', array('%' . $query . '%')); + return $this->searchCommon('search', ['%' . $query . '%']); } else { - return $this->searchCommon('searchQuery', array($query)); + return $this->searchCommon('searchQuery', [$query]); } } @@ -218,7 +219,7 @@ class Folder extends Node implements \OCP\Files\Folder { * @return Node[] */ public function searchByMime($mimetype) { - return $this->searchCommon('searchByMime', array($mimetype)); + return $this->searchCommon('searchByMime', [$mimetype]); } /** @@ -229,7 +230,7 @@ class Folder extends Node implements \OCP\Files\Folder { * @return Node[] */ public function searchByTag($tag, $userId) { - return $this->searchCommon('searchByTag', array($tag, $userId)); + return $this->searchCommon('searchByTag', [$tag, $userId]); } /** @@ -243,7 +244,7 @@ class Folder extends Node implements \OCP\Files\Folder { throw new \InvalidArgumentException('searching by owner is only allows on the users home folder'); } - $files = array(); + $files = []; $rootLength = strlen($this->path); $mount = $this->root->getMount($this->path); $storage = $mount->getStorage(); @@ -256,7 +257,7 @@ class Folder extends Node implements \OCP\Files\Folder { $cache = $storage->getCache(''); - $results = call_user_func_array(array($cache, $method), $args); + $results = call_user_func_array([$cache, $method], $args); foreach ($results as $result) { if ($internalRootLength === 0 or substr($result['path'], 0, $internalRootLength) === $internalPath) { $result['internalPath'] = $result['path']; @@ -394,7 +395,7 @@ class Folder extends Node implements \OCP\Files\Folder { public function delete() { if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) { - $this->sendHooks(array('preDelete')); + $this->sendHooks(['preDelete']); $fileInfo = $this->getFileInfo(); $this->view->rmdir($this->path); $nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo); diff --git a/lib/private/Files/Node/LazyRoot.php b/lib/private/Files/Node/LazyRoot.php index 8076c3b4f6a..6c92764aff0 100644 --- a/lib/private/Files/Node/LazyRoot.php +++ b/lib/private/Files/Node/LazyRoot.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Robin Appelman <robin@icewind.nl> * @author Roeland Jago Douma <roeland@famdouma.nl> * @@ -89,14 +90,14 @@ class LazyRoot implements IRootFolder { /** * @inheritDoc */ - public function emit($scope, $method, $arguments = array()) { + public function emit($scope, $method, $arguments = []) { $this->__call(__FUNCTION__, func_get_args()); } /** * @inheritDoc */ - public function mount($storage, $mountPoint, $arguments = array()) { + public function mount($storage, $mountPoint, $arguments = []) { $this->__call(__FUNCTION__, func_get_args()); } diff --git a/lib/private/Files/Node/Node.php b/lib/private/Files/Node/Node.php index 896b3050384..f8591080840 100644 --- a/lib/private/Files/Node/Node.php +++ b/lib/private/Files/Node/Node.php @@ -4,6 +4,7 @@ * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bernhard Posselt <dev@bernhard-posselt.com> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Julius Härtl <jus@bitgrid.net> * @author Morris Jobke <hey@morrisjobke.de> @@ -139,9 +140,9 @@ class Node implements \OCP\Files\Node { */ public function touch($mtime = null) { if ($this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE)) { - $this->sendHooks(array('preTouch')); + $this->sendHooks(['preTouch']); $this->view->touch($this->path, $mtime); - $this->sendHooks(array('postTouch')); + $this->sendHooks(['postTouch']); if ($this->fileInfo) { if (is_null($mtime)) { $mtime = time(); diff --git a/lib/private/Files/Node/Root.php b/lib/private/Files/Node/Root.php index 948715aec04..13c715816ef 100644 --- a/lib/private/Files/Node/Root.php +++ b/lib/private/Files/Node/Root.php @@ -35,6 +35,7 @@ use OC\Cache\CappedMemoryCache; use OC\Files\Mount\Manager; use OC\Files\Mount\MountPoint; use OC\Hooks\PublicEmitter; +use OC\User\NoUserException; use OCP\Files\Config\IUserMountCache; use OCP\Files\IRootFolder; use OCP\Files\NotFoundException; @@ -133,7 +134,7 @@ class Root extends Folder implements IRootFolder { * @param string $method * @param Node[] $arguments */ - public function emit($scope, $method, $arguments = array()) { + public function emit($scope, $method, $arguments = []) { $this->emitter->emit($scope, $method, $arguments); } @@ -142,7 +143,7 @@ class Root extends Folder implements IRootFolder { * @param string $mountPoint * @param array $arguments */ - public function mount($storage, $mountPoint, $arguments = array()) { + public function mount($storage, $mountPoint, $arguments = []) { $mount = new MountPoint($storage, $mountPoint, $arguments); $this->mountManager->addMount($mount); } @@ -352,7 +353,8 @@ class Root extends Folder implements IRootFolder { * * @param string $userId user ID * @return \OCP\Files\Folder - * @throws \OC\User\NoUserException + * @throws NoUserException + * @throws NotPermittedException */ public function getUserFolder($userId) { $userObject = $this->userManager->get($userId); @@ -367,7 +369,7 @@ class Root extends Folder implements IRootFolder { 'app' => 'files', ] ); - throw new \OC\User\NoUserException('Backends provided no user object'); + throw new NoUserException('Backends provided no user object'); } $userId = $userObject->getUID(); diff --git a/lib/private/Files/ObjectStore/NoopScanner.php b/lib/private/Files/ObjectStore/NoopScanner.php index f82eb7b1ddc..2625703b5c4 100644 --- a/lib/private/Files/ObjectStore/NoopScanner.php +++ b/lib/private/Files/ObjectStore/NoopScanner.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Morris Jobke <hey@morrisjobke.de> @@ -44,7 +45,7 @@ class NoopScanner extends Scanner { * @return array an array of metadata of the scanned file */ public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) { - return array(); + return []; } /** @@ -56,7 +57,7 @@ class NoopScanner extends Scanner { * @return array with the meta data of the scanned file or folder */ public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) { - return array(); + return []; } /** diff --git a/lib/private/Files/ObjectStore/ObjectStoreStorage.php b/lib/private/Files/ObjectStore/ObjectStoreStorage.php index e0d437839a0..5dfd835fb94 100644 --- a/lib/private/Files/ObjectStore/ObjectStoreStorage.php +++ b/lib/private/Files/ObjectStore/ObjectStoreStorage.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bjoern Schiessle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Marcel Klehr <mklehr@gmx.net> @@ -245,7 +246,7 @@ class ObjectStoreStorage extends \OC\Files\Storage\Common { $path = $this->normalizePath($path); try { - $files = array(); + $files = []; $folderContents = $this->getCache()->getFolderContents($path); foreach ($folderContents as $file) { $files[] = $file['name']; @@ -375,14 +376,14 @@ class ObjectStoreStorage extends \OC\Files\Storage\Common { // work with all object storage implementations $this->file_put_contents($path, ' '); $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path); - $stat = array( + $stat = [ 'etag' => $this->getETag($path), 'mimetype' => $mimeType, 'size' => 0, 'mtime' => $mtime, 'storage_mtime' => $mtime, 'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE, - ); + ]; $this->getCache()->put($path, $stat); } catch (\Exception $ex) { $this->logger->logException($ex, [ diff --git a/lib/private/Files/ObjectStore/S3ConnectionTrait.php b/lib/private/Files/ObjectStore/S3ConnectionTrait.php index f931b6092a6..5a619182238 100644 --- a/lib/private/Files/ObjectStore/S3ConnectionTrait.php +++ b/lib/private/Files/ObjectStore/S3ConnectionTrait.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016 Robin Appelman <robin@icewind.nl> * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @author S. Cat <33800996+sparrowjack63@users.noreply.github.com> @@ -117,7 +118,7 @@ trait S3ConnectionTrait { if (!$this->connection->isBucketDnsCompatible($this->bucket)) { throw new \Exception("The bucket will not be created because the name is not dns compatible, please correct it: " . $this->bucket); } - $this->connection->createBucket(array('Bucket' => $this->bucket)); + $this->connection->createBucket(['Bucket' => $this->bucket]); $this->testTimeout(); } catch (S3Exception $e) { $logger->logException($e, [ diff --git a/lib/private/Files/SimpleFS/NewSimpleFile.php b/lib/private/Files/SimpleFS/NewSimpleFile.php index 2c74a16fa92..b8e50941e5f 100644 --- a/lib/private/Files/SimpleFS/NewSimpleFile.php +++ b/lib/private/Files/SimpleFS/NewSimpleFile.php @@ -1,7 +1,12 @@ -<?php declare(strict_types=1); +<?php + +declare(strict_types=1); + /** * @copyright Copyright (c) 2020 Robin Appelman <robin@icewind.nl> * + * @author Robin Appelman <robin@icewind.nl> + * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify @@ -15,7 +20,7 @@ * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. + * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ diff --git a/lib/private/Files/SimpleFS/SimpleFolder.php b/lib/private/Files/SimpleFS/SimpleFolder.php index a4ebc6b4e53..169a8d96fd3 100644 --- a/lib/private/Files/SimpleFS/SimpleFolder.php +++ b/lib/private/Files/SimpleFS/SimpleFolder.php @@ -2,6 +2,7 @@ /** * @copyright 2016 Roeland Jago Douma <roeland@famdouma.nl> * + * @author Robin Appelman <robin@icewind.nl> * @author Roeland Jago Douma <roeland@famdouma.nl> * * @license GNU AGPL version 3 or any later version diff --git a/lib/private/Files/Storage/Common.php b/lib/private/Files/Storage/Common.php index 8760fae1185..f2d427227c9 100644 --- a/lib/private/Files/Storage/Common.php +++ b/lib/private/Files/Storage/Common.php @@ -5,6 +5,7 @@ * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Greta Doci <gretadoci@gmail.com> * @author hkjolhede <hkjolhede@gmail.com> * @author Joas Schilling <coding@schilljs.com> @@ -296,7 +297,7 @@ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage { * @return array */ protected function searchInDir($query, $dir = '') { - $files = array(); + $files = []; $dh = $this->opendir($dir); if (is_resource($dh)) { while (($item = readdir($dh)) !== false) { @@ -434,7 +435,7 @@ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage { $path = '/' . $path; } - $output = array(); + $output = []; foreach (explode('/', $path) as $chunk) { if ($chunk == '..') { array_pop($output); diff --git a/lib/private/Files/Storage/DAV.php b/lib/private/Files/Storage/DAV.php index 625e5f3f625..3654ef1285c 100644 --- a/lib/private/Files/Storage/DAV.php +++ b/lib/private/Files/Storage/DAV.php @@ -6,6 +6,7 @@ * @author Bart Visscher <bartv@thisnet.nl> * @author Björn Schießle <bjoern@schiessle.org> * @author Carlos Cerrillo <ccerrillo@gmail.com> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Lukas Reschke <lukas@statuscode.ch> @@ -265,7 +266,7 @@ class DAV extends Common { try { $response = $this->client->propFind( $this->encodePath($path), - array( + [ '{DAV:}getlastmodified', '{DAV:}getcontentlength', '{DAV:}getcontenttype', @@ -273,7 +274,7 @@ class DAV extends Common { '{http://open-collaboration-services.org/ns}share-permissions', '{DAV:}resourcetype', '{DAV:}getetag', - ) + ] ); $this->statCache->set($path, $response); } catch (ClientHttpException $e) { @@ -591,7 +592,7 @@ class DAV extends Common { } catch (\Exception $e) { $this->convertException($e, $path); } - return array(); + return []; } /** {@inheritdoc} */ diff --git a/lib/private/Files/Storage/Local.php b/lib/private/Files/Storage/Local.php index 13a3ca87097..fbb84418e2e 100644 --- a/lib/private/Files/Storage/Local.php +++ b/lib/private/Files/Storage/Local.php @@ -6,6 +6,7 @@ * @author Bart Visscher <bartv@thisnet.nl> * @author Boris Rybalkin <ribalkin@gmail.com> * @author Brice Maron <brice@bmaron.net> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Jakob Sack <mail@jakobsack.de> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> @@ -42,6 +43,7 @@ namespace OC\Files\Storage; use OC\Files\Filesystem; use OC\Files\Storage\Wrapper\Jail; +use OCP\Constants; use OCP\Files\ForbiddenException; use OCP\Files\Storage\IStorage; use OCP\ILogger; @@ -107,12 +109,12 @@ class Local extends \OC\Files\Storage\Common { * @var \SplFileInfo $file */ $file = $it->current(); - if (in_array($file->getBasename(), array('.', '..'))) { + if (in_array($file->getBasename(), ['.', '..'])) { $it->next(); continue; - } elseif ($file->isDir()) { + } else if ($file->isDir()) { rmdir($file->getPathname()); - } elseif ($file->isFile() || $file->isLink()) { + } else if ($file->isFile() || $file->isLink()) { unlink($file->getPathname()); } $it->next(); @@ -150,6 +152,54 @@ class Local extends \OC\Files\Storage\Common { return $statResult; } + /** + * @inheritdoc + */ + public function getMetaData($path) { + $fullPath = $this->getSourcePath($path); + $stat = @stat($fullPath); + if (!$stat) { + return null; + } + + $permissions = Constants::PERMISSION_SHARE; + $statPermissions = $stat['mode']; + $isDir = ($statPermissions & 0x4000) === 0x4000; + if ($statPermissions & 0x0100) { + $permissions += Constants::PERMISSION_READ; + } + if ($statPermissions & 0x0080) { + $permissions += Constants::PERMISSION_UPDATE; + if ($isDir) { + $permissions += Constants::PERMISSION_CREATE; + } + } + + if (!($path === '' || $path === '/')) { // deletable depends on the parents unix permissions + $parent = dirname($fullPath); + if (is_writable($parent)) { + $permissions += Constants::PERMISSION_DELETE; + } + } + + $data = []; + $data['mimetype'] = $isDir ? 'httpd/unix-directory' : \OC::$server->getMimeTypeDetector()->detectPath($path); + $data['mtime'] = $stat['mtime']; + if ($data['mtime'] === false) { + $data['mtime'] = time(); + } + if ($isDir) { + $data['size'] = -1; //unknown + } else { + $data['size'] = $stat['size']; + } + $data['etag'] = $this->calculateEtag($path, $stat); + $data['storage_mtime'] = $data['mtime']; + $data['permissions'] = $permissions; + + return $data; + } + public function filetype($path) { $filetype = filetype($this->getSourcePath($path)); if ($filetype == 'link') { @@ -340,7 +390,7 @@ class Local extends \OC\Files\Storage\Common { * @return array */ protected function searchInDir($query, $dir = '') { - $files = array(); + $files = []; $physicalDir = $this->getSourcePath($dir); foreach (scandir($physicalDir) as $item) { if (\OC\Files\Filesystem::isIgnoredDir($item)) @@ -423,9 +473,13 @@ class Local extends \OC\Files\Storage\Common { * @return string */ public function getETag($path) { - if ($this->is_file($path)) { - $stat = $this->stat($path); + return $this->calculateEtag($path, $this->stat($path)); + } + private function calculateEtag(string $path, array $stat): string { + if ($stat['mode'] & 0x4000) { // is_dir + return parent::getETag($path); + } else { if ($stat === false) { return md5(''); } @@ -445,8 +499,6 @@ class Local extends \OC\Files\Storage\Common { } return md5($toHash); - } else { - return parent::getETag($path); } } diff --git a/lib/private/Files/Storage/Temporary.php b/lib/private/Files/Storage/Temporary.php index bb501cb5565..5e4f834990b 100644 --- a/lib/private/Files/Storage/Temporary.php +++ b/lib/private/Files/Storage/Temporary.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> @@ -30,7 +31,7 @@ namespace OC\Files\Storage; */ class Temporary extends Local{ public function __construct($arguments = null) { - parent::__construct(array('datadir' => \OC::$server->getTempManager()->getTemporaryFolder())); + parent::__construct(['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]); } public function cleanUp() { diff --git a/lib/private/Files/Storage/Wrapper/Encryption.php b/lib/private/Files/Storage/Wrapper/Encryption.php index 68cf6f99ee5..eb92f07d973 100644 --- a/lib/private/Files/Storage/Wrapper/Encryption.php +++ b/lib/private/Files/Storage/Wrapper/Encryption.php @@ -5,6 +5,7 @@ * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bjoern Schiessle <bjoern@schiessle.org> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> @@ -87,7 +88,7 @@ class Encryption extends Wrapper { private $mountManager; /** @var array remember for which path we execute the repair step to avoid recursions */ - private $fixUnencryptedSizeOf = array(); + private $fixUnencryptedSizeOf = []; /** @var ArrayCache */ private $arrayCache; @@ -125,7 +126,7 @@ class Encryption extends Wrapper { $this->uid = $uid; $this->fileHelper = $fileHelper; $this->keyStorage = $keyStorage; - $this->unencryptedSize = array(); + $this->unencryptedSize = []; $this->update = $update; $this->mountManager = $mountManager; $this->arrayCache = $arrayCache; @@ -892,7 +893,7 @@ class Encryption extends Wrapper { * @return array */ protected function parseRawHeader($rawHeader) { - $result = array(); + $result = []; if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) { $header = $rawHeader; $endAt = strpos($header, Util::HEADER_END); diff --git a/lib/private/Files/Storage/Wrapper/Quota.php b/lib/private/Files/Storage/Wrapper/Quota.php index b5a1be95aaf..d4e4be41f71 100644 --- a/lib/private/Files/Storage/Wrapper/Quota.php +++ b/lib/private/Files/Storage/Wrapper/Quota.php @@ -29,6 +29,7 @@ namespace OC\Files\Storage\Wrapper; +use OC\Files\Filesystem; use OCP\Files\Cache\ICacheEntry; use OCP\Files\Storage\IStorage; @@ -44,6 +45,8 @@ class Quota extends Wrapper { */ protected $sizeRoot; + private $config; + /** * @param array $parameters */ @@ -51,6 +54,7 @@ class Quota extends Wrapper { parent::__construct($parameters); $this->quota = $parameters['quota']; $this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : ''; + $this->config = \OC::$server->getSystemConfig(); } /** @@ -65,16 +69,21 @@ class Quota extends Wrapper { * @param \OC\Files\Storage\Storage $storage */ protected function getSize($path, $storage = null) { - if (is_null($storage)) { - $cache = $this->getCache(); - } else { - $cache = $storage->getCache(); - } - $data = $cache->get($path); - if ($data instanceof ICacheEntry and isset($data['size'])) { - return $data['size']; + if ($this->config->getValue('quota_include_external_storage', false)) { + $rootInfo = Filesystem::getFileInfo('', 'ext'); + return $rootInfo->getSize(true); } else { - return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED; + if (is_null($storage)) { + $cache = $this->getCache(); + } else { + $cache = $storage->getCache(); + } + $data = $cache->get($path); + if ($data instanceof ICacheEntry and isset($data['size'])) { + return $data['size']; + } else { + return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED; + } } } diff --git a/lib/private/Files/Storage/Wrapper/Wrapper.php b/lib/private/Files/Storage/Wrapper/Wrapper.php index 7cb24f9b5b6..d67af5cb22e 100644 --- a/lib/private/Files/Storage/Wrapper/Wrapper.php +++ b/lib/private/Files/Storage/Wrapper/Wrapper.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> @@ -503,7 +504,7 @@ class Wrapper implements \OC\Files\Storage\Storage, ILockingStorage, IWriteStrea * @return mixed */ public function __call($method, $args) { - return call_user_func_array(array($this->getWrapperStorage(), $method), $args); + return call_user_func_array([$this->getWrapperStorage(), $method], $args); } /** diff --git a/lib/private/Files/Stream/Encryption.php b/lib/private/Files/Stream/Encryption.php index dc6cd9cea7f..527453c32e9 100644 --- a/lib/private/Files/Stream/Encryption.php +++ b/lib/private/Files/Stream/Encryption.php @@ -4,6 +4,7 @@ * * @author Bjoern Schiessle <bjoern@schiessle.org> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author jknockaert <jasper@knockaert.nl> * @author Lukas Reschke <lukas@statuscode.ch> * @author martink-p <47943787+martink-p@users.noreply.github.com> @@ -109,7 +110,7 @@ class Encryption extends Wrapper { protected $fileUpdated; public function __construct() { - $this->expectedContextProperties = array( + $this->expectedContextProperties = [ 'source', 'storage', 'internalPath', @@ -124,7 +125,7 @@ class Encryption extends Wrapper { 'encryptionStorage', 'headerSize', 'signed' - ); + ]; } @@ -165,8 +166,8 @@ class Encryption extends Wrapper { $signed, $wrapper = Encryption::class) { - $context = stream_context_create(array( - 'ocencryption' => array( + $context = stream_context_create([ + 'ocencryption' => [ 'source' => $source, 'storage' => $storage, 'internalPath' => $internalPath, @@ -181,8 +182,8 @@ class Encryption extends Wrapper { 'encryptionStorage' => $encStorage, 'headerSize' => $headerSize, 'signed' => $signed - ) - )); + ] + ]); return self::wrapSource($source, $context, 'ocencryption', $wrapper, $mode); } diff --git a/lib/private/Files/Stream/Quota.php b/lib/private/Files/Stream/Quota.php index 08272ad61cb..7d5337d3a7d 100644 --- a/lib/private/Files/Stream/Quota.php +++ b/lib/private/Files/Stream/Quota.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> @@ -44,12 +45,12 @@ class Quota extends Wrapper { * @return resource */ static public function wrap($stream, $limit) { - $context = stream_context_create(array( - 'quota' => array( + $context = stream_context_create([ + 'quota' => [ 'source' => $stream, 'limit' => $limit - ) - )); + ] + ]); return Wrapper::wrapSource($stream, $context, 'quota', self::class); } diff --git a/lib/private/Files/Type/Detection.php b/lib/private/Files/Type/Detection.php index 1352963fc67..b36f8a70b99 100644 --- a/lib/private/Files/Type/Detection.php +++ b/lib/private/Files/Type/Detection.php @@ -6,6 +6,7 @@ declare(strict_types=1); * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Andreas Fischer <bantu@owncloud.com> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Kesselberg <mail@danielkesselberg.de> * @author Hendrik Leppelsack <hendrik@leppelsack.de> * @author Jens-Christian Fischer <jens-christian.fischer@switch.ch> @@ -103,7 +104,7 @@ class Detection implements IMimeTypeDetector { public function registerType(string $extension, string $mimetype, ?string $secureMimeType = null): void { - $this->mimetypes[$extension] = array($mimetype, $secureMimeType); + $this->mimetypes[$extension] = [$mimetype, $secureMimeType]; $this->secureMimeTypes[$mimetype] = $secureMimeType ?: $mimetype; } diff --git a/lib/private/Files/Type/Loader.php b/lib/private/Files/Type/Loader.php index 616994d0c7b..fded04b5466 100644 --- a/lib/private/Files/Type/Loader.php +++ b/lib/private/Files/Type/Loader.php @@ -6,7 +6,6 @@ * @author Rello <Rello@users.noreply.github.com> * @author Robin Appelman <robin@icewind.nl> * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Roeland Jago Douma <roeland@famdouma.nl> * * @license AGPL-3.0 * @@ -26,7 +25,6 @@ namespace OC\Files\Type; -use Doctrine\DBAL\Exception\UniqueConstraintViolationException; use OCP\Files\IMimeTypeLoader; use OCP\IDBConnection; diff --git a/lib/private/Files/Type/TemplateManager.php b/lib/private/Files/Type/TemplateManager.php index 4febf9afbf1..5cd6b61f823 100644 --- a/lib/private/Files/Type/TemplateManager.php +++ b/lib/private/Files/Type/TemplateManager.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Julius Härtl <jus@bitgrid.net> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> @@ -29,7 +30,7 @@ namespace OC\Files\Type; * @deprecated 18.0.0 */ class TemplateManager { - protected $templates = array(); + protected $templates = []; public function registerTemplate($mimetype, $path) { $this->templates[$mimetype] = $path; diff --git a/lib/private/Files/Utils/Scanner.php b/lib/private/Files/Utils/Scanner.php index 943078215b5..49f8177834a 100644 --- a/lib/private/Files/Utils/Scanner.php +++ b/lib/private/Files/Utils/Scanner.php @@ -131,19 +131,19 @@ class Scanner extends PublicEmitter { protected function attachListener($mount) { $scanner = $mount->getStorage()->getScanner(); $scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function ($path) use ($mount) { - $this->emit('\OC\Files\Utils\Scanner', 'scanFile', array($mount->getMountPoint() . $path)); + $this->emit('\OC\Files\Utils\Scanner', 'scanFile', [$mount->getMountPoint() . $path]); $this->dispatcher->dispatchTyped(new BeforeFileScannedEvent($mount->getMountPoint() . $path)); }); $scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function ($path) use ($mount) { - $this->emit('\OC\Files\Utils\Scanner', 'scanFolder', array($mount->getMountPoint() . $path)); + $this->emit('\OC\Files\Utils\Scanner', 'scanFolder', [$mount->getMountPoint() . $path]); $this->dispatcher->dispatchTyped(new BeforeFolderScannedEvent($mount->getMountPoint() . $path)); }); $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFile', function ($path) use ($mount) { - $this->emit('\OC\Files\Utils\Scanner', 'postScanFile', array($mount->getMountPoint() . $path)); + $this->emit('\OC\Files\Utils\Scanner', 'postScanFile', [$mount->getMountPoint() . $path]); $this->dispatcher->dispatchTyped(new FileScannedEvent($mount->getMountPoint() . $path)); }); $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFolder', function ($path) use ($mount) { - $this->emit('\OC\Files\Utils\Scanner', 'postScanFolder', array($mount->getMountPoint() . $path)); + $this->emit('\OC\Files\Utils\Scanner', 'postScanFolder', [$mount->getMountPoint() . $path]); $this->dispatcher->dispatchTyped(new FolderScannedEvent($mount->getMountPoint() . $path)); }); } diff --git a/lib/private/Files/View.php b/lib/private/Files/View.php index 8ea94626a2a..e3f704a7cbc 100644 --- a/lib/private/Files/View.php +++ b/lib/private/Files/View.php @@ -5,6 +5,7 @@ * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Florin Peter <github@florin-peter.de> * @author Jesús Macias <jmacias@solidgear.es> * @author Joas Schilling <coding@schilljs.com> @@ -266,7 +267,7 @@ class View { * for \OC\Files\Storage\Storage via basicOperation(). */ public function mkdir($path) { - return $this->basicOperation('mkdir', $path, array('create', 'write')); + return $this->basicOperation('mkdir', $path, ['create', 'write']); } /** @@ -284,7 +285,7 @@ class View { $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true); \OC_Hook::emit( Filesystem::CLASSNAME, "umount", - array(Filesystem::signal_param_path => $relPath) + [Filesystem::signal_param_path => $relPath] ); $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true); $result = $mount->removeMount(); @@ -292,7 +293,7 @@ class View { if ($result) { \OC_Hook::emit( Filesystem::CLASSNAME, "post_umount", - array(Filesystem::signal_param_path => $relPath) + [Filesystem::signal_param_path => $relPath] ); } $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true); @@ -345,7 +346,7 @@ class View { return $this->removeMount($mount, $absolutePath); } if ($this->is_dir($path)) { - $result = $this->basicOperation('rmdir', $path, array('delete')); + $result = $this->basicOperation('rmdir', $path, ['delete']); } else { $result = false; } @@ -363,7 +364,7 @@ class View { * @return resource */ public function opendir($path) { - return $this->basicOperation('opendir', $path, array('read')); + return $this->basicOperation('opendir', $path, ['read']); } /** @@ -559,7 +560,7 @@ class View { $mtime = strtotime($mtime); } - $hooks = array('touch'); + $hooks = ['touch']; if (!$this->file_exists($path)) { $hooks[] = 'create'; @@ -581,7 +582,7 @@ class View { $mtime = time(); } //if native touch fails, we emulate it by changing the mtime in the cache - $this->putFileInfo($path, array('mtime' => floor($mtime))); + $this->putFileInfo($path, ['mtime' => floor($mtime)]); } return true; } @@ -592,7 +593,7 @@ class View { * @throws LockedException */ public function file_get_contents($path) { - return $this->basicOperation('file_get_contents', $path, array('read')); + return $this->basicOperation('file_get_contents', $path, ['read']); } /** @@ -602,20 +603,20 @@ class View { */ protected function emit_file_hooks_pre($exists, $path, &$run) { if (!$exists) { - \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array( + \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [ Filesystem::signal_param_path => $this->getHookPath($path), Filesystem::signal_param_run => &$run, - )); + ]); } else { - \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array( + \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [ Filesystem::signal_param_path => $this->getHookPath($path), Filesystem::signal_param_run => &$run, - )); + ]); } - \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array( + \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [ Filesystem::signal_param_path => $this->getHookPath($path), Filesystem::signal_param_run => &$run, - )); + ]); } /** @@ -624,17 +625,17 @@ class View { */ protected function emit_file_hooks_post($exists, $path) { if (!$exists) { - \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array( + \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [ Filesystem::signal_param_path => $this->getHookPath($path), - )); + ]); } else { - \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array( + \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [ Filesystem::signal_param_path => $this->getHookPath($path), - )); + ]); } - \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array( + \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [ Filesystem::signal_param_path => $this->getHookPath($path), - )); + ]); } /** @@ -690,7 +691,7 @@ class View { return false; } } else { - $hooks = $this->file_exists($path) ? array('update', 'write') : array('create', 'write'); + $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write']; return $this->basicOperation('file_put_contents', $path, $hooks, $data); } } @@ -770,11 +771,11 @@ class View { } elseif ($this->shouldEmitHooks($path1)) { \OC_Hook::emit( Filesystem::CLASSNAME, Filesystem::signal_rename, - array( + [ Filesystem::signal_param_oldpath => $this->getHookPath($path1), Filesystem::signal_param_newpath => $this->getHookPath($path2), Filesystem::signal_param_run => &$run - ) + ] ); } if ($run) { @@ -844,10 +845,10 @@ class View { \OC_Hook::emit( Filesystem::CLASSNAME, Filesystem::signal_post_rename, - array( + [ Filesystem::signal_param_oldpath => $this->getHookPath($path1), Filesystem::signal_param_newpath => $this->getHookPath($path2) - ) + ] ); } } @@ -900,11 +901,11 @@ class View { \OC_Hook::emit( Filesystem::CLASSNAME, Filesystem::signal_copy, - array( + [ Filesystem::signal_param_oldpath => $this->getHookPath($path1), Filesystem::signal_param_newpath => $this->getHookPath($path2), Filesystem::signal_param_run => &$run - ) + ] ); $this->emit_file_hooks_pre($exists, $path2, $run); } @@ -938,10 +939,10 @@ class View { \OC_Hook::emit( Filesystem::CLASSNAME, Filesystem::signal_post_copy, - array( + [ Filesystem::signal_param_oldpath => $this->getHookPath($path1), Filesystem::signal_param_newpath => $this->getHookPath($path2) - ) + ] ); $this->emit_file_hooks_post($exists, $path2); } @@ -968,7 +969,7 @@ class View { */ public function fopen($path, $mode) { $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support - $hooks = array(); + $hooks = []; switch ($mode) { case 'r': $hooks[] = 'read'; @@ -1087,7 +1088,7 @@ class View { \OC_Hook::emit( Filesystem::CLASSNAME, Filesystem::signal_read, - array(Filesystem::signal_param_path => $this->getHookPath($path)) + [Filesystem::signal_param_path => $this->getHookPath($path)] ); } list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix); @@ -1270,18 +1271,18 @@ class View { \OC_Hook::emit( Filesystem::CLASSNAME, $prefix . $hook, - array( + [ Filesystem::signal_param_run => &$run, Filesystem::signal_param_path => $path - ) + ] ); } elseif (!$post) { \OC_Hook::emit( Filesystem::CLASSNAME, $prefix . $hook, - array( + [ Filesystem::signal_param_path => $path - ) + ] ); } } @@ -1297,7 +1298,7 @@ class View { * @return bool */ public function hasUpdated($path, $time) { - return $this->basicOperation('hasUpdated', $path, array(), $time); + return $this->basicOperation('hasUpdated', $path, [], $time); } /** @@ -1591,7 +1592,7 @@ class View { * @return FileInfo[] */ public function search($query) { - return $this->searchCommon('search', array('%' . $query . '%')); + return $this->searchCommon('search', ['%' . $query . '%']); } /** @@ -1601,7 +1602,7 @@ class View { * @return FileInfo[] */ public function searchRaw($query) { - return $this->searchCommon('search', array($query)); + return $this->searchCommon('search', [$query]); } /** @@ -1611,7 +1612,7 @@ class View { * @return FileInfo[] */ public function searchByMime($mimetype) { - return $this->searchCommon('searchByMime', array($mimetype)); + return $this->searchCommon('searchByMime', [$mimetype]); } /** @@ -1622,7 +1623,7 @@ class View { * @return FileInfo[] */ public function searchByTag($tag, $userId) { - return $this->searchCommon('searchByTag', array($tag, $userId)); + return $this->searchCommon('searchByTag', [$tag, $userId]); } /** @@ -1631,7 +1632,7 @@ class View { * @return FileInfo[] */ private function searchCommon($method, $args) { - $files = array(); + $files = []; $rootLength = strlen($this->fakeRoot); $mount = $this->getMount(''); @@ -1640,7 +1641,7 @@ class View { if ($storage) { $cache = $storage->getCache(''); - $results = call_user_func_array(array($cache, $method), $args); + $results = call_user_func_array([$cache, $method], $args); foreach ($results as $result) { if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') { $internalPath = $result['path']; @@ -1659,7 +1660,7 @@ class View { $cache = $storage->getCache(''); $relativeMountPoint = substr($mountPoint, $rootLength); - $results = call_user_func_array(array($cache, $method), $args); + $results = call_user_func_array([$cache, $method], $args); if ($results) { foreach ($results as $result) { $internalPath = $result['path']; @@ -1881,7 +1882,7 @@ class View { // remove the single file array_pop($parts); - $result = array('/'); + $result = ['/']; $resultPath = ''; foreach ($parts as $part) { if ($part) { diff --git a/lib/private/Group/Backend.php b/lib/private/Group/Backend.php index 06cc8ae846f..024366a46be 100644 --- a/lib/private/Group/Backend.php +++ b/lib/private/Group/Backend.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Knut Ahlers <knut@ahlers.me> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Vincent Petry <pvince81@owncloud.com> @@ -94,7 +95,7 @@ abstract class Backend implements \OCP\GroupInterface { * if the user exists at all. */ public function getUserGroups($uid) { - return array(); + return []; } /** @@ -108,7 +109,7 @@ abstract class Backend implements \OCP\GroupInterface { */ public function getGroups($search = '', $limit = -1, $offset = 0) { - return array(); + return []; } /** @@ -129,6 +130,6 @@ abstract class Backend implements \OCP\GroupInterface { * @return array an array of user ids */ public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { - return array(); + return []; } } diff --git a/lib/private/Group/Database.php b/lib/private/Group/Database.php index 27dad809f89..8afd2c4aed2 100644 --- a/lib/private/Group/Database.php +++ b/lib/private/Group/Database.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> * @author Loki3000 <github@labcms.ru> diff --git a/lib/private/Group/Group.php b/lib/private/Group/Group.php index 26e23e3b1b1..90b4221b414 100644 --- a/lib/private/Group/Group.php +++ b/lib/private/Group/Group.php @@ -4,6 +4,7 @@ * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> * @author Lukas Reschke <lukas@statuscode.ch> @@ -51,7 +52,7 @@ class Group implements IGroup { private $gid; /** @var \OC\User\User[] */ - private $users = array(); + private $users = []; /** @var bool */ private $usersLoaded; @@ -127,7 +128,7 @@ class Group implements IGroup { return $this->users; } - $userIds = array(); + $userIds = []; foreach ($this->backends as $backend) { $diff = array_diff( $backend->usersInGroup($this->gid), @@ -177,7 +178,7 @@ class Group implements IGroup { ])); if ($this->emitter) { - $this->emitter->emit('\OC\Group', 'preAddUser', array($this, $user)); + $this->emitter->emit('\OC\Group', 'preAddUser', [$this, $user]); } foreach ($this->backends as $backend) { if ($backend->implementsActions(\OC\Group\Backend::ADD_TO_GROUP)) { @@ -191,7 +192,7 @@ class Group implements IGroup { ])); if ($this->emitter) { - $this->emitter->emit('\OC\Group', 'postAddUser', array($this, $user)); + $this->emitter->emit('\OC\Group', 'postAddUser', [$this, $user]); } return; } @@ -209,7 +210,7 @@ class Group implements IGroup { 'user' => $user, ])); if ($this->emitter) { - $this->emitter->emit('\OC\Group', 'preRemoveUser', array($this, $user)); + $this->emitter->emit('\OC\Group', 'preRemoveUser', [$this, $user]); } foreach ($this->backends as $backend) { if ($backend->implementsActions(\OC\Group\Backend::REMOVE_FROM_GOUP) and $backend->inGroup($user->getUID(), $this->gid)) { @@ -222,7 +223,7 @@ class Group implements IGroup { 'user' => $user, ])); if ($this->emitter) { - $this->emitter->emit('\OC\Group', 'postRemoveUser', array($this, $user)); + $this->emitter->emit('\OC\Group', 'postRemoveUser', [$this, $user]); } if ($this->users) { foreach ($this->users as $index => $groupUser) { @@ -244,7 +245,7 @@ class Group implements IGroup { * @return \OC\User\User[] */ public function searchUsers($search, $limit = null, $offset = null) { - $users = array(); + $users = []; foreach ($this->backends as $backend) { $userIds = $backend->usersInGroup($this->gid, $search, $limit, $offset); $users += $this->getVerifiedUsers($userIds); @@ -305,7 +306,7 @@ class Group implements IGroup { * @return \OC\User\User[] */ public function searchDisplayName($search, $limit = null, $offset = null) { - $users = array(); + $users = []; foreach ($this->backends as $backend) { $userIds = $backend->usersInGroup($this->gid, $search, $limit, $offset); $users = $this->getVerifiedUsers($userIds); @@ -330,7 +331,7 @@ class Group implements IGroup { $result = false; $this->dispatcher->dispatch(IGroup::class . '::preDelete', new GenericEvent($this)); if ($this->emitter) { - $this->emitter->emit('\OC\Group', 'preDelete', array($this)); + $this->emitter->emit('\OC\Group', 'preDelete', [$this]); } foreach ($this->backends as $backend) { if ($backend->implementsActions(\OC\Group\Backend::DELETE_GROUP)) { @@ -341,7 +342,7 @@ class Group implements IGroup { if ($result) { $this->dispatcher->dispatch(IGroup::class . '::postDelete', new GenericEvent($this)); if ($this->emitter) { - $this->emitter->emit('\OC\Group', 'postDelete', array($this)); + $this->emitter->emit('\OC\Group', 'postDelete', [$this]); } } return $result; @@ -354,9 +355,9 @@ class Group implements IGroup { */ private function getVerifiedUsers($userIds) { if (!is_array($userIds)) { - return array(); + return []; } - $users = array(); + $users = []; foreach ($userIds as $userId) { $user = $this->userManager->get($userId); if (!is_null($user)) { diff --git a/lib/private/Group/Manager.php b/lib/private/Group/Manager.php index 0879138619c..f0acacdd0c5 100644 --- a/lib/private/Group/Manager.php +++ b/lib/private/Group/Manager.php @@ -5,6 +5,7 @@ * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> * @author Bernhard Posselt <dev@bernhard-posselt.com> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> @@ -342,7 +343,7 @@ class Manager extends PublicEmitter implements IGroupManager { */ public function getUserGroupNames(IUser $user) { return array_map(function ($group) { - return array('displayName' => $group->getDisplayName()); + return ['displayName' => $group->getDisplayName()]; }, $this->getUserGroups($user)); } diff --git a/lib/private/Group/MetaData.php b/lib/private/Group/MetaData.php index 2a0198bc451..97d71b51f98 100644 --- a/lib/private/Group/MetaData.php +++ b/lib/private/Group/MetaData.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> * @author Lukas Reschke <lukas@statuscode.ch> @@ -43,7 +44,7 @@ class MetaData { /** @var bool */ protected $isAdmin; /** @var array */ - protected $metaData = array(); + protected $metaData = []; /** @var IGroupManager */ protected $groupManager; /** @var bool */ @@ -86,12 +87,12 @@ class MetaData { return $this->metaData[$key]; } - $adminGroups = array(); - $groups = array(); + $adminGroups = []; + $groups = []; $sortGroupsIndex = 0; - $sortGroupsKeys = array(); + $sortGroupsKeys = []; $sortAdminGroupsIndex = 0; - $sortAdminGroupsKeys = array(); + $sortAdminGroupsKeys = []; foreach($this->getGroups($groupSearch) as $group) { $groupMetaData = $this->generateGroupMetaData($group, $userSearch); @@ -117,7 +118,7 @@ class MetaData { $this->sort($groups, $sortGroupsKeys); $this->sort($adminGroups, $sortAdminGroupsKeys); - $this->metaData[$key] = array($adminGroups, $groups); + $this->metaData[$key] = [$adminGroups, $groups]; return $this->metaData[$key]; } @@ -163,14 +164,14 @@ class MetaData { * @return array with the keys 'id', 'name', 'usercount' and 'disabled' */ private function generateGroupMetaData(\OCP\IGroup $group, $userSearch) { - return array( + return [ 'id' => $group->getGID(), 'name' => $group->getDisplayName(), 'usercount' => $this->sorting === self::SORT_USERCOUNT ? $group->count($userSearch) : 0, 'disabled' => $group->countDisabled(), 'canAdd' => $group->canAddUser(), 'canRemove' => $group->canRemoveUser(), - ); + ]; } /** diff --git a/lib/private/Hooks/EmitterTrait.php b/lib/private/Hooks/EmitterTrait.php index a3c7e2df5da..85efa218f64 100644 --- a/lib/private/Hooks/EmitterTrait.php +++ b/lib/private/Hooks/EmitterTrait.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @@ -28,7 +29,7 @@ trait EmitterTrait { /** * @var callable[][] $listeners */ - protected $listeners = array(); + protected $listeners = []; /** * @param string $scope @@ -38,7 +39,7 @@ trait EmitterTrait { public function listen($scope, $method, callable $callback) { $eventName = $scope . '::' . $method; if (!isset($this->listeners[$eventName])) { - $this->listeners[$eventName] = array(); + $this->listeners[$eventName] = []; } if (array_search($callback, $this->listeners[$eventName], true) === false) { $this->listeners[$eventName][] = $callback; @@ -51,7 +52,7 @@ trait EmitterTrait { * @param callable $callback optional */ public function removeListener($scope = null, $method = null, callable $callback = null) { - $names = array(); + $names = []; $allNames = array_keys($this->listeners); if ($scope and $method) { $name = $scope . '::' . $method; @@ -83,7 +84,7 @@ trait EmitterTrait { unset($this->listeners[$name][$index]); } } else { - $this->listeners[$name] = array(); + $this->listeners[$name] = []; } } } @@ -93,7 +94,7 @@ trait EmitterTrait { * @param string $method * @param array $arguments optional */ - protected function emit($scope, $method, array $arguments = array()) { + protected function emit($scope, $method, array $arguments = []) { $eventName = $scope . '::' . $method; if (isset($this->listeners[$eventName])) { foreach ($this->listeners[$eventName] as $callback) { diff --git a/lib/private/Hooks/ForwardingEmitter.php b/lib/private/Hooks/ForwardingEmitter.php index d7dc6bfe9b5..3ac6cca096a 100644 --- a/lib/private/Hooks/ForwardingEmitter.php +++ b/lib/private/Hooks/ForwardingEmitter.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @@ -34,7 +35,7 @@ abstract class ForwardingEmitter extends BasicEmitter { /** * @var \OC\Hooks\Emitter[] array */ - private $forwardEmitters = array(); + private $forwardEmitters = []; /** * @param string $scope diff --git a/lib/private/Hooks/LegacyEmitter.php b/lib/private/Hooks/LegacyEmitter.php index 9d4051e5899..470c5e0b11d 100644 --- a/lib/private/Hooks/LegacyEmitter.php +++ b/lib/private/Hooks/LegacyEmitter.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> @@ -32,7 +33,7 @@ abstract class LegacyEmitter extends BasicEmitter { * * @suppress PhanAccessMethodProtected */ - protected function emit($scope, $method, array $arguments = array()) { + protected function emit($scope, $method, array $arguments = []) { \OC_Hook::emit($scope, $method, $arguments); parent::emit($scope, $method, $arguments); } diff --git a/lib/private/Hooks/PublicEmitter.php b/lib/private/Hooks/PublicEmitter.php index 88c3d7ff327..dbccc34f2e9 100644 --- a/lib/private/Hooks/PublicEmitter.php +++ b/lib/private/Hooks/PublicEmitter.php @@ -36,7 +36,7 @@ class PublicEmitter extends BasicEmitter { * * @suppress PhanAccessMethodProtected */ - public function emit($scope, $method, array $arguments = array()) { + public function emit($scope, $method, array $arguments = []) { parent::emit($scope, $method, $arguments); } } diff --git a/lib/private/Http/Client/Client.php b/lib/private/Http/Client/Client.php index 657bfb8d536..a73ae2c2be5 100644 --- a/lib/private/Http/Client/Client.php +++ b/lib/private/Http/Client/Client.php @@ -7,6 +7,7 @@ declare(strict_types=1); * * @author Daniel Kesselberg <mail@danielkesselberg.de> * @author Lukas Reschke <lukas@statuscode.ch> + * @author Mohammed Abdellatif <m.latief@gmail.com> * @author Robin Appelman <robin@icewind.nl> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Scott Shambarger <devel@shambarger.net> diff --git a/lib/private/L10N/Factory.php b/lib/private/L10N/Factory.php index bba55385882..91420b8d766 100644 --- a/lib/private/L10N/Factory.php +++ b/lib/private/L10N/Factory.php @@ -16,7 +16,7 @@ * @author Robin Appelman <robin@icewind.nl> * @author Robin McCorkell <robin@mccorkell.me.uk> * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Thomas Citharel <tcit@tcit.fr> + * @author Thomas Citharel <nextcloud@tcit.fr> * * @license AGPL-3.0 * @@ -118,7 +118,7 @@ class Factory implements IFactory { $app = \OC_App::cleanAppId($app); if ($lang !== null) { - $lang = str_replace(array('\0', '/', '\\', '..'), '', (string)$lang); + $lang = str_replace(['\0', '/', '\\', '..'], '', (string)$lang); } $forceLang = $this->config->getSystemValue('force_language', false); @@ -532,8 +532,8 @@ class Factory implements IFactory { $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] ); $body = str_replace( - array( 'plural', 'n', '$n$plurals', ), - array( '$plural', '$n', '$nplurals', ), + [ 'plural', 'n', '$n$plurals', ], + [ '$plural', '$n', '$nplurals', ], 'nplurals='. $nplurals . '; plural=' . $plural ); @@ -599,20 +599,20 @@ class Factory implements IFactory { // 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__'); if ($l->getLanguageCode() === $lang && $potentialName[0] !== '_') {//first check if the language name is in the translation file - $ln = array( + $ln = [ 'code' => $lang, 'name' => $potentialName - ); + ]; } else if ($lang === 'en') { - $ln = array( + $ln = [ 'code' => $lang, 'name' => 'English (US)' - ); + ]; } else {//fallback to language code - $ln = array( + $ln = [ 'code' => $lang, 'name' => $lang - ); + ]; } // put appropriate languages into appropriate arrays, to print them sorted diff --git a/lib/private/L10N/L10N.php b/lib/private/L10N/L10N.php index bc05bd81849..519ff45292b 100644 --- a/lib/private/L10N/L10N.php +++ b/lib/private/L10N/L10N.php @@ -8,7 +8,7 @@ declare(strict_types=1); * @author Georg Ehrke <oc.list@georgehrke.com> * @author Joas Schilling <coding@schilljs.com> * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Thomas Citharel <tcit@tcit.fr> + * @author Thomas Citharel <nextcloud@tcit.fr> * * @license AGPL-3.0 * diff --git a/lib/private/LargeFileHelper.php b/lib/private/LargeFileHelper.php index dd75ec9820c..7f6a329c22d 100755 --- a/lib/private/LargeFileHelper.php +++ b/lib/private/LargeFileHelper.php @@ -4,6 +4,7 @@ * @copyright Copyright (c) 2016, Lukas Reschke <lukas@statuscode.ch> * * @author Andreas Fischer <bantu@owncloud.com> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Lukas Reschke <lukas@statuscode.ch> * @author marco44 <cousinmarc@gmail.com> * @author Michael Roitzsch <reactorcontrol@icloud.com> @@ -125,7 +126,7 @@ class LargeFileHelper { $data = curl_exec($ch); curl_close($ch); if ($data !== false) { - $matches = array(); + $matches = []; preg_match('/Content-Length: (\d+)/', $data, $matches); if (isset($matches[1])) { return 0 + $matches[1]; diff --git a/lib/private/Lock/DBLockingProvider.php b/lib/private/Lock/DBLockingProvider.php index 974b0b55c89..a8c22b59cb1 100644 --- a/lib/private/Lock/DBLockingProvider.php +++ b/lib/private/Lock/DBLockingProvider.php @@ -28,7 +28,6 @@ namespace OC\Lock; -use Doctrine\DBAL\Exception\UniqueConstraintViolationException; use OC\DB\QueryBuilder\Literal; use OCP\AppFramework\Utility\ITimeFactory; use OCP\DB\QueryBuilder\IQueryBuilder; diff --git a/lib/private/Log/ErrorHandler.php b/lib/private/Log/ErrorHandler.php index 7561486a4a9..2d2cf7abd67 100644 --- a/lib/private/Log/ErrorHandler.php +++ b/lib/private/Log/ErrorHandler.php @@ -4,6 +4,7 @@ * * @author Bart Visscher <bartv@thisnet.nl> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Thomas Müller <thomas.mueller@tmit.eu> * @@ -44,15 +45,15 @@ class ErrorHandler { $handler = new ErrorHandler(); if ($debug) { - set_error_handler(array($handler, 'onAll'), E_ALL); + set_error_handler([$handler, 'onAll'], E_ALL); if (\OC::$CLI) { - set_exception_handler(array('OC_Template', 'printExceptionErrorPage')); + set_exception_handler(['OC_Template', 'printExceptionErrorPage']); } } else { - set_error_handler(array($handler, 'onError')); + set_error_handler([$handler, 'onError']); } - register_shutdown_function(array($handler, 'onShutdown')); - set_exception_handler(array($handler, 'onException')); + register_shutdown_function([$handler, 'onShutdown']); + set_exception_handler([$handler, 'onException']); } public static function setLogger(ILogger $logger) { @@ -65,7 +66,7 @@ class ErrorHandler { if($error && self::$logger) { //ob_end_clean(); $msg = $error['message'] . ' at ' . $error['file'] . '#' . $error['line']; - self::$logger->critical(self::removePassword($msg), array('app' => 'PHP')); + self::$logger->critical(self::removePassword($msg), ['app' => 'PHP']); } } @@ -87,14 +88,14 @@ class ErrorHandler { return; } $msg = $message . ' at ' . $file . '#' . $line; - self::$logger->error(self::removePassword($msg), array('app' => 'PHP')); + 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), array('app' => 'PHP')); + self::$logger->debug(self::removePassword($msg), ['app' => 'PHP']); } diff --git a/lib/private/Log/File.php b/lib/private/Log/File.php index eb7eedac83e..5fccb36acb1 100644 --- a/lib/private/Log/File.php +++ b/lib/private/Log/File.php @@ -4,6 +4,7 @@ * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author duritong <peter.meier+github@immerda.ch> * @author Georg Ehrke <oc.list@georgehrke.com> * @author Joas Schilling <coding@schilljs.com> @@ -106,7 +107,7 @@ class File extends LogDetails implements IWriter, IFileBased { */ public function getEntries(int $limit=50, int $offset=0):array { $minLevel = $this->config->getValue("loglevel", ILogger::WARN); - $entries = array(); + $entries = []; $handle = @fopen($this->logFile, 'rb'); if ($handle) { fseek($handle, 0, SEEK_END); diff --git a/lib/private/Log/LogDetails.php b/lib/private/Log/LogDetails.php index b1dc6e4311b..5ed486195cf 100644 --- a/lib/private/Log/LogDetails.php +++ b/lib/private/Log/LogDetails.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2019 Julius Härtl <jus@bitgrid.net> * + * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Julius Härtl <jus@bitgrid.net> * * @license GNU AGPL version 3 or any later version diff --git a/lib/private/Log/Systemdlog.php b/lib/private/Log/Systemdlog.php index 5dc6ab875b8..e74cab40fd6 100644 --- a/lib/private/Log/Systemdlog.php +++ b/lib/private/Log/Systemdlog.php @@ -27,7 +27,6 @@ namespace OC\Log; use OC\HintException; use OC\SystemConfig; -use OCP\IConfig; use OCP\ILogger; use OCP\Log\IWriter; diff --git a/lib/private/Mail/Mailer.php b/lib/private/Mail/Mailer.php index df5f2687daa..f8af68faad3 100644 --- a/lib/private/Mail/Mailer.php +++ b/lib/private/Mail/Mailer.php @@ -5,10 +5,12 @@ declare(strict_types=1); /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Arne Hamann <kontakt+github@arne.email> * @author Branko Kokanovic <branko@kokanovic.org> * @author Carsten Wiedmann <carsten_sttgt@gmx.de> * @author Jared Boone <jared.boone@gmail.com> * @author Joas Schilling <coding@schilljs.com> + * @author Julius Härtl <jus@bitgrid.net> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Roeland Jago Douma <roeland@famdouma.nl> @@ -34,6 +36,7 @@ namespace OC\Mail; use Egulias\EmailValidator\EmailValidator; use Egulias\EmailValidator\Validation\RFCValidation; use OCP\Defaults; +use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; use OCP\IL10N; use OCP\ILogger; @@ -42,6 +45,8 @@ use OCP\Mail\IAttachment; use OCP\Mail\IEMailTemplate; use OCP\Mail\IMailer; use OCP\Mail\IMessage; +use OCP\Mail\Events\BeforeMessageSent; + /** * Class Mailer provides some basic functions to create a mail message that can be used in combination with @@ -74,6 +79,8 @@ class Mailer implements IMailer { private $urlGenerator; /** @var IL10N */ private $l10n; + /** @var IEventDispatcher */ + private $dispatcher; /** * @param IConfig $config @@ -81,17 +88,20 @@ class Mailer implements IMailer { * @param Defaults $defaults * @param IURLGenerator $urlGenerator * @param IL10N $l10n + * @param IEventDispatcher $dispatcher */ public function __construct(IConfig $config, ILogger $logger, Defaults $defaults, IURLGenerator $urlGenerator, - IL10N $l10n) { + IL10N $l10n, + IEventDispatcher $dispatcher) { $this->config = $config; $this->logger = $logger; $this->defaults = $defaults; $this->urlGenerator = $urlGenerator; $this->l10n = $l10n; + $this->dispatcher = $dispatcher; } /** @@ -182,6 +192,9 @@ class Mailer implements IMailer { $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($mailLogger)); } + + $this->dispatcher->dispatchTyped(new BeforeMessageSent($message)); + $mailer->send($message->getSwiftMessage(), $failedRecipients); // Debugging logging diff --git a/lib/private/Mail/Message.php b/lib/private/Mail/Message.php index 4ea9da532b6..e5a31b5cbe1 100644 --- a/lib/private/Mail/Message.php +++ b/lib/private/Mail/Message.php @@ -5,6 +5,7 @@ declare(strict_types=1); /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Arne Hamann <kontakt+github@arne.email> * @author Jared Boone <jared.boone@gmail.com> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> @@ -112,7 +113,7 @@ class Message implements IMessage { * @return array */ public function getFrom(): array { - return $this->swiftMessage->getFrom(); + return $this->swiftMessage->getFrom() ?? []; } /** @@ -156,7 +157,7 @@ class Message implements IMessage { * @return array */ public function getTo(): array { - return $this->swiftMessage->getTo(); + return $this->swiftMessage->getTo() ?? []; } /** @@ -178,7 +179,7 @@ class Message implements IMessage { * @return array */ public function getCc(): array { - return $this->swiftMessage->getCc(); + return $this->swiftMessage->getCc() ?? []; } /** @@ -200,7 +201,7 @@ class Message implements IMessage { * @return array */ public function getBcc(): array { - return $this->swiftMessage->getBcc(); + return $this->swiftMessage->getBcc() ?? []; } /** @@ -258,6 +259,14 @@ class Message implements IMessage { /** * Get's the underlying SwiftMessage + * @param Swift_Message $swiftMessage + */ + public function setSwiftMessage(Swift_Message $swiftMessage): void { + $this->swiftMessage = $swiftMessage; + } + + /** + * Get's the underlying SwiftMessage * @return Swift_Message */ public function getSwiftMessage(): Swift_Message { diff --git a/lib/private/Memcache/ArrayCache.php b/lib/private/Memcache/ArrayCache.php index bf1304063a4..407f4af06f4 100644 --- a/lib/private/Memcache/ArrayCache.php +++ b/lib/private/Memcache/ArrayCache.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> @@ -28,7 +29,7 @@ use OCP\IMemcache; class ArrayCache extends Cache implements IMemcache { /** @var array Array with the cached data */ - protected $cachedData = array(); + protected $cachedData = []; use CADTrait; diff --git a/lib/private/Memcache/Memcached.php b/lib/private/Memcache/Memcached.php index 700ed05380e..e3fc1b35f1a 100644 --- a/lib/private/Memcache/Memcached.php +++ b/lib/private/Memcache/Memcached.php @@ -4,6 +4,7 @@ * * @author Andreas Fischer <bantu@owncloud.com> * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Morris Jobke <hey@morrisjobke.de> @@ -140,7 +141,7 @@ class Memcached extends Cache implements IMemcache { self::$cache->flush(); return true; } - $keys = array(); + $keys = []; $prefixLength = strlen($prefix); foreach ($allKeys as $key) { if (substr($key, 0, $prefixLength) === $prefix) { diff --git a/lib/private/NaturalSort.php b/lib/private/NaturalSort.php index 3cc82222353..aefa5d5a92a 100644 --- a/lib/private/NaturalSort.php +++ b/lib/private/NaturalSort.php @@ -4,6 +4,7 @@ * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author AW-UC <git@a-wesemann.de> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin McCorkell <robin@mccorkell.me.uk> @@ -32,7 +33,7 @@ use OCP\ILogger; class NaturalSort { private static $instance; private $collator; - private $cache = array(); + private $cache = []; /** * Instantiate a new \OC\NaturalSort instance. @@ -58,7 +59,7 @@ class NaturalSort { if (isset($this->cache[$t])) { return $this->cache[$t]; } - $tz = array(); + $tz = []; $x = 0; $y = -1; $n = null; diff --git a/lib/private/NavigationManager.php b/lib/private/NavigationManager.php index 47d20073455..310201e812d 100644 --- a/lib/private/NavigationManager.php +++ b/lib/private/NavigationManager.php @@ -4,6 +4,7 @@ * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Kesselberg <mail@danielkesselberg.de> * @author Joas Schilling <coding@schilljs.com> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> @@ -115,7 +116,7 @@ class NavigationManager implements INavigationManager { foreach ($this->closureEntries as $c) { $this->add($c()); } - $this->closureEntries = array(); + $this->closureEntries = []; $result = $this->entries; if ($type !== 'all') { diff --git a/lib/private/OCS/Result.php b/lib/private/OCS/Result.php index 0be12f3a234..b16d83e0410 100644 --- a/lib/private/OCS/Result.php +++ b/lib/private/OCS/Result.php @@ -5,6 +5,7 @@ * @author Bart Visscher <bartv@thisnet.nl> * @author Björn Schießle <bjoern@schiessle.org> * @author Christopher Schäpers <kondou@ts.unde.re> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin McCorkell <robin@mccorkell.me.uk> @@ -59,9 +60,9 @@ class Result { */ public function __construct($data = null, $code = 100, $message = null, $headers = []) { if ($data === null) { - $this->data = array(); + $this->data = []; } elseif (!is_array($data)) { - $this->data = array($this->data); + $this->data = [$this->data]; } else { $this->data = $data; } @@ -99,7 +100,7 @@ class Result { * @return array */ public function getMeta() { - $meta = array(); + $meta = []; $meta['status'] = $this->succeeded() ? 'ok' : 'failure'; $meta['statuscode'] = $this->statusCode; $meta['message'] = $this->message; diff --git a/lib/private/Preview/Generator.php b/lib/private/Preview/Generator.php index dcd4ccd130c..bb597460f9d 100644 --- a/lib/private/Preview/Generator.php +++ b/lib/private/Preview/Generator.php @@ -26,7 +26,6 @@ namespace OC\Preview; -use OC\Preview\GeneratorHelper; use OCP\Files\File; use OCP\Files\IAppData; use OCP\Files\NotFoundException; @@ -36,7 +35,6 @@ use OCP\Files\SimpleFS\ISimpleFolder; use OCP\IConfig; use OCP\IImage; use OCP\IPreview; -use OCP\Preview\IProvider; use OCP\Preview\IProviderV2; use OCP\Preview\IVersionedPreviewFile; use Symfony\Component\EventDispatcher\EventDispatcherInterface; diff --git a/lib/private/Preview/GeneratorHelper.php b/lib/private/Preview/GeneratorHelper.php index 470cad2d0a6..843aa0ed420 100644 --- a/lib/private/Preview/GeneratorHelper.php +++ b/lib/private/Preview/GeneratorHelper.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, Roeland Jago Douma <roeland@famdouma.nl> * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @author Roeland Jago Douma <roeland@famdouma.nl> @@ -25,7 +26,6 @@ namespace OC\Preview; -use OC\Files\View; use OCP\Files\File; use OCP\Files\IRootFolder; use OCP\Files\SimpleFS\ISimpleFile; diff --git a/lib/private/Repair.php b/lib/private/Repair.php index e80d6ec7874..4084a9efb81 100644 --- a/lib/private/Repair.php +++ b/lib/private/Repair.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Kesselberg <mail@danielkesselberg.de> * @author Georg Ehrke <oc.list@georgehrke.com> * @author Joas Schilling <coding@schilljs.com> @@ -93,7 +94,7 @@ class Repair implements IOutput { */ public function run() { if (count($this->repairSteps) === 0) { - $this->emit('\OC\Repair', 'info', array('No repair steps available')); + $this->emit('\OC\Repair', 'info', ['No repair steps available']); return; } @@ -207,7 +208,7 @@ class Repair implements IOutput { public function info($string) { // for now just emit as we did in the past - $this->emit('\OC\Repair', 'info', array($string)); + $this->emit('\OC\Repair', 'info', [$string]); } /** diff --git a/lib/private/Repair/CleanTags.php b/lib/private/Repair/CleanTags.php index d579068e163..959eb50e5a7 100644 --- a/lib/private/Repair/CleanTags.php +++ b/lib/private/Repair/CleanTags.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> @@ -186,7 +187,7 @@ class CleanTags implements IRepairStep { ); $result = $qb->execute(); - $orphanItems = array(); + $orphanItems = []; while ($row = $result->fetch()) { $orphanItems[] = (int) $row[$deleteId]; } diff --git a/lib/private/Repair/Collation.php b/lib/private/Repair/Collation.php index 891fdd99433..fb0e0192693 100644 --- a/lib/private/Repair/Collation.php +++ b/lib/private/Repair/Collation.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> @@ -126,7 +127,7 @@ class Collation implements IRepairStep { " WHERE TABLE_SCHEMA = ?" . " AND (COLLATION_NAME <> '" . $characterSet . "_bin' OR CHARACTER_SET_NAME <> '" . $characterSet . "')" . " AND TABLE_NAME LIKE '*PREFIX*%'", - array($dbName) + [$dbName] ); $rows = $statement->fetchAll(); $result = []; diff --git a/lib/private/Repair/RepairMimeTypes.php b/lib/private/Repair/RepairMimeTypes.php index c3ad7be72da..67dd1ca971d 100644 --- a/lib/private/Repair/RepairMimeTypes.php +++ b/lib/private/Repair/RepairMimeTypes.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Morris Jobke <hey@morrisjobke.de> * @author Olivier Paroz <github@oparoz.com> @@ -90,46 +91,46 @@ class RepairMimeTypes implements IRepairStep { private function updateMimetypes($updatedMimetypes) { if (empty($this->folderMimeTypeId)) { - $result = \OC_DB::executeAudited(self::getIdStmt(), array('httpd/unix-directory')); + $result = \OC_DB::executeAudited(self::getIdStmt(), ['httpd/unix-directory']); $this->folderMimeTypeId = (int)$result->fetchOne(); } $count = 0; foreach ($updatedMimetypes as $extension => $mimetype) { - $result = \OC_DB::executeAudited(self::existsStmt(), array($mimetype)); + $result = \OC_DB::executeAudited(self::existsStmt(), [$mimetype]); $exists = $result->fetchOne(); if (!$exists) { // insert mimetype - \OC_DB::executeAudited(self::insertStmt(), array($mimetype)); + \OC_DB::executeAudited(self::insertStmt(), [$mimetype]); } // get target mimetype id - $result = \OC_DB::executeAudited(self::getIdStmt(), array($mimetype)); + $result = \OC_DB::executeAudited(self::getIdStmt(), [$mimetype]); $mimetypeId = $result->fetchOne(); // change mimetype for files with x extension - $count += \OC_DB::executeAudited(self::updateByNameStmt(), array($mimetypeId, $this->folderMimeTypeId, $mimetypeId, '%.' . $extension)); + $count += \OC_DB::executeAudited(self::updateByNameStmt(), [$mimetypeId, $this->folderMimeTypeId, $mimetypeId, '%.' . $extension]); } return $count; } private function introduceImageTypes() { - $updatedMimetypes = array( + $updatedMimetypes = [ 'jp2' => 'image/jp2', 'webp' => 'image/webp', - ); + ]; return $this->updateMimetypes($updatedMimetypes); } private function introduceWindowsProgramTypes() { - $updatedMimetypes = array( + $updatedMimetypes = [ 'htaccess' => 'text/plain', 'bat' => 'application/x-msdos-program', 'cmd' => 'application/cmd', - ); + ]; return $this->updateMimetypes($updatedMimetypes); } diff --git a/lib/private/Route/CachingRouter.php b/lib/private/Route/CachingRouter.php index af68129e57d..e94039cce1a 100644 --- a/lib/private/Route/CachingRouter.php +++ b/lib/private/Route/CachingRouter.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> @@ -49,7 +50,7 @@ class CachingRouter extends Router { * @param bool $absolute * @return string */ - public function generate($name, $parameters = array(), $absolute = false) { + public function generate($name, $parameters = [], $absolute = false) { asort($parameters); $key = $this->context->getHost() . '#' . $this->context->getBaseUrl() . $name . sha1(json_encode($parameters)) . (int)$absolute; $cachedKey = $this->cache->get($key); diff --git a/lib/private/Route/Route.php b/lib/private/Route/Route.php index 645c2449908..60b14efc7d6 100644 --- a/lib/private/Route/Route.php +++ b/lib/private/Route/Route.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author David Prévot <taffit@debian.org> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> @@ -133,7 +134,7 @@ class Route extends SymfonyRoute implements IRoute { * to the class with $function */ public function action($class, $function = null) { - $action = array($class, $function); + $action = [$class, $function]; if (is_null($function)) { $action = $class; } diff --git a/lib/private/Search.php b/lib/private/Search.php index db533ff182a..ca9024bdd78 100644 --- a/lib/private/Search.php +++ b/lib/private/Search.php @@ -4,6 +4,7 @@ * * @author Andrew Brown <andrew@casabrown.com> * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> @@ -35,8 +36,8 @@ use OCP\Search\Provider; */ class Search implements ISearch { - private $providers = array(); - private $registeredProviders = array(); + private $providers = []; + private $registeredProviders = []; /** * Search all providers for $query @@ -46,9 +47,9 @@ class Search implements ISearch { * @param int $size, 0 = all * @return array An array of OC\Search\Result's */ - public function searchPaged($query, array $inApps = array(), $page = 1, $size = 30) { + public function searchPaged($query, array $inApps = [], $page = 1, $size = 30) { $this->initProviders(); - $results = array(); + $results = []; foreach($this->providers as $provider) { /** @var $provider Provider */ if ( ! $provider->providesResultsFor($inApps) ) { @@ -65,7 +66,7 @@ class Search implements ISearch { $results = array_merge($results, $providerResults); } } else { - \OC::$server->getLogger()->warning('Ignoring Unknown search provider', array('provider' => $provider)); + \OC::$server->getLogger()->warning('Ignoring Unknown search provider', ['provider' => $provider]); } } return $results; @@ -75,8 +76,8 @@ class Search implements ISearch { * Remove all registered search providers */ public function clearProviders() { - $this->providers = array(); - $this->registeredProviders = array(); + $this->providers = []; + $this->registeredProviders = []; } /** @@ -91,7 +92,7 @@ class Search implements ISearch { } ); // force regeneration of providers on next search - $this->providers = array(); + $this->providers = []; } /** @@ -99,8 +100,8 @@ class Search implements ISearch { * @param string $class class name of a OC\Search\Provider * @param array $options optional */ - public function registerProvider($class, array $options = array()) { - $this->registeredProviders[] = array('class' => $class, 'options' => $options); + public function registerProvider($class, array $options = []) { + $this->registeredProviders[] = ['class' => $class, 'options' => $options]; } /** diff --git a/lib/private/Search/Provider/File.php b/lib/private/Search/Provider/File.php index 87927b90768..afd37cfe703 100644 --- a/lib/private/Search/Provider/File.php +++ b/lib/private/Search/Provider/File.php @@ -4,6 +4,7 @@ * * @author Andrew Brown <andrew@casabrown.com> * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Jakob Sack <mail@jakobsack.de> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Morris Jobke <hey@morrisjobke.de> @@ -40,7 +41,7 @@ class File extends \OCP\Search\Provider { */ public function search($query) { $files = Filesystem::search($query); - $results = array(); + $results = []; // edit results foreach ($files as $fileData) { // skip versions diff --git a/lib/private/Security/CSP/ContentSecurityPolicy.php b/lib/private/Security/CSP/ContentSecurityPolicy.php index e2660dbb41c..4db1314e782 100644 --- a/lib/private/Security/CSP/ContentSecurityPolicy.php +++ b/lib/private/Security/CSP/ContentSecurityPolicy.php @@ -7,7 +7,7 @@ declare(strict_types=1); * * @author Lukas Reschke <lukas@statuscode.ch> * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Thomas Citharel <tcit@tcit.fr> + * @author Thomas Citharel <nextcloud@tcit.fr> * * @license AGPL-3.0 * diff --git a/lib/private/Security/CSP/ContentSecurityPolicyNonceManager.php b/lib/private/Security/CSP/ContentSecurityPolicyNonceManager.php index 7298fbe2eda..9dec2907b2f 100644 --- a/lib/private/Security/CSP/ContentSecurityPolicyNonceManager.php +++ b/lib/private/Security/CSP/ContentSecurityPolicyNonceManager.php @@ -7,6 +7,7 @@ declare(strict_types=1); * * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> + * @author Pavel Krasikov <klonishe@gmail.com> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Sam Bull <aa6bs0@sambull.org> * diff --git a/lib/private/Security/CertificateManager.php b/lib/private/Security/CertificateManager.php index 48ff28a3fb4..86df38625e0 100644 --- a/lib/private/Security/CertificateManager.php +++ b/lib/private/Security/CertificateManager.php @@ -4,6 +4,7 @@ * * @author Bjoern Schiessle <bjoern@schiessle.org> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> @@ -88,17 +89,17 @@ class CertificateManager implements ICertificateManager { public function listCertificates() { if (!$this->config->getSystemValue('installed', false)) { - return array(); + return []; } $path = $this->getPathToCertificates() . 'uploads/'; if (!$this->view->is_dir($path)) { - return array(); + return []; } - $result = array(); + $result = []; $handle = $this->view->opendir($path); if (!is_resource($handle)) { - return array(); + return []; } while (false !== ($file = readdir($handle))) { if ($file != '.' && $file != '..') { diff --git a/lib/private/Security/Hasher.php b/lib/private/Security/Hasher.php index 21271fffbd7..9850dbe1467 100644 --- a/lib/private/Security/Hasher.php +++ b/lib/private/Security/Hasher.php @@ -5,6 +5,7 @@ declare(strict_types=1); /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Roeland Jago Douma <roeland@famdouma.nl> diff --git a/lib/private/Security/Normalizer/IpAddress.php b/lib/private/Security/Normalizer/IpAddress.php index ef9dba6503a..b471c499440 100644 --- a/lib/private/Security/Normalizer/IpAddress.php +++ b/lib/private/Security/Normalizer/IpAddress.php @@ -8,7 +8,7 @@ declare(strict_types=1); * @author Konrad Bucheli <kb@open.ch> * @author Lukas Reschke <lukas@statuscode.ch> * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Thomas Citharel <tcit@tcit.fr> + * @author Thomas Citharel <nextcloud@tcit.fr> * * @license GNU AGPL version 3 or any later version * diff --git a/lib/private/Server.php b/lib/private/Server.php index 3300920edb7..c7a30e3c9f8 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * @copyright Copyright (c) 2016, Lukas Reschke <lukas@statuscode.ch> * + * @author Arne Hamann <kontakt+github@arne.email> * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> * @author Bernhard Posselt <dev@bernhard-posselt.com> @@ -62,6 +63,8 @@ use OC\App\AppStore\Fetcher\CategoryFetcher; use OC\AppFramework\Http\Request; use OC\AppFramework\Utility\SimpleContainer; use OC\AppFramework\Utility\TimeFactory; +use OC\Authentication\Events\LoginFailed; +use OC\Authentication\Listeners\LoginFailedListener; use OC\Authentication\LoginCredentials\Store; use OC\Authentication\Token\IProvider; use OC\Avatar\AvatarManager; @@ -391,44 +394,44 @@ class Server extends ServerContainer implements IServerContainer { $this->registerService(\OCP\IGroupManager::class, function (Server $c) { $groupManager = new \OC\Group\Manager($this->getUserManager(), $c->getEventDispatcher(), $this->getLogger()); $groupManager->listen('\OC\Group', 'preCreate', function ($gid) { - \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid)); + \OC_Hook::emit('OC_Group', 'pre_createGroup', ['run' => true, 'gid' => $gid]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); $dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid)); }); $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) { - \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $group->getGID())); + \OC_Hook::emit('OC_User', 'post_createGroup', ['gid' => $group->getGID()]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); $dispatcher->dispatchTyped(new GroupCreatedEvent($group)); }); $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) { - \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID())); + \OC_Hook::emit('OC_Group', 'pre_deleteGroup', ['run' => true, 'gid' => $group->getGID()]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); $dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group)); }); $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) { - \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID())); + \OC_Hook::emit('OC_User', 'post_deleteGroup', ['gid' => $group->getGID()]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); $dispatcher->dispatchTyped(new GroupDeletedEvent($group)); }); $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) { - \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID())); + \OC_Hook::emit('OC_Group', 'pre_addToGroup', ['run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); $dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user)); }); $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) { - \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID())); + \OC_Hook::emit('OC_Group', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]); //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks - \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID())); + \OC_Hook::emit('OC_User', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); @@ -491,7 +494,7 @@ class Server extends ServerContainer implements IServerContainer { $c->query(IEventDispatcher::class) ); $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) { - \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password)); + \OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); @@ -499,7 +502,7 @@ class Server extends ServerContainer implements IServerContainer { }); $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) { /** @var $user \OC\User\User */ - \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password)); + \OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); @@ -507,7 +510,7 @@ class Server extends ServerContainer implements IServerContainer { }); $userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) { /** @var $user \OC\User\User */ - \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID())); + \OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]); $legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user)); /** @var IEventDispatcher $dispatcher */ @@ -516,7 +519,7 @@ class Server extends ServerContainer implements IServerContainer { }); $userSession->listen('\OC\User', 'postDelete', function ($user) { /** @var $user \OC\User\User */ - \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID())); + \OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); @@ -524,7 +527,7 @@ class Server extends ServerContainer implements IServerContainer { }); $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) { /** @var $user \OC\User\User */ - \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword)); + \OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); @@ -532,14 +535,14 @@ class Server extends ServerContainer implements IServerContainer { }); $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) { /** @var $user \OC\User\User */ - \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword)); + \OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); $dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword)); }); $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) { - \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password)); + \OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); @@ -547,7 +550,7 @@ class Server extends ServerContainer implements IServerContainer { }); $userSession->listen('\OC\User', 'postLogin', function ($user, $password, $isTokenLogin) { /** @var $user \OC\User\User */ - \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'isTokenLogin' => $isTokenLogin)); + \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'isTokenLogin' => $isTokenLogin]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); @@ -560,14 +563,14 @@ class Server extends ServerContainer implements IServerContainer { }); $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) { /** @var $user \OC\User\User */ - \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password)); + \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); $dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password)); }); $userSession->listen('\OC\User', 'logout', function ($user) { - \OC_Hook::emit('OC_User', 'logout', array()); + \OC_Hook::emit('OC_User', 'logout', []); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); @@ -580,7 +583,7 @@ class Server extends ServerContainer implements IServerContainer { }); $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) { /** @var $user \OC\User\User */ - \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue)); + \OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]); /** @var IEventDispatcher $dispatcher */ $dispatcher = $this->query(IEventDispatcher::class); @@ -988,7 +991,8 @@ class Server extends ServerContainer implements IServerContainer { $c->getLogger(), $c->query(Defaults::class), $c->getURLGenerator(), - $c->getL10N('lib') + $c->getL10N('lib'), + $c->query(IEventDispatcher::class) ); }); $this->registerDeprecatedAlias('Mailer', IMailer::class); @@ -1415,6 +1419,10 @@ class Server extends ServerContainer implements IServerContainer { // no avatar to remove } }); + + /** @var IEventDispatcher $eventDispatched */ + $eventDispatched = $this->query(IEventDispatcher::class); + $eventDispatched->addServiceListener(LoginFailed::class, LoginFailedListener::class); } /** diff --git a/lib/private/Session/Internal.php b/lib/private/Session/Internal.php index b9aae76c3b0..7990c4a7dae 100644 --- a/lib/private/Session/Internal.php +++ b/lib/private/Session/Internal.php @@ -36,8 +36,6 @@ namespace OC\Session; use OC\Authentication\Exceptions\InvalidTokenException; use OC\Authentication\Token\IProvider; -use OC\SystemConfig; -use OCP\IConfig; use OCP\Session\Exceptions\SessionNotAvailableException; /** diff --git a/lib/private/Settings/Manager.php b/lib/private/Settings/Manager.php index ed1d2f45cd7..81b29020287 100644 --- a/lib/private/Settings/Manager.php +++ b/lib/private/Settings/Manager.php @@ -5,7 +5,6 @@ * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> - * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> * @author Julius Härtl <jus@bitgrid.net> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> @@ -33,7 +32,6 @@ namespace OC\Settings; use Closure; -use OC\Settings\Personal\PersonalInfo; use OCP\AppFramework\QueryException; use OCP\IL10N; use OCP\ILogger; diff --git a/lib/private/Setup.php b/lib/private/Setup.php index 26299aaa039..afdc881b482 100644 --- a/lib/private/Setup.php +++ b/lib/private/Setup.php @@ -25,6 +25,7 @@ * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Sean Comeau <sean@ftlnetworks.ca> * @author Serge Martin <edb@sigluy.net> + * @author Simounet <contact@simounet.net> * @author Thomas Müller <thomas.mueller@tmit.eu> * @author Vincent Petry <pvince81@owncloud.com> * @@ -59,7 +60,6 @@ use OCP\Defaults; use OCP\IGroup; use OCP\IL10N; use OCP\ILogger; -use OCP\IUser; use OCP\Security\ISecureRandom; class Setup { @@ -182,7 +182,7 @@ class Setup { throw new Exception('Supported databases are not properly configured.'); } - $supportedDatabases = array(); + $supportedDatabases = []; foreach ($configuredDatabases as $database) { if (array_key_exists($database, $availableDatabases)) { @@ -263,7 +263,7 @@ class Setup { ]; } - return array( + return [ 'hasSQLite' => isset($databases['sqlite']), 'hasMySQL' => isset($databases['mysql']), 'hasPostgreSQL' => isset($databases['pgsql']), @@ -272,7 +272,7 @@ class Setup { 'directory' => $dataDir, 'htaccessWorking' => $htAccessWorking, 'errors' => $errors, - ); + ]; } /** @@ -282,7 +282,7 @@ class Setup { public function install($options) { $l = $this->l10n; - $error = array(); + $error = []; $dbType = $options['dbtype']; if (empty($options['adminlogin'])) { @@ -310,7 +310,7 @@ class Setup { // validate the data directory if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) { - $error[] = $l->t("Can't create or write into the data directory %s", array($dataDir)); + $error[] = $l->t("Can't create or write into the data directory %s", [$dataDir]); } if (!empty($error)) { diff --git a/lib/private/Setup/AbstractDatabase.php b/lib/private/Setup/AbstractDatabase.php index d52aaa8882d..db6b182be63 100644 --- a/lib/private/Setup/AbstractDatabase.php +++ b/lib/private/Setup/AbstractDatabase.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Manish Bisht <manish.bisht490@gmail.com> * @author Morris Jobke <hey@morrisjobke.de> @@ -67,16 +68,16 @@ abstract class AbstractDatabase { } public function validate($config) { - $errors = array(); + $errors = []; if(empty($config['dbuser']) && empty($config['dbname'])) { - $errors[] = $this->trans->t("%s enter the database username and name.", array($this->dbprettyname)); + $errors[] = $this->trans->t("%s enter the database username and name.", [$this->dbprettyname]); } else if(empty($config['dbuser'])) { - $errors[] = $this->trans->t("%s enter the database username.", array($this->dbprettyname)); + $errors[] = $this->trans->t("%s enter the database username.", [$this->dbprettyname]); } else if(empty($config['dbname'])) { - $errors[] = $this->trans->t("%s enter the database name.", array($this->dbprettyname)); + $errors[] = $this->trans->t("%s enter the database name.", [$this->dbprettyname]); } if(substr_count($config['dbname'], '.') >= 1) { - $errors[] = $this->trans->t("%s you may not use dots in the database name", array($this->dbprettyname)); + $errors[] = $this->trans->t("%s you may not use dots in the database name", [$this->dbprettyname]); } return $errors; } @@ -109,13 +110,13 @@ abstract class AbstractDatabase { * @return \OC\DB\Connection */ protected function connect(array $configOverwrite = []) { - $connectionParams = array( + $connectionParams = [ 'host' => $this->dbHost, 'user' => $this->dbUser, 'password' => $this->dbPassword, 'tablePrefix' => $this->tablePrefix, 'dbname' => $this->dbName - ); + ]; // adding port support through installer if (!empty($this->dbPort)) { diff --git a/lib/private/Setup/OCI.php b/lib/private/Setup/OCI.php index 75d75254a00..ab00c8a47b2 100644 --- a/lib/private/Setup/OCI.php +++ b/lib/private/Setup/OCI.php @@ -4,9 +4,9 @@ * * @author Andreas Fischer <bantu@owncloud.com> * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> - * @author Manish Bisht <manish.bisht490@gmail.com> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> @@ -52,13 +52,13 @@ class OCI extends AbstractDatabase { } public function validate($config) { - $errors = array(); + $errors = []; if (empty($config['dbuser']) && empty($config['dbname'])) { - $errors[] = $this->trans->t("%s enter the database username and name.", array($this->dbprettyname)); + $errors[] = $this->trans->t("%s enter the database username and name.", [$this->dbprettyname]); } else if (empty($config['dbuser'])) { - $errors[] = $this->trans->t("%s enter the database username.", array($this->dbprettyname)); + $errors[] = $this->trans->t("%s enter the database username.", [$this->dbprettyname]); } else if (empty($config['dbname'])) { - $errors[] = $this->trans->t("%s enter the database name.", array($this->dbprettyname)); + $errors[] = $this->trans->t("%s enter the database name.", [$this->dbprettyname]); } return $errors; } @@ -101,7 +101,7 @@ class OCI extends AbstractDatabase { } else { $error = oci_error(); } - foreach (array('message', 'code') as $key) { + foreach (['message', 'code'] as $key) { if (isset($error[$key])) { return $error[$key]; } diff --git a/lib/private/Setup/Sqlite.php b/lib/private/Setup/Sqlite.php index 0b97b4c0451..b7d985786a3 100644 --- a/lib/private/Setup/Sqlite.php +++ b/lib/private/Setup/Sqlite.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Kesselberg <mail@danielkesselberg.de> * * @license AGPL-3.0 @@ -29,7 +30,7 @@ class Sqlite extends AbstractDatabase { public $dbprettyname = 'Sqlite'; public function validate($config) { - return array(); + return []; } public function initialize($config) { diff --git a/lib/private/Share/Constants.php b/lib/private/Share/Constants.php index 4ad9c71b511..d1b47f1dd47 100644 --- a/lib/private/Share/Constants.php +++ b/lib/private/Share/Constants.php @@ -5,6 +5,7 @@ * @author Bjoern Schiessle <bjoern@schiessle.org> * @author Björn Schießle <bjoern@schiessle.org> * @author Christopher Schäpers <kondou@ts.unde.re> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Calviño Sánchez <danxuliu@gmail.com> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> @@ -83,7 +84,7 @@ class Constants { protected static $shareTypeUserAndGroups = -1; protected static $shareTypeGroupUserUnique = 2; - protected static $backends = array(); - protected static $backendTypes = array(); + protected static $backends = []; + protected static $backendTypes = []; protected static $isResharingAllowed; } diff --git a/lib/private/Share/Helper.php b/lib/private/Share/Helper.php index 2dd91613cbd..1574bd726cf 100644 --- a/lib/private/Share/Helper.php +++ b/lib/private/Share/Helper.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Miguel Prokop <miguel.prokop@vtu.com> * @author Morris Jobke <hey@morrisjobke.de> @@ -82,15 +83,15 @@ class Helper extends \OC\Share\Constants { * @param bool $excludeGroupChildren exclude group children elements */ public static function delete($parent, $excludeParent = false, $uidOwner = null, $newParent = null, $excludeGroupChildren = false) { - $ids = array($parent); - $deletedItems = array(); - $changeParent = array(); - $parents = array($parent); + $ids = [$parent]; + $deletedItems = []; + $changeParent = []; + $parents = [$parent]; while (!empty($parents)) { $parents = "'".implode("','", $parents)."'"; // Check the owner on the first search of reshares, useful for // finding and deleting the reshares by a single user of a group share - $params = array(); + $params = []; if (count($ids) == 1 && isset($uidOwner)) { // FIXME: don't concat $parents, use Docrine's PARAM_INT_ARRAY approach $queryString = 'SELECT `id`, `share_with`, `item_type`, `share_type`, ' . @@ -110,15 +111,15 @@ class Helper extends \OC\Share\Constants { $query = \OC_DB::prepare($queryString); $result = $query->execute($params); // Reset parents array, only go through loop again if items are found - $parents = array(); + $parents = []; while ($item = $result->fetchRow()) { - $tmpItem = array( + $tmpItem = [ 'id' => $item['id'], 'shareWith' => $item['share_with'], 'itemTarget' => $item['item_target'], 'itemType' => $item['item_type'], 'shareType' => (int)$item['share_type'], - ); + ]; if (isset($item['file_target'])) { $tmpItem['fileTarget'] = $item['file_target']; } @@ -141,7 +142,7 @@ class Helper extends \OC\Share\Constants { if (!empty($changeParent)) { $idList = "'".implode("','", $changeParent)."'"; $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `parent` = ? WHERE `id` IN ('.$idList.')'); - $query->execute(array($newParent)); + $query->execute([$newParent]); } if (!empty($ids)) { @@ -161,7 +162,7 @@ class Helper extends \OC\Share\Constants { $config = \OC::$server->getConfig(); - $defaultExpireSettings = array('defaultExpireDateSet' => false); + $defaultExpireSettings = ['defaultExpireDateSet' => false]; // get default expire settings $defaultExpireDate = $config->getAppValue('core', 'shareapi_default_expire_date', 'no'); @@ -277,12 +278,12 @@ class Helper extends \OC\Share\Constants { \OCP\Util::emitHook( '\OCA\Files_Sharing\API\Server2Server', 'preLoginNameUsedAsUserName', - array('uid' => &$user1) + ['uid' => &$user1] ); \OCP\Util::emitHook( '\OCA\Files_Sharing\API\Server2Server', 'preLoginNameUsedAsUserName', - array('uid' => &$user2) + ['uid' => &$user2] ); if ($user1 === $user2) { diff --git a/lib/private/Share/SearchResultSorter.php b/lib/private/Share/SearchResultSorter.php index 452b7a4849c..54232b828ca 100644 --- a/lib/private/Share/SearchResultSorter.php +++ b/lib/private/Share/SearchResultSorter.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin McCorkell <robin@mccorkell.me.uk> * @author Roeland Jago Douma <roeland@famdouma.nl> @@ -56,7 +57,7 @@ class SearchResultSorter { 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', array('app' => 'core')); + 'missing array key', ['app' => 'core']); } return 0; } diff --git a/lib/private/Share/Share.php b/lib/private/Share/Share.php index ed876022bdd..2bc2afbea2e 100644 --- a/lib/private/Share/Share.php +++ b/lib/private/Share/Share.php @@ -7,6 +7,7 @@ * @author Bernhard Reiter <ockham@raz.or.at> * @author Bjoern Schiessle <bjoern@schiessle.org> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> @@ -37,9 +38,7 @@ namespace OC\Share; use OCP\DB\QueryBuilder\IQueryBuilder; -use OCP\IConfig; use OCP\ILogger; -use OCP\Util; /** * This class provides the ability for apps to share their content between users. @@ -76,11 +75,11 @@ class Share extends Constants { public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) { if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') { if (!isset(self::$backendTypes[$itemType])) { - self::$backendTypes[$itemType] = array( + self::$backendTypes[$itemType] = [ 'class' => $class, 'collectionOf' => $collectionOf, 'supportedFileExtensions' => $supportedFileExtensions - ); + ]; return true; } \OCP\Util::writeLog('OCP\Share', @@ -134,7 +133,7 @@ class Share extends Constants { * @return array Return list of items with file_target, permissions and expiration */ public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) { - $shares = array(); + $shares = []; $fileDependent = false; $where = 'WHERE'; @@ -151,7 +150,7 @@ class Share extends Constants { $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent); $where .= ' `' . $column . '` = ? AND `item_type` = ? '; - $arguments = array($itemSource, $itemType); + $arguments = [$itemSource, $itemType]; // for link shares $user === null if ($user !== null) { $where .= ' AND `share_with` = ? '; @@ -205,8 +204,8 @@ class Share extends Constants { if (!empty($groups)) { $where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)'; - $arguments = array($itemSource, $itemType, $groups); - $types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY); + $arguments = [$itemSource, $itemType, $groups]; + $types = [null, null, IQueryBuilder::PARAM_STR_ARRAY]; if ($owner !== null) { $where .= ' AND `uid_owner` = ?'; @@ -347,7 +346,7 @@ class Share extends Constants { $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType); - $toDelete = array(); + $toDelete = []; $newParent = null; $currentUser = $owner ? $owner : \OC_User::getUser(); foreach ($items as $item) { @@ -423,7 +422,7 @@ class Share extends Constants { } // Pass all the vars we have for now, they may be useful - $hookParams = array( + $hookParams = [ 'id' => $item['id'], 'itemType' => $item['item_type'], 'itemSource' => $item['item_source'], @@ -431,7 +430,7 @@ class Share extends Constants { 'shareWith' => $shareWith, 'itemParent' => $item['parent'], 'uidOwner' => $item['uid_owner'], - ); + ]; if($item['item_type'] === 'file' || $item['item_type'] === 'folder') { $hookParams['fileSource'] = $item['file_source']; $hookParams['fileTarget'] = $item['file_target']; @@ -464,20 +463,20 @@ class Share extends Constants { self::$backends[$itemType] = new $class; if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) { $message = 'Sharing backend %s must implement the interface OCP\Share_Backend'; - $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class)); + $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', [$class]); \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR); throw new \Exception($message_t); } return self::$backends[$itemType]; } else { $message = 'Sharing backend %s not found'; - $message_t = $l->t('Sharing backend %s not found', array($class)); + $message_t = $l->t('Sharing backend %s not found', [$class]); \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR); throw new \Exception($message_t); } } $message = 'Sharing backend for %s not found'; - $message_t = $l->t('Sharing backend for %s not found', array($itemType)); + $message_t = $l->t('Sharing backend for %s not found', [$itemType]); \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), ILogger::ERROR); throw new \Exception($message_t); } @@ -505,7 +504,7 @@ class Share extends Constants { * @return array */ private static function getCollectionItemTypes($itemType) { - $collectionTypes = array($itemType); + $collectionTypes = [$itemType]; foreach (self::$backendTypes as $type => $backend) { if (in_array($backend['collectionOf'], $collectionTypes)) { $collectionTypes[] = $type; @@ -538,7 +537,7 @@ class Share extends Constants { public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) { // First, we find out if $type is part of a collection (and if that collection is part of // another one and so on). - $collectionTypes = array(); + $collectionTypes = []; if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) { $collectionTypes[] = $type; } @@ -547,7 +546,7 @@ class Share extends Constants { // list of the ones for which a sharing backend has been registered. // FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it // with its $includeCollections parameter set to true. Unfortunately, this fails currently. - $allMaybeSharedItems = array(); + $allMaybeSharedItems = []; foreach ($collectionTypes as $collectionType) { if (isset(self::$backends[$collectionType])) { $allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser( @@ -558,7 +557,7 @@ class Share extends Constants { } } - $owners = array(); + $owners = []; if ($includeOwner) { $owners[] = $user; } @@ -599,7 +598,7 @@ class Share extends Constants { $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate = true) { if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') { - return array(); + return []; } $backend = self::getBackend($itemType); $collectionTypes = false; @@ -617,7 +616,7 @@ class Share extends Constants { } $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` '; $fileDependent = true; - $queryArgs = array(); + $queryArgs = []; } else { $fileDependent = false; $root = ''; @@ -625,7 +624,7 @@ class Share extends Constants { if ($includeCollections && !isset($item) && $collectionTypes) { // If includeCollections is true, find collections of this item type, e.g. a music album contains songs if (!in_array($itemType, $collectionTypes)) { - $itemTypes = array_merge(array($itemType), $collectionTypes); + $itemTypes = array_merge([$itemType], $collectionTypes); } else { $itemTypes = $collectionTypes; } @@ -634,7 +633,7 @@ class Share extends Constants { $queryArgs = $itemTypes; } else { $where = ' WHERE `item_type` = ?'; - $queryArgs = array($itemType); + $queryArgs = [$itemType]; } } if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') { @@ -754,10 +753,10 @@ class Share extends Constants { \OC_DB::getErrorMessage() . ', select=' . $select . ' where=', ILogger::ERROR); } - $items = array(); - $targets = array(); - $switchedItems = array(); - $mounts = array(); + $items = []; + $targets = []; + $switchedItems = []; + $mounts = []; while ($row = $result->fetchRow()) { self::transformDBResults($row); // Filter out duplicate group shares for users with unique targets @@ -812,7 +811,7 @@ class Share extends Constants { if (isset($uidOwner) && isset($row['path'])) { if (isset($row['parent'])) { $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?'); - $parentResult = $query->execute(array($row['parent'])); + $parentResult = $query->execute([$row['parent']]); if ($result === false) { \OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' . \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where, @@ -887,7 +886,7 @@ class Share extends Constants { } if (!empty($items)) { - $collectionItems = array(); + $collectionItems = []; foreach ($items as &$row) { // Return only the item instead of a 2-dimensional array if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) { @@ -905,7 +904,7 @@ class Share extends Constants { if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) { $collectionItems[] = $row; } else { - $collection = array(); + $collection = []; $collection['item_type'] = $row['item_type']; if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') { $collection['path'] = basename($row['path']); @@ -938,7 +937,7 @@ class Share extends Constants { return $childItem; } else { // Unset the items array and break out of both loops - $items = array(); + $items = []; $items[] = $childItem; break 2; } @@ -985,7 +984,7 @@ class Share extends Constants { // FIXME: Thats a dirty hack to improve file sharing performance, // see github issue #10588 for more details // Need to find a solution which works for all back-ends - $collectionItems = array(); + $collectionItems = []; $collectionBackend = self::getBackend('folder'); $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner); foreach ($sharedParents as $parent) { @@ -997,7 +996,7 @@ class Share extends Constants { return self::formatResult($collectionItems, $column, $backend, $format, $parameters); } - return array(); + return []; } /** @@ -1011,7 +1010,7 @@ class Share extends Constants { $fileSharing = $itemType === 'file' || $itemType === 'folder'; - $result = array(); + $result = []; foreach ($items as $item) { $grouped = false; @@ -1058,7 +1057,7 @@ class Share extends Constants { private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions) { - $queriesToExecute = array(); + $queriesToExecute = []; $suggestedItemTarget = null; $groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = ''; $groupItemTarget = $itemTarget = $fileSource = $parent = 0; @@ -1074,13 +1073,13 @@ class Share extends Constants { } $isGroupShare = false; - $users = array($shareWith); + $users = [$shareWith]; $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $suggestedItemTarget); $run = true; $error = ''; - $preHookData = array( + $preHookData = [ 'itemType' => $itemType, 'itemSource' => $itemSource, 'shareType' => $shareType, @@ -1091,7 +1090,7 @@ class Share extends Constants { 'token' => null, 'run' => &$run, 'error' => &$error - ); + ]; $preHookData['itemTarget'] = $itemTarget; $preHookData['shareWith'] = $shareWith; @@ -1144,7 +1143,7 @@ class Share extends Constants { } } - $queriesToExecute[] = array( + $queriesToExecute[] = [ 'itemType' => $itemType, 'itemSource' => $itemSource, 'itemTarget' => $itemTarget, @@ -1158,7 +1157,7 @@ class Share extends Constants { 'token' => null, 'parent' => $parent, 'expiration' => null, - ); + ]; } @@ -1169,7 +1168,7 @@ class Share extends Constants { $id = self::insertShare($shareQuery); } - $postHookData = array( + $postHookData = [ 'itemType' => $itemType, 'itemSource' => $itemSource, 'parent' => $parent, @@ -1180,7 +1179,7 @@ class Share extends Constants { 'id' => $parent, 'token' => null, 'expirationDate' => null, - ); + ]; $postHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith; $postHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget; @@ -1208,7 +1207,7 @@ class Share extends Constants { private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) { $backend = self::getBackend($itemType); - $result = array(); + $result = []; $column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source'; @@ -1419,7 +1418,7 @@ class Share extends Constants { if ($format === self::FORMAT_NONE) { return $items; } else if ($format === self::FORMAT_STATUSES) { - $statuses = array(); + $statuses = []; foreach ($items as $item) { if ($item['share_type'] === self::SHARE_TYPE_LINK) { if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) { @@ -1507,7 +1506,7 @@ class Share extends Constants { */ private static function sendRemoteUnshare($remote, $id, $token) { $url = rtrim($remote, '/'); - $fields = array('token' => $token, 'format' => 'json'); + $fields = ['token' => $token, 'format' => 'json']; $url = self::removeProtocolFromUrl($url); $result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields); $status = json_decode($result['result'], true); diff --git a/lib/private/Share20/DefaultShareProvider.php b/lib/private/Share20/DefaultShareProvider.php index e7f077f4022..065d06de37e 100644 --- a/lib/private/Share20/DefaultShareProvider.php +++ b/lib/private/Share20/DefaultShareProvider.php @@ -2,9 +2,9 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * - * @author Andrius <andrius.kulbis@ktu.lt> * @author Bjoern Schiessle <bjoern@schiessle.org> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Calviño Sánchez <danxuliu@gmail.com> * @author Jan-Philipp Litza <jplitza@users.noreply.github.com> * @author Joas Schilling <coding@schilljs.com> @@ -53,7 +53,6 @@ use OCP\IUserManager; use OCP\Mail\IMailer; use OCP\Share\Exceptions\ShareNotFound; use OCP\Share\IShare; -use OCP\Share\IShareHelper; use OCP\Share\IShareProvider; /** @@ -839,7 +838,7 @@ class DefaultShareProvider implements IShareProvider { $pathSections = explode('/', $data['path'], 2); // FIXME: would not detect rare md5'd home storage case properly if ($pathSections[0] !== 'files' - && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) { + && in_array(explode(':', $data['storage_string_id'], 2)[0], ['home', 'object'])) { return false; } return true; diff --git a/lib/private/Share20/Manager.php b/lib/private/Share20/Manager.php index 9023e14fd2c..4e1f6567e6b 100644 --- a/lib/private/Share20/Manager.php +++ b/lib/private/Share20/Manager.php @@ -858,7 +858,7 @@ class Manager implements IManager { 'shareWith' => $shareWith, ]); - $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', array($initiatorDisplayName, $filename))); + $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename])); $emailTemplate->addHeader(); $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false); $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]); @@ -1022,7 +1022,7 @@ class Manager implements IManager { } else { $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy()); } - \OC_Hook::emit(Share::class, 'post_update_permissions', array( + \OC_Hook::emit(Share::class, 'post_update_permissions', [ 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'shareType' => $share->getShareType(), @@ -1030,7 +1030,7 @@ class Manager implements IManager { 'uidOwner' => $share->getSharedBy(), 'permissions' => $share->getPermissions(), 'path' => $userFolder->getRelativePath($share->getNode()->getPath()), - )); + ]); } return $share; diff --git a/lib/private/Share20/ProviderFactory.php b/lib/private/Share20/ProviderFactory.php index 5a91202a1d0..cdfd40c8703 100644 --- a/lib/private/Share20/ProviderFactory.php +++ b/lib/private/Share20/ProviderFactory.php @@ -36,7 +36,6 @@ use OC\Share20\Exception\ProviderException; use OCA\FederatedFileSharing\AddressHandler; use OCA\FederatedFileSharing\FederatedShareProvider; use OCA\FederatedFileSharing\Notifications; -use OCA\FederatedFileSharing\OCM\CloudFederationProvider; use OCA\FederatedFileSharing\TokenHandler; use OCA\ShareByMail\Settings\SettingsManager; use OCA\ShareByMail\ShareByMailProvider; diff --git a/lib/private/SubAdmin.php b/lib/private/SubAdmin.php index b3b40e78b9f..ce2a38ccbf6 100644 --- a/lib/private/SubAdmin.php +++ b/lib/private/SubAdmin.php @@ -4,6 +4,7 @@ * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Georg Ehrke <oc.list@georgehrke.com> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> * @author Lukas Reschke <lukas@statuscode.ch> @@ -135,7 +136,7 @@ class SubAdmin extends PublicEmitter implements ISubAdmin { */ public function getSubAdminsGroupsName(IUser $user): array { return array_map(function($group) { - return array('displayName' => $group->getDisplayName()); + return ['displayName' => $group->getDisplayName()]; }, $this->getSubAdminsGroups($user)); } diff --git a/lib/private/TagManager.php b/lib/private/TagManager.php index a12076196c8..ccb2e796155 100644 --- a/lib/private/TagManager.php +++ b/lib/private/TagManager.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bernhard Reiter <ockham@raz.or.at> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Thomas Tanghus <thomas@tanghus.net> * @author Vincent Petry <pvince81@owncloud.com> @@ -77,7 +78,7 @@ class TagManager implements \OCP\ITagManager { * logged in user * @return \OCP\ITags */ - public function load($type, $defaultTags = array(), $includeShared = false, $userId = null) { + public function load($type, $defaultTags = [], $includeShared = false, $userId = null) { if (is_null($userId)) { $user = $this->userSession->getUser(); if ($user === null) { diff --git a/lib/private/Tagging/TagMapper.php b/lib/private/Tagging/TagMapper.php index fb58c33dd07..c021c3646a4 100644 --- a/lib/private/Tagging/TagMapper.php +++ b/lib/private/Tagging/TagMapper.php @@ -4,6 +4,7 @@ * * @author Bernhard Posselt <dev@bernhard-posselt.com> * @author Bernhard Reiter <ockham@raz.or.at> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Morris Jobke <hey@morrisjobke.de> * @author Roeland Jago Douma <roeland@famdouma.nl> * @@ -52,12 +53,12 @@ class TagMapper extends Mapper { */ public function loadTags($owners, $type) { if(!is_array($owners)) { - $owners = array($owners); + $owners = [$owners]; } $sql = 'SELECT `id`, `uid`, `type`, `category` FROM `' . $this->getTableName() . '` ' . 'WHERE `uid` IN (' . str_repeat('?,', count($owners)-1) . '?) AND `type` = ? ORDER BY `category`'; - return $this->findEntities($sql, array_merge($owners, array($type))); + return $this->findEntities($sql, array_merge($owners, [$type])); } /** @@ -70,7 +71,7 @@ class TagMapper extends Mapper { $sql = 'SELECT `id`, `uid`, `type`, `category` FROM `' . $this->getTableName() . '` ' . 'WHERE `uid` = ? AND `type` = ? AND `category` = ?'; try { - $this->findEntity($sql, array($tag->getOwner(), $tag->getType(), $tag->getName())); + $this->findEntity($sql, [$tag->getOwner(), $tag->getType(), $tag->getName()]); } catch (DoesNotExistException $e) { return false; } diff --git a/lib/private/Tags.php b/lib/private/Tags.php index fe24391a1a5..8e26cccb408 100644 --- a/lib/private/Tags.php +++ b/lib/private/Tags.php @@ -4,6 +4,8 @@ * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bernhard Reiter <ockham@raz.or.at> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> + * @author Daniel Kesselberg <mail@danielkesselberg.de> * @author derkostka <sebastian.kostka@gmail.com> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> @@ -57,14 +59,14 @@ class Tags implements ITags { * * @var array */ - private $tags = array(); + private $tags = []; /** * Used for storing objectid/categoryname pairs while rescanning. * * @var array */ - private static $relations = array(); + private static $relations = []; /** * Type @@ -93,7 +95,7 @@ class Tags implements ITags { * * @var array */ - private $owners = array(); + private $owners = []; /** * The Mapper we're using to communicate our Tag objects to the database. @@ -122,12 +124,12 @@ class Tags implements ITags { * @param array $defaultTags Tags that should be created at construction. * @param boolean $includeShared Whether to include tags for items shared with this user by others. */ - public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) { + public function __construct(TagMapper $mapper, $user, $type, $defaultTags = [], $includeShared = false) { $this->mapper = $mapper; $this->user = $user; $this->type = $type; $this->includeShared = $includeShared; - $this->owners = array($this->user); + $this->owners = [$this->user]; if ($this->includeShared) { $this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true)); $this->backend = \OC\Share\Share::getBackend($this->type); @@ -176,13 +178,13 @@ class Tags implements ITags { */ public function getTags() { if(!count($this->tags)) { - return array(); + return []; } usort($this->tags, function($a, $b) { return strnatcasecmp($a->getName(), $b->getName()); }); - $tagMap = array(); + $tagMap = []; foreach($this->tags as $tag) { if($tag->getName() !== ITags::TAG_FAVORITE) { @@ -216,7 +218,7 @@ class Tags implements ITags { * or false if an error occurred */ public function getTagsForObjects(array $objIds) { - $entries = array(); + $entries = []; try { $conn = \OC::$server->getDatabaseConnection(); @@ -226,13 +228,13 @@ class Tags implements ITags { 'SELECT `category`, `categoryid`, `objid` ' . 'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' . 'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)', - array($this->user, $this->type, $chunk), - array(null, null, IQueryBuilder::PARAM_INT_ARRAY) + [$this->user, $this->type, $chunk], + [null, null, IQueryBuilder::PARAM_INT_ARRAY] ); while ($row = $result->fetch()) { $objId = (int)$row['objid']; if (!isset($entries[$objId])) { - $entries[$objId] = array(); + $entries[$objId] = []; } $entries[$objId][] = $row['category']; } @@ -283,13 +285,13 @@ class Tags implements ITags { ); } - $ids = array(); + $ids = []; $sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE . '` WHERE `categoryid` = ?'; try { $stmt = \OC_DB::prepare($sql); - $result = $stmt->execute(array($tagId)); + $result = $stmt->execute([$tagId]); if ($result === null) { \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR); return false; @@ -440,19 +442,19 @@ class Tags implements ITags { */ public function addMultiple($names, $sync=false, $id = null) { if(!is_array($names)) { - $names = array($names); + $names = [$names]; } $names = array_map('trim', $names); array_filter($names); - $newones = array(); + $newones = []; foreach($names as $name) { if(!$this->hasTag($name) && $name !== '') { $newones[] = new Tag($this->user, $this->type, $name); } if(!is_null($id) ) { // Insert $objectid, $categoryid pairs if not exist. - self::$relations[] = array('objid' => $id, 'tag' => $name); + self::$relations[] = ['objid' => $id, 'tag' => $name]; } } $this->tags = array_merge($this->tags, $newones); @@ -498,11 +500,11 @@ class Tags implements ITags { if($tagId) { try { $dbConnection->insertIfNotExist(self::RELATION_TABLE, - array( + [ 'objid' => $relation['objid'], 'categoryid' => $tagId, 'type' => $this->type, - )); + ]); } catch(\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, @@ -512,7 +514,7 @@ class Tags implements ITags { } } } - self::$relations = array(); // reset + self::$relations = []; // reset } else { \OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! ' . print_r($this->tags, true), ILogger::ERROR); @@ -532,7 +534,7 @@ class Tags implements ITags { try { $stmt = \OC_DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` ' . 'WHERE `uid` = ?'); - $result = $stmt->execute(array($arguments['uid'])); + $result = $stmt->execute([$arguments['uid']]); if ($result === null) { \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR); } @@ -550,7 +552,7 @@ class Tags implements ITags { . 'WHERE `categoryid` = ?'); while( $row = $result->fetchRow()) { try { - $stmt->execute(array($row['id'])); + $stmt->execute([$row['id']]); } catch(\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, @@ -570,7 +572,7 @@ class Tags implements ITags { try { $stmt = \OC_DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` ' . 'WHERE `uid` = ?'); - $result = $stmt->execute(array($arguments['uid'])); + $result = $stmt->execute([$arguments['uid']]); if ($result === null) { \OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR); } @@ -635,7 +637,7 @@ class Tags implements ITags { 'level' => ILogger::ERROR, 'app' => 'core', ]); - return array(); + return []; } } @@ -685,11 +687,11 @@ class Tags implements ITags { } try { \OC::$server->getDatabaseConnection()->insertIfNotExist(self::RELATION_TABLE, - array( + [ 'objid' => $objid, 'categoryid' => $tagId, 'type' => $this->type, - )); + ]); } catch(\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, @@ -724,7 +726,7 @@ class Tags implements ITags { $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` ' . 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?'; $stmt = \OC_DB::prepare($sql); - $stmt->execute(array($objid, $tagId, $this->type)); + $stmt->execute([$objid, $tagId, $this->type]); } catch(\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, @@ -744,7 +746,7 @@ class Tags implements ITags { */ public function delete($names) { if(!is_array($names)) { - $names = array($names); + $names = [$names]; } $names = array_map('trim', $names); @@ -774,7 +776,7 @@ class Tags implements ITags { $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` ' . 'WHERE `categoryid` = ?'; $stmt = \OC_DB::prepare($sql); - $result = $stmt->execute(array($id)); + $result = $stmt->execute([$id]); if ($result === null) { \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), @@ -801,7 +803,7 @@ class Tags implements ITags { } return array_search(strtolower($needle), array_map( function($tag) use($mem) { - return strtolower(call_user_func(array($tag, $mem))); + return strtolower(call_user_func([$tag, $mem])); }, $haystack) ); } @@ -850,11 +852,11 @@ class Tags implements ITags { * @return array */ private function tagMap(Tag $tag) { - return array( + return [ 'id' => $tag->getId(), 'name' => $tag->getName(), 'owner' => $tag->getOwner(), 'type' => $tag->getType() - ); + ]; } } diff --git a/lib/private/Template/Base.php b/lib/private/Template/Base.php index dab4e9d9086..9ac74ffc60c 100644 --- a/lib/private/Template/Base.php +++ b/lib/private/Template/Base.php @@ -5,6 +5,7 @@ * @author Bart Visscher <bartv@thisnet.nl> * @author Björn Schießle <bjoern@schiessle.org> * @author Christopher Schäpers <kondou@ts.unde.re> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Julius Härtl <jus@bitgrid.net> * @author Lukas Reschke <lukas@statuscode.ch> @@ -48,7 +49,7 @@ class Base { * @param Defaults $theme */ public function __construct($template, $requestToken, $l10n, $theme ) { - $this->vars = array(); + $this->vars = []; $this->vars['requesttoken'] = $requestToken; $this->l10n = $l10n; $this->template = $template; @@ -118,7 +119,7 @@ class Base { $this->vars[$key][] = $value; } else{ - $this->vars[$key] = array( $value ); + $this->vars[$key] = [ $value ]; } } diff --git a/lib/private/Template/CSSResourceLocator.php b/lib/private/Template/CSSResourceLocator.php index 94eac48b61f..c931a62420a 100644 --- a/lib/private/Template/CSSResourceLocator.php +++ b/lib/private/Template/CSSResourceLocator.php @@ -4,6 +4,7 @@ * * @author Axel Helmert <axel.helmert@luka.de> * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> * @author Kyle Fazzari <kyrofa@ubuntu.com> @@ -145,7 +146,7 @@ class CSSResourceLocator extends ResourceLocator { } } - $this->resources[] = array($webRoot? : \OC::$WEBROOT, $webRoot, $file); + $this->resources[] = [$webRoot? : \OC::$WEBROOT, $webRoot, $file]; } } } diff --git a/lib/private/Template/JSCombiner.php b/lib/private/Template/JSCombiner.php index a6908ce8071..96d5a1e7779 100644 --- a/lib/private/Template/JSCombiner.php +++ b/lib/private/Template/JSCombiner.php @@ -2,6 +2,7 @@ /** * @copyright 2017, Roeland Jago Douma <roeland@famdouma.nl> * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Julius Härtl <jus@bitgrid.net> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> @@ -133,7 +134,7 @@ class JSCombiner { $deps = json_decode($deps, true); - if ($deps === NULL) { + if ($deps === null) { return false; } @@ -216,7 +217,7 @@ class JSCombiner { $fileName = array_pop($tmpfileLoc); $fileName = str_replace('.json', '.js', $fileName); - return substr($this->urlGenerator->linkToRoute('core.Js.getJs', array('fileName' => $fileName, 'appName' => $appName)), strlen(\OC::$WEBROOT) + 1); + return substr($this->urlGenerator->linkToRoute('core.Js.getJs', ['fileName' => $fileName, 'appName' => $appName]), strlen(\OC::$WEBROOT) + 1); } /** diff --git a/lib/private/Template/JSConfigHelper.php b/lib/private/Template/JSConfigHelper.php index ec11e8456d1..781cb0d7794 100644 --- a/lib/private/Template/JSConfigHelper.php +++ b/lib/private/Template/JSConfigHelper.php @@ -298,7 +298,7 @@ class JSConfigHelper { } // Allow hooks to modify the output values - \OC_Hook::emit('\OCP\Config', 'js', array('array' => &$array)); + \OC_Hook::emit('\OCP\Config', 'js', ['array' => &$array]); $result = ''; diff --git a/lib/private/Template/ResourceLocator.php b/lib/private/Template/ResourceLocator.php index 22595df7964..c99df063588 100755 --- a/lib/private/Template/ResourceLocator.php +++ b/lib/private/Template/ResourceLocator.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> @@ -37,7 +38,7 @@ abstract class ResourceLocator { protected $thirdpartyroot; protected $webroot; - protected $resources = array(); + protected $resources = []; /** @var \OCP\ILogger */ protected $logger; @@ -185,7 +186,7 @@ abstract class ResourceLocator { ]); } } - $this->resources[] = array($root, $webRoot, $file); + $this->resources[] = [$root, $webRoot, $file]; if ($throw && !is_file($root . '/' . $file)) { throw new ResourceNotFoundException($file, $webRoot); diff --git a/lib/private/Template/SCSSCacher.php b/lib/private/Template/SCSSCacher.php index f571967ea1c..427588ddddf 100644 --- a/lib/private/Template/SCSSCacher.php +++ b/lib/private/Template/SCSSCacher.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, John Molakvoæ (skjnldsv@protonmail.com) * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> * @author Julius Haertl <jus@bitgrid.net> * @author Julius Härtl <jus@bitgrid.net> diff --git a/lib/private/TemplateLayout.php b/lib/private/TemplateLayout.php index 8cecc17dbc1..5562d4b5e2a 100644 --- a/lib/private/TemplateLayout.php +++ b/lib/private/TemplateLayout.php @@ -5,6 +5,7 @@ * @author Bart Visscher <bartv@thisnet.nl> * @author Bjoern Schiessle <bjoern@schiessle.org> * @author Christopher Schäpers <kondou@ts.unde.re> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Clark Tomlinson <fallen013@gmail.com> * @author Daniel Calviño Sánchez <danxuliu@gmail.com> * @author Guillaume COMPAGNON <gcompagnon@outlook.com> @@ -22,7 +23,7 @@ * @author Robin Appelman <robin@icewind.nl> * @author Robin McCorkell <robin@mccorkell.me.uk> * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Thomas Citharel <tcit@tcit.fr> + * @author Thomas Citharel <nextcloud@tcit.fr> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 @@ -172,7 +173,7 @@ class TemplateLayout extends \OC_Template { // Add the js files $jsFiles = self::findJavascriptFiles(\OC_Util::$scripts); - $this->assign('jsfiles', array()); + $this->assign('jsfiles', []); if ($this->config->getSystemValue('installed', false) && $renderAs != 'error') { if (\OC::$server->getContentSecurityPolicyNonceManager()->browserSupportsCspV3()) { $jsConfigHelper = new JSConfigHelper( @@ -220,7 +221,7 @@ class TemplateLayout extends \OC_Template { $cssFiles = self::findStylesheetFiles(\OC_Util::$styles, false); } - $this->assign('cssfiles', array()); + $this->assign('cssfiles', []); $this->assign('printcssfiles', []); $this->assign('versionHash', self::$versionHash); foreach($cssFiles as $info) { @@ -303,8 +304,8 @@ class TemplateLayout extends \OC_Template { $locator = new \OC\Template\CSSResourceLocator( \OC::$server->getLogger(), $theme, - array( \OC::$SERVERROOT => \OC::$WEBROOT ), - array( \OC::$SERVERROOT => \OC::$WEBROOT ), + [ \OC::$SERVERROOT => \OC::$WEBROOT ], + [ \OC::$SERVERROOT => \OC::$WEBROOT ], $SCSSCacher ); $locator->find($styles); @@ -339,8 +340,8 @@ class TemplateLayout extends \OC_Template { $locator = new \OC\Template\JSResourceLocator( \OC::$server->getLogger(), $theme, - array( \OC::$SERVERROOT => \OC::$WEBROOT ), - array( \OC::$SERVERROOT => \OC::$WEBROOT ), + [ \OC::$SERVERROOT => \OC::$WEBROOT ], + [ \OC::$SERVERROOT => \OC::$WEBROOT ], \OC::$server->query(JSCombiner::class) ); $locator->find($scripts); diff --git a/lib/private/URLGenerator.php b/lib/private/URLGenerator.php index 4f50f779a83..62eafaafedb 100644 --- a/lib/private/URLGenerator.php +++ b/lib/private/URLGenerator.php @@ -7,6 +7,7 @@ declare(strict_types=1); * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Felix Epp <work@felixepp.de> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> @@ -77,7 +78,7 @@ class URLGenerator implements IURLGenerator { * * Returns a url to the given route. */ - public function linkToRoute(string $route, array $parameters = array()): string { + public function linkToRoute(string $route, array $parameters = []): string { // TODO: mock router return \OC::$server->getRouter()->generate($route, $parameters); } @@ -90,7 +91,7 @@ class URLGenerator implements IURLGenerator { * * Returns an absolute url to the given route. */ - public function linkToRouteAbsolute(string $routeName, array $arguments = array()): string { + public function linkToRouteAbsolute(string $routeName, array $arguments = []): string { return $this->getAbsoluteURL($this->linkToRoute($routeName, $arguments)); } @@ -118,7 +119,7 @@ class URLGenerator implements IURLGenerator { * * Returns a url to the given app and file. */ - public function linkTo(string $app, string $file, array $args = array()): string { + 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 !== '' ) { diff --git a/lib/private/Updater.php b/lib/private/Updater.php index 611da73254e..91a0943e048 100644 --- a/lib/private/Updater.php +++ b/lib/private/Updater.php @@ -124,22 +124,22 @@ class Updater extends BasicEmitter { $installedVersion = $this->config->getSystemValue('version', '0.0.0'); $currentVersion = implode('.', \OCP\Util::getVersion()); - $this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, array('app' => 'core')); + $this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, ['app' => 'core']); $success = true; try { $this->doUpgrade($currentVersion, $installedVersion); } catch (HintException $exception) { $this->log->logException($exception, ['app' => 'core']); - $this->emit('\OC\Updater', 'failure', array($exception->getMessage() . ': ' .$exception->getHint())); + $this->emit('\OC\Updater', 'failure', [$exception->getMessage() . ': ' .$exception->getHint()]); $success = false; } catch (\Exception $exception) { $this->log->logException($exception, ['app' => 'core']); - $this->emit('\OC\Updater', 'failure', array(get_class($exception) . ': ' .$exception->getMessage())); + $this->emit('\OC\Updater', 'failure', [get_class($exception) . ': ' .$exception->getMessage()]); $success = false; } - $this->emit('\OC\Updater', 'updateEnd', array($success)); + $this->emit('\OC\Updater', 'updateEnd', [$success]); if(!$wasMaintenanceModeEnabled && $success) { $this->config->setSystemValue('maintenance', false); @@ -324,7 +324,7 @@ class Updater extends BasicEmitter { $this->includePreUpdate($appId); } if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/database.xml')) { - $this->emit('\OC\Updater', 'appSimulateUpdate', array($appId)); + $this->emit('\OC\Updater', 'appSimulateUpdate', [$appId]); \OC_DB::simulateUpdateDbFromStructure(\OC_App::getAppPath($appId) . '/appinfo/database.xml'); } } @@ -349,15 +349,15 @@ class Updater extends BasicEmitter { */ protected function doAppUpgrade() { $apps = \OC_App::getEnabledApps(); - $priorityTypes = array('authentication', 'filesystem', 'logging'); + $priorityTypes = ['authentication', 'filesystem', 'logging']; $pseudoOtherType = 'other'; - $stacks = array($pseudoOtherType => array()); + $stacks = [$pseudoOtherType => []]; foreach ($apps as $appId) { $priorityType = false; foreach ($priorityTypes as $type) { if(!isset($stacks[$type])) { - $stacks[$type] = array(); + $stacks[$type] = []; } if (\OC_App::isType($appId, [$type])) { $stacks[$type][] = $appId; @@ -409,7 +409,7 @@ class Updater extends BasicEmitter { throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update'); } \OC::$server->getAppManager()->disableApp($app, true); - $this->emit('\OC\Updater', 'incompatibleAppDisabled', array($app)); + $this->emit('\OC\Updater', 'incompatibleAppDisabled', [$app]); } // no need to disable any app in case this is a non-core upgrade if (!$isCoreUpgrade) { diff --git a/lib/private/Updater/ChangesCheck.php b/lib/private/Updater/ChangesCheck.php index 259fb750c05..138e3bed9c3 100644 --- a/lib/private/Updater/ChangesCheck.php +++ b/lib/private/Updater/ChangesCheck.php @@ -6,6 +6,7 @@ declare(strict_types=1); * @copyright Copyright (c) 2018 Arthur Schiwon <blizzz@arthur-schiwon.de> * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> + * @author Daniel Kesselberg <mail@danielkesselberg.de> * * @license GNU AGPL version 3 or any later version * diff --git a/lib/private/User/Backend.php b/lib/private/User/Backend.php index a4dbcf77484..8fa2f3018b2 100644 --- a/lib/private/User/Backend.php +++ b/lib/private/User/Backend.php @@ -2,6 +2,7 @@ /** * @copyright Copyright (c) 2016, ownCloud, Inc. * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Roeland Jago Douma <roeland@famdouma.nl> * @@ -47,7 +48,7 @@ abstract class Backend implements UserInterface { const PROVIDE_AVATAR = 16777216; // 1 << 24 const COUNT_USERS = 268435456; // 1 << 28 - protected $possibleActions = array( + protected $possibleActions = [ self::CREATE_USER => 'createUser', self::SET_PASSWORD => 'setPassword', self::CHECK_PASSWORD => 'checkPassword', @@ -56,7 +57,7 @@ abstract class Backend implements UserInterface { self::SET_DISPLAYNAME => 'setDisplayName', self::PROVIDE_AVATAR => 'canChangeAvatar', self::COUNT_USERS => 'countUsers', - ); + ]; /** * Get all supported actions @@ -108,7 +109,7 @@ abstract class Backend implements UserInterface { * @return string[] an array of all uids */ public function getUsers($search = '', $limit = null, $offset = null) { - return array(); + return []; } /** @@ -147,7 +148,7 @@ abstract class Backend implements UserInterface { * @return array an array of all displayNames (value) and the corresponding uids (key) */ public function getDisplayNames($search = '', $limit = null, $offset = null) { - $displayNames = array(); + $displayNames = []; $users = $this->getUsers($search, $limit, $offset); foreach ( $users as $user) { $displayNames[$user] = $user; diff --git a/lib/private/User/Database.php b/lib/private/User/Database.php index 905a66f3797..856959a4596 100644 --- a/lib/private/User/Database.php +++ b/lib/private/User/Database.php @@ -72,7 +72,6 @@ use OCP\User\Backend\IGetHomeBackend; use OCP\User\Backend\IGetRealUIDBackend; use OCP\User\Backend\ISetDisplayNameBackend; use OCP\User\Backend\ISetPasswordBackend; -use Symfony\Component\EventDispatcher\GenericEvent; /** * Class for user management in a SQL Database (e.g. MySQL, SQLite) diff --git a/lib/private/User/Manager.php b/lib/private/User/Manager.php index 7fc774630bd..2dd12cf916d 100644 --- a/lib/private/User/Manager.php +++ b/lib/private/User/Manager.php @@ -69,12 +69,12 @@ class Manager extends PublicEmitter implements IUserManager { /** * @var \OCP\UserInterface[] $backends */ - private $backends = array(); + private $backends = []; /** * @var \OC\User\User[] $cachedUsers */ - private $cachedUsers = array(); + private $cachedUsers = []; /** @var IConfig */ private $config; @@ -121,7 +121,7 @@ class Manager extends PublicEmitter implements IUserManager { * @param \OCP\UserInterface $backend */ public function removeBackend($backend) { - $this->cachedUsers = array(); + $this->cachedUsers = []; if (($i = array_search($backend, $this->backends)) !== false) { unset($this->backends[$i]); } @@ -131,8 +131,8 @@ class Manager extends PublicEmitter implements IUserManager { * remove all user backends */ public function clearBackends() { - $this->cachedUsers = array(); - $this->backends = array(); + $this->cachedUsers = []; + $this->backends = []; } /** @@ -241,7 +241,7 @@ class Manager extends PublicEmitter implements IUserManager { * @return \OC\User\User[] */ public function search($pattern, $limit = null, $offset = null) { - $users = array(); + $users = []; foreach ($this->backends as $backend) { $backendUsers = $backend->getUsers($pattern, $limit, $offset); if (is_array($backendUsers)) { @@ -270,7 +270,7 @@ class Manager extends PublicEmitter implements IUserManager { * @return \OC\User\User[] */ public function searchDisplayName($pattern, $limit = null, $offset = null) { - $users = array(); + $users = []; foreach ($this->backends as $backend) { $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset); if (is_array($backendUsers)) { diff --git a/lib/private/User/Session.php b/lib/private/User/Session.php index 602f779c901..9129fb7054b 100644 --- a/lib/private/User/Session.php +++ b/lib/private/User/Session.php @@ -51,6 +51,7 @@ use OC_User; use OC_Util; use OCA\DAV\Connector\Sabre\Auth; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Authentication\Events\LoginFailedEvent; use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\NotPermittedException; use OCP\IConfig; @@ -58,6 +59,7 @@ use OCP\ILogger; use OCP\IRequest; use OCP\ISession; use OCP\IUser; +use OCP\IUserManager; use OCP\IUserSession; use OCP\Lockdown\ILockdownManager; use OCP\Security\ISecureRandom; @@ -137,7 +139,8 @@ class Session implements IUserSession, Emitter { ISecureRandom $random, ILockdownManager $lockdownManager, ILogger $logger, - IEventDispatcher $dispatcher) { + IEventDispatcher $dispatcher + ) { $this->manager = $manager; $this->session = $session; $this->timeFactory = $timeFactory; @@ -440,7 +443,7 @@ class Session implements IUserSession, Emitter { $currentDelay = $throttler->sleepDelay($request->getRemoteAddress(), 'login'); if ($this->manager instanceof PublicEmitter) { - $this->manager->emit('\OC\User', 'preLogin', array($user, $password)); + $this->manager->emit('\OC\User', 'preLogin', [$user, $password]); } try { @@ -467,6 +470,9 @@ class Session implements IUserSession, Emitter { $this->logger->warning('Login failed: \'' . $user . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']); $throttler->registerAttempt('login', $request->getRemoteAddress(), ['user' => $user]); + + $this->dispatcher->dispatchTyped(new OC\Authentication\Events\LoginFailed($user)); + if ($currentDelay === 0) { $throttler->sleepDelay($request->getRemoteAddress(), 'login'); } @@ -500,7 +506,7 @@ class Session implements IUserSession, Emitter { Util::emitHook( '\OCA\Files_Sharing\API\Server2Server', 'preLoginNameUsedAsUserName', - array('uid' => &$username) + ['uid' => &$username] ); $user = $this->manager->get($username); if (is_null($user)) { @@ -640,7 +646,7 @@ class Session implements IUserSession, Emitter { // Ignore and use empty string instead } - $this->manager->emit('\OC\User', 'preLogin', array($uid, $password)); + $this->manager->emit('\OC\User', 'preLogin', [$uid, $password]); $user = $this->manager->get($uid); if (is_null($user)) { @@ -841,7 +847,7 @@ class Session implements IUserSession, Emitter { */ public function loginWithCookie($uid, $currentToken, $oldSessionId) { $this->session->regenerateId(); - $this->manager->emit('\OC\User', 'preRememberedLogin', array($uid)); + $this->manager->emit('\OC\User', 'preRememberedLogin', [$uid]); $user = $this->manager->get($uid); if (is_null($user)) { // user does not exist diff --git a/lib/private/User/User.php b/lib/private/User/User.php index c68b8b88e31..0f17af3063e 100644 --- a/lib/private/User/User.php +++ b/lib/private/User/User.php @@ -5,6 +5,7 @@ * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> @@ -202,7 +203,7 @@ class User implements IUser { public function delete() { $this->dispatcher->dispatch(IUser::class . '::preDelete', new GenericEvent($this)); if ($this->emitter) { - $this->emitter->emit('\OC\User', 'preDelete', array($this)); + $this->emitter->emit('\OC\User', 'preDelete', [$this]); } // get the home now because it won't return it after user deletion $homePath = $this->getHome(); @@ -247,7 +248,7 @@ class User implements IUser { $this->dispatcher->dispatch(IUser::class . '::postDelete', new GenericEvent($this)); if ($this->emitter) { - $this->emitter->emit('\OC\User', 'postDelete', array($this)); + $this->emitter->emit('\OC\User', 'postDelete', [$this]); } } return !($result === false); @@ -266,7 +267,7 @@ class User implements IUser { 'recoveryPassword' => $recoveryPassword, ])); if ($this->emitter) { - $this->emitter->emit('\OC\User', 'preSetPassword', array($this, $password, $recoveryPassword)); + $this->emitter->emit('\OC\User', 'preSetPassword', [$this, $password, $recoveryPassword]); } if ($this->backend->implementsActions(Backend::SET_PASSWORD)) { $result = $this->backend->setPassword($this->uid, $password); @@ -275,7 +276,7 @@ class User implements IUser { 'recoveryPassword' => $recoveryPassword, ])); if ($this->emitter) { - $this->emitter->emit('\OC\User', 'postSetPassword', array($this, $password, $recoveryPassword)); + $this->emitter->emit('\OC\User', 'postSetPassword', [$this, $password, $recoveryPassword]); } return !($result === false); } else { @@ -473,7 +474,7 @@ class User implements IUser { 'oldValue' => $oldValue, ])); if ($this->emitter) { - $this->emitter->emit('\OC\User', 'changeUser', array($this, $feature, $value, $oldValue)); + $this->emitter->emit('\OC\User', 'changeUser', [$this, $feature, $value, $oldValue]); } } } diff --git a/lib/private/legacy/api.php b/lib/private/legacy/api.php index 44028407034..47590a00910 100644 --- a/lib/private/legacy/api.php +++ b/lib/private/legacy/api.php @@ -4,6 +4,7 @@ * * @author Bart Visscher <bartv@thisnet.nl> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Lukas Reschke <lukas@statuscode.ch> * @author Michael Gapczynski <GapczynskiM@gmail.com> @@ -36,7 +37,7 @@ class OC_API { /** * api actions */ - protected static $actions = array(); + protected static $actions = []; /** * respond to a call @@ -101,7 +102,7 @@ class OC_API { * @return string */ public static function requestedFormat() { - $formats = array('json', 'xml'); + $formats = ['json', 'xml']; $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml'; return $format; @@ -167,12 +168,12 @@ class OC_API { * @return string */ public static function renderResult($format, $meta, $data) { - $response = array( - 'ocs' => array( + $response = [ + 'ocs' => [ 'meta' => $meta, 'data' => $data, - ), - ); + ], + ]; if ($format == 'json') { return OC_JSON::encode($response); } diff --git a/lib/private/legacy/app.php b/lib/private/legacy/app.php index 961e51fe736..996b7a885c6 100644 --- a/lib/private/legacy/app.php +++ b/lib/private/legacy/app.php @@ -81,7 +81,7 @@ class OC_App { * @return string */ public static function cleanAppId(string $app): string { - return str_replace(array('\0', '/', '\\', '..'), '', $app); + return str_replace(['\0', '/', '\\', '..'], '', $app); } /** @@ -473,10 +473,10 @@ class OC_App { foreach ($possibleApps as $possibleApp) { $version = self::getAppVersionByPath($possibleApp['path'] . '/' . $appId); if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) { - $versionToLoad = array( + $versionToLoad = [ 'dir' => $possibleApp, 'version' => $version, - ); + ]; } } $app_dir[$appId] = $versionToLoad['dir']; diff --git a/lib/private/legacy/db.php b/lib/private/legacy/db.php index 9371e733d28..34cc39f26aa 100644 --- a/lib/private/legacy/db.php +++ b/lib/private/legacy/db.php @@ -5,6 +5,7 @@ * @author Andreas Fischer <bantu@owncloud.com> * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Lukas Reschke <lukas@statuscode.ch> @@ -121,7 +122,7 @@ class OC_DB { . ' pass an array with \'limit\' and \'offset\' instead'; throw new \OC\DatabaseException($message); } - $stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null); + $stmt = ['sql' => $stmt, 'limit' => null, 'offset' => null]; } if (is_array($stmt)) { // convert to prepared statement diff --git a/lib/private/legacy/db/statementwrapper.php b/lib/private/legacy/db/statementwrapper.php index 4512784d955..872e8f64e79 100644 --- a/lib/private/legacy/db/statementwrapper.php +++ b/lib/private/legacy/db/statementwrapper.php @@ -4,6 +4,7 @@ * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> @@ -42,7 +43,7 @@ class OC_DB_StatementWrapper { */ private $statement = null; private $isManipulation = false; - private $lastArguments = array(); + private $lastArguments = []; /** * @param boolean $isManipulation @@ -56,7 +57,7 @@ class OC_DB_StatementWrapper { * pass all other function directly to the \Doctrine\DBAL\Driver\Statement */ public function __call($name,$arguments) { - return call_user_func_array(array($this->statement,$name), $arguments); + return call_user_func_array([$this->statement,$name], $arguments); } /** diff --git a/lib/private/legacy/files.php b/lib/private/legacy/files.php index adc793ba9b7..249d3e5154f 100644 --- a/lib/private/legacy/files.php +++ b/lib/private/legacy/files.php @@ -4,6 +4,7 @@ * * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Daniel Calviño Sánchez <danxuliu@gmail.com> * @author Frank Karlitschek <frank@karlitschek.de> * @author Jakob Sack <mail@jakobsack.de> @@ -42,7 +43,6 @@ use OC\Files\View; use OC\Streamer; -use OCP\ILogger; use OCP\Lock\ILockingProvider; /** @@ -123,7 +123,7 @@ class OC_Files { if (!is_array($files)) { $filename = $dir . '/' . $files; if (!$view->is_dir($filename)) { - self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params); + self::getSingleFile($view, $dir, $files, is_null($params) ? [] : $params); return; } } @@ -150,7 +150,7 @@ class OC_Files { /* Calculate filesize and number of files */ if ($getType === self::ZIP_FILES) { - $fileInfos = array(); + $fileInfos = []; $fileSize = 0; foreach ($files as $file) { $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file); @@ -161,7 +161,7 @@ class OC_Files { } elseif ($getType === self::ZIP_DIR) { $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files); $fileSize = $fileInfo->getSize(); - $numberOfFiles = self::getNumberOfFiles(array($fileInfo)); + $numberOfFiles = self::getNumberOfFiles([$fileInfo]); } $streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles); @@ -239,7 +239,7 @@ class OC_Files { $minOffset = 0; $ind = 0; - $rangeArray = array(); + $rangeArray = []; foreach ($rArray as $value) { $ranges = explode('-', $value); @@ -258,7 +258,7 @@ class OC_Files { if ($ranges[1] >= $fileSize) { $ranges[1] = $fileSize-1; } - $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ); + $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ]; $minOffset = $ranges[1] + 1; if ($minOffset >= $fileSize) { break; @@ -266,7 +266,7 @@ class OC_Files { } elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) { // case: x- - $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize ); + $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize ]; break; } elseif (is_numeric($ranges[1])) { @@ -274,7 +274,7 @@ class OC_Files { if ($ranges[1] > $fileSize) { $ranges[1] = $fileSize; } - $rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize ); + $rangeArray[$ind++] = [ 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize ]; break; } } @@ -315,7 +315,7 @@ class OC_Files { OC_Util::obEnd(); $view->lockFile($filename, ILockingProvider::LOCK_SHARED); - $rangeArray = array(); + $rangeArray = []; if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') { $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), $fileSize); @@ -352,7 +352,7 @@ class OC_Files { header_remove('Accept-Ranges'); header_remove('Content-Range'); http_response_code(200); - self::sendHeaders($filename, $name, array()); + self::sendHeaders($filename, $name, []); $view->readfile($filename); } } diff --git a/lib/private/legacy/helper.php b/lib/private/legacy/helper.php index 3ddb9d07b14..626295af5a9 100644 --- a/lib/private/legacy/helper.php +++ b/lib/private/legacy/helper.php @@ -6,6 +6,7 @@ * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bart Visscher <bartv@thisnet.nl> * @author Björn Schießle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Clark Tomlinson <fallen013@gmail.com> * @author Daniel Kesselberg <mail@danielkesselberg.de> * @author Felix Moeller <mail@felixmoeller.de> @@ -42,6 +43,8 @@ * along with this program. If not, see <http://www.gnu.org/licenses/> * */ + +use OCP\IUser; use Symfony\Component\Process\ExecutableFinder; /** @@ -100,7 +103,7 @@ class OC_Helper { return (float)$str; } - $bytes_array = array( + $bytes_array = [ 'b' => 1, 'k' => 1024, 'kb' => 1024, @@ -112,7 +115,7 @@ class OC_Helper { 't' => 1024 * 1024 * 1024 * 1024, 'pb' => 1024 * 1024 * 1024 * 1024 * 1024, 'p' => 1024 * 1024 * 1024 * 1024 * 1024, - ); + ]; $bytes = (float)$str; @@ -245,7 +248,7 @@ class OC_Helper { */ public static function streamCopy($source, $target) { if (!$source or !$target) { - return array(0, false); + return [0, false]; } $bufSize = 8192; $result = true; @@ -266,7 +269,7 @@ class OC_Helper { break; } } - return array($count, $result); + return [$count, $result]; } /** @@ -342,7 +345,7 @@ class OC_Helper { */ public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') { $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER; - $ret = array(); + $ret = []; foreach ($input as $k => $v) { $ret[mb_convert_case($k, $case, $encoding)] = $v; } @@ -503,19 +506,14 @@ class OC_Helper { || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage') ) { /** @var \OC\Files\Storage\Home $storage */ - $userInstance = $storage->getUser(); - $user = ($userInstance === null) ? null : $userInstance->getUID(); + $user = $storage->getUser(); } else { - $user = \OC::$server->getUserSession()->getUser()->getUID(); - } - if ($user) { - $quota = OC_Util::getUserQuota($user); - } else { - $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED; + $user = \OC::$server->getUserSession()->getUser(); } + $quota = OC_Util::getUserQuota($user); if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) { // always get free space / total space from root + mount points - return self::getGlobalStorageInfo(); + return self::getGlobalStorageInfo($quota); } } @@ -561,11 +559,10 @@ class OC_Helper { /** * Get storage info including all mount points and quota * + * @param int $quota * @return array */ - private static function getGlobalStorageInfo() { - $quota = OC_Util::getUserQuota(\OCP\User::getUser()); - + private static function getGlobalStorageInfo($quota) { $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext'); $used = $rootInfo['size']; if ($used < 0) { diff --git a/lib/private/legacy/hook.php b/lib/private/legacy/hook.php index 6353d1f15db..2918dd4282f 100644 --- a/lib/private/legacy/hook.php +++ b/lib/private/legacy/hook.php @@ -36,7 +36,7 @@ class OC_Hook { public static $thrownExceptions = []; - static private $registered = array(); + static private $registered = []; /** * connects a function to a hook @@ -55,12 +55,12 @@ class OC_Hook { // If we're trying to connect to an emitting class that isn't // yet registered, register it if( !array_key_exists($signalClass, self::$registered )) { - self::$registered[$signalClass] = array(); + 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] )) { - self::$registered[$signalClass][$signalName] = array(); + self::$registered[$signalClass][$signalName] = []; } // don't connect hooks twice @@ -70,10 +70,10 @@ class OC_Hook { } } // Connect the hook handler to the requested emitter - self::$registered[$signalClass][$signalName][] = array( + self::$registered[$signalClass][$signalName][] = [ "class" => $slotClass, "name" => $slotName - ); + ]; // No chance for failure ;-) return true; @@ -108,7 +108,7 @@ class OC_Hook { // Call all slots foreach( self::$registered[$signalClass][$signalName] as $i ) { try { - call_user_func( array( $i["class"], $i["name"] ), $params ); + call_user_func( [ $i["class"], $i["name"] ], $params ); } catch (Exception $e){ self::$thrownExceptions[] = $e; \OC::$server->getLogger()->logException($e); @@ -132,12 +132,12 @@ class OC_Hook { static public function clear($signalClass='', $signalName='') { if ($signalClass) { if ($signalName) { - self::$registered[$signalClass][$signalName]=array(); + self::$registered[$signalClass][$signalName]=[]; }else{ - self::$registered[$signalClass]=array(); + self::$registered[$signalClass]=[]; } }else{ - self::$registered=array(); + self::$registered=[]; } } diff --git a/lib/private/legacy/image.php b/lib/private/legacy/image.php index e0f2dad3599..7d23ece7ffa 100644 --- a/lib/private/legacy/image.php +++ b/lib/private/legacy/image.php @@ -7,6 +7,7 @@ * @author Björn Schießle <bjoern@schiessle.org> * @author Byron Marohn <combustible@live.com> * @author Christopher Schäpers <kondou@ts.unde.re> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Georg Ehrke <oc.list@georgehrke.com> * @author j-ed <juergen@eisfair.org> * @author Joas Schilling <coding@schilljs.com> @@ -132,7 +133,7 @@ class OC_Image implements \OCP\IImage { */ public function widthTopLeft() { $o = $this->getOrientation(); - $this->logger->debug('OC_Image->widthTopLeft() Orientation: ' . $o, array('app' => 'core')); + $this->logger->debug('OC_Image->widthTopLeft() Orientation: ' . $o, ['app' => 'core']); switch ($o) { case -1: case 1: @@ -156,7 +157,7 @@ class OC_Image implements \OCP\IImage { */ public function heightTopLeft() { $o = $this->getOrientation(); - $this->logger->debug('OC_Image->heightTopLeft() Orientation: ' . $o, array('app' => 'core')); + $this->logger->debug('OC_Image->heightTopLeft() Orientation: ' . $o, ['app' => 'core']); switch ($o) { case -1: case 1: @@ -201,7 +202,7 @@ class OC_Image implements \OCP\IImage { } if ($filePath === null) { if ($this->filePath === null) { - $this->logger->error(__METHOD__ . '(): called with no path.', array('app' => 'core')); + $this->logger->error(__METHOD__ . '(): called with no path.', ['app' => 'core']); return false; } else { $filePath = $this->filePath; @@ -225,10 +226,10 @@ class OC_Image implements \OCP\IImage { } $isWritable = is_writable(dirname($filePath)); if (!$isWritable) { - $this->logger->error(__METHOD__ . '(): Directory \'' . dirname($filePath) . '\' is not writable.', array('app' => 'core')); + $this->logger->error(__METHOD__ . '(): Directory \'' . dirname($filePath) . '\' is not writable.', ['app' => 'core']); return false; } elseif ($isWritable && file_exists($filePath) && !is_writable($filePath)) { - $this->logger->error(__METHOD__ . '(): File \'' . $filePath . '\' is not writable.', array('app' => 'core')); + $this->logger->error(__METHOD__ . '(): File \'' . $filePath . '\' is not writable.', ['app' => 'core']); return false; } } @@ -360,11 +361,11 @@ class OC_Image implements \OCP\IImage { break; default: $res = imagepng($this->resource); - $this->logger->info('OC_Image->data. Could not guess mime-type, defaulting to png', array('app' => 'core')); + $this->logger->info('OC_Image->data. Could not guess mime-type, defaulting to png', ['app' => 'core']); break; } if (!$res) { - $this->logger->error('OC_Image->data. Error getting image data.', array('app' => 'core')); + $this->logger->error('OC_Image->data. Error getting image data.', ['app' => 'core']); } return ob_get_clean(); } @@ -399,19 +400,19 @@ class OC_Image implements \OCP\IImage { } if ($this->imageType !== IMAGETYPE_JPEG) { - $this->logger->debug('OC_Image->fixOrientation() Image is not a JPEG.', array('app' => 'core')); + $this->logger->debug('OC_Image->fixOrientation() Image is not a JPEG.', ['app' => 'core']); return -1; } if (!is_callable('exif_read_data')) { - $this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', array('app' => 'core')); + $this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', ['app' => 'core']); return -1; } if (!$this->valid()) { - $this->logger->debug('OC_Image->fixOrientation() No image loaded.', array('app' => 'core')); + $this->logger->debug('OC_Image->fixOrientation() No image loaded.', ['app' => 'core']); return -1; } if (is_null($this->filePath) || !is_readable($this->filePath)) { - $this->logger->debug('OC_Image->fixOrientation() No readable file path set.', array('app' => 'core')); + $this->logger->debug('OC_Image->fixOrientation() No readable file path set.', ['app' => 'core']); return -1; } $exif = @exif_read_data($this->filePath, 'IFD0'); @@ -427,11 +428,11 @@ class OC_Image implements \OCP\IImage { public function readExif($data) { if (!is_callable('exif_read_data')) { - $this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', array('app' => 'core')); + $this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', ['app' => 'core']); return; } if (!$this->valid()) { - $this->logger->debug('OC_Image->fixOrientation() No image loaded.', array('app' => 'core')); + $this->logger->debug('OC_Image->fixOrientation() No image loaded.', ['app' => 'core']); return; } @@ -453,7 +454,7 @@ class OC_Image implements \OCP\IImage { */ public function fixOrientation() { $o = $this->getOrientation(); - $this->logger->debug('OC_Image->fixOrientation() Orientation: ' . $o, array('app' => 'core')); + $this->logger->debug('OC_Image->fixOrientation() Orientation: ' . $o, ['app' => 'core']); $rotate = 0; $flip = false; switch ($o) { @@ -500,15 +501,15 @@ class OC_Image implements \OCP\IImage { $this->resource = $res; return true; } else { - $this->logger->debug('OC_Image->fixOrientation() Error during alpha-saving', array('app' => 'core')); + $this->logger->debug('OC_Image->fixOrientation() Error during alpha-saving', ['app' => 'core']); return false; } } else { - $this->logger->debug('OC_Image->fixOrientation() Error during alpha-blending', array('app' => 'core')); + $this->logger->debug('OC_Image->fixOrientation() Error during alpha-blending', ['app' => 'core']); return false; } } else { - $this->logger->debug('OC_Image->fixOrientation() Error during orientation fixing', array('app' => 'core')); + $this->logger->debug('OC_Image->fixOrientation() Error during orientation fixing', ['app' => 'core']); return false; } } @@ -550,7 +551,7 @@ class OC_Image implements \OCP\IImage { imagealphablending($this->resource, true); imagesavealpha($this->resource, true); } else { - $this->logger->debug('OC_Image->loadFromFile, GIF images not supported: ' . $imagePath, array('app' => 'core')); + $this->logger->debug('OC_Image->loadFromFile, GIF images not supported: ' . $imagePath, ['app' => 'core']); } break; case IMAGETYPE_JPEG: @@ -558,10 +559,10 @@ class OC_Image implements \OCP\IImage { if (getimagesize($imagePath) !== false) { $this->resource = @imagecreatefromjpeg($imagePath); } else { - $this->logger->debug('OC_Image->loadFromFile, JPG image not valid: ' . $imagePath, array('app' => 'core')); + $this->logger->debug('OC_Image->loadFromFile, JPG image not valid: ' . $imagePath, ['app' => 'core']); } } else { - $this->logger->debug('OC_Image->loadFromFile, JPG images not supported: ' . $imagePath, array('app' => 'core')); + $this->logger->debug('OC_Image->loadFromFile, JPG images not supported: ' . $imagePath, ['app' => 'core']); } break; case IMAGETYPE_PNG: @@ -571,21 +572,21 @@ class OC_Image implements \OCP\IImage { imagealphablending($this->resource, true); imagesavealpha($this->resource, true); } else { - $this->logger->debug('OC_Image->loadFromFile, PNG images not supported: ' . $imagePath, array('app' => 'core')); + $this->logger->debug('OC_Image->loadFromFile, PNG images not supported: ' . $imagePath, ['app' => 'core']); } break; case IMAGETYPE_XBM: if (imagetypes() & IMG_XPM) { $this->resource = @imagecreatefromxbm($imagePath); } else { - $this->logger->debug('OC_Image->loadFromFile, XBM/XPM images not supported: ' . $imagePath, array('app' => 'core')); + $this->logger->debug('OC_Image->loadFromFile, XBM/XPM images not supported: ' . $imagePath, ['app' => 'core']); } break; case IMAGETYPE_WBMP: if (imagetypes() & IMG_WBMP) { $this->resource = @imagecreatefromwbmp($imagePath); } else { - $this->logger->debug('OC_Image->loadFromFile, WBMP images not supported: ' . $imagePath, array('app' => 'core')); + $this->logger->debug('OC_Image->loadFromFile, WBMP images not supported: ' . $imagePath, ['app' => 'core']); } break; case IMAGETYPE_BMP: @@ -620,7 +621,7 @@ class OC_Image implements \OCP\IImage { // this is mostly file created from encrypted file $this->resource = imagecreatefromstring(\OC\Files\Filesystem::file_get_contents(\OC\Files\Filesystem::getLocalPath($imagePath))); $iType = IMAGETYPE_PNG; - $this->logger->debug('OC_Image->loadFromFile, Default', array('app' => 'core')); + $this->logger->debug('OC_Image->loadFromFile, Default', ['app' => 'core']); break; } if ($this->valid()) { @@ -651,7 +652,7 @@ class OC_Image implements \OCP\IImage { } if (!$this->resource) { - $this->logger->debug('OC_Image->loadFromFile, could not load', array('app' => 'core')); + $this->logger->debug('OC_Image->loadFromFile, could not load', ['app' => 'core']); return false; } return $this->resource; @@ -674,7 +675,7 @@ class OC_Image implements \OCP\IImage { $this->mimeType = $this->fileInfo->buffer($data); } if (!$this->resource) { - $this->logger->debug('OC_Image->loadFromBase64, could not load', array('app' => 'core')); + $this->logger->debug('OC_Image->loadFromBase64, could not load', ['app' => 'core']); return false; } return $this->resource; @@ -695,7 +696,7 @@ class OC_Image implements \OCP\IImage { */ private function imagecreatefrombmp($fileName) { if (!($fh = fopen($fileName, 'rb'))) { - $this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName, array('app' => 'core')); + $this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName, ['app' => 'core']); return false; } // read file header @@ -703,7 +704,7 @@ class OC_Image implements \OCP\IImage { // check for bitmap if ($meta['type'] != 19778) { fclose($fh); - $this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName . ' is not a bitmap!', array('app' => 'core')); + $this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName . ' is not a bitmap!', ['app' => 'core']); return false; } // read image header @@ -727,7 +728,7 @@ class OC_Image implements \OCP\IImage { $meta['imagesize'] = @filesize($fileName) - $meta['offset']; if ($meta['imagesize'] < 1) { fclose($fh); - $this->logger->warning('imagecreatefrombmp: Can not obtain file size of ' . $fileName . ' is not a bitmap!', array('app' => 'core')); + $this->logger->warning('imagecreatefrombmp: Can not obtain file size of ' . $fileName . ' is not a bitmap!', ['app' => 'core']); return false; } } @@ -735,7 +736,7 @@ class OC_Image implements \OCP\IImage { // calculate colors $meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors']; // read color palette - $palette = array(); + $palette = []; if ($meta['bits'] < 16) { $palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4)); // in rare cases the color value is signed @@ -751,7 +752,7 @@ class OC_Image implements \OCP\IImage { fclose($fh); $this->logger->warning( 'imagecreatefrombmp: imagecreatetruecolor failed for file "' . $fileName . '" with dimensions ' . $meta['width'] . 'x' . $meta['height'], - array('app' => 'core')); + ['app' => 'core']); return false; } @@ -768,7 +769,7 @@ class OC_Image implements \OCP\IImage { case 32: case 24: if (!($part = substr($data, $p, 3))) { - $this->logger->warning($error, array('app' => 'core')); + $this->logger->warning($error, ['app' => 'core']); return $im; } $color = @unpack('V', $part . $vide); @@ -776,7 +777,7 @@ class OC_Image implements \OCP\IImage { case 16: if (!($part = substr($data, $p, 2))) { fclose($fh); - $this->logger->warning($error, array('app' => 'core')); + $this->logger->warning($error, ['app' => 'core']); return $im; } $color = @unpack('v', $part); @@ -823,7 +824,7 @@ class OC_Image implements \OCP\IImage { break; default: fclose($fh); - $this->logger->warning('imagecreatefrombmp: ' . $fileName . ' has ' . $meta['bits'] . ' bits and this is not supported!', array('app' => 'core')); + $this->logger->warning('imagecreatefrombmp: ' . $fileName . ' has ' . $meta['bits'] . ' bits and this is not supported!', ['app' => 'core']); return false; } imagesetpixel($im, $x, $y, $color[1]); @@ -845,7 +846,7 @@ class OC_Image implements \OCP\IImage { */ public function resize($maxSize) { if (!$this->valid()) { - $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core')); + $this->logger->error(__METHOD__ . '(): No image loaded', ['app' => 'core']); return false; } $widthOrig = imagesx($this->resource); @@ -871,14 +872,14 @@ class OC_Image implements \OCP\IImage { */ public function preciseResize(int $width, int $height): bool { if (!$this->valid()) { - $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core')); + $this->logger->error(__METHOD__ . '(): No image loaded', ['app' => 'core']); return false; } $widthOrig = imagesx($this->resource); $heightOrig = imagesy($this->resource); $process = imagecreatetruecolor($width, $height); if ($process === false) { - $this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core')); + $this->logger->error(__METHOD__ . '(): Error creating true color image', ['app' => 'core']); return false; } @@ -891,7 +892,7 @@ class OC_Image implements \OCP\IImage { $res = imagecopyresampled($process, $this->resource, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig); if ($res === false) { - $this->logger->error(__METHOD__ . '(): Error re-sampling process image', array('app' => 'core')); + $this->logger->error(__METHOD__ . '(): Error re-sampling process image', ['app' => 'core']); imagedestroy($process); return false; } @@ -908,7 +909,7 @@ class OC_Image implements \OCP\IImage { */ public function centerCrop($size = 0) { if (!$this->valid()) { - $this->logger->error('OC_Image->centerCrop, No image loaded', array('app' => 'core')); + $this->logger->error('OC_Image->centerCrop, No image loaded', ['app' => 'core']); return false; } $widthOrig = imagesx($this->resource); @@ -935,7 +936,7 @@ class OC_Image implements \OCP\IImage { } $process = imagecreatetruecolor($targetWidth, $targetHeight); if ($process == false) { - $this->logger->error('OC_Image->centerCrop, Error creating true color image', array('app' => 'core')); + $this->logger->error('OC_Image->centerCrop, Error creating true color image', ['app' => 'core']); imagedestroy($process); return false; } @@ -949,7 +950,7 @@ class OC_Image implements \OCP\IImage { imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $targetWidth, $targetHeight, $width, $height); if ($process == false) { - $this->logger->error('OC_Image->centerCrop, Error re-sampling process image ' . $width . 'x' . $height, array('app' => 'core')); + $this->logger->error('OC_Image->centerCrop, Error re-sampling process image ' . $width . 'x' . $height, ['app' => 'core']); imagedestroy($process); return false; } @@ -969,12 +970,12 @@ class OC_Image implements \OCP\IImage { */ public function crop(int $x, int $y, int $w, int $h): bool { if (!$this->valid()) { - $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core')); + $this->logger->error(__METHOD__ . '(): No image loaded', ['app' => 'core']); return false; } $process = imagecreatetruecolor($w, $h); if ($process == false) { - $this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core')); + $this->logger->error(__METHOD__ . '(): Error creating true color image', ['app' => 'core']); imagedestroy($process); return false; } @@ -988,7 +989,7 @@ class OC_Image implements \OCP\IImage { imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h); if ($process == false) { - $this->logger->error(__METHOD__ . '(): Error re-sampling process image ' . $w . 'x' . $h, array('app' => 'core')); + $this->logger->error(__METHOD__ . '(): Error re-sampling process image ' . $w . 'x' . $h, ['app' => 'core']); imagedestroy($process); return false; } @@ -1008,7 +1009,7 @@ class OC_Image implements \OCP\IImage { */ public function fitIn($maxWidth, $maxHeight) { if (!$this->valid()) { - $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core')); + $this->logger->error(__METHOD__ . '(): No image loaded', ['app' => 'core']); return false; } $widthOrig = imagesx($this->resource); @@ -1031,7 +1032,7 @@ class OC_Image implements \OCP\IImage { */ public function scaleDownToFit($maxWidth, $maxHeight) { if (!$this->valid()) { - $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core')); + $this->logger->error(__METHOD__ . '(): No image loaded', ['app' => 'core']); return false; } $widthOrig = imagesx($this->resource); @@ -1075,7 +1076,7 @@ if (!function_exists('imagebmp')) { * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. */ function imagebmp($im, $fileName = '', $bit = 24, $compression = 0) { - if (!in_array($bit, array(1, 4, 8, 16, 24, 32))) { + if (!in_array($bit, [1, 4, 8, 16, 24, 32])) { $bit = 24; } else if ($bit == 32) { $bit = 24; diff --git a/lib/private/legacy/json.php b/lib/private/legacy/json.php index 29d0029a3a0..f83fca0a433 100644 --- a/lib/private/legacy/json.php +++ b/lib/private/legacy/json.php @@ -44,7 +44,7 @@ class OC_JSON{ public static function checkAppEnabled($app) { if( !\OC::$server->getAppManager()->isEnabledForUser($app)) { $l = \OC::$server->getL10N('lib'); - self::error(array( 'data' => array( 'message' => $l->t('Application is not enabled'), 'error' => 'application_not_enabled' ))); + self::error([ 'data' => [ 'message' => $l->t('Application is not enabled'), 'error' => 'application_not_enabled' ]]); exit(); } } @@ -60,7 +60,7 @@ class OC_JSON{ || $twoFactorAuthManger->needsSecondFactor(\OC::$server->getUserSession()->getUser())) { $l = \OC::$server->getL10N('lib'); http_response_code(\OCP\AppFramework\Http::STATUS_UNAUTHORIZED); - self::error(array( 'data' => array( 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' ))); + self::error([ 'data' => [ 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' ]]); exit(); } } @@ -78,7 +78,7 @@ class OC_JSON{ if( !\OC::$server->getRequest()->passesCSRFCheck()) { $l = \OC::$server->getL10N('lib'); - self::error(array( 'data' => array( 'message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired' ))); + self::error([ 'data' => [ 'message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired' ]]); exit(); } } @@ -91,7 +91,7 @@ class OC_JSON{ public static function checkAdminUser() { if( !OC_User::isAdminUser(OC_User::getUser())) { $l = \OC::$server->getL10N('lib'); - self::error(array( 'data' => array( 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' ))); + self::error([ 'data' => [ 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' ]]); exit(); } } @@ -101,7 +101,7 @@ class OC_JSON{ * @deprecated Use a AppFramework JSONResponse instead * @suppress PhanDeprecatedFunction */ - public static function error($data = array()) { + public static function error($data = []) { $data['status'] = 'error'; header( 'Content-Type: application/json; charset=utf-8'); echo self::encode($data); @@ -112,7 +112,7 @@ class OC_JSON{ * @deprecated Use a AppFramework JSONResponse instead * @suppress PhanDeprecatedFunction */ - public static function success($data = array()) { + public static function success($data = []) { $data['status'] = 'success'; header( 'Content-Type: application/json; charset=utf-8'); echo self::encode($data); @@ -133,7 +133,7 @@ class OC_JSON{ */ public static function encode($data) { if (is_array($data)) { - array_walk_recursive($data, array('OC_JSON', 'to_string')); + array_walk_recursive($data, ['OC_JSON', 'to_string']); } return json_encode($data, JSON_HEX_TAG); } diff --git a/lib/private/legacy/template.php b/lib/private/legacy/template.php index ed1e5627961..279ceb8de0f 100644 --- a/lib/private/legacy/template.php +++ b/lib/private/legacy/template.php @@ -54,7 +54,7 @@ class OC_Template extends \OC\Template\Base { private $path; // The path to the template /** @var array */ - private $headers = array(); //custom headers + private $headers = []; //custom headers /** @var string */ protected $app; // app id @@ -154,7 +154,7 @@ class OC_Template extends \OC\Template\Base { $locator = new \OC\Template\TemplateFileLocator( $dirs ); $template = $locator->find($name); $path = $locator->getPath(); - return array($path, $template); + return [$path, $template]; } /** @@ -165,11 +165,11 @@ class OC_Template extends \OC\Template\Base { * element will be written as empty element. So use "" to get a closing tag. */ public function addHeader($tag, $attributes, $text=null) { - $this->headers[]= array( + $this->headers[]= [ 'tag' => $tag, 'attributes' => $attributes, 'text' => $text - ); + ]; } /** @@ -238,7 +238,7 @@ class OC_Template extends \OC\Template\Base { * @param array $parameters Parameters for the template * @return boolean|null */ - public static function printUserPage( $application, $name, $parameters = array() ) { + public static function printUserPage( $application, $name, $parameters = [] ) { $content = new OC_Template( $application, $name, "user" ); foreach( $parameters as $key => $value ) { $content->assign( $key, $value ); @@ -253,7 +253,7 @@ class OC_Template extends \OC\Template\Base { * @param array $parameters Parameters for the template * @return bool */ - public static function printAdminPage( $application, $name, $parameters = array() ) { + public static function printAdminPage( $application, $name, $parameters = [] ) { $content = new OC_Template( $application, $name, "admin" ); foreach( $parameters as $key => $value ) { $content->assign( $key, $value ); @@ -268,7 +268,7 @@ class OC_Template extends \OC\Template\Base { * @param array|string $parameters Parameters for the template * @return bool */ - public static function printGuestPage( $application, $name, $parameters = array() ) { + public static function printGuestPage( $application, $name, $parameters = [] ) { $content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest'); foreach( $parameters as $key => $value ) { $content->assign( $key, $value ); @@ -297,7 +297,7 @@ class OC_Template extends \OC\Template\Base { http_response_code($statusCode); try { $content = new \OC_Template( '', 'error', 'error', false ); - $errors = array(array('error' => $error_msg, 'hint' => $hint)); + $errors = [['error' => $error_msg, 'hint' => $hint]]; $content->assign( 'errors', $errors ); $content->printPage(); } catch (\Exception $e) { diff --git a/lib/private/legacy/template/functions.php b/lib/private/legacy/template/functions.php index d931e4d129f..f2f737baf9a 100644 --- a/lib/private/legacy/template/functions.php +++ b/lib/private/legacy/template/functions.php @@ -4,6 +4,7 @@ * * @author Bart Visscher <bartv@thisnet.nl> * @author Bernhard Posselt <dev@bernhard-posselt.com> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Julius Härtl <jus@bitgrid.net> @@ -196,11 +197,11 @@ function component($app, $file) { if(is_array($file)) { foreach($file as $f) { $url = link_to($app, 'component/' . $f . '.html'); - OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url)); + OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]); } } else { $url = link_to($app, 'component/' . $file . '.html'); - OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url)); + OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]); } } @@ -213,7 +214,7 @@ function component($app, $file) { * * For further information have a look at \OCP\IURLGenerator::linkTo */ -function link_to( $app, $file, $args = array() ) { +function link_to( $app, $file, $args = [] ) { return \OC::$server->getURLGenerator()->linkTo($app, $file, $args); } @@ -305,9 +306,9 @@ function relative_modified_date($timestamp, $fromTime = null, $dateOnly = false) return $formatter->formatTimeSpan($timestamp, $fromTime); } -function html_select_options($options, $selected, $params=array()) { +function html_select_options($options, $selected, $params=[]) { if (!is_array($selected)) { - $selected=array($selected); + $selected=[$selected]; } if (isset($params['combine']) && $params['combine']) { $options = array_combine($options, $options); diff --git a/lib/private/legacy/user.php b/lib/private/legacy/user.php index 6a887063525..d96400ad1d4 100644 --- a/lib/private/legacy/user.php +++ b/lib/private/legacy/user.php @@ -6,7 +6,6 @@ * @author Andreas Fischer <bantu@owncloud.com> * @author Arthur Schiwon <blizzz@arthur-schiwon.de> * @author Bartek Przybylski <bart.p.pl@gmail.com> - * @author Bjoern Schiessle <bjoern@schiessle.org> * @author Björn Schießle <bjoern@schiessle.org> * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author Georg Ehrke <oc.list@georgehrke.com> @@ -59,9 +58,9 @@ use OCP\ILogger; */ class OC_User { - private static $_usedBackends = array(); + private static $_usedBackends = []; - private static $_setupedBackends = array(); + private static $_setupedBackends = []; // bool, stores if a user want to access a resource anonymously, e.g if they open a public link private static $incognitoMode = false; @@ -113,7 +112,7 @@ class OC_User { * remove all used backends */ public static function clearBackends() { - self::$_usedBackends = array(); + self::$_usedBackends = []; \OC::$server->getUserManager()->clearBackends(); } @@ -165,7 +164,7 @@ class OC_User { $uid = $backend->getCurrentUserId(); $run = true; - OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid, 'backend' => $backend)); + OC_Hook::emit("OC_User", "pre_login", ["run" => &$run, "uid" => $uid, 'backend' => $backend]); if ($uid) { if (self::getUser() !== $uid) { @@ -385,7 +384,7 @@ class OC_User { * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead. */ public static function getDisplayNames($search = '', $limit = null, $offset = null) { - $displayNames = array(); + $displayNames = []; $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset); foreach ($users as $user) { $displayNames[$user->getUID()] = $user->getDisplayName(); diff --git a/lib/private/legacy/util.php b/lib/private/legacy/util.php index bf0a1b9bb20..f14095675dc 100644 --- a/lib/private/legacy/util.php +++ b/lib/private/legacy/util.php @@ -69,9 +69,9 @@ use OCP\ILogger; use OCP\IUser; class OC_Util { - public static $scripts = array(); - public static $styles = array(); - public static $headers = array(); + public static $scripts = []; + public static $styles = []; + public static $headers = []; private static $rootMounted = false; private static $fsSetup = false; @@ -88,7 +88,7 @@ class OC_Util { //first set up the local "root" storage \OC\Files\Filesystem::initMountManager(); if (!self::$rootMounted) { - \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/'); + \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', ['datadir' => $configDataDirectory], '/'); self::$rootMounted = true; } } @@ -107,7 +107,7 @@ class OC_Util { \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR); } if (!isset($config['arguments'])) { - $config['arguments'] = array(); + $config['arguments'] = []; } // instantiate object store implementation @@ -141,7 +141,7 @@ class OC_Util { \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR); } if (!isset($config['arguments'])) { - $config['arguments'] = array(); + $config['arguments'] = []; } // instantiate object store implementation @@ -194,7 +194,7 @@ class OC_Util { } // load all filesystem apps before, so no setup-hook gets lost - OC_App::loadApps(array('filesystem')); + OC_App::loadApps(['filesystem']); // the filesystem will finish when $user is not empty, // mark fs setup here to avoid doing the setup from loading @@ -251,10 +251,9 @@ class OC_Util { ) { /** @var \OC\Files\Storage\Home $storage */ if (is_object($storage->getUser())) { - $user = $storage->getUser()->getUID(); - $quota = OC_Util::getUserQuota($user); + $quota = OC_Util::getUserQuota($storage->getUser()); if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) { - return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files')); + return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']); } } } @@ -279,7 +278,7 @@ class OC_Util { return $storage; }); - OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user)); + OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]); \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging); @@ -309,7 +308,7 @@ class OC_Util { //jail the user into his "home" directory \OC\Files\Filesystem::init($user, $userDir); - OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir)); + OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]); } \OC::$server->getEventLogger()->end('setup_fs'); return true; @@ -375,11 +374,10 @@ class OC_Util { /** * Get the quota of a user * - * @param string $userId + * @param IUser|null $user * @return float Quota bytes */ - public static function getUserQuota($userId) { - $user = \OC::$server->getUserManager()->get($userId); + public static function getUserQuota(?IUser $user) { if (is_null($user)) { return \OCP\Files\FileInfo::SPACE_UNLIMITED; } @@ -695,11 +693,11 @@ class OC_Util { * @param bool $prepend prepend the header to the beginning of the list */ public static function addHeader($tag, $attributes, $text = null, $prepend = false) { - $header = array( + $header = [ 'tag' => $tag, 'attributes' => $attributes, 'text' => $text - ); + ]; if ($prepend === true) { array_unshift (self::$headers, $header); @@ -716,7 +714,7 @@ class OC_Util { */ public static function checkServer(\OC\SystemConfig $config) { $l = \OC::$server->getL10N('lib'); - $errors = array(); + $errors = []; $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data'); if (!self::needUpgrade($config) && $config->getValue('installed', false)) { @@ -744,23 +742,23 @@ class OC_Util { $availableDatabases = $setup->getSupportedDatabases(); if (empty($availableDatabases)) { - $errors[] = array( + $errors[] = [ 'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'), 'hint' => '' //TODO: sane hint - ); + ]; $webServerRestart = true; } // Check if config folder is writable. if(!OC_Helper::isReadOnlyConfigEnabled()) { if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) { - $errors[] = array( + $errors[] = [ 'error' => $l->t('Cannot write into "config" directory'), 'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. ' . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s', [ $urlGenerator->linkToDocs('admin-config') ] ) - ); + ]; } } @@ -770,12 +768,11 @@ class OC_Util { || !is_writable(OC_App::getInstallPath()) || !is_readable(OC_App::getInstallPath()) ) { - $errors[] = array( + $errors[] = [ 'error' => $l->t('Cannot write into "apps" directory'), 'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory' - . ' or disabling the appstore in the config file. See %s', - [$urlGenerator->linkToDocs('admin-dir_permissions')]) - ); + . ' or disabling the appstore in the config file.') + ]; } } // Create root dir. @@ -795,7 +792,7 @@ class OC_Util { // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists. $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_')); $handle = fopen($testFile, 'w'); - if (!$handle || fwrite($handle, 'Test write operation') === FALSE) { + if (!$handle || fwrite($handle, 'Test write operation') === false) { $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.', [$urlGenerator->linkToDocs('admin-dir_permissions')]); $errors[] = [ @@ -812,12 +809,12 @@ class OC_Util { } if (!OC_Util::isSetLocaleWorking()) { - $errors[] = array( + $errors[] = [ 'error' => $l->t('Setting locale to %s failed', - array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/' - . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')), + ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/' + . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']), 'hint' => $l->t('Please install one of these locales on your system and restart your webserver.') - ); + ]; } // Contains the dependencies that should be checked against @@ -828,13 +825,13 @@ class OC_Util { // If the dependency is not found the missing module name is shown to the EndUser // When adding new checks always verify that they pass on Travis as well // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini - $dependencies = array( - 'classes' => array( + $dependencies = [ + 'classes' => [ 'ZipArchive' => 'zip', 'DOMDocument' => 'dom', 'XMLWriter' => 'XMLWriter', 'XMLReader' => 'XMLReader', - ), + ], 'functions' => [ 'xml_parser_create' => 'libxml', 'mb_strcut' => 'mbstring', @@ -848,14 +845,14 @@ class OC_Util { 'curl_init' => 'cURL', 'openssl_verify' => 'OpenSSL', ], - 'defined' => array( + 'defined' => [ 'PDO::ATTR_DRIVER_NAME' => 'PDO' - ), + ], 'ini' => [ 'default_charset' => 'UTF-8', ], - ); - $missingDependencies = array(); + ]; + $missingDependencies = []; $invalidIniSettings = []; $moduleHint = $l->t('Please ask your server administrator to install the module.'); @@ -894,10 +891,10 @@ class OC_Util { } foreach($missingDependencies as $missingDependency) { - $errors[] = array( - 'error' => $l->t('PHP module %s not installed.', array($missingDependency)), + $errors[] = [ + 'error' => $l->t('PHP module %s not installed.', [$missingDependency]), 'hint' => $moduleHint - ); + ]; $webServerRestart = true; } foreach($invalidIniSettings as $setting) { @@ -921,10 +918,10 @@ class OC_Util { */ if($iniWrapper->getBool('mbstring.func_overload') !== null && $iniWrapper->getBool('mbstring.func_overload') === true) { - $errors[] = array( + $errors[] = [ 'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]), 'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini') - ); + ]; } if(function_exists('xml_parser_create') && @@ -935,24 +932,24 @@ class OC_Util { $minor = floor($version/100); $version -= ($minor * 100); $patch = $version; - $errors[] = array( + $errors[] = [ 'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]), 'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.') - ); + ]; } if (!self::isAnnotationsWorking()) { - $errors[] = array( + $errors[] = [ 'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'), 'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.') - ); + ]; } if (!\OC::$CLI && $webServerRestart) { - $errors[] = array( + $errors[] = [ 'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'), 'hint' => $l->t('Please ask your server administrator to restart the web server.') - ); + ]; } $errors = array_merge($errors, self::checkDatabaseVersion()); @@ -970,7 +967,7 @@ class OC_Util { */ public static function checkDatabaseVersion() { $l = \OC::$server->getL10N('lib'); - $errors = array(); + $errors = []; $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite'); if ($dbType === 'pgsql') { // check PostgreSQL version @@ -980,10 +977,10 @@ class OC_Util { if (isset($data['server_version'])) { $version = $data['server_version']; if (version_compare($version, '9.0.0', '<')) { - $errors[] = array( + $errors[] = [ 'error' => $l->t('PostgreSQL >= 9 required'), 'hint' => $l->t('Please upgrade your database version') - ); + ]; } } } catch (\Doctrine\DBAL\DBALException $e) { |