diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 9178a49e25633..864c3a5e48698 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -2,3 +2,6 @@ # SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors # SPDX-License-Identifier: AGPL-3.0-or-later + +# Update to coding-standard 1.2.2 +98d8ae805eb6ff38e60237ad4b599605df981322 diff --git a/apps/admin_audit/lib/Actions/Files.php b/apps/admin_audit/lib/Actions/Files.php index bf9660b19397a..57204e0b022e5 100644 --- a/apps/admin_audit/lib/Actions/Files.php +++ b/apps/admin_audit/lib/Actions/Files.php @@ -41,7 +41,7 @@ public function read(BeforeNodeReadEvent $event): void { ]; } catch (InvalidPathException|NotFoundException $e) { \OCP\Server::get(LoggerInterface::class)->error( - "Exception thrown in file read: ".$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] + 'Exception thrown in file read: '.$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] ); return; } @@ -61,7 +61,7 @@ public function beforeRename(BeforeNodeRenamedEvent $event): void { $this->renamedNodes[$source->getId()] = $source; } catch (InvalidPathException|NotFoundException $e) { \OCP\Server::get(LoggerInterface::class)->error( - "Exception thrown in file rename: ".$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] + 'Exception thrown in file rename: '.$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] ); return; } @@ -81,7 +81,7 @@ public function afterRename(NodeRenamedEvent $event): void { ]; } catch (InvalidPathException|NotFoundException $e) { \OCP\Server::get(LoggerInterface::class)->error( - "Exception thrown in file rename: ".$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] + 'Exception thrown in file rename: '.$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] ); return; } @@ -105,7 +105,7 @@ public function create(NodeCreatedEvent $event): void { ]; } catch (InvalidPathException|NotFoundException $e) { \OCP\Server::get(LoggerInterface::class)->error( - "Exception thrown in file create: ".$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] + 'Exception thrown in file create: '.$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] ); return; } @@ -132,7 +132,7 @@ public function copy(NodeCopiedEvent $event): void { ]; } catch (InvalidPathException|NotFoundException $e) { \OCP\Server::get(LoggerInterface::class)->error( - "Exception thrown in file copy: ".$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] + 'Exception thrown in file copy: '.$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] ); return; } @@ -155,7 +155,7 @@ public function write(NodeWrittenEvent $event): void { ]; } catch (InvalidPathException|NotFoundException $e) { \OCP\Server::get(LoggerInterface::class)->error( - "Exception thrown in file write: ".$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] + 'Exception thrown in file write: '.$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] ); return; } @@ -181,7 +181,7 @@ public function delete(BeforeNodeDeletedEvent $event): void { ]; } catch (InvalidPathException|NotFoundException $e) { \OCP\Server::get(LoggerInterface::class)->error( - "Exception thrown in file delete: ".$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] + 'Exception thrown in file delete: '.$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] ); return; } @@ -210,7 +210,7 @@ public function preview(BeforePreviewFetchedEvent $event): void { ]; } catch (InvalidPathException|NotFoundException $e) { \OCP\Server::get(LoggerInterface::class)->error( - "Exception thrown in file preview: ".$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] + 'Exception thrown in file preview: '.$e->getMessage(), ['app' => 'admin_audit', 'exception' => $e] ); return; } diff --git a/apps/cloud_federation_api/lib/Capabilities.php b/apps/cloud_federation_api/lib/Capabilities.php index 61cc45a24e625..d5cb30bdc3fd4 100644 --- a/apps/cloud_federation_api/lib/Capabilities.php +++ b/apps/cloud_federation_api/lib/Capabilities.php @@ -55,8 +55,8 @@ public function getCapabilities() { $resource = $this->provider->createNewResourceType(); $resource->setName('file') - ->setShareTypes(['user', 'group']) - ->setProtocols(['webdav' => '/public.php/webdav/']); + ->setShareTypes(['user', 'group']) + ->setProtocols(['webdav' => '/public.php/webdav/']); $this->provider->addResourceType($resource); diff --git a/apps/cloud_federation_api/lib/Config.php b/apps/cloud_federation_api/lib/Config.php index 9aefca746a14b..610769f2d8ecd 100644 --- a/apps/cloud_federation_api/lib/Config.php +++ b/apps/cloud_federation_api/lib/Config.php @@ -1,4 +1,5 @@ |JSONResponse|JSONResponse - * 201: The notification was successfully received. The display name of the recipient might be returned in the body - * 400: Bad request due to invalid parameters, e.g. when `shareWith` is not found or required properties are missing - * 501: Share type or the resource type is not supported + * 201: The notification was successfully received. The display name of the recipient might be returned in the body + * 400: Bad request due to invalid parameters, e.g. when `shareWith` is not found or required properties are missing + * 501: Share type or the resource type is not supported */ #[PublicPage] #[NoCSRFRequired] @@ -196,10 +197,10 @@ public function addShare($shareWith, $name, $description, $providerId, $owner, $ * @param array|null $notification The actual payload of the notification * * @return JSONResponse, array{}>|JSONResponse|JSONResponse - * 201: The notification was successfully received - * 400: Bad request due to invalid parameters, e.g. when `type` is invalid or missing - * 403: Getting resource is not allowed - * 501: The resource type is not supported + * 201: The notification was successfully received + * 400: Bad request due to invalid parameters, e.g. when `type` is invalid or missing + * 403: Getting resource is not allowed + * 501: The resource type is not supported */ #[NoCSRFRequired] #[PublicPage] diff --git a/apps/comments/lib/Activity/Filter.php b/apps/comments/lib/Activity/Filter.php index 6f010d855cbcf..8dcafd872d749 100644 --- a/apps/comments/lib/Activity/Filter.php +++ b/apps/comments/lib/Activity/Filter.php @@ -1,4 +1,5 @@ mountCollection->getMountCache(); - $mounts = $cache->getMountsForFileId((int)$event->getComment()->getObjectId()); + $mounts = $cache->getMountsForFileId((int) $event->getComment()->getObjectId()); if (empty($mounts)) { return; } @@ -47,7 +47,7 @@ public function commentEvent(CommentsEvent $event): void { foreach ($mounts as $mount) { $owner = $mount->getUser()->getUID(); $ownerFolder = $this->rootFolder->getUserFolder($owner); - $nodes = $ownerFolder->getById((int)$event->getComment()->getObjectId()); + $nodes = $ownerFolder->getById((int) $event->getComment()->getObjectId()); if (!empty($nodes)) { /** @var Node $node */ $node = array_shift($nodes); @@ -75,7 +75,7 @@ public function commentEvent(CommentsEvent $event): void { foreach ($users as $user => $path) { // numerical user ids end up as integers from array keys, but string // is required - $activity->setAffectedUser((string)$user); + $activity->setAffectedUser((string) $user); $activity->setSubject('add_comment_subject', [ 'actor' => $actor, diff --git a/apps/comments/lib/Activity/Provider.php b/apps/comments/lib/Activity/Provider.php index 704ef0e0a4812..4806eeec6936a 100644 --- a/apps/comments/lib/Activity/Provider.php +++ b/apps/comments/lib/Activity/Provider.php @@ -1,4 +1,5 @@ rootFolder->getUserFolder($currentUser->getUID()); - $files = $userFolder->getById((int)$comment->getObjectId()); + $files = $userFolder->getById((int) $comment->getObjectId()); $this->markProcessed($comment, $currentUser); diff --git a/apps/comments/lib/Listener/CommentsEntityEventListener.php b/apps/comments/lib/Listener/CommentsEntityEventListener.php index 5aeeb3c63ea6c..2a805d800834b 100644 --- a/apps/comments/lib/Listener/CommentsEntityEventListener.php +++ b/apps/comments/lib/Listener/CommentsEntityEventListener.php @@ -28,7 +28,7 @@ public function handle(Event $event): void { } $event->addEntityCollection('files', function ($name): bool { - $nodes = $this->rootFolder->getUserFolder($this->userId)->getById((int)$name); + $nodes = $this->rootFolder->getUserFolder($this->userId)->getById((int) $name); return !empty($nodes); }); } diff --git a/apps/comments/lib/MaxAutoCompleteResultsInitialState.php b/apps/comments/lib/MaxAutoCompleteResultsInitialState.php index b4c8f8719db4c..96bc2e6ea16b3 100644 --- a/apps/comments/lib/MaxAutoCompleteResultsInitialState.php +++ b/apps/comments/lib/MaxAutoCompleteResultsInitialState.php @@ -22,6 +22,6 @@ public function getKey(): string { } public function getData(): int { - return (int)$this->config->getAppValue('comments', 'maxAutoCompleteResults', '10'); + return (int) $this->config->getAppValue('comments', 'maxAutoCompleteResults', '10'); } } diff --git a/apps/comments/lib/Notification/Notifier.php b/apps/comments/lib/Notification/Notifier.php index d5563ef7d8557..9ed63029fc9ee 100644 --- a/apps/comments/lib/Notification/Notifier.php +++ b/apps/comments/lib/Notification/Notifier.php @@ -84,7 +84,7 @@ public function prepare(INotification $notification, string $languageCode): INot throw new UnknownNotificationException('Unsupported comment object'); } $userFolder = $this->rootFolder->getUserFolder($notification->getUser()); - $nodes = $userFolder->getById((int)$parameters[1]); + $nodes = $userFolder->getById((int) $parameters[1]); if (empty($nodes)) { throw new AlreadyProcessedException(); } diff --git a/apps/comments/lib/Search/Result.php b/apps/comments/lib/Search/Result.php index f9bdc71f0a3ac..a37b80686d23b 100644 --- a/apps/comments/lib/Search/Result.php +++ b/apps/comments/lib/Search/Result.php @@ -1,4 +1,5 @@ mapper->find( $this->getUid(), - (int)$name + (int) $name ), $this->principalUri, $this->getACL() ); } catch (DoesNotExistException $ex) { - throw new NotFound("Contact does not exist: " . $ex->getMessage(), 0, $ex); + throw new NotFound('Contact does not exist: ' . $ex->getMessage(), 0, $ex); } } @@ -92,7 +92,7 @@ public function childExists($name): bool { try { $this->mapper->find( $this->getUid(), - (int)$name + (int) $name ); return true; } catch (DoesNotExistException $e) { @@ -112,7 +112,7 @@ public function getLastModified(): ?int { * @throws Exception */ public function propPatch(PropPatch $propPatch) { - throw new Exception("This addressbook is immutable"); + throw new Exception('This addressbook is immutable'); } /** diff --git a/apps/contactsinteraction/lib/Db/CardSearchDao.php b/apps/contactsinteraction/lib/Db/CardSearchDao.php index 0929cb7efa098..09fa4711adb29 100644 --- a/apps/contactsinteraction/lib/Db/CardSearchDao.php +++ b/apps/contactsinteraction/lib/Db/CardSearchDao.php @@ -50,7 +50,7 @@ public function findExisting(IUser $user, } $addressbooksQuery->selectDistinct('id') ->from('addressbooks') - ->where($addressbooksQuery->expr()->eq('principaluri', $cardQuery->createNamedParameter("principals/users/" . $user->getUID()))); + ->where($addressbooksQuery->expr()->eq('principaluri', $cardQuery->createNamedParameter('principals/users/' . $user->getUID()))); $propQuery->selectDistinct('cardid') ->from('cards_properties') ->where($propQuery->expr()->in('addressbookid', $propQuery->createFunction($addressbooksQuery->getSQL()), IQueryBuilder::PARAM_INT_ARRAY)) diff --git a/apps/contactsinteraction/lib/Db/RecentContactMapper.php b/apps/contactsinteraction/lib/Db/RecentContactMapper.php index c835b5287c87f..02d2c1e8ea193 100644 --- a/apps/contactsinteraction/lib/Db/RecentContactMapper.php +++ b/apps/contactsinteraction/lib/Db/RecentContactMapper.php @@ -100,7 +100,7 @@ public function findLastUpdatedForUserId(string $uid): ?int { return null; } - return (int)$row['last_contact']; + return (int) $row['last_contact']; } public function cleanUp(int $olderThan): void { diff --git a/apps/contactsinteraction/lib/Listeners/ContactInteractionListener.php b/apps/contactsinteraction/lib/Listeners/ContactInteractionListener.php index ac0cd92751296..78b366f015e35 100644 --- a/apps/contactsinteraction/lib/Listeners/ContactInteractionListener.php +++ b/apps/contactsinteraction/lib/Listeners/ContactInteractionListener.php @@ -45,12 +45,12 @@ public function handle(Event $event): void { } if ($event->getUid() === null && $event->getEmail() === null && $event->getFederatedCloudId() === null) { - $this->logger->warning("Contact interaction event has no user identifier set"); + $this->logger->warning('Contact interaction event has no user identifier set'); return; } if ($event->getUid() !== null && $event->getUid() === $event->getActor()->getUID()) { - $this->logger->info("Ignoring contact interaction with self"); + $this->logger->info('Ignoring contact interaction with self'); return; } diff --git a/apps/dav/appinfo/routes.php b/apps/dav/appinfo/routes.php index 91c1ba58ea2f4..dba7bcbbdf07f 100644 --- a/apps/dav/appinfo/routes.php +++ b/apps/dav/appinfo/routes.php @@ -1,4 +1,5 @@ avatar->getFile($this->size)->getMTime(); if (!empty($timestamp)) { - return (int)$timestamp; + return (int) $timestamp; } return $timestamp; } diff --git a/apps/dav/lib/Avatars/RootCollection.php b/apps/dav/lib/Avatars/RootCollection.php index d7cdb92c6be7d..2de5272bb6834 100644 --- a/apps/dav/lib/Avatars/RootCollection.php +++ b/apps/dav/lib/Avatars/RootCollection.php @@ -1,4 +1,5 @@ time->getTime() - (60 * 60); $this->calDavBackend->deleteOutdatedSchedulingObjects($time, 50000); - $this->logger->info("Removed outdated scheduling objects"); + $this->logger->info('Removed outdated scheduling objects'); } } diff --git a/apps/dav/lib/BackgroundJob/OutOfOfficeEventDispatcherJob.php b/apps/dav/lib/BackgroundJob/OutOfOfficeEventDispatcherJob.php index 8293b37099635..cc4fd5dce9dea 100644 --- a/apps/dav/lib/BackgroundJob/OutOfOfficeEventDispatcherJob.php +++ b/apps/dav/lib/BackgroundJob/OutOfOfficeEventDispatcherJob.php @@ -41,7 +41,7 @@ public function run($argument): void { try { $absence = $this->absenceMapper->findById($id); - } catch (DoesNotExistException | \OCP\DB\Exception $e) { + } catch (DoesNotExistException|\OCP\DB\Exception $e) { $this->logger->error('Failed to dispatch out-of-office event: ' . $e->getMessage(), [ 'exception' => $e, 'argument' => $argument, diff --git a/apps/dav/lib/BackgroundJob/UploadCleanup.php b/apps/dav/lib/BackgroundJob/UploadCleanup.php index d90e6cbd1718d..aa19dbb22ece8 100644 --- a/apps/dav/lib/BackgroundJob/UploadCleanup.php +++ b/apps/dav/lib/BackgroundJob/UploadCleanup.php @@ -44,7 +44,7 @@ protected function run($argument) { /** @var Folder $uploads */ $uploads = $userRoot->get('uploads'); $uploadFolder = $uploads->get($folder); - } catch (NotFoundException | NoUserException $e) { + } catch (NotFoundException|NoUserException $e) { $this->jobList->remove(self::class, $argument); return; } @@ -53,7 +53,7 @@ protected function run($argument) { $time = $this->time->getTime() - 60 * 60 * 24; if (!($uploadFolder instanceof Folder)) { - $this->logger->error("Found a file inside the uploads folder. Uid: " . $uid . ' folder: ' . $folder); + $this->logger->error('Found a file inside the uploads folder. Uid: ' . $uid . ' folder: ' . $folder); if ($uploadFolder->getMTime() < $time) { $uploadFolder->delete(); } diff --git a/apps/dav/lib/BackgroundJob/UserStatusAutomation.php b/apps/dav/lib/BackgroundJob/UserStatusAutomation.php index 1593be49a5d16..8d5c229241d84 100644 --- a/apps/dav/lib/BackgroundJob/UserStatusAutomation.php +++ b/apps/dav/lib/BackgroundJob/UserStatusAutomation.php @@ -55,14 +55,14 @@ protected function run($argument) { $userId = $argument['userId']; $user = $this->userManager->get($userId); - if($user === null) { + if ($user === null) { return; } $ooo = $this->coordinator->getCurrentOutOfOfficeData($user); $continue = $this->processOutOfOfficeData($user, $ooo); - if($continue === false) { + if ($continue === false) { return; } @@ -150,7 +150,7 @@ private function processAvailability(string $property, string $userId, bool $has $effectiveEnd = \DateTime::createFromImmutable($originalEnd)->sub(new \DateInterval('P7D')); try { - $it = new RRuleIterator((string)$available->RRULE, $effectiveStart); + $it = new RRuleIterator((string) $available->RRULE, $effectiveStart); $it->fastForward($lastMidnight); $startToday = $it->current(); @@ -196,7 +196,7 @@ private function processAvailability(string $property, string $userId, bool $has return; } - if(!$hasDndForOfficeHours) { + if (!$hasDndForOfficeHours) { // Office hours are not set to DND, so there is nothing to do. return; } @@ -207,7 +207,7 @@ private function processAvailability(string $property, string $userId, bool $has } private function processOutOfOfficeData(IUser $user, ?IOutOfOfficeData $ooo): bool { - if(empty($ooo)) { + if (empty($ooo)) { // Reset the user status if the absence doesn't exist $this->logger->debug('User has no OOO period in effect, reverting DND status if applicable'); $this->manager->revertUserStatus($user->getUID(), IUserStatus::MESSAGE_OUT_OF_OFFICE, IUserStatus::DND); @@ -215,12 +215,12 @@ private function processOutOfOfficeData(IUser $user, ?IOutOfOfficeData $ooo): bo return true; } - if(!$this->coordinator->isInEffect($ooo)) { + if (!$this->coordinator->isInEffect($ooo)) { // Reset the user status if the absence is (no longer) in effect $this->logger->debug('User has no OOO period in effect, reverting DND status if applicable'); $this->manager->revertUserStatus($user->getUID(), IUserStatus::MESSAGE_OUT_OF_OFFICE, IUserStatus::DND); - if($ooo->getStartDate() > $this->time->getTime()) { + if ($ooo->getStartDate() > $this->time->getTime()) { // Set the next run to take place at the start of the ooo period if it is in the future // This might be overwritten if there is an availability setting, but we can't determine // if this is the case here diff --git a/apps/dav/lib/BulkUpload/BulkUploadPlugin.php b/apps/dav/lib/BulkUpload/BulkUploadPlugin.php index ae7f55d7107de..80e7da98da157 100644 --- a/apps/dav/lib/BulkUpload/BulkUploadPlugin.php +++ b/apps/dav/lib/BulkUpload/BulkUploadPlugin.php @@ -1,4 +1,5 @@ getPath() !== "bulk") { + if ($request->getPath() !== 'bulk') { return true; } @@ -77,16 +78,16 @@ public function httpPost(RequestInterface $request, ResponseInterface $response) $node = $this->userFolder->getFirstNodeById($node->getId()); $writtenFiles[$headers['x-file-path']] = [ - "error" => false, - "etag" => $node->getETag(), - "fileid" => DavUtil::getDavFileId($node->getId()), - "permissions" => DavUtil::getDavPermissions($node), + 'error' => false, + 'etag' => $node->getETag(), + 'fileid' => DavUtil::getDavFileId($node->getId()), + 'permissions' => DavUtil::getDavPermissions($node), ]; } catch (\Exception $e) { $this->logger->error($e->getMessage(), ['path' => $headers['x-file-path']]); $writtenFiles[$headers['x-file-path']] = [ - "error" => true, - "message" => $e->getMessage(), + 'error' => true, + 'message' => $e->getMessage(), ]; } } diff --git a/apps/dav/lib/BulkUpload/MultipartRequestParser.php b/apps/dav/lib/BulkUpload/MultipartRequestParser.php index 2d3cf7d421c54..654246c98c810 100644 --- a/apps/dav/lib/BulkUpload/MultipartRequestParser.php +++ b/apps/dav/lib/BulkUpload/MultipartRequestParser.php @@ -1,4 +1,5 @@ stream = $stream; @@ -60,7 +61,7 @@ private function parseBoundaryFromHeaders(string $contentType): string { [$mimeType, $boundary] = explode(';', $contentType); [$boundaryKey, $boundaryValue] = explode('=', $boundary); } catch (\Exception $e) { - throw new BadRequest("Error while parsing boundary in Content-Type header.", Http::STATUS_BAD_REQUEST, $e); + throw new BadRequest('Error while parsing boundary in Content-Type header.', Http::STATUS_BAD_REQUEST, $e); } $boundaryValue = trim($boundaryValue); @@ -96,7 +97,7 @@ private function isAt(string $expectedContent): bool { $seekBackResult = fseek($this->stream, -$expectedContentLength, SEEK_CUR); if ($seekBackResult === -1) { - throw new Exception("Unknown error while seeking content", Http::STATUS_INTERNAL_SERVER_ERROR); + throw new Exception('Unknown error while seeking content', Http::STATUS_INTERNAL_SERVER_ERROR); } return $expectedContent === $content; @@ -134,7 +135,7 @@ public function parseNextPart(): array { $headers = $this->readPartHeaders(); - $content = $this->readPartContent($headers["content-length"], $headers["x-file-md5"]); + $content = $this->readPartContent($headers['content-length'], $headers['x-file-md5']); return [$headers, $content]; } @@ -146,7 +147,7 @@ public function parseNextPart(): array { */ private function readBoundary(): string { if (!$this->isAtBoundary()) { - throw new BadRequest("Boundary not found where it should be."); + throw new BadRequest('Boundary not found where it should be.'); } return fread($this->stream, strlen($this->boundary)); @@ -180,12 +181,12 @@ private function readPartHeaders(): array { } } - if (!isset($headers["content-length"])) { - throw new LengthRequired("The Content-Length header must not be null."); + if (!isset($headers['content-length'])) { + throw new LengthRequired('The Content-Length header must not be null.'); } - if (!isset($headers["x-file-md5"])) { - throw new BadRequest("The X-File-MD5 header must not be null."); + if (!isset($headers['x-file-md5'])) { + throw new BadRequest('The X-File-MD5 header must not be null.'); } return $headers; @@ -201,7 +202,7 @@ private function readPartContent(int $length, string $md5): string { $computedMd5 = $this->computeMd5Hash($length); if ($md5 !== $computedMd5) { - throw new BadRequest("Computed md5 hash is incorrect."); + throw new BadRequest('Computed md5 hash is incorrect.'); } if ($length === 0) { @@ -215,7 +216,7 @@ private function readPartContent(int $length, string $md5): string { } if ($length !== 0 && feof($this->stream)) { - throw new Exception("Unexpected EOF while reading stream."); + throw new Exception('Unexpected EOF while reading stream.'); } // Read '\r\n'. diff --git a/apps/dav/lib/CalDAV/Activity/Backend.php b/apps/dav/lib/CalDAV/Activity/Backend.php index c2018baab9255..41b243143886a 100644 --- a/apps/dav/lib/CalDAV/Activity/Backend.php +++ b/apps/dav/lib/CalDAV/Activity/Backend.php @@ -1,4 +1,5 @@ 'calendar', - 'id' => (string)$data['id'], + 'id' => (string) $data['id'], 'name' => $l->t('Personal'), ]; } return [ 'type' => 'calendar', - 'id' => (string)$data['id'], + 'id' => (string) $data['id'], 'name' => $data['name'], ]; } @@ -72,7 +73,7 @@ protected function generateCalendarParameter($data, IL10N $l) { protected function generateLegacyCalendarParameter($id, $name) { return [ 'type' => 'calendar', - 'id' => (string)$id, + 'id' => (string) $id, 'name' => $name, ]; } diff --git a/apps/dav/lib/CalDAV/Activity/Provider/Calendar.php b/apps/dav/lib/CalDAV/Activity/Provider/Calendar.php index a7509831f2966..04569cb8d6552 100644 --- a/apps/dav/lib/CalDAV/Activity/Provider/Calendar.php +++ b/apps/dav/lib/CalDAV/Activity/Provider/Calendar.php @@ -1,4 +1,5 @@ vobject->getBaseComponents(); foreach ($components as $key => $component) { $components[$key]->STATUS = 'CANCELLED'; - $components[$key]->SEQUENCE = isset($component->SEQUENCE) ? ((int)$component->SEQUENCE->getValue()) + 1 : 1; + $components[$key]->SEQUENCE = isset($component->SEQUENCE) ? ((int) $component->SEQUENCE->getValue()) + 1 : 1; if ($component->name === 'VEVENT') { $components[$key]->METHOD = 'CANCEL'; } @@ -116,9 +116,9 @@ public function getName(): string { throw new NotFound('Invalid node'); } if (isset($base->{'X-FILENAME'})) { - return (string)$base->{'X-FILENAME'}; + return (string) $base->{'X-FILENAME'}; } - return (string)$base->UID . '.ics'; + return (string) $base->UID . '.ics'; } public function setName($name): void { diff --git a/apps/dav/lib/CalDAV/BirthdayCalendar/EnablePlugin.php b/apps/dav/lib/CalDAV/BirthdayCalendar/EnablePlugin.php index 733e80791118c..049d76e7c10a9 100644 --- a/apps/dav/lib/CalDAV/BirthdayCalendar/EnablePlugin.php +++ b/apps/dav/lib/CalDAV/BirthdayCalendar/EnablePlugin.php @@ -1,4 +1,5 @@ getOwner(), 17); - if($owner !== $this->user->getUID()) { + if ($owner !== $this->user->getUID()) { $this->server->httpResponse->setStatus(403); return false; } diff --git a/apps/dav/lib/CalDAV/BirthdayService.php b/apps/dav/lib/CalDAV/BirthdayService.php index 0990cd674dd43..faf76f6697a05 100644 --- a/apps/dav/lib/CalDAV/BirthdayService.php +++ b/apps/dav/lib/CalDAV/BirthdayService.php @@ -169,7 +169,7 @@ public function buildDateFromContact(string $cardData, return null; } $birthday = $doc->{$dateField}; - if (!(string)$birthday) { + if (!(string) $birthday) { return null; } // Skip if the BDAY property is not of the right type. @@ -188,18 +188,18 @@ public function buildDateFromContact(string $cardData, $omitYear = (isset($parameters['X-APPLE-OMIT-YEAR']) && $parameters['X-APPLE-OMIT-YEAR'] === $dateParts['year']); // 'X-APPLE-OMIT-YEAR' is not always present, at least iOS 12.4 uses the hard coded date of 1604 (the start of the gregorian calendar) when the year is unknown - if ($omitYear || (int)$dateParts['year'] === 1604) { + if ($omitYear || (int) $dateParts['year'] === 1604) { $dateParts['year'] = null; } } $originalYear = null; if ($dateParts['year'] !== null) { - $originalYear = (int)$dateParts['year']; + $originalYear = (int) $dateParts['year']; } - $leapDay = ((int)$dateParts['month'] === 2 - && (int)$dateParts['date'] === 29); + $leapDay = ((int) $dateParts['month'] === 2 + && (int) $dateParts['date'] === 29); if ($dateParts['year'] === null || $originalYear < 1970) { $birthday = ($leapDay ? '1972-' : '1970-') . $dateParts['month'] . '-' . $dateParts['date']; diff --git a/apps/dav/lib/CalDAV/CachedSubscriptionImpl.php b/apps/dav/lib/CalDAV/CachedSubscriptionImpl.php index 3f6eff4e1f431..06fb7236000b9 100644 --- a/apps/dav/lib/CalDAV/CachedSubscriptionImpl.php +++ b/apps/dav/lib/CalDAV/CachedSubscriptionImpl.php @@ -62,7 +62,7 @@ public function getDisplayColor(): ?string { * @param string $pattern which should match within the $searchProperties * @param array $searchProperties defines the properties within the query pattern should match * @param array $options - optional parameters: - * ['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]] + * ['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]] * @param int|null $limit - limit number of search results * @param int|null $offset - offset for paging of search results * @return array an array of events/journals/todos which are arrays of key-value-pairs diff --git a/apps/dav/lib/CalDAV/CalDavBackend.php b/apps/dav/lib/CalDAV/CalDavBackend.php index 0aec5525cdbe6..81ad1f4a0f134 100644 --- a/apps/dav/lib/CalDAV/CalDavBackend.php +++ b/apps/dav/lib/CalDAV/CalDavBackend.php @@ -1,4 +1,5 @@ executeQuery(); - $column = (int)$result->fetchOne(); + $column = (int) $result->fetchOne(); $result->closeCursor(); return $column; } @@ -243,7 +244,7 @@ public function getSubscriptionsForUserCount(string $principalUri): int { } $result = $query->executeQuery(); - $column = (int)$result->fetchOne(); + $column = (int) $result->fetchOne(); $result->closeCursor(); return $column; } @@ -521,8 +522,8 @@ public function getPublicCalendars() { '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components), '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'), '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint), - '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ, - '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC, + '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int) $row['access'] === Backend::ACCESS_READ, + '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int) $row['access'] === self::ACCESS_PUBLIC, ]; $calendar = $this->rowToCalendar($row, $calendar); @@ -586,8 +587,8 @@ public function getPublicCalendar($uri) { '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components), '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'), '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint), - '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ, - '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC, + '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int) $row['access'] === Backend::ACCESS_READ, + '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int) $row['access'] === self::ACCESS_PUBLIC, ]; $calendar = $this->rowToCalendar($row, $calendar); @@ -799,7 +800,7 @@ public function createCalendar($principalUri, $calendarUri, array $properties) { return [$calendarId, $calendarData]; }, $this->db); - $this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData)); + $this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int) $calendarId, $calendarData)); return $calendarId; } @@ -847,7 +848,7 @@ public function updateCalendar($calendarId, PropPatch $propPatch) { $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId))); $query->executeStatement(); - $this->addChanges($calendarId, [""], 2); + $this->addChanges($calendarId, [''], 2); $calendarData = $this->getCalendarById($calendarId); $shares = $this->getShares($calendarId); @@ -1046,9 +1047,9 @@ public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_T 'lastmodified' => $row['lastmodified'], 'etag' => '"' . $row['etag'] . '"', 'calendarid' => $row['calendarid'], - 'size' => (int)$row['size'], + 'size' => (int) $row['size'], 'component' => strtolower($row['componenttype']), - 'classification' => (int)$row['classification'] + 'classification' => (int) $row['classification'] ]; } $stmt->closeCursor(); @@ -1113,9 +1114,9 @@ public function getDeletedCalendarObjectsByPrincipal(string $principalUri): arra 'etag' => '"' . $row['etag'] . '"', 'calendarid' => $row['calendarid'], 'calendaruri' => $row['calendaruri'], - 'size' => (int)$row['size'], + 'size' => (int) $row['size'], 'component' => strtolower($row['componenttype']), - 'classification' => (int)$row['classification'], + 'classification' => (int) $row['classification'], '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'], ]; } @@ -1173,10 +1174,10 @@ private function rowToCalendarObject(array $row): array { 'lastmodified' => $row['lastmodified'], 'etag' => '"' . $row['etag'] . '"', 'calendarid' => $row['calendarid'], - 'size' => (int)$row['size'], + 'size' => (int) $row['size'], 'calendardata' => $this->readBlob($row['calendardata']), 'component' => strtolower($row['componenttype']), - 'classification' => (int)$row['classification'], + 'classification' => (int) $row['classification'], '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'], ]; } @@ -1221,10 +1222,10 @@ public function getMultipleCalendarObjects($calendarId, array $uris, $calendarTy 'lastmodified' => $row['lastmodified'], 'etag' => '"' . $row['etag'] . '"', 'calendarid' => $row['calendarid'], - 'size' => (int)$row['size'], + 'size' => (int) $row['size'], 'calendardata' => $this->readBlob($row['calendardata']), 'component' => strtolower($row['componenttype']), - 'classification' => (int)$row['classification'] + 'classification' => (int) $row['classification'] ]; } $result->closeCursor(); @@ -1354,15 +1355,15 @@ public function updateCalendarObject($calendarId, $objectUri, $calendarData, $ca return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) { $query = $this->db->getQueryBuilder(); $query->update('calendarobjects') - ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB)) - ->set('lastmodified', $query->createNamedParameter(time())) - ->set('etag', $query->createNamedParameter($extraData['etag'])) - ->set('size', $query->createNamedParameter($extraData['size'])) - ->set('componenttype', $query->createNamedParameter($extraData['componentType'])) - ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence'])) - ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence'])) - ->set('classification', $query->createNamedParameter($extraData['classification'])) - ->set('uid', $query->createNamedParameter($extraData['uid'])) + ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB)) + ->set('lastmodified', $query->createNamedParameter(time())) + ->set('etag', $query->createNamedParameter($extraData['etag'])) + ->set('size', $query->createNamedParameter($extraData['size'])) + ->set('componenttype', $query->createNamedParameter($extraData['componentType'])) + ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence'])) + ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence'])) + ->set('classification', $query->createNamedParameter($extraData['classification'])) + ->set('uid', $query->createNamedParameter($extraData['uid'])) ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId))) ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri))) ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType))) @@ -1510,13 +1511,13 @@ public function deleteCalendarObject($calendarId, $objectUri, $calendarType = se if (!empty($pathInfo['extension'])) { // Append a suffix to "free" the old URI for recreation $newUri = sprintf( - "%s-deleted.%s", + '%s-deleted.%s', $pathInfo['filename'], $pathInfo['extension'] ); } else { $newUri = sprintf( - "%s-deleted", + '%s-deleted', $pathInfo['filename'] ); } @@ -1565,7 +1566,7 @@ public function restoreCalendarObject(array $objectData): void { $this->cachedObjects = []; $this->atomic(function () use ($objectData) { $id = (int) $objectData['id']; - $restoreUri = str_replace("-deleted.ics", ".ics", $objectData['uri']); + $restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']); $targetObject = $this->getCalendarObject( $objectData['calendarid'], $restoreUri @@ -1992,7 +1993,7 @@ public function search( // For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful. $outerQuery->addOrderBy('id'); - $offset = (int)$offset; + $offset = (int) $offset; $outerQuery->setFirstResult($offset); $calendarObjects = []; @@ -2013,7 +2014,7 @@ public function search( * * 25 rows and 3 retries is entirely arbitrary. */ - $maxResults = (int)max($limit, 25); + $maxResults = (int) max($limit, 25); $outerQuery->setMaxResults($maxResults); for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) { @@ -2220,7 +2221,7 @@ public function searchPrincipalUri(string $principalUri, $subscriptions = $this->getSubscriptionsForUser($principalUri); foreach ($calendars as $calendar) { $calendarAnd = $calendarObjectIdQuery->expr()->andX( - $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])), + $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $calendar['id'])), $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)), ); @@ -2234,7 +2235,7 @@ public function searchPrincipalUri(string $principalUri, } foreach ($subscriptions as $subscription) { $subscriptionAnd = $calendarObjectIdQuery->expr()->andX( - $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])), + $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $subscription['id'])), $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)), ); @@ -2323,8 +2324,8 @@ public function searchPrincipalUri(string $principalUri, $result = $query->executeQuery(); $calendarObjects = []; while (($array = $result->fetch()) !== false) { - $array['calendarid'] = (int)$array['calendarid']; - $array['calendartype'] = (int)$array['calendartype']; + $array['calendarid'] = (int) $array['calendarid']; + $array['calendartype'] = (int) $array['calendartype']; $array['calendardata'] = $this->readBlob($array['calendardata']); $calendarObjects[] = $array; @@ -2394,10 +2395,10 @@ public function getCalendarObjectById(string $principalUri, int $id): ?array { 'etag' => '"' . $row['etag'] . '"', 'calendarid' => $row['calendarid'], 'calendaruri' => $row['calendaruri'], - 'size' => (int)$row['size'], + 'size' => (int) $row['size'], 'calendardata' => $this->readBlob($row['calendardata']), 'component' => strtolower($row['componenttype']), - 'classification' => (int)$row['classification'], + 'classification' => (int) $row['classification'], 'deleted_at' => isset($row['deleted_at']) ? ((int) $row['deleted_at']) : null, ]; } @@ -2513,7 +2514,7 @@ public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limi while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) { // assign uri (column 0) to appropriate mutation based on operation (column 1) // forced (int) is needed as doctrine with OCI returns the operation field as string not integer - match ((int)$entry[1]) { + match ((int) $entry[1]) { 1 => $result['added'][] = $entry[0], 2 => $result['modified'][] = $entry[0], 3 => $result['deleted'][] = $entry[0], @@ -2694,7 +2695,7 @@ public function updateSubscription($subscriptionId, PropPatch $propPatch) { return $this->getSubscriptionById($subscriptionId); }, $this->db); - $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations)); + $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int) $subscriptionId, $subscriptionRow, [], $mutations)); return true; }); @@ -2732,7 +2733,7 @@ public function deleteSubscription($subscriptionId) { ->executeStatement(); if ($subscriptionRow) { - $this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, [])); + $this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int) $subscriptionId, $subscriptionRow, [])); } }, $this->db); } @@ -2772,7 +2773,7 @@ public function getSchedulingObject($principalUri, $objectUri) { 'calendardata' => $row['calendardata'], 'lastmodified' => $row['lastmodified'], 'etag' => '"' . $row['etag'] . '"', - 'size' => (int)$row['size'], + 'size' => (int) $row['size'], ]; } @@ -2790,9 +2791,9 @@ public function getSchedulingObject($principalUri, $objectUri) { public function getSchedulingObjects($principalUri) { $query = $this->db->getQueryBuilder(); $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size']) - ->from('schedulingobjects') - ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri))) - ->executeQuery(); + ->from('schedulingobjects') + ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri))) + ->executeQuery(); $results = []; while (($row = $stmt->fetch()) !== false) { @@ -2801,7 +2802,7 @@ public function getSchedulingObjects($principalUri) { 'uri' => $row['uri'], 'lastmodified' => $row['lastmodified'], 'etag' => '"' . $row['etag'] . '"', - 'size' => (int)$row['size'], + 'size' => (int) $row['size'], ]; } $stmt->closeCursor(); @@ -2820,9 +2821,9 @@ public function deleteSchedulingObject($principalUri, $objectUri) { $this->cachedObjects = []; $query = $this->db->getQueryBuilder(); $query->delete('schedulingobjects') - ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri))) - ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri))) - ->executeStatement(); + ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri))) + ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri))) + ->executeStatement(); } /** @@ -2840,11 +2841,11 @@ public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit) ->setMaxResults($limit); $result = $query->executeQuery(); $count = $result->rowCount(); - if($count === 0) { + if ($count === 0) { return; } $ids = array_map(static function (array $id) { - return (int)$id[0]; + return (int) $id[0]; }, $result->fetchAll(\PDO::FETCH_NUM)); $result->closeCursor(); @@ -2852,12 +2853,12 @@ public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit) $deleteQuery = $this->db->getQueryBuilder(); $deleteQuery->delete('schedulingobjects') ->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY)); - foreach(array_chunk($ids, 1000) as $chunk) { + foreach (array_chunk($ids, 1000) as $chunk) { $deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY); $numDeleted += $deleteQuery->executeStatement(); } - if($numDeleted === $limit) { + if ($numDeleted === $limit) { $this->logger->info("Deleted $limit scheduling objects, continuing with next batch"); $this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit); } @@ -2905,7 +2906,7 @@ protected function addChanges(int $calendarId, array $objectUris, int $operation ->from($table) ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId))); $result = $query->executeQuery(); - $syncToken = (int)$result->fetchOne(); + $syncToken = (int) $result->fetchOne(); $result->closeCursor(); $query = $this->db->getQueryBuilder(); @@ -2965,7 +2966,7 @@ public function restoreChanges(int $calendarId, int $calendarType = self::CALEND ); $resultDeleted = $qbDeleted->executeQuery(); $deletedUris = array_map(function (string $uri) { - return str_replace("-deleted.ics", ".ics", $uri); + return str_replace('-deleted.ics', '.ics', $uri); }, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN)); $resultDeleted->closeCursor(); $this->addChanges($calendarId, $deletedUris, 3, $calendarType); @@ -3009,7 +3010,7 @@ public function getDenormalizedData(string $calendarData): array { // Track first component type and uid if ($uid === null) { $componentType = $component->name; - $uid = (string)$component->UID; + $uid = (string) $component->UID; } } } @@ -3332,7 +3333,7 @@ public function purgeAllCachedEventsForSubscription($subscriptionId) { * @param array $calendarObjectUris */ public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void { - if(empty($calendarObjectUris)) { + if (empty($calendarObjectUris)) { return; } @@ -3432,7 +3433,7 @@ protected function getCalendarObjectId($calendarId, $uri, $calendarType):int { throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri); } - return (int)$objectIds['id']; + return (int) $objectIds['id']; } /** diff --git a/apps/dav/lib/CalDAV/CalendarHome.php b/apps/dav/lib/CalDAV/CalendarHome.php index d01c2affbc8c9..59a976ca6bc3d 100644 --- a/apps/dav/lib/CalDAV/CalendarHome.php +++ b/apps/dav/lib/CalDAV/CalendarHome.php @@ -149,9 +149,9 @@ public function getChild($name) { // Calendar - this covers all "regular" calendars, but not shared // only check if the method is available - if($this->caldavBackend instanceof CalDavBackend) { + if ($this->caldavBackend instanceof CalDavBackend) { $calendar = $this->caldavBackend->getCalendarByUri($this->principalInfo['uri'], $name); - if(!empty($calendar)) { + if (!empty($calendar)) { return new Calendar($this->caldavBackend, $calendar, $this->l10n, $this->config, $this->logger); } } diff --git a/apps/dav/lib/CalDAV/CalendarImpl.php b/apps/dav/lib/CalDAV/CalendarImpl.php index cac9bad0d89a4..e568b8f72a219 100644 --- a/apps/dav/lib/CalDAV/CalendarImpl.php +++ b/apps/dav/lib/CalDAV/CalendarImpl.php @@ -84,7 +84,7 @@ public function getSchedulingTimezone(): ?VTimeZone { /** @var VCalendar $vobj */ $vobj = Reader::read($timezoneProp); $components = $vobj->getComponents(); - if(empty($components)) { + if (empty($components)) { return null; } /** @var VTimeZone $vtimezone */ @@ -96,7 +96,7 @@ public function getSchedulingTimezone(): ?VTimeZone { * @param string $pattern which should match within the $searchProperties * @param array $searchProperties defines the properties within the query pattern should match * @param array $options - optional parameters: - * ['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]] + * ['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]] * @param int|null $limit - limit number of search results * @param int|null $offset - offset for paging of search results * @return array an array of events/journals/todos which are arrays of key-value-pairs @@ -233,7 +233,7 @@ public function handleIMipMessage(string $name, string $calendarData): void { } $iTipMessage->uid = isset($vEvent->{'UID'}) ? $vEvent->{'UID'}->getValue() : ''; $iTipMessage->component = 'VEVENT'; - $iTipMessage->sequence = isset($vEvent->{'SEQUENCE'}) ? (int)$vEvent->{'SEQUENCE'}->getValue() : 0; + $iTipMessage->sequence = isset($vEvent->{'SEQUENCE'}) ? (int) $vEvent->{'SEQUENCE'}->getValue() : 0; $iTipMessage->message = $vObject; $server->server->emit('schedule', [$iTipMessage]); } diff --git a/apps/dav/lib/CalDAV/CalendarManager.php b/apps/dav/lib/CalDAV/CalendarManager.php index a415a830d2ee8..538ee2e5289d5 100644 --- a/apps/dav/lib/CalDAV/CalendarManager.php +++ b/apps/dav/lib/CalDAV/CalendarManager.php @@ -1,4 +1,5 @@ objectData['calendarid']; + return (int) $this->objectData['calendarid']; } public function getPrincipalUri(): string { diff --git a/apps/dav/lib/CalDAV/EventComparisonService.php b/apps/dav/lib/CalDAV/EventComparisonService.php index e3c7749a772fd..63395e7ce1c65 100644 --- a/apps/dav/lib/CalDAV/EventComparisonService.php +++ b/apps/dav/lib/CalDAV/EventComparisonService.php @@ -37,14 +37,14 @@ class EventComparisonService { */ private function removeIfUnchanged(VEvent $filterEvent, array &$eventsToFilter): bool { $filterEventData = []; - foreach(self::EVENT_DIFF as $eventDiff) { + foreach (self::EVENT_DIFF as $eventDiff) { $filterEventData[] = IMipService::readPropertyWithDefault($filterEvent, $eventDiff, ''); } /** @var VEvent $component */ foreach ($eventsToFilter as $k => $eventToFilter) { $eventToFilterData = []; - foreach(self::EVENT_DIFF as $eventDiff) { + foreach (self::EVENT_DIFF as $eventDiff) { $eventToFilterData[] = IMipService::readPropertyWithDefault($eventToFilter, $eventDiff, ''); } // events are identical and can be removed @@ -73,23 +73,23 @@ public function findModified(VCalendar $new, ?VCalendar $old): array { $newEventComponents = $new->getComponents(); foreach ($newEventComponents as $k => $event) { - if(!$event instanceof VEvent) { + if (!$event instanceof VEvent) { unset($newEventComponents[$k]); } } - if(empty($old)) { + if (empty($old)) { return ['old' => null, 'new' => $newEventComponents]; } $oldEventComponents = $old->getComponents(); - if(is_array($oldEventComponents) && !empty($oldEventComponents)) { + if (is_array($oldEventComponents) && !empty($oldEventComponents)) { foreach ($oldEventComponents as $k => $event) { - if(!$event instanceof VEvent) { + if (!$event instanceof VEvent) { unset($oldEventComponents[$k]); continue; } - if($this->removeIfUnchanged($event, $newEventComponents)) { + if ($this->removeIfUnchanged($event, $newEventComponents)) { unset($oldEventComponents[$k]); } } diff --git a/apps/dav/lib/CalDAV/EventReader.php b/apps/dav/lib/CalDAV/EventReader.php index b1a4aac26d7fd..008e43fe52f3d 100644 --- a/apps/dav/lib/CalDAV/EventReader.php +++ b/apps/dav/lib/CalDAV/EventReader.php @@ -67,8 +67,8 @@ class EventReader { * @since 30.0.0 * * @param VCalendar|VEvent|Array|String $input - * @param string|null $uid - * @param DateTimeZone|null $timeZone reference timezone for floating dates and times + * @param string|null $uid + * @param DateTimeZone|null $timeZone reference timezone for floating dates and times */ public function __construct(VCalendar|VEvent|array|string $input, ?string $uid = null, ?DateTimeZone $timeZone = null) { @@ -308,9 +308,9 @@ public function recurs(): bool { * * @since 30.0.0 * - * @return string|null R - Relative or A - Absolute + * @return string|null R - Relative or A - Absolute */ - public function recurringPattern(): string | null { + public function recurringPattern(): string|null { if ($this->rruleIterator === null && $this->rdateIterator === null) { return null; } @@ -325,9 +325,9 @@ public function recurringPattern(): string | null { * * @since 30.0.0 * - * @return string|null daily, weekly, monthly, yearly, fixed + * @return string|null daily, weekly, monthly, yearly, fixed */ - public function recurringPrecision(): string | null { + public function recurringPrecision(): string|null { if ($this->rruleIterator !== null) { return $this->rruleIterator->precision(); } @@ -344,7 +344,7 @@ public function recurringPrecision(): string | null { * * @return int|null */ - public function recurringInterval(): int | null { + public function recurringInterval(): int|null { return $this->rruleIterator?->interval(); } @@ -387,7 +387,7 @@ public function recurringConcludes(): bool { * * @return int|null */ - public function recurringConcludesAfter(): int | null { + public function recurringConcludesAfter(): int|null { // construct count place holder $count = 0; @@ -412,7 +412,7 @@ public function recurringConcludesAfter(): int | null { * * @return DateTime|null */ - public function recurringConcludesOn(): DateTime | null { + public function recurringConcludesOn(): DateTime|null { if ($this->rruleIterator !== null) { // retrieve rrule conclusion date @@ -639,7 +639,7 @@ public function recurringRelativePositionNamed(): array { * * @return DateTime */ - public function recurrenceDate(): DateTime | null { + public function recurrenceDate(): DateTime|null { if ($this->recurrenceCurrentDate !== null) { return DateTime::createFromInterface($this->recurrenceCurrentDate); } else { @@ -758,7 +758,7 @@ public function recurrenceAdvance(): void { * * @since 30.0.0 * - * @param DateTimeInterface $dt date and time to advance + * @param DateTimeInterface $dt date and time to advance * * @return void */ diff --git a/apps/dav/lib/CalDAV/EventReaderRDate.php b/apps/dav/lib/CalDAV/EventReaderRDate.php index 65362be4b070c..9d9669dc0f346 100644 --- a/apps/dav/lib/CalDAV/EventReaderRDate.php +++ b/apps/dav/lib/CalDAV/EventReaderRDate.php @@ -13,15 +13,15 @@ class EventReaderRDate extends \Sabre\VObject\Recur\RDateIterator { - public function concludes(): DateTime | null { + public function concludes(): DateTime|null { return $this->concludesOn(); } - public function concludesAfter(): int | null { + public function concludesAfter(): int|null { return !empty($this->dates) ? count($this->dates) : null; } - public function concludesOn(): DateTime | null { + public function concludesOn(): DateTime|null { if (count($this->dates) > 0) { return new DateTime( $this->dates[array_key_last($this->dates)], diff --git a/apps/dav/lib/CalDAV/EventReaderRRule.php b/apps/dav/lib/CalDAV/EventReaderRRule.php index fa47930caa801..fc229ddcd4464 100644 --- a/apps/dav/lib/CalDAV/EventReaderRRule.php +++ b/apps/dav/lib/CalDAV/EventReaderRRule.php @@ -22,7 +22,7 @@ public function interval(): int { return $this->interval; } - public function concludes(): DateTime | null { + public function concludes(): DateTime|null { // evaluate if until value is a date if ($this->until instanceof DateTimeInterface) { return DateTime::createFromInterface($this->until); @@ -48,11 +48,11 @@ public function concludes(): DateTime | null { return null; } - public function concludesAfter(): int | null { + public function concludesAfter(): int|null { return !empty($this->count) ? $this->count : null; } - public function concludesOn(): DateTime | null { + public function concludesOn(): DateTime|null { return isset($this->until) ? DateTime::createFromInterface($this->until) : null; } diff --git a/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php b/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php index 2b4f8ed02238d..20138b4edf8c6 100644 --- a/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php +++ b/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php @@ -1,4 +1,5 @@ l('weekdayName', $dt, ['width' => 'abbreviated']); + return (string) $l10n->l('weekdayName', $dt, ['width' => 'abbreviated']); } private function getDateString(IL10N $l10n, DateTime $dt):string { - return (string)$l10n->l('date', $dt, ['width' => 'medium']); + return (string) $l10n->l('date', $dt, ['width' => 'medium']); } private function getDateTimeString(IL10N $l10n, DateTime $dt):string { - return (string)$l10n->l('datetime', $dt, ['width' => 'medium|short']); + return (string) $l10n->l('datetime', $dt, ['width' => 'medium|short']); } private function getTimeString(IL10N $l10n, DateTime $dt):string { - return (string)$l10n->l('time', $dt, ['width' => 'short']); + return (string) $l10n->l('time', $dt, ['width' => 'short']); } private function getTitleFromVEvent(VEvent $vevent, IL10N $l10n):string { if (isset($vevent->SUMMARY)) { - return (string)$vevent->SUMMARY; + return (string) $vevent->SUMMARY; } return $l10n->t('Untitled event'); diff --git a/apps/dav/lib/CalDAV/Reminder/Notifier.php b/apps/dav/lib/CalDAV/Reminder/Notifier.php index f3c784ea21f8a..216729f830201 100644 --- a/apps/dav/lib/CalDAV/Reminder/Notifier.php +++ b/apps/dav/lib/CalDAV/Reminder/Notifier.php @@ -292,7 +292,7 @@ private function isDayEqual(DateTime $dtStart, * @return string */ private function getWeekDayName(DateTime $dt):string { - return (string)$this->l10n->l('weekdayName', $dt, ['width' => 'abbreviated']); + return (string) $this->l10n->l('weekdayName', $dt, ['width' => 'abbreviated']); } /** @@ -300,7 +300,7 @@ private function getWeekDayName(DateTime $dt):string { * @return string */ private function getDateString(DateTime $dt):string { - return (string)$this->l10n->l('date', $dt, ['width' => 'medium']); + return (string) $this->l10n->l('date', $dt, ['width' => 'medium']); } /** @@ -308,7 +308,7 @@ private function getDateString(DateTime $dt):string { * @return string */ private function getDateTimeString(DateTime $dt):string { - return (string)$this->l10n->l('datetime', $dt, ['width' => 'medium|short']); + return (string) $this->l10n->l('datetime', $dt, ['width' => 'medium|short']); } /** @@ -316,6 +316,6 @@ private function getDateTimeString(DateTime $dt):string { * @return string */ private function getTimeString(DateTime $dt):string { - return (string)$this->l10n->l('time', $dt, ['width' => 'short']); + return (string) $this->l10n->l('time', $dt, ['width' => 'short']); } } diff --git a/apps/dav/lib/CalDAV/Reminder/ReminderService.php b/apps/dav/lib/CalDAV/Reminder/ReminderService.php index be81e534dd347..35a179deabce9 100644 --- a/apps/dav/lib/CalDAV/Reminder/ReminderService.php +++ b/apps/dav/lib/CalDAV/Reminder/ReminderService.php @@ -447,7 +447,7 @@ private function writeRemindersToDatabase(array $reminders): void { $uniqueReminders = []; foreach ($reminders as $reminder) { $key = $reminder['notification_date']. $reminder['event_hash'].$reminder['type']; - if(!isset($uniqueReminders[$key])) { + if (!isset($uniqueReminders[$key])) { $uniqueReminders[$key] = $reminder; } } diff --git a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php index 2eb8ebfc84edf..0824c2340dd2c 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php @@ -1,4 +1,5 @@ executeQuery(); } catch (Exception $e) { - $this->logger->error("Could not search resources: " . $e->getMessage(), ['exception' => $e]); + $this->logger->error('Could not search resources: ' . $e->getMessage(), ['exception' => $e]); } $rows = []; diff --git a/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php index 40396f67ce93c..c70d93daf5229 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php @@ -1,4 +1,5 @@ scheduleStatus = '5.0; EMail delivery failed'; return; } - $recipientName = $iTipMessage->recipientName ? (string)$iTipMessage->recipientName : null; + $recipientName = $iTipMessage->recipientName ? (string) $iTipMessage->recipientName : null; $newEvents = $iTipMessage->message; $oldEvents = $this->getVCalendar(); @@ -152,7 +152,7 @@ public function schedule(Message $iTipMessage) { // No changed events after all - this shouldn't happen if there is significant change yet here we are // The scheduling status is debatable - if(empty($vEvent)) { + if (empty($vEvent)) { $this->logger->warning('iTip message said the change was significant but comparison did not detect any updated VEvents'); $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email'; return; @@ -164,14 +164,14 @@ public function schedule(Message $iTipMessage) { // we also might not have an old event as this could be a new // invitation, or a new recurrence exception $attendee = $this->imipService->getCurrentAttendee($iTipMessage); - if($attendee === null) { + if ($attendee === null) { $uid = $vEvent->UID ?? 'no UID found'; $this->logger->debug('Could not find recipient ' . $recipient . ' as attendee for event with UID ' . $uid); $iTipMessage->scheduleStatus = '5.0; EMail delivery failed'; return; } // Don't send emails to things - if($this->imipService->isRoomOrResource($attendee)) { + if ($this->imipService->isRoomOrResource($attendee)) { $this->logger->debug('No invitation sent as recipient is room or resource', [ 'attendee' => $recipient, ]); diff --git a/apps/dav/lib/CalDAV/Schedule/IMipService.php b/apps/dav/lib/CalDAV/Schedule/IMipService.php index 81367d76ebe44..137fb3585a368 100644 --- a/apps/dav/lib/CalDAV/Schedule/IMipService.php +++ b/apps/dav/lib/CalDAV/Schedule/IMipService.php @@ -89,7 +89,7 @@ private function generateDiffString(VEvent $vevent, VEvent $oldVEvent, string $p return $default; } $newstring = $vevent->$property->getValue(); - if(isset($oldVEvent->$property) && $oldVEvent->$property->getValue() !== $newstring) { + if (isset($oldVEvent->$property) && $oldVEvent->$property->getValue() !== $newstring) { $oldstring = $oldVEvent->$property->getValue(); return sprintf($strikethrough, $oldstring, $newstring); } @@ -144,7 +144,7 @@ public function buildBodyData(VEvent $vEvent, ?VEvent $oldVEvent): array { $data = []; $data['meeting_when'] = $this->generateWhenString($eventReaderCurrent); - foreach(self::STRING_DIFF as $key => $property) { + foreach (self::STRING_DIFF as $key => $property) { $data[$key] = self::readPropertyWithDefault($vEvent, $property, $defaultVal); } @@ -154,7 +154,7 @@ public function buildBodyData(VEvent $vEvent, ?VEvent $oldVEvent): array { $data['meeting_location_html'] = $locationHtml; } - if(!empty($oldVEvent)) { + if (!empty($oldVEvent)) { $oldMeetingWhen = $this->generateWhenString($eventReaderPrevious); $data['meeting_title_html'] = $this->generateDiffString($vEvent, $oldVEvent, 'SUMMARY', $data['meeting_title']); $data['meeting_description_html'] = $this->generateDiffString($vEvent, $oldVEvent, 'DESCRIPTION', $data['meeting_description']); @@ -336,7 +336,7 @@ public function generateWhenStringRecurring(EventReader $er): string { public function generateWhenStringRecurringDaily(EventReader $er): string { // initialize - $interval = (int)$er->recurringInterval(); + $interval = (int) $er->recurringInterval(); $startTime = null; $conclusion = null; // time of the day @@ -387,7 +387,7 @@ public function generateWhenStringRecurringDaily(EventReader $er): string { public function generateWhenStringRecurringWeekly(EventReader $er): string { // initialize - $interval = (int)$er->recurringInterval(); + $interval = (int) $er->recurringInterval(); $startTime = null; $conclusion = null; // days of the week @@ -440,7 +440,7 @@ public function generateWhenStringRecurringWeekly(EventReader $er): string { public function generateWhenStringRecurringMonthly(EventReader $er): string { // initialize - $interval = (int)$er->recurringInterval(); + $interval = (int) $er->recurringInterval(); $startTime = null; $conclusion = null; // days of month @@ -505,7 +505,7 @@ public function generateWhenStringRecurringMonthly(EventReader $er): string { public function generateWhenStringRecurringYearly(EventReader $er): string { // initialize - $interval = (int)$er->recurringInterval(); + $interval = (int) $er->recurringInterval(); $startTime = null; $conclusion = null; // months of year @@ -777,10 +777,10 @@ public function buildCancelledBodyData(VEvent $vEvent): array { $strikethrough = "%s"; $newMeetingWhen = $this->generateWhenString($eventReaderCurrent); - $newSummary = isset($vEvent->SUMMARY) && (string)$vEvent->SUMMARY !== '' ? (string)$vEvent->SUMMARY : $this->l10n->t('Untitled event'); - $newDescription = isset($vEvent->DESCRIPTION) && (string)$vEvent->DESCRIPTION !== '' ? (string)$vEvent->DESCRIPTION : $defaultVal; - $newUrl = isset($vEvent->URL) && (string)$vEvent->URL !== '' ? sprintf('%1$s', $vEvent->URL) : $defaultVal; - $newLocation = isset($vEvent->LOCATION) && (string)$vEvent->LOCATION !== '' ? (string)$vEvent->LOCATION : $defaultVal; + $newSummary = isset($vEvent->SUMMARY) && (string) $vEvent->SUMMARY !== '' ? (string) $vEvent->SUMMARY : $this->l10n->t('Untitled event'); + $newDescription = isset($vEvent->DESCRIPTION) && (string) $vEvent->DESCRIPTION !== '' ? (string) $vEvent->DESCRIPTION : $defaultVal; + $newUrl = isset($vEvent->URL) && (string) $vEvent->URL !== '' ? sprintf('%1$s', $vEvent->URL) : $defaultVal; + $newLocation = isset($vEvent->LOCATION) && (string) $vEvent->LOCATION !== '' ? (string) $vEvent->LOCATION : $defaultVal; $newLocationHtml = $this->linkify($newLocation) ?? $newLocation; $data = []; @@ -791,7 +791,7 @@ public function buildCancelledBodyData(VEvent $vEvent): array { $data['meeting_description_html'] = $newDescription !== '' ? sprintf($strikethrough, $newDescription) : ''; $data['meeting_description'] = $newDescription; $data['meeting_url_html'] = $newUrl !== '' ? sprintf($strikethrough, $newUrl) : ''; - $data['meeting_url'] = isset($vEvent->URL) ? (string)$vEvent->URL : ''; + $data['meeting_url'] = isset($vEvent->URL) ? (string) $vEvent->URL : ''; $data['meeting_location_html'] = $newLocationHtml !== '' ? sprintf($strikethrough, $newLocationHtml) : ''; $data['meeting_location'] = $newLocation; return $data; @@ -808,7 +808,7 @@ public function getLastOccurrence(VCalendar $vObject) { $component = $vObject->VEVENT; if (isset($component->RRULE)) { - $it = new EventIterator($vObject, (string)$component->UID); + $it = new EventIterator($vObject, (string) $component->UID); $maxDate = new \DateTime(IMipPlugin::MAX_DATE); if ($it->isInfinite()) { return $maxDate->getTimestamp(); @@ -831,7 +831,7 @@ public function getLastOccurrence(VCalendar $vObject) { return $dtEnd->getDateTime()->getTimeStamp(); } - if(isset($component->DURATION)) { + if (isset($component->DURATION)) { /** @var \DateTime $endDate */ $endDate = clone $dtStart->getDateTime(); // $component->DTEND->getDateTime() returns DateTimeImmutable @@ -839,7 +839,7 @@ public function getLastOccurrence(VCalendar $vObject) { return $endDate->getTimestamp(); } - if(!$dtStart->hasTime()) { + if (!$dtStart->hasTime()) { /** @var \DateTime $endDate */ // $component->DTSTART->getDateTime() returns DateTimeImmutable $endDate = clone $dtStart->getDateTime(); @@ -855,7 +855,7 @@ public function getLastOccurrence(VCalendar $vObject) { * @param Property|null $attendee */ public function setL10n(?Property $attendee = null) { - if($attendee === null) { + if ($attendee === null) { return; } @@ -871,7 +871,7 @@ public function setL10n(?Property $attendee = null) { * @return bool */ public function getAttendeeRsvpOrReqForParticipant(?Property $attendee = null) { - if($attendee === null) { + if ($attendee === null) { return false; } @@ -979,10 +979,10 @@ public function addAttendees(IEMailTemplate $template, VEvent $vevent) { htmlspecialchars($organizer->getNormalizedValue()), htmlspecialchars($organizerName ?: $organizerEmail)); $organizerText = sprintf('%s <%s>', $organizerName, $organizerEmail); - if(isset($organizer['PARTSTAT'])) { + if (isset($organizer['PARTSTAT'])) { /** @var Parameter $partstat */ $partstat = $organizer['PARTSTAT']; - if(strcasecmp($partstat->getValue(), 'ACCEPTED') === 0) { + if (strcasecmp($partstat->getValue(), 'ACCEPTED') === 0) { $organizerHTML .= ' ✔︎'; $organizerText .= ' ✔︎'; } @@ -1154,7 +1154,7 @@ public function getReplyingAttendee(Message $iTipMessage): ?Property { public function isRoomOrResource(Property $attendee): bool { $cuType = $attendee->offsetGet('CUTYPE'); - if(!$cuType instanceof Parameter) { + if (!$cuType instanceof Parameter) { return false; } $type = $cuType->getValue() ?? 'INDIVIDUAL'; @@ -1178,7 +1178,7 @@ public function minimizeInterval(\DateInterval $dateInterval): array { $interval = $dateInterval->m; $scale = 'month'; } elseif ($dateInterval->d >= 7) { - $interval = (int)($dateInterval->d / 7); + $interval = (int) ($dateInterval->d / 7); $scale = 'week'; } elseif ($dateInterval->d > 0) { $interval = $dateInterval->d; diff --git a/apps/dav/lib/CalDAV/Search/SearchPlugin.php b/apps/dav/lib/CalDAV/Search/SearchPlugin.php index fb55dec593c86..a081045814510 100644 --- a/apps/dav/lib/CalDAV/Search/SearchPlugin.php +++ b/apps/dav/lib/CalDAV/Search/SearchPlugin.php @@ -1,4 +1,5 @@ userManager->get($userId); - if($user === null) { + if ($user === null) { return; } $availability = $this->availabilityCoordinator->getCurrentOutOfOfficeData($user); - if($availability !== null && $this->availabilityCoordinator->isInEffect($availability)) { + if ($availability !== null && $this->availabilityCoordinator->isInEffect($availability)) { $this->logger->debug('An Absence is in effect, skipping calendar status check', ['user' => $userId]); return; } $calendarEvents = $this->cache->get($userId); - if($calendarEvents === null) { + if ($calendarEvents === null) { $calendarEvents = $this->getCalendarEvents($user); $this->cache->set($userId, $calendarEvents, 300); } - if(empty($calendarEvents)) { + if (empty($calendarEvents)) { try { $this->userStatusService->revertUserStatus($userId, IUserStatus::MESSAGE_CALENDAR_BUSY); } catch (Exception $e) { @@ -81,7 +81,7 @@ public function processCalendarStatus(string $userId): void { $currentStatus = null; } - if(($currentStatus !== null && $currentStatus->getMessageId() === IUserStatus::MESSAGE_CALL) + if (($currentStatus !== null && $currentStatus->getMessageId() === IUserStatus::MESSAGE_CALL) || ($currentStatus !== null && $currentStatus->getStatus() === IUserStatus::DND) || ($currentStatus !== null && $currentStatus->getStatus() === IUserStatus::INVISIBLE)) { // We don't overwrite the call status, DND status or Invisible status @@ -101,7 +101,7 @@ public function processCalendarStatus(string $userId): void { if (isset($component['DTSTART']) && $userStatusTimestamp !== null) { /** @var DateTimeImmutable $dateTime */ $dateTime = $component['DTSTART'][0]; - if($dateTime instanceof DateTimeImmutable && $userStatusTimestamp > $dateTime->getTimestamp()) { + if ($dateTime instanceof DateTimeImmutable && $userStatusTimestamp > $dateTime->getTimestamp()) { return false; } } @@ -112,7 +112,7 @@ public function processCalendarStatus(string $userId): void { return true; }); - if(empty($applicableEvents)) { + if (empty($applicableEvents)) { try { $this->userStatusService->revertUserStatus($userId, IUserStatus::MESSAGE_CALENDAR_BUSY); } catch (Exception $e) { @@ -130,7 +130,7 @@ public function processCalendarStatus(string $userId): void { } // Only update the status if it's neccesary otherwise we mess up the timestamp - if($currentStatus === null || $currentStatus->getMessageId() !== IUserStatus::MESSAGE_CALENDAR_BUSY) { + if ($currentStatus === null || $currentStatus->getMessageId() !== IUserStatus::MESSAGE_CALENDAR_BUSY) { // One event that fulfills all status conditions is enough // 1. Not an OOO event // 2. Current user status (that is not a calendar status) was not set after the start of this event @@ -148,7 +148,7 @@ public function processCalendarStatus(string $userId): void { private function getCalendarEvents(User $user): array { $calendars = $this->calendarManager->getCalendarsForPrincipal('principals/users/' . $user->getUID()); - if(empty($calendars)) { + if (empty($calendars)) { return []; } @@ -172,7 +172,7 @@ private function getCalendarEvents(User $user): array { $dtEnd = DateTimeImmutable::createFromMutable($this->timeFactory->getDateTime('+5 minutes')); // Only query the calendars when there's any to search - if($query instanceof CalendarQuery && !empty($query->getCalendarUris())) { + if ($query instanceof CalendarQuery && !empty($query->getCalendarUris())) { // Query the next hour $query->setTimerangeStart($dtStart); $query->setTimerangeEnd($dtEnd); diff --git a/apps/dav/lib/CalDAV/WebcalCaching/Plugin.php b/apps/dav/lib/CalDAV/WebcalCaching/Plugin.php index ea1bf7d4f0ff8..e07be39c7b464 100644 --- a/apps/dav/lib/CalDAV/WebcalCaching/Plugin.php +++ b/apps/dav/lib/CalDAV/WebcalCaching/Plugin.php @@ -28,9 +28,9 @@ class Plugin extends ServerPlugin { * @var string[] */ public const ENABLE_FOR_CLIENTS = [ - "/^MSFT-WIN-3/", - "/Evolution/", - "/KIO/" + '/^MSFT-WIN-3/', + '/Evolution/', + '/KIO/' ]; /** diff --git a/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php b/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php index 14c72285f67a3..07cb4a28a8e20 100644 --- a/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php +++ b/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php @@ -45,12 +45,12 @@ public function refreshSubscription(string $principalUri, string $uri) { } // Check the refresh rate if there is any - if(!empty($subscription['{http://apple.com/ns/ical/}refreshrate'])) { + if (!empty($subscription['{http://apple.com/ns/ical/}refreshrate'])) { // add the refresh interval to the lastmodified timestamp $refreshInterval = new \DateInterval($subscription['{http://apple.com/ns/ical/}refreshrate']); $updateTime = $this->time->getDateTime(); $updateTime->setTimestamp($subscription['lastmodified'])->add($refreshInterval); - if($updateTime->getTimestamp() > $this->time->getTime()) { + if ($updateTime->getTimestamp() > $this->time->getTime()) { return; } } @@ -131,7 +131,7 @@ public function refreshSubscription(string $principalUri, string $uri) { try { $objectUri = $this->getRandomCalendarObjectUri(); $this->calDavBackend->createCalendarObject($subscription['id'], $objectUri, $vObject->serialize(), CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION); - } catch (NoInstancesException | BadRequest $ex) { + } catch (NoInstancesException|BadRequest $ex) { $this->logger->warning('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $ex, 'subscriptionId' => $subscription['id'], 'source' => $subscription['source']]); } } @@ -143,7 +143,7 @@ public function refreshSubscription(string $principalUri, string $uri) { return $dataSet['uri']; }, $localData); - if(!empty($ids) && !empty($uris)) { + if (!empty($ids) && !empty($uris)) { // Clean up on aisle 5 // The only events left over in the $localData array should be those that don't exist upstream // All deleted VObjects from upstream are removed @@ -157,7 +157,7 @@ public function refreshSubscription(string $principalUri, string $uri) { $this->updateSubscription($subscription, $mutations); } catch (ParseException $ex) { - $this->logger->error("Subscription {subscriptionId} could not be refreshed due to a parsing error", ['exception' => $ex, 'subscriptionId' => $subscription['id']]); + $this->logger->error('Subscription {subscriptionId} could not be refreshed due to a parsing error', ['exception' => $ex, 'subscriptionId' => $subscription['id']]); } } diff --git a/apps/dav/lib/Capabilities.php b/apps/dav/lib/Capabilities.php index c951c261115ce..3a1a9879e2dbf 100644 --- a/apps/dav/lib/Capabilities.php +++ b/apps/dav/lib/Capabilities.php @@ -1,4 +1,5 @@ 'addressbook', - 'id' => (string)$data['id'], + 'id' => (string) $data['id'], 'name' => $l->t('Personal'), ]; } return [ 'type' => 'addressbook', - 'id' => (string)$data['id'], + 'id' => (string) $data['id'], 'name' => $data['name'], ]; } diff --git a/apps/dav/lib/CardDAV/Activity/Setting.php b/apps/dav/lib/CardDAV/Activity/Setting.php index aa25898065fd7..cc68cf87c8383 100644 --- a/apps/dav/lib/CardDAV/Activity/Setting.php +++ b/apps/dav/lib/CardDAV/Activity/Setting.php @@ -27,8 +27,8 @@ public function getName(): string { /** * @return int whether the filter should be rather on the top or bottom of - * the admin section. The filters are arranged in ascending order of the - * priority values. It is required to return a value between 0 and 100. + * the admin section. The filters are arranged in ascending order of the + * priority values. It is required to return a value between 0 and 100. */ public function getPriority(): int { return 50; diff --git a/apps/dav/lib/CardDAV/AddressBook.php b/apps/dav/lib/CardDAV/AddressBook.php index 2ec645f04d231..c48f036f2bfdd 100644 --- a/apps/dav/lib/CardDAV/AddressBook.php +++ b/apps/dav/lib/CardDAV/AddressBook.php @@ -250,7 +250,7 @@ public function moveInto($targetName, $sourcePath, INode $sourceNode) { } try { - return $this->carddavBackend->moveCard($sourceNode->getAddressbookId(), (int)$this->addressBookInfo['id'], $sourceNode->getUri(), $sourceNode->getOwner()); + return $this->carddavBackend->moveCard($sourceNode->getAddressbookId(), (int) $this->addressBookInfo['id'], $sourceNode->getUri(), $sourceNode->getOwner()); } catch (Exception $e) { // Avoid injecting LoggerInterface everywhere Server::get(LoggerInterface::class)->error('Could not move calendar object: ' . $e->getMessage(), ['exception' => $e]); diff --git a/apps/dav/lib/CardDAV/AddressBookImpl.php b/apps/dav/lib/CardDAV/AddressBookImpl.php index 44ff7b40752a1..36bc30e02f956 100644 --- a/apps/dav/lib/CardDAV/AddressBookImpl.php +++ b/apps/dav/lib/CardDAV/AddressBookImpl.php @@ -91,19 +91,19 @@ public function getDisplayName() { * @param string $pattern which should match within the $searchProperties * @param array $searchProperties defines the properties within the query pattern should match * @param array $options Options to define the output format and search behavior - * - 'types' boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array - * example: ['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['type => 'HOME', 'value' => 'g@h.i']] - * - 'escape_like_param' - If set to false wildcards _ and % are not escaped - * - 'limit' - Set a numeric limit for the search results - * - 'offset' - Set the offset for the limited search results - * - 'wildcard' - Whether the search should use wildcards + * - 'types' boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array + * example: ['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['type => 'HOME', 'value' => 'g@h.i']] + * - 'escape_like_param' - If set to false wildcards _ and % are not escaped + * - 'limit' - Set a numeric limit for the search results + * - 'offset' - Set the offset for the limited search results + * - 'wildcard' - Whether the search should use wildcards * @psalm-param array{types?: bool, escape_like_param?: bool, limit?: int, offset?: int, wildcard?: bool} $options * @return array an array of contacts which are arrays of key-value-pairs - * example result: - * [ - * ['id' => 0, 'FN' => 'Thomas Müller', 'EMAIL' => 'a@b.c', 'GEO' => '37.386013;-122.082932'], - * ['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['d@e.f', 'g@h.i']] - * ] + * example result: + * [ + * ['id' => 0, 'FN' => 'Thomas Müller', 'EMAIL' => 'a@b.c', 'GEO' => '37.386013;-122.082932'], + * ['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['d@e.f', 'g@h.i']] + * ] * @since 5.0.0 */ public function search($pattern, $searchProperties, $options) { @@ -144,13 +144,13 @@ public function createOrUpdate($properties) { if (is_string($entry)) { $property = $vCard->createProperty($key, $entry); } else { - if (($key === "ADR" || $key === "PHOTO") && is_string($entry["value"])) { - $entry["value"] = stripslashes($entry["value"]); - $entry["value"] = explode(';', $entry["value"]); + if (($key === 'ADR' || $key === 'PHOTO') && is_string($entry['value'])) { + $entry['value'] = stripslashes($entry['value']); + $entry['value'] = explode(';', $entry['value']); } - $property = $vCard->createProperty($key, $entry["value"]); - if (isset($entry["type"])) { - $property->add('TYPE', $entry["type"]); + $property = $vCard->createProperty($key, $entry['value']); + if (isset($entry['type'])) { + $property->add('TYPE', $entry['type']); } } $vCard->add($property); @@ -353,7 +353,7 @@ public function isEnabled(): bool { $path = 'addressbooks/users/' . $user . '/' . $uri; $properties = $this->propertyMapper->findPropertyByPathAndName($user, $path, '{http://owncloud.org/ns}enabled'); if (count($properties) > 0) { - return (bool)$properties[0]->getPropertyvalue(); + return (bool) $properties[0]->getPropertyvalue(); } return true; } diff --git a/apps/dav/lib/CardDAV/Card.php b/apps/dav/lib/CardDAV/Card.php index 67f605d2fb4c5..218684ed832d8 100644 --- a/apps/dav/lib/CardDAV/Card.php +++ b/apps/dav/lib/CardDAV/Card.php @@ -26,7 +26,7 @@ protected function isShared(): bool { } public function getAddressbookId(): int { - return (int)$this->cardData['addressbookid']; + return (int) $this->cardData['addressbookid']; } public function getPrincipalUri(): string { diff --git a/apps/dav/lib/CardDAV/CardDavBackend.php b/apps/dav/lib/CardDAV/CardDavBackend.php index 9d787c917d34f..90d54329b995e 100644 --- a/apps/dav/lib/CardDAV/CardDavBackend.php +++ b/apps/dav/lib/CardDAV/CardDavBackend.php @@ -154,7 +154,7 @@ public function getAddressBooksForUser($principalUri) { continue; } - $readOnly = (int)$row['access'] === Backend::ACCESS_READ; + $readOnly = (int) $row['access'] === Backend::ACCESS_READ; if (isset($addressBooks[$row['id']])) { if ($readOnly) { // New share can not have more permissions then the old one. @@ -330,14 +330,14 @@ public function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatc $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId))) ->executeStatement(); - $this->addChange($addressBookId, "", 2); + $this->addChange($addressBookId, '', 2); - $addressBookRow = $this->getAddressBookById((int)$addressBookId); - $shares = $this->getShares((int)$addressBookId); + $addressBookRow = $this->getAddressBookById((int) $addressBookId); + $shares = $this->getShares((int) $addressBookId); return [$addressBookRow, $shares]; }, $this->db); - $this->dispatcher->dispatchTyped(new AddressBookUpdatedEvent((int)$addressBookId, $addressBookRow, $shares, $mutations)); + $this->dispatcher->dispatchTyped(new AddressBookUpdatedEvent((int) $addressBookId, $addressBookRow, $shares, $mutations)); return true; }); @@ -417,7 +417,7 @@ public function createAddressBook($principalUri, $url, array $properties) { */ public function deleteAddressBook($addressBookId) { $this->atomic(function () use ($addressBookId) { - $addressBookId = (int)$addressBookId; + $addressBookId = (int) $addressBookId; $addressBookData = $this->getAddressBookById($addressBookId); $shares = $this->getShares($addressBookId); @@ -616,7 +616,7 @@ public function createCard($addressBookId, $cardUri, $cardData, bool $checkAlrea ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid))) ->setMaxResults(1); $result = $q->executeQuery(); - $count = (bool)$result->fetchOne(); + $count = (bool) $result->fetchOne(); $result->closeCursor(); if ($count) { throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.'); @@ -729,7 +729,7 @@ public function moveCard(int $sourceAddressBookId, int $targetAddressBookId, str ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($sourceAddressBookId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT)) ->executeStatement(); - $this->purgeProperties($sourceAddressBookId, (int)$card['id']); + $this->purgeProperties($sourceAddressBookId, (int) $card['id']); $this->updateProperties($sourceAddressBookId, $card['uri'], $card['carddata']); $this->addChange($sourceAddressBookId, $card['uri'], 3); @@ -945,7 +945,7 @@ protected function addChange(int $addressBookId, string $objectUri, int $operati ->from('addressbooks') ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId))); $result = $query->executeQuery(); - $syncToken = (int)$result->fetchOne(); + $syncToken = (int) $result->fetchOne(); $result->closeCursor(); $query = $this->db->getQueryBuilder(); @@ -1032,11 +1032,11 @@ public function updateShares(IShareable $shareable, array $add, array $remove): * @param string $pattern which should match within the $searchProperties * @param array $searchProperties defines the properties within the query pattern should match * @param array $options = array() to define the search behavior - * - 'types' boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array - * - 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are - * - 'limit' - Set a numeric limit for the search results - * - 'offset' - Set the offset for the limited search results - * - 'wildcard' - Whether the search should use wildcards + * - 'types' boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array + * - 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are + * - 'limit' - Set a numeric limit for the search results + * - 'offset' - Set the offset for the limited search results + * - 'wildcard' - Whether the search should use wildcards * @psalm-param array{types?: bool, escape_like_param?: bool, limit?: int, offset?: int, wildcard?: bool} $options * @return array an array of contacts which are arrays of key-value-pairs */ @@ -1169,7 +1169,7 @@ private function searchByAddressBookIds(array $addressBookIds, $matches = $result->fetchAll(); $result->closeCursor(); $matches = array_map(function ($match) { - return (int)$match['cardid']; + return (int) $match['cardid']; }, $matches); $cards = []; @@ -1370,7 +1370,7 @@ protected function getCardId(int $addressBookId, string $uri): int { throw new \InvalidArgumentException('Card does not exists: ' . $uri); } - return (int)$cardIds['id']; + return (int) $cardIds['id']; } /** diff --git a/apps/dav/lib/CardDAV/ContactsManager.php b/apps/dav/lib/CardDAV/ContactsManager.php index 14bf8db7be58d..c4751497a6796 100644 --- a/apps/dav/lib/CardDAV/ContactsManager.php +++ b/apps/dav/lib/CardDAV/ContactsManager.php @@ -13,13 +13,13 @@ use OCP\IURLGenerator; class ContactsManager { - /** @var CardDavBackend */ + /** @var CardDavBackend */ private $backend; - /** @var IL10N */ + /** @var IL10N */ private $l10n; - /** @var PropertyMapper */ + /** @var PropertyMapper */ private $propertyMapper; /** @@ -51,7 +51,7 @@ public function setupContactsProvider(IManager $cm, $userId, IURLGenerator $urlG * @param IURLGenerator $urlGenerator */ public function setupSystemContactsProvider(IManager $cm, ?string $userId, IURLGenerator $urlGenerator) { - $addressBooks = $this->backend->getAddressBooksForUser("principals/system/system"); + $addressBooks = $this->backend->getAddressBooksForUser('principals/system/system'); $this->register($cm, $addressBooks, $urlGenerator, $userId); } diff --git a/apps/dav/lib/CardDAV/ImageExportPlugin.php b/apps/dav/lib/CardDAV/ImageExportPlugin.php index e2173db519be4..cbf78dcc707df 100644 --- a/apps/dav/lib/CardDAV/ImageExportPlugin.php +++ b/apps/dav/lib/CardDAV/ImageExportPlugin.php @@ -55,7 +55,7 @@ public function httpGet(RequestInterface $request, ResponseInterface $response) return true; } - $size = isset($queryParams['size']) ? (int)$queryParams['size'] : -1; + $size = isset($queryParams['size']) ? (int) $queryParams['size'] : -1; $path = $request->getPath(); $node = $this->server->tree->getNodeForPath($path); diff --git a/apps/dav/lib/CardDAV/PhotoCache.php b/apps/dav/lib/CardDAV/PhotoCache.php index 3ea99c29a51bb..83b5f417896ba 100644 --- a/apps/dav/lib/CardDAV/PhotoCache.php +++ b/apps/dav/lib/CardDAV/PhotoCache.php @@ -1,4 +1,5 @@ 'png', 'image/jpeg' => 'jpg', diff --git a/apps/dav/lib/CardDAV/SyncService.php b/apps/dav/lib/CardDAV/SyncService.php index 264d34a150bd7..259ffdf8fda9b 100644 --- a/apps/dav/lib/CardDAV/SyncService.php +++ b/apps/dav/lib/CardDAV/SyncService.php @@ -143,7 +143,7 @@ private function prepareUri(string $host, string $path): string { \GuzzleHttp\Psr7\Utils::uriFor($path) ); - return (string)$uri; + return (string) $uri; } /** @@ -184,7 +184,7 @@ protected function download(string $url, string $userName, string $sharedSecret, $options ); - return (string)$response->getBody(); + return (string) $response->getBody(); } private function buildSyncCollectionRequestBody(?string $syncToken): string { diff --git a/apps/dav/lib/CardDAV/SystemAddressbook.php b/apps/dav/lib/CardDAV/SystemAddressbook.php index 4ba06d0fc9c0e..aff51ac5b9bc3 100644 --- a/apps/dav/lib/CardDAV/SystemAddressbook.php +++ b/apps/dav/lib/CardDAV/SystemAddressbook.php @@ -254,7 +254,7 @@ public function getChanges($syncToken, $syncLevel, $limit = null) { try { $this->getChild($uri); $added[] = $uri; - } catch (NotFound | Forbidden $e) { + } catch (NotFound|Forbidden $e) { $deleted[] = $uri; } } @@ -262,7 +262,7 @@ public function getChanges($syncToken, $syncLevel, $limit = null) { try { $this->getChild($uri); $modified[] = $uri; - } catch (NotFound | Forbidden $e) { + } catch (NotFound|Forbidden $e) { $deleted[] = $uri; } } diff --git a/apps/dav/lib/CardDAV/UserAddressBooks.php b/apps/dav/lib/CardDAV/UserAddressBooks.php index d0719e02492c9..e2d3fe4d8c84d 100644 --- a/apps/dav/lib/CardDAV/UserAddressBooks.php +++ b/apps/dav/lib/CardDAV/UserAddressBooks.php @@ -89,7 +89,7 @@ public function getChildren() { try { $trustedServers = \OC::$server->get(TrustedServers::class); $request = \OC::$server->get(IRequest::class); - } catch (QueryException | NotFoundExceptionInterface | ContainerExceptionInterface $e) { + } catch (QueryException|NotFoundExceptionInterface|ContainerExceptionInterface $e) { // nothing to do, the request / trusted servers don't exist } if ($addressBook['principaluri'] === 'principals/system/system') { diff --git a/apps/dav/lib/Command/CreateAddressBook.php b/apps/dav/lib/Command/CreateAddressBook.php index e7d7824d1b6d1..9626edeba260a 100644 --- a/apps/dav/lib/Command/CreateAddressBook.php +++ b/apps/dav/lib/Command/CreateAddressBook.php @@ -24,14 +24,14 @@ public function __construct( protected function configure(): void { $this - ->setName('dav:create-addressbook') - ->setDescription('Create a dav addressbook') - ->addArgument('user', - InputArgument::REQUIRED, - 'User for whom the addressbook will be created') - ->addArgument('name', - InputArgument::REQUIRED, - 'Name of the addressbook'); + ->setName('dav:create-addressbook') + ->setDescription('Create a dav addressbook') + ->addArgument('user', + InputArgument::REQUIRED, + 'User for whom the addressbook will be created') + ->addArgument('name', + InputArgument::REQUIRED, + 'Name of the addressbook'); } protected function execute(InputInterface $input, OutputInterface $output): int { diff --git a/apps/dav/lib/Command/DeleteCalendar.php b/apps/dav/lib/Command/DeleteCalendar.php index 423a9b0343425..93c901b2ba678 100644 --- a/apps/dav/lib/Command/DeleteCalendar.php +++ b/apps/dav/lib/Command/DeleteCalendar.php @@ -56,7 +56,7 @@ protected function execute( InputInterface $input, OutputInterface $output ): int { - /** @var string $user **/ + /** @var string $user * */ $user = $input->getArgument('uid'); if (!$this->userManager->userExists($user)) { throw new \InvalidArgumentException( @@ -67,7 +67,7 @@ protected function execute( if ($birthday !== false) { $name = BirthdayService::BIRTHDAY_CALENDAR_URI; } else { - /** @var string $name **/ + /** @var string $name * */ $name = $input->getArgument('name'); if (!$name) { throw new \InvalidArgumentException( diff --git a/apps/dav/lib/Command/FixCalendarSyncCommand.php b/apps/dav/lib/Command/FixCalendarSyncCommand.php index 5e92b3270d205..e94e1dc9c4af3 100644 --- a/apps/dav/lib/Command/FixCalendarSyncCommand.php +++ b/apps/dav/lib/Command/FixCalendarSyncCommand.php @@ -56,7 +56,7 @@ public function execute(InputInterface $input, OutputInterface $output): int { } private function fixUserCalendars(IUser $user, ?ProgressBar $progress = null): void { - $calendars = $this->calDavBackend->getCalendarsForUser("principals/users/" . $user->getUID()); + $calendars = $this->calDavBackend->getCalendarsForUser('principals/users/' . $user->getUID()); foreach ($calendars as $calendar) { $this->calDavBackend->restoreChanges($calendar['id']); diff --git a/apps/dav/lib/Command/ListCalendars.php b/apps/dav/lib/Command/ListCalendars.php index 5344530e8a528..af3459686e59c 100644 --- a/apps/dav/lib/Command/ListCalendars.php +++ b/apps/dav/lib/Command/ListCalendars.php @@ -1,4 +1,5 @@ addArgument('destinationuid', InputArgument::REQUIRED, 'User who will receive the calendar') - ->addOption('force', 'f', InputOption::VALUE_NONE, "Force the migration by removing existing shares and renaming calendars in case of conflicts"); + ->addOption('force', 'f', InputOption::VALUE_NONE, 'Force the migration by removing existing shares and renaming calendars in case of conflicts'); } protected function execute(InputInterface $input, OutputInterface $output): int { @@ -97,8 +98,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int * Warn that share links have changed if there are shares */ $this->io->note([ - "Please note that moving calendar " . $calendar['uri'] . " from user <$userOrigin> to <$userDestination> has caused share links to change.", - "Sharees will need to change \"example.com/remote.php/dav/calendars/uid/" . $calendar['uri'] . "_shared_by_$userOrigin\" to \"example.com/remote.php/dav/calendars/uid/" . $newName ?: $calendar['uri'] . "_shared_by_$userDestination\"" + 'Please note that moving calendar ' . $calendar['uri'] . " from user <$userOrigin> to <$userDestination> has caused share links to change.", + 'Sharees will need to change "example.com/remote.php/dav/calendars/uid/' . $calendar['uri'] . "_shared_by_$userOrigin\" to \"example.com/remote.php/dav/calendars/uid/" . $newName ?: $calendar['uri'] . "_shared_by_$userDestination\"" ]); } @@ -155,7 +156,7 @@ private function checkShares(array $calendar, string $userOrigin, string $userDe if ($force) { $this->calDav->updateShares(new Calendar($this->calDav, $calendar, $this->l10n, $this->config, $this->logger), [], ['principal:principals/groups/' . $userOrGroup]); } else { - throw new \InvalidArgumentException("User <$userDestination> is not part of the group <$userOrGroup> with whom the calendar <" . $calendar['uri'] . "> was shared. You may use -f to move the calendar while deleting this share."); + throw new \InvalidArgumentException("User <$userDestination> is not part of the group <$userOrGroup> with whom the calendar <" . $calendar['uri'] . '> was shared. You may use -f to move the calendar while deleting this share.'); } } @@ -166,7 +167,7 @@ private function checkShares(array $calendar, string $userOrigin, string $userDe if ($force) { $this->calDav->updateShares(new Calendar($this->calDav, $calendar, $this->l10n, $this->config, $this->logger), [], ['principal:principals/users/' . $userOrGroup]); } else { - throw new \InvalidArgumentException("The calendar <" . $calendar['uri'] . "> is already shared to user <$userDestination>.You may use -f to move the calendar while deleting this share."); + throw new \InvalidArgumentException('The calendar <' . $calendar['uri'] . "> is already shared to user <$userDestination>.You may use -f to move the calendar while deleting this share."); } } } diff --git a/apps/dav/lib/Command/SendEventReminders.php b/apps/dav/lib/Command/SendEventReminders.php index f5afb30ed7076..89bb5ce8c205b 100644 --- a/apps/dav/lib/Command/SendEventReminders.php +++ b/apps/dav/lib/Command/SendEventReminders.php @@ -1,4 +1,5 @@ birthdayService->syncUser($user); return self::SUCCESS; } - $output->writeln("Start birthday calendar sync for all users ..."); + $output->writeln('Start birthday calendar sync for all users ...'); $p = new ProgressBar($output); $p->start(); $this->userManager->callForSeenUsers(function ($user) use ($p) { diff --git a/apps/dav/lib/Comments/CommentNode.php b/apps/dav/lib/Comments/CommentNode.php index 3a9e53625280c..a257611dd1520 100644 --- a/apps/dav/lib/Comments/CommentNode.php +++ b/apps/dav/lib/Comments/CommentNode.php @@ -30,7 +30,7 @@ class CommentNode implements \Sabre\DAV\INode, \Sabre\DAV\IProperties { public const PROPERTY_NAME_MENTION_ID = '{http://owncloud.org/ns}mentionId'; public const PROPERTY_NAME_MENTION_DISPLAYNAME = '{http://owncloud.org/ns}mentionDisplayName'; - /** @var IComment */ + /** @var IComment */ public $comment; /** @var ICommentsManager */ diff --git a/apps/dav/lib/Comments/CommentsPlugin.php b/apps/dav/lib/Comments/CommentsPlugin.php index 7db643131219a..ed6614312e1a0 100644 --- a/apps/dav/lib/Comments/CommentsPlugin.php +++ b/apps/dav/lib/Comments/CommentsPlugin.php @@ -34,13 +34,13 @@ class CommentsPlugin extends ServerPlugin { public const REPORT_PARAM_OFFSET = '{http://owncloud.org/ns}offset'; public const REPORT_PARAM_TIMESTAMP = '{http://owncloud.org/ns}datetime'; - /** @var ICommentsManager */ + /** @var ICommentsManager */ protected $commentsManager; /** @var \Sabre\DAV\Server $server */ private $server; - /** @var \OCP\IUserSession */ + /** @var \OCP\IUserSession */ protected $userSession; /** @@ -158,7 +158,7 @@ public function onReport($reportName, $report, $uri) { } if (!is_null($args['datetime'])) { - $args['datetime'] = new \DateTime((string)$args['datetime']); + $args['datetime'] = new \DateTime((string) $args['datetime']); } $results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']); diff --git a/apps/dav/lib/Comments/EntityCollection.php b/apps/dav/lib/Comments/EntityCollection.php index 367dab54c5e19..19af2d9c23401 100644 --- a/apps/dav/lib/Comments/EntityCollection.php +++ b/apps/dav/lib/Comments/EntityCollection.php @@ -27,7 +27,7 @@ class EntityCollection extends RootCollection implements IProperties { public const PROPERTY_NAME_READ_MARKER = '{http://owncloud.org/ns}readMarker'; - /** @var string */ + /** @var string */ protected $id; protected LoggerInterface $logger; diff --git a/apps/dav/lib/Connector/Sabre/AnonymousOptionsPlugin.php b/apps/dav/lib/Connector/Sabre/AnonymousOptionsPlugin.php index b39dc7197b099..0e2b1c58748b4 100644 --- a/apps/dav/lib/Connector/Sabre/AnonymousOptionsPlugin.php +++ b/apps/dav/lib/Connector/Sabre/AnonymousOptionsPlugin.php @@ -1,4 +1,5 @@ server->tree->getNodeForPath($path); if ($node instanceof File) { $type = strtolower( - (string)$request->getHeader('X-Recalculate-Hash') + (string) $request->getHeader('X-Recalculate-Hash') ); $hash = $node->hash($type); diff --git a/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php b/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php index 71514016bda76..84e914bee35f2 100644 --- a/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php @@ -59,14 +59,14 @@ private function cacheDirectory(Directory $directory): void { continue; } - $ids[] = (string)$id; + $ids[] = (string) $id; } $ids[] = (string) $directory->getId(); $unread = $this->commentsManager->getNumberOfUnreadCommentsForObjects('files', $ids, $this->userSession->getUser()); foreach ($unread as $id => $count) { - $this->cachedUnreadCount[(int)$id] = $count; + $this->cachedUnreadCount[(int) $id] = $count; } } @@ -95,7 +95,7 @@ public function handleGetProperties( } $propFind->handle(self::PROPERTY_NAME_COUNT, function () use ($node): int { - return $this->commentsManager->getNumberOfCommentsForObject('files', (string)$node->getId()); + return $this->commentsManager->getNumberOfCommentsForObject('files', (string) $node->getId()); }); $propFind->handle(self::PROPERTY_NAME_HREF, function () use ($node): ?string { @@ -117,7 +117,7 @@ public function getCommentsLink(Node $node): ?string { // in case we end up somewhere else, unexpectedly. return null; } - $commentsPart = 'dav/comments/files/' . rawurldecode((string)$node->getId()); + $commentsPart = 'dav/comments/files/' . rawurldecode((string) $node->getId()); return substr_replace($href, $commentsPart, $entryPoint + strlen('/remote.php/')); } @@ -131,8 +131,8 @@ public function getUnreadCount(Node $node): ?int { return null; } - $lastRead = $this->commentsManager->getReadMark('files', (string)$node->getId(), $user); + $lastRead = $this->commentsManager->getReadMark('files', (string) $node->getId(), $user); - return $this->commentsManager->getNumberOfCommentsForObject('files', (string)$node->getId(), $lastRead); + return $this->commentsManager->getNumberOfCommentsForObject('files', (string) $node->getId(), $lastRead); } } diff --git a/apps/dav/lib/Connector/Sabre/DavAclPlugin.php b/apps/dav/lib/Connector/Sabre/DavAclPlugin.php index 336930cf17d99..7846896182f01 100644 --- a/apps/dav/lib/Connector/Sabre/DavAclPlugin.php +++ b/apps/dav/lib/Connector/Sabre/DavAclPlugin.php @@ -52,7 +52,7 @@ public function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, } if ($this->getCurrentUserPrincipal() === $node->getOwner()) { - throw new Forbidden("Access denied"); + throw new Forbidden('Access denied'); } else { throw new NotFound( sprintf( diff --git a/apps/dav/lib/Connector/Sabre/Directory.php b/apps/dav/lib/Connector/Sabre/Directory.php index b429f45367909..71a48c0cb1478 100644 --- a/apps/dav/lib/Connector/Sabre/Directory.php +++ b/apps/dav/lib/Connector/Sabre/Directory.php @@ -294,7 +294,7 @@ public function getQuotaInfo() { } $relativePath = $this->fileView->getRelativePath($this->info->getPath()); if ($relativePath === null) { - $this->getLogger()->warning("error while getting quota as the relative path cannot be found"); + $this->getLogger()->warning('error while getting quota as the relative path cannot be found'); return [0, 0]; } @@ -311,13 +311,13 @@ public function getQuotaInfo() { ]; return $this->quotaInfo; } catch (\OCP\Files\NotFoundException $e) { - $this->getLogger()->warning("error while getting quota into", ['exception' => $e]); + $this->getLogger()->warning('error while getting quota into', ['exception' => $e]); return [0, 0]; } catch (\OCP\Files\StorageNotAvailableException $e) { - $this->getLogger()->warning("error while getting quota into", ['exception' => $e]); + $this->getLogger()->warning('error while getting quota into', ['exception' => $e]); return [0, 0]; } catch (NotPermittedException $e) { - $this->getLogger()->warning("error while getting quota into", ['exception' => $e]); + $this->getLogger()->warning('error while getting quota into', ['exception' => $e]); return [0, 0]; } } diff --git a/apps/dav/lib/Connector/Sabre/Exception/BadGateway.php b/apps/dav/lib/Connector/Sabre/Exception/BadGateway.php index 41ace00266076..1e1e4aaed041b 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/BadGateway.php +++ b/apps/dav/lib/Connector/Sabre/Exception/BadGateway.php @@ -1,4 +1,5 @@ path); } diff --git a/apps/dav/lib/Connector/Sabre/File.php b/apps/dav/lib/Connector/Sabre/File.php index 7d2933c50140b..1bab3ba713c46 100644 --- a/apps/dav/lib/Connector/Sabre/File.php +++ b/apps/dav/lib/Connector/Sabre/File.php @@ -228,7 +228,7 @@ public function put($data) { } $lengthHeader = $this->request->getHeader('content-length'); - $expected = $lengthHeader !== '' ? (int)$lengthHeader : -1; + $expected = $lengthHeader !== '' ? (int) $lengthHeader : -1; if ($result === false && $expected >= 0) { throw new Exception( $this->l10n->t( diff --git a/apps/dav/lib/Connector/Sabre/FilesPlugin.php b/apps/dav/lib/Connector/Sabre/FilesPlugin.php index 4c2537a354187..2739da472848c 100644 --- a/apps/dav/lib/Connector/Sabre/FilesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesPlugin.php @@ -607,7 +607,7 @@ private function handleUpdatePropertiesMetadata(PropPatch $propPatch, Node $node $mutation, function (mixed $value) use ($accessRight, $knownMetadata, $node, $mutation, $filesMetadataManager): bool { /** @var FilesMetadata $metadata */ - $metadata = $filesMetadataManager->getMetadata((int)$node->getFileId(), true); + $metadata = $filesMetadataManager->getMetadata((int) $node->getFileId(), true); $metadata->setStorageId($node->getNode()->getStorage()->getCache()->getNumericStorageId()); $metadataKey = substr($mutation, strlen(self::FILE_METADATA_PREFIX)); diff --git a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php index 9b29950e4b458..bb4a94dfc6042 100644 --- a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php @@ -184,9 +184,9 @@ public function onReport($reportName, $report, $uri) { } elseif ($name === '{DAV:}limit') { foreach ($reportProps['value'] as $propVal) { if ($propVal['name'] === '{DAV:}nresults') { - $limit = (int)$propVal['value']; + $limit = (int) $propVal['value']; } elseif ($propVal['name'] === $ncns . 'firstresult') { - $offset = (int)$propVal['value']; + $offset = (int) $propVal['value']; } } } @@ -363,7 +363,7 @@ private function getCirclesFileIds(array $circlesIds) { * Prepare propfind response for the given nodes * * @param string $filesUri $filesUri URI leading to root of the files URI, - * with a leading slash but no trailing slash + * with a leading slash but no trailing slash * @param string[] $requestedProps requested properties * @param Node[] nodes nodes for which to fetch and prepare responses * @return Response[] @@ -410,7 +410,7 @@ public function findNodesByFileIds(Node $rootNode, array $fileIds): array { $results = []; foreach ($fileIds as $fileId) { - $entry = $folder->getFirstNodeById((int)$fileId); + $entry = $folder->getFirstNodeById((int) $fileId); if ($entry) { $results[] = $this->wrapNode($entry); } diff --git a/apps/dav/lib/Connector/Sabre/MtimeSanitizer.php b/apps/dav/lib/Connector/Sabre/MtimeSanitizer.php index efed6ce09f80b..91ecb62ac4dd8 100644 --- a/apps/dav/lib/Connector/Sabre/MtimeSanitizer.php +++ b/apps/dav/lib/Connector/Sabre/MtimeSanitizer.php @@ -1,4 +1,5 @@ info->getMtime(); if (!empty($timestamp)) { - return (int)$timestamp; + return (int) $timestamp; } return $timestamp; } @@ -265,7 +265,7 @@ public function getSharePermissions($user) { if ($storage && $storage->instanceOfStorage(ISharedStorage::class)) { /** @var ISharedStorage $storage */ - $permissions = (int)$storage->getShare()->getPermissions(); + $permissions = (int) $storage->getShare()->getPermissions(); } else { $permissions = $this->info->getPermissions(); } diff --git a/apps/dav/lib/Connector/Sabre/ObjectTree.php b/apps/dav/lib/Connector/Sabre/ObjectTree.php index 7ac5b47615408..94098b4aca3ba 100644 --- a/apps/dav/lib/Connector/Sabre/ObjectTree.php +++ b/apps/dav/lib/Connector/Sabre/ObjectTree.php @@ -25,7 +25,7 @@ class ObjectTree extends CachingTree { protected $fileView; /** - * @var \OCP\Files\Mount\IMountManager + * @var \OCP\Files\Mount\IMountManager */ protected $mountManager; @@ -38,7 +38,7 @@ public function __construct() { /** * @param \Sabre\DAV\INode $rootNode * @param \OC\Files\View $view - * @param \OCP\Files\Mount\IMountManager $mountManager + * @param \OCP\Files\Mount\IMountManager $mountManager */ public function init(\Sabre\DAV\INode $rootNode, \OC\Files\View $view, \OCP\Files\Mount\IMountManager $mountManager) { $this->rootNode = $rootNode; diff --git a/apps/dav/lib/Connector/Sabre/Principal.php b/apps/dav/lib/Connector/Sabre/Principal.php index f09ff4def641b..671029f1475c9 100644 --- a/apps/dav/lib/Connector/Sabre/Principal.php +++ b/apps/dav/lib/Connector/Sabre/Principal.php @@ -1,4 +1,5 @@ 'principals/system/' . $name, - '{DAV:}displayname' => $this->languageFactory->get('dav')->t("Accounts"), + '{DAV:}displayname' => $this->languageFactory->get('dav')->t('Accounts'), ]; } return null; diff --git a/apps/dav/lib/Connector/Sabre/QuotaPlugin.php b/apps/dav/lib/Connector/Sabre/QuotaPlugin.php index 5bb0f9cac3194..4cc309ce43af7 100644 --- a/apps/dav/lib/Connector/Sabre/QuotaPlugin.php +++ b/apps/dav/lib/Connector/Sabre/QuotaPlugin.php @@ -81,7 +81,7 @@ public function beforeCreateFile($uri, $data, INode $parent, $modified) { $destinationPath = $this->server->calculateUri($request->getHeader('Destination')); $quotaPath = $this->getPathForDestination($destinationPath); if ($quotaPath && is_numeric($length)) { - return $this->checkQuota($quotaPath, (int)$length); + return $this->checkQuota($quotaPath, (int) $length); } } diff --git a/apps/dav/lib/Connector/Sabre/Server.php b/apps/dav/lib/Connector/Sabre/Server.php index f3bfac1d6e090..111463732749d 100644 --- a/apps/dav/lib/Connector/Sabre/Server.php +++ b/apps/dav/lib/Connector/Sabre/Server.php @@ -69,7 +69,7 @@ public function start() { $DOM->appendChild($error); $h = function ($v) { - return htmlspecialchars((string)$v, ENT_NOQUOTES, 'UTF-8'); + return htmlspecialchars((string) $v, ENT_NOQUOTES, 'UTF-8'); }; if (self::$exposeVersion) { diff --git a/apps/dav/lib/Connector/Sabre/ShareTypeList.php b/apps/dav/lib/Connector/Sabre/ShareTypeList.php index abe56cd0301d6..5c881c8e3c390 100644 --- a/apps/dav/lib/Connector/Sabre/ShareTypeList.php +++ b/apps/dav/lib/Connector/Sabre/ShareTypeList.php @@ -57,7 +57,7 @@ public static function xmlDeserialize(Reader $reader) { } foreach ($tree as $elem) { if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') { - $shareTypes[] = (int)$elem['value']; + $shareTypes[] = (int) $elem['value']; } } return new self($shareTypes); diff --git a/apps/dav/lib/Connector/Sabre/TagsPlugin.php b/apps/dav/lib/Connector/Sabre/TagsPlugin.php index d7572c46ed3a0..ee219aff18fb0 100644 --- a/apps/dav/lib/Connector/Sabre/TagsPlugin.php +++ b/apps/dav/lib/Connector/Sabre/TagsPlugin.php @@ -117,7 +117,7 @@ private function getTagger() { * * @param integer $fileId file id * @return array list($tags, $favorite) with $tags as tag array - * and $favorite is a boolean whether the file was favorited + * and $favorite is a boolean whether the file was favorited */ private function getTagsAndFav($fileId) { $isFav = false; @@ -203,9 +203,9 @@ public function handleGetProperties( )) { // note: pre-fetching only supported for depth <= 1 $folderContent = $node->getChildren(); - $fileIds[] = (int)$node->getId(); + $fileIds[] = (int) $node->getId(); foreach ($folderContent as $info) { - $fileIds[] = (int)$info->getId(); + $fileIds[] = (int) $info->getId(); } $tags = $this->getTagger()->getTagsForObjects($fileIds); if ($tags === false) { @@ -260,7 +260,7 @@ public function handleUpdateProperties($path, PropPatch $propPatch) { }); $propPatch->handle(self::FAVORITE_PROPERTYNAME, function ($favState) use ($node) { - if ((int)$favState === 1 || $favState === 'true') { + if ((int) $favState === 1 || $favState === 'true') { $this->getTagger()->tagAs($node->getId(), self::TAG_FAVORITE); } else { $this->getTagger()->unTag($node->getId(), self::TAG_FAVORITE); diff --git a/apps/dav/lib/Controller/BirthdayCalendarController.php b/apps/dav/lib/Controller/BirthdayCalendarController.php index e82c4ad534cd7..11aa6e308a195 100644 --- a/apps/dav/lib/Controller/BirthdayCalendarController.php +++ b/apps/dav/lib/Controller/BirthdayCalendarController.php @@ -1,4 +1,5 @@ isRequestPublic($request)) { - return [true, "principals/system/public"]; + return [true, 'principals/system/public']; } - return [false, "No public access to this resource."]; + return [false, 'No public access to this resource.']; } /** diff --git a/apps/dav/lib/DAV/Sharing/Backend.php b/apps/dav/lib/DAV/Sharing/Backend.php index f63e4dce45467..cdcf0ca7d4491 100644 --- a/apps/dav/lib/DAV/Sharing/Backend.php +++ b/apps/dav/lib/DAV/Sharing/Backend.php @@ -58,7 +58,7 @@ public function updateShares(IShareable $shareable, array $add, array $remove, a } // Don't add share for owner - if($shareable->getOwner() !== null && strcasecmp($shareable->getOwner(), $principal) === 0) { + if ($shareable->getOwner() !== null && strcasecmp($shareable->getOwner(), $principal) === 0) { continue; } @@ -83,7 +83,7 @@ public function updateShares(IShareable $shareable, array $add, array $remove, a } // Don't add unshare for owner - if($shareable->getOwner() !== null && strcasecmp($shareable->getOwner(), $principal) === 0) { + if ($shareable->getOwner() !== null && strcasecmp($shareable->getOwner(), $principal) === 0) { continue; } @@ -92,7 +92,7 @@ public function updateShares(IShareable $shareable, array $add, array $remove, a // Check if a user has a groupshare that they're trying to free themselves from // If so we need to add a self::ACCESS_UNSHARED row - if(!str_contains($principal, 'group') + if (!str_contains($principal, 'group') && $this->service->hasGroupShare($oldShares) ) { $this->service->unshare($shareable->getResourceId(), $principal); @@ -123,31 +123,31 @@ public function deleteAllSharesByUser(string $principaluri): void { * @return list */ public function getShares(int $resourceId): array { - $cached = $this->shareCache->get((string)$resourceId); + $cached = $this->shareCache->get((string) $resourceId); if ($cached) { return $cached; } $rows = $this->service->getShares($resourceId); $shares = []; - foreach($rows as $row) { + foreach ($rows as $row) { $p = $this->principalBackend->getPrincipalByPath($row['principaluri']); $shares[] = [ 'href' => "principal:{$row['principaluri']}", - 'commonName' => isset($p['{DAV:}displayname']) ? (string)$p['{DAV:}displayname'] : '', + 'commonName' => isset($p['{DAV:}displayname']) ? (string) $p['{DAV:}displayname'] : '', 'status' => 1, 'readOnly' => (int) $row['access'] === Backend::ACCESS_READ, - '{http://owncloud.org/ns}principal' => (string)$row['principaluri'], + '{http://owncloud.org/ns}principal' => (string) $row['principaluri'], '{http://owncloud.org/ns}group-share' => isset($p['uri']) && (str_starts_with($p['uri'], 'principals/groups') || str_starts_with($p['uri'], 'principals/circles')) ]; } - $this->shareCache->set((string)$resourceId, $shares); + $this->shareCache->set((string) $resourceId, $shares); return $shares; } public function preloadShares(array $resourceIds): void { $resourceIds = array_filter($resourceIds, function (int $resourceId) { - return empty($this->shareCache->get((string)$resourceId)); + return empty($this->shareCache->get((string) $resourceId)); }); if (empty($resourceIds)) { return; @@ -155,18 +155,18 @@ public function preloadShares(array $resourceIds): void { $rows = $this->service->getSharesForIds($resourceIds); $sharesByResource = array_fill_keys($resourceIds, []); - foreach($rows as $row) { - $resourceId = (int)$row['resourceid']; + foreach ($rows as $row) { + $resourceId = (int) $row['resourceid']; $p = $this->principalBackend->getPrincipalByPath($row['principaluri']); $sharesByResource[$resourceId][] = [ 'href' => "principal:{$row['principaluri']}", - 'commonName' => isset($p['{DAV:}displayname']) ? (string)$p['{DAV:}displayname'] : '', + 'commonName' => isset($p['{DAV:}displayname']) ? (string) $p['{DAV:}displayname'] : '', 'status' => 1, 'readOnly' => (int) $row['access'] === self::ACCESS_READ, - '{http://owncloud.org/ns}principal' => (string)$row['principaluri'], + '{http://owncloud.org/ns}principal' => (string) $row['principaluri'], '{http://owncloud.org/ns}group-share' => isset($p['uri']) && str_starts_with($p['uri'], 'principals/groups') ]; - $this->shareCache->set((string)$resourceId, $sharesByResource[$resourceId]); + $this->shareCache->set((string) $resourceId, $sharesByResource[$resourceId]); } } diff --git a/apps/dav/lib/DAV/ViewOnlyPlugin.php b/apps/dav/lib/DAV/ViewOnlyPlugin.php index df3301e2e6b99..b9e409a478142 100644 --- a/apps/dav/lib/DAV/ViewOnlyPlugin.php +++ b/apps/dav/lib/DAV/ViewOnlyPlugin.php @@ -74,7 +74,7 @@ public function checkViewOnly(RequestInterface $request): bool { $nodes = $this->userFolder->getById($node->getId()); $node = array_pop($nodes); if (!$node) { - throw new NotFoundException("Version file not accessible by current user"); + throw new NotFoundException('Version file not accessible by current user'); } } } else { diff --git a/apps/dav/lib/Db/Absence.php b/apps/dav/lib/Db/Absence.php index 550958aaabd27..ffe0287f65465 100644 --- a/apps/dav/lib/Db/Absence.php +++ b/apps/dav/lib/Db/Absence.php @@ -63,7 +63,7 @@ public function __construct() { public function toOutOufOfficeData(IUser $user, string $timezone): IOutOfOfficeData { if ($user->getUID() !== $this->getUserId()) { - throw new InvalidArgumentException("The user doesn't match the user id of this absence! Expected " . $this->getUserId() . ", got " . $user->getUID()); + throw new InvalidArgumentException("The user doesn't match the user id of this absence! Expected " . $this->getUserId() . ', got ' . $user->getUID()); } if ($this->getId() === null) { throw new Exception('Creating out-of-office data without ID'); @@ -74,7 +74,7 @@ public function toOutOufOfficeData(IUser $user, string $timezone): IOutOfOfficeD $endDate = new DateTime($this->getLastDay(), $tz); $endDate->setTime(23, 59); return new OutOfOfficeData( - (string)$this->getId(), + (string) $this->getId(), $user, $startDate->getTimestamp(), $endDate->getTimestamp(), diff --git a/apps/dav/lib/Direct/DirectFile.php b/apps/dav/lib/Direct/DirectFile.php index 45d86fcaeaeff..3c684b83ef2fd 100644 --- a/apps/dav/lib/Direct/DirectFile.php +++ b/apps/dav/lib/Direct/DirectFile.php @@ -96,7 +96,7 @@ private function getFile() { throw new NotFound(); } if (!$file instanceof File) { - throw new Forbidden("direct download not allowed on directories"); + throw new Forbidden('direct download not allowed on directories'); } $this->file = $file; diff --git a/apps/dav/lib/Events/CalendarDeletedEvent.php b/apps/dav/lib/Events/CalendarDeletedEvent.php index 20c4b187246b6..326af0702adbd 100644 --- a/apps/dav/lib/Events/CalendarDeletedEvent.php +++ b/apps/dav/lib/Events/CalendarDeletedEvent.php @@ -24,7 +24,7 @@ class CalendarDeletedEvent extends Event { /** @var array */ private $calendarData; - /** @var array */ + /** @var array */ private $shares; /** diff --git a/apps/dav/lib/Events/CalendarMovedToTrashEvent.php b/apps/dav/lib/Events/CalendarMovedToTrashEvent.php index 02ea0182e0a19..b2eb8e1f0183c 100644 --- a/apps/dav/lib/Events/CalendarMovedToTrashEvent.php +++ b/apps/dav/lib/Events/CalendarMovedToTrashEvent.php @@ -21,7 +21,7 @@ class CalendarMovedToTrashEvent extends Event { /** @var array */ private $calendarData; - /** @var array */ + /** @var array */ private $shares; /** diff --git a/apps/dav/lib/Events/CalendarRestoredEvent.php b/apps/dav/lib/Events/CalendarRestoredEvent.php index a4ba75755e3b6..5ea754ef200da 100644 --- a/apps/dav/lib/Events/CalendarRestoredEvent.php +++ b/apps/dav/lib/Events/CalendarRestoredEvent.php @@ -21,7 +21,7 @@ class CalendarRestoredEvent extends Event { /** @var array */ private $calendarData; - /** @var array */ + /** @var array */ private $shares; /** diff --git a/apps/dav/lib/Exception/UnsupportedLimitOnInitialSyncException.php b/apps/dav/lib/Exception/UnsupportedLimitOnInitialSyncException.php index 1022625c23b28..c6b7f8564c51d 100644 --- a/apps/dav/lib/Exception/UnsupportedLimitOnInitialSyncException.php +++ b/apps/dav/lib/Exception/UnsupportedLimitOnInitialSyncException.php @@ -1,4 +1,5 @@ maxResults, + (int) $limit->maxResults, $offset, $orders, $this->user, @@ -476,7 +477,7 @@ private function castValue(SearchPropertyDefinition $property, $value) { if (is_numeric($value)) { return max(0, 0 + $value); } - $date = \DateTime::createFromFormat(\DateTimeInterface::ATOM, (string)$value); + $date = \DateTime::createFromFormat(\DateTimeInterface::ATOM, (string) $value); return ($date instanceof \DateTime && $date->getTimestamp() !== false) ? $date->getTimestamp() : 0; default: return $value; diff --git a/apps/dav/lib/Files/LazySearchBackend.php b/apps/dav/lib/Files/LazySearchBackend.php index a0ad730ff2bc9..6ba539ddd87f6 100644 --- a/apps/dav/lib/Files/LazySearchBackend.php +++ b/apps/dav/lib/Files/LazySearchBackend.php @@ -1,4 +1,5 @@ logger->debug("Creating activity for Calendar having its shares updated"); + $this->logger->debug('Creating activity for Calendar having its shares updated'); $this->activityBackend->onCalendarUpdateShares( $event->getCalendarData(), diff --git a/apps/dav/lib/Listener/SubscriptionListener.php b/apps/dav/lib/Listener/SubscriptionListener.php index 9c9904d1aa247..971ec23fd645d 100644 --- a/apps/dav/lib/Listener/SubscriptionListener.php +++ b/apps/dav/lib/Listener/SubscriptionListener.php @@ -43,8 +43,8 @@ public function handle(Event $event): void { $this->logger->debug('Refreshing webcal data for subscription ' . $subscriptionId); $this->refreshWebcalService->refreshSubscription( - (string)$subscriptionData['principaluri'], - (string)$subscriptionData['uri'] + (string) $subscriptionData['principaluri'], + (string) $subscriptionData['uri'] ); $this->logger->debug('Scheduling webcal data refreshment for subscription ' . $subscriptionId); diff --git a/apps/dav/lib/Migration/BuildCalendarSearchIndex.php b/apps/dav/lib/Migration/BuildCalendarSearchIndex.php index 222554a373233..050ab17c76319 100644 --- a/apps/dav/lib/Migration/BuildCalendarSearchIndex.php +++ b/apps/dav/lib/Migration/BuildCalendarSearchIndex.php @@ -1,4 +1,5 @@ select($query->func()->max('cardid')) ->from('cards_properties') ->where($query->expr()->eq('name', $query->createNamedParameter('X-SOCIALPROFILE'))); - $maxId = (int)$query->execute()->fetchOne(); + $maxId = (int) $query->execute()->fetchOne(); if ($maxId === 0) { return; diff --git a/apps/dav/lib/Migration/BuildSocialSearchIndexBackgroundJob.php b/apps/dav/lib/Migration/BuildSocialSearchIndexBackgroundJob.php index f727f4ea09a7d..67b12b15070e5 100644 --- a/apps/dav/lib/Migration/BuildSocialSearchIndexBackgroundJob.php +++ b/apps/dav/lib/Migration/BuildSocialSearchIndexBackgroundJob.php @@ -60,7 +60,7 @@ private function buildIndex($offset, $stopAt) { ->from('cards', 'c') ->orderBy('id', 'ASC') ->where($query->expr()->like('carddata', $query->createNamedParameter('%SOCIALPROFILE%'))) - ->andWhere($query->expr()->gt('id', $query->createNamedParameter((int)$offset, IQueryBuilder::PARAM_INT))) + ->andWhere($query->expr()->gt('id', $query->createNamedParameter((int) $offset, IQueryBuilder::PARAM_INT))) ->setMaxResults(100); $social_cards = $query->executeQuery()->fetchAll(); diff --git a/apps/dav/lib/Migration/CalDAVRemoveEmptyValue.php b/apps/dav/lib/Migration/CalDAVRemoveEmptyValue.php index c7f57dcb11718..17260cfaa6cbb 100644 --- a/apps/dav/lib/Migration/CalDAVRemoveEmptyValue.php +++ b/apps/dav/lib/Migration/CalDAVRemoveEmptyValue.php @@ -1,4 +1,5 @@ startProgress(count($objects)); foreach ($objects as $row) { - $calObject = $this->calDavBackend->getCalendarObject((int)$row['calendarid'], $row['uri']); + $calObject = $this->calDavBackend->getCalendarObject((int) $row['calendarid'], $row['uri']); $data = preg_replace('/' . $pattern . '/', ':', $calObject['calendardata']); if ($data !== $calObject['calendardata']) { @@ -52,14 +53,14 @@ public function run(IOutput $output) { } catch (InvalidDataException $e) { $this->logger->info('Calendar object for calendar {cal} with uri {uri} still invalid', [ 'app' => 'dav', - 'cal' => (int)$row['calendarid'], + 'cal' => (int) $row['calendarid'], 'uri' => $row['uri'], ]); $warnings++; continue; } - $this->calDavBackend->updateCalendarObject((int)$row['calendarid'], $row['uri'], $data); + $this->calDavBackend->updateCalendarObject((int) $row['calendarid'], $row['uri'], $data); $count++; } } diff --git a/apps/dav/lib/Migration/FixBirthdayCalendarComponent.php b/apps/dav/lib/Migration/FixBirthdayCalendarComponent.php index d22e4b82c9fea..df49dedc941ee 100644 --- a/apps/dav/lib/Migration/FixBirthdayCalendarComponent.php +++ b/apps/dav/lib/Migration/FixBirthdayCalendarComponent.php @@ -1,4 +1,5 @@ closeCursor(); if ($count !== false) { - $count = (int)$count; + $count = (int) $count; } else { $count = 0; } diff --git a/apps/dav/lib/Migration/RemoveObjectProperties.php b/apps/dav/lib/Migration/RemoveObjectProperties.php index b87eb82af198a..32e59eec7b509 100644 --- a/apps/dav/lib/Migration/RemoveObjectProperties.php +++ b/apps/dav/lib/Migration/RemoveObjectProperties.php @@ -1,4 +1,5 @@ ['column1', 'column2'], ...] + * ['table1' => ['column1', 'column2'], ...] * @since 13.0.0 */ protected function getColumnsByTable() { diff --git a/apps/dav/lib/Migration/Version1005Date20180530124431.php b/apps/dav/lib/Migration/Version1005Date20180530124431.php index ac1994893fdcd..b5f9ff26962aa 100644 --- a/apps/dav/lib/Migration/Version1005Date20180530124431.php +++ b/apps/dav/lib/Migration/Version1005Date20180530124431.php @@ -1,4 +1,5 @@ userManager->countSeenUsers() > 100 || array_sum($this->userManager->countUsers()) > 100) { + if ($this->userManager->countSeenUsers() > 100 || array_sum($this->userManager->countUsers()) > 100) { $this->config->setAppValue('dav', 'needs_system_address_book_sync', 'yes'); $output->info('Could not sync system address books during update - too many user records have been found. Please call occ dav:sync-system-addressbook manually.'); return; diff --git a/apps/dav/lib/Migration/Version1029Date20221114151721.php b/apps/dav/lib/Migration/Version1029Date20221114151721.php index 05b04486c88ba..dba5e0b1a488a 100644 --- a/apps/dav/lib/Migration/Version1029Date20221114151721.php +++ b/apps/dav/lib/Migration/Version1029Date20221114151721.php @@ -28,7 +28,7 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); $calendarObjectsTable = $schema->getTable('calendarobjects'); - if(!$calendarObjectsTable->hasIndex('calobj_clssfction_index')) { + if (!$calendarObjectsTable->hasIndex('calobj_clssfction_index')) { $calendarObjectsTable->addIndex(['classification'], 'calobj_clssfction_index'); return $schema; } diff --git a/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php b/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php index f1313b89582c6..c8ef7a5cc19ac 100644 --- a/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php +++ b/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php @@ -1,4 +1,5 @@ getDavUrlForContact($addressBook['principaluri'], $addressBook['uri'], $contactRow['uri']) . '?photo'; } - $title = (string)$vCard->FN; + $title = (string) $vCard->FN; $subline = $this->generateSubline($vCard); $resourceUrl = $this->getDeepLinkToContactsApp($addressBook['uri'], (string) $vCard->UID); $result = new SearchResultEntry($thumbnailUrl, $title, $subline, $resourceUrl, 'icon-contacts-dark', true); - $result->addAttribute("displayName", $title); - $result->addAttribute("email", $subline); - $result->addAttribute("phoneNumber", (string)$vCard->TEL); + $result->addAttribute('displayName', $title); + $result->addAttribute('email', $subline); + $result->addAttribute('phoneNumber', (string) $vCard->TEL); return $result; }, $searchResults); @@ -166,7 +166,7 @@ protected function generateSubline(VCard $vCard): string { return ''; } - return (string)$emailAddresses[0]; + return (string) $emailAddresses[0]; } public function getSupportedFilters(): array { diff --git a/apps/dav/lib/Search/EventsSearchProvider.php b/apps/dav/lib/Search/EventsSearchProvider.php index 6c9fe5167c5bc..071fceee1fe22 100644 --- a/apps/dav/lib/Search/EventsSearchProvider.php +++ b/apps/dav/lib/Search/EventsSearchProvider.php @@ -149,7 +149,7 @@ public function search( } $formattedResults = \array_map(function (array $eventRow) use ($calendarsById, $subscriptionsById): SearchResultEntry { $component = $this->getPrimaryComponent($eventRow['calendardata'], self::$componentType); - $title = (string)($component->SUMMARY ?? $this->l10n->t('Untitled event')); + $title = (string) ($component->SUMMARY ?? $this->l10n->t('Untitled event')); $subline = $this->generateSubline($component); if ($eventRow['calendartype'] === CalDavBackend::CALENDAR_TYPE_CALENDAR) { @@ -164,7 +164,7 @@ public function search( if ($dtStart instanceof DateTime) { $startDateTime = $dtStart->getDateTime()->format('U'); - $result->addAttribute("createdAt", $startDateTime); + $result->addAttribute('createdAt', $startDateTime); } return $result; diff --git a/apps/dav/lib/Search/TasksSearchProvider.php b/apps/dav/lib/Search/TasksSearchProvider.php index 15baf070e8182..d37ed3ecac571 100644 --- a/apps/dav/lib/Search/TasksSearchProvider.php +++ b/apps/dav/lib/Search/TasksSearchProvider.php @@ -95,7 +95,7 @@ public function search( ); $formattedResults = \array_map(function (array $taskRow) use ($calendarsById, $subscriptionsById):SearchResultEntry { $component = $this->getPrimaryComponent($taskRow['calendardata'], self::$componentType); - $title = (string)($component->SUMMARY ?? $this->l10n->t('Untitled task')); + $title = (string) ($component->SUMMARY ?? $this->l10n->t('Untitled task')); $subline = $this->generateSubline($component); if ($taskRow['calendartype'] === CalDavBackend::CALENDAR_TYPE_CALENDAR) { diff --git a/apps/dav/lib/Server.php b/apps/dav/lib/Server.php index d57a4554fe377..8f4a6bc726f19 100644 --- a/apps/dav/lib/Server.php +++ b/apps/dav/lib/Server.php @@ -1,4 +1,5 @@ systemTagsInFilesDetector->detectAssignedSystemTagsIn($userFolder, $this->mediaType); $children = []; foreach ($result as $tagData) { - $tag = new SystemTag((string)$tagData['id'], $tagData['name'], (bool)$tagData['visibility'], (bool)$tagData['editable']); + $tag = new SystemTag((string) $tagData['id'], $tagData['name'], (bool) $tagData['visibility'], (bool) $tagData['editable']); // read only, so we can submit the isAdmin parameter as false generally $node = new SystemTagNode($tag, $user, false, $this->systemTagManager); $node->setNumberOfFiles((int) $tagData['number_files']); diff --git a/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php b/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php index dc0f1bc5d36e3..6871f03d6db49 100644 --- a/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php +++ b/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php @@ -37,7 +37,7 @@ public function __construct( function (string $name) use ($rootFolder, $userSession): bool { $user = $userSession->getUser(); if ($user) { - $node = $rootFolder->getUserFolder($user->getUID())->getFirstNodeById((int)$name); + $node = $rootFolder->getUserFolder($user->getUID())->getFirstNodeById((int) $name); return $node !== null; } else { return false; @@ -46,7 +46,7 @@ function (string $name) use ($rootFolder, $userSession): bool { function (string $name) use ($rootFolder, $userSession): bool { $user = $userSession->getUser(); if ($user) { - $nodes = $rootFolder->getUserFolder($user->getUID())->getById((int)$name); + $nodes = $rootFolder->getUserFolder($user->getUID())->getById((int) $name); foreach ($nodes as $node) { if (($node->getPermissions() & Constants::PERMISSION_UPDATE) === Constants::PERMISSION_UPDATE) { return true; diff --git a/apps/dav/lib/Traits/PrincipalProxyTrait.php b/apps/dav/lib/Traits/PrincipalProxyTrait.php index 279f796b72096..feec485fe5c3f 100644 --- a/apps/dav/lib/Traits/PrincipalProxyTrait.php +++ b/apps/dav/lib/Traits/PrincipalProxyTrait.php @@ -1,4 +1,5 @@ getUploadStorage($this->uploadPath); $chunkName = basename($request->getPath()); - $partId = is_numeric($chunkName) ? (int)$chunkName : -1; + $partId = is_numeric($chunkName) ? (int) $chunkName : -1; if (!($partId >= 1 && $partId <= 10000)) { throw new BadRequest('Invalid chunk name, must be numeric between 1 and 10000'); } @@ -147,7 +147,7 @@ public function beforePut(RequestInterface $request, ResponseInterface $response $uploadFile = $this->getUploadFile($this->uploadPath); $tempTargetFile = null; - $additionalSize = (int)$request->getHeader('Content-Length'); + $additionalSize = (int) $request->getHeader('Content-Length'); if ($this->uploadFolder->childExists(self::TEMP_TARGET) && $this->uploadPath) { /** @var UploadFile $tempTargetFile */ $tempTargetFile = $this->uploadFolder->getChild(self::TEMP_TARGET); @@ -162,7 +162,7 @@ public function beforePut(RequestInterface $request, ResponseInterface $response } $stream = $request->getBodyAsStream(); - $storage->putChunkedWritePart($storagePath, $this->uploadId, (string)$partId, $stream, $additionalSize); + $storage->putChunkedWritePart($storagePath, $this->uploadId, (string) $partId, $stream, $additionalSize); $storage->getCache()->update($uploadFile->getId(), ['size' => $uploadFile->getSize() + $additionalSize]); if ($tempTargetFile) { @@ -294,7 +294,7 @@ protected function sanitizeMtime(string $mtimeFromRequest): int { throw new InvalidArgumentException('X-OC-MTime header must be an integer (unix timestamp).'); } - return (int)$mtimeFromRequest; + return (int) $mtimeFromRequest; } /** diff --git a/apps/dav/lib/Upload/UploadFile.php b/apps/dav/lib/Upload/UploadFile.php index ae64760e0ce07..742eda78d0868 100644 --- a/apps/dav/lib/Upload/UploadFile.php +++ b/apps/dav/lib/Upload/UploadFile.php @@ -12,7 +12,7 @@ use Sabre\DAV\IFile; class UploadFile implements IFile { - /** @var File */ + /** @var File */ private $file; public function __construct(File $file) { diff --git a/apps/dav/lib/UserMigration/ContactsMigrator.php b/apps/dav/lib/UserMigration/ContactsMigrator.php index 70f92379fe228..a14d3bc5e1ccd 100644 --- a/apps/dav/lib/UserMigration/ContactsMigrator.php +++ b/apps/dav/lib/UserMigration/ContactsMigrator.php @@ -251,7 +251,7 @@ private function importContact(int $addressBookId, VCard $vCard, string $filenam $vCard->serialize(), ); } catch (Throwable $e) { - $output->writeln("Error creating contact \"" . ($vCard->FN ?? 'null') . "\" from \"$filename\", skipping…"); + $output->writeln('Error creating contact "' . ($vCard->FN ?? 'null') . "\" from \"$filename\", skipping…"); } } diff --git a/apps/dav/tests/unit/AppInfo/PluginManagerTest.php b/apps/dav/tests/unit/AppInfo/PluginManagerTest.php index 8211cdfc02cce..377654268db74 100644 --- a/apps/dav/tests/unit/AppInfo/PluginManagerTest.php +++ b/apps/dav/tests/unit/AppInfo/PluginManagerTest.php @@ -1,4 +1,5 @@ vobject->expects($this->once()) ->method('getBaseComponent') - ->willReturn((object)['UID' => 'someid']); + ->willReturn((object) ['UID' => 'someid']); $this->calendar->expects($this->once()) ->method('getPermissions') ->willReturn(Constants::PERMISSION_ALL); @@ -156,7 +156,7 @@ public function testDelete() { public function testGetName() { $this->vobject->expects($this->exactly(2)) ->method('getBaseComponent') - ->willReturnOnConsecutiveCalls((object)['UID' => 'someid'], (object)['UID' => 'someid', 'X-FILENAME' => 'real-filename.ics']); + ->willReturnOnConsecutiveCalls((object) ['UID' => 'someid'], (object) ['UID' => 'someid', 'X-FILENAME' => 'real-filename.ics']); $this->assertEquals($this->calendarObject->getName(), 'someid.ics'); $this->assertEquals($this->calendarObject->getName(), 'real-filename.ics'); diff --git a/apps/dav/tests/unit/CalDAV/BirthdayCalendar/EnablePluginTest.php b/apps/dav/tests/unit/CalDAV/BirthdayCalendar/EnablePluginTest.php index e7de7d0a55ea1..2cee9707bbfab 100644 --- a/apps/dav/tests/unit/CalDAV/BirthdayCalendar/EnablePluginTest.php +++ b/apps/dav/tests/unit/CalDAV/BirthdayCalendar/EnablePluginTest.php @@ -1,4 +1,5 @@ [0, 'lastOccurence', "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.3.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nDTSTART;VALUE=DATE:19110324\r\nDTEND;VALUE=DATE:19110325\r\nDTSTAMP:20200927T180638Z\r\nUID:asdfasdfasdf@google.com\r\nCREATED:20200626T181848Z\r\nDESCRIPTION:Very old event\r\nLAST-MODIFIED:20200922T192707Z\r\nSUMMARY:Some old event\r\nTRANSP:OPAQUE\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"], - 'first occurrence is found when not first VEVENT in group' => [(new DateTime('2020-09-01T110000', new DateTimeZone("America/Los_Angeles")))->getTimestamp(), 'firstOccurence', "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.3.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nDTSTART;TZID=America/Los_Angeles:20201013T110000\r\nDTEND;TZID=America/Los_Angeles:20201013T120000\r\nDTSTAMP:20200927T180638Z\r\nUID:asdf0000@google.com\r\nRECURRENCE-ID;TZID=America/Los_Angeles:20201013T110000\r\nCREATED:20160330T034726Z\r\nLAST-MODIFIED:20200925T042014Z\r\nSTATUS:CONFIRMED\r\nTRANSP:OPAQUE\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nDTSTART;TZID=America/Los_Angeles:20200901T110000\r\nDTEND;TZID=America/Los_Angeles:20200901T120000\r\nRRULE:FREQ=WEEKLY;BYDAY=TU\r\nEXDATE;TZID=America/Los_Angeles:20200922T110000\r\nEXDATE;TZID=America/Los_Angeles:20200915T110000\r\nEXDATE;TZID=America/Los_Angeles:20200908T110000\r\nDTSTAMP:20200927T180638Z\r\nUID:asdf0000@google.com\r\nCREATED:20160330T034726Z\r\nLAST-MODIFIED:20200915T162810Z\r\nSTATUS:CONFIRMED\r\nTRANSP:OPAQUE\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"], + 'first occurrence is found when not first VEVENT in group' => [(new DateTime('2020-09-01T110000', new DateTimeZone('America/Los_Angeles')))->getTimestamp(), 'firstOccurence', "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.3.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nDTSTART;TZID=America/Los_Angeles:20201013T110000\r\nDTEND;TZID=America/Los_Angeles:20201013T120000\r\nDTSTAMP:20200927T180638Z\r\nUID:asdf0000@google.com\r\nRECURRENCE-ID;TZID=America/Los_Angeles:20201013T110000\r\nCREATED:20160330T034726Z\r\nLAST-MODIFIED:20200925T042014Z\r\nSTATUS:CONFIRMED\r\nTRANSP:OPAQUE\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nDTSTART;TZID=America/Los_Angeles:20200901T110000\r\nDTEND;TZID=America/Los_Angeles:20200901T120000\r\nRRULE:FREQ=WEEKLY;BYDAY=TU\r\nEXDATE;TZID=America/Los_Angeles:20200922T110000\r\nEXDATE;TZID=America/Los_Angeles:20200915T110000\r\nEXDATE;TZID=America/Los_Angeles:20200908T110000\r\nDTSTAMP:20200927T180638Z\r\nUID:asdf0000@google.com\r\nCREATED:20160330T034726Z\r\nLAST-MODIFIED:20200915T162810Z\r\nSTATUS:CONFIRMED\r\nTRANSP:OPAQUE\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"], 'CLASS:PRIVATE' => [CalDavBackend::CLASSIFICATION_PRIVATE, 'classification', "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//dmfs.org//mimedir.icalendar//EN\r\nBEGIN:VTIMEZONE\r\nTZID:Europe/Berlin\r\nX-LIC-LOCATION:Europe/Berlin\r\nBEGIN:DAYLIGHT\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0200\r\nTZNAME:CEST\r\nDTSTART:19700329T020000\r\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0100\r\nTZNAME:CET\r\nDTSTART:19701025T030000\r\nRRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\nBEGIN:VEVENT\r\nDTSTART;TZID=Europe/Berlin:20160419T130000\r\nSUMMARY:Test\r\nCLASS:PRIVATE\r\nTRANSP:OPAQUE\r\nSTATUS:CONFIRMED\r\nDTEND;TZID=Europe/Berlin:20160419T140000\r\nLAST-MODIFIED:20160419T074202Z\r\nDTSTAMP:20160419T074202Z\r\nCREATED:20160419T074202Z\r\nUID:2e468c48-7860-492e-bc52-92fa0daeeccf.1461051722310\r\nEND:VEVENT\r\nEND:VCALENDAR"], diff --git a/apps/dav/tests/unit/CalDAV/CalendarHomeTest.php b/apps/dav/tests/unit/CalDAV/CalendarHomeTest.php index 9956c17fff354..bba9698bd0854 100644 --- a/apps/dav/tests/unit/CalDAV/CalendarHomeTest.php +++ b/apps/dav/tests/unit/CalDAV/CalendarHomeTest.php @@ -1,4 +1,5 @@ method('setCurrentPrincipal') ->with($this->calendar->getPrincipalURI()); - /** @var \Sabre\DAVACL\Plugin|MockObject $aclPlugin*/ + /** @var \Sabre\DAVACL\Plugin|MockObject $aclPlugin */ $aclPlugin = $this->createMock(\Sabre\DAVACL\Plugin::class); /** @var Plugin|MockObject $schedulingPlugin */ $schedulingPlugin = $this->createMock(Plugin::class); $iTipMessage = $this->getITipMessage($message); - $iTipMessage->recipient = "mailto:lewis@stardew-tent-living.com"; + $iTipMessage->recipient = 'mailto:lewis@stardew-tent-living.com'; $server = $this->createMock(Server::class); $server->expects($this->any()) @@ -250,7 +251,7 @@ private function getITipMessage($calendarData): Message { $iTipMessage->sender = $attendee; $iTipMessage->uid = isset($vEvent->{'UID'}) ? $vEvent->{'UID'}->getValue() : ''; $iTipMessage->component = 'VEVENT'; - $iTipMessage->sequence = isset($vEvent->{'SEQUENCE'}) ? (int)$vEvent->{'SEQUENCE'}->getValue() : 0; + $iTipMessage->sequence = isset($vEvent->{'SEQUENCE'}) ? (int) $vEvent->{'SEQUENCE'}->getValue() : 0; $iTipMessage->message = $vObject; return $iTipMessage; } diff --git a/apps/dav/tests/unit/CalDAV/CalendarManagerTest.php b/apps/dav/tests/unit/CalDAV/CalendarManagerTest.php index 63d92dff40d30..845474562c95b 100644 --- a/apps/dav/tests/unit/CalDAV/CalendarManagerTest.php +++ b/apps/dav/tests/unit/CalDAV/CalendarManagerTest.php @@ -1,4 +1,5 @@ expects($this->once()) ->method('t') ->with('Busy') - ->willReturn("Translated busy"); + ->willReturn('Translated busy'); } else { $l10n->expects($this->never()) ->method('t'); diff --git a/apps/dav/tests/unit/CalDAV/EventReaderTest.php b/apps/dav/tests/unit/CalDAV/EventReaderTest.php index fa07b99fbaf99..039763628fb9c 100644 --- a/apps/dav/tests/unit/CalDAV/EventReaderTest.php +++ b/apps/dav/tests/unit/CalDAV/EventReaderTest.php @@ -16,19 +16,19 @@ class EventReaderTest extends TestCase { - /** @var VCalendar*/ + /** @var VCalendar */ private $vCalendar1a; - /** @var VCalendar*/ + /** @var VCalendar */ private $vCalendar1b; - /** @var VCalendar*/ + /** @var VCalendar */ private $vCalendar1c; - /** @var VCalendar*/ + /** @var VCalendar */ private $vCalendar1d; - /** @var VCalendar*/ + /** @var VCalendar */ private $vCalendar1e; - /** @var VCalendar*/ + /** @var VCalendar */ private $vCalendar2; - /** @var VCalendar*/ + /** @var VCalendar */ private $vCalendar3; protected function setUp(): void { diff --git a/apps/dav/tests/unit/CalDAV/Integration/ExternalCalendarTest.php b/apps/dav/tests/unit/CalDAV/Integration/ExternalCalendarTest.php index 778df5697f0a2..824b3e1448f35 100644 --- a/apps/dav/tests/unit/CalDAV/Integration/ExternalCalendarTest.php +++ b/apps/dav/tests/unit/CalDAV/Integration/ExternalCalendarTest.php @@ -1,4 +1,5 @@ createMock(IConfig::class); - /** @var MockObject | LoggerInterface $logger */ + /** @var MockObject | LoggerInterface $logger */ $logger = $this->createMock(LoggerInterface::class); $c = new PublicCalendar($backend, $calendarInfo, $this->l10n, $config, $logger); $children = $c->getChildren(); @@ -134,7 +135,7 @@ public function testConfidentialClassification($expectedChildren, $isShared): vo ]; /** @var MockObject | IConfig $config */ $config = $this->createMock(IConfig::class); - /** @var MockObject | LoggerInterface $logger */ + /** @var MockObject | LoggerInterface $logger */ $logger = $this->createMock(LoggerInterface::class); $c = new PublicCalendar($backend, $calendarInfo, $this->l10n, $config, $logger); diff --git a/apps/dav/tests/unit/CalDAV/Publishing/PublisherTest.php b/apps/dav/tests/unit/CalDAV/Publishing/PublisherTest.php index 769e153764671..a410b0f210dbd 100644 --- a/apps/dav/tests/unit/CalDAV/Publishing/PublisherTest.php +++ b/apps/dav/tests/unit/CalDAV/Publishing/PublisherTest.php @@ -1,4 +1,5 @@ assertEquals($rows[3]['notification_date'], 123600); - $reminderId = (int) $rows[3]['id']; + $reminderId = (int) $rows[3]['id']; $newNotificationDate = 123700; $this->reminderBackend->updateReminder($reminderId, $newNotificationDate); diff --git a/apps/dav/tests/unit/CalDAV/Reminder/NotifierTest.php b/apps/dav/tests/unit/CalDAV/Reminder/NotifierTest.php index dcf11a1a6b833..396cf480b4070 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/NotifierTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/NotifierTest.php @@ -59,7 +59,7 @@ protected function setUp(): void { ->method('n') ->willReturnCallback(function ($textSingular, $textPlural, $count, $args) { $text = $count === 1 ? $textSingular : $textPlural; - $text = str_replace('%n', (string)$count, $text); + $text = str_replace('%n', (string) $count, $text); return vsprintf($text, $args); }); $this->factory = $this->createMock(IFactory::class); diff --git a/apps/dav/tests/unit/CalDAV/Reminder/ReminderServiceTest.php b/apps/dav/tests/unit/CalDAV/Reminder/ReminderServiceTest.php index d4594291d8858..198c8d97b125d 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/ReminderServiceTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/ReminderServiceTest.php @@ -35,13 +35,13 @@ class ReminderServiceTest extends TestCase { /** @var IUserManager|MockObject */ private $userManager; - /** @var IGroupManager|MockObject*/ + /** @var IGroupManager|MockObject */ private $groupManager; /** @var CalDavBackend|MockObject */ private $caldavBackend; - /** @var ITimeFactory|MockObject */ + /** @var ITimeFactory|MockObject */ private $timeFactory; /** @var IConfig|MockObject */ diff --git a/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php b/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php index ed39129fa56b4..1546836a29bed 100644 --- a/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php @@ -1,4 +1,5 @@ l10n->expects(self::once()) ->method('t') diff --git a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php index 7a1d61a083b25..cba61ef0b6121 100644 --- a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php +++ b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php @@ -42,7 +42,7 @@ class PluginTest extends TestCase { /** @var Server|MockObject */ private $server; - /** @var IConfig|MockObject */ + /** @var IConfig|MockObject */ private $config; /** @var LoggerInterface&MockObject */ @@ -348,10 +348,10 @@ public function testPropFindDefaultCalendarUrl(string $principalUri, ?string $ca if (!$exists || $deleted) { if (!$hasExistingCalendars) { $calendarBackend->expects($this->once()) - ->method('createCalendar') - ->with($principalUri, $calendarUri, [ - '{DAV:}displayname' => $displayName, - ]); + ->method('createCalendar') + ->with($principalUri, $calendarUri, [ + '{DAV:}displayname' => $displayName, + ]); $calendarHomeObject->expects($this->exactly($deleted ? 2 : 1)) ->method('getCalDAVBackend') diff --git a/apps/dav/tests/unit/CalDAV/Search/Request/CalendarSearchReportTest.php b/apps/dav/tests/unit/CalDAV/Search/Request/CalendarSearchReportTest.php index cbfd4639ed75e..f9a72ccfba8d0 100644 --- a/apps/dav/tests/unit/CalDAV/Search/Request/CalendarSearchReportTest.php +++ b/apps/dav/tests/unit/CalDAV/Search/Request/CalendarSearchReportTest.php @@ -1,4 +1,5 @@ willThrowException($localServerException); $this->logger->expects(self::once()) ->method('warning') - ->with("Subscription 42 was not refreshed because it violates local access rules", ['exception' => $localServerException]); + ->with('Subscription 42 was not refreshed because it violates local access rules', ['exception' => $localServerException]); $this->connection->queryWebcalFeed($subscription); } diff --git a/apps/dav/tests/unit/CalDAV/WebcalCaching/PluginTest.php b/apps/dav/tests/unit/CalDAV/WebcalCaching/PluginTest.php index 82c03c5cf6844..a7ac444e22f09 100644 --- a/apps/dav/tests/unit/CalDAV/WebcalCaching/PluginTest.php +++ b/apps/dav/tests/unit/CalDAV/WebcalCaching/PluginTest.php @@ -1,4 +1,5 @@ caldavBackend->expects(self::once()) - ->method("createCalendarObject") + ->method('createCalendarObject') ->willThrowException($noInstanceException); $this->logger->expects(self::once()) @@ -298,7 +298,7 @@ public function testRunCreateCalendarBadRequest(string $body, string $contentTyp $badRequestException = new BadRequest("can't add reach calendar url"); $this->caldavBackend->expects(self::once()) - ->method("createCalendarObject") + ->method('createCalendarObject') ->willThrowException($badRequestException); $this->logger->expects(self::once()) diff --git a/apps/dav/tests/unit/CapabilitiesTest.php b/apps/dav/tests/unit/CapabilitiesTest.php index e99f7b8da5f77..76a5e85fdad44 100644 --- a/apps/dav/tests/unit/CapabilitiesTest.php +++ b/apps/dav/tests/unit/CapabilitiesTest.php @@ -1,4 +1,5 @@ getMockBuilder(CardDavBackend::class) - ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->dispatcher, $this->sharingBackend]) - ->onlyMethods(['updateProperties', 'purgeProperties'])->getMock(); + ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->dispatcher, $this->sharingBackend]) + ->onlyMethods(['updateProperties', 'purgeProperties'])->getMock(); // create a new address book $backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); @@ -536,13 +536,13 @@ public function testUpdateProperties(): void { $this->assertSame('UID', $result[0]['name']); $this->assertSame($cardUri, $result[0]['value']); - $this->assertSame($bookId, (int)$result[0]['addressbookid']); - $this->assertSame($cardId, (int)$result[0]['cardid']); + $this->assertSame($bookId, (int) $result[0]['addressbookid']); + $this->assertSame($cardId, (int) $result[0]['cardid']); $this->assertSame('FN', $result[1]['name']); $this->assertSame('John Doe', $result[1]['value']); - $this->assertSame($bookId, (int)$result[1]['addressbookid']); - $this->assertSame($cardId, (int)$result[1]['cardid']); + $this->assertSame($bookId, (int) $result[1]['addressbookid']); + $this->assertSame($cardId, (int) $result[1]['cardid']); // update properties for existing vCard $vCard = new VCard(); @@ -561,8 +561,8 @@ public function testUpdateProperties(): void { $this->assertSame('UID', $result[0]['name']); $this->assertSame($cardUri, $result[0]['value']); - $this->assertSame($bookId, (int)$result[0]['addressbookid']); - $this->assertSame($cardId, (int)$result[0]['cardid']); + $this->assertSame($bookId, (int) $result[0]['addressbookid']); + $this->assertSame($cardId, (int) $result[0]['cardid']); } public function testPurgeProperties(): void { @@ -603,8 +603,8 @@ public function testPurgeProperties(): void { $qResult->closeCursor(); $this->assertSame(1, count($result)); - $this->assertSame(1, (int)$result[0]['addressbookid']); - $this->assertSame(2, (int)$result[0]['cardid']); + $this->assertSame(1, (int) $result[0]['addressbookid']); + $this->assertSame(2, (int) $result[0]['cardid']); } public function testGetCardId(): void { @@ -662,16 +662,16 @@ public function testSearch($pattern, $properties, $options, $expected): void { $query = $this->db->getQueryBuilder(); for ($i = 0; $i < 3; $i++) { $query->insert($this->dbCardsTable) - ->values( - [ - 'addressbookid' => $query->createNamedParameter(0), - 'carddata' => $query->createNamedParameter($vCards[$i]->serialize(), IQueryBuilder::PARAM_LOB), - 'uri' => $query->createNamedParameter('uri' . $i), - 'lastmodified' => $query->createNamedParameter(time()), - 'etag' => $query->createNamedParameter('etag' . $i), - 'size' => $query->createNamedParameter(120), - ] - ); + ->values( + [ + 'addressbookid' => $query->createNamedParameter(0), + 'carddata' => $query->createNamedParameter($vCards[$i]->serialize(), IQueryBuilder::PARAM_LOB), + 'uri' => $query->createNamedParameter('uri' . $i), + 'lastmodified' => $query->createNamedParameter(time()), + 'etag' => $query->createNamedParameter('etag' . $i), + 'size' => $query->createNamedParameter(120), + ] + ); $query->execute(); $vCardIds[] = $query->getLastInsertId(); } @@ -771,16 +771,16 @@ public function dataTestSearch() { public function testGetCardUri(): void { $query = $this->db->getQueryBuilder(); $query->insert($this->dbCardsTable) - ->values( - [ - 'addressbookid' => $query->createNamedParameter(1), - 'carddata' => $query->createNamedParameter('carddata', IQueryBuilder::PARAM_LOB), - 'uri' => $query->createNamedParameter('uri'), - 'lastmodified' => $query->createNamedParameter(5489543), - 'etag' => $query->createNamedParameter('etag'), - 'size' => $query->createNamedParameter(120), - ] - ); + ->values( + [ + 'addressbookid' => $query->createNamedParameter(1), + 'carddata' => $query->createNamedParameter('carddata', IQueryBuilder::PARAM_LOB), + 'uri' => $query->createNamedParameter('uri'), + 'lastmodified' => $query->createNamedParameter(5489543), + 'etag' => $query->createNamedParameter('etag'), + 'size' => $query->createNamedParameter(120), + ] + ); $query->execute(); $id = $query->getLastInsertId(); @@ -799,26 +799,26 @@ public function testGetContact(): void { $query = $this->db->getQueryBuilder(); for ($i = 0; $i < 2; $i++) { $query->insert($this->dbCardsTable) - ->values( - [ - 'addressbookid' => $query->createNamedParameter($i), - 'carddata' => $query->createNamedParameter('carddata' . $i, IQueryBuilder::PARAM_LOB), - 'uri' => $query->createNamedParameter('uri' . $i), - 'lastmodified' => $query->createNamedParameter(5489543), - 'etag' => $query->createNamedParameter('etag' . $i), - 'size' => $query->createNamedParameter(120), - ] - ); + ->values( + [ + 'addressbookid' => $query->createNamedParameter($i), + 'carddata' => $query->createNamedParameter('carddata' . $i, IQueryBuilder::PARAM_LOB), + 'uri' => $query->createNamedParameter('uri' . $i), + 'lastmodified' => $query->createNamedParameter(5489543), + 'etag' => $query->createNamedParameter('etag' . $i), + 'size' => $query->createNamedParameter(120), + ] + ); $query->execute(); } $result = $this->backend->getContact(0, 'uri0'); $this->assertSame(8, count($result)); - $this->assertSame(0, (int)$result['addressbookid']); + $this->assertSame(0, (int) $result['addressbookid']); $this->assertSame('uri0', $result['uri']); - $this->assertSame(5489543, (int)$result['lastmodified']); + $this->assertSame(5489543, (int) $result['lastmodified']); $this->assertSame('"etag0"', $result['etag']); - $this->assertSame(120, (int)$result['size']); + $this->assertSame(120, (int) $result['size']); // this shouldn't return any result because 'uri1' is in address book 1 // see https://github.com/nextcloud/server/issues/229 @@ -842,7 +842,7 @@ public function testCollectCardProperties(): void { 'preferred' => $query->createNamedParameter(0) ] ) - ->execute(); + ->execute(); $result = $this->backend->collectCardProperties(666, 'FN'); $this->assertEquals(['John Doe'], $result); diff --git a/apps/dav/tests/unit/CardDAV/ConverterTest.php b/apps/dav/tests/unit/CardDAV/ConverterTest.php index df6489d505387..a582e31f9f7da 100644 --- a/apps/dav/tests/unit/CardDAV/ConverterTest.php +++ b/apps/dav/tests/unit/CardDAV/ConverterTest.php @@ -53,7 +53,7 @@ protected function getAccountPropertyMock(string $name, ?string $value, string $ ->willReturn($name); $property->expects($this->any()) ->method('getValue') - ->willReturn((string)$value); + ->willReturn((string) $value); $property->expects($this->any()) ->method('getScope') ->willReturn($scope); @@ -89,7 +89,7 @@ public function getAccountManager(IUser $user) { * @dataProvider providesNewUsers */ public function testCreation($expectedVCard, $displayName = null, $eMailAddress = null, $cloudId = null): void { - $user = $this->getUserMock((string)$displayName, $eMailAddress, $cloudId); + $user = $this->getUserMock((string) $displayName, $eMailAddress, $cloudId); $accountManager = $this->getAccountManager($user); $converter = new Converter($accountManager, $this->userManager, $this->urlGenerator, $this->logger); @@ -104,7 +104,7 @@ public function testCreation($expectedVCard, $displayName = null, $eMailAddress } public function testManagerProp(): void { - $user = $this->getUserMock("user", "user@domain.tld", "user@cloud.domain.tld"); + $user = $this->getUserMock('user', 'user@domain.tld', 'user@cloud.domain.tld'); $user->method('getManagerUids') ->willReturn(['mgr']); $this->userManager->expects(self::once()) @@ -168,8 +168,8 @@ public function providesNewUsers() { 'fn' => 'Dr. Foo Bar', 'photo' => 'MTIzNDU2Nzg5', ], - "Dr. Foo Bar", - "foo@bar.net", + 'Dr. Foo Bar', + 'foo@bar.net', 'foo@cloud.net' ], [ @@ -178,9 +178,9 @@ public function providesNewUsers() { 'fn' => 'Dr. Foo Bar', 'photo' => 'MTIzNDU2Nzg5', ], - "Dr. Foo Bar", + 'Dr. Foo Bar', null, - "foo@cloud.net" + 'foo@cloud.net' ], [ [ diff --git a/apps/dav/tests/unit/CardDAV/SystemAddressBookTest.php b/apps/dav/tests/unit/CardDAV/SystemAddressBookTest.php index a1c614cb69dd0..806c71759f8b7 100644 --- a/apps/dav/tests/unit/CardDAV/SystemAddressBookTest.php +++ b/apps/dav/tests/unit/CardDAV/SystemAddressBookTest.php @@ -150,7 +150,7 @@ public function testGetFilteredChildForFederation(): void { ->with(123, 'user.vcf') ->willReturn($originalCard); - $card = $this->addressBook->getChild("user.vcf"); + $card = $this->addressBook->getChild('user.vcf'); /** @var VCard $vCard */ $vCard = Reader::read($card->get()); @@ -180,7 +180,7 @@ public function testGetChildNotFound(): void { ]); $this->expectException(NotFound::class); - $this->addressBook->getChild("LDAP:user.vcf"); + $this->addressBook->getChild('LDAP:user.vcf'); } public function testGetChildWithoutEnumeration(): void { @@ -193,7 +193,7 @@ public function testGetChildWithoutEnumeration(): void { ]); $this->expectException(Forbidden::class); - $this->addressBook->getChild("LDAP:user.vcf"); + $this->addressBook->getChild('LDAP:user.vcf'); } public function testGetChildAsGuest(): void { @@ -211,7 +211,7 @@ public function testGetChildAsGuest(): void { ->willReturn($user); $this->expectException(Forbidden::class); - $this->addressBook->getChild("LDAP:user.vcf"); + $this->addressBook->getChild('LDAP:user.vcf'); } public function testGetChildWithGroupEnumerationRestriction(): void { @@ -272,7 +272,7 @@ public function testGetChildWithPhoneNumberEnumerationRestriction(): void { ->willReturn($user); $this->expectException(Forbidden::class); - $this->addressBook->getChild("LDAP:user.vcf"); + $this->addressBook->getChild('LDAP:user.vcf'); } public function testGetOwnChildWithPhoneNumberEnumerationRestriction(): void { @@ -305,7 +305,7 @@ public function testGetOwnChildWithPhoneNumberEnumerationRestriction(): void { 'carddata' => $cardData, ]); - $this->addressBook->getChild("LDAP:user.vcf"); + $this->addressBook->getChild('LDAP:user.vcf'); } public function testGetMultipleChildrenWithGroupEnumerationRestriction(): void { diff --git a/apps/dav/tests/unit/Command/ListCalendarsTest.php b/apps/dav/tests/unit/Command/ListCalendarsTest.php index 30df9ee79dce7..fcb3658a6fc61 100644 --- a/apps/dav/tests/unit/Command/ListCalendarsTest.php +++ b/apps/dav/tests/unit/Command/ListCalendarsTest.php @@ -1,4 +1,5 @@ execute([ 'uid' => self::USERNAME, ]); - $this->assertStringContainsString("User <" . self::USERNAME . "> in unknown", $commandTester->getDisplay()); + $this->assertStringContainsString('User <' . self::USERNAME . '> in unknown', $commandTester->getDisplay()); } public function testWithCorrectUserWithNoCalendars(): void { @@ -72,7 +73,7 @@ public function testWithCorrectUserWithNoCalendars(): void { $commandTester->execute([ 'uid' => self::USERNAME, ]); - $this->assertStringContainsString("User <" . self::USERNAME . "> has no calendars\n", $commandTester->getDisplay()); + $this->assertStringContainsString('User <' . self::USERNAME . "> has no calendars\n", $commandTester->getDisplay()); } public function dataExecute() { diff --git a/apps/dav/tests/unit/Command/MoveCalendarTest.php b/apps/dav/tests/unit/Command/MoveCalendarTest.php index 09831fdb1b270..aac947cbf4c9f 100644 --- a/apps/dav/tests/unit/Command/MoveCalendarTest.php +++ b/apps/dav/tests/unit/Command/MoveCalendarTest.php @@ -1,4 +1,5 @@ 'user2', ]); - $this->assertStringContainsString("[OK] Calendar was moved from user to ", $commandTester->getDisplay()); + $this->assertStringContainsString('[OK] Calendar was moved from user to ', $commandTester->getDisplay()); } public function dataTestMoveWithDestinationNotPartOfGroup(): array { @@ -240,7 +241,7 @@ public function testMoveWithDestinationNotPartOfGroup(bool $shareWithGroupMember ]); if ($shareWithGroupMembersOnly === true) { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage("User is not part of the group with whom the calendar was shared. You may use -f to move the calendar while deleting this share."); + $this->expectExceptionMessage('User is not part of the group with whom the calendar was shared. You may use -f to move the calendar while deleting this share.'); } $commandTester = new CommandTester($this->command); @@ -294,7 +295,7 @@ public function testMoveWithDestinationPartOfGroup(): void { 'destinationuid' => 'user2', ]); - $this->assertStringContainsString("[OK] Calendar was moved from user to ", $commandTester->getDisplay()); + $this->assertStringContainsString('[OK] Calendar was moved from user to ', $commandTester->getDisplay()); } public function testMoveWithDestinationNotPartOfGroupAndForce(): void { @@ -342,7 +343,7 @@ public function testMoveWithDestinationNotPartOfGroupAndForce(): void { '--force' => true ]); - $this->assertStringContainsString("[OK] Calendar was moved from user to ", $commandTester->getDisplay()); + $this->assertStringContainsString('[OK] Calendar was moved from user to ', $commandTester->getDisplay()); } public function dataTestMoveWithCalendarAlreadySharedToDestination(): array { @@ -380,17 +381,17 @@ public function testMoveWithCalendarAlreadySharedToDestination(bool $force): voi ); $this->calDav->expects($this->once())->method('getShares') - ->with(1234) - ->willReturn([ - [ - 'href' => 'principal:principals/users/user2', - '{DAV:}displayname' => 'Personal' - ] - ]); + ->with(1234) + ->willReturn([ + [ + 'href' => 'principal:principals/users/user2', + '{DAV:}displayname' => 'Personal' + ] + ]); if ($force === false) { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage("The calendar is already shared to user .You may use -f to move the calendar while deleting this share."); + $this->expectExceptionMessage('The calendar is already shared to user .You may use -f to move the calendar while deleting this share.'); } else { $this->calDav->expects($this->once())->method('updateShares'); } diff --git a/apps/dav/tests/unit/Comments/CommentsNodeTest.php b/apps/dav/tests/unit/Comments/CommentsNodeTest.php index d2bb60af4b200..c253c59df0f93 100644 --- a/apps/dav/tests/unit/Comments/CommentsNodeTest.php +++ b/apps/dav/tests/unit/Comments/CommentsNodeTest.php @@ -19,7 +19,7 @@ class CommentsNodeTest extends \Test\TestCase { - /** @var ICommentsManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ICommentsManager|\PHPUnit\Framework\MockObject\MockObject */ protected $commentsManager; protected $comment; diff --git a/apps/dav/tests/unit/Comments/CommentsPluginTest.php b/apps/dav/tests/unit/Comments/CommentsPluginTest.php index 60c3e52ef54aa..5ca0cedf04bac 100644 --- a/apps/dav/tests/unit/Comments/CommentsPluginTest.php +++ b/apps/dav/tests/unit/Comments/CommentsPluginTest.php @@ -29,7 +29,7 @@ class CommentsPluginTest extends \Test\TestCase { /** @var ICommentsManager */ private $commentsManager; - /** @var IUserSession */ + /** @var IUserSession */ private $userSession; /** @var CommentsPluginImplementation */ diff --git a/apps/dav/tests/unit/Connector/Sabre/AuthTest.php b/apps/dav/tests/unit/Connector/Sabre/AuthTest.php index dccb1edd0ae55..de258c9aaec5e 100644 --- a/apps/dav/tests/unit/Connector/Sabre/AuthTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/AuthTest.php @@ -221,11 +221,11 @@ public function testValidateUserPassWithPasswordLoginForbidden(): void { public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForNonGet(): void { $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->userSession ->expects($this->any()) ->method('isLoggedIn') diff --git a/apps/dav/tests/unit/Connector/Sabre/BearerAuthTest.php b/apps/dav/tests/unit/Connector/Sabre/BearerAuthTest.php index 92d5c95f4c714..d4f3287450c69 100644 --- a/apps/dav/tests/unit/Connector/Sabre/BearerAuthTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/BearerAuthTest.php @@ -1,4 +1,5 @@ info->method('getType') ->willReturn(Node::TYPE_FOLDER); $this->info->method('getName') - ->willReturn("folder"); + ->willReturn('folder'); $this->info->method('getPath') - ->willReturn("/admin/files/folder"); + ->willReturn('/admin/files/folder'); $this->info->method('getPermissions') ->willReturn(Constants::PERMISSION_READ); } diff --git a/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php b/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php index 74f90507bb36b..c7fb6066ed41b 100644 --- a/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php @@ -20,7 +20,7 @@ public function testSerialization(): void { $DOM->appendChild($error); // serialize the exception - $message = "1234567890"; + $message = '1234567890'; $retry = false; $expectedXml = << diff --git a/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php b/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php index 3da0c41b7b300..98921d735fa2d 100644 --- a/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php @@ -20,7 +20,7 @@ public function testSerialization(): void { $DOM->appendChild($error); // serialize the exception - $message = "1234567890"; + $message = '1234567890'; $retry = false; $expectedXml = << diff --git a/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php index 40ebc69e42d0f..18165b79cb266 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php @@ -160,11 +160,11 @@ public function testFakeUnlockProvider(): void { ->getMock(); $response->expects($this->once()) - ->method('setStatus') - ->with('204'); + ->method('setStatus') + ->with('204'); $response->expects($this->once()) - ->method('setHeader') - ->with('Content-Length', '0'); + ->method('setHeader') + ->with('Content-Length', '0'); $this->assertSame(false, $this->fakeLockerPlugin->fakeUnlockProvider($request, $response)); } diff --git a/apps/dav/tests/unit/Connector/Sabre/FileTest.php b/apps/dav/tests/unit/Connector/Sabre/FileTest.php index d099a43118413..fb15e5904e728 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FileTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FileTest.php @@ -264,51 +264,51 @@ public function testPutSingleFile(): void { public function legalMtimeProvider() { return [ - "string" => [ - 'HTTP_X_OC_MTIME' => "string", + 'string' => [ + 'HTTP_X_OC_MTIME' => 'string', 'expected result' => null ], - "castable string (int)" => [ - 'HTTP_X_OC_MTIME' => "987654321", + 'castable string (int)' => [ + 'HTTP_X_OC_MTIME' => '987654321', 'expected result' => 987654321 ], - "castable string (float)" => [ - 'HTTP_X_OC_MTIME' => "123456789.56", + 'castable string (float)' => [ + 'HTTP_X_OC_MTIME' => '123456789.56', 'expected result' => 123456789 ], - "float" => [ + 'float' => [ 'HTTP_X_OC_MTIME' => 123456789.56, 'expected result' => 123456789 ], - "zero" => [ + 'zero' => [ 'HTTP_X_OC_MTIME' => 0, 'expected result' => null ], - "zero string" => [ - 'HTTP_X_OC_MTIME' => "0", + 'zero string' => [ + 'HTTP_X_OC_MTIME' => '0', 'expected result' => null ], - "negative zero string" => [ - 'HTTP_X_OC_MTIME' => "-0", + 'negative zero string' => [ + 'HTTP_X_OC_MTIME' => '-0', 'expected result' => null ], - "string starting with number following by char" => [ - 'HTTP_X_OC_MTIME' => "2345asdf", + 'string starting with number following by char' => [ + 'HTTP_X_OC_MTIME' => '2345asdf', 'expected result' => null ], - "string castable hex int" => [ - 'HTTP_X_OC_MTIME' => "0x45adf", + 'string castable hex int' => [ + 'HTTP_X_OC_MTIME' => '0x45adf', 'expected result' => null ], - "string that looks like invalid hex int" => [ - 'HTTP_X_OC_MTIME' => "0x123g", + 'string that looks like invalid hex int' => [ + 'HTTP_X_OC_MTIME' => '0x123g', 'expected result' => null ], - "negative int" => [ + 'negative int' => [ 'HTTP_X_OC_MTIME' => -34, 'expected result' => null ], - "negative float" => [ + 'negative float' => [ 'HTTP_X_OC_MTIME' => -34.43, 'expected result' => null ], @@ -322,7 +322,7 @@ public function legalMtimeProvider() { public function testPutSingleFileLegalMtime($requestMtime, $resultMtime): void { $request = new Request([ 'server' => [ - 'HTTP_X_OC_MTIME' => (string)$requestMtime, + 'HTTP_X_OC_MTIME' => (string) $requestMtime, ] ], $this->requestId, $this->config, null); $file = 'foo.txt'; @@ -905,10 +905,10 @@ private function getFileInfos($path = '', ?View $userView = null) { $userView = Filesystem::getView(); } return [ - "filesize" => $userView->filesize($path), - "mtime" => $userView->filemtime($path), - "filetype" => $userView->filetype($path), - "mimetype" => $userView->getMimeType($path) + 'filesize' => $userView->filesize($path), + 'mtime' => $userView->filemtime($path), + 'filetype' => $userView->filetype($path), + 'mimetype' => $userView->getMimeType($path) ]; } diff --git a/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php index de38f196420b8..fa5cf268471d7 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php @@ -74,8 +74,8 @@ protected function setUp(): void { ); $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $this->server->httpResponse = $response; $this->server->xml = new Service(); @@ -696,8 +696,8 @@ public function testDownloadHeaders($isClumsyAgent, $contentDispositionHeader): ->disableOriginalConstructor() ->getMock(); $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $request ->expects($this->once()) diff --git a/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php b/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php index 28c22202c1e71..9ecc49222e939 100644 --- a/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php @@ -20,7 +20,7 @@ class MaintenancePluginTest extends TestCase { /** @var IConfig */ private $config; - /** @var \PHPUnit\Framework\MockObject\Builder\InvocationMocker|\PHPUnit_Framework_MockObject_Builder_InvocationMocker|IL10N */ + /** @var \PHPUnit\Framework\MockObject\Builder\InvocationMocker|\PHPUnit_Framework_MockObject_Builder_InvocationMocker|IL10N */ private $l10n; /** @var MaintenancePlugin */ private $maintenancePlugin; diff --git a/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php b/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php index f0996a17a3360..5010f7698b5cd 100644 --- a/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php @@ -73,7 +73,7 @@ public function testCopy($sourcePath, $targetPath, $targetParent): void { ->with($this->identicalTo($sourcePath)) ->willReturn(false); - /** @var $objectTree \OCA\DAV\Connector\Sabre\ObjectTree */ + /** @var \OCA\DAV\Connector\Sabre\ObjectTree $objectTree */ $mountManager = Filesystem::getMountManager(); $objectTree->init($rootDir, $view, $mountManager); $objectTree->copy($sourcePath, $targetPath); @@ -114,7 +114,7 @@ public function testCopyFailNotCreatable($sourcePath, $targetPath, $targetParent $objectTree->expects($this->never()) ->method('getNodeForPath'); - /** @var $objectTree \OCA\DAV\Connector\Sabre\ObjectTree */ + /** @var \OCA\DAV\Connector\Sabre\ObjectTree $objectTree */ $mountManager = Filesystem::getMountManager(); $objectTree->init($rootDir, $view, $mountManager); $objectTree->copy($sourcePath, $targetPath); diff --git a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php index 03910f32095af..3595c85eb411b 100644 --- a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php @@ -1,4 +1,5 @@ createMock(User::class); $fooUser - ->expects($this->once()) - ->method('getUID') - ->willReturn('foo'); + ->expects($this->once()) + ->method('getUID') + ->willReturn('foo'); $fooUser - ->expects($this->once()) - ->method('getDisplayName') - ->willReturn('Dr. Foo-Bar'); + ->expects($this->once()) + ->method('getDisplayName') + ->willReturn('Dr. Foo-Bar'); $fooUser - ->expects($this->once()) - ->method('getSystemEMailAddress') - ->willReturn(''); + ->expects($this->once()) + ->method('getSystemEMailAddress') + ->willReturn(''); $barUser = $this->createMock(User::class); $barUser ->expects($this->once()) ->method('getUID') ->willReturn('bar'); $barUser - ->expects($this->once()) - ->method('getSystemEMailAddress') - ->willReturn('bar@nextcloud.com'); + ->expects($this->once()) + ->method('getSystemEMailAddress') + ->willReturn('bar@nextcloud.com'); $this->userManager ->expects($this->once()) ->method('search') @@ -229,13 +230,13 @@ public function testGetPrincipalsByPathWithoutMail(): void { public function testGetPrincipalsByPathWithMail(): void { $fooUser = $this->createMock(User::class); $fooUser - ->expects($this->once()) - ->method('getSystemEMailAddress') - ->willReturn('foo@nextcloud.com'); + ->expects($this->once()) + ->method('getSystemEMailAddress') + ->willReturn('foo@nextcloud.com'); $fooUser - ->expects($this->once()) - ->method('getUID') - ->willReturn('foo'); + ->expects($this->once()) + ->method('getUID') + ->willReturn('foo'); $this->userManager ->expects($this->once()) ->method('get') @@ -851,13 +852,13 @@ public function testFindByUriWithGroupRestriction($uri, $email, $expects): void ->willReturn(true); $this->shareManager->expects($this->once()) - ->method('shareWithGroupMembersOnly') - ->willReturn(true); + ->method('shareWithGroupMembersOnly') + ->willReturn(true); $user = $this->createMock(IUser::class); $this->userSession->expects($this->once()) - ->method('getUser') - ->willReturn($user); + ->method('getUser') + ->willReturn($user); $user2 = $this->createMock(IUser::class); $user2->method('getUID')->willReturn('user2'); @@ -865,9 +866,9 @@ public function testFindByUriWithGroupRestriction($uri, $email, $expects): void $user3->method('getUID')->willReturn('user3'); $this->userManager->expects($this->once()) - ->method('getByEmail') - ->with($email) - ->willReturn([$email === 'user2@foo.bar' ? $user2 : $user3]); + ->method('getByEmail') + ->with($email) + ->willReturn([$email === 'user2@foo.bar' ? $user2 : $user3]); if ($email === 'user2@foo.bar') { $this->groupManager->expects($this->exactly(2)) @@ -912,8 +913,8 @@ public function testFindByUriWithoutGroupRestriction($uri, $email, $expects): vo ->willReturn(true); $this->shareManager->expects($this->once()) - ->method('shareWithGroupMembersOnly') - ->willReturn(false); + ->method('shareWithGroupMembersOnly') + ->willReturn(false); $user2 = $this->createMock(IUser::class); $user2->method('getUID')->willReturn('user2'); @@ -921,9 +922,9 @@ public function testFindByUriWithoutGroupRestriction($uri, $email, $expects): vo $user3->method('getUID')->willReturn('user3'); $this->userManager->expects($this->once()) - ->method('getByEmail') - ->with($email) - ->willReturn([$email === 'user2@foo.bar' ? $user2 : $user3]); + ->method('getByEmail') + ->with($email) + ->willReturn([$email === 'user2@foo.bar' ? $user2 : $user3]); $this->assertEquals($expects, $this->connector->findByUri($uri, 'principals/users')); } diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php index bed5eb192d99b..cf1ea4c6bae02 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php @@ -72,7 +72,7 @@ public function check(RequestInterface $request, ResponseInterface $response) { \OC::$server->getUserFolder($user); return [true, "principals/$user"]; } - return [false, "login failed"]; + return [false, 'login failed']; } /** diff --git a/apps/dav/tests/unit/Controller/BirthdayCalendarControllerTest.php b/apps/dav/tests/unit/Controller/BirthdayCalendarControllerTest.php index c7c2bf0e43168..282a88d250c1b 100644 --- a/apps/dav/tests/unit/Controller/BirthdayCalendarControllerTest.php +++ b/apps/dav/tests/unit/Controller/BirthdayCalendarControllerTest.php @@ -1,4 +1,5 @@ expects($this->once()) ->method('eq') ->with('token', 'namedParameterToken') - ->willReturn((string)$function); + ->willReturn((string) $function); $this->dbConnection->expects($this->once()) ->method('getQueryBuilder') diff --git a/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php b/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php index ea5450391e8ca..2ea5e9c8b9f18 100644 --- a/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php +++ b/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php @@ -1,4 +1,5 @@ fetch()) { $value = $row['propertyvalue']; - if ((int)$row['valuetype'] === CustomPropertiesBackend::PROPERTY_TYPE_HREF) { + if ((int) $row['valuetype'] === CustomPropertiesBackend::PROPERTY_TYPE_HREF) { $value = new Href($value); } $data[$row['propertyname']] = $value; @@ -396,7 +396,7 @@ public function testPropPatchWithUnsuitableCalendar(): void { $this->defaultCalendarValidator->expects(self::once()) ->method('validateScheduleDefaultCalendar') ->with($node) - ->willThrowException(new \Sabre\DAV\Exception("Invalid calendar")); + ->willThrowException(new \Sabre\DAV\Exception('Invalid calendar')); $this->server->method('calculateUri') ->willReturnCallback(function ($uri) { diff --git a/apps/dav/tests/unit/DAV/GroupPrincipalTest.php b/apps/dav/tests/unit/DAV/GroupPrincipalTest.php index 92c89fc62f83b..284d11fa9f13f 100644 --- a/apps/dav/tests/unit/DAV/GroupPrincipalTest.php +++ b/apps/dav/tests/unit/DAV/GroupPrincipalTest.php @@ -1,4 +1,5 @@ shareCache->expects(self::once()) ->method('get') - ->with((string)$resourceId) + ->with((string) $resourceId) ->willReturn(null); $this->calendarService->expects(self::once()) ->method('getShares') @@ -315,7 +315,7 @@ public function testGetShares(): void { ->willReturn(['uri' => $principal, '{DAV:}displayname' => 'bob']); $this->shareCache->expects(self::once()) ->method('set') - ->with((string)$resourceId, $expected); + ->with((string) $resourceId, $expected); $result = $this->backend->getShares($resourceId); $this->assertEquals($expected, $result); @@ -351,7 +351,7 @@ public function testGetSharesAddressbooks(): void { $this->shareCache->expects(self::once()) ->method('get') - ->with((string)$resourceId) + ->with((string) $resourceId) ->willReturn(null); $service->expects(self::once()) ->method('getShares') @@ -363,7 +363,7 @@ public function testGetSharesAddressbooks(): void { ->willReturn(['uri' => $principal, '{DAV:}displayname' => 'bob']); $this->shareCache->expects(self::once()) ->method('set') - ->with((string)$resourceId, $expected); + ->with((string) $resourceId, $expected); $result = $backend->getShares($resourceId); $this->assertEquals($expected, $result); diff --git a/apps/dav/tests/unit/DAV/ViewOnlyPluginTest.php b/apps/dav/tests/unit/DAV/ViewOnlyPluginTest.php index eb15bfe0b5a19..7a4828dd2de53 100644 --- a/apps/dav/tests/unit/DAV/ViewOnlyPluginTest.php +++ b/apps/dav/tests/unit/DAV/ViewOnlyPluginTest.php @@ -132,9 +132,9 @@ public function testCanGet(bool $isVersion, ?bool $attrEnabled, bool $expectCanD $this->request->expects($this->once())->method('getPath')->willReturn($davPath); $this->tree->expects($this->once()) - ->method('getNodeForPath') - ->with($davPath) - ->willReturn($davNode); + ->method('getNodeForPath') + ->with($davPath) + ->willReturn($davNode); $storage = $this->createMock(SharedStorage::class); $share = $this->createMock(IShare::class); @@ -147,9 +147,9 @@ public function testCanGet(bool $isVersion, ?bool $attrEnabled, bool $expectCanD $extAttr = $this->createMock(IAttributes::class); $share->method('getAttributes')->willReturn($extAttr); $extAttr->expects($this->once()) - ->method('getAttribute') - ->with('permissions', 'download') - ->willReturn($attrEnabled); + ->method('getAttribute') + ->with('permissions', 'download') + ->willReturn($attrEnabled); if (!$expectCanDownloadFile) { $this->expectException(Forbidden::class); diff --git a/apps/dav/tests/unit/Files/FileSearchBackendTest.php b/apps/dav/tests/unit/Files/FileSearchBackendTest.php index f6fe8b1c1160a..1ac605eeaef35 100644 --- a/apps/dav/tests/unit/Files/FileSearchBackendTest.php +++ b/apps/dav/tests/unit/Files/FileSearchBackendTest.php @@ -1,4 +1,5 @@ [ - "Content-Length" => 7, - "X-File-MD5" => "4f2377b4d911f7ec46325fe603c3af03", - "X-File-Path" => "/coucou.txt" + 'headers' => [ + 'Content-Length' => 7, + 'X-File-MD5' => '4f2377b4d911f7ec46325fe603c3af03', + 'X-File-Path' => '/coucou.txt' ], - "content" => "Coucou\n" + 'content' => "Coucou\n" ] ]; } - private function getMultipartParser(array $parts, array $headers = [], string $boundary = "boundary_azertyuiop"): MultipartRequestParser { + private function getMultipartParser(array $parts, array $headers = [], string $boundary = 'boundary_azertyuiop'): MultipartRequestParser { $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') ->disableOriginalConstructor() ->getMock(); @@ -43,19 +44,19 @@ private function getMultipartParser(array $parts, array $headers = [], string $b return $headers[$key]; }); - $body = ""; + $body = ''; foreach ($parts as $part) { $body .= '--'.$boundary."\r\n"; foreach ($part['headers'] as $headerKey => $headerPart) { - $body .= $headerKey.": ".$headerPart."\r\n"; + $body .= $headerKey.': '.$headerPart."\r\n"; } $body .= "\r\n"; $body .= $part['content']."\r\n"; } - $body .= '--'.$boundary."--"; + $body .= '--'.$boundary.'--'; $stream = fopen('php://temp', 'r+'); fwrite($stream, $body); @@ -73,7 +74,7 @@ private function getMultipartParser(array $parts, array $headers = [], string $b * Test validation of the request's body type */ public function testBodyTypeValidation(): void { - $bodyStream = "I am not a stream, but pretend to be"; + $bodyStream = 'I am not a stream, but pretend to be'; $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') ->disableOriginalConstructor() ->getMock(); @@ -100,11 +101,11 @@ public function testValidRequest(): void { [$headers, $content] = $multipartParser->parseNextPart(); - $this->assertSame((int)$headers["content-length"], 7, "Content-Length header should be the same as provided."); - $this->assertSame($headers["x-file-md5"], "4f2377b4d911f7ec46325fe603c3af03", "X-File-MD5 header should be the same as provided."); - $this->assertSame($headers["x-file-path"], "/coucou.txt", "X-File-Path header should be the same as provided."); + $this->assertSame((int) $headers['content-length'], 7, 'Content-Length header should be the same as provided.'); + $this->assertSame($headers['x-file-md5'], '4f2377b4d911f7ec46325fe603c3af03', 'X-File-MD5 header should be the same as provided.'); + $this->assertSame($headers['x-file-path'], '/coucou.txt', 'X-File-Path header should be the same as provided.'); - $this->assertSame($content, "Coucou\n", "Content should be the same"); + $this->assertSame($content, "Coucou\n", 'Content should be the same'); } /** @@ -112,7 +113,7 @@ public function testValidRequest(): void { */ public function testInvalidMd5Hash(): void { $bodyObject = $this->getValidBodyObject(); - $bodyObject["0"]["headers"]["X-File-MD5"] = "f2377b4d911f7ec46325fe603c3af03"; + $bodyObject['0']['headers']['X-File-MD5'] = 'f2377b4d911f7ec46325fe603c3af03'; $multipartParser = $this->getMultipartParser( $bodyObject ); @@ -126,7 +127,7 @@ public function testInvalidMd5Hash(): void { */ public function testNullMd5Hash(): void { $bodyObject = $this->getValidBodyObject(); - unset($bodyObject["0"]["headers"]["X-File-MD5"]); + unset($bodyObject['0']['headers']['X-File-MD5']); $multipartParser = $this->getMultipartParser( $bodyObject ); @@ -140,7 +141,7 @@ public function testNullMd5Hash(): void { */ public function testNullContentLength(): void { $bodyObject = $this->getValidBodyObject(); - unset($bodyObject["0"]["headers"]["Content-Length"]); + unset($bodyObject['0']['headers']['Content-Length']); $multipartParser = $this->getMultipartParser( $bodyObject ); @@ -154,7 +155,7 @@ public function testNullContentLength(): void { */ public function testLowerContentLength(): void { $bodyObject = $this->getValidBodyObject(); - $bodyObject["0"]["headers"]["Content-Length"] = 6; + $bodyObject['0']['headers']['Content-Length'] = 6; $multipartParser = $this->getMultipartParser( $bodyObject ); @@ -168,7 +169,7 @@ public function testLowerContentLength(): void { */ public function testHigherContentLength(): void { $bodyObject = $this->getValidBodyObject(); - $bodyObject["0"]["headers"]["Content-Length"] = 8; + $bodyObject['0']['headers']['Content-Length'] = 8; $multipartParser = $this->getMultipartParser( $bodyObject ); diff --git a/apps/dav/tests/unit/Files/Sharing/FilesDropPluginTest.php b/apps/dav/tests/unit/Files/Sharing/FilesDropPluginTest.php index 7264119f8c688..b5994f985abd5 100644 --- a/apps/dav/tests/unit/Files/Sharing/FilesDropPluginTest.php +++ b/apps/dav/tests/unit/Files/Sharing/FilesDropPluginTest.php @@ -1,4 +1,5 @@ config->method('getAppValue') - ->withConsecutive( - ['dav', 'sendInvitations', 'yes'], - ['dav', 'generateBirthdayCalendar', 'yes'], - ['dav', 'sendEventReminders', 'yes'], - ['dav', 'sendEventRemindersToSharedUsers', 'yes'], - ['dav', 'sendEventRemindersPush', 'yes'], - ) - ->will($this->onConsecutiveCalls('yes', 'no', 'yes', 'yes', 'yes')); + ->withConsecutive( + ['dav', 'sendInvitations', 'yes'], + ['dav', 'generateBirthdayCalendar', 'yes'], + ['dav', 'sendEventReminders', 'yes'], + ['dav', 'sendEventRemindersToSharedUsers', 'yes'], + ['dav', 'sendEventRemindersPush', 'yes'], + ) + ->will($this->onConsecutiveCalls('yes', 'no', 'yes', 'yes', 'yes')); $this->urlGenerator ->expects($this->once()) ->method('linkToDocs') diff --git a/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php b/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php index 51711fc166655..67e7afa9c548a 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php @@ -543,11 +543,11 @@ public function testCreateTagInByIdCollection($userVisible, $userAssignable, $gr ->willReturn($node); $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $request->expects($this->once()) ->method('getPath') @@ -617,11 +617,11 @@ public function testCreateTagInMappingCollection(): void { ->with(1); $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $request->expects($this->once()) ->method('getPath') @@ -666,11 +666,11 @@ public function testCreateTagToUnknownNode(): void { ->method('createFile'); $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $request->expects($this->once()) ->method('getPath') @@ -714,11 +714,11 @@ public function testCreateTagConflict($nodeClass): void { ->willReturn($node); $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $request->expects($this->once()) ->method('getPath') diff --git a/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php b/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php index b202f340e328f..a2a877073f729 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php @@ -70,7 +70,7 @@ protected function setUp(): void { return $node !== null; }; $writeAccessClosure = function ($name) use ($userFolder) { - $nodes = $userFolder->getById((int)$name); + $nodes = $userFolder->getById((int) $name); foreach ($nodes as $node) { if (($node->getPermissions() & Constants::PERMISSION_UPDATE) === Constants::PERMISSION_UPDATE) { return true; diff --git a/apps/dav/tests/unit/Upload/AssemblyStreamTest.php b/apps/dav/tests/unit/Upload/AssemblyStreamTest.php index 6d821976f4e38..217713eca3301 100644 --- a/apps/dav/tests/unit/Upload/AssemblyStreamTest.php +++ b/apps/dav/tests/unit/Upload/AssemblyStreamTest.php @@ -55,11 +55,11 @@ public function providesNodes() { $dataLess8k = $this->makeData(8191); $tonofnodes = []; - $tonofdata = ""; + $tonofdata = ''; for ($i = 0; $i < 101; $i++) { $thisdata = random_int(0, 100); // variable length and content $tonofdata .= $thisdata; - $tonofnodes[] = $this->buildNode((string)$i, (string)$thisdata); + $tonofnodes[] = $this->buildNode((string) $i, (string) $thisdata); } return[ diff --git a/apps/encryption/lib/Command/DisableMasterKey.php b/apps/encryption/lib/Command/DisableMasterKey.php index 7993ba38078f8..4af4301db01e8 100644 --- a/apps/encryption/lib/Command/DisableMasterKey.php +++ b/apps/encryption/lib/Command/DisableMasterKey.php @@ -1,4 +1,5 @@ writeln("Specifying a user id and --all are mutually exclusive"); + $output->writeln('Specifying a user id and --all are mutually exclusive'); return 1; } @@ -96,20 +96,20 @@ protected function execute(InputInterface $input, OutputInterface $output): int } elseif ($all) { $result = 0; $this->userManager->callForSeenUsers(function (IUser $user) use ($pathOption, $output, &$result) { - $output->writeln("Processing files for " . $user->getUID()); + $output->writeln('Processing files for ' . $user->getUID()); $result = $this->runForUser($user->getUID(), $pathOption, $output); return $result === 0; }); return $result; } else { - $output->writeln("Either a user id or --all needs to be provided"); + $output->writeln('Either a user id or --all needs to be provided'); return 1; } } private function runForUser(string $user, string $pathOption, OutputInterface $output): int { $pathToWalk = "/$user/files"; - if ($pathOption !== "") { + if ($pathOption !== '') { $pathToWalk = "$pathToWalk/$pathOption"; } return $this->walkPathOfUser($user, $pathToWalk, $output); @@ -205,7 +205,7 @@ private function verifyFileContent(string $path, OutputInterface $output, bool $ } return false; } catch (HintException $e) { - $this->logger->warning("Issue: " . $e->getMessage()); + $this->logger->warning('Issue: ' . $e->getMessage()); // If allowOnce is set to false, this becomes recursive. if ($ignoreCorrectEncVersionCall === true) { // Lets rectify the file by correcting encrypted version @@ -254,7 +254,7 @@ private function correctEncryptedVersion(string $path, OutputInterface $output, // try with zero first $cacheInfo = ['encryptedVersion' => 0, 'encrypted' => 0]; $cache->put($fileCache->getPath(), $cacheInfo); - $output->writeln("Set the encrypted version to 0 (unencrypted)"); + $output->writeln('Set the encrypted version to 0 (unencrypted)'); if ($this->verifyFileContent($path, $output, false) === true) { $output->writeln("Fixed the file: \"$path\" with version 0 (unencrypted)"); return true; @@ -268,7 +268,7 @@ private function correctEncryptedVersion(string $path, OutputInterface $output, $cache->put($fileCache->getPath(), $cacheInfo); $output->writeln("Decrement the encrypted version to $encryptedVersion"); if ($this->verifyFileContent($path, $output, false) === true) { - $output->writeln("Fixed the file: \"$path\" with version " . $encryptedVersion . ""); + $output->writeln("Fixed the file: \"$path\" with version " . $encryptedVersion . ''); return true; } $encryptedVersion--; @@ -291,7 +291,7 @@ private function correctEncryptedVersion(string $path, OutputInterface $output, $cache->put($fileCache->getPath(), $cacheInfo); $output->writeln("Increment the encrypted version to $newEncryptedVersion"); if ($this->verifyFileContent($path, $output, false) === true) { - $output->writeln("Fixed the file: \"$path\" with version " . $newEncryptedVersion . ""); + $output->writeln("Fixed the file: \"$path\" with version " . $newEncryptedVersion . ''); return true; } $increment++; diff --git a/apps/encryption/lib/Command/FixKeyLocation.php b/apps/encryption/lib/Command/FixKeyLocation.php index cb3408f77f13d..4e6742b91a94e 100644 --- a/apps/encryption/lib/Command/FixKeyLocation.php +++ b/apps/encryption/lib/Command/FixKeyLocation.php @@ -50,7 +50,7 @@ public function __construct( $this->keyRootDirectory = rtrim($this->encryptionUtil->getKeyStorageRoot(), '/'); $this->rootView = new View(); if (!$encryptionManager instanceof Manager) { - throw new \Exception("Wrong encryption manager"); + throw new \Exception('Wrong encryption manager'); } $this->encryptionManager = $encryptionManager; @@ -65,7 +65,7 @@ protected function configure(): void { ->setName('encryption:fix-key-location') ->setDescription('Fix the location of encryption keys for external storage') ->addOption('dry-run', null, InputOption::VALUE_NONE, "Only list files that require key migration, don't try to perform any migration") - ->addArgument('user', InputArgument::REQUIRED, "User id to fix the key locations for"); + ->addArgument('user', InputArgument::REQUIRED, 'User id to fix the key locations for'); } protected function execute(InputInterface $input, OutputInterface $output): int { @@ -83,7 +83,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int foreach ($mounts as $mount) { $mountRootFolder = $this->rootFolder->get($mount->getMountPoint()); if (!$mountRootFolder instanceof Folder) { - $output->writeln("System wide mount point is not a directory, skipping: " . $mount->getMountPoint() . ""); + $output->writeln('System wide mount point is not a directory, skipping: ' . $mount->getMountPoint() . ''); continue; } @@ -97,14 +97,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int // key was stored incorrectly as user key, migrate if ($dryRun) { - $output->writeln("" . $file->getPath() . " needs migration"); + $output->writeln('' . $file->getPath() . ' needs migration'); } else { - $output->write("Migrating key for " . $file->getPath() . " "); + $output->write('Migrating key for ' . $file->getPath() . ' '); if ($this->copyUserKeyToSystemAndValidate($user, $file)) { - $output->writeln(""); + $output->writeln(''); } else { - $output->writeln("❌"); - $output->writeln(" Failed to validate key for " . $file->getPath() . ", key will not be migrated"); + $output->writeln('❌'); + $output->writeln(' Failed to validate key for ' . $file->getPath() . ', key will not be migrated'); } } } else { @@ -115,42 +115,42 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($isActuallyEncrypted) { if ($dryRun) { if ($shouldBeEncrypted) { - $output->write("" . $file->getPath() . " needs migration"); + $output->write('' . $file->getPath() . ' needs migration'); } else { - $output->write("" . $file->getPath() . " needs decryption"); + $output->write('' . $file->getPath() . ' needs decryption'); } $foundKey = $this->findUserKeyForSystemFile($user, $file); if ($foundKey) { - $output->writeln(", valid key found at " . $foundKey . ""); + $output->writeln(', valid key found at ' . $foundKey . ''); } else { - $output->writeln(" ❌ No key found"); + $output->writeln(' ❌ No key found'); } } else { if ($shouldBeEncrypted) { - $output->write("Migrating key for " . $file->getPath() . ""); + $output->write('Migrating key for ' . $file->getPath() . ''); } else { - $output->write("Decrypting " . $file->getPath() . ""); + $output->write('Decrypting ' . $file->getPath() . ''); } $foundKey = $this->findUserKeyForSystemFile($user, $file); if ($foundKey) { if ($shouldBeEncrypted) { $systemKeyPath = $this->getSystemKeyPath($file); $this->rootView->copy($foundKey, $systemKeyPath); - $output->writeln(" Migrated key from " . $foundKey . ""); + $output->writeln(' Migrated key from ' . $foundKey . ''); } else { $this->decryptWithSystemKey($file, $foundKey); - $output->writeln(" Decrypted with key from " . $foundKey . ""); + $output->writeln(' Decrypted with key from ' . $foundKey . ''); } } else { - $output->writeln(" ❌ No key found"); + $output->writeln(' ❌ No key found'); } } } else { if ($dryRun) { - $output->writeln("" . $file->getPath() . " needs to be marked as not encrypted"); + $output->writeln('' . $file->getPath() . ' needs to be marked as not encrypted'); } else { $this->markAsUnEncrypted($file); - $output->writeln("" . $file->getPath() . " marked as not encrypted"); + $output->writeln('' . $file->getPath() . ' marked as not encrypted'); } } } @@ -288,7 +288,7 @@ private function openWithoutDecryption(File $node, string $mode) { } /** @var resource|false $handle */ if ($handle === false) { - throw new \Exception("Failed to open " . $node->getPath()); + throw new \Exception('Failed to open ' . $node->getPath()); } return $handle; } @@ -339,7 +339,7 @@ private function findKeysByFileName(string $basePath, string $name) { /** @var false|resource $dh */ $dh = $this->rootView->opendir($basePath); if (!$dh) { - throw new \Exception("Invalid base path " . $basePath); + throw new \Exception('Invalid base path ' . $basePath); } while ($child = readdir($dh)) { if ($child != '..' && $child != '.') { @@ -398,7 +398,7 @@ private function decryptWithSystemKey(File $node, string $key): void { /** @var false|resource $source */ $source = $storage->fopen($node->getInternalPath(), 'r'); if (!$source) { - throw new \Exception("Failed to open " . $node->getPath() . " with " . $key); + throw new \Exception('Failed to open ' . $node->getPath() . ' with ' . $key); } $decryptedNode = $node->getParent()->newFile($name); @@ -418,7 +418,7 @@ private function decryptWithSystemKey(File $node, string $key): void { } if ($this->isDataEncrypted($decryptedNode)) { - throw new \Exception($node->getPath() . " still encrypted after attempting to decrypt with " . $key); + throw new \Exception($node->getPath() . ' still encrypted after attempting to decrypt with ' . $key); } $this->markAsUnEncrypted($decryptedNode); diff --git a/apps/encryption/lib/Command/RecoverUser.php b/apps/encryption/lib/Command/RecoverUser.php index fcdc3f15fb537..cb331b8d7dcc8 100644 --- a/apps/encryption/lib/Command/RecoverUser.php +++ b/apps/encryption/lib/Command/RecoverUser.php @@ -1,4 +1,5 @@ l->t('Bad Signature')); } else { - $this->logger->info("Signature check skipped", ['app' => 'encryption']); + $this->logger->info('Signature check skipped', ['app' => 'encryption']); } } } @@ -751,7 +751,7 @@ private function opensslOpen(string $data, string &$output, string $encrypted_ke $result = false; // check if RC4 is used - if (strcasecmp($cipher_algo, "rc4") === 0) { + if (strcasecmp($cipher_algo, 'rc4') === 0) { // decrypt the intermediate key with RSA if (openssl_private_decrypt($encrypted_key, $intermediate, $private_key, OPENSSL_PKCS1_PADDING)) { // decrypt the file key with the intermediate key @@ -776,7 +776,7 @@ private function opensslSeal(string $data, string &$sealed_data, array &$encrypt $result = false; // check if RC4 is used - if (strcasecmp($cipher_algo, "rc4") === 0) { + if (strcasecmp($cipher_algo, 'rc4') === 0) { // make sure that there is at least one public key to use if (count($public_key) >= 1) { // generate the intermediate key diff --git a/apps/encryption/lib/Crypto/DecryptAll.php b/apps/encryption/lib/Crypto/DecryptAll.php index e1eb1ba6a2a9b..80c187571b7db 100644 --- a/apps/encryption/lib/Crypto/DecryptAll.php +++ b/apps/encryption/lib/Crypto/DecryptAll.php @@ -18,19 +18,19 @@ class DecryptAll { - /** @var Util */ + /** @var Util */ protected $util; - /** @var QuestionHelper */ + /** @var QuestionHelper */ protected $questionHelper; - /** @var Crypt */ + /** @var Crypt */ protected $crypt; - /** @var KeyManager */ + /** @var KeyManager */ protected $keyManager; - /** @var Session */ + /** @var Session */ protected $session; /** diff --git a/apps/encryption/lib/Crypto/EncryptAll.php b/apps/encryption/lib/Crypto/EncryptAll.php index 09b418836d981..310f37aba838a 100644 --- a/apps/encryption/lib/Crypto/EncryptAll.php +++ b/apps/encryption/lib/Crypto/EncryptAll.php @@ -44,28 +44,28 @@ class EncryptAll { /** @var Util */ protected $util; - /** @var array */ + /** @var array */ protected $userPasswords; - /** @var IConfig */ + /** @var IConfig */ protected $config; /** @var IMailer */ protected $mailer; - /** @var IL10N */ + /** @var IL10N */ protected $l; - /** @var IFactory */ + /** @var IFactory */ protected $l10nFactory; - /** @var QuestionHelper */ + /** @var QuestionHelper */ protected $questionHelper; - /** @var OutputInterface */ + /** @var OutputInterface */ protected $output; - /** @var InputInterface */ + /** @var InputInterface */ protected $input; /** @var ISecureRandom */ @@ -203,7 +203,7 @@ protected function encryptAllUsersFiles() { $userNo++; } } - $progress->setMessage("all files encrypted"); + $progress->setMessage('all files encrypted'); $progress->finish(); } diff --git a/apps/encryption/lib/Crypto/Encryption.php b/apps/encryption/lib/Crypto/Encryption.php index dda93e1330631..04fee2fd92ae7 100644 --- a/apps/encryption/lib/Crypto/Encryption.php +++ b/apps/encryption/lib/Crypto/Encryption.php @@ -99,8 +99,8 @@ public function getDisplayName() { * @param array $accessList who has access to the file contains the key 'users' and 'public' * * @return array $header contain data as key-value pairs which should be - * written to the header, in case of a write operation - * or if no additional data is needed return a empty array + * written to the header, in case of a write operation + * or if no additional data is needed return a empty array */ public function begin($path, $user, $mode, array $header, array $accessList) { $this->path = $this->getPathToRealFile($path); @@ -131,7 +131,7 @@ public function begin($path, $user, $mode, array $header, array $accessList) { // always use the version from the original file, also part files // need to have a correct version number if they get moved over to the // final location - $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View()); + $this->version = (int) $this->keyManager->getVersion($this->stripPartFileExtension($path), new View()); if ( $mode === 'w' @@ -285,7 +285,7 @@ public function encrypt($data, $position = 0) { // Read the chunk from the start of $data $chunk = substr($data, 0, $this->getUnencryptedBlockSize(true)); - $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, (string)$position); + $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, (string) $position); // Remove the chunk we just processed from // $data, leaving only unprocessed data in $data diff --git a/apps/encryption/lib/Exceptions/PrivateKeyMissingException.php b/apps/encryption/lib/Exceptions/PrivateKeyMissingException.php index 9e3dea67f3efa..15fe8f4e72f68 100644 --- a/apps/encryption/lib/Exceptions/PrivateKeyMissingException.php +++ b/apps/encryption/lib/Exceptions/PrivateKeyMissingException.php @@ -16,7 +16,7 @@ class PrivateKeyMissingException extends GenericEncryptionException { */ public function __construct($userId) { if (empty($userId)) { - $userId = ""; + $userId = ''; } parent::__construct("Private Key missing for user: $userId"); } diff --git a/apps/encryption/lib/Exceptions/PublicKeyMissingException.php b/apps/encryption/lib/Exceptions/PublicKeyMissingException.php index 3173f0fb44a37..78eeeccf47d1e 100644 --- a/apps/encryption/lib/Exceptions/PublicKeyMissingException.php +++ b/apps/encryption/lib/Exceptions/PublicKeyMissingException.php @@ -16,7 +16,7 @@ class PublicKeyMissingException extends GenericEncryptionException { */ public function __construct($userId) { if (empty($userId)) { - $userId = ""; + $userId = ''; } parent::__construct("Public Key missing for user: $userId"); } diff --git a/apps/encryption/lib/HookManager.php b/apps/encryption/lib/HookManager.php index 71fa4f0a08e62..6ad56ebad782c 100644 --- a/apps/encryption/lib/HookManager.php +++ b/apps/encryption/lib/HookManager.php @@ -15,7 +15,7 @@ class HookManager { /** * @param array|IHook $instances - * - This accepts either a single instance of IHook or an array of instances of IHook + * - This accepts either a single instance of IHook or an array of instances of IHook * @return bool */ public function registerHook($instances) { diff --git a/apps/encryption/lib/KeyManager.php b/apps/encryption/lib/KeyManager.php index 9fd6c7655afd5..7b55a04f06921 100644 --- a/apps/encryption/lib/KeyManager.php +++ b/apps/encryption/lib/KeyManager.php @@ -42,7 +42,7 @@ public function __construct( $this->recoveryKeyId = $this->config->getAppValue('encryption', 'recoveryKeyId'); if (empty($this->recoveryKeyId)) { - $this->recoveryKeyId = 'recoveryKey_' . substr(md5((string)time()), 0, 8); + $this->recoveryKeyId = 'recoveryKey_' . substr(md5((string) time()), 0, 8); $this->config->setAppValue('encryption', 'recoveryKeyId', $this->recoveryKeyId); @@ -51,14 +51,14 @@ public function __construct( $this->publicShareKeyId = $this->config->getAppValue('encryption', 'publicShareKeyId'); if (empty($this->publicShareKeyId)) { - $this->publicShareKeyId = 'pubShare_' . substr(md5((string)time()), 0, 8); + $this->publicShareKeyId = 'pubShare_' . substr(md5((string) time()), 0, 8); $this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId); } $this->masterKeyId = $this->config->getAppValue('encryption', 'masterKeyId'); if (empty($this->masterKeyId)) { - $this->masterKeyId = 'master_' . substr(md5((string)time()), 0, 8); + $this->masterKeyId = 'master_' . substr(md5((string) time()), 0, 8); $this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId); } diff --git a/apps/encryption/lib/Migration/SetMasterKeyStatus.php b/apps/encryption/lib/Migration/SetMasterKeyStatus.php index 598f2dd516a37..91c8e8acac698 100644 --- a/apps/encryption/lib/Migration/SetMasterKeyStatus.php +++ b/apps/encryption/lib/Migration/SetMasterKeyStatus.php @@ -1,4 +1,5 @@
-

t("Default encryption module")); ?>

- - t("Encryption app is enabled but your keys are not initialized, please log-out and log-in again")); ?> +

t('Default encryption module')); ?>

+ + t('Encryption app is enabled but your keys are not initialized, please log-out and log-in again')); ?>

/>
- t("Enabling this option encrypts all files stored on the main storage, otherwise only files on external storage will be encrypted")); ?> + t('Enabling this option encrypts all files stored on the main storage, otherwise only files on external storage will be encrypted')); ?>


- t("Enable recovery key")) : p($l->t("Disable recovery key")); ?> + t('Enable recovery key')) : p($l->t('Disable recovery key')); ?>
- t("The recovery key is an additional encryption key used to encrypt files. It is used to recover files from an account if the password is forgotten.")) ?> + t('The recovery key is an additional encryption key used to encrypt files. It is used to recover files from an account if the password is forgotten.')) ?>
"/> + placeholder="t('Recovery key password')); ?>"/> "/> + placeholder="t('Repeat recovery key password')); ?>"/> " - value="t("Enable recovery key")) : p($l->t("Disable recovery key")); ?>"/> + status="" + value="t('Enable recovery key')) : p($l->t('Disable recovery key')); ?>"/>



> - t("Change recovery key password:")); ?> + t('Change recovery key password:')); ?>
"/> + placeholder="t('Old recovery key password')); ?>"/>
"/> + placeholder="t('New recovery key password')); ?>"/> "/> + placeholder="t('Repeat new recovery key password')); ?>"/>

diff --git a/apps/encryption/templates/settings-personal.php b/apps/encryption/templates/settings-personal.php index a875c3c6ed63c..18b5ef341b9e5 100644 --- a/apps/encryption/templates/settings-personal.php +++ b/apps/encryption/templates/settings-personal.php @@ -12,19 +12,19 @@

t('Basic encryption module')); ?>

- + - t("Encryption App is enabled, but your keys are not initialized. Please log-out and log-in again.")); ?> + t('Encryption App is enabled, but your keys are not initialized. Please log-out and log-in again.')); ?> - +


- t("Set your old private key password to your current log-in password:")); ?> - t('Set your old private key password to your current log-in password:')); ?> + t('If you do not remember your old password you can ask your administrator to recover your files.')); endif; ?>
@@ -32,29 +32,29 @@ type="password" name="changePrivateKeyPassword" id="oldPrivateKeyPassword" /> - +
- +

- +

- +
- t("Enabling this option will allow you to reobtain access to your encrypted files in case of password loss")); ?> + t('Enabling this option will allow you to reobtain access to your encrypted files in case of password loss')); ?>
/> - + /> +
/> - + /> +

diff --git a/apps/encryption/tests/Command/FixEncryptedVersionTest.php b/apps/encryption/tests/Command/FixEncryptedVersionTest.php index 9ea981e355d8b..c021c366ad89b 100644 --- a/apps/encryption/tests/Command/FixEncryptedVersionTest.php +++ b/apps/encryption/tests/Command/FixEncryptedVersionTest.php @@ -79,7 +79,7 @@ public function testEncryptedVersionLessThanOriginalValue() { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); - $view = new View("/" . $this->userId . "/files"); + $view = new View('/' . $this->userId . '/files'); $view->touch('hello.txt'); $view->touch('world.txt'); @@ -147,7 +147,7 @@ public function testEncryptedVersionGreaterThanOriginalValue() { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); - $view = new View("/" . $this->userId . "/files"); + $view = new View('/' . $this->userId . '/files'); $view->touch('hello.txt'); $view->touch('world.txt'); @@ -206,7 +206,7 @@ public function testVersionIsRestoredToOriginalIfNoFixIsFound() { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); - $view = new View("/" . $this->userId . "/files"); + $view = new View('/' . $this->userId . '/files'); $view->touch('bar.txt'); for ($i = 0; $i < 40; $i++) { @@ -227,7 +227,7 @@ public function testVersionIsRestoredToOriginalIfNoFixIsFound() { ]); $cacheInfo = $cache->get($fileInfo->getId()); - $encryptedVersion = $cacheInfo["encryptedVersion"]; + $encryptedVersion = $cacheInfo['encryptedVersion']; $this->assertEquals(15, $encryptedVersion); } @@ -236,7 +236,7 @@ public function testRepairUnencryptedFileWhenVersionIsSet() { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); - $view = new View("/" . $this->userId . "/files"); + $view = new View('/' . $this->userId . '/files'); // create a file, it's encrypted and also the version is set in the database $view->touch('hello.txt'); @@ -279,14 +279,14 @@ public function testExecuteWithFilePathOption() { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); - $view = new View("/" . $this->userId . "/files"); + $view = new View('/' . $this->userId . '/files'); $view->touch('hello.txt'); $view->touch('world.txt'); $this->commandTester->execute([ 'user' => $this->userId, - '--path' => "/hello.txt" + '--path' => '/hello.txt' ]); $output = $this->commandTester->getDisplay(); @@ -303,7 +303,7 @@ public function testExecuteWithDirectoryPathOption() { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); - $view = new View("/" . $this->userId . "/files"); + $view = new View('/' . $this->userId . '/files'); $view->mkdir('sub'); $view->touch('sub/hello.txt'); @@ -311,7 +311,7 @@ public function testExecuteWithDirectoryPathOption() { $this->commandTester->execute([ 'user' => $this->userId, - '--path' => "/sub" + '--path' => '/sub' ]); $output = $this->commandTester->getDisplay(); @@ -327,7 +327,7 @@ public function testExecuteWithNoUser() { $this->commandTester->execute([ 'user' => null, - '--path' => "/" + '--path' => '/' ]); $output = $this->commandTester->getDisplay(); @@ -341,7 +341,7 @@ public function testExecuteWithBadUser() { $this->commandTester->execute([ 'user' => 'nonexisting', - '--path' => "/" + '--path' => '/' ]); $output = $this->commandTester->getDisplay(); diff --git a/apps/encryption/tests/Command/TestEnableMasterKey.php b/apps/encryption/tests/Command/TestEnableMasterKey.php index 8e7dabf8bb60c..47bc978627d90 100644 --- a/apps/encryption/tests/Command/TestEnableMasterKey.php +++ b/apps/encryption/tests/Command/TestEnableMasterKey.php @@ -17,22 +17,22 @@ class TestEnableMasterKey extends TestCase { - /** @var EnableMasterKey */ + /** @var EnableMasterKey */ protected $enableMasterKey; - /** @var Util | \PHPUnit\Framework\MockObject\MockObject */ + /** @var Util | \PHPUnit\Framework\MockObject\MockObject */ protected $util; - /** @var \OCP\IConfig | \PHPUnit\Framework\MockObject\MockObject */ + /** @var \OCP\IConfig | \PHPUnit\Framework\MockObject\MockObject */ protected $config; /** @var \Symfony\Component\Console\Helper\QuestionHelper | \PHPUnit\Framework\MockObject\MockObject */ protected $questionHelper; - /** @var \Symfony\Component\Console\Output\OutputInterface | \PHPUnit\Framework\MockObject\MockObject */ + /** @var \Symfony\Component\Console\Output\OutputInterface | \PHPUnit\Framework\MockObject\MockObject */ protected $output; - /** @var \Symfony\Component\Console\Input\InputInterface | \PHPUnit\Framework\MockObject\MockObject */ + /** @var \Symfony\Component\Console\Input\InputInterface | \PHPUnit\Framework\MockObject\MockObject */ protected $input; protected function setUp(): void { diff --git a/apps/encryption/tests/Controller/StatusControllerTest.php b/apps/encryption/tests/Controller/StatusControllerTest.php index 3c59a80fe15cf..26210946cce9c 100644 --- a/apps/encryption/tests/Controller/StatusControllerTest.php +++ b/apps/encryption/tests/Controller/StatusControllerTest.php @@ -22,10 +22,10 @@ class StatusControllerTest extends TestCase { /** @var \OCP\IL10N|\PHPUnit\Framework\MockObject\MockObject */ private $l10nMock; - /** @var \OCA\Encryption\Session | \PHPUnit\Framework\MockObject\MockObject */ + /** @var \OCA\Encryption\Session | \PHPUnit\Framework\MockObject\MockObject */ protected $sessionMock; - /** @var IManager | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IManager | \PHPUnit\Framework\MockObject\MockObject */ protected $encryptionManagerMock; /** @var StatusController */ diff --git a/apps/encryption/tests/Crypto/CryptTest.php b/apps/encryption/tests/Crypto/CryptTest.php index eea4186377ccd..97f78b668562b 100644 --- a/apps/encryption/tests/Crypto/CryptTest.php +++ b/apps/encryption/tests/Crypto/CryptTest.php @@ -125,9 +125,9 @@ public function dataTestGenerateHeader() { public function testGetCipherWithInvalidCipher() { $this->config->expects($this->once()) - ->method('getSystemValueString') - ->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR')) - ->willReturn('Not-Existing-Cipher'); + ->method('getSystemValueString') + ->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR')) + ->willReturn('Not-Existing-Cipher'); $this->logger ->expects($this->once()) ->method('warning') diff --git a/apps/encryption/tests/Crypto/DecryptAllTest.php b/apps/encryption/tests/Crypto/DecryptAllTest.php index 7723fd5ce4ff7..2a46e5428040f 100644 --- a/apps/encryption/tests/Crypto/DecryptAllTest.php +++ b/apps/encryption/tests/Crypto/DecryptAllTest.php @@ -17,22 +17,22 @@ class DecryptAllTest extends TestCase { - /** @var DecryptAll */ + /** @var DecryptAll */ protected $instance; - /** @var Util | \PHPUnit\Framework\MockObject\MockObject */ + /** @var Util | \PHPUnit\Framework\MockObject\MockObject */ protected $util; - /** @var KeyManager | \PHPUnit\Framework\MockObject\MockObject */ + /** @var KeyManager | \PHPUnit\Framework\MockObject\MockObject */ protected $keyManager; - /** @var Crypt | \PHPUnit\Framework\MockObject\MockObject */ + /** @var Crypt | \PHPUnit\Framework\MockObject\MockObject */ protected $crypt; - /** @var Session | \PHPUnit\Framework\MockObject\MockObject */ + /** @var Session | \PHPUnit\Framework\MockObject\MockObject */ protected $session; - /** @var QuestionHelper | \PHPUnit\Framework\MockObject\MockObject */ + /** @var QuestionHelper | \PHPUnit\Framework\MockObject\MockObject */ protected $questionHelper; protected function setUp(): void { diff --git a/apps/encryption/tests/Crypto/EncryptAllTest.php b/apps/encryption/tests/Crypto/EncryptAllTest.php index ec05c422dd46c..a63b826bf3c36 100644 --- a/apps/encryption/tests/Crypto/EncryptAllTest.php +++ b/apps/encryption/tests/Crypto/EncryptAllTest.php @@ -29,49 +29,49 @@ class EncryptAllTest extends TestCase { - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCA\Encryption\KeyManager */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \OCA\Encryption\KeyManager */ protected $keyManager; - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCA\Encryption\Util */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \OCA\Encryption\Util */ protected $util; - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\IUserManager */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\IUserManager */ protected $userManager; - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCA\Encryption\Users\Setup */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \OCA\Encryption\Users\Setup */ protected $setupUser; - /** @var \PHPUnit\Framework\MockObject\MockObject | \OC\Files\View */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \OC\Files\View */ protected $view; - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\IConfig */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\IConfig */ protected $config; - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\Mail\IMailer */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\Mail\IMailer */ protected $mailer; - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\IL10N */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\IL10N */ protected $l; - /** @var \PHPUnit\Framework\MockObject\MockObject | IFactory */ + /** @var \PHPUnit\Framework\MockObject\MockObject | IFactory */ protected $l10nFactory; - /** @var \PHPUnit\Framework\MockObject\MockObject | \Symfony\Component\Console\Helper\QuestionHelper */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \Symfony\Component\Console\Helper\QuestionHelper */ protected $questionHelper; - /** @var \PHPUnit\Framework\MockObject\MockObject | \Symfony\Component\Console\Input\InputInterface */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \Symfony\Component\Console\Input\InputInterface */ protected $inputInterface; - /** @var \PHPUnit\Framework\MockObject\MockObject | \Symfony\Component\Console\Output\OutputInterface */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \Symfony\Component\Console\Output\OutputInterface */ protected $outputInterface; - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\UserInterface */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\UserInterface */ protected $userInterface; - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\Security\ISecureRandom */ + /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\Security\ISecureRandom */ protected $secureRandom; - /** @var EncryptAll */ + /** @var EncryptAll */ protected $encryptAll; protected function setUp(): void { @@ -136,7 +136,7 @@ protected function setUp(): void { } public function testEncryptAll() { - /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ + /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ $encryptAll = $this->getMockBuilder(EncryptAll::class) ->setConstructorArgs( [ @@ -165,7 +165,7 @@ public function testEncryptAll() { } public function testEncryptAllWithMasterKey() { - /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ + /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ $encryptAll = $this->getMockBuilder(EncryptAll::class) ->setConstructorArgs( [ @@ -195,7 +195,7 @@ public function testEncryptAllWithMasterKey() { } public function testCreateKeyPairs() { - /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ + /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ $encryptAll = $this->getMockBuilder(EncryptAll::class) ->setConstructorArgs( [ @@ -245,7 +245,7 @@ function ($user) { } public function testEncryptAllUsersFiles() { - /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ + /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ $encryptAll = $this->getMockBuilder(EncryptAll::class) ->setConstructorArgs( [ @@ -281,7 +281,7 @@ public function testEncryptAllUsersFiles() { } public function testEncryptUsersFiles() { - /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ + /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ $encryptAll = $this->getMockBuilder(EncryptAll::class) ->setConstructorArgs( [ diff --git a/apps/encryption/tests/EncryptedStorageTest.php b/apps/encryption/tests/EncryptedStorageTest.php index 8c38586eb3352..26d5d9c494115 100644 --- a/apps/encryption/tests/EncryptedStorageTest.php +++ b/apps/encryption/tests/EncryptedStorageTest.php @@ -31,23 +31,23 @@ class EncryptedStorageTest extends TestCase { use UserTrait; public function testMoveFromEncrypted() { - $this->createUser("test1", "test2"); - $this->setupForUser("test1", 'test2'); + $this->createUser('test1', 'test2'); + $this->setupForUser('test1', 'test2'); $unwrapped = new Temporary(); - $this->registerMount("test1", new TemporaryNoEncrypted(), "/test1/files/unenc"); - $this->registerMount("test1", $unwrapped, "/test1/files/enc"); + $this->registerMount('test1', new TemporaryNoEncrypted(), '/test1/files/unenc'); + $this->registerMount('test1', $unwrapped, '/test1/files/enc'); - $this->loginWithEncryption("test1"); + $this->loginWithEncryption('test1'); - $view = new View("/test1/files"); + $view = new View('/test1/files'); /** @var IMountManager $mountManager */ $mountManager = \OC::$server->get(IMountManager::class); - $encryptedMount = $mountManager->find("/test1/files/enc"); - $unencryptedMount = $mountManager->find("/test1/files/unenc"); + $encryptedMount = $mountManager->find('/test1/files/enc'); + $unencryptedMount = $mountManager->find('/test1/files/unenc'); $encryptedStorage = $encryptedMount->getStorage(); $unencryptedStorage = $unencryptedMount->getStorage(); $encryptedCache = $encryptedStorage->getCache(); @@ -56,15 +56,15 @@ public function testMoveFromEncrypted() { $this->assertTrue($encryptedStorage->instanceOfStorage(Encryption::class)); $this->assertFalse($unencryptedStorage->instanceOfStorage(Encryption::class)); - $encryptedStorage->file_put_contents("foo.txt", "bar"); - $this->assertEquals("bar", $encryptedStorage->file_get_contents("foo.txt")); - $this->assertStringStartsWith("HBEGIN:oc_encryption_module:", $unwrapped->file_get_contents("foo.txt")); + $encryptedStorage->file_put_contents('foo.txt', 'bar'); + $this->assertEquals('bar', $encryptedStorage->file_get_contents('foo.txt')); + $this->assertStringStartsWith('HBEGIN:oc_encryption_module:', $unwrapped->file_get_contents('foo.txt')); - $this->assertTrue($encryptedCache->get("foo.txt")->isEncrypted()); + $this->assertTrue($encryptedCache->get('foo.txt')->isEncrypted()); - $view->rename("enc/foo.txt", "unenc/foo.txt"); + $view->rename('enc/foo.txt', 'unenc/foo.txt'); - $this->assertEquals("bar", $unencryptedStorage->file_get_contents("foo.txt")); - $this->assertFalse($unencryptedCache->get("foo.txt")->isEncrypted()); + $this->assertEquals('bar', $unencryptedStorage->file_get_contents('foo.txt')); + $this->assertFalse($unencryptedCache->get('foo.txt')->isEncrypted()); } } diff --git a/apps/encryption/tests/SessionTest.php b/apps/encryption/tests/SessionTest.php index 098120e2b039b..61e57f66611be 100644 --- a/apps/encryption/tests/SessionTest.php +++ b/apps/encryption/tests/SessionTest.php @@ -183,15 +183,15 @@ protected function setUp(): void { $this->sessionMock->expects($this->any()) ->method('set') - ->willReturnCallback([$this, "setValueTester"]); + ->willReturnCallback([$this, 'setValueTester']); $this->sessionMock->expects($this->any()) ->method('get') - ->willReturnCallback([$this, "getValueTester"]); + ->willReturnCallback([$this, 'getValueTester']); $this->sessionMock->expects($this->any()) ->method('remove') - ->willReturnCallback([$this, "removeValueTester"]); + ->willReturnCallback([$this, 'removeValueTester']); $this->instance = new Session($this->sessionMock); diff --git a/apps/encryption/tests/Settings/AdminTest.php b/apps/encryption/tests/Settings/AdminTest.php index 80f7803baddf9..05db5185cf442 100644 --- a/apps/encryption/tests/Settings/AdminTest.php +++ b/apps/encryption/tests/Settings/AdminTest.php @@ -1,4 +1,5 @@ notifications->sendUpdateToRemote($remote, $remoteId, $token, $action, $data, $try); @@ -75,7 +75,7 @@ protected function reAddJob(IJobList $jobList, array $argument): void { 'token' => $argument['token'], 'data' => $argument['data'], 'action' => $argument['action'], - 'try' => (int)$argument['try'] + 1, + 'try' => (int) $argument['try'] + 1, 'lastRun' => $this->time->getTime() ] ); @@ -85,7 +85,7 @@ protected function reAddJob(IJobList $jobList, array $argument): void { * Test if it is time for the next run */ protected function shouldRun(array $argument): bool { - $lastRun = (int)$argument['lastRun']; + $lastRun = (int) $argument['lastRun']; return (($this->time->getTime() - $lastRun) > $this->interval); } } diff --git a/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php b/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php index b5b5806d335d6..249e0a42f98f0 100644 --- a/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php +++ b/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php @@ -1,4 +1,5 @@ |JSONResponse - * 200: Remote URL returned - * 400: Creating share is not possible + * 200: Remote URL returned + * 400: Creating share is not possible */ #[NoCSRFRequired] #[PublicPage] diff --git a/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php b/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php index 5edb80b016b33..bfab62c975057 100644 --- a/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php +++ b/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php @@ -51,7 +51,7 @@ class RequestHandlerController extends OCSController { /** @var AddressHandler */ private $addressHandler; - /** @var IUserManager */ + /** @var IUserManager */ private $userManager; /** @var string */ @@ -385,7 +385,7 @@ public function updatePermissions(int $id, ?string $token = null, ?int $permissi try { $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file'); - $ocmPermissions = $this->ncPermissions2ocmPermissions((int)$ncPermissions); + $ocmPermissions = $this->ncPermissions2ocmPermissions((int) $ncPermissions); $notification = ['sharedSecret' => $token, 'permission' => $ocmPermissions]; $provider->notificationReceived('RESHARE_CHANGE_PERMISSION', $id, $notification); $this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent('Federated share with id "%s" has updated permissions "%s"', [$id, implode(', ', $ocmPermissions)])); diff --git a/apps/federatedfilesharing/lib/FederatedShareProvider.php b/apps/federatedfilesharing/lib/FederatedShareProvider.php index 8a8f76ffaf592..29983c7981255 100644 --- a/apps/federatedfilesharing/lib/FederatedShareProvider.php +++ b/apps/federatedfilesharing/lib/FederatedShareProvider.php @@ -271,7 +271,7 @@ protected function getShareFromExternalShareTable(IShare $share) { $result = $qResult->fetchAll(); $qResult->closeCursor(); - if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) { + if (isset($result[0]) && (int) $result[0]['remote_id'] > 0) { return $result[0]; } @@ -329,12 +329,12 @@ public function update(IShare $share) { */ $qb = $this->dbConnection->getQueryBuilder(); $qb->update('share') - ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))) - ->set('permissions', $qb->createNamedParameter($share->getPermissions())) - ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner())) - ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy())) - ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE)) - ->execute(); + ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))) + ->set('permissions', $qb->createNamedParameter($share->getPermissions())) + ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner())) + ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy())) + ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE)) + ->execute(); // send the updated permission to the owner/initiator, if they are not the same if ($share->getShareOwner() !== $share->getSharedBy()) { @@ -405,7 +405,7 @@ public function storeRemoteId(int $shareId, string $remoteId): void { public function getRemoteId(IShare $share): string { $query = $this->dbConnection->getQueryBuilder(); $query->select('remote_id')->from('federated_reshares') - ->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId()))); + ->where($query->expr()->eq('share_id', $query->createNamedParameter((int) $share->getId()))); $result = $query->execute(); $data = $result->fetch(); $result->closeCursor(); @@ -414,7 +414,7 @@ public function getRemoteId(IShare $share): string { throw new ShareNotFound(); } - return (string)$data['remote_id']; + return (string) $data['remote_id']; } /** @@ -549,7 +549,7 @@ public function restore(IShare $share, string $recipient): IShare { public function getSharesInFolder($userId, Folder $node, $reshares, $shallow = true) { if (!$shallow) { - throw new \Exception("non-shallow getSharesInFolder is no longer supported"); + throw new \Exception('non-shallow getSharesInFolder is no longer supported'); } $qb = $this->dbConnection->getQueryBuilder(); @@ -805,15 +805,15 @@ private function getRawShare($id) { */ private function createShareObject($data) { $share = new Share($this->rootFolder, $this->userManager); - $share->setId((int)$data['id']) - ->setShareType((int)$data['share_type']) - ->setPermissions((int)$data['permissions']) + $share->setId((int) $data['id']) + ->setShareType((int) $data['share_type']) + ->setPermissions((int) $data['permissions']) ->setTarget($data['file_target']) - ->setMailSend((bool)$data['mail_send']) + ->setMailSend((bool) $data['mail_send']) ->setToken($data['token']); $shareTime = new \DateTime(); - $shareTime->setTimestamp((int)$data['stime']); + $shareTime->setTimestamp((int) $data['stime']); $share->setShareTime($shareTime); $share->setSharedWith($data['share_with']); @@ -823,13 +823,13 @@ private function createShareObject($data) { } else { //OLD SHARE $share->setSharedBy($data['uid_owner']); - $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']); + $path = $this->getNode($share->getSharedBy(), (int) $data['file_source']); $owner = $path->getOwner(); $share->setShareOwner($owner->getUID()); } - $share->setNodeId((int)$data['file_source']); + $share->setNodeId((int) $data['file_source']); $share->setNodeType($data['item_type']); $share->setProviderId($this->identifier()); diff --git a/apps/federatedfilesharing/lib/Notifications.php b/apps/federatedfilesharing/lib/Notifications.php index 947427141b37c..1725e28832b6e 100644 --- a/apps/federatedfilesharing/lib/Notifications.php +++ b/apps/federatedfilesharing/lib/Notifications.php @@ -116,7 +116,7 @@ public function requestReShare($token, $id, $shareId, $remote, $shareWith, $perm ]; $ocmFields = $fields; - $ocmFields['remoteId'] = (string)$id; + $ocmFields['remoteId'] = (string) $id; $ocmFields['localId'] = $shareId; $ocmFields['name'] = $filename; @@ -286,7 +286,7 @@ protected function getTimestamp() { * @return array * @throws \Exception */ - protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action = "share") { + protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action = 'share') { if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) { $remoteDomain = 'https://' . $remoteDomain; } diff --git a/apps/federatedfilesharing/lib/OCM/CloudFederationProviderFiles.php b/apps/federatedfilesharing/lib/OCM/CloudFederationProviderFiles.php index e1bbbbc310f6c..9a06e7b349be6 100644 --- a/apps/federatedfilesharing/lib/OCM/CloudFederationProviderFiles.php +++ b/apps/federatedfilesharing/lib/OCM/CloudFederationProviderFiles.php @@ -1,4 +1,5 @@ getNode()->getId(); + $fileId = (int) $share->getNode()->getId(); [$file, $link] = $this->getFile($this->getCorrectUid($share), $fileId); } catch (\Exception $e) { throw new ShareNotFound(); @@ -382,7 +383,7 @@ protected function executeDeclineShare(IShare $share) { $this->federatedShareProvider->removeShareFromTable($share); try { - $fileId = (int)$share->getNode()->getId(); + $fileId = (int) $share->getNode()->getId(); [$file, $link] = $this->getFile($this->getCorrectUid($share), $fileId); } catch (\Exception $e) { throw new ShareNotFound(); @@ -431,7 +432,7 @@ private function undoReshare($id, array $notification) { */ private function unshare($id, array $notification) { if (!$this->isS2SEnabled(true)) { - throw new ActionNotSupportedException("incoming shares disabled!"); + throw new ActionNotSupportedException('incoming shares disabled!'); } if (!isset($notification['sharedSecret'])) { @@ -474,12 +475,12 @@ private function unshare($id, array $notification) { // delete all child in case of a group share $qb = $this->connection->getQueryBuilder(); $qb->delete('share_external') - ->where($qb->expr()->eq('parent', $qb->createNamedParameter((int)$share['id']))); + ->where($qb->expr()->eq('parent', $qb->createNamedParameter((int) $share['id']))); $qb->execute(); $ownerDisplayName = $this->getUserDisplayName($owner->getId()); - if ((int)$share['share_type'] === IShare::TYPE_USER) { + if ((int) $share['share_type'] === IShare::TYPE_USER) { if ($share['accepted']) { $path = trim($mountpoint, '/'); } else { @@ -488,7 +489,7 @@ private function unshare($id, array $notification) { $notification = $this->notificationManager->createNotification(); $notification->setApp('files_sharing') ->setUser($share['user']) - ->setObject('remote_share', (int)$share['id']); + ->setObject('remote_share', (int) $share['id']); $this->notificationManager->markProcessed($notification); $event = $this->activityManager->generateEvent(); @@ -496,7 +497,7 @@ private function unshare($id, array $notification) { ->setType('remote_share') ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path, $ownerDisplayName]) ->setAffectedUser($user) - ->setObject('remote_share', (int)$share['id'], $path); + ->setObject('remote_share', (int) $share['id'], $path); \OC::$server->getActivityManager()->publish($event); } } @@ -540,7 +541,7 @@ protected function reshareRequested($id, array $notification) { $share = $this->federatedShareProvider->getShareById($id); // We have to respect the default share permissions - $permissions = $share->getPermissions() & (int)$this->config->getAppValue('core', 'shareapi_default_permissions', (string)Constants::PERMISSION_ALL); + $permissions = $share->getPermissions() & (int) $this->config->getAppValue('core', 'shareapi_default_permissions', (string) Constants::PERMISSION_ALL); $share->setPermissions($permissions); // don't allow to share a file back to the owner @@ -563,7 +564,7 @@ protected function reshareRequested($id, array $notification) { $share->setSharedBy($share->getSharedWith()); $share->setSharedWith($shareWith); $result = $this->federatedShareProvider->create($share); - $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $senderId); + $this->federatedShareProvider->storeRemoteId((int) $result->getId(), $senderId); return ['token' => $result->getToken(), 'providerId' => $result->getId()]; } else { throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id); diff --git a/apps/federatedfilesharing/lib/Settings/Admin.php b/apps/federatedfilesharing/lib/Settings/Admin.php index bb41aede1c8ed..508eaab96654f 100644 --- a/apps/federatedfilesharing/lib/Settings/Admin.php +++ b/apps/federatedfilesharing/lib/Settings/Admin.php @@ -1,4 +1,5 @@ time->getTime(); + $created = isset($argument['created']) ? (int) $argument['created'] : $this->time->getTime(); $currentTime = $this->time->getTime(); $source = $this->urlGenerator->getAbsoluteURL('/'); $source = rtrim($source, '/'); diff --git a/apps/federation/lib/BackgroundJob/RequestSharedSecret.php b/apps/federation/lib/BackgroundJob/RequestSharedSecret.php index a1d0d2b0df06a..ce681b6fbd139 100644 --- a/apps/federation/lib/BackgroundJob/RequestSharedSecret.php +++ b/apps/federation/lib/BackgroundJob/RequestSharedSecret.php @@ -84,7 +84,7 @@ protected function parentStart(IJobList $jobList): void { */ protected function run($argument) { $target = $argument['url']; - $created = isset($argument['created']) ? (int)$argument['created'] : $this->time->getTime(); + $created = isset($argument['created']) ? (int) $argument['created'] : $this->time->getTime(); $currentTime = $this->time->getTime(); $source = $this->urlGenerator->getAbsoluteURL('/'); $source = rtrim($source, '/'); @@ -149,7 +149,7 @@ protected function run($argument) { */ protected function reAddJob(array $argument): void { $url = $argument['url']; - $created = isset($argument['created']) ? (int)$argument['created'] : $this->time->getTime(); + $created = isset($argument['created']) ? (int) $argument['created'] : $this->time->getTime(); $token = $argument['token']; $attempt = $this->getAttempt($argument) + 1; diff --git a/apps/federation/lib/DbHandler.php b/apps/federation/lib/DbHandler.php index ca05417d76820..7d9fe4dd2f998 100644 --- a/apps/federation/lib/DbHandler.php +++ b/apps/federation/lib/DbHandler.php @@ -196,7 +196,7 @@ public function getSharedSecret(string $url): string { $statement = $query->executeQuery(); $result = $statement->fetch(); $statement->closeCursor(); - return (string)$result['shared_secret']; + return (string) $result['shared_secret']; } /** @@ -206,8 +206,8 @@ public function setServerStatus(string $url, int $status, ?string $token = null) $hash = $this->hash($url); $query = $this->connection->getQueryBuilder(); $query->update($this->dbTable) - ->set('status', $query->createNamedParameter($status)) - ->where($query->expr()->eq('url_hash', $query->createNamedParameter($hash))); + ->set('status', $query->createNamedParameter($status)) + ->where($query->expr()->eq('url_hash', $query->createNamedParameter($hash))); if (!is_null($token)) { $query->set('sync_token', $query->createNamedParameter($token)); } @@ -221,13 +221,13 @@ public function getServerStatus(string $url): int { $hash = $this->hash($url); $query = $this->connection->getQueryBuilder(); $query->select('status')->from($this->dbTable) - ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash'))) - ->setParameter('url_hash', $hash); + ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash'))) + ->setParameter('url_hash', $hash); $statement = $query->executeQuery(); $result = $statement->fetch(); $statement->closeCursor(); - return (int)$result['status']; + return (int) $result['status']; } /** @@ -262,7 +262,7 @@ public function auth(string $username, string $password): bool { } $query = $this->connection->getQueryBuilder(); $query->select('url')->from($this->dbTable) - ->where($query->expr()->eq('shared_secret', $query->createNamedParameter($password))); + ->where($query->expr()->eq('shared_secret', $query->createNamedParameter($password))); $statement = $query->executeQuery(); $result = $statement->fetch(); diff --git a/apps/federation/lib/Settings/Admin.php b/apps/federation/lib/Settings/Admin.php index 56e27eda2b9ad..88d81f7818e24 100644 --- a/apps/federation/lib/Settings/Admin.php +++ b/apps/federation/lib/Settings/Admin.php @@ -1,4 +1,5 @@ l->t("Trusted servers"); + return $this->l->t('Trusted servers'); } public function getAuthorizedAppConfig(): array { diff --git a/apps/federation/lib/SyncFederationAddressBooks.php b/apps/federation/lib/SyncFederationAddressBooks.php index 1b47c92db1a4c..aaed6ca9d9469 100644 --- a/apps/federation/lib/SyncFederationAddressBooks.php +++ b/apps/federation/lib/SyncFederationAddressBooks.php @@ -50,7 +50,7 @@ public function syncThemAll(\Closure $callback) { continue; } $targetBookId = $trustedServer['url_hash']; - $targetPrincipal = "principals/system/system"; + $targetPrincipal = 'principals/system/system'; $targetBookProperties = [ '{DAV:}displayname' => $url ]; diff --git a/apps/federation/templates/settings-admin.php b/apps/federation/templates/settings-admin.php index dabd341ce72da..80340611b2ec8 100644 --- a/apps/federation/templates/settings-admin.php +++ b/apps/federation/templates/settings-admin.php @@ -19,12 +19,12 @@
  • - + diff --git a/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php index a53bfb8d4c1af..bc3e971fad2d0 100644 --- a/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php +++ b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php @@ -33,7 +33,7 @@ class GetSharedSecretTest extends TestCase { /** @var \PHPUnit\Framework\MockObject\MockObject|IClient */ private $httpClient; - /** @var \PHPUnit\Framework\MockObject\MockObject|IClientService */ + /** @var \PHPUnit\Framework\MockObject\MockObject|IClientService */ private $httpClientService; /** @var \PHPUnit\Framework\MockObject\MockObject|IJobList */ @@ -42,7 +42,7 @@ class GetSharedSecretTest extends TestCase { /** @var \PHPUnit\Framework\MockObject\MockObject|IURLGenerator */ private $urlGenerator; - /** @var \PHPUnit\Framework\MockObject\MockObject|TrustedServers */ + /** @var \PHPUnit\Framework\MockObject\MockObject|TrustedServers */ private $trustedServers; /** @var \PHPUnit\Framework\MockObject\MockObject|LoggerInterface */ diff --git a/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php index 9bfc6239301c3..7d67de38f5f39 100644 --- a/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php +++ b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php @@ -50,7 +50,7 @@ class RequestSharedSecretTest extends TestCase { /** @var MockObject|ITimeFactory */ private $timeFactory; - /** @var RequestSharedSecret */ + /** @var RequestSharedSecret */ private $requestSharedSecret; protected function setUp(): void { diff --git a/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php b/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php index ef008b991f5f9..9f2d41a10724c 100644 --- a/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php +++ b/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php @@ -23,7 +23,7 @@ class OCSAuthAPIControllerTest extends TestCase { /** @var \PHPUnit\Framework\MockObject\MockObject|IRequest */ private $request; - /** @var \PHPUnit\Framework\MockObject\MockObject|ISecureRandom */ + /** @var \PHPUnit\Framework\MockObject\MockObject|ISecureRandom */ private $secureRandom; /** @var \PHPUnit\Framework\MockObject\MockObject|JobList */ diff --git a/apps/federation/tests/DbHandlerTest.php b/apps/federation/tests/DbHandlerTest.php index fa06807d110cd..2dc6a54dbbd15 100644 --- a/apps/federation/tests/DbHandlerTest.php +++ b/apps/federation/tests/DbHandlerTest.php @@ -18,16 +18,16 @@ */ class DbHandlerTest extends TestCase { - /** @var DbHandler */ + /** @var DbHandler */ private $dbHandler; /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject */ private $il10n; - /** @var IDBConnection */ + /** @var IDBConnection */ private $connection; - /** @var string */ + /** @var string */ private $dbTable = 'trusted_servers'; protected function setUp(): void { @@ -72,9 +72,9 @@ public function testAddServer($url, $expectedUrl, $expectedHash) { $qResult->closeCursor(); $this->assertSame(1, count($result)); $this->assertSame($expectedUrl, $result[0]['url']); - $this->assertSame($id, (int)$result[0]['id']); + $this->assertSame($id, (int) $result[0]['id']); $this->assertSame($expectedHash, $result[0]['url_hash']); - $this->assertSame(TrustedServers::STATUS_PENDING, (int)$result[0]['status']); + $this->assertSame(TrustedServers::STATUS_PENDING, (int) $result[0]['status']); } public function dataTestAddServer() { @@ -97,8 +97,8 @@ public function testRemove() { $this->assertSame(2, count($result)); $this->assertSame('server1', $result[0]['url']); $this->assertSame('server2', $result[1]['url']); - $this->assertSame($id1, (int)$result[0]['id']); - $this->assertSame($id2, (int)$result[1]['id']); + $this->assertSame($id1, (int) $result[0]['id']); + $this->assertSame($id2, (int) $result[1]['id']); $this->dbHandler->removeServer($id2); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); @@ -108,7 +108,7 @@ public function testRemove() { $qResult->closeCursor(); $this->assertSame(1, count($result)); $this->assertSame('server1', $result[0]['url']); - $this->assertSame($id1, (int)$result[0]['id']); + $this->assertSame($id1, (int) $result[0]['id']); } @@ -128,8 +128,8 @@ public function testGetAll() { $this->assertSame(2, count($result)); $this->assertSame('server1', $result[0]['url']); $this->assertSame('server2', $result[1]['url']); - $this->assertSame($id1, (int)$result[0]['id']); - $this->assertSame($id2, (int)$result[1]['id']); + $this->assertSame($id1, (int) $result[0]['id']); + $this->assertSame($id2, (int) $result[1]['id']); } /** @@ -216,7 +216,7 @@ public function testSetServerStatus() { $result = $qResult->fetchAll(); $qResult->closeCursor(); $this->assertSame(1, count($result)); - $this->assertSame(TrustedServers::STATUS_PENDING, (int)$result[0]['status']); + $this->assertSame(TrustedServers::STATUS_PENDING, (int) $result[0]['status']); $this->dbHandler->setServerStatus('http://server1', TrustedServers::STATUS_OK); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); @@ -224,7 +224,7 @@ public function testSetServerStatus() { $result = $qResult->fetchAll(); $qResult->closeCursor(); $this->assertSame(1, count($result)); - $this->assertSame(TrustedServers::STATUS_OK, (int)$result[0]['status']); + $this->assertSame(TrustedServers::STATUS_OK, (int) $result[0]['status']); } public function testGetServerStatus() { diff --git a/apps/federation/tests/Middleware/AddServerMiddlewareTest.php b/apps/federation/tests/Middleware/AddServerMiddlewareTest.php index 5cdd255a4977a..85b918a80f1c3 100644 --- a/apps/federation/tests/Middleware/AddServerMiddlewareTest.php +++ b/apps/federation/tests/Middleware/AddServerMiddlewareTest.php @@ -17,7 +17,7 @@ class AddServerMiddlewareTest extends TestCase { - /** @var \PHPUnit\Framework\MockObject\MockObject | LoggerInterface */ + /** @var \PHPUnit\Framework\MockObject\MockObject | LoggerInterface */ private $logger; /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\IL10N */ @@ -25,7 +25,7 @@ class AddServerMiddlewareTest extends TestCase { private AddServerMiddleware $middleware; - /** @var \PHPUnit\Framework\MockObject\MockObject | SettingsController */ + /** @var \PHPUnit\Framework\MockObject\MockObject | SettingsController */ private $controller; protected function setUp(): void { diff --git a/apps/federation/tests/Settings/AdminTest.php b/apps/federation/tests/Settings/AdminTest.php index 3bbf4c4a9e73e..5b2ad29ea47ab 100644 --- a/apps/federation/tests/Settings/AdminTest.php +++ b/apps/federation/tests/Settings/AdminTest.php @@ -1,4 +1,5 @@ setMethods(['normalizeUrl', 'updateProtocol']) ->getMock(); $trustedServers->expects($this->once())->method('updateProtocol') - ->with('url')->willReturn('https://url'); + ->with('url')->willReturn('https://url'); $this->timeFactory->method('getTime') ->willReturn(1234567); $this->dbHandler->expects($this->once())->method('addServer')->with('https://url') @@ -127,9 +127,9 @@ public function testAddSharedSecret(): void { public function testGetSharedSecret(): void { $this->dbHandler->expects($this->once()) - ->method('getSharedSecret') - ->with('url') - ->willReturn('secret'); + ->method('getSharedSecret') + ->with('url') + ->willReturn('secret'); $this->assertSame( $this->trustedServers->getSharedSecret('url'), 'secret' diff --git a/apps/files/ajax/download.php b/apps/files/ajax/download.php index fc434f79e2c2c..b5129119afb1f 100644 --- a/apps/files/ajax/download.php +++ b/apps/files/ajax/download.php @@ -9,8 +9,8 @@ OC_Util::checkLoggedIn(); \OC::$server->getSession()->close(); -$files = isset($_GET['files']) ? (string)$_GET['files'] : ''; -$dir = isset($_GET['dir']) ? (string)$_GET['dir'] : ''; +$files = isset($_GET['files']) ? (string) $_GET['files'] : ''; +$dir = isset($_GET['dir']) ? (string) $_GET['dir'] : ''; $files_list = json_decode($files); // in case we get only a single file diff --git a/apps/files/lib/Activity/FavoriteProvider.php b/apps/files/lib/Activity/FavoriteProvider.php index 00f1387df94fa..de645dfc933cf 100644 --- a/apps/files/lib/Activity/FavoriteProvider.php +++ b/apps/files/lib/Activity/FavoriteProvider.php @@ -1,4 +1,5 @@ getAppValue('files', 'max_chunk_size', (string)(10 * 1024 * 1024)); + $maxChunkSize = (int) Server::get(IConfig::class)->getAppValue('files', 'max_chunk_size', (string) (10 * 1024 * 1024)); $appConfig['files'] = [ 'max_chunk_size' => $maxChunkSize ]; diff --git a/apps/files/lib/BackgroundJob/TransferOwnership.php b/apps/files/lib/BackgroundJob/TransferOwnership.php index de8d1989733e9..562cde15f7389 100644 --- a/apps/files/lib/BackgroundJob/TransferOwnership.php +++ b/apps/files/lib/BackgroundJob/TransferOwnership.php @@ -99,7 +99,7 @@ private function failedNotication(Transfer $transfer): void { 'targetUser' => $transfer->getTargetUser(), 'nodeName' => $transfer->getNodeName(), ]) - ->setObject('transfer', (string)$transfer->getId()); + ->setObject('transfer', (string) $transfer->getId()); $this->notificationManager->notify($notification); // Send notification to source user $notification = $this->notificationManager->createNotification(); @@ -111,7 +111,7 @@ private function failedNotication(Transfer $transfer): void { 'targetUser' => $transfer->getTargetUser(), 'nodeName' => $transfer->getNodeName(), ]) - ->setObject('transfer', (string)$transfer->getId()); + ->setObject('transfer', (string) $transfer->getId()); $this->notificationManager->notify($notification); } @@ -126,7 +126,7 @@ private function successNotification(Transfer $transfer): void { 'targetUser' => $transfer->getTargetUser(), 'nodeName' => $transfer->getNodeName(), ]) - ->setObject('transfer', (string)$transfer->getId()); + ->setObject('transfer', (string) $transfer->getId()); $this->notificationManager->notify($notification); // Send notification to source user @@ -139,7 +139,7 @@ private function successNotification(Transfer $transfer): void { 'targetUser' => $transfer->getTargetUser(), 'nodeName' => $transfer->getNodeName(), ]) - ->setObject('transfer', (string)$transfer->getId()); + ->setObject('transfer', (string) $transfer->getId()); $this->notificationManager->notify($notification); } } diff --git a/apps/files/lib/Command/Copy.php b/apps/files/lib/Command/Copy.php index 9981497232f84..e51a16899076b 100644 --- a/apps/files/lib/Command/Copy.php +++ b/apps/files/lib/Command/Copy.php @@ -30,10 +30,10 @@ protected function configure(): void { $this ->setName('files:copy') ->setDescription('Copy a file or folder') - ->addArgument('source', InputArgument::REQUIRED, "Source file id or path") - ->addArgument('target', InputArgument::REQUIRED, "Target path") + ->addArgument('source', InputArgument::REQUIRED, 'Source file id or path') + ->addArgument('target', InputArgument::REQUIRED, 'Target path') ->addOption('force', 'f', InputOption::VALUE_NONE, "Don't ask for confirmation and don't output any warnings") - ->addOption('no-target-directory', 'T', InputOption::VALUE_NONE, "When target path is folder, overwrite the folder instead of copying into the folder"); + ->addOption('no-target-directory', 'T', InputOption::VALUE_NONE, 'When target path is folder, overwrite the folder instead of copying into the folder'); } public function execute(InputInterface $input, OutputInterface $output): int { @@ -98,7 +98,7 @@ public function execute(InputInterface $input, OutputInterface $output): int { /** @var QuestionHelper $helper */ $helper = $this->getHelper('question'); - $question = new ConfirmationQuestion("" . $targetInput . " already exists, overwrite? [y/N] ", false); + $question = new ConfirmationQuestion('' . $targetInput . ' already exists, overwrite? [y/N] ', false); if (!$helper->ask($input, $output, $question)) { return 1; } diff --git a/apps/files/lib/Command/Delete.php b/apps/files/lib/Command/Delete.php index 32aa52aed2f32..d984f839c91d9 100644 --- a/apps/files/lib/Command/Delete.php +++ b/apps/files/lib/Command/Delete.php @@ -30,7 +30,7 @@ protected function configure(): void { $this ->setName('files:delete') ->setDescription('Delete a file or folder') - ->addArgument('file', InputArgument::REQUIRED, "File id or path") + ->addArgument('file', InputArgument::REQUIRED, 'File id or path') ->addOption('force', 'f', InputOption::VALUE_NONE, "Don't ask for configuration and don't output any warnings"); } @@ -59,30 +59,30 @@ public function execute(InputInterface $input, OutputInterface $output): int { return self::SUCCESS; } else { $node = $storage->getShare()->getNode(); - $output->writeln(""); + $output->writeln(''); } } $filesByUsers = $this->fileUtils->getFilesByUser($node); if (count($filesByUsers) > 1) { - $output->writeln("Warning: the provided file is accessible by more than one user"); - $output->writeln(" all of the following users will lose access to the file when deleted:"); - $output->writeln(""); + $output->writeln('Warning: the provided file is accessible by more than one user'); + $output->writeln(' all of the following users will lose access to the file when deleted:'); + $output->writeln(''); foreach ($filesByUsers as $user => $filesByUser) { - $output->writeln($user . ":"); - foreach($filesByUser as $file) { - $output->writeln(" - " . $file->getPath()); + $output->writeln($user . ':'); + foreach ($filesByUser as $file) { + $output->writeln(' - ' . $file->getPath()); } } - $output->writeln(""); + $output->writeln(''); } if ($node instanceof Folder) { $maybeContents = " and all it's contents"; } else { - $maybeContents = ""; + $maybeContents = ''; } - $question = new ConfirmationQuestion("Delete " . $node->getPath() . $maybeContents . "? [y/N] ", false); + $question = new ConfirmationQuestion('Delete ' . $node->getPath() . $maybeContents . '? [y/N] ', false); $deleteConfirmed = $helper->ask($input, $output, $question); } @@ -90,7 +90,7 @@ public function execute(InputInterface $input, OutputInterface $output): int { if ($node->isDeletable()) { $node->delete(); } else { - $output->writeln("File cannot be deleted, insufficient permissions."); + $output->writeln('File cannot be deleted, insufficient permissions.'); } } diff --git a/apps/files/lib/Command/Get.php b/apps/files/lib/Command/Get.php index 0d901fe825052..60e028f615e00 100644 --- a/apps/files/lib/Command/Get.php +++ b/apps/files/lib/Command/Get.php @@ -26,8 +26,8 @@ protected function configure(): void { $this ->setName('files:get') ->setDescription('Get the contents of a file') - ->addArgument('file', InputArgument::REQUIRED, "Source file id or Nextcloud path") - ->addArgument('output', InputArgument::OPTIONAL, "Target local file to output to, defaults to STDOUT"); + ->addArgument('file', InputArgument::REQUIRED, 'Source file id or Nextcloud path') + ->addArgument('output', InputArgument::OPTIONAL, 'Target local file to output to, defaults to STDOUT'); } public function execute(InputInterface $input, OutputInterface $output): int { @@ -48,7 +48,7 @@ public function execute(InputInterface $input, OutputInterface $output): int { $isTTY = stream_isatty(STDOUT); if ($outputName === null && $isTTY && $node->getMimePart() !== 'text') { $output->writeln([ - "Warning: Binary output can mess up your terminal", + 'Warning: Binary output can mess up your terminal', " Use occ files:get $fileInput - to output it to the terminal anyway", " Or occ files:get $fileInput to save to a file instead" ]); diff --git a/apps/files/lib/Command/Move.php b/apps/files/lib/Command/Move.php index dd1cd1aae76f9..cd9e56f8e2905 100644 --- a/apps/files/lib/Command/Move.php +++ b/apps/files/lib/Command/Move.php @@ -31,8 +31,8 @@ protected function configure(): void { $this ->setName('files:move') ->setDescription('Move a file or folder') - ->addArgument('source', InputArgument::REQUIRED, "Source file id or path") - ->addArgument('target', InputArgument::REQUIRED, "Target path") + ->addArgument('source', InputArgument::REQUIRED, 'Source file id or path') + ->addArgument('target', InputArgument::REQUIRED, 'Target path') ->addOption('force', 'f', InputOption::VALUE_NONE, "Don't ask for configuration and don't output any warnings"); } @@ -88,7 +88,7 @@ public function execute(InputInterface $input, OutputInterface $output): int { /** @var QuestionHelper $helper */ $helper = $this->getHelper('question'); - $question = new ConfirmationQuestion("" . $targetInput . " already exists, overwrite? [y/N] ", false); + $question = new ConfirmationQuestion('' . $targetInput . ' already exists, overwrite? [y/N] ', false); if (!$helper->ask($input, $output, $question)) { return 1; } diff --git a/apps/files/lib/Command/Object/Delete.php b/apps/files/lib/Command/Object/Delete.php index f9fc3a58229b6..07613ecc61674 100644 --- a/apps/files/lib/Command/Object/Delete.php +++ b/apps/files/lib/Command/Object/Delete.php @@ -27,13 +27,13 @@ protected function configure(): void { $this ->setName('files:object:delete') ->setDescription('Delete an object from the object store') - ->addArgument('object', InputArgument::REQUIRED, "Object to delete") + ->addArgument('object', InputArgument::REQUIRED, 'Object to delete') ->addOption('bucket', 'b', InputOption::VALUE_REQUIRED, "Bucket to delete the object from, only required in cases where it can't be determined from the config"); } public function execute(InputInterface $input, OutputInterface $output): int { $object = $input->getArgument('object'); - $objectStore = $this->objectUtils->getObjectStore($input->getOption("bucket"), $output); + $objectStore = $this->objectUtils->getObjectStore($input->getOption('bucket'), $output); if (!$objectStore) { return -1; } @@ -41,7 +41,7 @@ public function execute(InputInterface $input, OutputInterface $output): int { if ($fileId = $this->objectUtils->objectExistsInDb($object)) { $output->writeln("Warning, object $object belongs to an existing file, deleting the object will lead to unexpected behavior if not replaced"); $output->writeln(" Note: use occ files:delete $fileId to delete the file cleanly or occ info:file $fileId for more information about the file"); - $output->writeln(""); + $output->writeln(''); } if (!$objectStore->objectExists($object)) { diff --git a/apps/files/lib/Command/Object/Get.php b/apps/files/lib/Command/Object/Get.php index 054278211f667..c32de020c5ae0 100644 --- a/apps/files/lib/Command/Object/Get.php +++ b/apps/files/lib/Command/Object/Get.php @@ -25,15 +25,15 @@ protected function configure(): void { $this ->setName('files:object:get') ->setDescription('Get the contents of an object') - ->addArgument('object', InputArgument::REQUIRED, "Object to get") - ->addArgument('output', InputArgument::REQUIRED, "Target local file to output to, use - for STDOUT") + ->addArgument('object', InputArgument::REQUIRED, 'Object to get') + ->addArgument('output', InputArgument::REQUIRED, 'Target local file to output to, use - for STDOUT') ->addOption('bucket', 'b', InputOption::VALUE_REQUIRED, "Bucket to get the object from, only required in cases where it can't be determined from the config"); } public function execute(InputInterface $input, OutputInterface $output): int { $object = $input->getArgument('object'); $outputName = $input->getArgument('output'); - $objectStore = $this->objectUtils->getObjectStore($input->getOption("bucket"), $output); + $objectStore = $this->objectUtils->getObjectStore($input->getOption('bucket'), $output); if (!$objectStore) { return self::FAILURE; } diff --git a/apps/files/lib/Command/Object/ObjectUtil.php b/apps/files/lib/Command/Object/ObjectUtil.php index 7021c815490d3..b85591e8a32be 100644 --- a/apps/files/lib/Command/Object/ObjectUtil.php +++ b/apps/files/lib/Command/Object/ObjectUtil.php @@ -41,19 +41,19 @@ private function getObjectStoreConfig(): ?array { public function getObjectStore(?string $bucket, OutputInterface $output): ?IObjectStore { $config = $this->getObjectStoreConfig(); if (!$config) { - $output->writeln("Instance is not using primary object store"); + $output->writeln('Instance is not using primary object store'); return null; } if ($config['multibucket'] && !$bucket) { - $output->writeln("--bucket option required because multi bucket is enabled."); + $output->writeln('--bucket option required because multi bucket is enabled.'); return null; } if (!isset($config['arguments'])) { - throw new \Exception("no arguments configured for object store configuration"); + throw new \Exception('no arguments configured for object store configuration'); } if (!isset($config['class'])) { - throw new \Exception("no class configured for object store configuration"); + throw new \Exception('no class configured for object store configuration'); } if ($bucket) { @@ -65,7 +65,7 @@ public function getObjectStore(?string $bucket, OutputInterface $output): ?IObje $store = new $config['class']($config['arguments']); if (!$store instanceof IObjectStore) { - throw new \Exception("configured object store class is not an object store implementation"); + throw new \Exception('configured object store class is not an object store implementation'); } return $store; } @@ -78,7 +78,7 @@ public function objectExistsInDb(string $object): int|false { return false; } - $fileId = (int)substr($object, strlen('urn:oid:')); + $fileId = (int) substr($object, strlen('urn:oid:')); $query = $this->connection->getQueryBuilder(); $query->select('fileid') ->from('filecache') diff --git a/apps/files/lib/Command/Object/Put.php b/apps/files/lib/Command/Object/Put.php index 34e4ceb854bc3..fc49e28c70ad0 100644 --- a/apps/files/lib/Command/Object/Put.php +++ b/apps/files/lib/Command/Object/Put.php @@ -29,16 +29,16 @@ protected function configure(): void { $this ->setName('files:object:put') ->setDescription('Write a file to the object store') - ->addArgument('input', InputArgument::REQUIRED, "Source local path, use - to read from STDIN") - ->addArgument('object', InputArgument::REQUIRED, "Object to write") + ->addArgument('input', InputArgument::REQUIRED, 'Source local path, use - to read from STDIN') + ->addArgument('object', InputArgument::REQUIRED, 'Object to write') ->addOption('bucket', 'b', InputOption::VALUE_REQUIRED, "Bucket where to store the object, only required in cases where it can't be determined from the config"); ; } public function execute(InputInterface $input, OutputInterface $output): int { $object = $input->getArgument('object'); - $inputName = (string)$input->getArgument('input'); - $objectStore = $this->objectUtils->getObjectStore($input->getOption("bucket"), $output); + $inputName = (string) $input->getArgument('input'); + $objectStore = $this->objectUtils->getObjectStore($input->getOption('bucket'), $output); if (!$objectStore) { return -1; } @@ -46,11 +46,11 @@ public function execute(InputInterface $input, OutputInterface $output): int { if ($fileId = $this->objectUtils->objectExistsInDb($object)) { $output->writeln("Warning, object $object belongs to an existing file, overwriting the object contents can lead to unexpected behavior."); $output->writeln("You can use occ files:put $inputName $fileId to write to the file safely."); - $output->writeln(""); + $output->writeln(''); /** @var QuestionHelper $helper */ $helper = $this->getHelper('question'); - $question = new ConfirmationQuestion("Write to the object anyway? [y/N] ", false); + $question = new ConfirmationQuestion('Write to the object anyway? [y/N] ', false); if (!$helper->ask($input, $output, $question)) { return -1; } diff --git a/apps/files/lib/Command/Put.php b/apps/files/lib/Command/Put.php index f72fa90234683..fd9d75db78c11 100644 --- a/apps/files/lib/Command/Put.php +++ b/apps/files/lib/Command/Put.php @@ -29,8 +29,8 @@ protected function configure(): void { $this ->setName('files:put') ->setDescription('Write contents of a file') - ->addArgument('input', InputArgument::REQUIRED, "Source local path, use - to read from STDIN") - ->addArgument('file', InputArgument::REQUIRED, "Target Nextcloud file path to write to or fileid of existing file"); + ->addArgument('input', InputArgument::REQUIRED, 'Source local path, use - to read from STDIN') + ->addArgument('file', InputArgument::REQUIRED, 'Target Nextcloud file path to write to or fileid of existing file'); } public function execute(InputInterface $input, OutputInterface $output): int { diff --git a/apps/files/lib/Command/RepairTree.php b/apps/files/lib/Command/RepairTree.php index 99e92741a2e9c..ca4aa10264749 100644 --- a/apps/files/lib/Command/RepairTree.php +++ b/apps/files/lib/Command/RepairTree.php @@ -33,7 +33,7 @@ public function execute(InputInterface $input, OutputInterface $output): int { $rows = $this->findBrokenTreeBits(); $fix = !$input->getOption('dry-run'); - $output->writeln("Found " . count($rows) . " file entries with an invalid path"); + $output->writeln('Found ' . count($rows) . ' file entries with an invalid path'); if ($fix) { $this->connection->beginTransaction(); @@ -50,10 +50,10 @@ public function execute(InputInterface $input, OutputInterface $output): int { $output->writeln("Path of file {$row['fileid']} is {$row['path']} but should be {$row['parent_path']}/{$row['name']} based on its parent", OutputInterface::VERBOSITY_VERBOSE); if ($fix) { - $fileId = $this->getFileId((int)$row['parent_storage'], $row['parent_path'] . '/' . $row['name']); + $fileId = $this->getFileId((int) $row['parent_storage'], $row['parent_path'] . '/' . $row['name']); if ($fileId > 0) { $output->writeln("Cache entry has already be recreated with id $fileId, deleting instead"); - $this->deleteById((int)$row['fileid']); + $this->deleteById((int) $row['fileid']); } else { $query->setParameters([ 'fileid' => $row['fileid'], diff --git a/apps/files/lib/Command/Scan.php b/apps/files/lib/Command/Scan.php index 68c80f6559ab4..6b192797ae642 100644 --- a/apps/files/lib/Command/Scan.php +++ b/apps/files/lib/Command/Scan.php @@ -302,9 +302,9 @@ protected function presentStats(OutputInterface $output): void { * Formats microtime into a human-readable format */ protected function formatExecTime(): string { - $secs = (int)round($this->execTime); + $secs = (int) round($this->execTime); # convert seconds into HH:MM:SS form - return sprintf('%02d:%02d:%02d', (int)($secs / 3600), ((int)($secs / 60) % 60), $secs % 60); + return sprintf('%02d:%02d:%02d', (int) ($secs / 3600), ((int) ($secs / 60) % 60), $secs % 60); } protected function reconnectToDatabase(OutputInterface $output): Connection { diff --git a/apps/files/lib/Command/ScanAppData.php b/apps/files/lib/Command/ScanAppData.php index 61f4b6f3ba242..635651c81604d 100644 --- a/apps/files/lib/Command/ScanAppData.php +++ b/apps/files/lib/Command/ScanAppData.php @@ -1,4 +1,5 @@ execTime); # convert seconds into HH:MM:SS form - return sprintf('%02d:%02d:%02d', (int)($secs / 3600), ((int)($secs / 60) % 60), (int)$secs % 60); + return sprintf('%02d:%02d:%02d', (int) ($secs / 3600), ((int) ($secs / 60) % 60), (int) $secs % 60); } protected function reconnectToDatabase(OutputInterface $output): Connection { - /** @var Connection $connection*/ + /** @var Connection $connection */ $connection = \OC::$server->get(Connection::class); try { $connection->close(); diff --git a/apps/files/lib/Command/TransferOwnership.php b/apps/files/lib/Command/TransferOwnership.php index db4c19dc54e4d..edc73e62c381e 100644 --- a/apps/files/lib/Command/TransferOwnership.php +++ b/apps/files/lib/Command/TransferOwnership.php @@ -78,12 +78,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int $destinationUserObject = $this->userManager->get($input->getArgument('destination-user')); if (!$sourceUserObject instanceof IUser) { - $output->writeln("Unknown source user " . $input->getArgument('source-user') . ""); + $output->writeln('Unknown source user ' . $input->getArgument('source-user') . ''); return self::FAILURE; } if (!$destinationUserObject instanceof IUser) { - $output->writeln("Unknown destination user " . $input->getArgument('destination-user') . ""); + $output->writeln('Unknown destination user ' . $input->getArgument('destination-user') . ''); return self::FAILURE; } @@ -105,7 +105,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } break; default: - $output->writeln("Option --transfer-incoming-shares: wrong usage. Transfer aborted."); + $output->writeln('Option --transfer-incoming-shares: wrong usage. Transfer aborted.'); return self::FAILURE; } @@ -119,7 +119,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $includeIncoming ); } catch (TransferOwnershipException $e) { - $output->writeln("" . $e->getMessage() . ""); + $output->writeln('' . $e->getMessage() . ''); return $e->getCode() !== 0 ? $e->getCode() : self::FAILURE; } diff --git a/apps/files/lib/Controller/ApiController.php b/apps/files/lib/Controller/ApiController.php index eb30601a9377a..27d41f8a016ed 100644 --- a/apps/files/lib/Controller/ApiController.php +++ b/apps/files/lib/Controller/ApiController.php @@ -339,7 +339,7 @@ public function getStorageStats($dir = '/'): JSONResponse { #[NoAdminRequired] public function setViewConfig(string $view, string $key, $value): JSONResponse { try { - $this->viewConfig->setConfig($view, $key, (string)$value); + $this->viewConfig->setConfig($view, $key, (string) $value); } catch (\InvalidArgumentException $e) { return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); } @@ -368,7 +368,7 @@ public function getViewConfigs(): JSONResponse { #[NoAdminRequired] public function setConfig(string $key, $value): JSONResponse { try { - $this->userConfig->setConfig($key, (string)$value); + $this->userConfig->setConfig($key, (string) $value); } catch (\InvalidArgumentException $e) { return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); } diff --git a/apps/files/lib/Controller/DirectEditingController.php b/apps/files/lib/Controller/DirectEditingController.php index 693587f9c8a56..422bacf944870 100644 --- a/apps/files/lib/Controller/DirectEditingController.php +++ b/apps/files/lib/Controller/DirectEditingController.php @@ -1,4 +1,5 @@ $recipient, 'nodeName' => $node->getName(), ]) - ->setObject('transfer', (string)$transferOwnership->getId()); + ->setObject('transfer', (string) $transferOwnership->getId()); $this->notificationManager->notify($notification); @@ -146,7 +146,7 @@ public function accept(int $id): DataResponse { $notification = $this->notificationManager->createNotification(); $notification->setApp('files') - ->setObject('transfer', (string)$id); + ->setObject('transfer', (string) $id); $this->notificationManager->markProcessed($notification); return new DataResponse([], Http::STATUS_OK); @@ -177,7 +177,7 @@ public function reject(int $id): DataResponse { $notification = $this->notificationManager->createNotification(); $notification->setApp('files') - ->setObject('transfer', (string)$id); + ->setObject('transfer', (string) $id); $this->notificationManager->markProcessed($notification); $this->mapper->delete($transferOwnership); diff --git a/apps/files/lib/Controller/ViewController.php b/apps/files/lib/Controller/ViewController.php index 66c0c1cf8f0e0..5c7b021ffb3cd 100644 --- a/apps/files/lib/Controller/ViewController.php +++ b/apps/files/lib/Controller/ViewController.php @@ -88,7 +88,7 @@ public function showFile(?string $fileid = null, ?string $openfile = null): Resp // This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server. try { - return $this->redirectToFile((int)$fileid, $openfile); + return $this->redirectToFile((int) $fileid, $openfile); } catch (NotFoundException $e) { // Keep the fileid even if not found, it will be used // to detect the file could not be found and warn the user @@ -132,7 +132,7 @@ public function indexViewFileid($dir = '', $view = '', $fileid = null) { public function index($dir = '', $view = '', $fileid = null) { if ($fileid !== null && $view !== 'trashbin') { try { - return $this->redirectToFileIfInTrashbin((int)$fileid); + return $this->redirectToFileIfInTrashbin((int) $fileid); } catch (NotFoundException $e) { } } @@ -149,14 +149,14 @@ public function index($dir = '', $view = '', $fileid = null) { // in the correct folder if ($fileid && $dir !== '') { $baseFolder = $this->rootFolder->getUserFolder($userId); - $nodes = $baseFolder->getById((int)$fileid); + $nodes = $baseFolder->getById((int) $fileid); if (!empty($nodes)) { $nodePath = $baseFolder->getRelativePath($nodes[0]->getPath()); $relativePath = $nodePath ? dirname($nodePath) : ''; // If the requested path does not contain the file id // or if the requested path is not the file id itself if (count($nodes) === 1 && $relativePath !== $dir && $nodePath !== $dir) { - return $this->redirectToFile((int)$fileid); + return $this->redirectToFile((int) $fileid); } } } diff --git a/apps/files/lib/Listener/SyncLivePhotosListener.php b/apps/files/lib/Listener/SyncLivePhotosListener.php index 6df9b8d6e95a4..17242d448a9b7 100644 --- a/apps/files/lib/Listener/SyncLivePhotosListener.php +++ b/apps/files/lib/Listener/SyncLivePhotosListener.php @@ -94,7 +94,7 @@ private function runMoveOrCopyChecks(Node $sourceFile, Node $targetFile, Node $p $targetName = $targetFile->getName(); $peerTargetName = substr($targetName, 0, -strlen($sourceExtension)) . $peerFileExtension; - if (!str_ends_with($targetName, "." . $sourceExtension)) { + if (!str_ends_with($targetName, '.' . $sourceExtension)) { throw new AbortedEventException('Cannot change the extension of a Live Photo'); } @@ -165,12 +165,12 @@ private function handleCopy(File $sourceFile, File $targetFile, File $peerFile): /** @var FilesMetadata $targetMetadata */ $targetMetadata = $this->filesMetadataManager->getMetadata($targetFile->getId(), true); $targetMetadata->setStorageId($targetFile->getStorage()->getCache()->getNumericStorageId()); - $targetMetadata->setString('files-live-photo', (string)$targetPeerFile->getId()); + $targetMetadata->setString('files-live-photo', (string) $targetPeerFile->getId()); $this->filesMetadataManager->saveMetadata($targetMetadata); /** @var FilesMetadata $peerMetadata */ $peerMetadata = $this->filesMetadataManager->getMetadata($targetPeerFile->getId(), true); $peerMetadata->setStorageId($targetPeerFile->getStorage()->getCache()->getNumericStorageId()); - $peerMetadata->setString('files-live-photo', (string)$targetFile->getId()); + $peerMetadata->setString('files-live-photo', (string) $targetFile->getId()); $this->filesMetadataManager->saveMetadata($peerMetadata); } @@ -188,7 +188,7 @@ private function handleDeletion(BeforeNodeDeletedEvent $event, Node $peerFile): unset($this->pendingDeletion[$peerFile->getId()]); return; } else { - throw new AbortedEventException("Cannot delete the video part of a live photo"); + throw new AbortedEventException('Cannot delete the video part of a live photo'); } } else { $this->pendingDeletion[$deletedFile->getId()] = true; diff --git a/apps/files/lib/Notification/Notifier.php b/apps/files/lib/Notification/Notifier.php index 89ddbb9b6ecdb..12ae2593e8775 100644 --- a/apps/files/lib/Notification/Notifier.php +++ b/apps/files/lib/Notification/Notifier.php @@ -275,7 +275,7 @@ public function dismissNotification(INotification $notification): void { // TODO: This should all be moved to a service that also the transferownershipController uses. try { - $transferOwnership = $this->mapper->getById((int)$notification->getObjectId()); + $transferOwnership = $this->mapper->getById((int) $notification->getObjectId()); } catch (DoesNotExistException $e) { return; } @@ -295,7 +295,7 @@ public function dismissNotification(INotification $notification): void { 'targetUser' => $transferOwnership->getTargetUser(), 'nodeName' => $transferOwnership->getNodeName() ]) - ->setObject('transfer', (string)$transferOwnership->getId()); + ->setObject('transfer', (string) $transferOwnership->getId()); $this->notificationManager->notify($notification); $this->mapper->delete($transferOwnership); diff --git a/apps/files/lib/Search/FilesSearchProvider.php b/apps/files/lib/Search/FilesSearchProvider.php index 950c8b14ab66f..bcb8c1482aa6e 100644 --- a/apps/files/lib/Search/FilesSearchProvider.php +++ b/apps/files/lib/Search/FilesSearchProvider.php @@ -144,7 +144,7 @@ public function search(IUser $user, ISearchQuery $query): SearchResult { $this->urlGenerator->getAbsoluteURL($link), $icon, ); - $searchResultEntry->addAttribute('fileId', (string)$result->getId()); + $searchResultEntry->addAttribute('fileId', (string) $result->getId()); $searchResultEntry->addAttribute('path', $path); return $searchResultEntry; }, $userFolder->search($fileQuery)), diff --git a/apps/files/lib/Service/DirectEditingService.php b/apps/files/lib/Service/DirectEditingService.php index c21742d25ea21..8816c11bb013b 100644 --- a/apps/files/lib/Service/DirectEditingService.php +++ b/apps/files/lib/Service/DirectEditingService.php @@ -1,4 +1,5 @@ getString('files-live-photo'); + return (int) $metadata->getString('files-live-photo'); } } diff --git a/apps/files/lib/Service/OwnershipTransferService.php b/apps/files/lib/Service/OwnershipTransferService.php index 2f3cb6788c4c8..055b3233bc0ad 100644 --- a/apps/files/lib/Service/OwnershipTransferService.php +++ b/apps/files/lib/Service/OwnershipTransferService.php @@ -80,7 +80,7 @@ public function transfer( // If encryption is on we have to ensure the user has logged in before and that all encryption modules are ready if (($this->encryptionManager->isEnabled() && $destinationUser->getLastLogin() === 0) || !$this->encryptionManager->isReadyForUser($destinationUid)) { - throw new TransferOwnershipException("The target user is not ready to accept files. The user has at least to have logged in once.", 2); + throw new TransferOwnershipException('The target user is not ready to accept files. The user has at least to have logged in once.', 2); } // setup filesystem @@ -121,7 +121,7 @@ public function transfer( } if ($move && !$firstLogin && count($view->getDirectoryContent($finalTarget)) > 0) { - throw new TransferOwnershipException("Destination path does not exists or is not empty", 1); + throw new TransferOwnershipException('Destination path does not exists or is not empty', 1); } @@ -277,10 +277,10 @@ function (FileInfo $fileInfo) use ($progress, $masterKeyEnabled, &$encryptedFile // no file is allowed to be encrypted if (!empty($encryptedFiles)) { - $output->writeln("Some files are encrypted - please decrypt them first."); + $output->writeln('Some files are encrypted - please decrypt them first.'); foreach ($encryptedFiles as $encryptedFile) { /** @var FileInfo $encryptedFile */ - $output->writeln(" " . $encryptedFile->getPath()); + $output->writeln(' ' . $encryptedFile->getPath()); } throw new TransferOwnershipException('Some files are encrypted - please decrypt them first.', 1); } @@ -414,7 +414,7 @@ protected function transferFiles(string $sourceUid, $finalTarget = $finalTarget . '/' . basename($sourcePath); } if ($view->rename($sourcePath, $finalTarget, ['checkSubMounts' => false]) === false) { - throw new TransferOwnershipException("Could not transfer files.", 1); + throw new TransferOwnershipException('Could not transfer files.', 1); } if (!is_dir("$sourceUid/files")) { // because the files folder is moved away we need to recreate it @@ -433,7 +433,7 @@ private function restoreShares( array $shares, OutputInterface $output, ):void { - $output->writeln("Restoring shares ..."); + $output->writeln('Restoring shares ...'); $progress = new ProgressBar($output, count($shares)); foreach ($shares as ['share' => $share, 'suffix' => $suffix]) { @@ -502,7 +502,7 @@ private function transferIncomingShares(string $sourceUid, string $path, string $finalTarget, bool $move): void { - $output->writeln("Restoring incoming shares ..."); + $output->writeln('Restoring incoming shares ...'); $progress = new ProgressBar($output, count($sourceShares)); $prefix = "$destinationUid/files"; $finalShareTarget = ''; diff --git a/apps/files/lib/Service/TagService.php b/apps/files/lib/Service/TagService.php index 4737938ab5214..4bb43145e4a12 100644 --- a/apps/files/lib/Service/TagService.php +++ b/apps/files/lib/Service/TagService.php @@ -53,7 +53,7 @@ public function __construct( * replace the actual tag selection. * * @param string $path path - * @param array $tags array of tags + * @param array $tags array of tags * @return array list of tags * @throws \OCP\Files\NotFoundException if the file does not exist */ diff --git a/apps/files/lib/Service/UserConfig.php b/apps/files/lib/Service/UserConfig.php index c233996579379..f2e5982bff7e6 100644 --- a/apps/files/lib/Service/UserConfig.php +++ b/apps/files/lib/Service/UserConfig.php @@ -1,4 +1,5 @@ writeln((string)$value); + $output->writeln((string) $value); } /** diff --git a/apps/files_external/lib/Command/Create.php b/apps/files_external/lib/Command/Create.php index 4396d2e2b13df..6c29485e0eba9 100644 --- a/apps/files_external/lib/Command/Create.php +++ b/apps/files_external/lib/Command/Create.php @@ -1,4 +1,5 @@ getOption('user'); + $user = (string) $input->getOption('user'); $mountPoint = $input->getArgument('mount_point'); $storageIdentifier = $input->getArgument('storage_backend'); $authIdentifier = $input->getArgument('authentication_backend'); @@ -140,7 +141,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($input->getOption('output') === self::OUTPUT_FORMAT_PLAIN) { $output->writeln('Storage created with id ' . $mount->getId() . ''); } else { - $output->writeln((string)$mount->getId()); + $output->writeln((string) $mount->getId()); } } return self::SUCCESS; diff --git a/apps/files_external/lib/Command/Delete.php b/apps/files_external/lib/Command/Delete.php index 1c2bfe39fb00b..4a2b3e08c40bd 100644 --- a/apps/files_external/lib/Command/Delete.php +++ b/apps/files_external/lib/Command/Delete.php @@ -1,4 +1,5 @@ getApplicableUsers() === $mount->getApplicableUsers() && $existingMount->getBackendOptions() === $mount->getBackendOptions() ) { - $output->writeln("Duplicate mount (" . $mount->getMountPoint() . ")"); + $output->writeln('Duplicate mount (' . $mount->getMountPoint() . ')'); return self::FAILURE; } } diff --git a/apps/files_external/lib/Command/ListCommand.php b/apps/files_external/lib/Command/ListCommand.php index fabcce677750d..b077db552904e 100644 --- a/apps/files_external/lib/Command/ListCommand.php +++ b/apps/files_external/lib/Command/ListCommand.php @@ -1,4 +1,5 @@ globalService->getStorageForAllUsers(); $userId = self::ALL; } else { - $userId = (string)$input->getArgument('user_id'); + $userId = (string) $input->getArgument('user_id'); $storageService = $this->getStorageService($userId); $mounts = $storageService->getAllStorages(); } @@ -85,11 +86,11 @@ public function listMounts($userId, array $mounts, InputInterface $input, Output $output->writeln('[]'); } else { if ($userId === self::ALL) { - $output->writeln("No mounts configured"); + $output->writeln('No mounts configured'); } elseif ($userId) { $output->writeln("No mounts configured by $userId"); } else { - $output->writeln("No admin mounts configured"); + $output->writeln('No admin mounts configured'); } } return; diff --git a/apps/files_external/lib/Command/Notify.php b/apps/files_external/lib/Command/Notify.php index a4e7edf02075b..6dfbfdc976d01 100644 --- a/apps/files_external/lib/Command/Notify.php +++ b/apps/files_external/lib/Command/Notify.php @@ -136,7 +136,7 @@ private function markParentAsOutdated($mountId, $path, OutputInterface $output, $storageIds = array_values(array_unique($storageIds)); if ($dryRun) { - $output->writeln(" dry-run: skipping database write"); + $output->writeln(' dry-run: skipping database write'); } else { $result = $this->updateParent($storageIds, $parent); if ($result === 0) { @@ -168,7 +168,7 @@ private function logUpdate(IChange $change, OutputInterface $output): void { } private function getStorageIds(int $mountId, string $path): array { - $pathHash = md5(trim((string)\OC_Util::normalizeUnicode($path), '/')); + $pathHash = md5(trim((string) \OC_Util::normalizeUnicode($path), '/')); $qb = $this->connection->getQueryBuilder(); return $qb ->select('storage_id', 'user_id') @@ -181,7 +181,7 @@ private function getStorageIds(int $mountId, string $path): array { } private function updateParent(array $storageIds, string $parent): int { - $pathHash = md5(trim((string)\OC_Util::normalizeUnicode($parent), '/')); + $pathHash = md5(trim((string) \OC_Util::normalizeUnicode($parent), '/')); $qb = $this->connection->getQueryBuilder(); return $qb ->update('filecache') @@ -215,7 +215,7 @@ private function reconnectToDatabase(IDBConnection $connection, OutputInterface private function selfTest(IStorage $storage, INotifyHandler $notifyHandler, OutputInterface $output): void { usleep(100 * 1000); //give time for the notify to start if (!$storage->file_put_contents('/.nc_test_file.txt', 'test content')) { - $output->writeln("Failed to create test file for self-test"); + $output->writeln('Failed to create test file for self-test'); return; } $storage->mkdir('/.nc_test_folder'); diff --git a/apps/files_external/lib/Command/Option.php b/apps/files_external/lib/Command/Option.php index 6051c9c5fbdc5..5567dd3769443 100644 --- a/apps/files_external/lib/Command/Option.php +++ b/apps/files_external/lib/Command/Option.php @@ -1,4 +1,5 @@ writeln((string)$value); + $output->writeln((string) $value); } /** diff --git a/apps/files_external/lib/Command/StorageAuthBase.php b/apps/files_external/lib/Command/StorageAuthBase.php index 6f830a08a60f6..3decc6a50e0de 100644 --- a/apps/files_external/lib/Command/StorageAuthBase.php +++ b/apps/files_external/lib/Command/StorageAuthBase.php @@ -29,7 +29,7 @@ public function __construct( private function getUserOption(InputInterface $input): ?string { if ($input->getOption('user')) { - return (string)$input->getOption('user'); + return (string) $input->getOption('user'); } return $_ENV['NOTIFY_USER'] ?? $_SERVER['NOTIFY_USER'] ?? null; @@ -37,7 +37,7 @@ private function getUserOption(InputInterface $input): ?string { private function getPasswordOption(InputInterface $input): ?string { if ($input->getOption('password')) { - return (string)$input->getOption('password'); + return (string) $input->getOption('password'); } return $_ENV['NOTIFY_PASSWORD'] ?? $_SERVER['NOTIFY_PASSWORD'] ?? null; @@ -52,7 +52,7 @@ private function getPasswordOption(InputInterface $input): ?string { protected function createStorage(InputInterface $input, OutputInterface $output): array { try { /** @var StorageConfig|null $mount */ - $mount = $this->globalService->getStorage((int)$input->getArgument('mount_id')); + $mount = $this->globalService->getStorage((int) $input->getArgument('mount_id')); } catch (NotFoundException $e) { $output->writeln('Mount not found'); return [null, null]; diff --git a/apps/files_external/lib/Command/Verify.php b/apps/files_external/lib/Command/Verify.php index 1455e427b77e3..37ea93d7df543 100644 --- a/apps/files_external/lib/Command/Verify.php +++ b/apps/files_external/lib/Command/Verify.php @@ -1,4 +1,5 @@ sanitizedPlaceholder = trim(strtolower($this->placeholder)); - if (!(bool)\preg_match('/^[a-z0-9]*$/', $this->sanitizedPlaceholder)) { + if (!(bool) \preg_match('/^[a-z0-9]*$/', $this->sanitizedPlaceholder)) { throw new \RuntimeException(sprintf( 'Invalid placeholder %s, only [a-z0-9] are allowed', $this->sanitizedPlaceholder )); diff --git a/apps/files_external/lib/Config/UserContext.php b/apps/files_external/lib/Config/UserContext.php index 5d9d2910ea25d..ac5870c94879e 100644 --- a/apps/files_external/lib/Config/UserContext.php +++ b/apps/files_external/lib/Config/UserContext.php @@ -1,4 +1,5 @@ getCode() ? $e->getCode() : StorageNotAvailableException::STATUS_INDETERMINATE; $storage->setStatus( - (int)$status, + (int) $status, $this->l10n->t('Insufficient data: %s', [$e->getMessage()]) ); } catch (StorageNotAvailableException $e) { $storage->setStatus( - (int)$e->getCode(), + (int) $e->getCode(), $this->l10n->t('%s', [$e->getMessage()]) ); } catch (\Exception $e) { diff --git a/apps/files_external/lib/Controller/UserGlobalStoragesController.php b/apps/files_external/lib/Controller/UserGlobalStoragesController.php index 3896eb4b2dc4d..ec6a25ecc44ae 100644 --- a/apps/files_external/lib/Controller/UserGlobalStoragesController.php +++ b/apps/files_external/lib/Controller/UserGlobalStoragesController.php @@ -1,4 +1,5 @@ getCredentials($user); - $loginKey = $storage->getBackendOption("login_ldap_attr"); + $loginKey = $storage->getBackendOption('login_ldap_attr'); if ($loginKey) { $backend = $user->getBackend(); if ($backend instanceof IUserBackend && $backend->getBackendName() === 'LDAP') { diff --git a/apps/files_external/lib/Lib/Auth/Password/Password.php b/apps/files_external/lib/Lib/Auth/Password/Password.php index e339323384075..d4291148e3e39 100644 --- a/apps/files_external/lib/Lib/Auth/Password/Password.php +++ b/apps/files_external/lib/Lib/Auth/Password/Password.php @@ -1,4 +1,5 @@ flags & $flag); + return (bool) ($this->flags & $flag); } /** diff --git a/apps/files_external/lib/Lib/DependencyTrait.php b/apps/files_external/lib/Lib/DependencyTrait.php index 1d11253212857..644132b82bcf7 100644 --- a/apps/files_external/lib/Lib/DependencyTrait.php +++ b/apps/files_external/lib/Lib/DependencyTrait.php @@ -1,4 +1,5 @@ parameters for mechanism */ private array $parameters = []; diff --git a/apps/files_external/lib/Lib/IFrontendDefinition.php b/apps/files_external/lib/Lib/IFrontendDefinition.php index 0184d5f536cf2..c8b06a1c30b11 100644 --- a/apps/files_external/lib/Lib/IFrontendDefinition.php +++ b/apps/files_external/lib/Lib/IFrontendDefinition.php @@ -1,4 +1,5 @@ objectCache[$key]) && !isset($this->objectCache[$key]["Key"])) { + if (is_array($this->objectCache[$key]) && !isset($this->objectCache[$key]['Key'])) { /** @psalm-suppress InvalidArgument Psalm doesn't understand nested arrays well */ - $this->objectCache[$key]["Key"] = $key; + $this->objectCache[$key]['Key'] = $key; } return $this->objectCache[$key]; } @@ -340,12 +341,12 @@ public function stat($path) { */ private function getContentLength($path) { if (isset($this->filesCache[$path])) { - return (int)$this->filesCache[$path]['ContentLength']; + return (int) $this->filesCache[$path]['ContentLength']; } $result = $this->headObject($path); if (isset($result['ContentLength'])) { - return (int)$result['ContentLength']; + return (int) $result['ContentLength']; } return 0; @@ -690,7 +691,7 @@ private function objectToMetaData(array $object): array { 'storage_mtime' => strtotime($object['LastModified']), 'etag' => trim($object['ETag'], '"'), 'permissions' => Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE, - 'size' => (int)($object['Size'] ?? $object['ContentLength']), + 'size' => (int) ($object['Size'] ?? $object['ContentLength']), ]; } @@ -766,7 +767,7 @@ public function writeStream(string $path, $stream, ?int $size = null): int { } if (!is_resource($stream)) { - throw new \InvalidArgumentException("Invalid stream provided"); + throw new \InvalidArgumentException('Invalid stream provided'); } $path = $this->normalizePath($path); diff --git a/apps/files_external/lib/Lib/Storage/FTP.php b/apps/files_external/lib/Lib/Storage/FTP.php index 0af6ca141bb65..9f75269aa70b2 100644 --- a/apps/files_external/lib/Lib/Storage/FTP.php +++ b/apps/files_external/lib/Lib/Storage/FTP.php @@ -1,4 +1,5 @@ secure = ($params['secure'] === 'true'); } else { - $this->secure = (bool)$params['secure']; + $this->secure = (bool) $params['secure']; } } else { $this->secure = false; @@ -66,11 +67,11 @@ protected function getConnection(): FtpConnection { $this->password ); } catch (\Exception $e) { - throw new StorageNotAvailableException("Failed to create ftp connection", 0, $e); + throw new StorageNotAvailableException('Failed to create ftp connection', 0, $e); } if ($this->utf8Mode) { if (!$this->connection->setUtf8Mode()) { - throw new StorageNotAvailableException("Could not set UTF-8 mode"); + throw new StorageNotAvailableException('Could not set UTF-8 mode'); } } } @@ -219,7 +220,7 @@ public function mkdir($path) { } public function is_dir($path) { - if ($path === "") { + if ($path === '') { return true; } if ($this->getConnection()->chdir($this->buildPath($path)) === true) { diff --git a/apps/files_external/lib/Lib/Storage/FtpConnection.php b/apps/files_external/lib/Lib/Storage/FtpConnection.php index 8855dffbc0fde..ee960313371ec 100644 --- a/apps/files_external/lib/Lib/Storage/FtpConnection.php +++ b/apps/files_external/lib/Lib/Storage/FtpConnection.php @@ -23,11 +23,11 @@ public function __construct(bool $secure, string $hostname, int $port, string $u } if ($connection === false) { - throw new \Exception("Failed to connect to ftp"); + throw new \Exception('Failed to connect to ftp'); } if (ftp_login($connection, $username, $password) === false) { - throw new \Exception("Failed to connect to login to ftp"); + throw new \Exception('Failed to connect to login to ftp'); } ftp_pasv($connection, true); @@ -39,7 +39,7 @@ public function __destruct() { } public function setUtf8Mode(): bool { - $response = ftp_raw($this->connection, "OPTS UTF8 ON"); + $response = ftp_raw($this->connection, 'OPTS UTF8 ON'); return substr($response[0], 0, 3) === '200'; } @@ -75,8 +75,8 @@ public function mdtm(string $path): int { $result = @ftp_mdtm($this->connection, $path); // filezilla doesn't like empty path with mdtm - if ($result === -1 && $path === "") { - $result = @ftp_mdtm($this->connection, "/"); + if ($result === -1 && $path === '') { + $result = @ftp_mdtm($this->connection, '/'); } return $result; } @@ -150,13 +150,13 @@ private function parseUnixItem(string $item, string $directory): array { $parsedDate = (new \DateTime()) ->setTimestamp(strtotime("$month $day $time")); - $tomorrow = (new \DateTime())->add(new \DateInterval("P1D")); + $tomorrow = (new \DateTime())->add(new \DateInterval('P1D')); // since the provided date doesn't include the year, we either set it to the correct year // or when the date would otherwise be in the future (by more then 1 day to account for timezone errors) // we use last year if ($parsedDate > $tomorrow) { - $parsedDate = $parsedDate->sub(new \DateInterval("P1Y")); + $parsedDate = $parsedDate->sub(new \DateInterval('P1Y')); } $formattedDate = $parsedDate @@ -167,7 +167,7 @@ private function parseUnixItem(string $item, string $directory): array { 'name' => $name, 'modify' => $formattedDate, 'perm' => $this->normalizePermissions($permissions), - 'size' => (int)$size, + 'size' => (int) $size, ]; } @@ -216,7 +216,7 @@ private function parseWindowsItem(string $item, string $directory): array { 'name' => $name, 'modify' => $formattedDate, 'perm' => ($type === 'file') ? 'adfrw' : 'flcdmpe', - 'size' => (int)$size, + 'size' => (int) $size, ]; } } diff --git a/apps/files_external/lib/Lib/Storage/OwnCloud.php b/apps/files_external/lib/Lib/Storage/OwnCloud.php index d5562a3cb327f..20175e897f995 100644 --- a/apps/files_external/lib/Lib/Storage/OwnCloud.php +++ b/apps/files_external/lib/Lib/Storage/OwnCloud.php @@ -1,4 +1,5 @@ getConnection()->stat($this->absPath($path)); - $mtime = isset($stat['mtime']) ? (int)$stat['mtime'] : -1; - $size = isset($stat['size']) ? (int)$stat['size'] : 0; + $mtime = isset($stat['mtime']) ? (int) $stat['mtime'] : -1; + $size = isset($stat['size']) ? (int) $stat['size'] : 0; return [ 'mtime' => $mtime, @@ -482,7 +483,7 @@ public function writeStream(string $path, $stream, ?int $size = null): int { $size = $writtenSize; }); if (!$stream) { - throw new \Exception("Failed to wrap stream"); + throw new \Exception('Failed to wrap stream'); } } /** @psalm-suppress InternalMethod */ @@ -490,11 +491,11 @@ public function writeStream(string $path, $stream, ?int $size = null): int { fclose($stream); if ($result) { if ($size === null) { - throw new \Exception("Failed to get written size from sftp storage wrapper"); + throw new \Exception('Failed to get written size from sftp storage wrapper'); } return $size; } else { - throw new \Exception("Failed to write steam to sftp storage"); + throw new \Exception('Failed to write steam to sftp storage'); } } diff --git a/apps/files_external/lib/Lib/Storage/SMB.php b/apps/files_external/lib/Lib/Storage/SMB.php index 50ba29ecf13db..7ea615c739469 100644 --- a/apps/files_external/lib/Lib/Storage/SMB.php +++ b/apps/files_external/lib/Lib/Storage/SMB.php @@ -1,4 +1,5 @@ 0) { $options->setTimeout($timeout); } @@ -271,7 +272,7 @@ protected function getFolderContents($path): iterable { } } catch (ConnectException $e) { $this->logger->error('Error while getting folder content', ['exception' => $e]); - throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e); + throw new StorageNotAvailableException($e->getMessage(), (int) $e->getCode(), $e); } catch (NotFoundException $e) { throw new \OCP\Files\NotFoundException($e->getMessage(), 0, $e); } @@ -425,7 +426,7 @@ public function unlink($path) { return false; } catch (ConnectException $e) { $this->logger->error('Error while deleting file', ['exception' => $e]); - throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e); + throw new StorageNotAvailableException($e->getMessage(), (int) $e->getCode(), $e); } } @@ -509,10 +510,10 @@ public function fopen($path, $mode) { } catch (ForbiddenException $e) { return false; } catch (OutOfSpaceException $e) { - throw new EntityTooLargeException("not enough available space to create file", 0, $e); + throw new EntityTooLargeException('not enough available space to create file', 0, $e); } catch (ConnectException $e) { $this->logger->error('Error while opening file', ['exception' => $e]); - throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e); + throw new StorageNotAvailableException($e->getMessage(), (int) $e->getCode(), $e); } } @@ -539,7 +540,7 @@ public function rmdir($path) { return false; } catch (ConnectException $e) { $this->logger->error('Error while removing folder', ['exception' => $e]); - throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e); + throw new StorageNotAvailableException($e->getMessage(), (int) $e->getCode(), $e); } } @@ -552,10 +553,10 @@ public function touch($path, $mtime = null) { } return false; } catch (OutOfSpaceException $e) { - throw new EntityTooLargeException("not enough available space to create file", 0, $e); + throw new EntityTooLargeException('not enough available space to create file', 0, $e); } catch (ConnectException $e) { $this->logger->error('Error while creating file', ['exception' => $e]); - throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e); + throw new StorageNotAvailableException($e->getMessage(), (int) $e->getCode(), $e); } } @@ -652,7 +653,7 @@ public function mkdir($path) { return true; } catch (ConnectException $e) { $this->logger->error('Error while creating folder', ['exception' => $e]); - throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e); + throw new StorageNotAvailableException($e->getMessage(), (int) $e->getCode(), $e); } catch (Exception $e) { return false; } @@ -678,7 +679,7 @@ public function file_exists($path) { } catch (\OCP\Files\ForbiddenException $e) { return false; } catch (ConnectException $e) { - throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e); + throw new StorageNotAvailableException($e->getMessage(), (int) $e->getCode(), $e); } } @@ -722,7 +723,7 @@ public function isDeletable($path) { */ public static function checkDependencies() { return ( - (bool)\OC_Helper::findBinaryPath('smbclient') + (bool) \OC_Helper::findBinaryPath('smbclient') || NativeServer::available(new System()) ) ? true : ['smbclient']; } diff --git a/apps/files_external/lib/Lib/Storage/StreamWrapper.php b/apps/files_external/lib/Lib/Storage/StreamWrapper.php index 2928c081505c5..bff6b3de545a7 100644 --- a/apps/files_external/lib/Lib/Storage/StreamWrapper.php +++ b/apps/files_external/lib/Lib/Storage/StreamWrapper.php @@ -1,4 +1,5 @@ getHost()) { $params['bucket'] = basename($bucketUrl->getPath()); - $params['endpoint_url'] = (string)$bucketUrl->withPath(dirname($bucketUrl->getPath())); + $params['endpoint_url'] = (string) $bucketUrl->withPath(dirname($bucketUrl->getPath())); } if (empty($params['url'])) { @@ -324,7 +324,7 @@ public function stat($path) { } $stat = []; - $stat['size'] = (int)$object->contentLength; + $stat['size'] = (int) $object->contentLength; $stat['mtime'] = $mtime; $stat['atime'] = time(); return $stat; @@ -425,7 +425,7 @@ public function touch($path, $mtime = null) { if (is_null($mtime)) { $mtime = time(); } - $metadata = ['timestamp' => (string)$mtime]; + $metadata = ['timestamp' => (string) $mtime]; if ($this->file_exists($path)) { if ($this->is_dir($path) && $path !== '.') { $path .= '/'; diff --git a/apps/files_external/lib/Lib/StorageConfig.php b/apps/files_external/lib/Lib/StorageConfig.php index 682516c73bae3..be3b123083d16 100644 --- a/apps/files_external/lib/Lib/StorageConfig.php +++ b/apps/files_external/lib/Lib/StorageConfig.php @@ -1,4 +1,5 @@ getType()) { case \OCA\Files_External\Lib\DefinitionParameter::VALUE_BOOLEAN: - $value = (bool)$value; + $value = (bool) $value; break; } $backendOptions[$key] = $value; diff --git a/apps/files_external/lib/Lib/StorageModifierTrait.php b/apps/files_external/lib/Lib/StorageModifierTrait.php index 7cc7a15605ccb..f0f62a8b1d616 100644 --- a/apps/files_external/lib/Lib/StorageModifierTrait.php +++ b/apps/files_external/lib/Lib/StorageModifierTrait.php @@ -1,4 +1,5 @@ fetch()) { - $config = $this->getStorageConfig((int)$mount['mount_id']); + $config = $this->getStorageConfig((int) $mount['mount_id']); $hostname = $config['hostname']; $bucket = $config['bucket']; $key = $config['key']; diff --git a/apps/files_external/lib/MountConfig.php b/apps/files_external/lib/MountConfig.php index b057fb810bd08..f81537a7cf4f1 100644 --- a/apps/files_external/lib/MountConfig.php +++ b/apps/files_external/lib/MountConfig.php @@ -1,4 +1,5 @@ closeCursor(); foreach ($result as $row) { - if ((int)$row['count'] > 1) { + if ((int) $row['count'] > 1) { $this->removeApplicable($row['mount_id'], $applicableType, $applicableId); } else { $this->removeMount($row['mount_id']); @@ -402,8 +403,8 @@ private function getMountsFromQuery(IQueryBuilder $query) { $options = $this->getOptionsForMounts($mountIds); return array_map(function ($mount, $applicable, $config, $options) { - $mount['type'] = (int)$mount['type']; - $mount['priority'] = (int)$mount['priority']; + $mount['type'] = (int) $mount['type']; + $mount['priority'] = (int) $mount['priority']; $mount['applicable'] = $applicable; $mount['config'] = $config; $mount['options'] = $options; @@ -442,7 +443,7 @@ private function selectForMounts($table, array $fields, array $mountIds) { } foreach ($rows as $row) { if (isset($row['type'])) { - $row['type'] = (int)$row['type']; + $row['type'] = (int) $row['type']; } $result[$row['mount_id']][] = $row; } diff --git a/apps/files_external/lib/Service/GlobalStoragesService.php b/apps/files_external/lib/Service/GlobalStoragesService.php index c799007cc6dd4..8d29d52047260 100644 --- a/apps/files_external/lib/Service/GlobalStoragesService.php +++ b/apps/files_external/lib/Service/GlobalStoragesService.php @@ -1,4 +1,5 @@ setType($mount['type']); - $config->setId((int)$mount['mount_id']); + $config->setId((int) $mount['mount_id']); return $config; } catch (\UnexpectedValueException $e) { // don't die if a storage backend doesn't exist diff --git a/apps/files_external/lib/Service/UserGlobalStoragesService.php b/apps/files_external/lib/Service/UserGlobalStoragesService.php index 58590b8d682d1..89f850d391048 100644 --- a/apps/files_external/lib/Service/UserGlobalStoragesService.php +++ b/apps/files_external/lib/Service/UserGlobalStoragesService.php @@ -1,4 +1,5 @@ t("Enable encryption"); -$l->t("Enable previews"); -$l->t("Enable sharing"); -$l->t("Check for changes"); -$l->t("Never"); -$l->t("Once every direct access"); +$l->t('Enable encryption'); +$l->t('Enable previews'); +$l->t('Enable sharing'); +$l->t('Check for changes'); +$l->t('Never'); +$l->t('Once every direct access'); $l->t('Read only'); \OCP\Util::addScript('files_external', 'settings'); @@ -64,7 +64,7 @@ function writeParameterInput($parameter, $options, $classes = []) { - +