diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..c7f81110f --- /dev/null +++ b/.editorconfig @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: AGPL-3.0-or-later + +[*] +charset = utf-8 +indent_style = tab +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[{package.json,webpack.config.js}] +indent_style = space +indent_size = 2 diff --git a/appinfo/routes.php b/appinfo/routes.php index b0e56b99f..d59500c69 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -88,7 +88,7 @@ ['name' => 'Icon#getLocalIconList', 'url' => '/api/v2/icon/list', 'verb' => 'GET'], // - ['name' => 'Vault#preflighted_cors', 'url' => '/api/v2/{path}', 'verb' => 'OPTIONS', 'requirements' => array('path' => '.+')], + ['name' => 'Vault#preflighted_cors', 'url' => '/api/v2/{path}', 'verb' => 'OPTIONS', 'requirements' => ['path' => '.+']], //Internal API ['name' => 'Internal#remind', 'url' => '/api/internal/notifications/remind/{credential_id}', 'verb' => 'POST'], ['name' => 'Internal#read', 'url' => '/api/internal/notifications/read/{credential_id}', 'verb' => 'DELETE'], diff --git a/composer.json b/composer.json index fe3f573dc..c86410a7e 100644 --- a/composer.json +++ b/composer.json @@ -6,5 +6,12 @@ "email": "brantje@gmail.com" } ], - "require": {} + "license": "AGPL-3.0-or-later", + "scripts": { + "rector:check": "rector --dry-run --clear-cache", + "rector:fix": "rector" + }, + "require-dev": { + "rector/rector": "^2.1" + } } diff --git a/lib/Activity.php b/lib/Activity.php index 73adae07b..c9c8c1ccf 100644 --- a/lib/Activity.php +++ b/lib/Activity.php @@ -227,18 +227,15 @@ public function getSpecialParameterList($app, $text) { * @param string $type * @return string|false */ - public function getTypeIcon($type) { - switch ($type) { - case self::TYPE_ITEM_ACTION: - case self::TYPE_ITEM_EXPIRED: - return 'icon-password'; - case self::TYPE_ITEM_SHARED: - return 'icon-share'; - case self::TYPE_ITEM_RENAMED: - return 'icon-rename'; - } - return false; - } + public function getTypeIcon($type) + { + return match ($type) { + self::TYPE_ITEM_ACTION, self::TYPE_ITEM_EXPIRED => 'icon-password', + self::TYPE_ITEM_SHARED => 'icon-share', + self::TYPE_ITEM_RENAMED => 'icon-rename', + default => false, + }; + } /** * The extension can define the parameter grouping by returning the index as integer. diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index ce0697dd3..df6cd4d7c 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -69,13 +69,9 @@ public function register(IRegistrationContext $context): void { $context->registerSearchProvider(Provider::class); - $context->registerService(View::class, function () { - return new View(''); - }, false); + $context->registerService(View::class, fn() => new View(''), false); - $context->registerService('isCLI', function () { - return \OC::$CLI; - }); + $context->registerService('isCLI', fn() => \OC::$CLI); $context->registerMiddleware(ShareMiddleware::class); $context->registerMiddleware(APIMiddleware::class); @@ -106,20 +102,16 @@ public function register(IRegistrationContext $context): void { }); - $context->registerService('CronService', function (ContainerInterface $c) { - return new CronService( + $context->registerService('CronService', fn(ContainerInterface $c) => new CronService( $c->get(CredentialService::class), $c->get(LoggerInterface::class), $c->get(Utils::class), $c->get(NotificationService::class), $c->get(ActivityService::class), $c->get(IDBConnection::class) - ); - }); + )); - $context->registerService('Logger', function (ContainerInterface $c) { - return $c->get(ServerContainer::class)->getLogger(); - }); + $context->registerService('Logger', fn(ContainerInterface $c) => $c->get(ServerContainer::class)->getLogger()); } public function boot(IBootContext $context): void { diff --git a/lib/BackgroundJob/ExpireCredentials.php b/lib/BackgroundJob/ExpireCredentials.php index a0b431445..89dbd633a 100644 --- a/lib/BackgroundJob/ExpireCredentials.php +++ b/lib/BackgroundJob/ExpireCredentials.php @@ -45,7 +45,7 @@ class ExpireCredentials extends TimedJob { public function __construct( ITimeFactory $timeFactory, protected IConfig $config, - private CronService $cronService, + private readonly CronService $cronService, ) { parent::__construct($timeFactory); diff --git a/lib/Controller/AdminController.php b/lib/Controller/AdminController.php index 6ea16b0db..7c8028479 100644 --- a/lib/Controller/AdminController.php +++ b/lib/Controller/AdminController.php @@ -28,19 +28,17 @@ class AdminController extends ApiController { - private $userId; - public function __construct( $AppName, IRequest $request, - $UserId, - private VaultService $vaultService, - private CredentialService $credentialService, - private FileService $fileService, - private CredentialRevisionService $revisionService, - private DeleteVaultRequestService $deleteVaultRequestService, - private IConfig $config, - private IUserManager $userManager, + private $userId, + private readonly VaultService $vaultService, + private readonly CredentialService $credentialService, + private readonly FileService $fileService, + private readonly CredentialRevisionService $revisionService, + private readonly DeleteVaultRequestService $deleteVaultRequestService, + private readonly IConfig $config, + private readonly IUserManager $userManager, ) { parent::__construct( $AppName, @@ -48,7 +46,6 @@ public function __construct( 'GET, POST, DELETE, PUT, PATCH, OPTIONS', 'Authorization, Content-Type, Accept', 86400); - $this->userId = $UserId; } @@ -121,7 +118,7 @@ public function acceptRequestDeletion($vault_guid, $requested_by){ $req = $this->deleteVaultRequestService->getDeleteRequestForVault($vault_guid); try{ $vault = $this->vaultService->getByGuid($vault_guid, $requested_by); - } catch (\Exception $e){ + } catch (\Exception){ //Ignore } @@ -175,7 +172,7 @@ public function deleteRequestDeletion($vault_guid) { $result = false; try { $delete_request = $this->deleteVaultRequestService->getDeleteRequestForVault($vault_guid); - } catch (\Exception $exception){ + } catch (\Exception){ // Ignore it } diff --git a/lib/Controller/CredentialController.php b/lib/Controller/CredentialController.php index 75f442e51..accffb568 100644 --- a/lib/Controller/CredentialController.php +++ b/lib/Controller/CredentialController.php @@ -28,17 +28,15 @@ class CredentialController extends ApiController { - private $userId; - public function __construct( $AppName, IRequest $request, - $userId, - private CredentialService $credentialService, - private ActivityService $activityService, - private CredentialRevisionService $credentialRevisionService, - private ShareService $sharingService, - private SettingsService $settings, + private $userId, + private readonly CredentialService $credentialService, + private readonly ActivityService $activityService, + private readonly CredentialRevisionService $credentialRevisionService, + private readonly ShareService $sharingService, + private readonly SettingsService $settings, ) { parent::__construct( $AppName, @@ -46,7 +44,6 @@ public function __construct( 'GET, POST, DELETE, PUT, PATCH, OPTIONS', 'Authorization, Content-Type, Accept', 86400); - $this->userId = $userId; } @@ -199,7 +196,7 @@ public function updateCredential($changed, $created, try { $acl_list = $this->sharingService->getCredentialAclList($storedCredential->getGuid()); - } catch (\Exception $exception) { + } catch (\Exception) { // Just check if we have an acl list } if (!empty($acl_list)) { @@ -264,7 +261,7 @@ public function updateCredential($changed, $created, public function deleteCredential($credential_guid) { try { $credential = $this->credentialService->getCredentialByGUID($credential_guid, $this->userId); - } catch (\Exception $e) { + } catch (\Exception) { return new NotFoundJSONResponse(); } if ($credential instanceof Credential) { @@ -285,7 +282,7 @@ public function deleteCredential($credential_guid) { public function getRevision($credential_guid) { try { $credential = $this->credentialService->getCredentialByGUID($credential_guid); - } catch (\Exception $ex) { + } catch (\Exception) { return new NotFoundJSONResponse(); } // If the request was made by the owner of the credential @@ -320,7 +317,7 @@ public function updateRevision($revision_id, $credential_data) { $revision = null; try { $revision = $this->credentialRevisionService->getRevision($revision_id); - } catch (\Exception $exception) { + } catch (\Exception) { return new JSONResponse([]); } diff --git a/lib/Controller/FileController.php b/lib/Controller/FileController.php index 8655fba01..38ad70eb3 100644 --- a/lib/Controller/FileController.php +++ b/lib/Controller/FileController.php @@ -18,14 +18,12 @@ use Psr\Log\LoggerInterface; class FileController extends ApiController { - private $userId; - public function __construct( $AppName, IRequest $request, - $UserId, - private FileService $fileService, - private LoggerInterface $logger, + private $userId, + private readonly FileService $fileService, + private readonly LoggerInterface $logger, ) { parent::__construct( $AppName, @@ -33,7 +31,6 @@ public function __construct( 'GET, POST, DELETE, PUT, PATCH, OPTIONS', 'Authorization, Content-Type, Accept', 86400); - $this->userId = $UserId; } @@ -72,9 +69,9 @@ public function deleteFile($file_id) { * @NoAdminRequired * @NoCSRFRequired */ - public function deleteFiles($file_ids) { + public function deleteFiles(string $file_ids) { $failed_file_ids = []; - if ($file_ids != null && !empty($file_ids)) { + if (!empty($file_ids)) { $decoded_file_ids = json_decode($file_ids); foreach ($decoded_file_ids as $file_id) { try { @@ -97,7 +94,7 @@ public function deleteFiles($file_ids) { public function updateFile($file_id, $file_data, $filename) { try { $file = $this->fileService->getFile($file_id, $this->userId); - } catch (\Exception $doesNotExistException) { + } catch (\Exception) { } if ($file) { diff --git a/lib/Controller/IconController.php b/lib/Controller/IconController.php index 0a9c23e5d..1fab0b34d 100644 --- a/lib/Controller/IconController.php +++ b/lib/Controller/IconController.php @@ -24,16 +24,15 @@ use OCP\IURLGenerator; class IconController extends ApiController { - private $userId; const ICON_CACHE_OFFSET = 2592000; // 3600 * 24 * 30 public function __construct( $AppName, IRequest $request, - $UserId, - private CredentialService $credentialService, - private AppManager $am, - private IURLGenerator $urlGenerator, + private $userId, + private readonly CredentialService $credentialService, + private readonly AppManager $am, + private readonly IURLGenerator $urlGenerator, ) { parent::__construct( $AppName, @@ -41,8 +40,6 @@ public function __construct( 'GET, POST, DELETE, PUT, PATCH, OPTIONS', 'Authorization, Content-Type, Accept', 86400); - $this->userId = $UserId; - } /** @@ -78,7 +75,7 @@ public function getIcon($base64Url, $credentialId) { try { $credential = $this->credentialService->getCredentialById($credentialId, $this->userId); $credential = $credential->jsonSerialize(); - } catch (DoesNotExistException $e) { + } catch (DoesNotExistException) { // Credential is not found, continue $credential = false; } @@ -97,14 +94,14 @@ public function getIcon($base64Url, $credentialId) { $data = $icon->icoData; $type = $icon->icoType; } - } catch (\InvalidArgumentException $e) { + } catch (\InvalidArgumentException) { //no need to do stuff in catch //if IconService fails the predefined $data and $type are used } if (isset($credential) && $credential['user_id'] == $this->userId) { $iconData = [ - 'type' => ($type) ? $type : 'x-icon', + 'type' => $type ?: 'x-icon', 'content' => base64_encode($data) ]; $credential['icon'] = json_encode($iconData); @@ -112,7 +109,7 @@ public function getIcon($base64Url, $credentialId) { if ($credential) { $this->credentialService->updateCredential($credential); } - } catch (DriverException $exception) { + } catch (DriverException) { /** * @FIXME Syntax error or access violation: 1118 Row size too large * This happens when favicons are quite big. @@ -146,7 +143,7 @@ public function getLocalIconList() { $icons = []; foreach ($result as $icon) { $iconPath = $icon; - $path = explode('passman/', $iconPath); + $path = explode('passman/', (string) $iconPath); $pack = explode('/', $path[1])[2]; $mime = mime_content_type($iconPath); if ($mime !== 'directory') { diff --git a/lib/Controller/InternalController.php b/lib/Controller/InternalController.php index 6a7614525..6e63209b1 100644 --- a/lib/Controller/InternalController.php +++ b/lib/Controller/InternalController.php @@ -21,16 +21,14 @@ use OCP\IRequest; class InternalController extends ApiController { - private $userId; - public function __construct( $AppName, IRequest $request, - $UserId, - private CredentialService $credentialService, - private NotificationService $notificationService, - private IConfig $config, - private IAppManager $appManager, + private $userId, + private readonly CredentialService $credentialService, + private readonly NotificationService $notificationService, + private readonly IConfig $config, + private readonly IAppManager $appManager, ) { parent::__construct( $AppName, @@ -38,7 +36,6 @@ public function __construct( 'GET, POST, DELETE, PUT, PATCH, OPTIONS', 'Authorization, Content-Type, Accept', 86400); - $this->userId = $UserId; } /** @@ -48,7 +45,7 @@ public function remind($credential_id) { $credential = $this->credentialService->getCredentialById($credential_id, $this->userId); if ($credential) { $credential->setExpireTime(time() + (24 * 60 * 60)); - $this->credentialService->upd($credential); + $this->credentialService->updateCredentialEntity($credential); $this->notificationService->markNotificationOfCredentialAsProcessed($credential_id, $this->userId); } @@ -72,7 +69,7 @@ public function read($credential_id) { $credential = $this->credentialService->getCredentialById($credential_id, $this->userId); if ($credential) { $credential->setExpireTime(0); - $this->credentialService->upd($credential); + $this->credentialService->updateCredentialEntity($credential); $this->notificationService->markNotificationOfCredentialAsProcessed($credential_id, $this->userId); } diff --git a/lib/Controller/SettingsController.php b/lib/Controller/SettingsController.php index 1c97b882e..ab5e21cba 100644 --- a/lib/Controller/SettingsController.php +++ b/lib/Controller/SettingsController.php @@ -24,8 +24,8 @@ public function __construct( $AppName, IRequest $request, private $userId, - private SettingsService $settings, - private IL10N $l, + private readonly SettingsService $settings, + private readonly IL10N $l, ) { parent::__construct( $AppName, diff --git a/lib/Controller/ShareController.php b/lib/Controller/ShareController.php index 91883249c..02eb203e5 100644 --- a/lib/Controller/ShareController.php +++ b/lib/Controller/ShareController.php @@ -35,25 +35,23 @@ class ShareController extends ApiController { - private $userId; - private $limit = 50; private $offset = 0; public function __construct( $AppName, IRequest $request, - $UserId, - private IGroupManager $groupManager, - private IUserManager $userManager, - private ActivityService $activityService, - private VaultService $vaultService, - private ShareService $shareService, - private CredentialService $credentialService, - private NotificationService $notificationService, - private FileService $fileService, - private SettingsService $settings, - private IManager $manager, + private $userId, + private readonly IGroupManager $groupManager, + private readonly IUserManager $userManager, + private readonly ActivityService $activityService, + private readonly VaultService $vaultService, + private readonly ShareService $shareService, + private readonly CredentialService $credentialService, + private readonly NotificationService $notificationService, + private readonly FileService $fileService, + private readonly SettingsService $settings, + private readonly IManager $manager, ) { parent::__construct( $AppName, @@ -61,8 +59,6 @@ public function __construct( 'GET, POST, DELETE, PUT, PATCH, OPTIONS', 'Authorization, Content-Type, Accept', 86400); - - $this->userId = $UserId; } @@ -77,13 +73,13 @@ public function __construct( public function createPublicShare($item_id, $item_guid, $permissions, $expire_timestamp, $expire_views) { try { $credential = $this->credentialService->getCredentialByGUID($item_guid); - } catch (\Exception $exception) { + } catch (\Exception) { return new NotFoundResponse(); } try { $acl = $this->shareService->getACL(null, $item_guid); - } catch (\Exception $exception) { + } catch (\Exception) { $acl = new SharingACL(); } @@ -125,14 +121,14 @@ public function applyIntermediateShare($item_id, $item_guid, $vaults, $permissio if (count($shareRequests) > 0) { return new JSONResponse(['error' => 'User got already pending requests']); } - } catch (\Exception $exception) { + } catch (\Exception) { // no need to catch this } $acl = null; try { $acl = $this->shareService->getCredentialAclForUser($first_vault['user_id'], $item_guid); - } catch (\Exception $exception) { + } catch (\Exception) { // no need to catch this } @@ -147,7 +143,7 @@ public function applyIntermediateShare($item_id, $item_guid, $vaults, $permissio if (!in_array($vault->getTargetUserId(), $processed_users)) { $target_user = $vault->getTargetUserId(); $notification = [ - 'from_user' => ucfirst($this->userId->getDisplayName()), + 'from_user' => ucfirst((string) $this->userId->getDisplayName()), 'credential_label' => $credential->getLabel(), 'credential_id' => $credential->getId(), 'item_id' => $credential->getId(), @@ -216,14 +212,14 @@ public function unshareCredentialFromUser($item_guid, $user_id) { $sr = null; try { $acl = $this->shareService->getCredentialAclForUser($user_id, $item_guid); - } catch (\Exception $e) { - + } catch (\Exception) { + // no need to handle this } try { $shareRequests = $this->shareService->getPendingShareRequestsForCredential($item_guid, $user_id); $sr = array_pop($shareRequests); - } catch (\Exception $e) { - // no need to catch this + } catch (\Exception) { + // no need to handle this } if ($sr) { @@ -275,7 +271,7 @@ public function getVaultsByUser($user_id) { public function savePendingRequest($item_guid, $target_vault_guid, $final_shared_key) { try { $sr = $this->shareService->getRequestByGuid($item_guid, $target_vault_guid); - } catch (\Exception $ex) { + } catch (\Exception) { return new NotFoundResponse(); } @@ -286,7 +282,7 @@ public function savePendingRequest($item_guid, $target_vault_guid, $final_shared $this->manager->markProcessed($notification); $notification = [ - 'from_user' => ucfirst($this->userId->getDisplayName()), + 'from_user' => ucfirst((string) $this->userId->getDisplayName()), 'credential_label' => $this->credentialService->getCredentialLabelById($sr->getItemId())->getLabel(), 'target_user' => $sr->getFromUserId(), 'req_id' => $sr->getId() @@ -315,7 +311,7 @@ public function getPendingRequests() { $results[] = $result; } return new JSONResponse($results); - } catch (\Exception $ex) { + } catch (\Exception) { return new NotFoundResponse(); } } @@ -329,7 +325,7 @@ public function getPendingRequests() { public function getRevisions($item_guid) { try { return new JSONResponse($this->shareService->getItemHistory($this->userId, $item_guid)); - } catch (\Exception $ex) { + } catch (\Exception) { return new NotFoundJSONResponse(); } } @@ -343,7 +339,7 @@ public function getRevisions($item_guid) { public function getVaultItems($vault_guid) { try { return new JSONResponse($this->shareService->getSharedItems($this->userId->getUID(), $vault_guid)); - } catch (\Exception $ex) { + } catch (\Exception) { return new NotFoundResponse(); } } @@ -357,7 +353,7 @@ public function getVaultItems($vault_guid) { public function getVaultAclEntries($vault_guid) { try { return new JSONResponse($this->shareService->getVaultAclList($this->userId->getUID(), $vault_guid)); - } catch (\Exception $ex) { + } catch (\Exception) { return new NotFoundResponse(); } } @@ -373,7 +369,7 @@ public function deleteShareRequest($share_request_id) { $sr = $this->shareService->getShareRequestById($share_request_id); $notification = [ - 'from_user' => ucfirst($this->userId->getDisplayName()), + 'from_user' => ucfirst((string) $this->userId->getDisplayName()), 'credential_label' => $this->credentialService->getCredentialLabelById($sr->getItemId())->getLabel(), 'target_user' => $sr->getFromUserId(), 'req_id' => $sr->getId() @@ -391,7 +387,7 @@ public function deleteShareRequest($share_request_id) { $this->shareService->cleanItemRequestsForUser($sr); return new JSONResponse(['result' => true]); - } catch (\Exception $ex) { + } catch (\Exception) { return new NotFoundJSONResponse(); } } @@ -424,7 +420,7 @@ public function getPublicCredentialData($credential_guid) { try { $credential = $this->shareService->getSharedItem(null, $credential_guid); return new JSONResponse($credential); - } catch (\Exception $ex) { + } catch (\Exception) { return new NotFoundJSONResponse(); } } @@ -450,7 +446,7 @@ public function getItemAcl($item_guid) { } else { return new NotFoundResponse(); } - } catch (\Exception $ex) { + } catch (\Exception) { return new JSONResponse([]); } } @@ -467,7 +463,7 @@ public function getItemAcl($item_guid) { public function getFile($item_guid, $file_guid) { try { $credential = $this->credentialService->getCredentialByGUID($item_guid); - } catch (\Exception $e) { + } catch (\Exception) { return new NotFoundJSONResponse(); } @@ -497,7 +493,7 @@ public function getFile($item_guid, $file_guid) { public function uploadFile($item_guid, $data, $filename, $mimetype, $size) { try { $credential = $this->credentialService->getCredentialByGUID($item_guid); - } catch (\Exception $e) { + } catch (\Exception) { return new NotFoundJSONResponse(); } @@ -532,7 +528,7 @@ public function uploadFile($item_guid, $data, $filename, $mimetype, $size) { public function updateSharedCredentialACL($item_guid, $user_id, $permission) { try { $credential = $this->credentialService->getCredentialByGUID($item_guid); - } catch (\Exception $exception) { + } catch (\Exception) { return new NotFoundJSONResponse(); } if ($this->userId->getUID() === $credential->getUserId()) { @@ -541,7 +537,7 @@ public function updateSharedCredentialACL($item_guid, $user_id, $permission) { $acl = $this->shareService->getACL($user_id, $item_guid); $acl->setPermissions($permission); return $this->shareService->updateCredentialACL($acl); - } catch (\Exception $exception) { + } catch (\Exception) { } diff --git a/lib/Controller/TranslationController.php b/lib/Controller/TranslationController.php index 40533bd46..10d35d401 100644 --- a/lib/Controller/TranslationController.php +++ b/lib/Controller/TranslationController.php @@ -21,7 +21,7 @@ class TranslationController extends ApiController { public function __construct( $AppName, IRequest $request, - private IL10N $trans, + private readonly IL10N $trans, ) { parent::__construct( $AppName, diff --git a/lib/Controller/VaultController.php b/lib/Controller/VaultController.php index f29e49149..23a9991b9 100644 --- a/lib/Controller/VaultController.php +++ b/lib/Controller/VaultController.php @@ -25,18 +25,16 @@ class VaultController extends ApiController { - private $userId; - public function __construct( $AppName, IRequest $request, - $UserId, - private VaultService $vaultService, - private CredentialService $credentialService, - private DeleteVaultRequestService $deleteVaultRequestService, - private SettingsService $settings, - private FileService $fileService, - private LoggerInterface $logger, + private $userId, + private readonly VaultService $vaultService, + private readonly CredentialService $credentialService, + private readonly DeleteVaultRequestService $deleteVaultRequestService, + private readonly SettingsService $settings, + private readonly FileService $fileService, + private readonly LoggerInterface $logger, ) { parent::__construct( $AppName, @@ -44,7 +42,6 @@ public function __construct( 'GET, POST, DELETE, PUT, PATCH, OPTIONS', 'Authorization, Content-Type, Accept', 86400); - $this->userId = $UserId; } /** @@ -95,7 +92,7 @@ public function get($vault_guid) { $vault = null; try { $vault = $this->vaultService->getByGuid($vault_guid, $this->userId); - } catch (\Exception $e) { + } catch (\Exception) { return new NotFoundJSONResponse(); } $result = []; @@ -146,8 +143,8 @@ public function updateSharingKeys($vault_guid, $private_sharing_key, $public_sha $vault = null; try { $vault = $this->vaultService->getByGuid($vault_guid, $this->userId); - } catch (\Exception $e) { - // No need to catch the execption + } catch (\Exception) { + // No need to catch the exception } if ($vault) { @@ -181,7 +178,7 @@ public function delete($vault_guid) { } } } - } catch (\Exception $e) { + } catch (\Exception) { return new NotFoundJSONResponse(); } diff --git a/lib/Db/CredentialMapper.php b/lib/Db/CredentialMapper.php index 257874195..43a9100fb 100644 --- a/lib/Db/CredentialMapper.php +++ b/lib/Db/CredentialMapper.php @@ -25,18 +25,21 @@ use OCA\Passman\Utility\Utils; use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\AppFramework\Db\QBMapper; +use OCP\DB\Exception; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + */ class CredentialMapper extends QBMapper { const TABLE_NAME = 'passman_credentials'; public function __construct( IDBConnection $db, - private Utils $utils, + private readonly Utils $utils, ) { parent::__construct($db, self::TABLE_NAME); } @@ -47,9 +50,9 @@ public function __construct( * * @param string $vault_id * @param string $user_id - * @return Entity[] + * @return Credential[] */ - public function getCredentialsByVaultId(string $vault_id, string $user_id) { + public function getCredentialsByVaultId(string $vault_id, string $user_id): array { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -64,9 +67,10 @@ public function getCredentialsByVaultId(string $vault_id, string $user_id) { * * @param string $vault_id * @param string $user_id - * @return Credential[] + * @return Credential + * @throws Exception */ - public function getRandomCredentialByVaultId(string $vault_id, string $user_id) { + public function getRandomCredentialByVaultId(string $vault_id, string $user_id): Credential { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -76,20 +80,18 @@ public function getRandomCredentialByVaultId(string $vault_id, string $user_id) ->setMaxResults(20); $entities = $this->findEntities($qb); - $count = count($entities) - 1; + $maxEntitiesIndex = count($entities) - 1; - /** @var Credential[] $entity */ - $entity = array_splice($entities, rand(0, $count), 1); - return $entity; + return $entities[rand(0, $maxEntitiesIndex)]; } /** * Get expired credentials * * @param int $timestamp - * @return Entity[] + * @return Credential[] */ - public function getExpiredCredentials(int $timestamp) { + public function getExpiredCredentials(int $timestamp): array { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -100,16 +102,16 @@ public function getExpiredCredentials(int $timestamp) { } /** - * Get an credential by id. + * Get a credential by id. * Optional user id * * @param int $credential_id * @param string|null $user_id - * @return Entity + * @return Credential * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getCredentialById(int $credential_id, string $user_id = null) { + public function getCredentialById(int $credential_id, ?string $user_id = null): Credential { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -126,11 +128,11 @@ public function getCredentialById(int $credential_id, string $user_id = null) { * Get credential label by id * * @param int $credential_id - * @return Entity + * @return Credential partial Credential, containing only 'id' and 'label' * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getCredentialLabelById(int $credential_id) { + public function getCredentialLabelById(int $credential_id): Credential { $qb = $this->db->getQueryBuilder(); $qb->select(['id', 'label']) ->from(self::TABLE_NAME) @@ -145,7 +147,7 @@ public function getCredentialLabelById(int $credential_id) { * @param $raw_credential * @return Credential */ - public function create($raw_credential) { + public function create($raw_credential): Credential { $credential = new Credential(); $credential->setGuid($this->utils->GUID()); @@ -176,13 +178,13 @@ public function create($raw_credential) { } /** - * @param $raw_credential array An array containing all the credential fields - * @param $useRawUser bool - * @return Credential|Entity The updated credential + * @param array $raw_credential An array containing all the credential fields + * @param bool $useRawUser + * @return Credential The updated credential * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function updateCredential($raw_credential, bool $useRawUser) { + public function updateCredential(array $raw_credential, bool $useRawUser): Credential { $original = $this->getCredentialByGUID($raw_credential['guid']); $uid = ($useRawUser) ? $raw_credential['user_id'] : $original->getUserId(); @@ -216,11 +218,11 @@ public function updateCredential($raw_credential, bool $useRawUser) { return parent::update($credential); } - public function deleteCredential(Credential $credential) { + public function deleteCredential(Credential $credential): Credential { return $this->delete($credential); } - public function upd(Credential $credential) { + public function upd(Credential $credential): void { $this->update($credential); } @@ -229,11 +231,11 @@ public function upd(Credential $credential) { * * @param string $credential_guid * @param string|null $user_id - * @return Entity + * @return Credential * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getCredentialByGUID(string $credential_guid, string $user_id = null) { + public function getCredentialByGUID(string $credential_guid, ?string $user_id = null): Credential { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) diff --git a/lib/Db/CredentialRevisionMapper.php b/lib/Db/CredentialRevisionMapper.php index 001e43742..4550e6eda 100644 --- a/lib/Db/CredentialRevisionMapper.php +++ b/lib/Db/CredentialRevisionMapper.php @@ -25,19 +25,19 @@ use OCA\Passman\Utility\Utils; use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\AppFramework\Db\QBMapper; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + */ class CredentialRevisionMapper extends QBMapper { const TABLE_NAME = 'passman_revisions'; - private Utils $utils; - public function __construct(IDBConnection $db, Utils $utils) { + public function __construct(IDBConnection $db, private readonly Utils $utils) { parent::__construct($db, self::TABLE_NAME); - $this->utils = $utils; } @@ -46,9 +46,9 @@ public function __construct(IDBConnection $db, Utils $utils) { * * @param int $credential_id * @param string|null $user_id - * @return Entity[] + * @return CredentialRevision[] */ - public function getRevisions(int $credential_id, string $user_id = null) { + public function getRevisions(int $credential_id, ?string $user_id = null): array { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -64,11 +64,11 @@ public function getRevisions(int $credential_id, string $user_id = null) { /** * @param int $revision_id * @param string|null $user_id - * @return Entity + * @return CredentialRevision * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getRevision(int $revision_id, string $user_id = null) { + public function getRevision(int $revision_id, ?string $user_id = null): CredentialRevision { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -83,13 +83,13 @@ public function getRevision(int $revision_id, string $user_id = null) { /** * Create a revision - * @param $credential - * @param $userId - * @param $credential_id - * @param $edited_by + * @param mixed $credential + * @param string $userId + * @param int $credential_id + * @param string $edited_by * @return CredentialRevision */ - public function create($credential, $userId, $credential_id, $edited_by) { + public function create(mixed $credential, string $userId, int $credential_id, string $edited_by): CredentialRevision { $revision = new CredentialRevision(); $revision->setGuid($this->utils->GUID()); $revision->setUserId($userId); @@ -103,11 +103,11 @@ public function create($credential, $userId, $credential_id, $edited_by) { /** * Delete a revision - * @param $revision_id - * @param $user_id + * @param int $revision_id + * @param string $user_id * @return CredentialRevision */ - public function deleteRevision($revision_id, $user_id) { + public function deleteRevision(int $revision_id, string $user_id): CredentialRevision { $revision = new CredentialRevision(); $revision->setId($revision_id); $revision->setUserId($user_id); diff --git a/lib/Db/DeleteVaultRequestMapper.php b/lib/Db/DeleteVaultRequestMapper.php index 585780d4e..b863e751a 100644 --- a/lib/Db/DeleteVaultRequestMapper.php +++ b/lib/Db/DeleteVaultRequestMapper.php @@ -25,12 +25,14 @@ use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\AppFramework\Db\QBMapper; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + */ class DeleteVaultRequestMapper extends QBMapper { const TABLE_NAME = 'passman_delete_vault_request'; @@ -41,17 +43,17 @@ public function __construct(IDBConnection $db) { /** * Create a new enty in the db * @param DeleteVaultRequest $request - * @return Entity + * @return DeleteVaultRequest */ - public function createRequest(DeleteVaultRequest $request) { + public function createRequest(DeleteVaultRequest $request): DeleteVaultRequest { return $this->insert($request); } /** * Get all delete requests - * @return Entity[] + * @return DeleteVaultRequest[] */ - public function getDeleteRequests() { + public function getDeleteRequests(): array { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME); @@ -62,11 +64,11 @@ public function getDeleteRequests() { /** * Get request for a vault guid * @param string $vault_guid - * @return Entity + * @return DeleteVaultRequest * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getDeleteRequestsForVault(string $vault_guid) { + public function getDeleteRequestsForVault(string $vault_guid): DeleteVaultRequest { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -80,8 +82,7 @@ public function getDeleteRequestsForVault(string $vault_guid) { * @param DeleteVaultRequest $request Request to delete * @return DeleteVaultRequest The deleted request */ - public function removeDeleteVaultRequest(DeleteVaultRequest $request) { + public function removeDeleteVaultRequest(DeleteVaultRequest $request): DeleteVaultRequest { return $this->delete($request); } - } diff --git a/lib/Db/FileMapper.php b/lib/Db/FileMapper.php index 6e33a3edc..c0ca1353e 100644 --- a/lib/Db/FileMapper.php +++ b/lib/Db/FileMapper.php @@ -26,18 +26,20 @@ use OCA\Passman\Utility\Utils; use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\AppFramework\Db\QBMapper; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + */ class FileMapper extends QBMapper { const TABLE_NAME = 'passman_files'; public function __construct( IDBConnection $db, - private Utils $utils, + private readonly Utils $utils, ) { parent::__construct($db, self::TABLE_NAME); } @@ -46,11 +48,11 @@ public function __construct( /** * @param int $file_id * @param string|null $user_id - * @return Entity + * @return File * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getFile(int $file_id, string $user_id = null) { + public function getFile(int $file_id, ?string $user_id = null): File { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -66,11 +68,11 @@ public function getFile(int $file_id, string $user_id = null) { /** * @param string $file_guid * @param string|null $user_id - * @return Entity + * @return File * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getFileByGuid(string $file_guid, string $user_id = null) { + public function getFileByGuid(string $file_guid, ?string $user_id = null): File { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -84,11 +86,11 @@ public function getFileByGuid(string $file_guid, string $user_id = null) { } /** - * @param $file_raw - * @param $userId + * @param array|File $file_raw + * @param string $userId * @return File */ - public function create($file_raw, $userId) { + public function create(array|File $file_raw, string $userId): File { $file = new File(); $file->setGuid($this->utils->GUID()); $file->setUserId($userId); @@ -106,9 +108,9 @@ public function create($file_raw, $userId) { * * @param int $file_id * @param string $userId - * @return File|Entity + * @return File */ - public function deleteFile(int $file_id, string $userId) { + public function deleteFile(int $file_id, string $userId): File { $file = new File(); $file->setId($file_id); $file->setUserId($userId); @@ -116,19 +118,19 @@ public function deleteFile(int $file_id, string $userId) { } /** - * Uodate file + * Update file * @param File $file * @return File */ - public function updateFile(File $file) { + public function updateFile(File $file): File { return $this->update($file); } /** * @param string $user_id - * @return Entity[] + * @return File[] array of incomplete File objects, containing only the guid */ - public function getFileGuidsFromUser(string $user_id) { + public function getFileGuidsFromUser(string $user_id): array { $qb = $this->db->getQueryBuilder(); $qb->select('guid') ->from(self::TABLE_NAME) diff --git a/lib/Db/ShareRequestMapper.php b/lib/Db/ShareRequestMapper.php index 3b12a3ba4..f6d088c30 100644 --- a/lib/Db/ShareRequestMapper.php +++ b/lib/Db/ShareRequestMapper.php @@ -25,14 +25,15 @@ use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\AppFramework\Db\QBMapper; use OCP\DB\Exception; -use OCP\DB\IResult; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + */ class ShareRequestMapper extends QBMapper { const TABLE_NAME = 'passman_share_request'; @@ -42,9 +43,9 @@ public function __construct(IDBConnection $db) { /** * @param ShareRequest $request - * @return ShareRequest|Entity + * @return ShareRequest */ - public function createRequest(ShareRequest $request) { + public function createRequest(ShareRequest $request): ShareRequest { return $this->insert($request); } @@ -53,11 +54,11 @@ public function createRequest(ShareRequest $request) { * * @param string $item_guid * @param string $target_vault_guid - * @return Entity + * @return ShareRequest * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getRequestByItemAndVaultGuid(string $item_guid, string $target_vault_guid) { + public function getRequestByItemAndVaultGuid(string $item_guid, string $target_vault_guid): ShareRequest { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -71,11 +72,11 @@ public function getRequestByItemAndVaultGuid(string $item_guid, string $target_v * Get shared items for the given item_guid * * @param string $item_guid - * @return Entity[] + * @return ShareRequest[] * @throws Exception */ - public function getRequestsByItemGuid(string $item_guid) { - if (strtolower($this->db->getDatabasePlatform()->getName()) === 'mysql') { + public function getRequestsByItemGuid(string $item_guid): array { + if ($this->db->getDatabaseProvider() === IDBConnection::PLATFORM_MYSQL) { $this->db->executeQuery("SET sql_mode = '';"); } $qb = $this->db->getQueryBuilder(); @@ -91,10 +92,10 @@ public function getRequestsByItemGuid(string $item_guid) { * * @param int $item_id * @param string $target_user_id - * @return int|IResult + * @return int * @throws Exception */ - public function cleanItemRequestsForUser(int $item_id, string $target_user_id) { + public function cleanItemRequestsForUser(int $item_id, string $target_user_id): int { $qb = $this->db->getQueryBuilder(); return $qb->delete(self::TABLE_NAME) ->where($qb->expr()->eq('item_id', $qb->createNamedParameter($item_id, IQueryBuilder::PARAM_INT))) @@ -106,9 +107,9 @@ public function cleanItemRequestsForUser(int $item_id, string $target_user_id) { * Obtains all pending share requests for the given user ID * * @param string $user_id - * @return Entity[] + * @return ShareRequest[] */ - public function getUserPendingRequests(string $user_id) { + public function getUserPendingRequests(string $user_id): array { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -122,19 +123,19 @@ public function getUserPendingRequests(string $user_id) { * @param ShareRequest $shareRequest Request to delete * @return ShareRequest The deleted request */ - public function deleteShareRequest(ShareRequest $shareRequest) { + public function deleteShareRequest(ShareRequest $shareRequest): ShareRequest { return $this->delete($shareRequest); } /** - * Gets a share request by it's unique incremental id + * Gets a share request by its unique incremental id * * @param int $id - * @return Entity + * @return ShareRequest * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getShareRequestById(int $id) { + public function getShareRequestById(int $id): ShareRequest { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -147,9 +148,9 @@ public function getShareRequestById(int $id) { * Gets all share requests by a given item GUID * * @param string $item_guid - * @return Entity[] + * @return ShareRequest[] */ - public function getShareRequestsByItemGuid(string $item_guid) { + public function getShareRequestsByItemGuid(string $item_guid): array { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -163,7 +164,7 @@ public function getShareRequestsByItemGuid(string $item_guid) { * @param ShareRequest $shareRequest * @return ShareRequest */ - public function updateShareRequest(ShareRequest $shareRequest) { + public function updateShareRequest(ShareRequest $shareRequest): ShareRequest { return $this->update($shareRequest); } @@ -172,9 +173,9 @@ public function updateShareRequest(ShareRequest $shareRequest) { * * @param string $item_guid * @param string $user_id - * @return Entity[] + * @return ShareRequest[] */ - public function getPendingShareRequests(string $item_guid, string $user_id) { + public function getPendingShareRequests(string $item_guid, string $user_id): array { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -190,10 +191,10 @@ public function getPendingShareRequests(string $item_guid, string $user_id) { * @param string $item_guid The item for which to update the requests * @param string $user_id The user for which to update the requests * @param int $permissions The new permissions to apply - * @return int|IResult + * @return int * @throws Exception */ - public function updatePendingRequestPermissions(string $item_guid, string $user_id, int $permissions) { + public function updatePendingRequestPermissions(string $item_guid, string $user_id, int $permissions): int { $qb = $this->db->getQueryBuilder(); return $qb->update(self::TABLE_NAME) ->set('permissions', $qb->createNamedParameter($permissions, IQueryBuilder::PARAM_INT)) diff --git a/lib/Db/SharingACLMapper.php b/lib/Db/SharingACLMapper.php index cf525efaf..28bcd8103 100644 --- a/lib/Db/SharingACLMapper.php +++ b/lib/Db/SharingACLMapper.php @@ -25,12 +25,14 @@ use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\AppFramework\Db\QBMapper; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + */ class SharingACLMapper extends QBMapper { const TABLE_NAME = 'passman_sharing_acl'; @@ -39,11 +41,11 @@ public function __construct(IDBConnection $db) { } /** - * @param SharingACL $acl - * @return SharingACL|Entity + * @param SharingACL $sharingACL + * @return SharingACL */ - public function createACLEntry(SharingACL $acl) { - return $this->insert($acl); + public function createACLEntry(SharingACL $sharingACL): SharingACL { + return $this->insert($sharingACL); } /** @@ -51,9 +53,9 @@ public function createACLEntry(SharingACL $acl) { * * @param string $user_id * @param string $vault_guid - * @return Entity[] + * @return SharingACL[] */ - public function getVaultEntries(string $user_id, string $vault_guid) { + public function getVaultEntries(string $user_id, string $vault_guid): array { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -66,13 +68,13 @@ public function getVaultEntries(string $user_id, string $vault_guid) { /** * Gets the acl for a given item guid * - * @param string $user_id + * @param string|null $user_id * @param string $item_guid - * @return Entity + * @return SharingACL * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getItemACL(?string $user_id, string $item_guid) { + public function getItemACL(?string $user_id, string $item_guid): SharingACL { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -91,9 +93,9 @@ public function getItemACL(?string $user_id, string $item_guid) { * Update an acl * * @param SharingACL $sharingACL - * @return SharingACL|Entity + * @return SharingACL */ - public function updateCredentialACL(SharingACL $sharingACL) { + public function updateCredentialACL(SharingACL $sharingACL): SharingACL { return $this->update($sharingACL); } @@ -101,9 +103,9 @@ public function updateCredentialACL(SharingACL $sharingACL) { * Gets the currently accepted share requests from the given user for the given vault guid * * @param string $item_guid - * @return Entity[] + * @return SharingACL[] */ - public function getCredentialAclList(string $item_guid) { + public function getCredentialAclList(string $item_guid): array { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -113,10 +115,10 @@ public function getCredentialAclList(string $item_guid) { } /** - * @param SharingACL $ACL - * @return SharingACL|Entity + * @param SharingACL $sharingACL + * @return SharingACL */ - public function deleteShareACL(SharingACL $ACL) { - return $this->delete($ACL); + public function deleteShareACL(SharingACL $sharingACL): SharingACL { + return $this->delete($sharingACL); } } diff --git a/lib/Db/VaultMapper.php b/lib/Db/VaultMapper.php index e35356d41..2f822dc3b 100644 --- a/lib/Db/VaultMapper.php +++ b/lib/Db/VaultMapper.php @@ -25,18 +25,20 @@ use OCA\Passman\Utility\Utils; use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\AppFramework\Db\QBMapper; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +/** + * @template-extends QBMapper + */ class VaultMapper extends QBMapper { const TABLE_NAME = 'passman_vaults'; public function __construct( IDBConnection $db, - private Utils $utils, + private readonly Utils $utils, ) { parent::__construct($db, self::TABLE_NAME); } @@ -45,26 +47,26 @@ public function __construct( /** * @param int $vault_id * @param string $user_id - * @return Entity[] + * @return Vault */ - public function find(int $vault_id, string $user_id) { + public function findById(int $vault_id, string $user_id): Vault { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) ->where($qb->expr()->eq('id', $qb->createNamedParameter($vault_id, IQueryBuilder::PARAM_INT))) ->andWhere($qb->expr()->eq('user_id', $qb->createNamedParameter($user_id, IQueryBuilder::PARAM_STR))); - return $this->findEntities($qb); + return $this->findEntity($qb); } /** * @param string $vault_guid * @param string $user_id - * @return Entity + * @return Vault * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function findByGuid(string $vault_guid, string $user_id) { + public function findByGuid(string $vault_guid, string $user_id): Vault { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -77,9 +79,9 @@ public function findByGuid(string $vault_guid, string $user_id) { /** * @param string $user_id - * @return Entity[] + * @return Vault[] */ - public function findVaultsFromUser(string $user_id) { + public function findVaultsFromUser(string $user_id): array { $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from(self::TABLE_NAME) @@ -93,9 +95,9 @@ public function findVaultsFromUser(string $user_id) { * * @param string $vault_name * @param string $user_id - * @return Vault|Entity + * @return Vault */ - public function create(string $vault_name, string $user_id) { + public function create(string $vault_name, string $user_id): Vault { $vault = new Vault(); $vault->setName($vault_name); $vault->setUserId($user_id); @@ -110,9 +112,9 @@ public function create(string $vault_name, string $user_id) { * * @param int $vault_id * @param string $user_id - * @return Vault|Entity + * @return Vault */ - public function setLastAccess(int $vault_id, string $user_id) { + public function setLastAccess(int $vault_id, string $user_id): Vault { $vault = new Vault(); $vault->setId($vault_id); $vault->setUserId($user_id); @@ -124,9 +126,9 @@ public function setLastAccess(int $vault_id, string $user_id) { * Update vault * * @param Vault $vault - * @return Vault|Entity + * @return Vault */ - public function updateVault(Vault $vault) { + public function updateVault(Vault $vault): Vault { return $this->update($vault); } @@ -136,9 +138,9 @@ public function updateVault(Vault $vault) { * @param int $vault_id * @param string $privateKey * @param string $publicKey - * @return Vault|Entity + * @return Vault */ - public function updateSharingKeys(int $vault_id, string $privateKey, string $publicKey) { + public function updateSharingKeys(int $vault_id, string $privateKey, string $publicKey): Vault { $vault = new Vault(); $vault->setId($vault_id); $vault->setPrivateSharingKey($privateKey); @@ -152,7 +154,7 @@ public function updateSharingKeys(int $vault_id, string $privateKey, string $pub * * @param Vault $vault */ - public function deleteVault(Vault $vault) { + public function deleteVault(Vault $vault): void { $this->delete($vault); } } diff --git a/lib/Middleware/APIMiddleware.php b/lib/Middleware/APIMiddleware.php index 92f3cc176..21c076df1 100644 --- a/lib/Middleware/APIMiddleware.php +++ b/lib/Middleware/APIMiddleware.php @@ -10,7 +10,7 @@ class APIMiddleware extends Middleware { public function __construct( - private IRequest $request, + private readonly IRequest $request, ) { } diff --git a/lib/Middleware/ShareMiddleware.php b/lib/Middleware/ShareMiddleware.php index 75aa138f0..699e83928 100644 --- a/lib/Middleware/ShareMiddleware.php +++ b/lib/Middleware/ShareMiddleware.php @@ -10,11 +10,9 @@ class ShareMiddleware extends Middleware { - private $settings; - - public function __construct(SettingsService $config) { - $this->settings = $config; - } + public function __construct(private readonly SettingsService $settings) + { + } public function beforeController($controller, $methodName) { diff --git a/lib/Migration/ServerSideEncryption.php b/lib/Migration/ServerSideEncryption.php index 3726ec3f8..414b01ad9 100644 --- a/lib/Migration/ServerSideEncryption.php +++ b/lib/Migration/ServerSideEncryption.php @@ -43,12 +43,12 @@ class ServerSideEncryption implements IRepairStep { private $installedVersion; public function __construct( - private EncryptService $encryptService, - private IDBConnection $db, - private LoggerInterface $logger, - private CredentialService $credentialService, - private CredentialRevisionService $revisionService, - private FileService $fileService, + private readonly EncryptService $encryptService, + private readonly IDBConnection $db, + private readonly LoggerInterface $logger, + private readonly CredentialService $credentialService, + private readonly CredentialRevisionService $revisionService, + private readonly FileService $fileService, IConfig $config, ) { $this->installedVersion = $config->getAppValue('passman', 'installed_version'); diff --git a/lib/Search/Provider.php b/lib/Search/Provider.php index cac452e32..8385fd05e 100644 --- a/lib/Search/Provider.php +++ b/lib/Search/Provider.php @@ -43,10 +43,10 @@ class Provider implements IProvider { public function __construct( - private IL10N $l10n, - private IURLGenerator $urlGenerator, - private IDBConnection $db, - private SettingsService $settings, + private readonly IL10N $l10n, + private readonly IURLGenerator $urlGenerator, + private readonly IDBConnection $db, + private readonly SettingsService $settings, ) { } @@ -60,7 +60,7 @@ public function getName(): string { } public function getOrder(string $route, array $routeParameters): int { - if (strpos($route, Application::APP_ID . '.') === 0) { + if (str_starts_with($route, Application::APP_ID . '.')) { // Active app, prefer my results return -1; } @@ -72,29 +72,28 @@ public function search(IUser $user, ISearchQuery $query): SearchResult { $searchResultEntries = []; if ($this->settings->getAppSetting('enable_global_search', 0) === 1) { - $VaultService = new VaultService(new VaultMapper($this->db, new Utils())); - $Vaults = $VaultService->getByUser($user->getUID()); - $CredentialMapper = new CredentialMapper($this->db, new Utils()); + $vaultService = new VaultService(new VaultMapper($this->db, new Utils())); + $vaults = $vaultService->getByUser($user->getUID()); + $credentialMapper = new CredentialMapper($this->db, new Utils()); - foreach ($Vaults as $Vault) { + foreach ($vaults as $vault) { try { - $Credentials = $CredentialMapper->getCredentialsByVaultId($Vault->getId(), $Vault->getUserId()); + $credentials = $credentialMapper->getCredentialsByVaultId($vault->getId(), $vault->getUserId()); - foreach ($Credentials as $Credential) { - if (strpos($Credential->getLabel(), $query->getTerm()) !== false) { + foreach ($credentials as $credential) { + if (str_contains($credential->getLabel(), $query->getTerm())) { try { $searchResultEntries[] = new SearchResultEntry( $this->urlGenerator->imagePath(Application::APP_ID, 'app.svg'), - $Credential->getLabel(), - \sprintf("Part of Passman vault %s", $Vault->getName()), - $this->urlGenerator->linkToRoute('passman.Page.index') . "#/vault/" . $Vault->getGuid() . "?show=" . $Credential->getGuid() + $credential->getLabel(), + \sprintf("Part of Passman vault %s", $vault->getName()), + $this->urlGenerator->linkToRoute('passman.Page.index') . "#/vault/" . $vault->getGuid() . "?show=" . $credential->getGuid() ); - } catch (\Exception $e) { + } catch (\Exception) { } } } - } catch (DoesNotExistException $e) { - } catch (MultipleObjectsReturnedException $e) { + } catch (DoesNotExistException|MultipleObjectsReturnedException) { } } } diff --git a/lib/Service/CredentialRevisionService.php b/lib/Service/CredentialRevisionService.php index 83072bb6e..45453f447 100644 --- a/lib/Service/CredentialRevisionService.php +++ b/lib/Service/CredentialRevisionService.php @@ -26,7 +26,6 @@ use OCA\Passman\Db\CredentialRevision; use OCA\Passman\Db\CredentialRevisionMapper; use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\IConfig; @@ -36,8 +35,8 @@ class CredentialRevisionService { private $server_key; public function __construct( - private CredentialRevisionMapper $credentialRevisionMapper, - private EncryptService $encryptService, + private readonly CredentialRevisionMapper $credentialRevisionMapper, + private readonly EncryptService $encryptService, IConfig $config, ) { $this->server_key = $config->getSystemValue('passwordsalt', ''); @@ -53,7 +52,7 @@ public function __construct( * @return CredentialRevision * @throws \Exception */ - public function createRevision($credential, $userId, $credential_id, $edited_by) { + public function createRevision($credential, $userId, $credential_id, $edited_by): CredentialRevision { $credential = $this->encryptService->encryptCredential($credential); return $this->credentialRevisionMapper->create($credential, $userId, $credential_id, $edited_by); } @@ -63,15 +62,17 @@ public function createRevision($credential, $userId, $credential_id, $edited_by) * * @param int $credential_id * @param string|null $user_id - * @return Entity[] + * @return CredentialRevision[] array with the json optimized ("serialized") versions of CredentialRevision * @throws \Exception */ - public function getRevisions(int $credential_id, string $user_id = null) { - $result = $this->credentialRevisionMapper->getRevisions($credential_id, $user_id); - foreach ($result as $index => $revision) { + public function getRevisions(int $credential_id, ?string $user_id = null): array { + $result = []; + $revisions = $this->credentialRevisionMapper->getRevisions($credential_id, $user_id); + foreach ($revisions as $revision) { $c = json_decode(base64_decode($revision->getCredentialData()), true); - $result[$index] = $revision->jsonSerialize(); - $result[$index]['credential_data'] = $this->encryptService->decryptCredential($c); + $serializedRevision = $revision->jsonSerialize(); + $serializedRevision['credential_data'] = $this->encryptService->decryptCredential($c); + $result[] = $serializedRevision; } return $result; } @@ -79,12 +80,12 @@ public function getRevisions(int $credential_id, string $user_id = null) { /** * @param int $credential_id * @param string|null $user_id - * @return Entity + * @return CredentialRevision * @throws DoesNotExistException * @throws MultipleObjectsReturnedException * @throws \Exception */ - public function getRevision(int $credential_id, string $user_id = null) { + public function getRevision(int $credential_id, ?string $user_id = null): CredentialRevision { $revision = $this->credentialRevisionMapper->getRevision($credential_id, $user_id); $c = json_decode(base64_decode($revision->getCredentialData()), true); $revision->setCredentialData($this->encryptService->decryptCredential($c)); @@ -98,7 +99,7 @@ public function getRevision(int $credential_id, string $user_id = null) { * @param string $user_id * @return CredentialRevision */ - public function deleteRevision(int $revision_id, string $user_id) { + public function deleteRevision(int $revision_id, string $user_id): CredentialRevision { return $this->credentialRevisionMapper->deleteRevision($revision_id, $user_id); } @@ -106,10 +107,10 @@ public function deleteRevision(int $revision_id, string $user_id) { * Update revision * * @param CredentialRevision $credentialRevision - * @return CredentialRevision|Entity + * @return CredentialRevision * @throws \Exception */ - public function updateRevision(CredentialRevision $credentialRevision) { + public function updateRevision(CredentialRevision $credentialRevision): CredentialRevision { $credential_data = $credentialRevision->getCredentialData(); $credential_data = json_decode(base64_decode($credential_data), true); $credential_data = base64_encode(json_encode($this->encryptService->encryptCredential($credential_data))); diff --git a/lib/Service/CredentialService.php b/lib/Service/CredentialService.php index fe66949e6..700048d7d 100644 --- a/lib/Service/CredentialService.php +++ b/lib/Service/CredentialService.php @@ -29,8 +29,8 @@ use OCA\Passman\Db\SharingACL; use OCA\Passman\Db\SharingACLMapper; use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\MultipleObjectsReturnedException; +use OCP\DB\Exception; use OCP\IConfig; use OCP\IURLGenerator; @@ -40,15 +40,15 @@ class CredentialService { private $server_key; public function __construct( - private CredentialMapper $credentialMapper, - private SharingACLMapper $sharingACL, - private ActivityService $activityService, - private ShareService $shareService, - private EncryptService $encryptService, - private CredentialRevisionService $credentialRevisionService, - private IURLGenerator $urlGenerator, - private VaultService $vaultService, - private NotificationService $notificationService, + private readonly CredentialMapper $credentialMapper, + private readonly SharingACLMapper $sharingACL, + private readonly ActivityService $activityService, + private readonly ShareService $shareService, + private readonly EncryptService $encryptService, + private readonly CredentialRevisionService $credentialRevisionService, + private readonly IURLGenerator $urlGenerator, + private readonly VaultService $vaultService, + private readonly NotificationService $notificationService, IConfig $config, ) { $this->server_key = $config->getSystemValue('passwordsalt', ''); @@ -61,7 +61,7 @@ public function __construct( * @return Credential * @throws \Exception */ - public function createCredential(array $credential) { + public function createCredential(array $credential): Credential { $credential = $this->encryptService->encryptCredential($credential); return $this->credentialMapper->create($credential); } @@ -70,25 +70,26 @@ public function createCredential(array $credential) { * Update credential * * @param array $credential - * @param false $useRawUser - * @return Credential|Entity + * @param bool $useRawUser + * @return Credential * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function updateCredential(array $credential, $useRawUser = false) { - $credential = $this->encryptService->encryptCredential($credential); - return $this->credentialMapper->updateCredential($credential, $useRawUser); + public function updateCredential(array $credential, bool $useRawUser = false): Credential { + $encryptedCredentialData = $this->encryptService->encryptCredential($credential); + return $this->credentialMapper->updateCredential((array) $encryptedCredentialData, $useRawUser); } /** - * Update credential + * Update credential based on its model/entity. + * Usually only for internal processing. * * @param Credential $credential - * @return Credential|Entity + * @return Credential * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function upd(Credential $credential) { + public function updateCredentialEntity(Credential $credential): Credential { $credential = $this->encryptService->encryptCredential($credential); return $this->credentialMapper->updateCredential($credential->jsonSerialize(), false); } @@ -97,19 +98,21 @@ public function upd(Credential $credential) { * Delete credential * * @param Credential $credential - * @return Entity + * @return Credential */ - public function deleteCredential(Credential $credential) { + public function deleteCredential(Credential $credential): Credential { $this->shareService->unshareCredential($credential->getGuid()); return $this->credentialMapper->deleteCredential($credential); } /** * Delete leftovers from a credential + * * @param Credential $credential + * @param string $userId * @throws \Exception */ - public function deleteCredentialParts(Credential $credential, $userId) { + public function deleteCredentialParts(Credential $credential, string $userId): void { $this->activityService->add( 'item_destroyed_self', [$credential->getLabel()], '', [], @@ -129,10 +132,10 @@ public function deleteCredentialParts(Credential $credential, $userId) { * * @param int $vault_id * @param string $user_id - * @return Entity[] + * @return Credential[] * @throws \Exception */ - public function getCredentialsByVaultId(int $vault_id, string $user_id) { + public function getCredentialsByVaultId(int $vault_id, string $user_id): array { $credentials = $this->credentialMapper->getCredentialsByVaultId($vault_id, $user_id); foreach ($credentials as $index => $credential) { $credentials[$index] = $this->encryptService->decryptCredential($credential); @@ -145,24 +148,22 @@ public function getCredentialsByVaultId(int $vault_id, string $user_id) { * * @param int $vault_id * @param string $user_id - * @return mixed + * @return Credential + * @throws Exception */ - public function getRandomCredentialByVaultId(int $vault_id, string $user_id) { - $credentials = $this->credentialMapper->getRandomCredentialByVaultId($vault_id, $user_id); - foreach ($credentials as $index => $credential) { - $credentials[$index] = $this->encryptService->decryptCredential($credential); - } - return array_pop($credentials); + public function getRandomCredentialByVaultId(int $vault_id, string $user_id): Credential { + $credential = $this->credentialMapper->getRandomCredentialByVaultId($vault_id, $user_id); + return $this->encryptService->decryptCredential($credential); } /** * Get expired credentials. * * @param int $timestamp - * @return Entity[] + * @return Credential[] * @throws \Exception */ - public function getExpiredCredentials(int $timestamp) { + public function getExpiredCredentials(int $timestamp): array { $credentials = $this->credentialMapper->getExpiredCredentials($timestamp); foreach ($credentials as $index => $credential) { $credentials[$index] = $this->encryptService->decryptCredential($credential); @@ -174,12 +175,12 @@ public function getExpiredCredentials(int $timestamp) { * Get a single credential. * * @param int $credential_id - * @param string $user_id - * @return array|Credential + * @param string|null $user_id + * @return Credential * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getCredentialById(int $credential_id, ?string $user_id) { + public function getCredentialById(int $credential_id, ?string $user_id): Credential { $credential = $this->credentialMapper->getCredentialById($credential_id); if ($credential->getUserId() === $user_id) { return $this->encryptService->decryptCredential($credential); @@ -209,13 +210,13 @@ public function credentialExistsById(int $credential_id): bool { * Get credential label by credential id. * * @param int $credential_id - * @return array|Credential + * @return Credential partial Credential, containing only 'id' and 'label' * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getCredentialLabelById(int $credential_id) { - $credential = $this->credentialMapper->getCredentialLabelById($credential_id); - return $this->encryptService->decryptCredential($credential); + public function getCredentialLabelById(int $credential_id): Credential { + $partialCredential = $this->credentialMapper->getCredentialLabelById($credential_id); + return $this->encryptService->decryptCredential($partialCredential); } /** @@ -223,21 +224,21 @@ public function getCredentialLabelById(int $credential_id) { * * @param string $credential_guid * @param string|null $user_id - * @return array|Credential + * @return Credential * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getCredentialByGUID(string $credential_guid, string $user_id = null) { + public function getCredentialByGUID(string $credential_guid, ?string $user_id = null): Credential { $credential = $this->credentialMapper->getCredentialByGUID($credential_guid, $user_id); return $this->encryptService->decryptCredential($credential); } public function getDirectEditLink(Credential $credential): string { - $vaults = $this->vaultService->getById($credential->getVaultId(), $credential->getUserId()); + $vault = $this->vaultService->getById($credential->getVaultId(), $credential->getUserId()); return $this->urlGenerator->getAbsoluteURL( $this->urlGenerator->linkTo( '', - 'index.php/apps/passman/#/vault/' . $vaults[0]->getGuid() . '/edit/' . $credential->getGuid() + 'index.php/apps/passman/#/vault/' . $vault->getGuid() . '/edit/' . $credential->getGuid() ) ); } diff --git a/lib/Service/CronService.php b/lib/Service/CronService.php index de39670df..c68b62642 100644 --- a/lib/Service/CronService.php +++ b/lib/Service/CronService.php @@ -32,11 +32,11 @@ class CronService { public function __construct( - private CredentialService $credentialService, - private LoggerInterface $logger, - private Utils $utils, - private NotificationService $notificationService, - private ActivityService $activityService, + private readonly CredentialService $credentialService, + private readonly LoggerInterface $logger, + private readonly Utils $utils, + private readonly NotificationService $notificationService, + private readonly ActivityService $activityService, ) { } diff --git a/lib/Service/DeleteVaultRequestService.php b/lib/Service/DeleteVaultRequestService.php index 2e98c6f06..0df2be102 100644 --- a/lib/Service/DeleteVaultRequestService.php +++ b/lib/Service/DeleteVaultRequestService.php @@ -25,55 +25,54 @@ use OCA\Passman\Db\DeleteVaultRequest; use OCA\Passman\Db\DeleteVaultRequestMapper; -use OCP\AppFramework\Db\Entity; class DeleteVaultRequestService { public function __construct( - private DeleteVaultRequestMapper $deleteVaultRequestMapper, + private readonly DeleteVaultRequestMapper $deleteVaultRequestMapper, ) { } /** - * Create a new DeleteVaultRequest + * Create a new DeleteVaultRequest * * @param $request DeleteVaultRequest * @return DeleteVaultRequest */ - public function createRequest(DeleteVaultRequest $request) { + public function createRequest(DeleteVaultRequest $request): DeleteVaultRequest { return $this->deleteVaultRequestMapper->insert($request); } /** - * Create a new DeleteVaultRequest + * Get all delete requests * - * @return Entity[] + * @return DeleteVaultRequest[] */ - public function getDeleteRequests() { + public function getDeleteRequests(): array { return $this->deleteVaultRequestMapper->getDeleteRequests(); } /** - * Create a new DeleteVaultRequest + * Get DeleteVaultRequest for a specific vault by its guid * * @param $vault_guid string The vault guid - * @return bool | Entity + * @return bool | DeleteVaultRequest */ - public function getDeleteRequestForVault(string $vault_guid) { + public function getDeleteRequestForVault(string $vault_guid): DeleteVaultRequest|bool { try { return $this->deleteVaultRequestMapper->getDeleteRequestsForVault($vault_guid); - } catch (\Exception $e) { + } catch (\Exception) { return false; } } /** - * Create a new DeleteVaultRequest + * Deletes the given DeleteVaultRequest * * @param $req DeleteVaultRequest */ - public function removeDeleteRequestForVault(DeleteVaultRequest $req) { + public function removeDeleteRequestForVault(DeleteVaultRequest $req): void { $this->deleteVaultRequestMapper->removeDeleteVaultRequest($req); } } diff --git a/lib/Service/EncryptService.php b/lib/Service/EncryptService.php index 82fb46328..3110c87e9 100644 --- a/lib/Service/EncryptService.php +++ b/lib/Service/EncryptService.php @@ -28,7 +28,6 @@ // Upgraded to use openssl use OCA\Passman\Db\Credential; use OCA\Passman\Db\File; -use OCP\AppFramework\Db\Entity; use OCP\IConfig; /** @@ -68,7 +67,16 @@ class EncryptService { // The fields of a credential which are encrypted public $encrypted_credential_fields = [ - 'description', 'username', 'password', 'files', 'custom_fields', 'otp', 'email', 'tags', 'url', 'icon' + 'description', + 'username', + 'password', + 'files', + 'custom_fields', + 'otp', + 'email', + 'tags', + 'url', + 'icon' ]; // Contains the server key @@ -124,16 +132,15 @@ public function getKeySize() { /** * Decrypt the data with the provided key * - * @param string $data_hex The encrypted datat to decrypt + * @param string|null $data_hex The encrypted data to decrypt. Accept null for dynamic caller compatibility, but always return false then. * @param string $key The key to use for decryption * * @returns string|false The returned string if decryption is successful * false if it is not */ - public function decrypt($data_hex, $key) { - + public function decrypt(?string $data_hex, string $key): bool|string { if (!function_exists('hex2bin')) { - function hex2bin($str) { + function hex2bin(string $str): string { $sbin = ""; $len = strlen($str); for ($i = 0; $i < $len; $i += 2) { @@ -143,6 +150,9 @@ function hex2bin($str) { return $sbin; } } + if ($data_hex === null) { + return false; + } $data = hex2bin($data_hex); @@ -150,13 +160,11 @@ function hex2bin($str) { $enc = substr($data, 128, -64); $mac = substr($data, -64); - list ($cipherKey, $macKey, $iv) = $this->getKeys($salt, $key); + [$cipherKey, $macKey, $iv] = $this->getKeys($salt, $key); - if (hash_equals(hash_hmac('sha512', $enc, $macKey, true), $mac)) { + if (hash_equals(hash_hmac('sha512', $enc, (string)$macKey, true), $mac)) { $dec = openssl_decrypt($enc, $this->cipher, $cipherKey, true, $iv); - $data = $this->unpad($dec); - - return $data; + return $this->unpad($dec); } return false; @@ -170,19 +178,17 @@ function hex2bin($str) { * * @returns string The encrypted data */ - public function encrypt($data, $key) { + public function encrypt(string $data, string $key): string { if (function_exists('random_bytes')) { $salt = random_bytes(128); } else { $salt = openssl_random_pseudo_bytes(128); } - list ($cipherKey, $macKey, $iv) = $this->getKeys($salt, $key); + [$cipherKey, $macKey, $iv] = $this->getKeys($salt, $key); $data = $this->pad($data); $enc = openssl_encrypt($data, $this->cipher, $cipherKey, true, $iv); - $mac = hash_hmac('sha512', $enc, $macKey, true); - $data = bin2hex($salt . $enc . $mac); - return $data; - + $mac = hash_hmac('sha512', $enc, (string)$macKey, true); + return bin2hex($salt . $enc . $mac); } /** @@ -193,7 +199,7 @@ public function encrypt($data, $key) { * * @returns array An array of keys (a cipher key, a mac key, and a IV) */ - protected function getKeys($salt, $key) { + protected function getKeys(string $salt, string $key): array { $ivSize = openssl_cipher_iv_length($this->cipher); $keySize = openssl_cipher_iv_length($this->cipher); $length = 2 * $keySize + $ivSize; @@ -219,7 +225,7 @@ protected function getKeys($salt, $key) { * * @returns string The derived key. */ - protected function pbkdf2($algo, $key, $salt, $rounds, $length) { + protected function pbkdf2(string $algo, string $key, string $salt, int $rounds, int $length): string { $size = strlen(hash($algo, '', true)); $len = ceil($length / $size); $result = ''; @@ -238,10 +244,10 @@ protected function pbkdf2($algo, $key, $salt, $rounds, $length) { /** * Pad the data with a random char chosen by the pad amount. * - * @param $data + * @param string $data * @return string */ - protected function pad($data) { + protected function pad(string $data): string { $length = $this->getKeySize(); $padAmount = $length - strlen($data) % $length; if ($padAmount === 0) { @@ -252,15 +258,20 @@ protected function pad($data) { /** - * Unpad the the data + * Unpad the data * - * @param $data + * @param false|string $data * @return bool|string */ - protected function unpad($data) { + protected function unpad(false|string $data): bool|string { + if ($data === false) { + return false; + } $length = $this->getKeySize(); $last = ord($data[strlen($data) - 1]); - if ($last > $length) return false; + if ($last > $length) { + return false; + } if (substr($data, -1 * $last) !== str_repeat(chr($last), $last)) { return false; } @@ -269,24 +280,24 @@ protected function unpad($data) { /** - * Encrypt a credential + * Decrypt a credential * - * @param Credential|Entity|array $credential the credential to decrypt - * @return Credential|array + * @param Credential|array $credential the credential to decrypt + * @return Credential|array modified $credential input object of the same type * @throws \Exception */ - public function decryptCredential($credential) { + public function decryptCredential(Credential|array $credential): Credential|array { return $this->handleCredential($credential, EncryptService::OP_DECRYPT); } /** * Encrypt a credential * - * @param Credential|array $credential the credential to encrypt - * @return Credential|array + * @param array|Credential $credential the credential to encrypt + * @return Credential|array modified $credential input object of the same type * @throws \Exception */ - public function encryptCredential($credential) { + public function encryptCredential(Credential|array $credential): Credential|array { return $this->handleCredential($credential, EncryptService::OP_ENCRYPT); } @@ -297,29 +308,30 @@ private function extractKeysFromCredential($credential) { if ($credential instanceof Credential) { $userSuppliedKey = $credential->getLabel(); $sk = $credential->getSharedKey(); - $userKey = (isset($sk)) ? $sk : $credential->getUserId(); + $userKey = $sk ?? $credential->getUserId(); } if (is_array($credential)) { $userSuppliedKey = $credential['label']; - $userKey = (isset($credential['shared_key'])) ? $credential['shared_key'] : $credential['user_id']; + $userKey = $credential['shared_key'] ?? $credential['user_id']; } return [$userKey, $userSuppliedKey]; } /** - * Handles the encryption / decryption of a credential + * Handles the encryption / decryption of a credential. + * This modifies the $credential parameter object, slightly different based on the passed parameter type. * * @param Credential|array $credential the credential to encrypt - * @return Credential|array + * @return Credential|array modified $credential input object of the same type * @throws \Exception */ - private function handleCredential($credential, $service_function) { - list($userKey, $userSuppliedKey) = $this->extractKeysFromCredential($credential); + private function handleCredential(Credential|array $credential, $service_function): Credential|array { + [$userKey, $userSuppliedKey] = $this->extractKeysFromCredential($credential); - $key = $this->makeKey($userKey, $this->server_key, $userSuppliedKey); + $key = static::makeKey($userKey, $this->server_key, $userSuppliedKey); foreach ($this->encrypted_credential_fields as $field) { if ($credential instanceof Credential) { - $field = str_replace(' ', '', str_replace('_', ' ', ucwords($field, '_'))); + $field = str_replace(' ', '', str_replace('_', ' ', ucwords((string)$field, '_'))); $set = 'set' . $field; $get = 'get' . $field; $credential->{$set}($this->{$service_function}($credential->{$get}(), $key)); @@ -335,33 +347,34 @@ private function handleCredential($credential, $service_function) { /** * Encrypt a file * - * @param File|array $file - * @return File|array + * @param array|File $file + * @return array|File modified $file input object of the same type * @throws \Exception */ - public function encryptFile($file) { + public function encryptFile(array|File $file): array|File { return $this->handleFile($file, EncryptService::OP_ENCRYPT); } /** * Decrypt a file * - * @param File|Entity|array $file - * @return array|File + * @param array|File $file + * @return array|File modified $file input object of the same type * @throws \Exception */ - public function decryptFile($file) { + public function decryptFile(array|File $file): array|File { return $this->handleFile($file, EncryptService::OP_DECRYPT); } /** - * Handles the encryption / decryption of a File + * Handles the encryption / decryption of a File. + * This modifies the $file parameter object, slightly different based on the passed parameter type. * - * @param File|array $file the credential to encrypt - * @return File|array + * @param array|File $file the file to encrypt/decrypt + * @return array|File modified $file input object of the same type * @throws \Exception */ - private function handleFile($file, $service_function) { + private function handleFile(array|File $file, $service_function): array|File { $userKey = ''; $userSuppliedKey = ''; if ($file instanceof File) { @@ -371,10 +384,10 @@ private function handleFile($file, $service_function) { if (is_array($file)) { $userSuppliedKey = $file['size']; - $userKey = md5($file['mimetype']); + $userKey = md5((string)$file['mimetype']); } - $key = $this->makeKey($userKey, $this->server_key, $userSuppliedKey); + $key = static::makeKey($userKey, $this->server_key, $userSuppliedKey); if ($file instanceof File) { diff --git a/lib/Service/FileService.php b/lib/Service/FileService.php index 5a8e4bb76..f522513e2 100644 --- a/lib/Service/FileService.php +++ b/lib/Service/FileService.php @@ -27,7 +27,6 @@ use OCA\Passman\Db\File; use OCA\Passman\Db\FileMapper; use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\IConfig; @@ -37,8 +36,8 @@ class FileService { private $server_key; public function __construct( - private FileMapper $fileMapper, - private EncryptService $encryptService, + private readonly FileMapper $fileMapper, + private readonly EncryptService $encryptService, IConfig $config, ) { $this->server_key = $config->getSystemValue('passwordsalt', ''); @@ -49,12 +48,12 @@ public function __construct( * * @param int $fileId * @param string|null $userId - * @return array|File + * @return File * @throws DoesNotExistException * @throws MultipleObjectsReturnedException * @throws Exception */ - public function getFile(int $fileId, string $userId = null) { + public function getFile(int $fileId, ?string $userId = null): File { $file = $this->fileMapper->getFile($fileId, $userId); return $this->encryptService->decryptFile($file); } @@ -64,30 +63,30 @@ public function getFile(int $fileId, string $userId = null) { * * @param string $file_guid * @param string|null $userId - * @return array|File + * @return File * @throws DoesNotExistException * @throws MultipleObjectsReturnedException * @throws Exception */ - public function getFileByGuid(string $file_guid, string $userId = null) { + public function getFileByGuid(string $file_guid, ?string $userId = null): File { $file = $this->fileMapper->getFileByGuid($file_guid, $userId); return $this->encryptService->decryptFile($file); } /** - * Upload a new file, + * Upload a new file * * @param array $file * @param string $userId - * @return array|File + * @return File * @throws DoesNotExistException * @throws MultipleObjectsReturnedException * @throws Exception */ - public function createFile(array $file, string $userId) { + public function createFile(array $file, string $userId): File { $file = $this->encryptService->encryptFile($file); - $file = $this->fileMapper->create($file, $userId); - return $this->getFile($file->getId()); + $fileEntity = $this->fileMapper->create($file, $userId); + return $this->getFile($fileEntity->getId()); } /** @@ -95,9 +94,9 @@ public function createFile(array $file, string $userId) { * * @param int $file_id * @param string $userId - * @return File|Entity + * @return File */ - public function deleteFile(int $file_id, string $userId) { + public function deleteFile(int $file_id, string $userId): File { return $this->fileMapper->deleteFile($file_id, $userId); } @@ -108,7 +107,7 @@ public function deleteFile(int $file_id, string $userId) { * @return File * @throws Exception */ - public function updateFile(File $file) { + public function updateFile(File $file): File { $file = $this->encryptService->encryptFile($file); return $this->fileMapper->updateFile($file); } @@ -120,11 +119,11 @@ public function updateFile(File $file) { * @return string[] * @throws Exception */ - public function getFileGuidsFromUser(string $userId) { - $files = $this->fileMapper->getFileGuidsFromUser($userId); + public function getFileGuidsFromUser(string $userId): array { + $partialFiles = $this->fileMapper->getFileGuidsFromUser($userId); $results = []; - foreach ($files as $fileGuid) { - $results[] = $fileGuid->getGuid(); + foreach ($partialFiles as $partialFile) { + $results[] = $partialFile->getGuid(); } return $results; } diff --git a/lib/Service/IconService.php b/lib/Service/IconService.php index 4867854bf..fcb92f6f2 100644 --- a/lib/Service/IconService.php +++ b/lib/Service/IconService.php @@ -35,84 +35,84 @@ class IconService { /** * @var string Page URL */ - public $url; + public string $url; /** * @var string Page URL, after prospective redirects */ - public $pageUrl; + public string $pageUrl; /** * @var string Site root URL (homepage), based on $pageUrl */ - public $siteUrl; + public string $siteUrl; /** * @var string full URI to favicon */ - public $icoUrl; + public string $icoUrl; /** * @var string favicon type (file extension, ex: ico|gif|png) */ - public $icoType; + public string $icoType; /** * @var string favicon url determination method (default /favicon.ico or found in head>link tag) */ - public $findMethod; + public string $findMethod; /** * @var string details, in case of failure */ - public $error; + public string $error; /** * @var bool tell if the favicon exists (set after calling IconService) */ - public $icoExists; + public bool $icoExists; /** * @var string md5 of $icoData */ - public $icoMd5; + public string $icoMd5; /** * @var string favicon binary data */ - public $icoData; + public string $icoData; /** * @var array Additional debug info */ - public $debugInfo; + public array $debugInfo; /** - * @var string HTTP proxy (ex: localhost:8888) + * @var string|null HTTP proxy (ex: localhost:8888) */ - protected $httpProxy; + protected mixed $httpProxy; /** * @var bool SSL verify peer (default: true) */ - protected $sslVerify; + protected bool $sslVerify; /** * Create a new IconService object, search & download favicon if $auto is true * * @param string $url Page URL - * @param array $options Optional settings + * @param array|null $options Optional settings * @param bool $auto Search & download favicon on instantiation */ - public function __construct($url, $options = null, $auto = true) { - if (!$url) { + public function __construct(string $url, ?array $options = null, bool $auto = true) { + if (empty($url)) { throw new \InvalidArgumentException("url is empty"); } if (self::urlType($url) != self::URL_TYPE_ABSOLUTE) { throw new \InvalidArgumentException("'" . $url . "' is not an absolute url"); } $this->url = $url; - $this->httpProxy = isset($options['httpProxy']) ? $options['httpProxy'] : null; + $this->httpProxy = $options['httpProxy'] ?? null; $this->sslVerify = isset($options['sslVerify']) && $options['sslVerify'] === false ? false : true; if ($auto) { $this->getFaviconUrl(); @@ -164,12 +164,12 @@ public function getFaviconUrl() { $this->findMethod = 'default'; // HTML tag extraction - preg_match('#^(.*)<\s*body#isU', $html, $matches); - $htmlHead = isset($matches[1]) ? $matches[1] : $html; + preg_match('#^(.*)<\s*body#isU', (string) $html, $matches); + $htmlHead = $matches[1] ?? $html; // HTML tag href extraction $base_href = null; - if (preg_match('#]+href=(["\'])([^>]+)\1#i', $htmlHead, $matches)) { + if (preg_match('#]+href=(["\'])([^>]+)\1#i', (string) $htmlHead, $matches)) { $base_href = rtrim($matches[2], '/') . '/'; $this->debugInfo['base_href'] = $base_href; } @@ -182,7 +182,7 @@ public function getFaviconUrl() { private function parseLinkElement($htmlHead, $pageUrlInfo, $base_href){ - if (preg_match('#<\s*link[^>]*(rel=(["\'])[^>\2]*icon[^>\2]*\2)[^>]*>#i', $htmlHead, $matches)) { + if (preg_match('#<\s*link[^>]*(rel=(["\'])[^>\2]*icon[^>\2]*\2)[^>]*>#i', (string) $htmlHead, $matches)) { $link_tag = $matches[0]; $this->debugInfo['link_tag'] = $link_tag; @@ -224,7 +224,7 @@ private function parseLinkElement($htmlHead, $pageUrlInfo, $base_href){ break; case self::URL_TYPE_RELATIVE: $this->findMethod .= ' relative'; - $path = preg_replace('#/[^/]+?$#i', '/', $pageUrlInfo['path']); + $path = preg_replace('#/[^/]+?$#i', '/', (string) $pageUrlInfo['path']); $this->icoUrl = $pageUrlInfo['scheme'] . '://' . $pageUrlInfo['host'] . $path . $ico_href; $this->findMethod .= ' without base href'; if (isset($base_href)) { @@ -297,19 +297,19 @@ public function downloadFavicon() { } // Check favicon content - if (strlen($content) == 0) { + if (strlen((string) $content) == 0) { $this->error = "Empty content"; return false; } $textTypes = ['text/html', 'text/plain']; - if (in_array($info['content_type'], $textTypes) || preg_match('#(|)#i', $content)) { + if (in_array($info['content_type'], $textTypes) || preg_match('#(|)#i', (string) $content)) { $this->error = "Seems to be a text document"; return false; } // All right baby ! $this->icoData = $content; - $this->icoMd5 = md5($content); + $this->icoMd5 = md5((string) $content); $this->icoExists = true; return true; } @@ -350,7 +350,7 @@ public function downloadAs($url, &$info = null) { $info['content_type'] = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); curl_close($ch); - if ($info['curl_errno'] !== CURLE_OK || in_array($info['http_code'], array(403, 404, 500, 503))) { + if ($info['curl_errno'] !== CURLE_OK || in_array($info['http_code'], [403, 404, 500, 503])) { return false; } return $content; @@ -400,9 +400,10 @@ public static function getExtensionFromMimeType($mimeType) { * - URL_TYPE_RELATIVE ex: ../images/fav.ico * - URL_TYPE_EMBED_BASE64 ex: data:image/x-icon;base64,AAABAA... * - * @return int + * @param string $url + * @return false|int */ - public static function urlType($url) { + public static function urlType(string $url): false|int { if (empty($url)) { return false; } diff --git a/lib/Service/NotificationService.php b/lib/Service/NotificationService.php index 03ba6e714..df07b9bd4 100644 --- a/lib/Service/NotificationService.php +++ b/lib/Service/NotificationService.php @@ -31,9 +31,9 @@ class NotificationService { public function __construct( - private IManager $manager, - private IURLGenerator $urlGenerator, - private IDBConnection $db, + private readonly IManager $manager, + private readonly IURLGenerator $urlGenerator, + private readonly IDBConnection $db, ) { } diff --git a/lib/Service/SettingsService.php b/lib/Service/SettingsService.php index fa20d20ca..f7da1f94a 100644 --- a/lib/Service/SettingsService.php +++ b/lib/Service/SettingsService.php @@ -28,8 +28,6 @@ class SettingsService { - private $userId; - private $appName; public $settings; private $numeric_settings = [ @@ -44,12 +42,10 @@ class SettingsService { ]; public function __construct( - $UserId, - private IConfig $config, - $AppName, + private $userId, + private readonly IConfig $config, + private $appName, ) { - $this->userId = $UserId; - $this->appName = $AppName; $this->settings = [ 'link_sharing_enabled' => intval($this->config->getAppValue('passman', 'link_sharing_enabled', 1)), 'user_sharing_enabled' => intval($this->config->getAppValue('passman', 'user_sharing_enabled', 1)), @@ -82,7 +78,7 @@ public function getAppSettings() { * @return mixed */ public function getAppSetting($key, $default_value = null) { - $value = ($this->settings[$key]) ? $this->settings[$key] : $this->config->getAppValue('passman', $key, $default_value); + $value = $this->settings[$key] ?: $this->config->getAppValue('passman', $key, $default_value); if (in_array($key, $this->numeric_settings)) { $value = intval($value); } diff --git a/lib/Service/ShareService.php b/lib/Service/ShareService.php index 4db20777d..299257ce7 100644 --- a/lib/Service/ShareService.php +++ b/lib/Service/ShareService.php @@ -25,26 +25,25 @@ use OCA\Passman\Db\CredentialMapper; +use OCA\Passman\Db\CredentialRevision; use OCA\Passman\Db\ShareRequest; use OCA\Passman\Db\ShareRequestMapper; use OCA\Passman\Db\SharingACL; use OCA\Passman\Db\SharingACLMapper; use OCA\Passman\Utility\Utils; use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\DB\Exception; -use OCP\DB\IResult; use OCP\Notification\IManager; class ShareService { public function __construct( - private SharingACLMapper $sharingACL, - private ShareRequestMapper $shareRequest, - private CredentialMapper $credential, - private CredentialRevisionService $revisions, - private EncryptService $encryptService, - private IManager $IManager, + private readonly SharingACLMapper $sharingACL, + private readonly ShareRequestMapper $shareRequest, + private readonly CredentialMapper $credential, + private readonly CredentialRevisionService $revisions, + private readonly EncryptService $encryptService, + private readonly IManager $IManager, ) { } @@ -83,10 +82,12 @@ public function createBulkRequests($target_item_id, $target_item_guid, $request_ /** * @param SharingACL $acl - * @return Entity + * @return SharingACL */ - public function createACLEntry(SharingACL $acl) { - if ($acl->getCreated() === null) $acl->setCreated((new \DateTime())->getTimestamp()); + public function createACLEntry(SharingACL $acl): SharingACL { + if ($acl->getCreated() === null) { + $acl->setCreated((new \DateTime())->getTimestamp()); + } return $this->sharingACL->createACLEntry($acl); } @@ -100,7 +101,7 @@ public function createACLEntry(SharingACL $acl) { * @throws Exception * @throws MultipleObjectsReturnedException */ - public function applyShare(string $item_guid, string $target_vault_guid, string $final_shared_key) { + public function applyShare(string $item_guid, string $target_vault_guid, string $final_shared_key): void { $request = $this->shareRequest->getRequestByItemAndVaultGuid($item_guid, $target_vault_guid); $permissions = $request->getPermissions(); @@ -123,9 +124,9 @@ public function applyShare(string $item_guid, string $target_vault_guid, string * Obtains pending requests for the given user ID * * @param string $user_id - * @return Entity[] + * @return SharingACL[] */ - public function getUserPendingRequests(string $user_id) { + public function getUserPendingRequests(string $user_id): array { return $this->shareRequest->getUserPendingRequests($user_id); } @@ -138,114 +139,126 @@ public function getUserPendingRequests(string $user_id) { * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getSharedItems(string $user_id, string $vault_guid) { - $entries = $this->sharingACL->getVaultEntries($user_id, $vault_guid); + public function getSharedItems(string $user_id, string $vault_guid): array { + $acceptedVaultShareRequests = $this->sharingACL->getVaultEntries($user_id, $vault_guid); $return = []; - foreach ($entries as $entry) { - // Check if the user can read the credential, probably unnecesary, but just to be sure - if (!$entry->hasPermission(SharingACL::READ)) continue; - $tmp = $entry->jsonSerialize(); - $credential = $this->credential->getCredentialById($entry->getItemId()); - $credential = $this->encryptService->decryptCredential($credential); - $tmp['credential_data'] = $credential->jsonSerialize(); - - if (!$entry->hasPermission(SharingACL::FILES)) unset($tmp['credential_data']['files']); - unset($tmp['credential_data']['shared_key']); - $return[] = $tmp; + foreach ($acceptedVaultShareRequests as $acceptedVaultShareRequest) { + $serializableVaultShareRequest = $this->prepareSharedItemForResponse($acceptedVaultShareRequest); + if (!empty($serializableVaultShareRequest)) { + $return[] = $serializableVaultShareRequest; + } } return $return; } /** - * Gets the acl for a given item guid + * Get shared credential (from a user) * - * @param string $user_id + * @param string|null $user_id * @param string $item_guid - * @return Entity + * @return array * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getACL(?string $user_id, string $item_guid) { - return $this->sharingACL->getItemACL($user_id, $item_guid); + public function getSharedItem(?string $user_id, string $item_guid): array { + $acl = $this->sharingACL->getItemACL($user_id, $item_guid); + + $serializableItemACL = $this->prepareSharedItemForResponse($acl); + if (empty($serializableItemACL)) { + throw new DoesNotExistException("Item not found or wrong access level"); + } + return $serializableItemACL; } /** - * @param string $user_id - * @param string $item_guid - * @return array|mixed - * @throws DoesNotExistException * @throws MultipleObjectsReturnedException + * @throws DoesNotExistException */ - public function getSharedItem(?string $user_id, string $item_guid) { - $acl = $this->sharingACL->getItemACL($user_id, $item_guid); - - // Check if the user can read the credential, probably unnecesary, but just to be sure - if (!$acl->hasPermission(SharingACL::READ)) throw new DoesNotExistException("Item not found or wrong access level"); + private function prepareSharedItemForResponse(SharingACL $sharingACL): array|null { + // Check if the user can read the credential, probably unnecessary, but just to be sure + if (!$sharingACL->hasPermission(SharingACL::READ)) { + return null; + } - $tmp = $acl->jsonSerialize(); - $credential = $this->credential->getCredentialById($acl->getItemId()); + $credential = $this->credential->getCredentialById($sharingACL->getItemId()); $credential = $this->encryptService->decryptCredential($credential); - $tmp['credential_data'] = $credential->jsonSerialize(); + $serializableSharingACL = $sharingACL->jsonSerialize(); + $serializableSharingACL['credential_data'] = $credential->jsonSerialize(); - if (!$acl->hasPermission(SharingACL::FILES)) unset($tmp['credential_data']['files']); - unset($tmp['credential_data']['shared_key']); + if (!$sharingACL->hasPermission(SharingACL::FILES)) { + unset($serializableSharingACL['credential_data']['files']); + } + unset($serializableSharingACL['credential_data']['shared_key']); + return $serializableSharingACL; + } - return $tmp; + /** + * Gets the acl for a given item guid + * + * @param string|null $user_id + * @param string $item_guid + * @return SharingACL + * @throws DoesNotExistException + * @throws MultipleObjectsReturnedException + */ + public function getACL(?string $user_id, string $item_guid): SharingACL { + return $this->sharingACL->getItemACL($user_id, $item_guid); } /** * Gets history from the given item checking the user's permissions to access it * - * @param string $user_id + * @param string|null $user_id * @param string $item_guid - * @return array|Entity[] + * @return array|CredentialRevision[] * @throws DoesNotExistException * @throws MultipleObjectsReturnedException - * @throws \Exception */ - public function getItemHistory(?string $user_id, string $item_guid) { + public function getItemHistory(?string $user_id, string $item_guid): array { $acl = $this->sharingACL->getItemACL($user_id, $item_guid); - if (!$acl->hasPermission(SharingACL::READ | SharingACL::HISTORY)) return []; + if (!$acl->hasPermission(SharingACL::READ | SharingACL::HISTORY)) { + return []; + } return $this->revisions->getRevisions($acl->getItemId()); } /** - * Deletes a share request by the item ID + * Deletes a share request by the item id * * @param ShareRequest $request - * @return int|IResult + * @return int * @throws Exception */ - public function cleanItemRequestsForUser(ShareRequest $request) { + public function cleanItemRequestsForUser(ShareRequest $request): int { return $this->shareRequest->cleanItemRequestsForUser($request->getItemId(), $request->getTargetUserId()); } /** - * Get an share request by id + * Get a share request by id * * @param int $id - * @return Entity + * @return ShareRequest * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getShareRequestById(int $id) { + public function getShareRequestById(int $id): ShareRequest { return $this->shareRequest->getShareRequestById($id); } /** - * Get an share request by $item_guid and $target_vault_guid + * Get a share request by $item_guid and $target_vault_guid * * @param string $item_guid * @param string $target_vault_guid - * @return Entity + * @return ShareRequest * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getRequestByGuid(string $item_guid, string $target_vault_guid) { + public function getRequestByGuid(string $item_guid, string $target_vault_guid): ShareRequest { return $this->shareRequest->getRequestByItemAndVaultGuid($item_guid, $target_vault_guid); } @@ -253,9 +266,9 @@ public function getRequestByGuid(string $item_guid, string $target_vault_guid) { * Get the access control list by item guid * * @param string $item_guid - * @return Entity[] + * @return SharingACL[] */ - public function getCredentialAclList(string $item_guid) { + public function getCredentialAclList(string $item_guid): array { return $this->sharingACL->getCredentialAclList($item_guid); } @@ -264,31 +277,31 @@ public function getCredentialAclList(string $item_guid) { * * @param string $user_id * @param string $vault_guid - * @return Entity[] + * @return SharingACL[] */ - public function getVaultAclList(string $user_id, string $vault_guid) { + public function getVaultAclList(string $user_id, string $vault_guid): array { return $this->sharingACL->getVaultEntries($user_id, $vault_guid); } /** * @param string $item_guid - * @return Entity[] + * @return ShareRequest[] * @throws Exception */ - public function getCredentialPendingAclList(string $item_guid) { + public function getCredentialPendingAclList(string $item_guid): array { return $this->shareRequest->getRequestsByItemGuid($item_guid); } /** * Gets the ACL on the credential for the user * - * @param string $user_id + * @param string|null $user_id * @param string $item_guid - * @return Entity + * @return SharingACL * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getCredentialAclForUser(?string $user_id, string $item_guid) { + public function getCredentialAclForUser(?string $user_id, string $item_guid): SharingACL { return $this->sharingACL->getItemACL($user_id, $item_guid); } @@ -296,9 +309,9 @@ public function getCredentialAclForUser(?string $user_id, string $item_guid) { * Get pending share requests by guid * * @param string $item_guid - * @return Entity[] + * @return ShareRequest[] */ - public function getShareRequestsByGuid(string $item_guid) { + public function getShareRequestsByGuid(string $item_guid): array { return $this->shareRequest->getShareRequestsByItemGuid($item_guid); } @@ -308,27 +321,27 @@ public function getShareRequestsByGuid(string $item_guid) { * @param ShareRequest $request * @return ShareRequest */ - public function deleteShareRequest(ShareRequest $request) { + public function deleteShareRequest(ShareRequest $request): ShareRequest { return $this->shareRequest->deleteShareRequest($request); } /** * Delete ACL * - * @param SharingACL|Entity $ACL - * @return SharingACL|Entity + * @param SharingACL $sharingACL + * @return SharingACL */ - public function deleteShareACL(SharingACL $ACL) { - return $this->sharingACL->deleteShareACL($ACL); + public function deleteShareACL(SharingACL $sharingACL): SharingACL { + return $this->sharingACL->deleteShareACL($sharingACL); } /** * Updates the given ACL entry * * @param SharingACL $sharingACL - * @return SharingACL|Entity + * @return SharingACL */ - public function updateCredentialACL(SharingACL $sharingACL) { + public function updateCredentialACL(SharingACL $sharingACL): SharingACL { return $this->sharingACL->updateCredentialACL($sharingACL); } @@ -336,7 +349,7 @@ public function updateCredentialACL(SharingACL $sharingACL) { * @param ShareRequest $shareRequest * @return ShareRequest */ - public function updateCredentialShareRequest(ShareRequest $shareRequest) { + public function updateCredentialShareRequest(ShareRequest $shareRequest): ShareRequest { return $this->shareRequest->updateShareRequest($shareRequest); } @@ -346,9 +359,9 @@ public function updateCredentialShareRequest(ShareRequest $shareRequest) { * * @param string $item_guid * @param string $user_id - * @return Entity[] + * @return ShareRequest[] */ - public function getPendingShareRequestsForCredential(string $item_guid, string $user_id) { + public function getPendingShareRequestsForCredential(string $item_guid, string $user_id): array { return $this->shareRequest->getPendingShareRequests($item_guid, $user_id); } @@ -356,10 +369,10 @@ public function getPendingShareRequestsForCredential(string $item_guid, string $ * @param string $item_guid * @param string $user_id * @param int $permissions - * @return int|IResult + * @return int * @throws Exception */ - public function updatePendingShareRequestsForCredential(string $item_guid, string $user_id, int $permissions) { + public function updatePendingShareRequestsForCredential(string $item_guid, string $user_id, int $permissions): int { return $this->shareRequest->updatePendingRequestPermissions($item_guid, $user_id, $permissions); } @@ -368,7 +381,7 @@ public function updatePendingShareRequestsForCredential(string $item_guid, strin * This will delete all ACL's and share requests. * @param string $item_guid */ - public function unshareCredential(string $item_guid) { + public function unshareCredential(string $item_guid): void { $acl_list = $this->getCredentialAclList($item_guid); $request_list = $this->getShareRequestsByGuid($item_guid); foreach ($acl_list as $ACL) { diff --git a/lib/Service/VaultService.php b/lib/Service/VaultService.php index 7687d1997..f7a1a899b 100644 --- a/lib/Service/VaultService.php +++ b/lib/Service/VaultService.php @@ -26,14 +26,13 @@ use OCA\Passman\Db\Vault; use OCA\Passman\Db\VaultMapper; use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; use OCP\AppFramework\Db\MultipleObjectsReturnedException; class VaultService { public function __construct( - private VaultMapper $vaultMapper, + private readonly VaultMapper $vaultMapper, ) { } @@ -41,9 +40,9 @@ public function __construct( /** * Get vaults from a user. * @param $userId - * @return Entity[] + * @return Vault[] */ - public function getByUser($userId) { + public function getByUser($userId): array { return $this->vaultMapper->findVaultsFromUser($userId); } @@ -51,21 +50,21 @@ public function getByUser($userId) { * Get a single vault * @param $vault_id * @param $user_id - * @return Entity[] + * @return Vault */ - public function getById($vault_id, $user_id) { - return $this->vaultMapper->find($vault_id, $user_id); + public function getById($vault_id, $user_id): Vault { + return $this->vaultMapper->findById($vault_id, $user_id); } /** * Get a single vault. * @param $vault_guid * @param $user_id - * @return Entity + * @return Vault * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function getByGuid($vault_guid, $user_id) { + public function getByGuid($vault_guid, $user_id): Vault { return $this->vaultMapper->findByGuid($vault_guid, $user_id); } @@ -75,16 +74,16 @@ public function getByGuid($vault_guid, $user_id) { * @param $userId * @return Vault */ - public function createVault($vault_name, $userId) { + public function createVault($vault_name, $userId): Vault { return $this->vaultMapper->create($vault_name, $userId); } /** * Update vault * @param $vault - * @return Vault|Entity + * @return Vault */ - public function updateVault($vault) { + public function updateVault($vault): Vault { return $this->vaultMapper->updateVault($vault); } @@ -92,9 +91,9 @@ public function updateVault($vault) { * Update last access time of a vault. * @param $vault_id * @param $user_id - * @return Vault|Entity + * @return Vault */ - public function setLastAccess($vault_id, $user_id) { + public function setLastAccess($vault_id, $user_id): Vault { return $this->vaultMapper->setLastAccess($vault_id, $user_id); } @@ -103,9 +102,9 @@ public function setLastAccess($vault_id, $user_id) { * @param $vault_id * @param $privateKey * @param $publicKey - * @return Vault|Entity + * @return Vault */ - public function updateSharingKeys($vault_id, $privateKey, $publicKey) { + public function updateSharingKeys($vault_id, $privateKey, $publicKey): Vault { return $this->vaultMapper->updateSharingKeys($vault_id, $privateKey, $publicKey); } @@ -116,10 +115,8 @@ public function updateSharingKeys($vault_id, $privateKey, $publicKey) { * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ - public function deleteVault($vault_guid, $user_id) { + public function deleteVault($vault_guid, $user_id): void { $vault = $this->getByGuid($vault_guid, $user_id); - if ($vault instanceof Vault) { - $this->vaultMapper->deleteVault($vault); - } + $this->vaultMapper->deleteVault($vault); } } diff --git a/lib/Settings/Admin.php b/lib/Settings/Admin.php index ec7cb60ad..928d2406c 100644 --- a/lib/Settings/Admin.php +++ b/lib/Settings/Admin.php @@ -24,6 +24,7 @@ namespace OCA\Passman\Settings; use GuzzleHttp\Client; +use GuzzleHttp\Exception\GuzzleException; use OCP\App\IAppManager; use OCP\AppFramework\Http\TemplateResponse; use OCP\IConfig; @@ -41,9 +42,9 @@ class Admin implements ISettings { */ public function __construct( protected IConfig $config, - private IL10N $l, - private IAppManager $appManager, - private LoggerInterface $logger, + private readonly IL10N $l, + private readonly IAppManager $appManager, + private readonly LoggerInterface $logger, ) { } @@ -66,8 +67,8 @@ public function getForm(): TemplateResponse { $response = $httpClient->request('get', $url); $json = $response->getBody()->getContents(); - if ($json) { - $data = json_decode($json); + if (!empty($json)) { + $data = json_decode((string) $json); if (isset($data->tag_name) && is_string($data->tag_name)) { $githubVersion = $data->tag_name; @@ -76,7 +77,7 @@ public function getForm(): TemplateResponse { } } } - } catch (\Exception $e) { + } catch (\Exception|GuzzleException $e) { $this->logger->error('Error fetching latest GitHub release version in lib/Admin:getForm()', ['exception' => $e->getTrace(), 'message' => $e->getMessage()]); } diff --git a/rector.php b/rector.php new file mode 100644 index 000000000..426341255 --- /dev/null +++ b/rector.php @@ -0,0 +1,29 @@ +withPaths([ + __DIR__ . '/appinfo', + __DIR__ . '/lib', + __DIR__ . '/templates', + __DIR__ . '/tests', + ]) + ->withPhpSets(php84: true) + ->withTypeCoverageLevel(0) + ->withSkip([ + // skip rule since it marks code that's intended, as it is + \Rector\Php70\Rector\FuncCall\RandomFunctionRector::class, + + // skip rule since it's introduced with php8.4 and not compatible to php8.1 + \Rector\Php84\Rector\MethodCall\NewMethodCallWithoutParenthesesRector::class, + // skip rule since it's introduced with php8.3 and not compatible to php8.1 + \Rector\Php83\Rector\ClassMethod\AddOverrideAttributeToOverriddenMethodsRector::class + ]); diff --git a/tests/db/DatabaseHelperTest.php b/tests/db/DatabaseHelperTest.php index cd5fe26b8..554eafaf3 100644 --- a/tests/db/DatabaseHelperTest.php +++ b/tests/db/DatabaseHelperTest.php @@ -80,12 +80,12 @@ public function truncateTable($table_name) { $this->db->executeQuery($this->db->getDatabasePlatform()->getTruncateTableSQL($table_name)); } - /** - * Initializes the table with the corresponding dataset on the dumps dir - * - * @param $table_name - */ - public function setUpTable($table_name){ + /** + * Initializes the table with the corresponding dataset on the dumps dir + * + * @param string $table_name + */ + public function setUpTable(string $table_name){ $table = $this->getTableDataset($table_name); $table_no_prefix = substr($table_name, 3); diff --git a/tests/unit/controller/InternalControllerTest.php b/tests/unit/controller/InternalControllerTest.php index 7f5ad49ba..b69f53738 100644 --- a/tests/unit/controller/InternalControllerTest.php +++ b/tests/unit/controller/InternalControllerTest.php @@ -41,7 +41,7 @@ class InternalControllerTest extends PHPUnit_Framework_TestCase { public function setUp() { $request = $this->getMockBuilder('OCP\IRequest')->getMock(); $config = $this->getMockBuilder('OCP\IConfig')->getMock(); - $this->credentialService = $this->getMockBuilder('OCA\Passman\Service\CredentialService') + $this->credentialService = $this->getMockBuilder(\OCA\Passman\Service\CredentialService::class) ->disableOriginalConstructor() ->getMock(); $this->controller = new InternalController( diff --git a/tests/unit/lib/BackgroundJob/ExpireCredentialsTest.php b/tests/unit/lib/BackgroundJob/ExpireCredentialsTest.php index 836a3b091..ef2da6036 100644 --- a/tests/unit/lib/BackgroundJob/ExpireCredentialsTest.php +++ b/tests/unit/lib/BackgroundJob/ExpireCredentialsTest.php @@ -46,7 +46,7 @@ public function testRun() { try { $backgroundJob->execute($jobList); } - catch (Exception $ex) { + catch (Exception) { $this->assertTrue(false); } } diff --git a/tests/unit/lib/Db/CredentialMapperTest.php b/tests/unit/lib/Db/CredentialMapperTest.php index 525d29612..9fdb3c973 100644 --- a/tests/unit/lib/Db/CredentialMapperTest.php +++ b/tests/unit/lib/Db/CredentialMapperTest.php @@ -106,8 +106,7 @@ public function testGetRandomCredentialByVaultId() { $tmp = $this->filterDataset($tmp, 'id', $data[0]->getId()); $this->assertCount(count($tmp), $data); - $tmp[0] = Credential::fromRow($tmp[0]); - $this->assertEquals($tmp, $data); + $this->assertEquals(Credential::fromRow($tmp[0]), $data); } /** @@ -286,4 +285,4 @@ public function testUpd() { $this->mapper->getCredentialById($cred->getId())->jsonSerialize() ); } -} \ No newline at end of file +} diff --git a/tests/unit/lib/Service/IconServiceTest.php b/tests/unit/lib/Service/IconServiceTest.php index 4f4f2657c..0c7a7ac46 100644 --- a/tests/unit/lib/Service/IconServiceTest.php +++ b/tests/unit/lib/Service/IconServiceTest.php @@ -39,9 +39,9 @@ class IconServiceTest extends PHPUnit_Framework_TestCase { private $testKey; public function setUp() { - $this->options = array( + $this->options = [ 'sslVerify' => false, - ); + ]; }