diff --git a/.drone.star b/.drone.star index 283a3f54b3eb..7bb32f06ce95 100644 --- a/.drone.star +++ b/.drone.star @@ -27,7 +27,7 @@ SONARSOURCE_SONAR_SCANNER_CLI = "sonarsource/sonar-scanner-cli" TOOLHIPPIE_CALENS = "toolhippie/calens:latest" WEBHIPPIE_REDIS = "webhippie/redis:latest" -DEFAULT_PHP_VERSION = "7.4" +DEFAULT_PHP_VERSION = "8.2" DEFAULT_NODEJS_VERSION = "14" # minio mc environment variables diff --git a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php index ffe6930fdb4a..4fcbc95e535e 100644 --- a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php +++ b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php @@ -41,21 +41,12 @@ * @license http://sabre.io/license/ Modified BSD License */ class IMipPlugin extends SabreIMipPlugin { - /** @var IMailer */ - private $mailer; - - /** @var ILogger */ - private $logger; - - /** @var IRequest */ - private $request; + private IMailer $mailer; + private ILogger $logger; + private IRequest $request; /** * Creates the email handler. - * - * @param IMailer $mailer - * @param ILogger $logger - * @param IRequest $request */ public function __construct(IMailer $mailer, ILogger $logger, IRequest $request) { parent::__construct(''); @@ -123,14 +114,10 @@ public function schedule(ITip\Message $iTipMessage) { ->setFrom([$sender => $senderName]) ->setTo([$recipient => $recipientName]) ->setSubject($subject) - ->setBody($iTipMessage->message->serialize(), $contentType); + ->attach($iTipMessage->message->serialize(), "event.ics", $contentType); try { - $failed = $this->mailer->send($message); + $this->mailer->send($message); $iTipMessage->scheduleStatus = '1.1; Scheduling message is sent via iMip'; - if ($failed) { - $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => \implode(', ', $failed)]); - $iTipMessage->scheduleStatus = '5.0; EMail delivery failed'; - } } catch (\Exception $ex) { $this->logger->logException($ex, ['app' => 'dav']); $iTipMessage->scheduleStatus = '5.0; EMail delivery failed'; diff --git a/apps/dav/lib/Connector/Sabre/Principal.php b/apps/dav/lib/Connector/Sabre/Principal.php index c9022719a894..4942052e8103 100644 --- a/apps/dav/lib/Connector/Sabre/Principal.php +++ b/apps/dav/lib/Connector/Sabre/Principal.php @@ -97,10 +97,10 @@ public function getPrincipalsByPrefix($prefixPath) { * getPrincipalsByPrefix. * * @param string $path - * @return array + * @return array|null */ - public function getPrincipalByPath($path) { - list($prefix, $name) = \Sabre\Uri\split($path); + public function getPrincipalByPath($path): ?array { + [$prefix, $name] = \Sabre\Uri\split($path); if ($prefix === $this->principalPrefix) { $user = $this->userManager->get($name); @@ -219,12 +219,12 @@ public function findByUri($uri, $principalPrefix) { * @param IUser $user * @return array */ - protected function userToPrincipal($user) { + protected function userToPrincipal(IUser $user): array { $userId = $user->getUID(); $displayName = $user->getDisplayName(); $principal = [ 'uri' => $this->principalPrefix . '/' . $userId, - '{DAV:}displayname' => $displayName === null ? $userId : $displayName, + '{DAV:}displayname' => $displayName, ]; $email = $user->getEMailAddress(); diff --git a/apps/dav/lib/Server.php b/apps/dav/lib/Server.php index 338be6e7816c..c4e5315a00df 100644 --- a/apps/dav/lib/Server.php +++ b/apps/dav/lib/Server.php @@ -179,7 +179,6 @@ public function __construct(IRequest $request, $baseUri) { $acl->principalCollectionSet = [ 'principals/users', 'principals/groups' ]; - $acl->defaultUsernamePath = 'principals/users'; $this->server->addPlugin($acl); } diff --git a/apps/dav/lib/Upload/AssemblyStream.php b/apps/dav/lib/Upload/AssemblyStream.php index 2f408f5b876a..da32e15b113d 100644 --- a/apps/dav/lib/Upload/AssemblyStream.php +++ b/apps/dav/lib/Upload/AssemblyStream.php @@ -248,9 +248,12 @@ public static function wrap(array $nodes) { 'assembly' => [ 'nodes' => $nodes] ]); - \stream_wrapper_register('assembly', '\OCA\DAV\Upload\AssemblyStream'); + $existed = \in_array("assembly", stream_get_wrappers()); + if (!$existed) { + \stream_wrapper_register('assembly', __CLASS__); + } try { - $wrapped = \fopen('assembly://', 'r', null, $context); + $wrapped = \fopen('assembly://', 'r', false, $context); } catch (\BadMethodCallException $e) { \stream_wrapper_unregister('assembly'); throw $e; diff --git a/apps/dav/tests/unit/CalDAV/CalendarTest.php b/apps/dav/tests/unit/CalDAV/CalendarTest.php index 4cdbfe8a517f..a5042f271840 100644 --- a/apps/dav/tests/unit/CalDAV/CalendarTest.php +++ b/apps/dav/tests/unit/CalDAV/CalendarTest.php @@ -42,9 +42,9 @@ public function setUp(): void { $this->l10n ->expects($this->any()) ->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { + ->willReturnCallback(function ($text, $parameters = []) { return \vsprintf($text, $parameters); - })); + }); } public function testDelete() { diff --git a/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php index c1902456caab..534cd97253e0 100644 --- a/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php +++ b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php @@ -22,124 +22,78 @@ namespace OCA\DAV\Tests\unit\CalDAV\Schedule; +use Exception; use OC\Mail\Mailer; use OCA\DAV\CalDAV\Schedule\IMipPlugin; use OCP\ILogger; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\VObject\Component\VCalendar; use Sabre\VObject\ITip\Message; +use Symfony\Component\Mime\Email; use Test\TestCase; use OC\Log; class IMipPluginTest extends TestCase { - public function testDelivery() { - $mailMessage = new \OC\Mail\Message(new \Swift_Message()); - /** @var Mailer | \PHPUnit\Framework\MockObject\MockObject $mailer */ - $mailer = $this->createMock(Mailer::class); - $mailer->method('createMessage')->willReturn($mailMessage); - $mailer->expects($this->once())->method('send'); - /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject $logger */ - $logger = $this->createMock(Log::class); - /** @var IRequest| \PHPUnit\Framework\MockObject\MockObject $request */ + private \OC\Mail\Message $mailMessage; + /** + * @var Mailer|MockObject + */ + private $mailer; + private IMipPlugin $plugin; + /** @var ILogger|MockObject */ + private $logger; + + protected function setUp(): void { + parent::setUp(); + + $this->mailMessage = new \OC\Mail\Message(new Email()); + $this->mailer = $this->createMock(Mailer::class); + $this->mailer->method('createMessage')->willReturn($this->mailMessage); + + $this->logger = $this->createMock(Log::class); + /** @var IRequest| MockObject $request */ $request = $this->createMock(IRequest::class); - $plugin = new IMipPlugin($mailer, $logger, $request); - $message = new Message(); - $message->method = 'REQUEST'; - $message->message = new VCalendar(); - $message->message->add('VEVENT', [ - 'UID' => $message->uid, - 'SEQUENCE' => $message->sequence, - 'SUMMARY' => 'Fellowship meeting', - ]); - $message->sender = 'mailto:gandalf@wiz.ard'; - $message->recipient = 'mailto:frodo@hobb.it'; + $this->plugin = new IMipPlugin($this->mailer, $this->logger, $request); + } + + public function testDelivery(): void { + $this->mailer->expects($this->once())->method('send'); + + $message = $this->buildIMIPMessage('REQUEST'); - $plugin->schedule($message); + $this->plugin->schedule($message); $this->assertEquals('1.1', $message->getScheduleStatus()); - $this->assertEquals('Fellowship meeting', $mailMessage->getSubject()); - $this->assertEquals(['frodo@hobb.it' => null], $mailMessage->getTo()); - $this->assertEquals(['gandalf@wiz.ard' => null], $mailMessage->getReplyTo()); - $this->assertEquals('text/calendar; charset=UTF-8; method=REQUEST', $mailMessage->getSwiftMessage()->getContentType()); + $this->assertEquals('Fellowship meeting', $this->mailMessage->getSubject()); + $this->assertEquals(['frodo@hobb.it' => null], $this->mailMessage->getTo()); + $this->assertEquals(['gandalf@wiz.ard' => null], $this->mailMessage->getReplyTo()); + $this->assertStringContainsString('text/calendar; charset=UTF-8; method=REQUEST', $this->mailMessage->getMessage()->getBody()->bodyToString()); } - public function testFailedDeliveryWithException() { - $mailMessage = new \OC\Mail\Message(new \Swift_Message()); - /** @var Mailer | \PHPUnit\Framework\MockObject\MockObject $mailer */ - $mailer = $this->createMock(Mailer::class); - $mailer->method('createMessage')->willReturn($mailMessage); - $mailer->method('send')->willThrowException(new \Exception()); - /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject $logger */ - $logger = $this->createMock(Log::class); - /** @var IRequest| \PHPUnit\Framework\MockObject\MockObject $request */ - $request = $this->createMock(IRequest::class); + public function testFailedDeliveryWithException(): void { + $ex = new Exception(); + $this->mailer->method('send')->willThrowException($ex); + $this->logger->expects(self::once())->method('logException')->with($ex, ['app' => 'dav']); - $plugin = new IMipPlugin($mailer, $logger, $request); - $message = new Message(); - $message->method = 'REQUEST'; - $message->message = new VCalendar(); - $message->message->add('VEVENT', [ - 'UID' => $message->uid, - 'SEQUENCE' => $message->sequence, - 'SUMMARY' => 'Fellowship meeting', - ]); - $message->sender = 'mailto:gandalf@wiz.ard'; - $message->recipient = 'mailto:frodo@hobb.it'; + $message = $this->buildIMIPMessage('REQUEST'); - $plugin->schedule($message); - $this->assertEquals('5.0', $message->getScheduleStatus()); - $this->assertEquals('Fellowship meeting', $mailMessage->getSubject()); - $this->assertEquals(['frodo@hobb.it' => null], $mailMessage->getTo()); - $this->assertEquals(['gandalf@wiz.ard' => null], $mailMessage->getReplyTo()); - $this->assertEquals('text/calendar; charset=UTF-8; method=REQUEST', $mailMessage->getSwiftMessage()->getContentType()); + $this->plugin->schedule($message); + $this->assertIMipState($message, '5.0', 'REQUEST', 'Fellowship meeting'); } - public function testFailedDelivery() { - $mailMessage = new \OC\Mail\Message(new \Swift_Message()); - /** @var Mailer | \PHPUnit\Framework\MockObject\MockObject $mailer */ - $mailer = $this->createMock(Mailer::class); - $mailer->method('createMessage')->willReturn($mailMessage); - $mailer->method('send')->willReturn(['foo@example.net']); - /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject $logger */ - $logger = $this->createMock(Log::class); - $logger->expects(self::once())->method('error')->with('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => 'foo@example.net']); - /** @var IRequest| \PHPUnit\Framework\MockObject\MockObject $request */ - $request = $this->createMock(IRequest::class); + public function testDeliveryOfCancel(): void { + $this->mailer->expects($this->once())->method('send'); - $plugin = new IMipPlugin($mailer, $logger, $request); - $message = new Message(); - $message->method = 'REQUEST'; - $message->message = new VCalendar(); - $message->message->add('VEVENT', [ - 'UID' => $message->uid, - 'SEQUENCE' => $message->sequence, - 'SUMMARY' => 'Fellowship meeting', - ]); - $message->sender = 'mailto:gandalf@wiz.ard'; - $message->recipient = 'mailto:frodo@hobb.it'; + $message = $this->buildIMIPMessage('CANCEL'); - $plugin->schedule($message); - $this->assertEquals('5.0', $message->getScheduleStatus()); - $this->assertEquals('Fellowship meeting', $mailMessage->getSubject()); - $this->assertEquals(['frodo@hobb.it' => null], $mailMessage->getTo()); - $this->assertEquals(['gandalf@wiz.ard' => null], $mailMessage->getReplyTo()); - $this->assertEquals('text/calendar; charset=UTF-8; method=REQUEST', $mailMessage->getSwiftMessage()->getContentType()); + $this->plugin->schedule($message); + $this->assertIMipState($message, '1.1', 'CANCEL', 'Cancelled: Fellowship meeting'); } - public function testDeliveryOfCancel() { - $mailMessage = new \OC\Mail\Message(new \Swift_Message()); - /** @var Mailer | \PHPUnit\Framework\MockObject\MockObject $mailer */ - $mailer = $this->createMock(Mailer::class); - $mailer->method('createMessage')->willReturn($mailMessage); - $mailer->expects($this->once())->method('send'); - /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject $logger */ - $logger = $this->createMock(Log::class); - /** @var IRequest| \PHPUnit\Framework\MockObject\MockObject $request */ - $request = $this->createMock(IRequest::class); - - $plugin = new IMipPlugin($mailer, $logger, $request); + private function buildIMIPMessage(string $method): Message { $message = new Message(); - $message->method = 'CANCEL'; + $message->method = $method; $message->message = new VCalendar(); $message->message->add('VEVENT', [ 'UID' => $message->uid, @@ -148,13 +102,14 @@ public function testDeliveryOfCancel() { ]); $message->sender = 'mailto:gandalf@wiz.ard'; $message->recipient = 'mailto:frodo@hobb.it'; + return $message; + } - $plugin->schedule($message); - $this->assertEquals('1.1', $message->getScheduleStatus()); - $this->assertEquals('Cancelled: Fellowship meeting', $mailMessage->getSubject()); - $this->assertEquals(['frodo@hobb.it' => null], $mailMessage->getTo()); - $this->assertEquals(['gandalf@wiz.ard' => null], $mailMessage->getReplyTo()); - $this->assertEquals('text/calendar; charset=UTF-8; method=CANCEL', $mailMessage->getSwiftMessage()->getContentType()); - $this->assertEquals('CANCELLED', $message->message->VEVENT->STATUS->getValue()); + private function assertIMipState(Message $message, string $scheduleStatus, string $method, string $mailSubject): void { + $this->assertEquals($scheduleStatus, $message->getScheduleStatus()); + $this->assertEquals($mailSubject, $this->mailMessage->getSubject()); + $this->assertEquals(['frodo@hobb.it' => null], $this->mailMessage->getTo()); + $this->assertEquals(['gandalf@wiz.ard' => null], $this->mailMessage->getReplyTo()); + $this->assertStringContainsString("text/calendar; charset=UTF-8; method=$method", $this->mailMessage->getMessage()->getBody()->bodyToString()); } } diff --git a/apps/dav/tests/unit/Connector/Sabre/FileTest.php b/apps/dav/tests/unit/Connector/Sabre/FileTest.php index 20c7ec8cb72a..29c9d923201e 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FileTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FileTest.php @@ -262,13 +262,12 @@ public function testFileContentNotAllowedConvertedToForbidden() { ->getMock(); $view->expects($this->atLeastOnce()) ->method('resolvePath') - ->will( - $this->returnCallback( - function ($path) use ($storage) { - return [$storage, $path]; - } - ) + ->willReturnCallback( + function ($path) use ($storage) { + return [$storage, $path]; + } ); + $view->method('getRelativePath')->willReturn('test.txt'); $storage->expects($this->once()) ->method('fopen') @@ -349,11 +348,11 @@ public function testChunkedPutFails($thrownException, $expectedException, $check $view = $this->createMock(View::class, ['getRelativePath', 'resolvePath'], []); $view->expects($this->atLeastOnce()) ->method('resolvePath') - ->will($this->returnCallback( - function ($path) use ($storage) { - return [$storage, $path]; - } - )); + ->willReturnCallback(function ($path) use ($storage) { + return [$storage, $path]; + }); + $view->method('getAbsolutePath')->willReturnArgument(0); + $view->method('getRelativePath')->willReturnArgument(0); if ($thrownException !== null) { $storage->expects($this->once()) @@ -362,7 +361,7 @@ function ($path) use ($storage) { } else { $storage->expects($this->once()) ->method('fopen') - ->will($this->returnValue(false)); + ->willReturn(false); } $view->expects($this->any()) @@ -774,7 +773,7 @@ public function testPutOverwriteFileTriggersHooks() { * if the passed view was chrooted (can happen with public webdav * where the root is the share root) */ - public function testPutSingleFileTriggersHooksDifferentRoot() { + public function testPutSingleFileTriggersHooksDifferentRoot(): void { $view = Filesystem::getView(); $view->mkdir('noderoot'); diff --git a/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php index 61b35a748307..e8bcbc200498 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php @@ -612,6 +612,10 @@ public function testAdditionalHeaders() { ->expects($this->once()) ->method('getName') ->willReturn('somefile.xml'); + $node + ->expects($this->once()) + ->method('getContentDispositionFileName') + ->willReturn('somefile.xml'); $this->tree ->expects($this->once()) diff --git a/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php index 2dda24113852..ed3167881e16 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php @@ -25,45 +25,57 @@ namespace OCA\DAV\Tests\unit\Connector\Sabre; use OC\Files\View; +use OCA\DAV\Connector\Sabre\Directory; +use OCA\DAV\Connector\Sabre\FilesPlugin; use OCA\DAV\Connector\Sabre\FilesReportPlugin as FilesReportPluginImplementation; use OCA\DAV\Files\Xml\FilterRequest; +use OCP\Files\File; use OCP\Files\Folder; use OCP\IConfig; use OCP\IGroupManager; use OCP\IRequest; use OCP\ITags; +use OCP\IUserSession; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\ISystemTagObjectMapper; - -class FilesReportPluginTest extends \Test\TestCase { - /** @var \Sabre\DAV\Server|\PHPUnit\Framework\MockObject\MockObject */ +use OCP\SystemTag\TagNotFoundException; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Server; +use Sabre\DAV\Tree; +use Sabre\HTTP\ResponseInterface; +use Test\TestCase; +use function array_keys; +use function array_values; + +class FilesReportPluginTest extends TestCase { + /** @var Server|MockObject */ private $server; - /** @var \Sabre\DAV\Tree|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Tree|MockObject */ private $tree; - /** @var ISystemTagObjectMapper|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ISystemTagObjectMapper|MockObject */ private $tagMapper; - /** @var ISystemTagManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ISystemTagManager|MockObject */ private $tagManager; - /** @var ITags|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ITags|MockObject */ private $privateTags; - /** @var \OCP\IUserSession */ + /** @var IUserSession */ private $userSession; /** @var FilesReportPluginImplementation */ private $plugin; - /** @var View|\PHPUnit\Framework\MockObject\MockObject **/ + /** @var View|MockObject **/ private $view; - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject **/ + /** @var IGroupManager|MockObject **/ private $groupManager; - /** @var Folder|\PHPUnit\Framework\MockObject\MockObject **/ + /** @var Folder|MockObject **/ private $userFolder; public function setUp(): void { @@ -81,7 +93,7 @@ public function setUp(): void { $this->server->expects($this->any()) ->method('getBaseUri') - ->will($this->returnValue('http://example.com/owncloud/remote.php/dav')); + ->willReturn('http://example.com/owncloud/remote.php/dav'); $this->groupManager = $this->getMockBuilder('\OCP\IGroupManager') ->disableOriginalConstructor() @@ -99,19 +111,19 @@ public function setUp(): void { $privateTagManager->expects($this->any()) ->method('load') ->with('files') - ->will($this->returnValue($this->privateTags)); + ->willReturn($this->privateTags); $user = $this->createMock('\OCP\IUser'); $user->expects($this->any()) ->method('getUID') - ->will($this->returnValue('testuser')); + ->willReturn('testuser'); $this->userSession->expects($this->any()) ->method('getUser') - ->will($this->returnValue($user)); + ->willReturn($user); // add FilesPlugin to test more properties $this->server->addPlugin( - new \OCA\DAV\Connector\Sabre\FilesPlugin( + new FilesPlugin( $this->tree, $this->createMock(IConfig::class), $this->createMock(IRequest::class) @@ -179,7 +191,7 @@ public function testOnReport() { $this->groupManager->expects($this->any()) ->method('isAdmin') - ->will($this->returnValue(true)); + ->willReturn(true); $this->tagMapper ->expects($this->exactly(2)) @@ -193,8 +205,9 @@ public function testOnReport() { ['111', '222', '333'], ); - $reportTargetNode = $this->createMock(\OCA\DAV\Connector\Sabre\Directory::class); - $response = $this->createMock(\Sabre\HTTP\ResponseInterface::class); + $reportTargetNode = $this->createMock(Directory::class); + $reportTargetNode->method('getPath')->willReturn(''); + $response = $this->createMock(ResponseInterface::class); $response->expects($this->once()) ->method('setHeader') ->with('Content-Type', 'application/xml; charset=utf-8'); @@ -209,14 +222,14 @@ public function testOnReport() { $this->tree->expects($this->any()) ->method('getNodeForPath') ->with('/' . $path) - ->will($this->returnValue($reportTargetNode)); + ->willReturn($reportTargetNode); - $filesNode1 = $this->createMock(\OCP\Files\Folder::class); + $filesNode1 = $this->createMock(Folder::class); $filesNode1->method('getId')->willReturn(111); $filesNode1->method('getPath')->willReturn('/node1'); $filesNode1->method('isReadable')->willReturn(true); $filesNode1->method('getSize')->willReturn(2048); - $filesNode2 = $this->createMock(\OCP\Files\File::class); + $filesNode2 = $this->createMock(File::class); $filesNode2->method('getId')->willReturn(222); $filesNode2->method('getPath')->willReturn('/sub/node2'); $filesNode2->method('getSize')->willReturn(1024); @@ -236,17 +249,17 @@ public function testOnReport() { $this->server->expects($this->any()) ->method('getRequestUri') - ->will($this->returnValue($path)); + ->willReturn($path); $this->server->httpResponse = $response; $this->plugin->initialize($this->server); $responses = null; $this->server->expects($this->once()) ->method('generateMultiStatus') - ->will( - $this->returnCallback(function ($responsesArg) use (&$responses) { + ->willReturnCallback( + function ($responsesArg) use (&$responses) { $responses = $responsesArg; - }) + } ); $this->assertFalse($this->plugin->onReport(FilesReportPluginImplementation::REPORT_NAME, $parameters, '/' . $path)); @@ -273,7 +286,7 @@ public function testOnReport() { $this->assertCount(0, $props2[200]['{DAV:}resourcetype']->getValue()); } - public function testOnReportPaginationFiltered() { + public function testOnReportPaginationFiltered(): void { $path = 'test'; $parameters = new FilterRequest(); @@ -291,7 +304,7 @@ public function testOnReportPaginationFiltered() { $filesNodes = []; for ($i = 0; $i < 20; $i++) { - $filesNode = $this->createMock(\OCP\Files\File::class); + $filesNode = $this->createMock(File::class); $filesNode->method('getId')->willReturn(1000 + $i); $filesNode->method('getPath')->willReturn('/nodes/node' . $i); $filesNode->method('isReadable')->willReturn(true); @@ -301,14 +314,15 @@ public function testOnReportPaginationFiltered() { // return all above nodes as favorites $this->privateTags->expects($this->once()) ->method('getFavorites') - ->will($this->returnValue(\array_keys($filesNodes))); + ->willReturn(array_keys($filesNodes)); - $reportTargetNode = $this->createMock(\OCA\DAV\Connector\Sabre\Directory::class); + $reportTargetNode = $this->createMock(Directory::class); + $reportTargetNode->method('getPath')->willReturn('/'); $this->tree->expects($this->any()) ->method('getNodeForPath') ->with('/' . $path) - ->will($this->returnValue($reportTargetNode)); + ->willReturn($reportTargetNode); // getById must only be called for the required nodes $this->userFolder @@ -327,17 +341,17 @@ public function testOnReportPaginationFiltered() { $this->server->expects($this->any()) ->method('getRequestUri') - ->will($this->returnValue($path)); + ->willReturn($path); $this->plugin->initialize($this->server); $responses = null; $this->server->expects($this->once()) ->method('generateMultiStatus') - ->will( - $this->returnCallback(function ($responsesArg) use (&$responses) { + ->willReturnCallback( + function ($responsesArg) use (&$responses) { $responses = $responsesArg; - }) + } ); $this->assertFalse($this->plugin->onReport(FilesReportPluginImplementation::REPORT_NAME, $parameters, '/' . $path)); @@ -383,7 +397,7 @@ public function testFindNodesByFileIdsRoot() { [$filesNode2], ); - /** @var \OCA\DAV\Connector\Sabre\Directory|\PHPUnit\Framework\MockObject\MockObject $reportTargetNode */ + /** @var Directory|MockObject $reportTargetNode */ $result = $this->plugin->findNodesByFileIds($reportTargetNode, ['111', '222']); $this->assertCount(2, $result); @@ -436,7 +450,7 @@ public function testFindNodesByFileIdsSubDir() { [$filesNode2], ); - /** @var \OCA\DAV\Connector\Sabre\Directory|\PHPUnit\Framework\MockObject\MockObject $reportTargetNode */ + /** @var Directory|MockObject $reportTargetNode */ $result = $this->plugin->findNodesByFileIds($reportTargetNode, ['111', '222']); $this->assertCount(2, $result); @@ -489,7 +503,7 @@ public function testProcessFilterRulesAndCondition() { 'favorite' => null ]; - $this->assertEquals(['222'], \array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); + $this->assertEquals(['222'], array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); } public function testProcessFilterRulesAndConditionWithOneEmptyResult() { @@ -513,7 +527,7 @@ public function testProcessFilterRulesAndConditionWithOneEmptyResult() { 'favorite' => null ]; - $this->assertEquals([], \array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); + $this->assertEquals([], array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); } public function testProcessFilterRulesAndConditionWithFirstEmptyResult() { @@ -537,7 +551,7 @@ public function testProcessFilterRulesAndConditionWithFirstEmptyResult() { 'favorite' => null ]; - $this->assertEquals([], \array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); + $this->assertEquals([], array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); } public function testProcessFilterRulesAndConditionWithEmptyMidResult() { @@ -563,7 +577,7 @@ public function testProcessFilterRulesAndConditionWithEmptyMidResult() { 'favorite' => null ]; - $this->assertEquals([], \array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); + $this->assertEquals([], array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); } public function testProcessFilterRulesInvisibleTagAsAdmin() { @@ -608,13 +622,13 @@ public function testProcessFilterRulesInvisibleTagAsAdmin() { 'favorite' => null ]; - $this->assertEquals(['222'], \array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); + $this->assertEquals(['222'], array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); } /** */ public function testProcessFilterRulesInvisibleTagAsUser() { - $this->expectException(\OCP\SystemTag\TagNotFoundException::class); + $this->expectException(TagNotFoundException::class); $this->groupManager->expects($this->any()) ->method('isAdmin') @@ -692,7 +706,7 @@ public function testProcessFilterRulesVisibleTagAsUser() { 'favorite' => null ]; - $this->assertEquals(['222'], \array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); + $this->assertEquals(['222'], array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); } public function testProcessFavoriteFilter() { @@ -705,7 +719,7 @@ public function testProcessFavoriteFilter() { ->method('getFavorites') ->will($this->returnValue(['456', '789'])); - $this->assertEquals(['456', '789'], \array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); + $this->assertEquals(['456', '789'], array_values(self::invokePrivate($this->plugin, 'processFilterRules', [$rules]))); } public function filesBaseUriProvider() { diff --git a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php index 7374792ac287..ecedf884193d 100644 --- a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php @@ -24,67 +24,75 @@ namespace OCA\DAV\Tests\unit\Connector\Sabre; +use OCA\DAV\Connector\Sabre\Principal; use OCP\IGroupManager; use OCP\IUserManager; +use Sabre\DAV\Exception; use Sabre\DAV\PropPatch; use Test\TestCase; +use OC\User\User; +use OCP\IGroup; class PrincipalTest extends TestCase { /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ private $userManager; - /** @var \OCA\DAV\Connector\Sabre\Principal */ + /** @var Principal */ private $connector; /** @var IGroupManager | \PHPUnit\Framework\MockObject\MockObject */ private $groupManager; public function setUp(): void { - $this->userManager = $this->getMockBuilder('\OCP\IUserManager') + $this->userManager = $this->getMockBuilder(IUserManager::class) ->disableOriginalConstructor()->getMock(); - $this->groupManager = $this->getMockBuilder('\OCP\IGroupManager') + $this->groupManager = $this->getMockBuilder(IGroupManager::class) ->disableOriginalConstructor()->getMock(); - $this->connector = new \OCA\DAV\Connector\Sabre\Principal( + $this->connector = new Principal( $this->userManager, $this->groupManager ); parent::setUp(); } - public function testGetPrincipalsByPrefixWithoutPrefix() { + public function testGetPrincipalsByPrefixWithoutPrefix(): void { $response = $this->connector->getPrincipalsByPrefix(''); $this->assertSame([], $response); } - public function testGetPrincipalsByPrefixWithUsers() { - $fooUser = $this->getMockBuilder('\OC\User\User') + public function testGetPrincipalsByPrefixWithUsers(): void { + $fooUser = $this->getMockBuilder(User::class) ->disableOriginalConstructor()->getMock(); $fooUser - ->expects($this->exactly(1)) + ->expects($this->once()) ->method('getUID') - ->will($this->returnValue('foo')); + ->willReturn('foo'); $fooUser - ->expects($this->exactly(1)) + ->expects($this->once()) ->method('getDisplayName') - ->will($this->returnValue('Dr. Foo-Bar')); + ->willReturn('Dr. Foo-Bar'); $fooUser - ->expects($this->exactly(1)) + ->expects($this->once()) ->method('getEMailAddress') - ->will($this->returnValue('')); - $barUser = $this->getMockBuilder('\OC\User\User') + ->willReturn(''); + $barUser = $this->getMockBuilder(User::class) ->disableOriginalConstructor()->getMock(); $barUser - ->expects($this->exactly(1)) + ->expects($this->once()) ->method('getUID') - ->will($this->returnValue('bar')); + ->willReturn('bar'); + $barUser + ->expects($this->once()) + ->method('getDisplayName') + ->willReturn('bar'); $barUser - ->expects($this->exactly(1)) + ->expects($this->once()) ->method('getEMailAddress') - ->will($this->returnValue('bar@owncloud.com')); + ->willReturn('bar@owncloud.com'); $this->userManager ->expects($this->once()) ->method('search') ->with('') - ->will($this->returnValue([$fooUser, $barUser])); + ->willReturn([$fooUser, $barUser]); $expectedResponse = [ 0 => [ @@ -101,29 +109,33 @@ public function testGetPrincipalsByPrefixWithUsers() { $this->assertSame($expectedResponse, $response); } - public function testGetPrincipalsByPrefixEmpty() { + public function testGetPrincipalsByPrefixEmpty(): void { $this->userManager ->expects($this->once()) ->method('search') ->with('') - ->will($this->returnValue([])); + ->willReturn([]); $response = $this->connector->getPrincipalsByPrefix('principals/users'); $this->assertSame([], $response); } - public function testGetPrincipalsByPathWithoutMail() { - $fooUser = $this->getMockBuilder('\OC\User\User') + public function testGetPrincipalsByPathWithoutMail(): void { + $fooUser = $this->getMockBuilder(User::class) ->disableOriginalConstructor()->getMock(); $fooUser - ->expects($this->exactly(1)) + ->expects($this->once()) ->method('getUID') - ->will($this->returnValue('foo')); + ->willReturn('foo'); + $fooUser + ->expects($this->once()) + ->method('getDisplayname') + ->willReturn('foo'); $this->userManager ->expects($this->once()) ->method('get') ->with('foo') - ->will($this->returnValue($fooUser)); + ->willReturn($fooUser); $expectedResponse = [ 'uri' => 'principals/users/foo', @@ -133,22 +145,26 @@ public function testGetPrincipalsByPathWithoutMail() { $this->assertSame($expectedResponse, $response); } - public function testGetPrincipalsByPathWithMail() { - $fooUser = $this->getMockBuilder('\OC\User\User') + public function testGetPrincipalsByPathWithMail(): void { + $fooUser = $this->getMockBuilder(User::class) ->disableOriginalConstructor()->getMock(); $fooUser - ->expects($this->exactly(1)) + ->expects($this->once()) ->method('getEMailAddress') - ->will($this->returnValue('foo@owncloud.com')); + ->willReturn('foo@owncloud.com'); $fooUser - ->expects($this->exactly(1)) - ->method('getUID') - ->will($this->returnValue('foo')); + ->expects($this->once()) + ->method('getUID') + ->willReturn('foo'); + $fooUser + ->expects($this->once()) + ->method('getDisplayName') + ->willReturn('foo'); $this->userManager ->expects($this->once()) ->method('get') ->with('foo') - ->will($this->returnValue($fooUser)); + ->willReturn($fooUser); $expectedResponse = [ 'uri' => 'principals/users/foo', @@ -159,29 +175,29 @@ public function testGetPrincipalsByPathWithMail() { $this->assertSame($expectedResponse, $response); } - public function testGetPrincipalsByPathEmpty() { + public function testGetPrincipalsByPathEmpty(): void { $this->userManager ->expects($this->once()) ->method('get') ->with('foo') - ->will($this->returnValue(null)); + ->willReturn(null); $response = $this->connector->getPrincipalByPath('principals/users/foo'); $this->assertNull($response); } - public function testGetGroupMemberSet() { - $fooUser = $this->getMockBuilder('\OC\User\User') + public function testGetGroupMemberSet(): void { + $fooUser = $this->getMockBuilder(User::class) ->disableOriginalConstructor()->getMock(); $fooUser - ->expects($this->exactly(1)) + ->expects($this->once()) ->method('getUID') - ->will($this->returnValue('foo')); + ->willReturn('foo'); $this->userManager ->expects($this->once()) ->method('get') ->with('foo') - ->will($this->returnValue($fooUser)); + ->willReturn($fooUser); $response = $this->connector->getGroupMemberSet('principals/users/foo'); $this->assertSame(['principals/users/foo'], $response); @@ -189,23 +205,23 @@ public function testGetGroupMemberSet() { /** */ - public function testGetGroupMemberSetEmpty() { - $this->expectException(\Sabre\DAV\Exception::class); + public function testGetGroupMemberSetEmpty(): void { + $this->expectException(Exception::class); $this->expectExceptionMessage('Principal not found'); $this->userManager ->expects($this->once()) ->method('get') ->with('foo') - ->will($this->returnValue(null)); + ->willReturn(null); $this->connector->getGroupMemberSet('principals/users/foo'); } - public function testGetGroupMembership() { - $fooUser = $this->getMockBuilder('\OC\User\User') + public function testGetGroupMembership(): void { + $fooUser = $this->getMockBuilder(User::class) ->disableOriginalConstructor()->getMock(); - $group = $this->getMockBuilder('\OCP\IGroup') + $group = $this->getMockBuilder(IGroup::class) ->disableOriginalConstructor()->getMock(); $group->expects($this->once()) ->method('getGID') @@ -229,45 +245,43 @@ public function testGetGroupMembership() { $this->assertSame($expectedResponse, $response); } - /** - */ - public function testGetGroupMembershipEmpty() { - $this->expectException(\Sabre\DAV\Exception::class); + public function testGetGroupMembershipEmpty(): void { + $this->expectException(Exception::class); $this->expectExceptionMessage('Principal not found'); $this->userManager ->expects($this->once()) ->method('get') ->with('foo') - ->will($this->returnValue(null)); + ->willReturn(null); $this->connector->getGroupMembership('principals/users/foo'); } /** */ - public function testSetGroupMembership() { - $this->expectException(\Sabre\DAV\Exception::class); + public function testSetGroupMembership(): void { + $this->expectException(Exception::class); $this->expectExceptionMessage('Setting members of the group is not supported yet'); $this->connector->setGroupMemberSet('principals/users/foo', ['foo']); } - public function testUpdatePrincipal() { + public function testUpdatePrincipal(): void { $this->assertSame(0, $this->connector->updatePrincipal('foo', new PropPatch([]))); } - public function testSearchPrincipals() { + public function testSearchPrincipals(): void { $this->assertSame([], $this->connector->searchPrincipals('principals/users', [])); } - public function testFindByUri() { - $fooUser = $this->getMockBuilder('\OC\User\User') + public function testFindByUri(): void { + $fooUser = $this->getMockBuilder(User::class) ->disableOriginalConstructor()->getMock(); $fooUser - ->expects($this->exactly(1)) + ->expects($this->once()) ->method('getUID') - ->will($this->returnValue('foo')); + ->willReturn('foo'); $this->userManager->expects($this->once())->method('getByEmail')->willReturn([ $fooUser diff --git a/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php b/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php index a67094929978..df84d9868ac8 100644 --- a/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php +++ b/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php @@ -111,7 +111,7 @@ public function createShare() { null ); - if (\strlen($token) > 128) { + if ($token === null || \strlen($token) > 128) { throw new BadRequestException('Token too long'); } diff --git a/apps/federatedfilesharing/lib/FederatedShareProvider.php b/apps/federatedfilesharing/lib/FederatedShareProvider.php index 5989f3af249e..6c9a60cfdea9 100644 --- a/apps/federatedfilesharing/lib/FederatedShareProvider.php +++ b/apps/federatedfilesharing/lib/FederatedShareProvider.php @@ -723,7 +723,7 @@ public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offs * @inheritdoc */ public function getShareById($id, $recipientId = null) { - if (!ctype_digit($id)) { + if (!ctype_digit((string)$id)) { // share id is defined as a field of type integer // if someone calls the API asking for a share id like "abc" or "42.1" // then there is no point trying to query the database, diff --git a/apps/federatedfilesharing/tests/Controller/OcmControllerTest.php b/apps/federatedfilesharing/tests/Controller/OcmControllerTest.php index 6532d544a783..fff53ca61b20 100644 --- a/apps/federatedfilesharing/tests/Controller/OcmControllerTest.php +++ b/apps/federatedfilesharing/tests/Controller/OcmControllerTest.php @@ -115,6 +115,8 @@ protected function setUp(): void { $this->logger = $this->createMock(ILogger::class); $this->config = $this->createMock(IConfig::class); + $this->urlGenerator->method('linkToRouteAbsolute')->willReturn(''); + $this->ocmController = new OcmController( 'federatedfilesharing', $this->request, diff --git a/apps/federatedfilesharing/tests/Panels/GeneralPersonalPanelTest.php b/apps/federatedfilesharing/tests/Panels/GeneralPersonalPanelTest.php index 602ef9c4f0b2..d5e6e5c92671 100644 --- a/apps/federatedfilesharing/tests/Panels/GeneralPersonalPanelTest.php +++ b/apps/federatedfilesharing/tests/Panels/GeneralPersonalPanelTest.php @@ -49,6 +49,10 @@ class GeneralPersonalPanelTest extends \Test\TestCase { public function setUp(): void { parent::setUp(); $this->l = $this->getMockBuilder(IL10N::class)->getMock(); + $this->l->method('t')->willReturnCallback(function ($text, $parameters = []) { + return \vsprintf($text, $parameters); + }); + $this->urlGenerator = $this->getMockBuilder(IURLGenerator::class)->getMock(); $this->userSession = $this->getMockBuilder(IUserSession::class)->getMock(); $this->request = $this->getMockBuilder(IRequest::class)->getMock(); diff --git a/apps/federatedfilesharing/tests/TestCase.php b/apps/federatedfilesharing/tests/TestCase.php index 6f5628d63748..ec2165ab14b1 100644 --- a/apps/federatedfilesharing/tests/TestCase.php +++ b/apps/federatedfilesharing/tests/TestCase.php @@ -25,6 +25,7 @@ use OC\Files\Filesystem; use OCA\Files\Share; use Test\Traits\UserTrait; +use OCA\Files_Sharing\SharedStorage; /** * Class Test_Files_Sharing_Base @@ -85,8 +86,6 @@ public static function tearDownAfterClass(): void { * @param string $user */ protected static function loginHelper($user) { - self::resetStorage(); - \OC_Util::tearDownFS(); \OC::$server->getUserSession()->setUser(null); \OC\Files\Filesystem::tearDown(); @@ -95,15 +94,4 @@ protected static function loginHelper($user) { \OC_Util::setupFS($user); } - - /** - * reset init status for the share storage - */ - protected static function resetStorage() { - $storage = new \ReflectionClass('\OCA\Files_Sharing\SharedStorage'); - $isInitialized = $storage->getProperty('initialized'); - $isInitialized->setAccessible(true); - $isInitialized->setValue($storage, false); - $isInitialized->setAccessible(false); - } } diff --git a/apps/files/lib/Command/TransferOwnership.php b/apps/files/lib/Command/TransferOwnership.php index a9ff6c54a9ad..ec7e26c459a9 100644 --- a/apps/files/lib/Command/TransferOwnership.php +++ b/apps/files/lib/Command/TransferOwnership.php @@ -153,7 +153,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->sourceUser = $sourceUserObject->getUID(); $this->destinationUser = $destinationUserObject->getUID(); - $this->inputPath = $input->getOption('path'); + $this->inputPath = $input->getOption('path') ?? ''; $this->inputPath = \ltrim($this->inputPath, '/'); // target user has to be ready diff --git a/apps/files/tests/Command/ScanTest.php b/apps/files/tests/Command/ScanTest.php index 228756300491..fcb9bd9c7ec5 100644 --- a/apps/files/tests/Command/ScanTest.php +++ b/apps/files/tests/Command/ScanTest.php @@ -91,7 +91,7 @@ class ScanTest extends TestCase { private $commandTester; /** - * @var string[] + * @var array */ private $groupsCreated = []; @@ -118,8 +118,8 @@ protected function setUp(): void { ); $this->commandTester = new CommandTester($command); - $this->scanUser1 = $this->createUser('scanuser1' . \uniqid()); - $this->scanUser2 = $this->createUser('scanuser2' . \uniqid()); + $this->scanUser1 = $this->createUser('scanuser1' . \uniqid('', true)); + $this->scanUser2 = $this->createUser('scanuser2' . \uniqid('', true)); $user1 = $this->createUser('user1'); $this->createUser('user2'); diff --git a/apps/files_external/appinfo/Migrations/Version20220329110116.php b/apps/files_external/appinfo/Migrations/Version20220329110116.php index 62ef9ad00166..d0f322c94941 100644 --- a/apps/files_external/appinfo/Migrations/Version20220329110116.php +++ b/apps/files_external/appinfo/Migrations/Version20220329110116.php @@ -12,6 +12,7 @@ use OCP\ILogger; use OCP\IConfig; use phpseclib3\Crypt\RSA as RSACrypt; +use phpseclib3\Crypt\RSA\PrivateKey; class Version20220329110116 implements ISimpleMigration { /** @var IGlobalStoragesService */ diff --git a/apps/files_sharing/lib/Controller/Share20OcsController.php b/apps/files_sharing/lib/Controller/Share20OcsController.php index 0a2d706cb78b..6362dfa580cd 100644 --- a/apps/files_sharing/lib/Controller/Share20OcsController.php +++ b/apps/files_sharing/lib/Controller/Share20OcsController.php @@ -1173,10 +1173,10 @@ protected function canAccessShare(IShare $share) { * * @param string $expireDate * - * @throws Exception * @return \DateTime + *@throws Exception */ - private function parseDate($expireDate) { + private function parseDate(string $expireDate) { try { $date = new \DateTime($expireDate); } catch (Exception $e) { diff --git a/apps/files_sharing/lib/Controller/ShareesController.php b/apps/files_sharing/lib/Controller/ShareesController.php index ecf6b9bfa22e..7287e83d5120 100644 --- a/apps/files_sharing/lib/Controller/ShareesController.php +++ b/apps/files_sharing/lib/Controller/ShareesController.php @@ -226,7 +226,7 @@ protected function getUsers($search) { // Check if exact display name || \strtolower($user->getDisplayName()) === $lowerSearch // Check if exact first email - || \strtolower($user->getEMailAddress()) === $lowerSearch + || \strtolower($user->getEMailAddress() ?? '') === $lowerSearch // Check for exact search term matches (when mail attributes configured as search terms + no enumeration) || \in_array($lowerSearch, \array_map('strtolower', $user->getSearchTerms())) ) diff --git a/apps/files_sharing/tests/ApiTest.php b/apps/files_sharing/tests/ApiTest.php index 79151b05c3e6..1cefaa79dbf9 100644 --- a/apps/files_sharing/tests/ApiTest.php +++ b/apps/files_sharing/tests/ApiTest.php @@ -1,4 +1,5 @@ * @author Joas Schilling diff --git a/apps/files_sharing/tests/Controller/Share20OcsControllerTest.php b/apps/files_sharing/tests/Controller/Share20OcsControllerTest.php index 9a671357c788..9f583ecc2e23 100644 --- a/apps/files_sharing/tests/Controller/Share20OcsControllerTest.php +++ b/apps/files_sharing/tests/Controller/Share20OcsControllerTest.php @@ -44,7 +44,6 @@ use OCP\IUserSession; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; -use OCP\Share; use OCP\User\Constants; use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\EventDispatcher\EventDispatcher; @@ -56,6 +55,10 @@ use OCP\Share\IShare; use OCP\Share\IAttributes as IShareAttributes; use OCP\Share\IManager; +use OCP\Files\File; +use OC\Files\Cache\Cache; +use OC\Files\Storage\Storage; +use OCP\Files\Cache\ICache; /** * Class Share20OcsControllerTest @@ -114,11 +117,9 @@ protected function setUp(): void { ->disableOriginalConstructor() ->getMock(); $this->shareManager - ->expects($this->any()) ->method('shareApiEnabled') ->willReturn(true); $this->shareManager - ->expects($this->any()) ->method('newShare') ->willReturn($this->newShare()); $this->shareManager @@ -148,18 +149,18 @@ protected function setUp(): void { $this->sharee = $this->createMock(IUser::class); $this->sharee->method('getUID')->willReturn('validUser'); - $this->l = $this->createMock('\OCP\IL10N'); + $this->l = $this->createMock(IL10N::class); $this->l->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { + ->willReturnCallback(function ($text, $parameters = []) { return \vsprintf($text, $parameters); - })); + }); $this->config = $this->createMock(IConfig::class); $this->config->method('getAppValue') - ->will($this->returnValueMap([ + ->willReturnMap([ ['core', 'shareapi_default_permissions', \OCP\Constants::PERMISSION_ALL, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE], ['core', 'shareapi_auto_accept_share', 'yes', 'yes'], - ])); + ]); $this->notificationPublisher = $this->createMock(NotificationPublisher::class); $this->eventDispatcher = $this->createMock(EventDispatcher::class); @@ -167,7 +168,6 @@ protected function setUp(): void { $this->sharingAllowlist= $this->createMock(SharingAllowlist::class); $this->userTypeHelper = $this->createMock(UserTypeHelper::class); $this->userTypeHelper - ->expects($this->any()) ->method('getUserType') ->willReturn(Constants::USER_TYPE_USER); @@ -215,7 +215,7 @@ private function mockFormatShare() { ->getMock(); } - private function newShare() { + private function newShare(): IShare { return \OC::$server->getShareManager()->newShare(); } @@ -234,7 +234,7 @@ private function getGroupMock(array $attrs) { return $groupMock; } - private function mockShareAttributes() { + private function mockShareAttributes(): array { $formattedShareAttributes = [ [ [ @@ -253,17 +253,17 @@ private function mockShareAttributes() { return [$shareAttributes, \json_encode($formattedShareAttributes)]; } - public function testDeleteShareShareNotFound() { + public function testDeleteShareShareNotFound(): void { $this->shareManager ->expects($this->exactly(2)) ->method('getShareById') - ->will($this->returnCallback(function ($id) { + ->willReturnCallback(function ($id) { if ($id === 'ocinternal:42' || $id === 'ocFederatedSharing:42') { - throw new \OCP\Share\Exceptions\ShareNotFound(); - } else { - throw new \Exception(); + throw new ShareNotFound(); } - })); + + throw new \Exception(); + }); $this->shareManager->method('outgoingServer2ServerSharesAllowed')->willReturn(true); @@ -271,8 +271,8 @@ public function testDeleteShareShareNotFound() { $this->assertEquals($expected, $this->ocs->deleteShare(42)); } - public function testDeleteShare() { - $node = $this->createMock('\OCP\Files\File'); + public function testDeleteShare(): void { + $node = $this->createMock(File::class); $share = $this->newShare(); $share->setSharedBy($this->currentUser->getUID()) @@ -298,8 +298,8 @@ public function testDeleteShare() { $this->assertEquals($expected, $this->ocs->deleteShare(42)); } - public function testDeleteShareLocked() { - $node = $this->createMock('\OCP\Files\File'); + public function testDeleteShareLocked(): void { + $node = $this->createMock(File::class); $share = $this->newShare(); $share->setSharedBy($this->currentUser->getUID()) @@ -379,52 +379,52 @@ public function createShare( $share->method('getPassword')->willReturn($password); $share->method('getName')->willReturn($name); - if ($shareType === Share::SHARE_TYPE_USER || - $shareType === Share::SHARE_TYPE_GROUP || - $shareType === Share::SHARE_TYPE_LINK) { + if ($shareType === \OC\Share\Constants::SHARE_TYPE_USER || + $shareType === \OC\Share\Constants::SHARE_TYPE_GROUP || + $shareType === \OC\Share\Constants::SHARE_TYPE_LINK) { $share->method('getFullId')->willReturn('ocinternal:'.$id); } return $share; } - public function dataGetShare() { + public function dataGetShare(): array { $data = []; - $cache = $this->getMockBuilder('OC\Files\Cache\Cache') + $cache = $this->getMockBuilder(Cache::class) ->disableOriginalConstructor() ->getMock(); $cache->method('getNumericStorageId')->willReturn(101); - $storage = $this->getMockBuilder('OC\Files\Storage\Storage') + $storage = $this->getMockBuilder(Storage::class) ->disableOriginalConstructor() ->getMock(); $storage->method('getId')->willReturn('STORAGE'); $storage->method('getCache')->willReturn($cache); - $parentFolder = $this->createMock('OCP\Files\Folder'); + $parentFolder = $this->createMock(Folder::class); $parentFolder->method('getId')->willReturn(3); - $file = $this->createMock('OCP\Files\File'); + $file = $this->createMock(File::class); $file->method('getId')->willReturn(1); $file->method('getPath')->willReturn('file'); $file->method('getStorage')->willReturn($storage); $file->method('getParent')->willReturn($parentFolder); $file->method('getMimeType')->willReturn('myMimeType'); - $folder = $this->createMock('OCP\Files\Folder'); + $folder = $this->createMock(Folder::class); $folder->method('getId')->willReturn(2); $folder->method('getPath')->willReturn('folder'); $folder->method('getStorage')->willReturn($storage); $folder->method('getParent')->willReturn($parentFolder); $folder->method('getMimeType')->willReturn('myFolderMimeType'); - list($shareAttributes, $shareAttributesReturnJson) = $this->mockShareAttributes(); + [$shareAttributes, $shareAttributesReturnJson] = $this->mockShareAttributes(); // File shared with user $share = $this->createShare( 100, - Share::SHARE_TYPE_USER, + \OC\Share\Constants::SHARE_TYPE_USER, 'userId', 'initiatorId', 'ownerId', @@ -442,7 +442,7 @@ public function dataGetShare() { ); $expected = [ 'id' => 100, - 'share_type' => Share::SHARE_TYPE_USER, + 'share_type' => \OC\Share\Constants::SHARE_TYPE_USER, 'share_with' => 'userId', 'share_with_displayname' => 'userDisplay', 'share_with_user_type' => Constants::USER_TYPE_USER, @@ -475,7 +475,7 @@ public function dataGetShare() { // Folder shared with group $share = $this->createShare( 101, - Share::SHARE_TYPE_GROUP, + \OC\Share\Constants::SHARE_TYPE_GROUP, 'groupId', 'initiatorId', 'ownerId', @@ -493,7 +493,7 @@ public function dataGetShare() { ); $expected = [ 'id' => 101, - 'share_type' => Share::SHARE_TYPE_GROUP, + 'share_type' => \OC\Share\Constants::SHARE_TYPE_GROUP, 'share_with' => 'groupId', 'share_with_displayname' => 'groupId', 'uid_owner' => 'initiatorId', @@ -525,7 +525,7 @@ public function dataGetShare() { $expire = \DateTime::createFromFormat('Y-m-d h:i:s', '2000-01-02 01:02:03'); $share = $this->createShare( 101, - Share::SHARE_TYPE_LINK, + \OC\Share\Constants::SHARE_TYPE_LINK, null, 'initiatorId', 'ownerId', @@ -542,7 +542,7 @@ public function dataGetShare() { ); $expected = [ 'id' => 101, - 'share_type' => Share::SHARE_TYPE_LINK, + 'share_type' => \OC\Share\Constants::SHARE_TYPE_LINK, 'share_with' => '***redacted***', 'share_with_displayname' => '***redacted***', 'uid_owner' => 'initiatorId', @@ -578,7 +578,7 @@ public function dataGetShare() { /** * @dataProvider dataGetShare */ - public function testGetShare(\OCP\Share\IShare $share, array $result) { + public function testGetShare(IShare $share, array $result): void { $ocs = $this->getMockBuilder(Share20OcsController::class) ->setConstructorArgs([ 'files_sharing', @@ -599,7 +599,10 @@ public function testGetShare(\OCP\Share\IShare $share, array $result) { ])->setMethods(['canAccessShare']) ->getMock(); - $ocs->expects($this->any())->method('canAccessShare')->willReturn(true); + $ocs + ->expects($this->once()) + ->method('canAccessShare') + ->willReturn(true); $this->shareManager ->expects($this->once()) @@ -607,7 +610,7 @@ public function testGetShare(\OCP\Share\IShare $share, array $result) { ->with($share->getFullId()) ->willReturn($share); - $userFolder = $this->createMock('OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); $userFolder ->method('getRelativePath') ->will($this->returnArgument(0)); @@ -624,35 +627,35 @@ public function testGetShare(\OCP\Share\IShare $share, array $result) { ->method('linkToRouteAbsolute') ->willReturn('url'); - $initiator = $this->createMock('OCP\IUser'); + $initiator = $this->createMock(IUser::class); $initiator->method('getUID')->willReturn('initiatorId'); $initiator->method('getDisplayName')->willReturn('initiatorDisplay'); - $owner = $this->createMock('OCP\IUser'); + $owner = $this->createMock(IUser::class); $owner->method('getUID')->willReturn('ownerId'); $owner->method('getDisplayName')->willReturn('ownerDisplay'); - $user = $this->createMock('OCP\IUser'); + $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('userId'); $user->method('getDisplayName')->willReturn('userDisplay'); - $group = $this->createMock('OCP\IGroup'); + $group = $this->createMock(IGroup::class); $group->method('getGID')->willReturn('groupId'); - $this->userManager->method('get')->will($this->returnValueMap([ + $this->userManager->method('get')->willReturnMap([ ['userId', false, $user], ['initiatorId', false, $initiator], ['ownerId', false, $owner], - ])); - $this->groupManager->method('get')->will($this->returnValueMap([ + ]); + $this->groupManager->method('get')->willReturnMap([ ['group', $group], - ])); + ]); $expected = new Result([$result]); $this->assertEquals($expected->getData(), $ocs->getShare($share->getId())->getData()); } - public function testGetShareInvalidNode() { + public function testGetShareInvalidNode(): void { $share = \OC::$server->getShareManager()->newShare(); $share->setSharedBy('initiator') ->setSharedWith('recipient') @@ -668,73 +671,73 @@ public function testGetShareInvalidNode() { $this->assertEquals($expected->getMeta(), $this->ocs->getShare(42)->getMeta()); } - public function testCanAccessShare() { - $share = $this->createMock('OCP\Share\IShare'); + public function testCanAccessShare(): void { + $share = $this->createMock(IShare::class); $share->method('getShareOwner')->willReturn($this->currentUser->getUID()); $this->assertTrue(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(IShare::class); $share->method('getSharedBy')->willReturn($this->currentUser->getUID()); $this->assertTrue(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); - $share = $this->createMock('OCP\Share\IShare'); - $share->method('getShareType')->willReturn(Share::SHARE_TYPE_USER); + $share = $this->createMock(IShare::class); + $share->method('getShareType')->willReturn(\OC\Share\Constants::SHARE_TYPE_USER); $share->method('getSharedWith')->willReturn($this->currentUser->getUID()); $this->assertTrue(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); - $share = $this->createMock('OCP\Share\IShare'); - $share->method('getShareType')->willReturn(Share::SHARE_TYPE_USER); - $share->method('getSharedWith')->willReturn($this->createMock('OCP\IUser')); + $share = $this->createMock(IShare::class); + $share->method('getShareType')->willReturn(\OC\Share\Constants::SHARE_TYPE_USER); + $share->method('getSharedWith')->willReturn($this->createMock(IUser::class)); $this->assertFalse(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); - $share = $this->createMock('OCP\Share\IShare'); - $share->method('getShareType')->willReturn(Share::SHARE_TYPE_GROUP); + $share = $this->createMock(IShare::class); + $share->method('getShareType')->willReturn(\OC\Share\Constants::SHARE_TYPE_GROUP); $share->method('getSharedWith')->willReturn('group'); - $group = $this->createMock('OCP\IGroup'); + $group = $this->createMock(IGroup::class); $group->method('inGroup')->with($this->currentUser)->willReturn(true); - $group2 = $this->createMock('OCP\IGroup'); + $group2 = $this->createMock(IGroup::class); $group2->method('inGroup')->with($this->currentUser)->willReturn(false); - $this->groupManager->method('get')->will($this->returnValueMap([ + $this->groupManager->method('get')->willReturnMap([ ['group', $group], ['group2', $group2], ['groupnull', null], - ])); + ]); $this->assertTrue(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); - $share = $this->createMock('OCP\Share\IShare'); - $share->method('getShareType')->willReturn(Share::SHARE_TYPE_GROUP); + $share = $this->createMock(IShare::class); + $share->method('getShareType')->willReturn(\OC\Share\Constants::SHARE_TYPE_GROUP); $share->method('getSharedWith')->willReturn('group2'); $this->assertFalse(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); // null group - $share = $this->createMock('OCP\Share\IShare'); - $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_GROUP); + $share = $this->createMock(IShare::class); + $share->method('getShareType')->willReturn(\OC\Share\Constants::SHARE_TYPE_GROUP); $share->method('getSharedWith')->willReturn('groupnull'); $this->assertFalse(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); - $share = $this->createMock('OCP\Share\IShare'); - $share->method('getShareType')->willReturn(Share::SHARE_TYPE_LINK); + $share = $this->createMock(IShare::class); + $share->method('getShareType')->willReturn(\OC\Share\Constants::SHARE_TYPE_LINK); $this->assertFalse(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); // should not happen ever again, but who knows... let's cover it - $share = $this->createMock('OCP\Share\IShare'); - $share->method('getShareType')->willReturn(Share::SHARE_TYPE_USER); - $share->method('getState')->willReturn(Share::STATE_ACCEPTED); + $share = $this->createMock(IShare::class); + $share->method('getShareType')->willReturn(\OC\Share\Constants::SHARE_TYPE_USER); + $share->method('getState')->willReturn(\OC\Share\Constants::STATE_ACCEPTED); $share->method('getPermissions')->willReturn(0); $this->assertFalse(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); // legacy zero permission entries from group sub-shares, let it pass - $share = $this->createMock('OCP\Share\IShare'); - $share->method('getShareType')->willReturn(Share::SHARE_TYPE_GROUP); + $share = $this->createMock(IShare::class); + $share->method('getShareType')->willReturn(\OC\Share\Constants::SHARE_TYPE_GROUP); $share->method('getSharedWith')->willReturn('group'); - $share->method('getState')->willReturn(Share::STATE_REJECTED); + $share->method('getState')->willReturn(\OC\Share\Constants::STATE_REJECTED); $share->method('getPermissions')->willReturn(0); $this->assertTrue(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); } - public function testCreateShareNoPath() { + public function testCreateShareNoPath(): void { $expected = new Result(null, 404, 'Please specify a file or folder path'); $result = $this->ocs->createShare(); @@ -743,14 +746,14 @@ public function testCreateShareNoPath() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareInvalidPath() { + public function testCreateShareInvalidPath(): void { $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'invalid-path'], - ])); + ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') @@ -759,7 +762,7 @@ public function testCreateShareInvalidPath() { $userFolder->expects($this->once()) ->method('get') ->with('invalid-path') - ->will($this->throwException(new \OCP\Files\NotFoundException())); + ->will($this->throwException(new NotFoundException())); $expected = new Result(null, 404, 'Wrong path, file/folder doesn\'t exist'); @@ -769,28 +772,29 @@ public function testCreateShareInvalidPath() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareUserNoShareWith() { + public function testCreateShareUserNoShareWith(): void { $share = $this->newShare(); $this->shareManager->method('newShare')->willReturn($share); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], ['permissions', null, \OCP\Constants::PERMISSION_ALL], - ['shareType', $this->any(), Share::SHARE_TYPE_USER], - ])); + ['shareType', $this->any(), \OC\Share\Constants::SHARE_TYPE_USER], + ['expireDate', '', ''], + ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -812,7 +816,7 @@ public function testCreateShareUserNoShareWith() { $this->assertEquals($expected->getData(), $result->getData()); } - public function InvalidShareWithProvider() { + public function InvalidShareWithProvider(): array { return [ ['invaliduser'], [123456], @@ -824,29 +828,30 @@ public function InvalidShareWithProvider() { * @dataProvider InvalidShareWithProvider * @param mixed $shareWith */ - public function testCreateShareUserNoValidShareWith($shareWith) { + public function testCreateShareUserNoValidShareWith($shareWith): void { $share = $this->newShare(); $this->shareManager->method('newShare')->willReturn($share); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], ['permissions', null, \OCP\Constants::PERMISSION_ALL], - ['shareType', $this->any(), Share::SHARE_TYPE_USER], + ['shareType', $this->any(), \OC\Share\Constants::SHARE_TYPE_USER], ['shareWith', $this->any(), $shareWith], - ])); + ['expireDate', '', ''], + ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -866,7 +871,7 @@ public function testCreateShareUserNoValidShareWith($shareWith) { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareUser() { + public function testCreateShareUser(): void { $share = $this->newShare(); $this->shareManager->method('newShare')->willReturn($share); @@ -879,20 +884,21 @@ public function testCreateShareUser() { ->willReturnMap([ ['path', null, 'valid-path'], ['permissions', null, \OCP\Constants::PERMISSION_ALL], - ['shareType', $this->any(), Share::SHARE_TYPE_USER], + ['shareType', $this->any(), \OC\Share\Constants::SHARE_TYPE_USER], ['shareWith', null, 'validUser'], + ['expireDate', '', ''], ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -910,12 +916,12 @@ public function testCreateShareUser() { ->with(ILockingProvider::LOCK_SHARED); $this->shareManager->method('createShare') - ->with($this->callback(function (\OCP\Share\IShare $share) use ($path) { + ->with($this->callback(function (IShare $share) use ($path) { return $share->getNode() === $path && $share->getPermissions() === ( \OCP\Constants::PERMISSION_ALL ) && - $share->getShareType() === Share::SHARE_TYPE_USER && + $share->getShareType() === \OC\Share\Constants::SHARE_TYPE_USER && $share->getSharedWith() === 'validUser' && $share->getSharedBy() === 'currentUser'; })) @@ -932,30 +938,31 @@ public function testCreateShareUser() { * @dataProvider InvalidShareWithProvider * @param mixed $shareWith */ - public function testCreateShareGroupNoValidShareWith($shareWith) { + public function testCreateShareGroupNoValidShareWith($shareWith): void { $share = $this->newShare(); $this->shareManager->method('newShare')->willReturn($share); $this->shareManager->method('createShare')->will($this->returnArgument(0)); $this->request ->method('getParam') - ->will($this->returnValueMap([ - ['path', null, 'valid-path'], - ['permissions', null, \OCP\Constants::PERMISSION_ALL], - ['shareType', '-1', Share::SHARE_TYPE_GROUP], - ['shareWith', null, $shareWith], - ])); - - $userFolder = $this->createMock('\OCP\Files\Folder'); + ->willReturnMap([ + ['path', null, 'valid-path'], + ['permissions', null, \OCP\Constants::PERMISSION_ALL], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_GROUP], + ['shareWith', null, $shareWith], + ['expireDate', '', ''], + ]); + + $userFolder = $this->createMock(Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -979,28 +986,29 @@ public function testCreateShareGroupNoValidShareWith($shareWith) { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareGroupBlacklisted() { + public function testCreateShareGroupBlacklisted(): void { $share = $this->newShare(); $this->shareManager->method('newShare')->willReturn($share); $this->request->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], ['permissions', null, \OCP\Constants::PERMISSION_ALL], - ['shareType', '-1', Share::SHARE_TYPE_GROUP], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_GROUP], ['shareWith', null, 'validGroup'], - ])); + ['expireDate', '', ''], + ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -1027,7 +1035,7 @@ public function testCreateShareGroupBlacklisted() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareGroup() { + public function testCreateShareGroup(): void { $share = $this->newShare(); $this->shareManager->method('newShare')->willReturn($share); @@ -1035,23 +1043,24 @@ public function testCreateShareGroup() { $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], ['permissions', null, \OCP\Constants::PERMISSION_ALL], - ['shareType', '-1', Share::SHARE_TYPE_GROUP], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_GROUP], ['shareWith', null, 'validGroup'], - ])); + ['expireDate', '', ''], + ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -1076,10 +1085,10 @@ public function testCreateShareGroup() { ->with(ILockingProvider::LOCK_SHARED); $this->shareManager->method('createShare') - ->with($this->callback(function (\OCP\Share\IShare $share) use ($path) { + ->with($this->callback(function (IShare $share) use ($path) { return $share->getNode() === $path && $share->getPermissions() === \OCP\Constants::PERMISSION_ALL && - $share->getShareType() === Share::SHARE_TYPE_GROUP && + $share->getShareType() === \OC\Share\Constants::SHARE_TYPE_GROUP && $share->getSharedWith() === 'validGroup' && $share->getSharedBy() === 'currentUser'; })) @@ -1094,29 +1103,30 @@ public function testCreateShareGroup() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareGroupNotAllowed() { + public function testCreateShareGroupNotAllowed(): void { $share = $this->newShare(); $this->shareManager->method('newShare')->willReturn($share); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], ['permissions', null, \OCP\Constants::PERMISSION_ALL], - ['shareType', '-1', Share::SHARE_TYPE_GROUP], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_GROUP], ['shareWith', null, 'validGroup'], - ])); + ['expireDate', '', ''], + ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -1138,18 +1148,19 @@ public function testCreateShareGroupNotAllowed() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareLinkNoLinksAllowed() { + public function testCreateShareLinkNoLinksAllowed(): void { $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], - ['shareType', '-1', Share::SHARE_TYPE_LINK], - ])); + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_LINK], + ['expireDate', '', ''], + ]); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1164,19 +1175,20 @@ public function testCreateShareLinkNoLinksAllowed() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareLinkNoPublicUpload() { + public function testCreateShareLinkNoPublicUpload(): void { $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], - ['shareType', '-1', Share::SHARE_TYPE_LINK], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_LINK], ['publicUpload', null, 'true'], - ])); + ['expireDate', '', ''], + ]); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1192,19 +1204,20 @@ public function testCreateShareLinkNoPublicUpload() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareLinkNotInAllowlist() { + public function testCreateShareLinkNotInAllowlist(): void { $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], - ['shareType', '-1', Share::SHARE_TYPE_LINK], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_LINK], ['publicUpload', null, 'true'], - ])); + ['expireDate', '', ''], + ]); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1224,19 +1237,20 @@ public function testCreateShareLinkNotInAllowlist() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareLinkPublicUploadFile() { + public function testCreateShareLinkPublicUploadFile(): void { $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], - ['shareType', '-1', Share::SHARE_TYPE_LINK], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_LINK], ['publicUpload', null, 'true'], - ])); + ['expireDate', '', ''], + ]); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1253,23 +1267,23 @@ public function testCreateShareLinkPublicUploadFile() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareLinkPublicUploadFolder() { + public function testCreateShareLinkPublicUploadFolder(): void { $ocs = $this->mockFormatShare(); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], - ['shareType', '-1', Share::SHARE_TYPE_LINK], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_LINK], ['publicUpload', null, 'true'], ['expireDate', '', ''], ['password', '', ''], - ])); + ]); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1280,9 +1294,9 @@ public function testCreateShareLinkPublicUploadFolder() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('createShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($path) { + $this->callback(function (IShare $share) use ($path) { return $share->getNode() === $path && - $share->getShareType() === Share::SHARE_TYPE_LINK && + $share->getShareType() === \OC\Share\Constants::SHARE_TYPE_LINK && $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) && $share->getSharedBy() === 'currentUser' && $share->getPassword() === null && @@ -1297,23 +1311,23 @@ public function testCreateShareLinkPublicUploadFolder() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareLinkReadWritePermissions() { + public function testCreateShareLinkReadWritePermissions(): void { $ocs = $this->mockFormatShare(); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], - ['shareType', '-1', Share::SHARE_TYPE_LINK], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_LINK], ['permissions', null, '15'], ['expireDate', '', ''], ['password', '', ''], - ])); + ]); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1324,9 +1338,9 @@ public function testCreateShareLinkReadWritePermissions() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('createShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($path) { + $this->callback(function (IShare $share) use ($path) { return $share->getNode() === $path && - $share->getShareType() === Share::SHARE_TYPE_LINK && + $share->getShareType() === \OC\Share\Constants::SHARE_TYPE_LINK && $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) && $share->getSharedBy() === 'currentUser' && $share->getPassword() === null && @@ -1341,23 +1355,23 @@ public function testCreateShareLinkReadWritePermissions() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareLinkCreateOnlyFolder() { + public function testCreateShareLinkCreateOnlyFolder(): void { $ocs = $this->mockFormatShare(); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], - ['shareType', '-1', Share::SHARE_TYPE_LINK], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_LINK], ['permissions', null, '4'], ['expireDate', '', ''], ['password', '', ''], - ])); + ]); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1368,9 +1382,9 @@ public function testCreateShareLinkCreateOnlyFolder() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('createShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($path) { + $this->callback(function (IShare $share) use ($path) { return $share->getNode() === $path && - $share->getShareType() === Share::SHARE_TYPE_LINK && + $share->getShareType() === \OC\Share\Constants::SHARE_TYPE_LINK && $share->getPermissions() === (\OCP\Constants::PERMISSION_CREATE) && $share->getSharedBy() === 'currentUser' && $share->getPassword() === null && @@ -1385,23 +1399,23 @@ public function testCreateShareLinkCreateOnlyFolder() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareLinkCreateOnlyFolderPublicUploadDisabled() { + public function testCreateShareLinkCreateOnlyFolderPublicUploadDisabled(): void { $ocs = $this->mockFormatShare(); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], - ['shareType', '-1', Share::SHARE_TYPE_LINK], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_LINK], ['permissions', null, '4'], ['expireDate', '', ''], ['password', '', ''], - ])); + ]); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1418,22 +1432,22 @@ public function testCreateShareLinkCreateOnlyFolderPublicUploadDisabled() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareLinkDefaultPerms() { + public function testCreateShareLinkDefaultPerms(): void { $ocs = $this->mockFormatShare(); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], - ['shareType', '-1', Share::SHARE_TYPE_LINK], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_LINK], ['expireDate', '', ''], ['password', '', ''], - ])); + ]); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1444,9 +1458,9 @@ public function testCreateShareLinkDefaultPerms() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(false); $this->shareManager->expects($this->once())->method('createShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($path) { + $this->callback(function (IShare $share) use ($path) { return $share->getNode() === $path && - $share->getShareType() === Share::SHARE_TYPE_LINK && + $share->getShareType() === \OC\Share\Constants::SHARE_TYPE_LINK && $share->getPermissions() === (\OCP\Constants::PERMISSION_READ) && $share->getSharedBy() === 'currentUser' && $share->getPassword() === null && @@ -1461,23 +1475,23 @@ public function testCreateShareLinkDefaultPerms() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareLinkPassword() { + public function testCreateShareLinkPassword(): void { $ocs = $this->mockFormatShare(); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], - ['shareType', '-1', Share::SHARE_TYPE_LINK], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_LINK], ['publicUpload', null, 'false'], ['expireDate', '', ''], ['password', '', 'password'], - ])); + ]); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1488,9 +1502,9 @@ public function testCreateShareLinkPassword() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('createShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($path) { + $this->callback(function (IShare $share) use ($path) { return $share->getNode() === $path && - $share->getShareType() === Share::SHARE_TYPE_LINK && + $share->getShareType() === \OC\Share\Constants::SHARE_TYPE_LINK && $share->getPermissions() === \OCP\Constants::PERMISSION_READ && $share->getSharedBy() === 'currentUser' && $share->getPassword() === 'password' && @@ -1509,30 +1523,31 @@ public function testCreateShareLinkPassword() { * @dataProvider InvalidShareWithProvider * @param mixed $shareWith */ - public function testCreateShareRemoteNoValidShareWith($shareWith) { + public function testCreateShareRemoteNoValidShareWith($shareWith): void { $share = $this->newShare(); $this->shareManager->method('newShare')->willReturn($share); $this->shareManager->method('outgoingServer2ServerSharesAllowed')->willReturn(true); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], ['permissions', null, \OCP\Constants::PERMISSION_ALL], - ['shareType', '-1', Share::SHARE_TYPE_REMOTE], - ['shareWith', $this->any(), $shareWith] - ])); + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_REMOTE], + ['shareWith', $this->any(), $shareWith], + ['expireDate', '', ''], + ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -1551,23 +1566,23 @@ public function testCreateShareRemoteNoValidShareWith($shareWith) { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareValidExpireDate() { + public function testCreateShareValidExpireDate(): void { $ocs = $this->mockFormatShare(); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], - ['shareType', '-1', Share::SHARE_TYPE_LINK], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_LINK], ['publicUpload', null, 'false'], ['expireDate', '', '2000-01-01'], ['password', '', ''], - ])); + ]); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1578,12 +1593,12 @@ public function testCreateShareValidExpireDate() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('createShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($path) { + $this->callback(function (IShare $share) use ($path) { $date = new \DateTime('2000-01-01'); $date->setTime(0, 0, 0); return $share->getNode() === $path && - $share->getShareType() === Share::SHARE_TYPE_LINK && + $share->getShareType() === \OC\Share\Constants::SHARE_TYPE_LINK && $share->getPermissions() === \OCP\Constants::PERMISSION_READ && $share->getSharedBy() === 'currentUser' && $share->getPassword() === null && @@ -1598,23 +1613,23 @@ public function testCreateShareValidExpireDate() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testCreateShareInvalidExpireDate() { + public function testCreateShareInvalidExpireDate(): void { $ocs = $this->mockFormatShare(); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], - ['shareType', '-1', Share::SHARE_TYPE_LINK], + ['shareType', '-1', \OC\Share\Constants::SHARE_TYPE_LINK], ['publicUpload', null, 'false'], ['expireDate', '', 'a1b2d3'], ['password', '', ''], - ])); + ]); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1635,7 +1650,7 @@ public function testCreateShareInvalidExpireDate() { * Test for https://github.com/owncloud/core/issues/22587 * TODO: Remove once proper solution is in place */ - public function testCreateReshareOfFederatedMountNoDeletePermissions() { + public function testCreateReshareOfFederatedMountNoDeletePermissions(): void { $share = \OC::$server->getShareManager()->newShare(); $this->shareManager->method('newShare')->willReturn($share); @@ -1643,23 +1658,24 @@ public function testCreateReshareOfFederatedMountNoDeletePermissions() { $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, 'valid-path'], ['permissions', null, \OCP\Constants::PERMISSION_ALL], - ['shareType', $this->any(), Share::SHARE_TYPE_USER], + ['shareType', $this->any(), \OC\Share\Constants::SHARE_TYPE_USER], ['shareWith', null, 'validUser'], - ])); + ['expireDate', '', ''], + ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(true); $path->method('getStorage')->willReturn($storage); $path->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_READ); @@ -1673,7 +1689,7 @@ public function testCreateReshareOfFederatedMountNoDeletePermissions() { $this->shareManager ->expects($this->once()) ->method('createShare') - ->with($this->callback(function (\OCP\Share\IShare $share) { + ->with($this->callback(function (IShare $share) { return $share->getPermissions() === \OCP\Constants::PERMISSION_READ; })) ->will($this->returnArgument(0)); @@ -1681,8 +1697,8 @@ public function testCreateReshareOfFederatedMountNoDeletePermissions() { $ocs->createShare(); } - public function testUpdateShareCantChange() { - $node = $this->createMock('\OCP\Files\Folder'); + public function testUpdateShareCantChange(): void { + $node = $this->createMock(Folder::class); $share = $this->newShare(); $share->setNode($node); @@ -1699,12 +1715,12 @@ public function testUpdateShareCantChange() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateNoParametersLink() { - $node = $this->createMock('\OCP\Files\Folder'); + public function testUpdateNoParametersLink(): void { + $node = $this->createMock(Folder::class); $share = $this->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setNode($node); $node->expects($this->once()) @@ -1720,20 +1736,20 @@ public function testUpdateNoParametersLink() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateNoParametersOther() { + public function testUpdateNoParametersOther(): void { $ocs = $this->mockFormatShare(); - $node = $this->createMock('\OCP\Files\Folder'); + $node = $this->createMock(Folder::class); $share = $this->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_GROUP) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_GROUP) ->setNode($node); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) { + $this->callback(function (IShare $share) { return $share->getPermissions() === \OCP\Constants::PERMISSION_ALL && $share->getPassword() === null && $share->getExpirationDate() === null; @@ -1748,7 +1764,7 @@ public function testUpdateNoParametersOther() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateLinkShareClear() { + public function testUpdateLinkShareClear(): void { $userFolder = $this->createMock(Folder::class); $userFolder->method('getById')->willReturn([]); $this->rootFolder @@ -1757,12 +1773,12 @@ public function testUpdateLinkShareClear() { $ocs = $this->mockFormatShare(); - $node = $this->createMock('\OCP\Files\Folder'); + $node = $this->createMock(Folder::class); $share = $this->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) ->setShareOwner($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setPassword('password') ->setExpirationDate(new \DateTime()) ->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -1777,16 +1793,16 @@ public function testUpdateLinkShareClear() { $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['publicUpload', null, 'false'], ['expireDate', null, ''], ['password', null, ''], - ])); + ]); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) { + $this->callback(function (IShare $share) { return $share->getPermissions() === \OCP\Constants::PERMISSION_READ && $share->getPassword() === null && $share->getExpirationDate() === null; @@ -1800,7 +1816,7 @@ public function testUpdateLinkShareClear() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateLinkShareSet() { + public function testUpdateLinkShareSet(): void { $userFolder = $this->createMock(Folder::class); $userFolder->method('getById')->willReturn([]); $this->rootFolder @@ -1809,28 +1825,28 @@ public function testUpdateLinkShareSet() { $ocs = $this->mockFormatShare(); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock(Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) ->setShareOwner($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setNode($folder); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['publicUpload', null, 'true'], ['expireDate', null, '2000-01-01'], ['password', null, 'password'], - ])); + ]); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) { + $this->callback(function (IShare $share) { $date = new \DateTime('2000-01-01'); $date->setTime(0, 0, 0); @@ -1850,7 +1866,7 @@ public function testUpdateLinkShareSet() { /** * @dataProvider publicUploadParamsProvider */ - public function testUpdateLinkShareEnablePublicUpload($params) { + public function testUpdateLinkShareEnablePublicUpload($params): void { $userFolder = $this->createMock(Folder::class); $userFolder->method('getById')->willReturn([]); $this->rootFolder @@ -1859,35 +1875,35 @@ public function testUpdateLinkShareEnablePublicUpload($params) { $ocs = $this->mockFormatShare(); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock(Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) ->setShareOwner($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setPassword('password') ->setNode($folder); $this->request ->method('getParam') - ->will($this->returnValueMap($params)); + ->willReturnMap($params); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->method('getSharedWith')->willReturn([]); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) { + $this->callback(function (IShare $share) { if ($share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE)) { return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) && $share->getPassword() === 'password' && $share->getExpirationDate() === null; - } else { - return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) && - $share->getPassword() === 'password' && - $share->getExpirationDate() === null; } + + return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) && + $share->getPassword() === 'password' && + $share->getExpirationDate() === null; }) )->will($this->returnArgument(0)); @@ -1898,7 +1914,7 @@ public function testUpdateLinkShareEnablePublicUpload($params) { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateLinkShareInvalidDate() { + public function testUpdateLinkShareInvalidDate(): void { $userFolder = $this->createMock(Folder::class); $userFolder->method('getById')->willReturn([]); $this->rootFolder @@ -1907,21 +1923,21 @@ public function testUpdateLinkShareInvalidDate() { $ocs = $this->mockFormatShare(); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock(Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setNode($folder); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['publicUpload', null, 'true'], ['expireDate', null, '2000-01-a'], ['password', null, 'password'], - ])); + ]); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); @@ -1933,7 +1949,7 @@ public function testUpdateLinkShareInvalidDate() { $this->assertEquals($expected->getData(), $result->getData()); } - public function publicUploadParamsProvider() { + public function publicUploadParamsProvider(): array { return [ [[ ['publicUpload', null, 'true'], @@ -1956,20 +1972,20 @@ public function publicUploadParamsProvider() { /** * @dataProvider publicUploadParamsProvider */ - public function testUpdateLinkSharePublicUploadNotAllowed($params) { + public function testUpdateLinkSharePublicUploadNotAllowed($params): void { $ocs = $this->mockFormatShare(); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock(Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setNode($folder); $this->request ->method('getParam') - ->will($this->returnValueMap($params)); + ->willReturnMap($params); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(false); @@ -1981,24 +1997,24 @@ public function testUpdateLinkSharePublicUploadNotAllowed($params) { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateLinkSharePublicUploadOnFile() { + public function testUpdateLinkSharePublicUploadOnFile(): void { $ocs = $this->mockFormatShare(); - $file = $this->createMock('\OCP\Files\File'); + $file = $this->createMock(File::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setNode($file); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['publicUpload', null, 'true'], ['expireDate', '', ''], ['password', '', 'password'], - ])); + ]); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); @@ -2010,17 +2026,17 @@ public function testUpdateLinkSharePublicUploadOnFile() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateLinkSharePasswordDoesNotChangeOther() { + public function testUpdateLinkSharePasswordDoesNotChangeOther(): void { $ocs = $this->mockFormatShare(); $date = new \DateTime('2000-01-01'); $date->setTime(0, 0, 0); - $node = $this->createMock('\OCP\Files\File'); + $node = $this->createMock(File::class); $share = $this->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setPassword('password') ->setExpirationDate($date) ->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -2035,14 +2051,14 @@ public function testUpdateLinkSharePasswordDoesNotChangeOther() { $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['password', null, 'newpassword'], - ])); + ]); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($date) { + $this->callback(function (IShare $share) use ($date) { return $share->getPermissions() === \OCP\Constants::PERMISSION_ALL && $share->getPassword() === 'newpassword' && $share->getExpirationDate() === $date; @@ -2056,14 +2072,14 @@ public function testUpdateLinkSharePasswordDoesNotChangeOther() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateLinkShareExpireDateDoesNotChangeOther() { + public function testUpdateLinkShareExpireDateDoesNotChangeOther(): void { $ocs = $this->mockFormatShare(); - $node = $this->createMock('\OCP\Files\File'); + $node = $this->createMock(File::class); $share = $this->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setPassword('password') ->setExpirationDate(new \DateTime()) ->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -2071,9 +2087,9 @@ public function testUpdateLinkShareExpireDateDoesNotChangeOther() { $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['expireDate', null, '2010-12-23'], - ])); + ]); $node->expects($this->once()) ->method('lock') @@ -2085,7 +2101,7 @@ public function testUpdateLinkShareExpireDateDoesNotChangeOther() { $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) { + $this->callback(function (IShare $share) { $date = new \DateTime('2010-12-23'); $date->setTime(0, 0, 0); @@ -2102,7 +2118,7 @@ public function testUpdateLinkShareExpireDateDoesNotChangeOther() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateLinkSharePublicUploadDoesNotChangeOther() { + public function testUpdateLinkSharePublicUploadDoesNotChangeOther(): void { $userFolder = $this->createMock(Folder::class); $userFolder->method('getById')->willReturn([]); $this->rootFolder @@ -2113,13 +2129,13 @@ public function testUpdateLinkSharePublicUploadDoesNotChangeOther() { $date = new \DateTime('2000-01-01'); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock(Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) ->setShareOwner($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setPassword('password') ->setExpirationDate($date) ->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -2127,15 +2143,15 @@ public function testUpdateLinkSharePublicUploadDoesNotChangeOther() { $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['publicUpload', null, 'true'], - ])); + ]); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($date) { + $this->callback(function (IShare $share) use ($date) { return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) && $share->getPassword() === 'password' && $share->getExpirationDate() === $date; @@ -2149,7 +2165,7 @@ public function testUpdateLinkSharePublicUploadDoesNotChangeOther() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateLinkSharePermissions() { + public function testUpdateLinkSharePermissions(): void { $userFolder = $this->createMock(Folder::class); $userFolder->method('getById')->willReturn([]); $this->rootFolder @@ -2160,12 +2176,12 @@ public function testUpdateLinkSharePermissions() { $date = new \DateTime('2000-01-01'); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock(Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setPassword('password') ->setExpirationDate($date) ->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -2173,15 +2189,15 @@ public function testUpdateLinkSharePermissions() { $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['permissions', null, '7'], - ])); + ]); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($date) { + $this->callback(function (IShare $share) use ($date) { return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) && $share->getPassword() === 'password' && $share->getExpirationDate() === $date; @@ -2197,7 +2213,7 @@ public function testUpdateLinkSharePermissions() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateLinkShareCreateOnly() { + public function testUpdateLinkShareCreateOnly(): void { $userFolder = $this->createMock(Folder::class); $userFolder->method('getById')->willReturn([]); $this->rootFolder @@ -2206,26 +2222,26 @@ public function testUpdateLinkShareCreateOnly() { $ocs = $this->mockFormatShare(); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock(Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setPermissions(\OCP\Constants::PERMISSION_READ) ->setNode($folder); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['permissions', null, '4'], - ])); + ]); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) { + $this->callback(function (IShare $share) { return $share->getPermissions() === \OCP\Constants::PERMISSION_CREATE; }) )->will($this->returnArgument(0)); @@ -2239,17 +2255,17 @@ public function testUpdateLinkShareCreateOnly() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateLinkShareInvalidPermissions() { + public function testUpdateLinkShareInvalidPermissions(): void { $ocs = $this->mockFormatShare(); $date = new \DateTime('2000-01-01'); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock(Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setPassword('password') ->setExpirationDate($date) ->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -2257,9 +2273,9 @@ public function testUpdateLinkShareInvalidPermissions() { $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['permissions', null, '31'], - ])); + ]); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); @@ -2271,28 +2287,28 @@ public function testUpdateLinkShareInvalidPermissions() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateOtherPermissions() { + public function testUpdateOtherPermissions(): void { $ocs = $this->mockFormatShare(); - $file = $this->createMock('\OCP\Files\File'); + $file = $this->createMock(File::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_USER) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_USER) ->setNode($file); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['permissions', null, '31'], - ])); + ]); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) { + $this->callback(function (IShare $share) { return $share->getPermissions() === \OCP\Constants::PERMISSION_ALL; }) )->will($this->returnArgument(0)); @@ -2306,30 +2322,30 @@ public function testUpdateOtherPermissions() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateLinkShareNameAlone() { + public function testUpdateLinkShareNameAlone(): void { $ocs = $this->mockFormatShare(); $date = new \DateTime('2000-01-01'); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock(Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_READ) ->setSharedBy($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setName('somename') ->setNode($folder); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['name', null, 'another'], - ])); + ]); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($date) { + $this->callback(function (IShare $share) use ($date) { return $share->getName() === 'another'; }) )->will($this->returnArgument(0)); @@ -2343,30 +2359,30 @@ public function testUpdateLinkShareNameAlone() { $this->assertEquals($expected->getData(), $result->getData()); } - public function testUpdateLinkShareKeepNameWhenNotSpecified() { + public function testUpdateLinkShareKeepNameWhenNotSpecified(): void { $ocs = $this->mockFormatShare(); $date = new \DateTime('2000-01-01'); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock(Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_READ) ->setSharedBy($this->currentUser->getUID()) - ->setShareType(Share::SHARE_TYPE_LINK) + ->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setName('somename') ->setNode($folder); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['password', null, 'test'], - ])); + ]); $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($date) { + $this->callback(function (IShare $share) use ($date) { return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ) && $share->getPassword() === 'test' && $share->getName() === 'somename'; @@ -2382,10 +2398,10 @@ public function testUpdateLinkShareKeepNameWhenNotSpecified() { $this->assertEquals($expected->getData(), $result->getData()); } - private function getMockFileFolder() { - $file = $this->createMock('\OCP\Files\File'); - $folder = $this->createMock('\OCP\Files\Folder'); - $parent = $this->createMock('\OCP\Files\Folder'); + private function getMockFileFolder(): array { + $file = $this->createMock(File::class); + $folder = $this->createMock(Folder::class); + $parent = $this->createMock(Folder::class); $file->method('getMimeType')->willReturn('myMimeType'); $folder->method('getMimeType')->willReturn('myFolderMimeType'); @@ -2400,9 +2416,9 @@ private function getMockFileFolder() { $file->method('getParent')->willReturn($parent); $folder->method('getParent')->willReturn($parent); - $cache = $this->createMock('OCP\Files\Cache\ICache'); + $cache = $this->createMock(ICache::class); $cache->method('getNumericStorageId')->willReturn(100); - $storage = $this->createMock('\OCP\Files\Storage'); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('getId')->willReturn('storageId'); $storage->method('getCache')->willReturn($cache); @@ -2412,20 +2428,20 @@ private function getMockFileFolder() { return [$file, $folder]; } - public function dataFormatShare() { - list($file, $folder) = $this->getMockFileFolder(); - $owner = $this->createMock('\OCP\IUser'); + public function dataFormatShare(): array { + [$file, $folder] = $this->getMockFileFolder(); + $owner = $this->createMock(IUser::class); $owner->method('getDisplayName')->willReturn('ownerDN'); - $initiator = $this->createMock('\OCP\IUser'); + $initiator = $this->createMock(IUser::class); $initiator->method('getDisplayName')->willReturn('initiatorDN'); - $recipient = $this->createMock('\OCP\IUser'); + $recipient = $this->createMock(IUser::class); $recipient->method('getDisplayName')->willReturn('recipientDN'); - list($shareAttributes, $shareAttributesReturnJson) = $this->mockShareAttributes(); + [$shareAttributes, $shareAttributesReturnJson] = $this->mockShareAttributes(); $result = []; $share = \OC::$server->getShareManager()->newShare(); - $share->setShareType(Share::SHARE_TYPE_USER) + $share->setShareType(\OC\Share\Constants::SHARE_TYPE_USER) ->setSharedWith('recipient') ->setSharedBy('initiator') ->setShareOwner('owner') @@ -2440,7 +2456,7 @@ public function dataFormatShare() { $result[] = [ [ 'id' => 42, - 'share_type' => Share::SHARE_TYPE_USER, + 'share_type' => \OC\Share\Constants::SHARE_TYPE_USER, 'uid_owner' => 'initiator', 'displayname_owner' => 'initiator', 'share_with_user_type' => Constants::USER_TYPE_USER, @@ -2471,7 +2487,7 @@ public function dataFormatShare() { $result[] = [ [ 'id' => 42, - 'share_type' => Share::SHARE_TYPE_USER, + 'share_type' => \OC\Share\Constants::SHARE_TYPE_USER, 'uid_owner' => 'initiator', 'displayname_owner' => 'initiatorDN', 'share_with_user_type' => Constants::USER_TYPE_USER, @@ -2506,7 +2522,7 @@ public function dataFormatShare() { ]; $share = \OC::$server->getShareManager()->newShare(); - $share->setShareType(Share::SHARE_TYPE_USER) + $share->setShareType(\OC\Share\Constants::SHARE_TYPE_USER) ->setSharedWith('recipient') ->setSharedBy('initiator') ->setShareOwner('owner') @@ -2520,7 +2536,7 @@ public function dataFormatShare() { $result[] = [ [ 'id' => 42, - 'share_type' => Share::SHARE_TYPE_USER, + 'share_type' => \OC\Share\Constants::SHARE_TYPE_USER, 'share_with_user_type' => Constants::USER_TYPE_USER, 'uid_owner' => 'initiator', 'displayname_owner' => 'initiator', @@ -2549,7 +2565,7 @@ public function dataFormatShare() { // with existing group $share = \OC::$server->getShareManager()->newShare(); - $share->setShareType(Share::SHARE_TYPE_GROUP) + $share->setShareType(\OC\Share\Constants::SHARE_TYPE_GROUP) ->setSharedWith('recipientGroup') ->setSharedBy('initiator') ->setShareOwner('owner') @@ -2562,7 +2578,7 @@ public function dataFormatShare() { $result[] = [ [ 'id' => 42, - 'share_type' => Share::SHARE_TYPE_GROUP, + 'share_type' => \OC\Share\Constants::SHARE_TYPE_GROUP, 'uid_owner' => 'initiator', 'displayname_owner' => 'initiator', 'permissions' => 1, @@ -2590,7 +2606,7 @@ public function dataFormatShare() { // with unknown group / no group backend $share = \OC::$server->getShareManager()->newShare(); - $share->setShareType(Share::SHARE_TYPE_GROUP) + $share->setShareType(\OC\Share\Constants::SHARE_TYPE_GROUP) ->setSharedWith('recipientGroup2') ->setSharedBy('initiator') ->setShareOwner('owner') @@ -2602,7 +2618,7 @@ public function dataFormatShare() { $result[] = [ [ 'id' => 42, - 'share_type' => Share::SHARE_TYPE_GROUP, + 'share_type' => \OC\Share\Constants::SHARE_TYPE_GROUP, 'uid_owner' => 'initiator', 'displayname_owner' => 'initiator', 'permissions' => 1, @@ -2629,7 +2645,7 @@ public function dataFormatShare() { ]; $share = \OC::$server->getShareManager()->newShare(); - $share->setShareType(Share::SHARE_TYPE_LINK) + $share->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK) ->setSharedBy('initiator') ->setShareOwner('owner') ->setPermissions(\OCP\Constants::PERMISSION_READ) @@ -2645,7 +2661,7 @@ public function dataFormatShare() { $result[] = [ [ 'id' => 42, - 'share_type' => Share::SHARE_TYPE_LINK, + 'share_type' => \OC\Share\Constants::SHARE_TYPE_LINK, 'uid_owner' => 'initiator', 'displayname_owner' => 'initiator', 'permissions' => 1, @@ -2674,7 +2690,7 @@ public function dataFormatShare() { ]; $share = \OC::$server->getShareManager()->newShare(); - $share->setShareType(Share::SHARE_TYPE_REMOTE) + $share->setShareType(\OC\Share\Constants::SHARE_TYPE_REMOTE) ->setSharedBy('initiator') ->setSharedWith('user@server.com') ->setShareOwner('owner') @@ -2687,7 +2703,7 @@ public function dataFormatShare() { $result[] = [ [ 'id' => 42, - 'share_type' => Share::SHARE_TYPE_REMOTE, + 'share_type' => \OC\Share\Constants::SHARE_TYPE_REMOTE, 'uid_owner' => 'initiator', 'displayname_owner' => 'initiator', 'permissions' => 1, @@ -2714,7 +2730,7 @@ public function dataFormatShare() { ]; $share = \OC::$server->getShareManager()->newShare(); - $share->setShareType(Share::SHARE_TYPE_USER) + $share->setShareType(\OC\Share\Constants::SHARE_TYPE_USER) ->setSharedBy('initiator') ->setSharedWith('recipient') ->setShareOwner('owner') @@ -2734,18 +2750,18 @@ public function dataFormatShare() { * @dataProvider dataFormatShare * * @param array $expects - * @param \OCP\Share\IShare $share + * @param IShare $share * @param array $users * @param $exception */ - public function testFormatShare(array $expects, \OCP\Share\IShare $share, array $users, $exception) { - $this->userManager->method('get')->will($this->returnValueMap($users)); + public function testFormatShare(array $expects, IShare $share, array $users, $exception): void { + $this->userManager->method('get')->willReturnMap($users); - $recipientGroup = $this->createMock('\OCP\IGroup'); + $recipientGroup = $this->createMock(IGroup::class); $recipientGroup->method('getDisplayName')->willReturn('recipientGroupDisplayName'); - $this->groupManager->method('get')->will($this->returnValueMap([ - ['recipientGroup', $recipientGroup], - ])); + $this->groupManager->method('get')->willReturnMap([ + ['recipientGroup', $recipientGroup], + ]); $this->urlGenerator->method('linkToRouteAbsolute') ->with('files_sharing.sharecontroller.showShare', ['token' => 'myToken']) @@ -2777,12 +2793,11 @@ public function testFormatShare(array $expects, \OCP\Share\IShare $share, array /** * @return Share20OcsController */ - public function getOcsDisabledAPI() { - $shareManager = $this->getMockBuilder('OCP\Share\IManager') + public function getOcsDisabledAPI(): Share20OcsController { + $shareManager = $this->getMockBuilder(IManager::class) ->disableOriginalConstructor() ->getMock(); $shareManager - ->expects($this->any()) ->method('shareApiEnabled') ->willReturn(false); @@ -2805,7 +2820,7 @@ public function getOcsDisabledAPI() { ); } - public function testGetShareApiDisabled() { + public function testGetShareApiDisabled(): void { $ocs = $this->getOcsDisabledAPI(); $expected = new Result(null, 404, 'Share API is disabled'); @@ -2814,7 +2829,7 @@ public function testGetShareApiDisabled() { $this->assertEquals($expected, $result); } - public function testDeleteShareApiDisabled() { + public function testDeleteShareApiDisabled(): void { $ocs = $this->getOcsDisabledAPI(); $expected = new Result(null, 404, 'Share API is disabled'); @@ -2823,7 +2838,7 @@ public function testDeleteShareApiDisabled() { $this->assertEquals($expected, $result); } - public function testCreateShareApiDisabled() { + public function testCreateShareApiDisabled(): void { $ocs = $this->getOcsDisabledAPI(); $expected = new Result(null, 404, 'Share API is disabled'); @@ -2832,7 +2847,7 @@ public function testCreateShareApiDisabled() { $this->assertEquals($expected, $result); } - public function testGetSharesApiDisabled() { + public function testGetSharesApiDisabled(): void { $ocs = $this->getOcsDisabledAPI(); $expected = new Result(); @@ -2841,7 +2856,7 @@ public function testGetSharesApiDisabled() { $this->assertEquals($expected, $result); } - public function testUpdateShareApiDisabled() { + public function testUpdateShareApiDisabled(): void { $ocs = $this->getOcsDisabledAPI(); $expected = new Result(null, 404, 'Share API is disabled'); @@ -2850,7 +2865,7 @@ public function testUpdateShareApiDisabled() { $this->assertEquals($expected, $result); } - public function additionalInfoDataProvider() { + public function additionalInfoDataProvider(): array { return [ ['', null, null, null], ['unsupported', null, null, null], @@ -2862,13 +2877,13 @@ public function additionalInfoDataProvider() { /** * @dataProvider additionalInfoDataProvider */ - public function testGetShareAdditionalInfo($configValue, $expectedInfo, $expectedOwnerInfo, $expectedInitiatorInfo) { + public function testGetShareAdditionalInfo($configValue, $expectedInfo, $expectedOwnerInfo, $expectedInitiatorInfo): void { $config = $this->createMock(IConfig::class); $config->method('getAppValue') - ->will($this->returnValueMap([ + ->willReturnMap([ ['core', 'shareapi_default_permissions', \OCP\Constants::PERMISSION_ALL, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE], ['core', 'user_additional_info_field', '', $configValue], - ])); + ]); $initiator = $this->createMock(IUser::class); $initiator->method('getUID')->willReturn('initiator_id'); @@ -2882,11 +2897,11 @@ public function testGetShareAdditionalInfo($configValue, $expectedInfo, $expecte $recipient->method('getUID')->willReturn('recipient_id'); $recipient->method('getEMailAddress')->willReturn('email@example.com'); - $this->userManager->method('get')->will($this->returnValueMap([ + $this->userManager->method('get')->willReturnMap([ ['initiator', false, $initiator], ['recipient', false, $recipient], ['owner', false, $owner], - ])); + ]); $ocs = new Share20OcsController( 'files_sharing', @@ -2906,10 +2921,10 @@ public function testGetShareAdditionalInfo($configValue, $expectedInfo, $expecte $this->userTypeHelper ); - list($file, ) = $this->getMockFileFolder(); + [$file,] = $this->getMockFileFolder(); $share = \OC::$server->getShareManager()->newShare(); - $share->setShareType(Share::SHARE_TYPE_USER) + $share->setShareType(\OC\Share\Constants::SHARE_TYPE_USER) ->setSharedWith('recipient') ->setSharedBy('initiator') ->setShareOwner('owner') @@ -2938,7 +2953,7 @@ public function testGetShareAdditionalInfo($configValue, $expectedInfo, $expecte $this->assertEquals($expectedInitiatorInfo, $result['additional_info_owner']); } - public function providesGetSharesAll() { + public function providesGetSharesAll(): array { return [ [ null, @@ -2968,25 +2983,25 @@ public function providesGetSharesAll() { null, false, false, - [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_REMOTE], + [\OC\Share\Constants::SHARE_TYPE_USER, \OC\Share\Constants::SHARE_TYPE_REMOTE], ], [ '/requested/path', true, false, - [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_REMOTE], + [\OC\Share\Constants::SHARE_TYPE_USER, \OC\Share\Constants::SHARE_TYPE_REMOTE], ], [ '/requested/path', false, false, - [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_REMOTE], + [\OC\Share\Constants::SHARE_TYPE_USER, \OC\Share\Constants::SHARE_TYPE_REMOTE], ], [ '/requested/path', true, true, - [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_REMOTE], + [\OC\Share\Constants::SHARE_TYPE_USER, \OC\Share\Constants::SHARE_TYPE_REMOTE], ], ]; } @@ -2994,7 +3009,7 @@ public function providesGetSharesAll() { /** * @dataProvider providesGetSharesAll */ - public function testGetSharesAll($requestedPath, $requestedReshares, $fedAllowed, $shareTypes) { + public function testGetSharesAll($requestedPath, $requestedReshares, $fedAllowed, $shareTypes): void { $userShare = $this->newShare(); $groupShare = $this->newShare(); $linkShare = $this->newShare(); @@ -3022,62 +3037,62 @@ public function testGetSharesAll($requestedPath, $requestedReshares, $fedAllowed } $this->shareManager->method('getSharesBy') - ->will($this->returnValueMap([ - ['currentUser', \OCP\Share::SHARE_TYPE_USER, $node, $requestedReshares, -1, 0, [$userShare]], - ['currentUser', \OCP\Share::SHARE_TYPE_GROUP, $node, $requestedReshares, -1, 0, [$groupShare]], - ['currentUser', \OCP\Share::SHARE_TYPE_LINK, $node, $requestedReshares, -1, 0, [$linkShare]], - ['currentUser', \OCP\Share::SHARE_TYPE_REMOTE, $node, $requestedReshares, -1, 0, [$federatedShare]], - ])); + ->willReturnMap([ + ['currentUser', \OC\Share\Constants::SHARE_TYPE_USER, $node, $requestedReshares, -1, 0, [$userShare]], + ['currentUser', \OC\Share\Constants::SHARE_TYPE_GROUP, $node, $requestedReshares, -1, 0, [$groupShare]], + ['currentUser', \OC\Share\Constants::SHARE_TYPE_LINK, $node, $requestedReshares, -1, 0, [$linkShare]], + ['currentUser', \OC\Share\Constants::SHARE_TYPE_REMOTE, $node, $requestedReshares, -1, 0, [$federatedShare]], + ]); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, $requestedPath], ['reshares', null, $requestedReshares ? 'true' : 'false'], ['share_types', '', \implode(',', $shareTypes)], - ])); + ]); $this->shareManager->method('outgoingServer2ServerSharesAllowed')->willReturn($fedAllowed); $ocs = $this->mockFormatShare(); - $ocs->expects($this->any())->method('formatShare')->will($this->returnArgument(0)); + $ocs->expects(self::atLeast(1))->method('formatShare')->will($this->returnArgument(0)); $result = $ocs->getShares(); if (\count($shareTypes) === 0) { $shareTypes = [ - \OCP\Share::SHARE_TYPE_USER, - \OCP\Share::SHARE_TYPE_GROUP, - \OCP\Share::SHARE_TYPE_LINK, - \OCP\Share::SHARE_TYPE_REMOTE, + \OC\Share\Constants::SHARE_TYPE_USER, + \OC\Share\Constants::SHARE_TYPE_GROUP, + \OC\Share\Constants::SHARE_TYPE_LINK, + \OC\Share\Constants::SHARE_TYPE_REMOTE, ]; } foreach ($shareTypes as $shareType) { switch ($shareType) { - case \OCP\Share::SHARE_TYPE_USER: + case \OC\Share\Constants::SHARE_TYPE_USER: $this->assertContains($userShare, $result->getData(), 'result contains user share'); break; - case \OCP\Share::SHARE_TYPE_GROUP: + case \OC\Share\Constants::SHARE_TYPE_GROUP: $this->assertContains($groupShare, $result->getData(), 'result contains group share'); break; - case \OCP\Share::SHARE_TYPE_LINK: + case \OC\Share\Constants::SHARE_TYPE_LINK: $this->assertContains($linkShare, $result->getData(), 'result contains link share'); break; - case \OCP\Share::SHARE_TYPE_REMOTE: + case \OC\Share\Constants::SHARE_TYPE_REMOTE: if ($fedAllowed) { $this->assertContains($federatedShare, $result->getData(), 'result contains federated share'); } break; } } - if ($fedAllowed && \in_array(\OCP\Share::SHARE_TYPE_REMOTE, $shareTypes, true)) { + if ($fedAllowed && \in_array(\OC\Share\Constants::SHARE_TYPE_REMOTE, $shareTypes, true)) { $this->assertCount(\count($shareTypes), $result->getData()); } else { $this->assertCount(\count($shareTypes) - 1, $result->getData()); } } - public function providesGetSharesSharedWithMe() { + public function providesGetSharesSharedWithMe(): array { return [ [ null, @@ -3091,12 +3106,12 @@ public function providesGetSharesSharedWithMe() { ], [ '/requested/path', - \OCP\Share::STATE_PENDING, + \OC\Share\Constants::STATE_PENDING, [], ], [ '/requested/path', - \OCP\Share::STATE_ACCEPTED, + \OC\Share\Constants::STATE_ACCEPTED, [], ], [ @@ -3107,52 +3122,52 @@ public function providesGetSharesSharedWithMe() { [ null, 'all', - [\OCP\Share::SHARE_TYPE_USER], + [\OC\Share\Constants::SHARE_TYPE_USER], ], [ '/requested/path', 'all', - [\OCP\Share::SHARE_TYPE_USER], + [\OC\Share\Constants::SHARE_TYPE_USER], ], [ '/requested/path', - \OCP\Share::STATE_PENDING, - [\OCP\Share::SHARE_TYPE_USER], + \OC\Share\Constants::STATE_PENDING, + [\OC\Share\Constants::SHARE_TYPE_USER], ], [ '/requested/path', - \OCP\Share::STATE_ACCEPTED, - [\OCP\Share::SHARE_TYPE_USER], + \OC\Share\Constants::STATE_ACCEPTED, + [\OC\Share\Constants::SHARE_TYPE_USER], ], [ '/requested/path', '', - [\OCP\Share::SHARE_TYPE_USER], + [\OC\Share\Constants::SHARE_TYPE_USER], ], [ null, 'all', - [\OCP\Share::SHARE_TYPE_GROUP], + [\OC\Share\Constants::SHARE_TYPE_GROUP], ], [ '/requested/path', 'all', - [\OCP\Share::SHARE_TYPE_GROUP], + [\OC\Share\Constants::SHARE_TYPE_GROUP], ], [ '/requested/path', - \OCP\Share::STATE_PENDING, - [\OCP\Share::SHARE_TYPE_GROUP], + \OC\Share\Constants::STATE_PENDING, + [\OC\Share\Constants::SHARE_TYPE_GROUP], ], [ '/requested/path', - \OCP\Share::STATE_ACCEPTED, - [\OCP\Share::SHARE_TYPE_GROUP], + \OC\Share\Constants::STATE_ACCEPTED, + [\OC\Share\Constants::SHARE_TYPE_GROUP], ], [ '/requested/path', '', - [\OCP\Share::SHARE_TYPE_GROUP], + [\OC\Share\Constants::SHARE_TYPE_GROUP], ], ]; } @@ -3160,27 +3175,27 @@ public function providesGetSharesSharedWithMe() { /** * @dataProvider providesGetSharesSharedWithMe */ - public function testGetSharesSharedWithMe($requestedPath, $stateFilter, $shareTypes) { + public function testGetSharesSharedWithMe($requestedPath, $stateFilter, $shareTypes): void { $testStateFilter = $stateFilter; if ($testStateFilter === '' || $testStateFilter === 'all') { - $testStateFilter = \OCP\Share::STATE_ACCEPTED; + $testStateFilter = \OC\Share\Constants::STATE_ACCEPTED; } $userShare = $this->newShare(); $userShare->setShareOwner('shareOwner'); $userShare->setSharedWith('currentUser'); - $userShare->setShareType(\OCP\Share::SHARE_TYPE_USER); + $userShare->setShareType(\OC\Share\Constants::SHARE_TYPE_USER); $userShare->setState($testStateFilter); $userShare->setPermissions(\OCP\Constants::PERMISSION_ALL); $userShareNoAccess = $this->newShare(); $userShareNoAccess->setShareOwner('shareOwner'); $userShareNoAccess->setSharedWith('currentUser'); - $userShareNoAccess->setShareType(\OCP\Share::SHARE_TYPE_USER); + $userShareNoAccess->setShareType(\OC\Share\Constants::SHARE_TYPE_USER); $userShareNoAccess->setState($testStateFilter); $userShareNoAccess->setPermissions(0); $userShareDifferentState = $this->newShare(); $userShareDifferentState->setShareOwner('shareOwner'); $userShareDifferentState->setSharedWith('currentUser'); - $userShareDifferentState->setShareType(\OCP\Share::SHARE_TYPE_USER); + $userShareDifferentState->setShareType(\OC\Share\Constants::SHARE_TYPE_USER); $userShareDifferentState->setState($testStateFilter + 1); $userShareDifferentState->setPermissions(\OCP\Constants::PERMISSION_ALL); $groupShare = $this->newShare(); @@ -3188,15 +3203,15 @@ public function testGetSharesSharedWithMe($requestedPath, $stateFilter, $shareTy $groupShare->setSharedWith('group1'); $groupShare->setState($testStateFilter); $groupShare->setPermissions(\OCP\Constants::PERMISSION_ALL); - $groupShare->setShareType(\OCP\Share::SHARE_TYPE_GROUP); + $groupShare->setShareType(\OC\Share\Constants::SHARE_TYPE_GROUP); $groupShareNonOwner = $this->newShare(); $groupShareNonOwner->setShareOwner('currentUser'); $groupShareNonOwner->setSharedWith('group1'); $groupShareNonOwner->setState($testStateFilter); - $groupShareNonOwner->setShareType(\OCP\Share::SHARE_TYPE_GROUP); + $groupShareNonOwner->setShareType(\OC\Share\Constants::SHARE_TYPE_GROUP); $groupShareNonOwner->setPermissions(\OCP\Constants::PERMISSION_ALL); - $group = $this->createMock('OCP\IGroup'); + $group = $this->createMock(IGroup::class); $group->method('inGroup')->with($this->currentUser)->willReturn(true); $this->groupManager->method('get')->with('group1')->willReturn($group); @@ -3223,43 +3238,43 @@ public function testGetSharesSharedWithMe($requestedPath, $stateFilter, $shareTy } $this->shareManager->method('getSharedWith') - ->will($this->returnValueMap([ - ['currentUser', \OCP\Share::SHARE_TYPE_USER, $node, -1, 0, [$userShare, $userShareDifferentState, $userShareNoAccess]], - ['currentUser', \OCP\Share::SHARE_TYPE_GROUP, $node, -1, 0, [$groupShare, $groupShareNonOwner]], - ])); + ->willReturnMap([ + ['currentUser', \OC\Share\Constants::SHARE_TYPE_USER, $node, -1, 0, [$userShare, $userShareDifferentState, $userShareNoAccess]], + ['currentUser', \OC\Share\Constants::SHARE_TYPE_GROUP, $node, -1, 0, [$groupShare, $groupShareNonOwner]], + ]); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, $requestedPath], - ['state', \OCP\Share::STATE_ACCEPTED, $stateFilter], + ['state', \OC\Share\Constants::STATE_ACCEPTED, $stateFilter], ['shared_with_me', null, 'true'], ['share_types', '', \implode(',', $shareTypes)], - ])); + ]); $ocs = $this->mockFormatShare(); - $ocs->expects($this->any())->method('formatShare')->will($this->returnArgument(0)); + $ocs->expects($this->atLeast(1))->method('formatShare')->will($this->returnArgument(0)); $result = $ocs->getShares(); if (empty($shareTypes)) { $shareTypes = [ - \OCP\Share::SHARE_TYPE_USER, - \OCP\Share::SHARE_TYPE_GROUP, + \OC\Share\Constants::SHARE_TYPE_USER, + \OC\Share\Constants::SHARE_TYPE_GROUP, ]; } - if (\in_array(\OCP\Share::SHARE_TYPE_USER, $shareTypes, true)) { + if (\in_array(\OC\Share\Constants::SHARE_TYPE_USER, $shareTypes, true)) { $this->assertContains($userShare, $result->getData(), 'result contains user share'); $this->assertNotContains($userShareNoAccess, $result->getData(), 'result does not contain inaccessible share'); if ($stateFilter === 'all') { - if (\in_array(\OCP\Share::SHARE_TYPE_GROUP, $shareTypes, true)) { + if (\in_array(\OC\Share\Constants::SHARE_TYPE_GROUP, $shareTypes, true)) { $this->assertCount(3, $result->getData()); } else { $this->assertCount(2, $result->getData()); } $this->assertContains($userShareDifferentState, $result->getData(), 'result contains shares from all states'); } else { - if (\in_array(\OCP\Share::SHARE_TYPE_GROUP, $shareTypes, true)) { + if (\in_array(\OC\Share\Constants::SHARE_TYPE_GROUP, $shareTypes, true)) { $this->assertCount(2, $result->getData()); } else { $this->assertCount(1, $result->getData()); @@ -3268,23 +3283,23 @@ public function testGetSharesSharedWithMe($requestedPath, $stateFilter, $shareTy } } - if (\in_array(\OCP\Share::SHARE_TYPE_GROUP, $shareTypes, true)) { + if (\in_array(\OC\Share\Constants::SHARE_TYPE_GROUP, $shareTypes, true)) { $this->assertContains($groupShare, $result->getData(), 'result contains group share'); $this->assertNotContains($groupShareNonOwner, $result->getData(), 'result does not contain share from same owner'); } } - public function testGetSharesSharedWithMeAndBlockGroup() { + public function testGetSharesSharedWithMeAndBlockGroup(): void { $requestedPath = "/requested/path"; $stateFilter = "all"; $testStateFilter = $stateFilter; if ($testStateFilter === '' || $testStateFilter === 'all') { - $testStateFilter = \OCP\Share::STATE_ACCEPTED; + $testStateFilter = \OC\Share\Constants::STATE_ACCEPTED; } $userShare = $this->newShare(); $userShare->setShareOwner('shareOwner'); $userShare->setSharedWith('currentUser'); - $userShare->setShareType(\OCP\Share::SHARE_TYPE_USER); + $userShare->setShareType(\OC\Share\Constants::SHARE_TYPE_USER); $userShare->setState($testStateFilter); $userShare->setPermissions(\OCP\Constants::PERMISSION_ALL); @@ -3296,10 +3311,10 @@ public function testGetSharesSharedWithMeAndBlockGroup() { ->willReturn(true); $this->groupManager->method('get') - ->will($this->returnValueMap([ + ->willReturnMap([ ['group', $group], ['excluded_group', $groupObj] - ])); + ]); $node = $this->createMock(Node::class); $node->expects($this->once()) @@ -3318,63 +3333,63 @@ public function testGetSharesSharedWithMeAndBlockGroup() { ->willReturn($userFolder); $this->shareManager->method('getSharedWith') - ->will($this->returnValueMap([ - ['currentUser', \OCP\Share::SHARE_TYPE_USER, $node, -1, 0, [$userShare]], - ['currentUser', \OCP\Share::SHARE_TYPE_GROUP, $node, -1, 0, []], - ])); + ->willReturnMap([ + ['currentUser', \OC\Share\Constants::SHARE_TYPE_USER, $node, -1, 0, [$userShare]], + ['currentUser', \OC\Share\Constants::SHARE_TYPE_GROUP, $node, -1, 0, []], + ]); $this->shareManager->method('sharingDisabledForUser') ->with('currentUser') ->willReturn(true); $this->request ->method('getParam') - ->will($this->returnValueMap([ + ->willReturnMap([ ['path', null, $requestedPath], - ['state', \OCP\Share::STATE_ACCEPTED, $stateFilter], + ['state', \OC\Share\Constants::STATE_ACCEPTED, $stateFilter], ['shared_with_me', null, 'true'], ['share_types', '', ''], - ])); + ]); $ocs = $this->mockFormatShare(); - $ocs->expects($this->any())->method('formatShare')->will($this->returnArgument(0)); + $ocs->expects($this->atLeastOnce())->method('formatShare')->will($this->returnArgument(0)); $result = $ocs->getShares(); $this->assertEquals($userShare->getPermissions(), $result->getData()[0]->getPermissions()); } - public function providesAcceptRejectShare() { + public function providesAcceptRejectShare(): array { return [ - ['acceptShare', '/target', true, \OCP\Share::STATE_ACCEPTED], - ['acceptShare', '/sfoo/target', true, \OCP\Share::STATE_ACCEPTED], - ['acceptShare', '/target', false, \OCP\Share::STATE_ACCEPTED], - ['acceptShare', '/sfoo/target', false, \OCP\Share::STATE_ACCEPTED], - ['declineShare', '/target', true, \OCP\Share::STATE_REJECTED], - ['declineShare', '/sfoo/target', true, \OCP\Share::STATE_REJECTED], + ['acceptShare', '/target', true, \OC\Share\Constants::STATE_ACCEPTED], + ['acceptShare', '/sfoo/target', true, \OC\Share\Constants::STATE_ACCEPTED], + ['acceptShare', '/target', false, \OC\Share\Constants::STATE_ACCEPTED], + ['acceptShare', '/sfoo/target', false, \OC\Share\Constants::STATE_ACCEPTED], + ['declineShare', '/target', true, \OC\Share\Constants::STATE_REJECTED], + ['declineShare', '/sfoo/target', true, \OC\Share\Constants::STATE_REJECTED], ]; } /** * @dataProvider providesAcceptRejectShare */ - public function testAcceptRejectShare($method, $target, $targetExists, $expectedState) { + public function testAcceptRejectShare($method, $target, $targetExists, $expectedState): void { $userShare = $this->makeReceivedUserShareForOperation($target); - $this->shareManager->expects($this->exactly(1)) + $this->shareManager->expects($this->once()) ->method('getShareById') ->with('ocinternal:123', 'currentUser') ->willReturn($userShare); $this->shareManager->expects($this->exactly(2)) ->method('getSharedWith') - ->will($this->returnValueMap([ - ['currentUser', Share::SHARE_TYPE_USER, $userShare->getNode(), -1, 0, [$userShare]], - ['currentUser', Share::SHARE_TYPE_GROUP, $userShare->getNode(), -1, 0, []] - ])); + ->willReturnMap([ + ['currentUser', \OC\Share\Constants::SHARE_TYPE_USER, $userShare->getNode(), -1, 0, [$userShare]], + ['currentUser', \OC\Share\Constants::SHARE_TYPE_GROUP, $userShare->getNode(), -1, 0, []] + ]); $this->shareManager->expects($this->once()) ->method('updateShareForRecipient') ->with($userShare, 'currentUser'); - $userFolder = $this->createMock('OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); if ($method === 'acceptShare') { // deduplicate if ($targetExists) { @@ -3419,7 +3434,7 @@ public function testAcceptRejectShare($method, $target, $targetExists, $expected ->willReturn($userFolder); $ocs = $this->mockFormatShare(); - $ocs->expects($this->any())->method('formatShare')->will($this->returnArgument(0)); + $ocs->expects($this->atLeastOnce())->method('formatShare')->will($this->returnArgument(0)); $result = $ocs->$method(123); $this->assertEquals(100, $result->getStatusCode()); @@ -3427,31 +3442,31 @@ public function testAcceptRejectShare($method, $target, $targetExists, $expected if ($method === 'acceptShare' && $targetExists) { $this->assertEquals("$target (2)", $userShare->getTarget()); } else { - $this->assertEquals("$target", $userShare->getTarget()); + $this->assertEquals((string)$target, $userShare->getTarget()); } $this->assertSame($expectedState, $userShare->getState()); } - public function providesAcceptRejectShareSameState() { + public function providesAcceptRejectShareSameState(): array { return [ - ['acceptShare', '/target', true, \OCP\Share::STATE_ACCEPTED], - ['declineShare', '/sfoo/target', true, \OCP\Share::STATE_REJECTED], + ['acceptShare', '/target', true, \OC\Share\Constants::STATE_ACCEPTED], + ['declineShare', '/sfoo/target', true, \OC\Share\Constants::STATE_REJECTED], ]; } /** * @dataProvider providesAcceptRejectShareSameState */ - public function testAcceptRejectShareSameState($method, $target) { + public function testAcceptRejectShareSameState($method, $target): void { $userShare = $this->makeReceivedUserShareForOperation($target); - $this->shareManager->expects($this->exactly(1)) + $this->shareManager->expects($this->once()) ->method('getShareById') ->with('ocinternal:123', 'currentUser') ->willReturn($userShare); if ($method === 'acceptShare') { - $userShare->setState(\OCP\Share::STATE_ACCEPTED); + $userShare->setState(\OC\Share\Constants::STATE_ACCEPTED); $this->eventDispatcher->expects($this->exactly(2)) ->method('dispatch') ->withConsecutive( @@ -3459,7 +3474,7 @@ public function testAcceptRejectShareSameState($method, $target) { [$this->equalTo(new GenericEvent(null, ['share' => $userShare])), $this->equalTo('share.afteraccept')] ); } else { - $userShare->setState(\OCP\Share::STATE_REJECTED); + $userShare->setState(\OC\Share\Constants::STATE_REJECTED); $this->eventDispatcher->expects($this->exactly(2)) ->method('dispatch') ->withConsecutive( @@ -3478,32 +3493,32 @@ public function testAcceptRejectShareSameState($method, $target) { /** * @dataProvider providesAcceptRejectShare */ - public function testAcceptRejectShareMultiple($method, $target, $targetExists, $expectedState) { + public function testAcceptRejectShareMultiple($method, $target, $targetExists, $expectedState): void { $userShare = $this->makeReceivedUserShareForOperation($target); $groupShare = $this->newShare(); $groupShare->setId(234); - $groupShare->setShareType(Share::SHARE_TYPE_GROUP); + $groupShare->setShareType(\OC\Share\Constants::SHARE_TYPE_GROUP); $groupShare->setSharedWith('group1'); $groupShare->setNode($userShare->getNode()); $groupShare->setTarget($target); - $this->shareManager->expects($this->exactly(1)) + $this->shareManager->expects($this->once()) ->method('getShareById') ->with('ocinternal:123', 'currentUser') ->willReturn($userShare); $this->shareManager->expects($this->exactly(2)) ->method('getSharedWith') - ->will($this->returnValueMap([ - ['currentUser', Share::SHARE_TYPE_USER, $userShare->getNode(), -1, 0, [$userShare]], - ['currentUser', Share::SHARE_TYPE_GROUP, $userShare->getNode(), -1, 0, [$groupShare]] - ])); + ->willReturnMap([ + ['currentUser', \OC\Share\Constants::SHARE_TYPE_USER, $userShare->getNode(), -1, 0, [$userShare]], + ['currentUser', \OC\Share\Constants::SHARE_TYPE_GROUP, $userShare->getNode(), -1, 0, [$groupShare]] + ]); $this->shareManager->expects($this->exactly(2)) ->method('updateShareForRecipient') ->withConsecutive([$userShare], [$groupShare]); - $userFolder = $this->createMock('OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); if ($method === 'acceptShare') { // deduplicate if ($targetExists) { @@ -3548,7 +3563,7 @@ public function testAcceptRejectShareMultiple($method, $target, $targetExists, $ ->willReturn($userFolder); $ocs = $this->mockFormatShare(); - $ocs->expects($this->any())->method('formatShare')->will($this->returnArgument(0)); + $ocs->expects($this->atLeastOnce())->method('formatShare')->will($this->returnArgument(0)); $result = $ocs->$method(123); $this->assertEquals(100, $result->getStatusCode()); @@ -3556,7 +3571,7 @@ public function testAcceptRejectShareMultiple($method, $target, $targetExists, $ if ($method === 'acceptShare' && $targetExists) { $this->assertEquals("$target (2)", $userShare->getTarget()); } else { - $this->assertEquals("$target", $userShare->getTarget()); + $this->assertEquals((string)$target, $userShare->getTarget()); } $this->assertSame($expectedState, $userShare->getState()); } @@ -3564,7 +3579,7 @@ public function testAcceptRejectShareMultiple($method, $target, $targetExists, $ /** * @dataProvider providesAcceptRejectShare */ - public function testAcceptRejectShareApiDisabled($method, $target, $targetExists, $expectedState) { + public function testAcceptRejectShareApiDisabled($method, $target, $targetExists): void { $ocs = $this->getOcsDisabledAPI(); $expected = new Result(null, 404, 'Share API is disabled'); @@ -3573,19 +3588,19 @@ public function testAcceptRejectShareApiDisabled($method, $target, $targetExists $this->assertEquals($expected, $result); } - private function makeReceivedUserShareForOperation($target) { + private function makeReceivedUserShareForOperation($target): IShare { $node = $this->createMock(Node::class); - $node->expects($this->any()) + $node->expects($this->atLeastOnce()) ->method('lock'); - $node->expects($this->any()) + $node->expects($this->atLeastOnce()) ->method('unlock'); $userShare = $this->newShare(); $userShare->setId(123); $userShare->setShareOwner('shareOwner'); $userShare->setSharedWith('currentUser'); - $userShare->setShareType(\OCP\Share::SHARE_TYPE_USER); - $userShare->setState(\OCP\Share::STATE_PENDING); + $userShare->setShareType(\OC\Share\Constants::SHARE_TYPE_USER); + $userShare->setState(\OC\Share\Constants::STATE_PENDING); $userShare->setPermissions(\OCP\Constants::PERMISSION_ALL); $userShare->setTarget($target); $userShare->setNode($node); @@ -3596,7 +3611,7 @@ private function makeReceivedUserShareForOperation($target) { /** * @dataProvider providesAcceptRejectShare */ - public function testAcceptRejectShareInvalidId($method, $target, $targetExists, $expectedState) { + public function testAcceptRejectShareInvalidId($method, $target, $targetExists, $expectedState): void { $this->shareManager->expects($this->any()) ->method('getShareById') ->with('ocinternal:123') @@ -3614,7 +3629,7 @@ public function testAcceptRejectShareInvalidId($method, $target, $targetExists, /** * @dataProvider providesAcceptRejectShare */ - public function testAcceptRejectShareAccessDenied($method, $target, $targetExists, $expectedState) { + public function testAcceptRejectShareAccessDenied($method, $target, $targetExists): void { $userShare = $this->makeReceivedUserShareForOperation($target); $userShare->setPermissions(0); @@ -3635,10 +3650,10 @@ public function testAcceptRejectShareAccessDenied($method, $target, $targetExist /** * @dataProvider providesAcceptRejectShare */ - public function testAcceptRejectShareAccessNotRecipient($method, $target, $targetExists, $expectedState) { + public function testAcceptRejectShareAccessNotRecipient($method, $target, $targetExists): void { $userShare = $this->makeReceivedUserShareForOperation($target); - $this->shareManager->expects($this->any()) + $this->shareManager ->method('getShareById') ->with('ocinternal:123', 'currentUser') ->willReturn($userShare); @@ -3664,7 +3679,7 @@ public function testAcceptRejectShareAccessNotRecipient($method, $target, $targe /** * @dataProvider providesAcceptRejectShare */ - public function testAcceptRejectShareOperationError($method, $target, $targetExists, $expectedState) { + public function testAcceptRejectShareOperationError($method, $target, $targetExists): void { $userShare = $this->makeReceivedUserShareForOperation($target); $this->shareManager->expects($this->once()) @@ -3679,8 +3694,8 @@ public function testAcceptRejectShareOperationError($method, $target, $targetExi $this->shareManager->expects($this->exactly(2)) ->method('getSharedWith') ->willReturnMap([ - ['currentUser', Share::SHARE_TYPE_USER, $userShare->getNode(), -1, 0, [$userShare]], - ['currentUser', Share::SHARE_TYPE_GROUP, $userShare->getNode(), -1, 0, []] + ['currentUser', \OC\Share\Constants::SHARE_TYPE_USER, $userShare->getNode(), -1, 0, [$userShare]], + ['currentUser', \OC\Share\Constants::SHARE_TYPE_GROUP, $userShare->getNode(), -1, 0, []] ]); $userFolder = $this->createMock(Folder::class); @@ -3711,7 +3726,7 @@ public function testAcceptRejectShareOperationError($method, $target, $targetExi /** * @dataProvider providesTestAttributes */ - public function testSettingAttributes($attributes, $expectedAttributeObject) { + public function testSettingAttributes($attributes, $expectedAttributeObject): void { $share = $this->newShare(); $this->shareManager->method('newShare')->willReturn($share); @@ -3731,20 +3746,21 @@ public function testSettingAttributes($attributes, $expectedAttributeObject) { ['path', null, 'valid-path'], ['permissions', null, 1], ['attributes', null, $attributes], - ['shareType', $this->any(), Share::SHARE_TYPE_USER], + ['shareType', $this->any(), \OC\Share\Constants::SHARE_TYPE_USER], ['shareWith', null, 'validUser'], + ['expireDate', '', ''] ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -3769,7 +3785,7 @@ public function testSettingAttributes($attributes, $expectedAttributeObject) { $this->assertEquals($expectedAttributeObject, $result->getData()['attributes']->toArray()); } - public function providesTestAttributes() { + public function providesTestAttributes(): array { return [ [ [ @@ -3821,7 +3837,7 @@ public function providesTestAttributes() { /** * @dataProvider providesPermissionsViaAttributes */ - public function testPermissionsViaAttributes($expectedPermission, $attributes) { + public function testPermissionsViaAttributes($expectedPermission, $attributes): void { $share = $this->newShare(); $this->shareManager->method('newShare')->willReturn($share); @@ -3841,20 +3857,21 @@ public function testPermissionsViaAttributes($expectedPermission, $attributes) { ['path', null, 'valid-path'], ['permissions', null, null], ['attributes', null, $attributes], - ['shareType', $this->any(), Share::SHARE_TYPE_USER], + ['shareType', $this->any(), \OC\Share\Constants::SHARE_TYPE_USER], ['shareWith', null, 'validUser'], + ['expireDate', '', ''] ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock(Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock(File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -3878,7 +3895,7 @@ public function testPermissionsViaAttributes($expectedPermission, $attributes) { $this->assertEquals($expectedPermission, $result->getData()['permissions']); } - public function providesPermissionsViaAttributes() { + public function providesPermissionsViaAttributes(): array { return [ [ \OCP\Constants::PERMISSION_READ, [ diff --git a/apps/files_sharing/tests/EtagPropagationTest.php b/apps/files_sharing/tests/EtagPropagationTest.php index 2240db0743e1..4478dd5c3888 100644 --- a/apps/files_sharing/tests/EtagPropagationTest.php +++ b/apps/files_sharing/tests/EtagPropagationTest.php @@ -181,7 +181,7 @@ protected function setUpShares() { $this->logout(); } - public function testOwnerWritesToShare() { + public function testOwnerWritesToShare(): void { self::loginAsUser(self::TEST_FILES_SHARING_API_USER1); Filesystem::file_put_contents('/sub1/sub2/folder/asd.txt', 'bar'); $this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER4]); diff --git a/apps/files_sharing/tests/TestCase.php b/apps/files_sharing/tests/TestCase.php index 0ab286ed7dfc..2c7d5d160f69 100644 --- a/apps/files_sharing/tests/TestCase.php +++ b/apps/files_sharing/tests/TestCase.php @@ -180,12 +180,6 @@ protected static function loginHelper($user, $create = false, $password = false) * reset init status for the share storage */ protected static function resetStorage() { - $storage = new \ReflectionClass(SharedStorage::class); - $isInitialized = $storage->getProperty('initialized'); - $isInitialized->setAccessible(true); - $isInitialized->setValue($storage, false); - $isInitialized->setAccessible(false); - $storage = new \ReflectionClass(Storage::class); $property = $storage->getProperty('localCache'); $property->setAccessible(true); diff --git a/apps/files_trashbin/tests/TestCase.php b/apps/files_trashbin/tests/TestCase.php index 08ac9738006b..a2d6bac970f9 100644 --- a/apps/files_trashbin/tests/TestCase.php +++ b/apps/files_trashbin/tests/TestCase.php @@ -21,12 +21,13 @@ namespace OCA\Files_Trashbin\Tests; -use OC\Files\Cache\Watcher; use OC\Files\Filesystem; use OC\Files\View; use OCA\Files_Sharing\AppInfo\Application; use OCA\Files_Trashbin\Expiration; use OCA\Files_Trashbin\Trashbin; +use OCP\Files\Cache\IWatcher; +use OCP\IConfig; /** * Class TrashbinTestCase @@ -83,13 +84,9 @@ public static function setUpBeforeClass(): void { public static function tearDownAfterClass(): void { // cleanup test user $user = \OC::$server->getUserManager()->get(self::TEST_TRASHBIN_USER1); - if ($user !== null) { - $user->delete(); - } + $user?->delete(); $user = \OC::$server->getUserManager()->get(self::TEST_TRASHBIN_USER2); - if ($user !== null) { - $user->delete(); - } + $user?->delete(); \OC::$server->getConfig()->setSystemValue('trashbin_retention_obligation', self::$rememberRetentionObligation); @@ -109,16 +106,17 @@ protected function setUp(): void { \OC::$server->getAppManager()->enableApp('files_trashbin'); $config = \OC::$server->getConfig(); - $mockConfig = $this->createMock('\OCP\IConfig'); - $mockConfig->expects($this->any()) + $mockConfig = $this->createMock(IConfig::class); + $mockConfig ->method('getSystemValue') - ->will($this->returnCallback(function ($key, $default) use ($config) { + ->willReturnCallback(function ($key, $default) use ($config) { if ($key === 'filesystem_check_changes') { - return Watcher::CHECK_ONCE; - } else { - return $config->getSystemValue($key, $default); + return IWatcher::CHECK_ONCE; } - })); + + return $config->getSystemValue($key, $default); + }); + $mockConfig->method('getUserValue')->willReturnArgument(2); $this->overwriteService('AllConfig', $mockConfig); $this->trashRoot1 = '/' . self::TEST_TRASHBIN_USER1 . '/files_trashbin'; @@ -138,7 +136,7 @@ protected function tearDown(): void { // clear trash table $connection = \OC::$server->getDatabaseConnection(); - $connection->executeUpdate('DELETE FROM `*PREFIX*files_trash`'); + $connection->executeStatement('DELETE FROM `*PREFIX*files_trash`'); parent::tearDown(); } @@ -147,7 +145,7 @@ protected function tearDown(): void { * @param string $user * @param bool $create */ - protected static function loginHelper($user, $create = false) { + protected static function loginHelper($user, $create = false): void { if ($create) { try { \OC::$server->getUserManager()->createUser($user, $user); diff --git a/apps/files_versions/tests/VersioningTest.php b/apps/files_versions/tests/VersioningTest.php index 3e6623e93a41..a8c12e9a69c6 100644 --- a/apps/files_versions/tests/VersioningTest.php +++ b/apps/files_versions/tests/VersioningTest.php @@ -49,6 +49,7 @@ use OCA\Files_Versions\Hooks; use OCA\Files_Versions\MetaStorage; use OCP\Constants; +use OCA\Files_Versions\Expiration; use OCP\Files\Cache\IWatcher; use OCP\Files\Storage; use OCP\IConfig; @@ -106,7 +107,7 @@ protected function setUp(): void { $this->dataDir = OC::$server->getConfig()->getSystemValue('datadirectory'); // Generate random usernames for better isolation - $testId = uniqid('', true); + $testId = \uniqid('', true); $this->user1 = "test-versions-user1-$testId"; $this->user2 = "test-versions-user2-$testId"; $this->versionsRootOfUser1 = "/$this->user1/files_versions"; @@ -179,6 +180,8 @@ private function overwriteConfig($saveVersionMetadata=false, $versionsRetentionO return $config->getSystemValue($key, $default); }); + $this->mockConfig->method('getAppValue')->willReturnArgument(2); + $this->overwriteService('AllConfig', $this->mockConfig); // clear hooks @@ -1407,17 +1410,11 @@ private function createAndCheckVersions(View $view, $path): void { * @param string $user * @param bool $create */ - public static function loginHelper($user, $create = false): void { + public static function loginHelper(string $user, bool $create = false): void { if ($create) { OC::$server->getUserManager()->createUser($user, $user); } - $storage = new ReflectionClass('\OCA\Files_Sharing\SharedStorage'); - $isInitialized = $storage->getProperty('initialized'); - $isInitialized->setAccessible(true); - $isInitialized->setValue($storage, false); - $isInitialized->setAccessible(false); - OC_Util::tearDownFS(); OC_User::setUserId(''); Filesystem::tearDown(); diff --git a/composer.json b/composer.json index a1495910ba7d..8d515559f576 100644 --- a/composer.json +++ b/composer.json @@ -7,12 +7,13 @@ "optimize-autoloader": true, "classmap-authoritative": false, "platform": { - "php": "7.4" + "php": "8.2" }, "allow-plugins": { "bamarni/composer-bin-plugin": true, "dg/composer-cleaner": true - } + }, + "sort-packages": true }, "autoload" : { "psr-4": { @@ -44,7 +45,7 @@ "roave/security-advisories": "dev-latest" }, "require": { - "php": ">=7.4", + "php": ">=8.2", "ext-apcu": "*", "ext-ctype": "*", "ext-curl": "*", @@ -89,9 +90,9 @@ "sabre/dav": "^4.4", "sabre/http": "^5.1", "sabre/vobject": "^4.5", - "swiftmailer/swiftmailer": "^6.3", "symfony/console": "^5.4", "symfony/event-dispatcher": "^5.4", + "symfony/mailer": "^5.4", "symfony/process": "^5.4", "symfony/routing": "^5.4", "symfony/translation": "^5.4" diff --git a/composer.lock b/composer.lock index 16459be94f30..99f7558df1f0 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "bf6744a7c1c955849e3a5ab203b66c94", + "content-hash": "920a0b3d694d94ebeb3e0972c6859d48", "packages": [ { "name": "bantu/ini-get-wrapper", @@ -629,28 +629,27 @@ }, { "name": "doctrine/lexer", - "version": "2.1.1", + "version": "3.0.1", "source": { "type": "git", "url": "https://github.com/doctrine/lexer.git", - "reference": "861c870e8b75f7c8f69c146c7f89cc1c0f1b49b6" + "reference": "31ad66abc0fc9e1a1f2d9bc6a42668d2fbbcd6dd" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/lexer/zipball/861c870e8b75f7c8f69c146c7f89cc1c0f1b49b6", - "reference": "861c870e8b75f7c8f69c146c7f89cc1c0f1b49b6", + "url": "https://api.github.com/repos/doctrine/lexer/zipball/31ad66abc0fc9e1a1f2d9bc6a42668d2fbbcd6dd", + "reference": "31ad66abc0fc9e1a1f2d9bc6a42668d2fbbcd6dd", "shasum": "" }, "require": { - "doctrine/deprecations": "^1.0", - "php": "^7.1 || ^8.0" + "php": "^8.1" }, "require-dev": { - "doctrine/coding-standard": "^9 || ^12", - "phpstan/phpstan": "^1.3", - "phpunit/phpunit": "^7.5 || ^8.5 || ^9.6", + "doctrine/coding-standard": "^12", + "phpstan/phpstan": "^1.10", + "phpunit/phpunit": "^10.5", "psalm/plugin-phpunit": "^0.18.3", - "vimeo/psalm": "^4.11 || ^5.21" + "vimeo/psalm": "^5.21" }, "type": "library", "autoload": { @@ -687,7 +686,7 @@ ], "support": { "issues": "https://github.com/doctrine/lexer/issues", - "source": "https://github.com/doctrine/lexer/tree/2.1.1" + "source": "https://github.com/doctrine/lexer/tree/3.0.1" }, "funding": [ { @@ -703,30 +702,30 @@ "type": "tidelift" } ], - "time": "2024-02-05T11:35:39+00:00" + "time": "2024-02-05T11:56:58+00:00" }, { "name": "egulias/email-validator", - "version": "3.2.6", + "version": "4.0.2", "source": { "type": "git", "url": "https://github.com/egulias/EmailValidator.git", - "reference": "e5997fa97e8790cdae03a9cbd5e78e45e3c7bda7" + "reference": "ebaaf5be6c0286928352e054f2d5125608e5405e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/egulias/EmailValidator/zipball/e5997fa97e8790cdae03a9cbd5e78e45e3c7bda7", - "reference": "e5997fa97e8790cdae03a9cbd5e78e45e3c7bda7", + "url": "https://api.github.com/repos/egulias/EmailValidator/zipball/ebaaf5be6c0286928352e054f2d5125608e5405e", + "reference": "ebaaf5be6c0286928352e054f2d5125608e5405e", "shasum": "" }, "require": { - "doctrine/lexer": "^1.2|^2", - "php": ">=7.2", - "symfony/polyfill-intl-idn": "^1.15" + "doctrine/lexer": "^2.0 || ^3.0", + "php": ">=8.1", + "symfony/polyfill-intl-idn": "^1.26" }, "require-dev": { - "phpunit/phpunit": "^8.5.8|^9.3.3", - "vimeo/psalm": "^4" + "phpunit/phpunit": "^10.2", + "vimeo/psalm": "^5.12" }, "suggest": { "ext-intl": "PHP Internationalization Libraries are required to use the SpoofChecking validation" @@ -734,7 +733,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "3.0.x-dev" + "dev-master": "4.0.x-dev" } }, "autoload": { @@ -762,7 +761,7 @@ ], "support": { "issues": "https://github.com/egulias/EmailValidator/issues", - "source": "https://github.com/egulias/EmailValidator/tree/3.2.6" + "source": "https://github.com/egulias/EmailValidator/tree/4.0.2" }, "funding": [ { @@ -770,7 +769,7 @@ "type": "github" } ], - "time": "2023-06-01T07:04:22+00:00" + "time": "2023-10-06T06:47:41+00:00" }, { "name": "firebase/php-jwt", @@ -906,16 +905,16 @@ }, { "name": "google/apiclient-services", - "version": "v0.335.0", + "version": "v0.337.0", "source": { "type": "git", "url": "https://github.com/googleapis/google-api-php-client-services.git", - "reference": "3e6cea8f43066378babdf00e718f01c7c55233fd" + "reference": "0f2a9a00c91a903b2f30f4f531a09af948df384e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/googleapis/google-api-php-client-services/zipball/3e6cea8f43066378babdf00e718f01c7c55233fd", - "reference": "3e6cea8f43066378babdf00e718f01c7c55233fd", + "url": "https://api.github.com/repos/googleapis/google-api-php-client-services/zipball/0f2a9a00c91a903b2f30f4f531a09af948df384e", + "reference": "0f2a9a00c91a903b2f30f4f531a09af948df384e", "shasum": "" }, "require": { @@ -944,22 +943,22 @@ ], "support": { "issues": "https://github.com/googleapis/google-api-php-client-services/issues", - "source": "https://github.com/googleapis/google-api-php-client-services/tree/v0.335.0" + "source": "https://github.com/googleapis/google-api-php-client-services/tree/v0.337.0" }, - "time": "2024-02-12T01:08:15+00:00" + "time": "2024-02-26T01:00:27+00:00" }, { "name": "google/auth", - "version": "v1.35.0", + "version": "v1.37.0", "source": { "type": "git", "url": "https://github.com/googleapis/google-auth-library-php.git", - "reference": "6e9c9fd4e2bbd7042f50083076346e4a1eff4e4b" + "reference": "5f16f67375b6f202b857183d7ef4e076acd7d4aa" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/googleapis/google-auth-library-php/zipball/6e9c9fd4e2bbd7042f50083076346e4a1eff4e4b", - "reference": "6e9c9fd4e2bbd7042f50083076346e4a1eff4e4b", + "url": "https://api.github.com/repos/googleapis/google-auth-library-php/zipball/5f16f67375b6f202b857183d7ef4e076acd7d4aa", + "reference": "5f16f67375b6f202b857183d7ef4e076acd7d4aa", "shasum": "" }, "require": { @@ -1002,9 +1001,9 @@ "support": { "docs": "https://googleapis.github.io/google-auth-library-php/main/", "issues": "https://github.com/googleapis/google-auth-library-php/issues", - "source": "https://github.com/googleapis/google-auth-library-php/tree/v1.35.0" + "source": "https://github.com/googleapis/google-auth-library-php/tree/v1.37.0" }, - "time": "2024-02-01T20:41:08+00:00" + "time": "2024-02-21T17:03:52+00:00" }, { "name": "guzzlehttp/guzzle", @@ -1482,38 +1481,38 @@ }, { "name": "laminas/laminas-filter", - "version": "2.22.0", + "version": "2.34.0", "source": { "type": "git", "url": "https://github.com/laminas/laminas-filter.git", - "reference": "c48e8a392a81de7d211026c078dce0e8bc57e2e3" + "reference": "008923542683d853109af5c71b7e9099de76c3e6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laminas/laminas-filter/zipball/c48e8a392a81de7d211026c078dce0e8bc57e2e3", - "reference": "c48e8a392a81de7d211026c078dce0e8bc57e2e3", + "url": "https://api.github.com/repos/laminas/laminas-filter/zipball/008923542683d853109af5c71b7e9099de76c3e6", + "reference": "008923542683d853109af5c71b7e9099de76c3e6", "shasum": "" }, "require": { "ext-mbstring": "*", - "laminas/laminas-servicemanager": "^3.14.0", + "laminas/laminas-servicemanager": "^3.21.0", "laminas/laminas-stdlib": "^3.13.0", - "php": "^7.4 || ~8.0.0 || ~8.1.0" + "php": "~8.1.0 || ~8.2.0 || ~8.3.0" }, "conflict": { "laminas/laminas-validator": "<2.10.1", "zendframework/zend-filter": "*" }, "require-dev": { - "laminas/laminas-coding-standard": "~2.4.0", - "laminas/laminas-crypt": "^3.5.1", - "laminas/laminas-uri": "^2.9.1", + "laminas/laminas-coding-standard": "~2.5.0", + "laminas/laminas-crypt": "^3.11", + "laminas/laminas-i18n": "^2.25.0", + "laminas/laminas-uri": "^2.11", "pear/archive_tar": "^1.4.14", - "phpspec/prophecy-phpunit": "^2.0.1", - "phpunit/phpunit": "^9.5.24", - "psalm/plugin-phpunit": "^0.17.0", - "psr/http-factory": "^1.0.1", - "vimeo/psalm": "^4.27.0" + "phpunit/phpunit": "^10.5.5", + "psalm/plugin-phpunit": "^0.18.4", + "psr/http-factory": "^1.0.2", + "vimeo/psalm": "^5.18.0" }, "suggest": { "laminas/laminas-crypt": "Laminas\\Crypt component, for encryption filters", @@ -1557,40 +1556,39 @@ "type": "community_bridge" } ], - "time": "2022-10-11T08:14:46+00:00" + "time": "2024-01-04T11:47:08+00:00" }, { "name": "laminas/laminas-inputfilter", - "version": "2.21.0", + "version": "2.29.0", "source": { "type": "git", "url": "https://github.com/laminas/laminas-inputfilter.git", - "reference": "8668227246d19564f339643f0f2aedcdff66612b" + "reference": "82a76f40477c3e399863d13446a5c0187f421775" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laminas/laminas-inputfilter/zipball/8668227246d19564f339643f0f2aedcdff66612b", - "reference": "8668227246d19564f339643f0f2aedcdff66612b", + "url": "https://api.github.com/repos/laminas/laminas-inputfilter/zipball/82a76f40477c3e399863d13446a5c0187f421775", + "reference": "82a76f40477c3e399863d13446a5c0187f421775", "shasum": "" }, "require": { - "laminas/laminas-filter": "^2.13", - "laminas/laminas-servicemanager": "^3.16.0", + "laminas/laminas-filter": "^2.19", + "laminas/laminas-servicemanager": "^3.21.0", "laminas/laminas-stdlib": "^3.0", - "laminas/laminas-validator": "^2.15", - "php": "^7.4 || ~8.0.0 || ~8.1.0" + "laminas/laminas-validator": "^2.25", + "php": "~8.1.0 || ~8.2.0 || ~8.3.0" }, "conflict": { "zendframework/zend-inputfilter": "*" }, "require-dev": { "ext-json": "*", - "laminas/laminas-coding-standard": "~2.4.0", - "laminas/laminas-db": "^2.15.0", - "phpunit/phpunit": "^9.5.24", - "psalm/plugin-phpunit": "^0.17.0", - "psr/http-message": "^1.0", - "vimeo/psalm": "^4.27.0", + "laminas/laminas-coding-standard": "~2.5.0", + "phpunit/phpunit": "^10.5.5", + "psalm/plugin-phpunit": "^0.18.4", + "psr/http-message": "^2.0", + "vimeo/psalm": "^5.18", "webmozart/assert": "^1.11" }, "suggest": { @@ -1632,30 +1630,30 @@ "type": "community_bridge" } ], - "time": "2022-09-20T10:03:09+00:00" + "time": "2024-01-10T11:57:06+00:00" }, { "name": "laminas/laminas-servicemanager", - "version": "3.17.0", + "version": "3.22.1", "source": { "type": "git", "url": "https://github.com/laminas/laminas-servicemanager.git", - "reference": "360be5f16955dd1edbcce1cfaa98ed82a17f02ec" + "reference": "de98d297d4743956a0558a6d71616979ff779328" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laminas/laminas-servicemanager/zipball/360be5f16955dd1edbcce1cfaa98ed82a17f02ec", - "reference": "360be5f16955dd1edbcce1cfaa98ed82a17f02ec", + "url": "https://api.github.com/repos/laminas/laminas-servicemanager/zipball/de98d297d4743956a0558a6d71616979ff779328", + "reference": "de98d297d4743956a0558a6d71616979ff779328", "shasum": "" }, "require": { - "laminas/laminas-stdlib": "^3.2.1", - "php": "~7.4.0 || ~8.0.0 || ~8.1.0", + "laminas/laminas-stdlib": "^3.17", + "php": "~8.1.0 || ~8.2.0 || ~8.3.0", "psr/container": "^1.0" }, "conflict": { "ext-psr": "*", - "laminas/laminas-code": "<3.3.1", + "laminas/laminas-code": "<4.10.0", "zendframework/zend-code": "<3.3.1", "zendframework/zend-servicemanager": "*" }, @@ -1666,20 +1664,19 @@ "container-interop/container-interop": "^1.2.0" }, "require-dev": { - "composer/package-versions-deprecated": "^1.0", - "laminas/laminas-coding-standard": "~2.4.0", - "laminas/laminas-container-config-test": "^0.7", - "laminas/laminas-dependency-plugin": "^2.1.2", - "mikey179/vfsstream": "^1.6.10@alpha", - "ocramius/proxy-manager": "^2.11", - "phpbench/phpbench": "^1.1", - "phpspec/prophecy-phpunit": "^2.0", - "phpunit/phpunit": "^9.5.5", - "psalm/plugin-phpunit": "^0.17.0", - "vimeo/psalm": "^4.8" + "composer/package-versions-deprecated": "^1.11.99.5", + "friendsofphp/proxy-manager-lts": "^1.0.14", + "laminas/laminas-code": "^4.10.0", + "laminas/laminas-coding-standard": "~2.5.0", + "laminas/laminas-container-config-test": "^0.8", + "mikey179/vfsstream": "^1.6.11", + "phpbench/phpbench": "^1.2.9", + "phpunit/phpunit": "^10.4", + "psalm/plugin-phpunit": "^0.18.4", + "vimeo/psalm": "^5.8.0" }, "suggest": { - "ocramius/proxy-manager": "ProxyManager ^2.1.1 to handle lazy initialization of services" + "friendsofphp/proxy-manager-lts": "ProxyManager ^2.1.1 to handle lazy initialization of services" }, "bin": [ "bin/generate-deps-for-config-factory", @@ -1723,35 +1720,34 @@ "type": "community_bridge" } ], - "time": "2022-09-22T11:33:46+00:00" + "time": "2023-10-24T11:19:47+00:00" }, { "name": "laminas/laminas-stdlib", - "version": "3.13.0", + "version": "3.19.0", "source": { "type": "git", "url": "https://github.com/laminas/laminas-stdlib.git", - "reference": "66a6d03c381f6c9f1dd988bf8244f9afb9380d76" + "reference": "6a192dd0882b514e45506f533b833b623b78fff3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laminas/laminas-stdlib/zipball/66a6d03c381f6c9f1dd988bf8244f9afb9380d76", - "reference": "66a6d03c381f6c9f1dd988bf8244f9afb9380d76", + "url": "https://api.github.com/repos/laminas/laminas-stdlib/zipball/6a192dd0882b514e45506f533b833b623b78fff3", + "reference": "6a192dd0882b514e45506f533b833b623b78fff3", "shasum": "" }, "require": { - "php": "^7.4 || ~8.0.0 || ~8.1.0" + "php": "~8.1.0 || ~8.2.0 || ~8.3.0" }, "conflict": { "zendframework/zend-stdlib": "*" }, "require-dev": { - "laminas/laminas-coding-standard": "~2.3.0", - "phpbench/phpbench": "^1.2.6", - "phpstan/phpdoc-parser": "^0.5.4", - "phpunit/phpunit": "^9.5.23", - "psalm/plugin-phpunit": "^0.17.0", - "vimeo/psalm": "^4.26" + "laminas/laminas-coding-standard": "^2.5", + "phpbench/phpbench": "^1.2.15", + "phpunit/phpunit": "^10.5.8", + "psalm/plugin-phpunit": "^0.18.4", + "vimeo/psalm": "^5.20.0" }, "type": "library", "autoload": { @@ -1783,45 +1779,43 @@ "type": "community_bridge" } ], - "time": "2022-08-24T13:56:50+00:00" + "time": "2024-01-19T12:39:49+00:00" }, { "name": "laminas/laminas-validator", - "version": "2.25.0", + "version": "2.49.0", "source": { "type": "git", "url": "https://github.com/laminas/laminas-validator.git", - "reference": "42de39b78e73b321db7d948cf8530a2764f8b9aa" + "reference": "d58c2e7d3cd420554400dd8cca694fafa3b8e45f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laminas/laminas-validator/zipball/42de39b78e73b321db7d948cf8530a2764f8b9aa", - "reference": "42de39b78e73b321db7d948cf8530a2764f8b9aa", + "url": "https://api.github.com/repos/laminas/laminas-validator/zipball/d58c2e7d3cd420554400dd8cca694fafa3b8e45f", + "reference": "d58c2e7d3cd420554400dd8cca694fafa3b8e45f", "shasum": "" }, "require": { - "laminas/laminas-servicemanager": "^3.12.0", + "laminas/laminas-servicemanager": "^3.21.0", "laminas/laminas-stdlib": "^3.13", - "php": "^7.4 || ~8.0.0 || ~8.1.0" + "php": "~8.1.0 || ~8.2.0 || ~8.3.0", + "psr/http-message": "^1.0.1 || ^2.0.0" }, "conflict": { "zendframework/zend-validator": "*" }, "require-dev": { - "laminas/laminas-coding-standard": "^2.4.0", - "laminas/laminas-db": "^2.15.0", - "laminas/laminas-filter": "^2.18.0", - "laminas/laminas-http": "^2.16.0", - "laminas/laminas-i18n": "^2.17.0", - "laminas/laminas-session": "^2.13.0", - "laminas/laminas-uri": "^2.9.1", - "phpspec/prophecy-phpunit": "^2.0", - "phpunit/phpunit": "^9.5.24", - "psalm/plugin-phpunit": "^0.17.0", - "psr/http-client": "^1.0", - "psr/http-factory": "^1.0", - "psr/http-message": "^1.0", - "vimeo/psalm": "^4.27.0" + "laminas/laminas-coding-standard": "^2.5", + "laminas/laminas-db": "^2.19", + "laminas/laminas-filter": "^2.34", + "laminas/laminas-i18n": "^2.26.0", + "laminas/laminas-session": "^2.18", + "laminas/laminas-uri": "^2.11.0", + "phpunit/phpunit": "^10.5.10", + "psalm/plugin-phpunit": "^0.18.4", + "psr/http-client": "^1.0.3", + "psr/http-factory": "^1.0.2", + "vimeo/psalm": "^5.22.1" }, "suggest": { "laminas/laminas-db": "Laminas\\Db component, required by the (No)RecordExists validator", @@ -1869,7 +1863,7 @@ "type": "community_bridge" } ], - "time": "2022-09-20T11:33:19+00:00" + "time": "2024-02-22T16:46:06+00:00" }, { "name": "laravel/serializable-closure", @@ -2083,42 +2077,41 @@ }, { "name": "monolog/monolog", - "version": "2.9.2", + "version": "3.5.0", "source": { "type": "git", "url": "https://github.com/Seldaek/monolog.git", - "reference": "437cb3628f4cf6042cc10ae97fc2b8472e48ca1f" + "reference": "c915e2634718dbc8a4a15c61b0e62e7a44e14448" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Seldaek/monolog/zipball/437cb3628f4cf6042cc10ae97fc2b8472e48ca1f", - "reference": "437cb3628f4cf6042cc10ae97fc2b8472e48ca1f", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/c915e2634718dbc8a4a15c61b0e62e7a44e14448", + "reference": "c915e2634718dbc8a4a15c61b0e62e7a44e14448", "shasum": "" }, "require": { - "php": ">=7.2", - "psr/log": "^1.0.1 || ^2.0 || ^3.0" + "php": ">=8.1", + "psr/log": "^2.0 || ^3.0" }, "provide": { - "psr/log-implementation": "1.0.0 || 2.0.0 || 3.0.0" + "psr/log-implementation": "3.0.0" }, "require-dev": { - "aws/aws-sdk-php": "^2.4.9 || ^3.0", + "aws/aws-sdk-php": "^3.0", "doctrine/couchdb": "~1.0@dev", "elasticsearch/elasticsearch": "^7 || ^8", "ext-json": "*", - "graylog2/gelf-php": "^1.4.2 || ^2@dev", - "guzzlehttp/guzzle": "^7.4", + "graylog2/gelf-php": "^1.4.2 || ^2.0", + "guzzlehttp/guzzle": "^7.4.5", "guzzlehttp/psr7": "^2.2", "mongodb/mongodb": "^1.8", "php-amqplib/php-amqplib": "~2.4 || ^3", - "phpspec/prophecy": "^1.15", - "phpstan/phpstan": "^0.12.91", - "phpunit/phpunit": "^8.5.14", - "predis/predis": "^1.1 || ^2.0", - "rollbar/rollbar": "^1.3 || ^2 || ^3", + "phpstan/phpstan": "^1.9", + "phpstan/phpstan-deprecation-rules": "^1.0", + "phpstan/phpstan-strict-rules": "^1.4", + "phpunit/phpunit": "^10.1", + "predis/predis": "^1.1 || ^2", "ruflin/elastica": "^7", - "swiftmailer/swiftmailer": "^5.3|^6.0", "symfony/mailer": "^5.4 || ^6", "symfony/mime": "^5.4 || ^6" }, @@ -2141,7 +2134,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "2.x-dev" + "dev-main": "3.x-dev" } }, "autoload": { @@ -2169,7 +2162,7 @@ ], "support": { "issues": "https://github.com/Seldaek/monolog/issues", - "source": "https://github.com/Seldaek/monolog/tree/2.9.2" + "source": "https://github.com/Seldaek/monolog/tree/3.5.0" }, "funding": [ { @@ -2181,7 +2174,7 @@ "type": "tidelift" } ], - "time": "2023-10-27T15:25:26+00:00" + "time": "2023-10-27T15:32:31+00:00" }, { "name": "nikic/php-parser", @@ -2814,20 +2807,20 @@ }, { "name": "psr/cache", - "version": "1.0.1", + "version": "3.0.0", "source": { "type": "git", "url": "https://github.com/php-fig/cache.git", - "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8" + "reference": "aa5030cfa5405eccfdcb1083ce040c2cb8d253bf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/cache/zipball/d11b50ad223250cf17b86e38383413f5a6764bf8", - "reference": "d11b50ad223250cf17b86e38383413f5a6764bf8", + "url": "https://api.github.com/repos/php-fig/cache/zipball/aa5030cfa5405eccfdcb1083ce040c2cb8d253bf", + "reference": "aa5030cfa5405eccfdcb1083ce040c2cb8d253bf", "shasum": "" }, "require": { - "php": ">=5.3.0" + "php": ">=8.0.0" }, "type": "library", "extra": { @@ -2847,7 +2840,7 @@ "authors": [ { "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" + "homepage": "https://www.php-fig.org/" } ], "description": "Common interface for caching libraries", @@ -2857,9 +2850,9 @@ "psr-6" ], "support": { - "source": "https://github.com/php-fig/cache/tree/master" + "source": "https://github.com/php-fig/cache/tree/3.0.0" }, - "time": "2016-08-06T20:24:11+00:00" + "time": "2021-02-03T23:26:27+00:00" }, { "name": "psr/container", @@ -3121,30 +3114,30 @@ }, { "name": "psr/log", - "version": "1.1.4", + "version": "2.0.0", "source": { "type": "git", "url": "https://github.com/php-fig/log.git", - "reference": "d49695b909c3b7628b6289db5479a1c204601f11" + "reference": "ef29f6d262798707a9edd554e2b82517ef3a9376" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/d49695b909c3b7628b6289db5479a1c204601f11", - "reference": "d49695b909c3b7628b6289db5479a1c204601f11", + "url": "https://api.github.com/repos/php-fig/log/zipball/ef29f6d262798707a9edd554e2b82517ef3a9376", + "reference": "ef29f6d262798707a9edd554e2b82517ef3a9376", "shasum": "" }, "require": { - "php": ">=5.3.0" + "php": ">=8.0.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.1.x-dev" + "dev-master": "2.0.x-dev" } }, "autoload": { "psr-4": { - "Psr\\Log\\": "Psr/Log/" + "Psr\\Log\\": "src" } }, "notification-url": "https://packagist.org/downloads/", @@ -3165,9 +3158,9 @@ "psr-3" ], "support": { - "source": "https://github.com/php-fig/log/tree/1.1.4" + "source": "https://github.com/php-fig/log/tree/2.0.0" }, - "time": "2021-05-03T11:20:27+00:00" + "time": "2021-07-14T16:41:46+00:00" }, { "name": "punic/punic", @@ -3745,82 +3738,6 @@ }, "time": "2023-06-28T12:56:05+00:00" }, - { - "name": "swiftmailer/swiftmailer", - "version": "v6.3.0", - "source": { - "type": "git", - "url": "https://github.com/swiftmailer/swiftmailer.git", - "reference": "8a5d5072dca8f48460fce2f4131fcc495eec654c" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/swiftmailer/swiftmailer/zipball/8a5d5072dca8f48460fce2f4131fcc495eec654c", - "reference": "8a5d5072dca8f48460fce2f4131fcc495eec654c", - "shasum": "" - }, - "require": { - "egulias/email-validator": "^2.0|^3.1", - "php": ">=7.0.0", - "symfony/polyfill-iconv": "^1.0", - "symfony/polyfill-intl-idn": "^1.10", - "symfony/polyfill-mbstring": "^1.0" - }, - "require-dev": { - "mockery/mockery": "^1.0", - "symfony/phpunit-bridge": "^4.4|^5.4" - }, - "suggest": { - "ext-intl": "Needed to support internationalized email addresses" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "6.2-dev" - } - }, - "autoload": { - "files": [ - "lib/swift_required.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Chris Corbyn" - }, - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - } - ], - "description": "Swiftmailer, free feature-rich PHP mailer", - "homepage": "https://swiftmailer.symfony.com", - "keywords": [ - "email", - "mail", - "mailer" - ], - "support": { - "issues": "https://github.com/swiftmailer/swiftmailer/issues", - "source": "https://github.com/swiftmailer/swiftmailer/tree/v6.3.0" - }, - "funding": [ - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/swiftmailer/swiftmailer", - "type": "tidelift" - } - ], - "abandoned": "symfony/mailer", - "time": "2021-10-18T15:26:12+00:00" - }, { "name": "symfony/console", "version": "v5.4.36", @@ -3922,25 +3839,25 @@ }, { "name": "symfony/deprecation-contracts", - "version": "v2.5.2", + "version": "v3.4.0", "source": { "type": "git", "url": "https://github.com/symfony/deprecation-contracts.git", - "reference": "e8b495ea28c1d97b5e0c121748d6f9b53d075c66" + "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/e8b495ea28c1d97b5e0c121748d6f9b53d075c66", - "reference": "e8b495ea28c1d97b5e0c121748d6f9b53d075c66", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/7c3aff79d10325257a001fcf92d991f24fc967cf", + "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf", "shasum": "" }, "require": { - "php": ">=7.1" + "php": ">=8.1" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "2.5-dev" + "dev-main": "3.4-dev" }, "thanks": { "name": "symfony/contracts", @@ -3969,7 +3886,7 @@ "description": "A generic function and convention to trigger deprecation notices", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v2.5.2" + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.4.0" }, "funding": [ { @@ -3985,7 +3902,7 @@ "type": "tidelift" } ], - "time": "2022-01-02T09:53:40+00:00" + "time": "2023-05-23T14:45:45+00:00" }, { "name": "symfony/event-dispatcher", @@ -4074,29 +3991,26 @@ }, { "name": "symfony/event-dispatcher-contracts", - "version": "v2.5.2", + "version": "v3.4.0", "source": { "type": "git", "url": "https://github.com/symfony/event-dispatcher-contracts.git", - "reference": "f98b54df6ad059855739db6fcbc2d36995283fe1" + "reference": "a76aed96a42d2b521153fb382d418e30d18b59df" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/f98b54df6ad059855739db6fcbc2d36995283fe1", - "reference": "f98b54df6ad059855739db6fcbc2d36995283fe1", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/a76aed96a42d2b521153fb382d418e30d18b59df", + "reference": "a76aed96a42d2b521153fb382d418e30d18b59df", "shasum": "" }, "require": { - "php": ">=7.2.5", + "php": ">=8.1", "psr/event-dispatcher": "^1" }, - "suggest": { - "symfony/event-dispatcher-implementation": "" - }, "type": "library", "extra": { "branch-alias": { - "dev-main": "2.5-dev" + "dev-main": "3.4-dev" }, "thanks": { "name": "symfony/contracts", @@ -4133,7 +4047,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v2.5.2" + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.4.0" }, "funding": [ { @@ -4149,7 +4063,167 @@ "type": "tidelift" } ], - "time": "2022-01-02T09:53:40+00:00" + "time": "2023-05-23T14:45:45+00:00" + }, + { + "name": "symfony/mailer", + "version": "v5.4.36", + "source": { + "type": "git", + "url": "https://github.com/symfony/mailer.git", + "reference": "b57d722f2bf6e1dc08df9c86efbfdcaaba89693b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/mailer/zipball/b57d722f2bf6e1dc08df9c86efbfdcaaba89693b", + "reference": "b57d722f2bf6e1dc08df9c86efbfdcaaba89693b", + "shasum": "" + }, + "require": { + "egulias/email-validator": "^2.1.10|^3|^4", + "php": ">=7.2.5", + "psr/event-dispatcher": "^1", + "psr/log": "^1|^2|^3", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/event-dispatcher": "^4.4|^5.0|^6.0", + "symfony/mime": "^5.2.6|^6.0", + "symfony/polyfill-php80": "^1.16", + "symfony/service-contracts": "^1.1|^2|^3" + }, + "conflict": { + "symfony/http-kernel": "<4.4" + }, + "require-dev": { + "symfony/http-client": "^4.4|^5.0|^6.0", + "symfony/messenger": "^4.4|^5.0|^6.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Mailer\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Helps sending emails", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/mailer/tree/v5.4.36" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-02-01T13:42:14+00:00" + }, + { + "name": "symfony/mime", + "version": "v6.4.3", + "source": { + "type": "git", + "url": "https://github.com/symfony/mime.git", + "reference": "5017e0a9398c77090b7694be46f20eb796262a34" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/mime/zipball/5017e0a9398c77090b7694be46f20eb796262a34", + "reference": "5017e0a9398c77090b7694be46f20eb796262a34", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/polyfill-intl-idn": "^1.10", + "symfony/polyfill-mbstring": "^1.0" + }, + "conflict": { + "egulias/email-validator": "~3.0.0", + "phpdocumentor/reflection-docblock": "<3.2.2", + "phpdocumentor/type-resolver": "<1.4.0", + "symfony/mailer": "<5.4", + "symfony/serializer": "<6.3.2" + }, + "require-dev": { + "egulias/email-validator": "^2.1.10|^3.1|^4", + "league/html-to-markdown": "^5.0", + "phpdocumentor/reflection-docblock": "^3.0|^4.0|^5.0", + "symfony/dependency-injection": "^5.4|^6.0|^7.0", + "symfony/property-access": "^5.4|^6.0|^7.0", + "symfony/property-info": "^5.4|^6.0|^7.0", + "symfony/serializer": "^6.3.2|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Mime\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Allows manipulating MIME messages", + "homepage": "https://symfony.com", + "keywords": [ + "mime", + "mime-type" + ], + "support": { + "source": "https://github.com/symfony/mime/tree/v6.4.3" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-01-30T08:32:12+00:00" }, { "name": "symfony/polyfill-php80", @@ -4385,33 +4459,29 @@ }, { "name": "symfony/service-contracts", - "version": "v2.5.2", + "version": "v3.4.1", "source": { "type": "git", "url": "https://github.com/symfony/service-contracts.git", - "reference": "4b426aac47d6427cc1a1d0f7e2ac724627f5966c" + "reference": "fe07cbc8d837f60caf7018068e350cc5163681a0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/service-contracts/zipball/4b426aac47d6427cc1a1d0f7e2ac724627f5966c", - "reference": "4b426aac47d6427cc1a1d0f7e2ac724627f5966c", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/fe07cbc8d837f60caf7018068e350cc5163681a0", + "reference": "fe07cbc8d837f60caf7018068e350cc5163681a0", "shasum": "" }, "require": { - "php": ">=7.2.5", - "psr/container": "^1.1", - "symfony/deprecation-contracts": "^2.1|^3" + "php": ">=8.1", + "psr/container": "^1.1|^2.0" }, "conflict": { "ext-psr": "<1.1|>=2" }, - "suggest": { - "symfony/service-implementation": "" - }, "type": "library", "extra": { "branch-alias": { - "dev-main": "2.5-dev" + "dev-main": "3.4-dev" }, "thanks": { "name": "symfony/contracts", @@ -4421,7 +4491,10 @@ "autoload": { "psr-4": { "Symfony\\Contracts\\Service\\": "" - } + }, + "exclude-from-classmap": [ + "/Test/" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -4448,7 +4521,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/service-contracts/tree/v2.5.2" + "source": "https://github.com/symfony/service-contracts/tree/v3.4.1" }, "funding": [ { @@ -4464,38 +4537,38 @@ "type": "tidelift" } ], - "time": "2022-05-30T19:17:29+00:00" + "time": "2023-12-26T14:02:43+00:00" }, { "name": "symfony/string", - "version": "v5.4.36", + "version": "v6.4.4", "source": { "type": "git", "url": "https://github.com/symfony/string.git", - "reference": "4e232c83622bd8cd32b794216aa29d0d266d353b" + "reference": "4e465a95bdc32f49cf4c7f07f751b843bbd6dcd9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/string/zipball/4e232c83622bd8cd32b794216aa29d0d266d353b", - "reference": "4e232c83622bd8cd32b794216aa29d0d266d353b", + "url": "https://api.github.com/repos/symfony/string/zipball/4e465a95bdc32f49cf4c7f07f751b843bbd6dcd9", + "reference": "4e465a95bdc32f49cf4c7f07f751b843bbd6dcd9", "shasum": "" }, "require": { - "php": ">=7.2.5", + "php": ">=8.1", "symfony/polyfill-ctype": "~1.8", "symfony/polyfill-intl-grapheme": "~1.0", "symfony/polyfill-intl-normalizer": "~1.0", - "symfony/polyfill-mbstring": "~1.0", - "symfony/polyfill-php80": "~1.15" + "symfony/polyfill-mbstring": "~1.0" }, "conflict": { - "symfony/translation-contracts": ">=3.0" + "symfony/translation-contracts": "<2.5" }, "require-dev": { - "symfony/error-handler": "^4.4|^5.0|^6.0", - "symfony/http-client": "^4.4|^5.0|^6.0", - "symfony/translation-contracts": "^1.1|^2", - "symfony/var-exporter": "^4.4|^5.0|^6.0" + "symfony/error-handler": "^5.4|^6.0|^7.0", + "symfony/http-client": "^5.4|^6.0|^7.0", + "symfony/intl": "^6.2|^7.0", + "symfony/translation-contracts": "^2.5|^3.0", + "symfony/var-exporter": "^5.4|^6.0|^7.0" }, "type": "library", "autoload": { @@ -4534,7 +4607,7 @@ "utf8" ], "support": { - "source": "https://github.com/symfony/string/tree/v5.4.36" + "source": "https://github.com/symfony/string/tree/v6.4.4" }, "funding": [ { @@ -4550,7 +4623,7 @@ "type": "tidelift" } ], - "time": "2024-02-01T08:49:30+00:00" + "time": "2024-02-01T13:16:41+00:00" }, { "name": "symfony/translation", @@ -4788,30 +4861,30 @@ }, { "name": "doctrine/instantiator", - "version": "1.5.0", + "version": "2.0.0", "source": { "type": "git", "url": "https://github.com/doctrine/instantiator.git", - "reference": "0a0fa9780f5d4e507415a065172d26a98d02047b" + "reference": "c6222283fa3f4ac679f8b9ced9a4e23f163e80d0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/instantiator/zipball/0a0fa9780f5d4e507415a065172d26a98d02047b", - "reference": "0a0fa9780f5d4e507415a065172d26a98d02047b", + "url": "https://api.github.com/repos/doctrine/instantiator/zipball/c6222283fa3f4ac679f8b9ced9a4e23f163e80d0", + "reference": "c6222283fa3f4ac679f8b9ced9a4e23f163e80d0", "shasum": "" }, "require": { - "php": "^7.1 || ^8.0" + "php": "^8.1" }, "require-dev": { - "doctrine/coding-standard": "^9 || ^11", + "doctrine/coding-standard": "^11", "ext-pdo": "*", "ext-phar": "*", - "phpbench/phpbench": "^0.16 || ^1", - "phpstan/phpstan": "^1.4", - "phpstan/phpstan-phpunit": "^1", - "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5", - "vimeo/psalm": "^4.30 || ^5.4" + "phpbench/phpbench": "^1.2", + "phpstan/phpstan": "^1.9.4", + "phpstan/phpstan-phpunit": "^1.3", + "phpunit/phpunit": "^9.5.27", + "vimeo/psalm": "^5.4" }, "type": "library", "autoload": { @@ -4838,7 +4911,7 @@ ], "support": { "issues": "https://github.com/doctrine/instantiator/issues", - "source": "https://github.com/doctrine/instantiator/tree/1.5.0" + "source": "https://github.com/doctrine/instantiator/tree/2.0.0" }, "funding": [ { @@ -4854,7 +4927,7 @@ "type": "tidelift" } ], - "time": "2022-12-30T00:15:36+00:00" + "time": "2022-12-30T00:23:10+00:00" }, { "name": "mikey179/vfsstream", @@ -7262,7 +7335,7 @@ "prefer-stable": false, "prefer-lowest": false, "platform": { - "php": ">=7.4", + "php": ">=8.2", "ext-apcu": "*", "ext-ctype": "*", "ext-curl": "*", @@ -7283,7 +7356,7 @@ }, "platform-dev": [], "platform-overrides": { - "php": "7.4" + "php": "8.2" }, "plugin-api-version": "2.6.0" } diff --git a/composer.phar b/composer.phar new file mode 100755 index 000000000000..553efcce527c Binary files /dev/null and b/composer.phar differ diff --git a/config/config.sample.php b/config/config.sample.php index b06a8f472c82..1fc10a120e03 100644 --- a/config/config.sample.php +++ b/config/config.sample.php @@ -445,7 +445,7 @@ /** * Define the SMTP security style - * Depends on `mail_smtpmode`. Specify when you are using `ssl` or `tls`. + * Depends on `mail_smtpmode`. Specify when you are using `ssl` or not. * Leave empty for no encryption. */ 'mail_smtpsecure' => '', @@ -456,13 +456,6 @@ */ 'mail_smtpauth' => false, -/** - * Define the SMTP authentication type - * Depends on `mail_smtpmode`. If SMTP authentication is required, - * choose the authentication type as `LOGIN` (default) or `PLAIN`. - */ -'mail_smtpauthtype' => 'LOGIN', - /** * Define the SMTP authentication username * Depends on `mail_smtpauth`. Specify the username for authenticating to the SMTP server. diff --git a/core/Command/Integrity/SignApp.php b/core/Command/Integrity/SignApp.php index a68c47cf649c..b9bd469df82c 100644 --- a/core/Command/Integrity/SignApp.php +++ b/core/Command/Integrity/SignApp.php @@ -26,6 +26,7 @@ use OC\IntegrityCheck\Helpers\FileAccessHelper; use OCP\IURLGenerator; use phpseclib3\Crypt\RSA; +use phpseclib3\Crypt\RSA\PrivateKey; use phpseclib3\File\X509; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; diff --git a/core/Command/Integrity/SignCore.php b/core/Command/Integrity/SignCore.php index a998adfcc29b..116785160a2f 100644 --- a/core/Command/Integrity/SignCore.php +++ b/core/Command/Integrity/SignCore.php @@ -25,6 +25,7 @@ use OC\IntegrityCheck\Checker; use OC\IntegrityCheck\Helpers\FileAccessHelper; use phpseclib3\Crypt\RSA; +use phpseclib3\Crypt\RSA\PrivateKey; use phpseclib3\File\X509; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; diff --git a/core/Command/User/ListUsers.php b/core/Command/User/ListUsers.php index ac1277f74623..7412271cfdc9 100644 --- a/core/Command/User/ListUsers.php +++ b/core/Command/User/ListUsers.php @@ -99,7 +99,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $showAllAttributes = $input->getOption('show-all-attributes'); $useKey = \count($attributes) > 1 || $input->getOption('output') !== self::OUTPUT_FORMAT_PLAIN; - $users = $this->userManager->search($userNameSubString, null, null, true); + $users = $this->userManager->search($userNameSubString ?? '', null, null, true); $users = \array_map(function (IUser $user) use ($output, $attributes, $useKey, $showAllAttributes) { if ($output->isVerbose() || $showAllAttributes) { // include all attributes diff --git a/core/Controller/AvatarController.php b/core/Controller/AvatarController.php index 0c70e5992e77..cd72a19f27ad 100644 --- a/core/Controller/AvatarController.php +++ b/core/Controller/AvatarController.php @@ -213,7 +213,7 @@ public function postAvatar($path) { try { $image = new \OC_Image(); - $image->load($handle); + $image->loadFromFileHandle($handle); $image->fixOrientation(); // don't accept images with too big dimensions // 4k - 4096×2160 diff --git a/core/Controller/LostController.php b/core/Controller/LostController.php index 3155711e6749..ccbe084d87e4 100644 --- a/core/Controller/LostController.php +++ b/core/Controller/LostController.php @@ -166,7 +166,7 @@ public function resetform($token, $userId) { private function checkPasswordResetToken($token, $userId) { $user = $this->userManager->get($userId); - $splittedToken = \explode(':', $this->config->getUserValue($userId, 'owncloud', 'lostpassword', null)); + $splittedToken = \explode(':', $this->config->getUserValue($userId, 'owncloud', 'lostpassword', null) ?? ''); if (\count($splittedToken) !== 2) { $this->config->deleteUserValue($userId, 'owncloud', 'lostpassword'); throw new \Exception($this->l10n->t('Could not reset password because the token is invalid')); @@ -354,7 +354,7 @@ public function sendEmail($user, $token, $link) { } } - $getToken = $this->config->getUserValue($user, 'owncloud', 'lostpassword'); + $getToken = $this->config->getUserValue($user, 'owncloud', 'lostpassword') ?? ''; if ($getToken !== '') { $splittedToken = \explode(':', $getToken); if ((\count($splittedToken)) === 2 && $splittedToken[0] > ($this->timeFactory->getTime() - 60 * 5)) { @@ -383,7 +383,7 @@ public function sendEmail($user, $token, $link) { $this->mailer->send($message); } catch (\Exception $e) { throw new \Exception($this->l10n->t( - 'Couldn\'t send reset email. Please contact your administrator.' + "Couldn't send reset email. Please contact your administrator." )); } diff --git a/lib/base.php b/lib/base.php index 43269235bf7f..f7ec7c0a9654 100644 --- a/lib/base.php +++ b/lib/base.php @@ -5,14 +5,14 @@ if (\defined('OC_CONSOLE')) { $eol = PHP_EOL; } -if (PHP_VERSION_ID < 70400) { - echo 'This version of ownCloud requires at least PHP 7.4.0'.$eol; +if (PHP_VERSION_ID < 80200) { + echo 'This version of ownCloud requires at least PHP 8.2.0'.$eol; echo 'You are currently running PHP ' . PHP_VERSION . '. Please update your PHP version.'.$eol; exit(1); } -if (PHP_VERSION_ID >= 80000) { - echo 'This version of ownCloud is not compatible with PHP 8.0' . $eol; +if (PHP_VERSION_ID >= 80300) { + echo 'This version of ownCloud is not compatible with PHP 8.3' . $eol; echo 'You are currently running PHP ' . PHP_VERSION . '.' . $eol; exit(1); } diff --git a/lib/private/App/DependencyAnalyzer.php b/lib/private/App/DependencyAnalyzer.php index 4acbc9b181dc..15d47f928fb0 100644 --- a/lib/private/App/DependencyAnalyzer.php +++ b/lib/private/App/DependencyAnalyzer.php @@ -136,19 +136,19 @@ private function analyzePhpVersion(array $dependencies) { if (isset($dependencies['php']['@attributes']['min-version'])) { $minVersion = $dependencies['php']['@attributes']['min-version']; if ($this->compareSmaller($this->platform->getPhpVersion(), $minVersion)) { - $missing[] = (string)$this->l->t('PHP %s or higher is required.', $minVersion); + $missing[] = (string)$this->l->t('PHP %s or higher is required.', [$minVersion]); } } if (isset($dependencies['php']['@attributes']['max-version'])) { $maxVersion = $dependencies['php']['@attributes']['max-version']; if ($this->compareBigger($this->platform->getPhpVersion(), $maxVersion)) { - $missing[] = (string)$this->l->t('PHP with a version lower than %s is required.', $maxVersion); + $missing[] = (string)$this->l->t('PHP with a version lower than %s is required.', [$maxVersion]); } } if (isset($dependencies['php']['@attributes']['min-int-size'])) { $intSize = $dependencies['php']['@attributes']['min-int-size']; if ($intSize > $this->platform->getIntSize()*8) { - $missing[] = (string)$this->l->t('%sbit or higher PHP required.', $intSize); + $missing[] = (string)$this->l->t('%sbit or higher PHP required.', [$intSize]); } } return $missing; @@ -175,8 +175,8 @@ private function analyzeDatabases(array $dependencies) { return $this->getValue($db); }, $supportedDatabases); $currentDatabase = $this->platform->getDatabase(); - if (!\in_array($currentDatabase, $supportedDatabases)) { - $missing[] = (string)$this->l->t('Following databases are supported: %s', \join(', ', $supportedDatabases)); + if (!\in_array($currentDatabase, $supportedDatabases, true)) { + $missing[] = (string)$this->l->t('Following databases are supported: %s', [\implode(', ', $supportedDatabases)]); } return $missing; } @@ -205,7 +205,7 @@ private function analyzeCommands(array $dependencies) { } $commandName = $this->getValue($command); if (!$this->platform->isCommandKnown($commandName)) { - $missing[] = (string)$this->l->t('The command line tool %s could not be found', $commandName); + $missing[] = (string)$this->l->t('The command line tool %s could not be found', [$commandName]); } } return $missing; @@ -232,7 +232,7 @@ private function analyzeLibraries(array $dependencies) { $libName = $this->getValue($lib); $libVersion = $this->platform->getLibraryVersion($libName); if ($libVersion === null) { - $missing[] = (string)$this->l->t('The library %s is not available.', $libName); + $missing[] = (string)$this->l->t('The library %s is not available.', [$libName]); continue; } @@ -282,8 +282,8 @@ private function analyzeOS(array $dependencies) { $oss = [$oss]; } $currentOS = $this->platform->getOS(); - if (!\in_array($currentOS, $oss)) { - $missing[] = (string)$this->l->t('Following platforms are supported: %s', \join(', ', $oss)); + if (!\in_array($currentOS, $oss, true)) { + $missing[] = (string)$this->l->t('Following platforms are supported: %s', [\implode(', ', $oss)]); } return $missing; } @@ -312,12 +312,12 @@ private function analyzeOC(array $dependencies, array $appInfo) { if ($minVersion !== null) { if ($this->compareSmaller($this->platform->getOcVersion(), $minVersion)) { - $missing[] = (string)$this->l->t('ownCloud %s or higher is required.', $minVersion); + $missing[] = (string)$this->l->t('ownCloud %s or higher is required.', [$minVersion]); } } if ($maxVersion !== null) { if ($this->compareBigger($this->platform->getOcVersion(), $maxVersion)) { - $missing[] = (string)$this->l->t('ownCloud %s or lower is required.', $maxVersion); + $missing[] = (string)$this->l->t('ownCloud %s or lower is required.', [$maxVersion]); } } return $missing; diff --git a/lib/private/App/InfoParser.php b/lib/private/App/InfoParser.php index 6ca1ecc2ca7f..93f5ead4fd8e 100644 --- a/lib/private/App/InfoParser.php +++ b/lib/private/App/InfoParser.php @@ -43,10 +43,8 @@ public function parse($file) { } \libxml_use_internal_errors(true); - $loadEntities = \libxml_disable_entity_loader(false); $xml = \simplexml_load_file($file); - \libxml_disable_entity_loader($loadEntities); if ($xml === false) { \libxml_clear_errors(); throw new InvalidArgumentException('Invalid XML'); diff --git a/lib/private/AppFramework/Db/Db.php b/lib/private/AppFramework/Db/Db.php index c5c92f8f34cd..0aa8d4b6699f 100644 --- a/lib/private/AppFramework/Db/Db.php +++ b/lib/private/AppFramework/Db/Db.php @@ -236,7 +236,7 @@ public function tableExists($table) { /** * @inheritdoc */ - public function escapeLikeParameter($param) { + public function escapeLikeParameter(string $param): string { return $this->connection->escapeLikeParameter($param); } diff --git a/lib/private/AppFramework/Http.php b/lib/private/AppFramework/Http.php index b8ef72c83a45..17a89cfd17e4 100644 --- a/lib/private/AppFramework/Http.php +++ b/lib/private/AppFramework/Http.php @@ -30,15 +30,15 @@ use OCP\AppFramework\Http as BaseHttp; class Http extends BaseHttp { - private $server; - private $protocolVersion; - protected $headers; + private array $server; + private string $protocolVersion; + protected array $headers; /** * @param array $server $_SERVER * @param string $protocolVersion the http version to use defaults to HTTP/1.1 */ - public function __construct($server, $protocolVersion='HTTP/1.1') { + public function __construct(array $server, string $protocolVersion='HTTP/1.1') { $this->server = $server; $this->protocolVersion = $protocolVersion; @@ -107,16 +107,17 @@ public function __construct($server, $protocolVersion='HTTP/1.1') { /** * Gets the correct header + * * @param Http::CONSTANT $status the constant from the Http class - * @param \DateTime $lastModified formatted last modified date - * @param string $ETag the etag + * @param \DateTime|null $lastModified formatted last modified date + * @param null $ETag the etag * @return string */ public function getStatusHeader( $status, \DateTime $lastModified=null, $ETag=null - ) { + ): string { if ($lastModified !== null) { $lastModified = $lastModified->format(\DateTime::RFC2822); } @@ -135,7 +136,7 @@ public function getStatusHeader( // we have one change currently for the http 1.0 header that differs // from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND - // if this differs any more, we want to create childclasses for this + // if this differs anymore, we want to create child-classes for this if ($status === self::STATUS_TEMPORARY_REDIRECT && $this->protocolVersion === 'HTTP/1.0') { $status = self::STATUS_FOUND; diff --git a/lib/private/AppFramework/Http/Dispatcher.php b/lib/private/AppFramework/Http/Dispatcher.php index 98666bc2dc7b..ae92ea6942f1 100644 --- a/lib/private/AppFramework/Http/Dispatcher.php +++ b/lib/private/AppFramework/Http/Dispatcher.php @@ -26,23 +26,28 @@ namespace OC\AppFramework\Http; -use \OC\AppFramework\Middleware\MiddlewareDispatcher; -use \OC\AppFramework\Http; -use \OC\AppFramework\Utility\ControllerMethodReflector; +use Exception; +use OC\AppFramework\Middleware\MiddlewareDispatcher; +use OC\AppFramework\Http; +use OC\AppFramework\Utility\ControllerMethodReflector; use OCP\AppFramework\Controller; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Http\DataResponse; use OCP\IRequest; +use function array_merge; +use function call_user_func_array; +use function in_array; +use function settype; /** * Class to dispatch the request to the middleware dispatcher */ class Dispatcher { - private $middlewareDispatcher; - private $protocol; - private $reflector; - private $request; + private MiddlewareDispatcher $middlewareDispatcher; + private Http $protocol; + private ControllerMethodReflector $reflector; + private IRequest $request; /** * @param Http $protocol the http protocol with contains all status headers @@ -66,19 +71,20 @@ public function __construct( /** * Handles a request and calls the dispatcher on the controller + * * @param Controller $controller the controller which will be called * @param string $methodName the method name which will be called on * the controller * @return array $array[0] contains a string with the http main header, * $array[1] contains headers in the form: $key => value, $array[2] contains * the response output - * @throws \Exception + * @throws Exception */ - public function dispatch(Controller $controller, $methodName) { + public function dispatch(Controller $controller, string $methodName): array { $out = [null, [], null]; try { - // prefill reflector with everything thats needed for the + // prefill reflector with everything that's needed for the // middlewares $this->reflector->reflect($controller, $methodName); @@ -90,9 +96,9 @@ public function dispatch(Controller $controller, $methodName) { // if an exception appears, the middleware checks if it can handle the // exception and creates a response. If no response is created, it is - // assumed that theres no middleware who can handle it and the error is + // assumed that there's no middleware who can handle it and the error is // thrown again - } catch (\Exception $exception) { + } catch (Exception $exception) { $response = $this->middlewareDispatcher->afterException( $controller, $methodName, @@ -115,7 +121,7 @@ public function dispatch(Controller $controller, $methodName) { $response->getLastModified(), $response->getETag() ); - $out[1] = \array_merge($response->getHeaders()); + $out[1] = array_merge($response->getHeaders()); $out[2] = $response->getCookies(); $out[3] = $this->middlewareDispatcher->beforeOutput( $controller, @@ -130,11 +136,12 @@ public function dispatch(Controller $controller, $methodName) { /** * Uses the reflected parameters, types and request parameters to execute * the controller + * * @param Controller $controller the controller to be executed * @param string $methodName the method on the controller that should be executed * @return Response */ - private function executeController($controller, $methodName) { + private function executeController(Controller $controller, string $methodName): Response { $arguments = []; // valid types that will be casted @@ -152,15 +159,12 @@ private function executeController($controller, $methodName) { $value === 'false' && ( $this->request->method === 'GET' || - \strpos( - $this->request->getHeader('Content-Type') ?? '', - 'application/x-www-form-urlencoded' - ) !== false + str_contains($this->request->getHeader('Content-Type') ?? '', 'application/x-www-form-urlencoded') ) ) { $value = false; - } elseif ($value !== null && \in_array($type, $types)) { - \settype($value, $type); + } elseif ($value !== null && \in_array($type, $types, true)) { + settype($value, $type); } $arguments[] = $value; diff --git a/lib/private/AppFramework/Http/Request.php b/lib/private/AppFramework/Http/Request.php index e9e0e6cabdba..2f6bf6993b66 100644 --- a/lib/private/AppFramework/Http/Request.php +++ b/lib/private/AppFramework/Http/Request.php @@ -168,7 +168,7 @@ public function setUrlParameters(array $parameters): void { * Countable method * @return int */ - public function count() { + public function count(): int { return \count(\array_keys($this->items['parameters'])); } @@ -192,28 +192,28 @@ public function count() { * @param string $offset The key to lookup * @return boolean */ - public function offsetExists($offset) { + public function offsetExists($offset): bool { return isset($this->items['parameters'][$offset]); } /** * @see offsetExists */ - public function offsetGet($offset) { + public function offsetGet($offset): mixed { return $this->items['parameters'][$offset] ?? null; } /** * @see offsetExists */ - public function offsetSet($offset, $value) { + public function offsetSet($offset, $value): void { throw new \RuntimeException('You cannot change the contents of the request object'); } /** * @see offsetExists */ - public function offsetUnset($offset) { + public function offsetUnset($offset): void { throw new \RuntimeException('You cannot change the contents of the request object'); } @@ -324,10 +324,10 @@ public function getHeader(string $name): ?string { * 1. URL parameters * 2. POST parameters * 3. GET parameters - * @param mixed $default If the key is not found, this value will be returned + * @param mixed|null $default If the key is not found, this value will be returned * @return mixed the content of the array */ - public function getParam($key, $default = null) { + public function getParam(string $key, mixed $default = null): mixed { return $this->parameters[$key] ?? $default; } @@ -336,7 +336,7 @@ public function getParam($key, $default = null) { * (as GET or POST) or through the URL by the route * @return array the array with all parameters */ - public function getParams() { + public function getParams(): array { return $this->parameters; } @@ -344,7 +344,7 @@ public function getParams() { * Returns the method of the request * @return string the method of the request (POST, GET, etc) */ - public function getMethod() { + public function getMethod(): string { return $this->method; } @@ -391,8 +391,8 @@ protected function getContent() { if ($this->method === 'PUT' && $this->getHeader('Content-Length') !== 0 && $this->getHeader('Content-Length') !== null - && \strpos($this->getHeader('Content-Type') ?? '', 'application/x-www-form-urlencoded') === false - && \strpos($this->getHeader('Content-Type') ?? '', 'application/json') === false + && !str_contains($this->getHeader('Content-Type') ?? '', 'application/x-www-form-urlencoded') + && !str_contains($this->getHeader('Content-Type') ?? '', 'application/json') ) { if ($this->content === false) { throw new \LogicException( @@ -431,7 +431,7 @@ protected function decodeContent() { // or post correctly } elseif ($this->method !== 'GET' && $this->method !== 'POST' - && \strpos($this->getHeader('Content-Type') ?? '', 'application/x-www-form-urlencoded') !== false) { + && str_contains($this->getHeader('Content-Type') ?? '', 'application/x-www-form-urlencoded')) { \parse_str(\file_get_contents($this->inputStream), $params); if (\is_array($params)) { $this->items['params'] = $params; @@ -586,8 +586,8 @@ public function getServerProtocol() { * * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0. */ - public function getHttpProtocol() { - $claimedProtocol = \strtoupper($this->server['SERVER_PROTOCOL']); + public function getHttpProtocol(): string { + $claimedProtocol = \strtoupper($this->server['SERVER_PROTOCOL'] ?? 'HTTP/1.1'); $validProtocols = [ 'HTTP/1.0', @@ -658,18 +658,18 @@ public function getRawPathInfo() { // strip off the script name's dir and file name // FIXME: Sabre does not really belong here - list($path, $name) = \Sabre\Uri\split($scriptName); + [$path, $name] = \Sabre\Uri\split($scriptName); if (!empty($path)) { - if ($path === $pathInfo || \strpos($pathInfo, $path.'/') === 0) { + if ($path === $pathInfo || str_starts_with($pathInfo, $path . '/')) { $pathInfo = \substr($pathInfo, \strlen($path)); } else { throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')"); } } - if (\strpos($pathInfo, "/$name") === 0) { - $pathInfo = \substr($pathInfo, \strlen($name) + 1); + if (str_starts_with($pathInfo, "/$name")) { + $pathInfo = \substr($pathInfo, \strlen($name ?? '') + 1); } - if (\is_string($name) && \strpos($pathInfo, $name) === 0) { + if (\is_string($name) && str_starts_with($pathInfo, $name)) { $pathInfo = \substr($pathInfo, \strlen($name)); } @@ -709,7 +709,7 @@ public function getPathInfo() { */ public function getScriptName() { $name = $this->server['SCRIPT_NAME']; - $overwriteWebRoot = $this->config->getSystemValue('overwritewebroot'); + $overwriteWebRoot = $this->config->getSystemValue('overwritewebroot') ?? ''; if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) { // FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous $serverRoot = \str_replace('\\', '/', \substr(__DIR__, 0, -\strlen('lib/private/appframework/http/'))); diff --git a/lib/private/AppFramework/Utility/SimpleContainer.php b/lib/private/AppFramework/Utility/SimpleContainer.php index 91d7b1a15484..1d8d820a22c8 100644 --- a/lib/private/AppFramework/Utility/SimpleContainer.php +++ b/lib/private/AppFramework/Utility/SimpleContainer.php @@ -47,31 +47,30 @@ private function buildClass(ReflectionClass $class) { $constructor = $class->getConstructor(); if ($constructor === null) { return $class->newInstance(); - } else { - $parameters = []; - foreach ($constructor->getParameters() as $parameter) { - $parameterClass = $parameter->getClass(); + } - // try to find out if it is a class or a simple parameter - if ($parameterClass === null) { - $resolveName = $parameter->getName(); - } else { - $resolveName = $parameterClass->name; - } + $parameters = []; + foreach ($constructor->getParameters() as $parameter) { + $resolveName = $parameter->getName(); - try { - $parameters[] = $this->query($resolveName); - } catch (QueryException $ex) { - if ($parameter->isDefaultValueAvailable()) { - $default = $parameter->getDefaultValue(); - $parameters[] = $default; - } else { - throw $ex; - } + $parameterType = $parameter->getType(); + // try to find out if it is a class or a simple parameter + if (($parameterType instanceof \ReflectionNamedType) && !$parameterType->isBuiltin()) { + $resolveName = $parameterType->getName(); + } + + try { + $parameters[] = $this->query($resolveName); + } catch (QueryException $ex) { + if ($parameter->isDefaultValueAvailable()) { + $default = $parameter->getDefaultValue(); + $parameters[] = $default; + } else { + throw $ex; } } - return $class->newInstanceArgs($parameters); } + return $class->newInstanceArgs($parameters); } /** diff --git a/lib/private/Archive/ZIP.php b/lib/private/Archive/ZIP.php index 897d6f671221..ba7f6eda226f 100644 --- a/lib/private/Archive/ZIP.php +++ b/lib/private/Archive/ZIP.php @@ -30,9 +30,11 @@ namespace OC\Archive; +use ZipArchive; + class ZIP extends Archive { /** - * @var \ZipArchive zip + * @var ZipArchive zip */ private $zip=null; private $path; @@ -42,8 +44,8 @@ class ZIP extends Archive { */ public function __construct($source) { $this->path=$source; - $this->zip=new \ZipArchive(); - if ($this->zip->open($source, \ZipArchive::CREATE)) { + $this->zip=new ZipArchive(); + if ($this->zip->open($source, ZipArchive::CREATE)) { } else { \OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, \OCP\Util::WARN); } diff --git a/lib/private/Authentication/Token/DefaultToken.php b/lib/private/Authentication/Token/DefaultToken.php index 64a7d676f7b0..43f1a33ab22b 100644 --- a/lib/private/Authentication/Token/DefaultToken.php +++ b/lib/private/Authentication/Token/DefaultToken.php @@ -102,7 +102,7 @@ public function getPassword() { return $this->password; } - public function jsonSerialize() { + public function jsonSerialize(): array { return [ 'id' => $this->id, 'name' => $this->name, diff --git a/lib/private/Avatar.php b/lib/private/Avatar.php index 293499b3464c..653eac875608 100644 --- a/lib/private/Avatar.php +++ b/lib/private/Avatar.php @@ -72,7 +72,7 @@ public function __construct(IStorage $storage, IL10N $l, User $user, ILogger $lo $this->path = $this->buildAvatarPath(); } - private function buildAvatarPath() { + private function buildAvatarPath(): string { return 'avatars/' . \substr_replace(\substr_replace(\md5($this->user->getUID()), '/', 4, 0), '/', 2, 0); } diff --git a/lib/private/BackgroundJob/JobList.php b/lib/private/BackgroundJob/JobList.php index 967238cff57b..f6a8421c1e9c 100644 --- a/lib/private/BackgroundJob/JobList.php +++ b/lib/private/BackgroundJob/JobList.php @@ -209,7 +209,7 @@ public function getNext() { } // skip jobs marked as disabled - $jobs_disabled = \explode(',', $this->config->getAppValue('backgroundjob', 'jobs_disabled', '')); + $jobs_disabled = \explode(',', $this->config->getAppValue('backgroundjob', 'jobs_disabled', '') ?? ''); if (\in_array($row['id'], $jobs_disabled, true)) { $this->logger->warning("Background job configuration has the job {$row['id']} as disabled. Skipping it"); return $this->getNext(); diff --git a/lib/private/Cache/CappedMemoryCache.php b/lib/private/Cache/CappedMemoryCache.php index 1e0b9eddef3c..38322c66bf06 100644 --- a/lib/private/Cache/CappedMemoryCache.php +++ b/lib/private/Cache/CappedMemoryCache.php @@ -60,19 +60,19 @@ public function clear($prefix = '') { return true; } - public function offsetExists($offset) { + public function offsetExists($offset): bool { return $this->hasKey($offset); } - public function &offsetGet($offset) { + public function &offsetGet($offset): mixed { return $this->cache[$offset]; } - public function offsetSet($offset, $value) { + public function offsetSet($offset, $value): void { $this->set($offset, $value); } - public function offsetUnset($offset) { + public function offsetUnset($offset): void { $this->remove($offset); } diff --git a/lib/private/DB/Connection.php b/lib/private/DB/Connection.php index bbb97a7a30b4..43ca61a7a897 100644 --- a/lib/private/DB/Connection.php +++ b/lib/private/DB/Connection.php @@ -439,7 +439,7 @@ public function inTransaction() { * @param string $param * @return string */ - public function escapeLikeParameter($param) { + public function escapeLikeParameter(string $param): string { return \addcslashes($param, '\\_%'); } diff --git a/lib/private/DB/MDB2SchemaManager.php b/lib/private/DB/MDB2SchemaManager.php index 044f0ff617cd..f39488e3639b 100644 --- a/lib/private/DB/MDB2SchemaManager.php +++ b/lib/private/DB/MDB2SchemaManager.php @@ -156,11 +156,15 @@ public function removeDBStructure($file) { * @return bool */ private function executeSchemaChange($schema) { - $this->conn->beginTransaction(); + if (!$this->conn->getDatabasePlatform() instanceof MySqlPlatform) { + $this->conn->beginTransaction(); + } foreach ($schema->toSql($this->conn->getDatabasePlatform()) as $sql) { - $this->conn->query($sql); + $this->conn->executeQuery($sql); + } + if (!$this->conn->getDatabasePlatform() instanceof MySQLPlatform) { + $this->conn->commit(); } - $this->conn->commit(); if ($this->conn->getDatabasePlatform() instanceof SqlitePlatform) { $this->conn->close(); diff --git a/lib/private/DB/MDB2SchemaReader.php b/lib/private/DB/MDB2SchemaReader.php index cf6be41ce7b0..e917cf0c9cab 100644 --- a/lib/private/DB/MDB2SchemaReader.php +++ b/lib/private/DB/MDB2SchemaReader.php @@ -54,9 +54,7 @@ public function __construct(IConfig $config, AbstractPlatform $platform) { * @return Schema */ public function loadSchemaFromFile($file, Schema $schema) { - $loadEntities = \libxml_disable_entity_loader(false); $xml = \simplexml_load_file($file); - \libxml_disable_entity_loader($loadEntities); foreach ($xml->children() as $child) { /** * @var \SimpleXMLElement $child diff --git a/lib/private/DB/Migrator.php b/lib/private/DB/Migrator.php index db8fdd4d69e1..39433d354a86 100644 --- a/lib/private/DB/Migrator.php +++ b/lib/private/DB/Migrator.php @@ -28,6 +28,7 @@ namespace OC\DB; use \Doctrine\DBAL\DBALException; +use Doctrine\DBAL\Platforms\MySqlPlatform; use \Doctrine\DBAL\Schema\Index; use \Doctrine\DBAL\Schema\Table; use \Doctrine\DBAL\Schema\Schema; @@ -191,26 +192,18 @@ protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $ $schemaDiff = $this->getDiff($targetSchema, $connection); - $connection->beginTransaction(); + if (!$connection->getDatabasePlatform() instanceof MySqlPlatform) { + $connection->beginTransaction(); + } $sqls = $schemaDiff->toSql($connection->getDatabasePlatform()); $step = 0; foreach ($sqls as $sql) { $this->emit($sql, $step++, \count($sqls)); - $connection->query($sql); + $connection->executeQuery($sql); + } + if (!$connection->getDatabasePlatform() instanceof MySQLPlatform) { + $connection->commit(); } - $connection->commit(); - } - - /** - * @param string $sourceName - * @param string $targetName - */ - protected function copyTable($sourceName, $targetName) { - $quotedSource = $this->connection->quoteIdentifier($sourceName); - $quotedTarget = $this->connection->quoteIdentifier($targetName); - - $this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')'); - $this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource); } /** diff --git a/lib/private/DB/QueryBuilder/CompositeExpression.php b/lib/private/DB/QueryBuilder/CompositeExpression.php index 22af55359f52..ff0b372947e8 100644 --- a/lib/private/DB/QueryBuilder/CompositeExpression.php +++ b/lib/private/DB/QueryBuilder/CompositeExpression.php @@ -68,7 +68,7 @@ public function add($part) { * * @return integer */ - public function count() { + public function count(): int { return $this->compositeExpression->count(); } diff --git a/lib/private/Diagnostics/Query.php b/lib/private/Diagnostics/Query.php index 7c6d2ce6a1ed..ea009deeaada 100644 --- a/lib/private/Diagnostics/Query.php +++ b/lib/private/Diagnostics/Query.php @@ -29,16 +29,11 @@ class Query implements IQuery, \JsonSerializable { private array $params; - private int $start; + private float $start; - private int $end; + private float $end; - /** - * @param string $sql - * @param array $params - * @param int $start - */ - public function __construct(string $sql, $params, $start) { + public function __construct(string $sql, array $params, float $start) { $this->sql = $sql; $this->params = $params; $this->start = $start; @@ -76,7 +71,7 @@ public function getDuration() { return $this->end - $this->start; } - public function jsonSerialize() { + public function jsonSerialize(): mixed { return [ 'query' => $this->sql, 'parameters' => $this->params, diff --git a/lib/private/Files/Cache/CacheEntry.php b/lib/private/Files/Cache/CacheEntry.php index f5e647848d03..871492e1eb26 100644 --- a/lib/private/Files/Cache/CacheEntry.php +++ b/lib/private/Files/Cache/CacheEntry.php @@ -36,24 +36,20 @@ public function __construct(array $data) { $this->data = $data; } - public function offsetSet($offset, $value) { + public function offsetSet($offset, $value): void { $this->data[$offset] = $value; } - public function offsetExists($offset) { + public function offsetExists($offset): bool { return isset($this->data[$offset]); } - public function offsetUnset($offset) { + public function offsetUnset($offset): void { unset($this->data[$offset]); } - public function offsetGet($offset) { - if (isset($this->data[$offset])) { - return $this->data[$offset]; - } else { - return null; - } + public function offsetGet($offset): mixed { + return $this->data[$offset] ?? null; } public function getId() { diff --git a/lib/private/Files/Cache/Wrapper/CacheJail.php b/lib/private/Files/Cache/Wrapper/CacheJail.php index c425e9767a6a..10eef736c02b 100644 --- a/lib/private/Files/Cache/Wrapper/CacheJail.php +++ b/lib/private/Files/Cache/Wrapper/CacheJail.php @@ -61,7 +61,7 @@ protected function getSourcePath($path) { * @param string $path * @return null|string the jailed path or null if the path is outside the jail */ - protected function getJailedPath($path) { + protected function getJailedPath(string $path) { if ($this->root === '') { return $path; } @@ -296,8 +296,11 @@ public function getIncomplete() { * @param int $id * @return string|null */ - public function getPathById($id) { + public function getPathById($id): ?string { $path = $this->cache->getPathById($id); + if ($path === null) { + return null; + } return $this->getJailedPath($path); } diff --git a/lib/private/Files/External/ConfigAdapter.php b/lib/private/Files/External/ConfigAdapter.php index 448b0e018adf..dd544dfc1d53 100644 --- a/lib/private/Files/External/ConfigAdapter.php +++ b/lib/private/Files/External/ConfigAdapter.php @@ -187,10 +187,10 @@ public function getMountsForUser(IUser $user, IStorageFactory $loader) { * fill in the correct values for $user * * @param string $user user value - * @param string|array $input + * @param array|string $input * @return string */ - private function setUserVars($user, $input) { + private function setUserVars(string $user, array|string $input): array|string { if (\is_array($input)) { foreach ($input as $key => $value) { if (\is_string($value)) { diff --git a/lib/private/Files/External/StorageConfig.php b/lib/private/Files/External/StorageConfig.php index 936f5628ef0c..407dff485551 100644 --- a/lib/private/Files/External/StorageConfig.php +++ b/lib/private/Files/External/StorageConfig.php @@ -391,10 +391,8 @@ public function setType($type) { /** * Serialize config to JSON - * - * @return array */ - public function jsonSerialize() { + public function jsonSerialize(): array { $result = []; if ($this->id !== null) { $result['id'] = $this->id; diff --git a/lib/private/Files/External/StoragesBackendService.php b/lib/private/Files/External/StoragesBackendService.php index fc7a2664abb6..83840ee4f143 100644 --- a/lib/private/Files/External/StoragesBackendService.php +++ b/lib/private/Files/External/StoragesBackendService.php @@ -70,7 +70,7 @@ public function __construct( } $this->userMountingBackends = \explode( ',', - $this->config->getAppValue('files_external', 'user_mounting_backends', '') + $this->config->getAppValue('files_external', 'user_mounting_backends', '') ?? '' ); // if no backend is in the list an empty string is in the array and user mounting is disabled diff --git a/lib/private/Files/FileInfo.php b/lib/private/Files/FileInfo.php index 1a3d927e566d..a2ff1f7f16f9 100644 --- a/lib/private/Files/FileInfo.php +++ b/lib/private/Files/FileInfo.php @@ -85,30 +85,32 @@ public function __construct($path, $storage, $internalPath, $data, $mount, $owne $this->owner = $owner; } - public function offsetSet($offset, $value) { + public function offsetSet($offset, $value): void { $this->data[$offset] = $value; } - public function offsetExists($offset) { + public function offsetExists($offset): bool { return isset($this->data[$offset]); } - public function offsetUnset($offset) { + public function offsetUnset($offset): void { unset($this->data[$offset]); } - public function offsetGet($offset) { + public function offsetGet($offset): mixed { if ($offset === 'type') { return $this->getType(); - } elseif ($offset === 'etag') { + } + + if ($offset === 'etag') { return $this->getEtag(); - } elseif ($offset === 'permissions') { + } + + if ($offset === 'permissions') { return $this->getPermissions(); - } elseif (isset($this->data[$offset])) { - return $this->data[$offset]; - } else { - return null; } + + return $this->data[$offset] ?? null; } /** @@ -341,6 +343,6 @@ public function addSubEntry($data, $entryPath) { * @inheritdoc */ public function getChecksum() { - return $this->data['checksum']; + return $this->data['checksum'] ?? ''; } } diff --git a/lib/private/Files/Storage/Wrapper/Encryption.php b/lib/private/Files/Storage/Wrapper/Encryption.php index 906568d088da..b859608dd70f 100644 --- a/lib/private/Files/Storage/Wrapper/Encryption.php +++ b/lib/private/Files/Storage/Wrapper/Encryption.php @@ -988,9 +988,9 @@ protected function getHeaderSize($path) { $path = $realFile; } } - $firstBlock = $this->readFirstBlock($path); + $firstBlock = $this->readFirstBlock($path) ?? ''; - if (\substr($firstBlock, 0, \strlen(Util::HEADER_START)) === Util::HEADER_START) { + if (str_starts_with($firstBlock, Util::HEADER_START)) { $headerSize = $this->util->getHeaderSize(); } diff --git a/lib/private/Files/Stream/Close.php b/lib/private/Files/Stream/Close.php index 4810d01150a8..421173d2bc2e 100644 --- a/lib/private/Files/Stream/Close.php +++ b/lib/private/Files/Stream/Close.php @@ -28,6 +28,7 @@ * stream wrapper that provides a callback on stream close */ class Close { + public $context; private static $callBacks = []; private $path = ''; private $source; diff --git a/lib/private/Files/Stream/Dir.php b/lib/private/Files/Stream/Dir.php index 8b0034e0fb81..38735745bc72 100644 --- a/lib/private/Files/Stream/Dir.php +++ b/lib/private/Files/Stream/Dir.php @@ -28,6 +28,7 @@ class Dir { private static $dirs = []; private $name; private $index; + public $context; public function dir_opendir($path, $options) { $this->name = \substr($path, \strlen('fakedir://')); diff --git a/lib/private/Files/Stream/Encryption.php b/lib/private/Files/Stream/Encryption.php index 7ec3b2d6cccd..9c3244c2bd91 100644 --- a/lib/private/Files/Stream/Encryption.php +++ b/lib/private/Files/Stream/Encryption.php @@ -99,6 +99,9 @@ class Encryption extends Wrapper { /** @var array */ protected $expectedContextProperties; + /** @var string - keep this for property access in L224*/ + protected $sourceFileOfRename; + public function __construct() { $this->expectedContextProperties = [ 'source', @@ -199,11 +202,8 @@ public static function wrap( protected static function wrapSource($source, $context = [], $protocol = null, $class = null, $mode = 'r+') { try { \stream_wrapper_register($protocol, $class); - if (@\rewinddir($source) === false) { - $wrapped = \fopen($protocol . '://', $mode, false, $context); - } else { - $wrapped = \opendir($protocol . '://', $context); - } + \rewind($source); + $wrapped = \fopen($protocol . '://', $mode, false, $context); } catch (\BadMethodCallException $e) { \stream_wrapper_unregister($protocol); throw $e; diff --git a/lib/private/Files/Stream/Quota.php b/lib/private/Files/Stream/Quota.php index 1cb7c4c77370..2964da6a7d1c 100644 --- a/lib/private/Files/Stream/Quota.php +++ b/lib/private/Files/Stream/Quota.php @@ -32,6 +32,7 @@ * or: resource \OC\Files\Stream\Quota::wrap($stream, $limit) */ class Quota { + public $context; private static $streams = []; /** @@ -66,7 +67,7 @@ public static function clear() { * @return resource */ public static function wrap($stream, $limit) { - $id = \uniqid(); + $id = \uniqid('', true); self::register($id, $stream, $limit); $meta = \stream_get_meta_data($stream); return \fopen('quota://' . $id, $meta['mode']); @@ -77,9 +78,9 @@ public function stream_open($path, $mode, $options, &$opened_path) { if (isset(self::$streams[$id])) { list($this->source, $this->limit) = self::$streams[$id]; return true; - } else { - return false; } + + return false; } public function stream_seek($offset, $whence = SEEK_SET) { diff --git a/lib/private/Files/View.php b/lib/private/Files/View.php index 9bd55a420c3b..f46b2213023d 100644 --- a/lib/private/Files/View.php +++ b/lib/private/Files/View.php @@ -388,15 +388,15 @@ public function rmdir($path) { * * @return bool */ - protected function isShareFolderOrShareFolderParent($path) { - $shareFolder = \trim($this->config->getSystemValue('share_folder', '/'), '/'); + protected function isShareFolderOrShareFolderParent($path): bool { + $shareFolder = \trim($this->config->getSystemValue('share_folder', '/') ?? '', '/'); if ($shareFolder === '') { return false; } $user = \OC_User::getUser(); $shareFolderAbsolutePath = "/$user/files/$shareFolder"; $trimmedAbsolutePath = $this->getAbsolutePath(\trim($path, '/')); - return $shareFolderAbsolutePath === $trimmedAbsolutePath || \strpos($shareFolderAbsolutePath, "$trimmedAbsolutePath/") === 0; + return $shareFolderAbsolutePath === $trimmedAbsolutePath || \str_starts_with($shareFolderAbsolutePath, "$trimmedAbsolutePath/"); } /** @@ -1439,7 +1439,7 @@ public function getFileInfo($path, $includeMountPoints = true) { if (!Filesystem::isValidPath($path)) { return false; } - if (Cache\Scanner::isPartialFile($path)) { + if (Cache\Scanner::isPartialFile($path ?? '')) { return $this->getPartFileInfo($path); } $relativePath = $path; @@ -1972,7 +1972,7 @@ public function verifyPath($path, $fileName) { * @return string[] */ private function getParents($path) { - $path = \trim($path, '/'); + $path = \trim($path ?? '', '/'); if (!$path) { return []; } diff --git a/lib/private/Image/BmpToResource.php b/lib/private/Image/BmpToResource.php index 4eb87814aa61..b62ab6edf47c 100644 --- a/lib/private/Image/BmpToResource.php +++ b/lib/private/Image/BmpToResource.php @@ -46,8 +46,7 @@ class BmpToResource { /** @var string[][] $pixelArray */ private $pixelArray; - /** @var resource $resource */ - private $resource; + private \GdImage $resource; /** @var array $bytesPerDepth */ private $bytesPerDepth = [ @@ -69,10 +68,9 @@ public function __construct($fileName) { } /** - * @return resource * @throws \Exception */ - public function toResource() { + public function toResource(): \GdImage { try { $this->header = $this->readBitmapHeader(); $this->header += $this->readDibHeader(); @@ -87,10 +85,11 @@ public function toResource() { $this->pixelArray = $this->readPixelArray(); // create gd image - $this->resource = \imagecreatetruecolor($this->header['width'], $this->header['height']); - if ($this->resource === false) { + $resource = \imagecreatetruecolor($this->header['width'], $this->header['height']); + if ($resource === false) { throw new \RuntimeException('imagecreatetruecolor failed for file ' . $this->getFilename() . '" with dimensions ' . $this->header['width'] . 'x' . $this->header['height']); } + $this->resource = $resource; $this->pixelArrayToImage(); } catch (\Exception $e) { @@ -149,7 +148,7 @@ private function readDibHeader() { } $validBitDepth = \array_keys($this->bytesPerDepth); - if (!\in_array($dibHeader['bits'], $validBitDepth)) { + if (!\in_array($dibHeader['bits'], $validBitDepth, true)) { throw new \UnexpectedValueException('Bit Depth ' . $dibHeader['bits'] . ' in ' . $this->getFilename() . ' is not supported'); } @@ -159,7 +158,7 @@ private function readDibHeader() { private function fixImageSize($header) { // No compression - calculate it in our own if ($header['compression'] === self::COMPRESSION_BI_RGB) { - $bytesPerRow = \intval(\floor(($header['bits'] * $header['width'] + 31) / 32) * 4); + $bytesPerRow = (int)(\floor(($header['bits'] * $header['width'] + 31) / 32) * 4); $imageSize = $bytesPerRow * \abs($header['height']); } else { $imageSize = $this->file->getSize() - $this->header['offset']; @@ -196,7 +195,7 @@ private function readPixelArray() { $this->file->fseek($this->header['offset'], SEEK_SET); $pixelString = $this->readFile($this->header['imagesize']); - $bytesPerRow = \intval(\floor(($this->header['bits'] * $this->header['width'] + 31) / 32) * 4); + $bytesPerRow = (int)(\floor(($this->header['bits'] * $this->header['width'] + 31) / 32) * 4); $plainPixelArray = \str_split($pixelString, $bytesPerRow); // Positive height: Bottom row first. @@ -212,10 +211,7 @@ private function readPixelArray() { return $pixelArray; } - /** - * @return resource - */ - private function pixelArrayToImage() { + private function pixelArrayToImage(): \GdImage { $x = 0; $y = 0; foreach ($this->pixelArray as $pixelRow) { @@ -246,7 +242,7 @@ private function pixelArrayToImage() { private function getColors($raw) { $extra = \chr(0); // used to complement an argument to word or double word $colors = []; - if (\in_array($this->header['bits'], [32, 24])) { + if (\in_array($this->header['bits'], [32, 24], true)) { $colors = @\unpack('V', $raw . $extra); } elseif ($this->header['bits'] === 16) { $colors = @\unpack('v', $raw); @@ -264,8 +260,7 @@ function ($i) { ); } - $colors = \array_values($colors); - return $colors; + return \array_values($colors); } /** diff --git a/lib/private/IntegrityCheck/Checker.php b/lib/private/IntegrityCheck/Checker.php index f69de935766f..610e99e22595 100644 --- a/lib/private/IntegrityCheck/Checker.php +++ b/lib/private/IntegrityCheck/Checker.php @@ -38,6 +38,7 @@ use OCP\IConfig; use OCP\ITempManager; use phpseclib3\Crypt\RSA; +use phpseclib3\Crypt\RSA\PrivateKey; use phpseclib3\File\X509; /** @@ -342,7 +343,11 @@ private function verify($signaturePath, $basePath, $certificateCN, $force = fals return []; } - $signatureData = \json_decode($this->fileAccessHelper->file_get_contents($signaturePath), true); + $content = $this->fileAccessHelper->file_get_contents($signaturePath); + if (!$content) { + throw new MissingSignatureException('Signature data not found.'); + } + $signatureData = \json_decode($content, true); if (!\is_array($signatureData)) { throw new MissingSignatureException('Signature data not found.'); } @@ -464,7 +469,8 @@ public function getResults() { return \json_decode($cachedResults, true); } - return \json_decode($this->getAppValue(self::CACHE_KEY, '{}'), true); + $v = $this->getAppValue(self::CACHE_KEY, '{}') ?? '{}'; + return \json_decode($v, true); } /** diff --git a/lib/private/IntegrityCheck/Iterator/ExcludeFileByNameFilterIterator.php b/lib/private/IntegrityCheck/Iterator/ExcludeFileByNameFilterIterator.php index 1d6e78bdcec5..651355a7134f 100644 --- a/lib/private/IntegrityCheck/Iterator/ExcludeFileByNameFilterIterator.php +++ b/lib/private/IntegrityCheck/Iterator/ExcludeFileByNameFilterIterator.php @@ -65,10 +65,7 @@ class ExcludeFileByNameFilterIterator extends \RecursiveFilterIterator { '|/core/js/mimetypelist.js$|', // this file can be regenerated with additional entries with occ maintenance:mimetype:update-js ]; - /** - * @return bool - */ - public function accept() { + public function accept(): bool { /** @var \SplFileInfo $current */ $current = $this->current(); diff --git a/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php b/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php index b3030f6b74f8..58437fcae528 100644 --- a/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php +++ b/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php @@ -49,10 +49,7 @@ public function __construct(\RecursiveIterator $iterator, $root = '') { $this->excludedFolders = \array_merge($excludedFolders, $appFolders); } - /** - * @return bool - */ - public function accept() { + public function accept(): bool { return !\in_array( $this->current()->getPathName(), $this->excludedFolders, diff --git a/lib/private/L10N/L10N.php b/lib/private/L10N/L10N.php index 9e663d84943c..cb88988d823f 100644 --- a/lib/private/L10N/L10N.php +++ b/lib/private/L10N/L10N.php @@ -70,14 +70,16 @@ public function getLanguageCode() { /** * Translating + * * @param string $text The text we need a translation for - * @param array $parameters default:array() Parameters for sprintf + * @param array|mixed $parameters default:array() Parameters for sprintf * @return string Translation or the same text * * Returns the translation. If no translation is found, $text will be * returned. */ - public function t($text, $parameters = []) { + public function t(string $text, $parameters = []): string { + $parameters = \is_array($parameters) ? $parameters : [$parameters]; return (string) new \OC_L10N_String($this, $text, $parameters); } diff --git a/lib/private/Lock/MemcacheLockingProvider.php b/lib/private/Lock/MemcacheLockingProvider.php index 27bd5b66f372..8682930bc0da 100644 --- a/lib/private/Lock/MemcacheLockingProvider.php +++ b/lib/private/Lock/MemcacheLockingProvider.php @@ -55,7 +55,7 @@ private function setTTL($path) { public function isLocked($path, $type) { $lockValue = $this->memcache->get($path); if ($type === self::LOCK_SHARED) { - return $lockValue > 0; + return (int)($lockValue) > 0; } if ($type === self::LOCK_EXCLUSIVE) { diff --git a/lib/private/Log/Owncloud.php b/lib/private/Log/Owncloud.php index 54f21dadde46..cecf7f21612b 100644 --- a/lib/private/Log/Owncloud.php +++ b/lib/private/Log/Owncloud.php @@ -68,71 +68,76 @@ public static function write($app, $message, $level, $conditionalLogFile = null) } public static function writeExtra($app, $message, $level, $conditionalLogFile, $extraFields = []) { - $config = \OC::$server->getSystemConfig(); - - // default to ISO8601 - $format = $config->getValue('logdateformat', 'c'); - $logTimeZone = $config->getValue("logtimezone", 'UTC'); try { - $timezone = new \DateTimeZone($logTimeZone); - } catch (\Exception $e) { - $timezone = new \DateTimeZone('UTC'); - } - $time = \DateTime::createFromFormat("U.u", \number_format(\microtime(true), 4, ".", "")); - if ($time === false) { - $time = new \DateTime(null, $timezone); - } else { - // apply timezone if $time is created from UNIX timestamp - $time->setTimezone($timezone); - } - $request = \OC::$server->getRequest(); - $reqId = $request->getId(); - $remoteAddr = $request->getRemoteAddress(); - // remove username/passwords from URLs before writing the to the log file - $time = $time->format($format); - $url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--'; - $method = \is_string($request->getMethod()) ? $request->getMethod() : '--'; - if (\OC::$server->getConfig()->getSystemValue('installed', false)) { - $user = (\OC_User::getUser()) ? \OC_User::getUser() : '--'; - } else { - $user = '--'; - } - $entry = \compact( - 'reqId', - 'level', - 'time', - 'remoteAddr', - 'user', - 'app', - 'method', - 'url', - 'message' - ); + $config = \OC::$server->getSystemConfig(); - if (!empty($extraFields)) { - // augment with additional fields - $entry = \array_merge($entry, $extraFields); - } + // default to ISO8601 + $format = $config->getValue('logdateformat', 'c'); + $logTimeZone = $config->getValue("logtimezone", 'UTC'); + try { + $timezone = new \DateTimeZone($logTimeZone); + } catch (\Exception $e) { + $timezone = new \DateTimeZone('UTC'); + } + $time = \DateTime::createFromFormat("U.u", \number_format(\microtime(true), 4, ".", "")); + if ($time === false) { + $time = new \DateTime(null, $timezone); + } else { + // apply timezone if $time is created from UNIX timestamp + $time->setTimezone($timezone); + } + $request = \OC::$server->getRequest(); + $reqId = $request->getId(); + $remoteAddr = $request->getRemoteAddress(); + // remove username/passwords from URLs before writing the to the log file + $time = $time->format($format); + $url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--'; + $method = \is_string($request->getMethod()) ? $request->getMethod() : '--'; + if (\OC::$server->getConfig()->getSystemValue('installed', false)) { + $user = (\OC_User::getUser()) ? \OC_User::getUser() : '--'; + } else { + $user = '--'; + } + $entry = \compact( + 'reqId', + 'level', + 'time', + 'remoteAddr', + 'user', + 'app', + 'method', + 'url', + 'message' + ); - $entry = \json_encode($entry); - if ($conditionalLogFile !== null) { - if ($conditionalLogFile[0] !== '/') { - $conditionalLogFile = \OC::$server->getConfig()->getSystemValue('datadirectory') . "/" . $conditionalLogFile; + if (!empty($extraFields)) { + // augment with additional fields + $entry = \array_merge($entry, $extraFields); } - self::createLogFile($conditionalLogFile); - $handle = @\fopen($conditionalLogFile, 'a'); - } else { - self::createLogFile(self::$logFile); - $handle = @\fopen(self::$logFile, 'a'); - } - if ($handle) { - \fwrite($handle, $entry."\n"); - \fclose($handle); - } else { - // Fall back to error_log - \error_log($entry); - } - if (\php_sapi_name() === 'cli-server') { + + $entry = \json_encode($entry); + if ($conditionalLogFile !== null) { + if ($conditionalLogFile[0] !== '/') { + $conditionalLogFile = \OC::$server->getConfig()->getSystemValue('datadirectory') . "/" . $conditionalLogFile; + } + self::createLogFile($conditionalLogFile); + $handle = @\fopen($conditionalLogFile, 'a'); + } else { + self::createLogFile(self::$logFile); + $handle = @\fopen(self::$logFile, 'a'); + } + if ($handle) { + \fwrite($handle, $entry."\n"); + \fclose($handle); + } else { + // Fall back to error_log + \error_log($entry); + } + if (\php_sapi_name() === 'cli-server') { + \error_log($message, 4); + } + } catch(\Exception $ex) { + \error_log($ex->getMessage()); \error_log($message, 4); } } diff --git a/lib/private/Mail/Logger.php b/lib/private/Mail/Logger.php new file mode 100644 index 000000000000..81f0240f3913 --- /dev/null +++ b/lib/private/Mail/Logger.php @@ -0,0 +1,20 @@ +log[] = [$level, $message, $context]; + } + + /** + * @throws \JsonException + */ + public function toJSON(): string { + return json_encode($this->log, JSON_THROW_ON_ERROR); + } +} diff --git a/lib/private/Mail/Mailer.php b/lib/private/Mail/Mailer.php index 62b33d89f22d..8a5f3eed175c 100644 --- a/lib/private/Mail/Mailer.php +++ b/lib/private/Mail/Mailer.php @@ -23,9 +23,17 @@ use Egulias\EmailValidator\EmailValidator; use Egulias\EmailValidator\Validation\RFCValidation; +use OC_Defaults; use OCP\IConfig; use OCP\Mail\IMailer; use OCP\ILogger; +use Psr\Log\LoggerInterface; +use Symfony\Component\Mailer\Exception\TransportExceptionInterface; +use Symfony\Component\Mailer\Transport\SendmailTransport; +use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport; +use Symfony\Component\Mailer\Transport\Smtp\Stream\SocketStream; +use Symfony\Component\Mailer\Transport\TransportInterface; +use Symfony\Component\Mime\Email; /** * Class Mailer provides some basic functions to create a mail message that can be used in combination with @@ -46,24 +54,15 @@ * @package OC\Mail */ class Mailer implements IMailer { - /** @var \Swift_SmtpTransport|\Swift_SendmailTransport Cached transport */ - private $instance = null; - /** @var IConfig */ - private $config; - /** @var ILogger */ - private $logger; - /** @var \OC_Defaults */ - private $defaults; + private ?TransportInterface $instance = null; + private IConfig $config; + private ILogger $logger; + private OC_Defaults $defaults; - /** - * @param IConfig $config - * @param ILogger $logger - * @param \OC_Defaults $defaults - */ public function __construct( IConfig $config, ILogger $logger, - \OC_Defaults $defaults + OC_Defaults $defaults ) { $this->config = $config; $this->logger = $logger; @@ -72,11 +71,9 @@ public function __construct( /** * Creates a new message object that can be passed to send() - * - * @return Message */ - public function createMessage() { - return new Message(new \Swift_Message()); + public function createMessage(): Message { + return new Message(new Email()); } /** @@ -89,18 +86,34 @@ public function createMessage() { * @throws \Exception In case it was not possible to send the message. (for example if an invalid mail address * has been supplied.) */ - public function send(Message $message) { - $debugMode = $this->config->getSystemValue('mail_smtpdebug', false); - + public function send(Message $message): array { if (!\is_array($message->getFrom()) || \count($message->getFrom()) === 0) { $message->setFrom([\OCP\Util::getDefaultEmailAddress($this->defaults->getName())]); } - $failedRecipients = []; - - $mailer = $this->getInstance(); - - $mailer->send($message->getSwiftMessage(), $failedRecipients); + $debugMode = $this->config->getSystemValue('mail_smtpdebug', false); + $logger = $debugMode ? new Logger() : null; + + try { + $this->getInstance($logger ?? null)->send($message->getMessage()); + } catch (TransportExceptionInterface $e) { + # in case of exception it is expected that none of the mails has been sent + $failedRecipients = []; + + $recipients = array_merge($message->getTo(), $message->getCc(), $message->getBcc()); + array_walk($recipients, static function ($value, $key) use (&$failedRecipients) { + if (is_numeric($key)) { + $failedRecipients[] = $value; + } else { + $failedRecipients[] = $key; + } + }); + + $this->logger->logException($e, ['failed-recipients' => $recipients]); + + # list of failed recipients is not added by intention to not accidentally disclose private data + throw new \RuntimeException("Failed to deliver email", 0, $e); + } $allRecipients = []; if (!empty($message->getTo())) { @@ -119,10 +132,11 @@ public function send(Message $message) { 'app' => 'core', 'from' => \json_encode($message->getFrom()), 'recipients' => \json_encode($allRecipients), - 'subject' => $message->getSubject() + 'subject' => $message->getSubject(), + 'mail_log' => ($logger !== null) ? $logger->toJSON() : null, ]); - return $failedRecipients; + return []; } /** @@ -131,9 +145,9 @@ public function send(Message $message) { * @param string $email Email address to be validated * @return bool True if the mail address is valid, false otherwise */ - public function validateMailAddress($email) { - $validator = new EmailValidator(); - return $validator->isValid($this->convertEmail($email), new RFCValidation()); + public function validateMailAddress(string $email): bool { + return (new EmailValidator()) + ->isValid($this->convertEmail($email), new RFCValidation()); } /** @@ -144,12 +158,12 @@ public function validateMailAddress($email) { * @param string $email * @return string Converted mail address if `idn_to_ascii` exists */ - protected function convertEmail($email) { + protected function convertEmail(string $email): string { if (!\function_exists('idn_to_ascii') || \strpos($email, '@') === false) { return $email; } - list($name, $domain) = \explode('@', $email, 2); + [$name, $domain] = \explode('@', $email, 2); if (\defined('INTL_IDNA_VARIANT_UTS46')) { $domain = \idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); } else { @@ -158,80 +172,50 @@ protected function convertEmail($email) { return $name.'@'.$domain; } - /** - * Returns whatever transport is configured within the config - * - * @return \Swift_SmtpTransport|\Swift_SendmailTransport - */ - protected function getInstance() { + protected function getInstance(?LoggerInterface $logger = null): TransportInterface { if ($this->instance !== null) { return $this->instance; } $mailMode = $this->config->getSystemValue('mail_smtpmode', 'php'); if ($mailMode === 'smtp') { - $instance = $this->getSmtpInstance(); + $transport = $this->getSmtpInstance($logger ?? null); } else { - // FIXME: Move into the return statement but requires proper testing - // for SMTP and mail as well. Thus not really doable for a - // minor release. - $instance = new \Swift_Mailer($this->getSendMailInstance()); - } - - // Register plugins - - // Enable logger if debug mode is enabled - if ($this->config->getSystemValue('mail_smtpdebug', false)) { - $mailLogger = new \Swift_Plugins_Loggers_ArrayLogger(); - $instance->registerPlugin(new \Swift_Plugins_LoggerPlugin($mailLogger)); + $transport = $this->getSendMailInstance($logger ?? null); } - // Enable antiflood on smtp connection (defaults to 100 mails before reconnect) - $instance->registerPlugin(new \Swift_Plugins_AntiFloodPlugin()); - - $this->instance = $instance; + $this->instance = $transport; return $this->instance; } - /** - * Returns the SMTP transport - * - * @return \Swift_SmtpTransport - */ - protected function getSmtpInstance() { - $transport = new \Swift_SmtpTransport(); - $transport->setTimeout($this->config->getSystemValue('mail_smtptimeout', 10)); - $transport->setHost($this->config->getSystemValue('mail_smtphost', '127.0.0.1')); - $transport->setPort($this->config->getSystemValue('mail_smtpport', 25)); + protected function getSmtpInstance(?LoggerInterface $logger): EsmtpTransport { + $timeout = $this->config->getSystemValue('mail_smtptimeout', 10); + $host = $this->config->getSystemValue('mail_smtphost', '127.0.0.1'); + $port = $this->config->getSystemValue('mail_smtpport', 25); + $smtpSecurity = $this->config->getSystemValue('mail_smtpsecure', ''); + $tls = $smtpSecurity === 'ssl' ? true : null; + $transport = new EsmtpTransport($host, $port, $tls, null, $logger); if ($this->config->getSystemValue('mail_smtpauth', false)) { $transport->setUsername($this->config->getSystemValue('mail_smtpname', '')); $transport->setPassword($this->config->getSystemValue('mail_smtppassword', '')); - $transport->setAuthMode($this->config->getSystemValue('mail_smtpauthtype', 'LOGIN')); } - $smtpSecurity = $this->config->getSystemValue('mail_smtpsecure', ''); - if (!empty($smtpSecurity)) { - $transport->setEncryption($smtpSecurity); + $stream = $transport->getStream(); + if ($stream instanceof SocketStream) { + $stream->setTimeout($timeout); } - $transport->start(); + return $transport; } - /** - * Returns the sendmail transport - * - * @return \Swift_SendmailTransport - */ - protected function getSendMailInstance() { - switch ($this->config->getSystemValue('mail_smtpmode', 'sendmail')) { - case 'qmail': - $binaryPath = '/var/qmail/bin/sendmail'; - break; - default: - $binaryPath = '/usr/sbin/sendmail'; - break; + protected function getSendMailInstance(?LoggerInterface $logger = null): SendmailTransport { + $i = $this->config->getSystemValue('mail_smtpmode', 'sendmail'); + if ($i === 'qmail') { + $binaryPath = '/var/qmail/bin/sendmail'; + } else { + $binaryPath = '/usr/sbin/sendmail'; } - return new \Swift_SendmailTransport($binaryPath . ' -bs'); + return new SendmailTransport($binaryPath . ' -bs', null, $logger); } } diff --git a/lib/private/Mail/Message.php b/lib/private/Mail/Message.php index 12633ff76ad6..88ce719abf07 100644 --- a/lib/private/Mail/Message.php +++ b/lib/private/Mail/Message.php @@ -22,55 +22,38 @@ namespace OC\Mail; -use Swift_Message; +use Symfony\Component\Mime\Address; +use Symfony\Component\Mime\Email; /** - * Class Message provides a wrapper around SwiftMail + * Class Message provides a wrapper around Symfony\Component\Mime\Email * * @package OC\Mail */ class Message { - /** @var Swift_Message */ - private $swiftMessage; + private Email $message; + private array $from = []; + private array $replyTo = []; + private array $to = []; + private array $cc = []; + private array $bcc = []; - /** - * @param Swift_Message $swiftMessage - */ - public function __construct(Swift_Message $swiftMessage) { - $this->swiftMessage = $swiftMessage; + public function __construct(Email $swiftMessage) { + $this->message = $swiftMessage; } /** - * SwiftMailer does currently not work with IDN domains, this function therefore converts the domains - * FIXME: Remove this once SwiftMailer supports IDN - * * @param array $addresses Array of mail addresses, key will get converted - * @return array Converted addresses if `idn_to_ascii` exists + * @return Address[] Converted addresses if `idn_to_ascii` exists */ - protected function convertAddresses($addresses) { - if (!\function_exists('idn_to_ascii')) { - return $addresses; - } - + protected function convertAddresses(array $addresses): array { $convertedAddresses = []; foreach ($addresses as $email => $readableName) { - if (!\is_numeric($email)) { - list($name, $domain) = \explode('@', $email, 2); - if (\defined('INTL_IDNA_VARIANT_UTS46')) { - $domain = \idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); - } else { - $domain = \idn_to_ascii($domain); - } - $convertedAddresses[$name.'@'.$domain] = $readableName; + if (\is_numeric($email)) { + $convertedAddresses[] = new Address($readableName); } else { - list($name, $domain) = \explode('@', $readableName, 2); - if (\defined('INTL_IDNA_VARIANT_UTS46')) { - $domain = \idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); - } else { - $domain = \idn_to_ascii($domain); - } - $convertedAddresses[$email] = $name.'@'.$domain; + $convertedAddresses[] = new Address($email, $readableName ?? ''); } } @@ -83,12 +66,11 @@ protected function convertAddresses($addresses) { * If no "From" address is used \OC\Mail\Mailer will use mail_from_address and mail_domain from config.php * * @param array $addresses Example: array('sender@domain.org', 'other@domain.org' => 'A name') - * @return $this */ - public function setFrom(array $addresses) { - $addresses = $this->convertAddresses($addresses); + public function setFrom(array $addresses): Message { + $this->message->from(...$this->convertAddresses($addresses)); - $this->swiftMessage->setFrom($addresses); + $this->from = $addresses; return $this; } @@ -97,42 +79,36 @@ public function setFrom(array $addresses) { * * @return array */ - public function getFrom() { - return $this->swiftMessage->getFrom(); + public function getFrom(): array { + return $this->from; } /** * Set the Reply-To address of this message - * - * @param array $addresses - * @return $this */ - public function setReplyTo(array $addresses) { - $addresses = $this->convertAddresses($addresses); + public function setReplyTo(array $addresses): Message { + $this->message->replyTo(...$this->convertAddresses($addresses)); - $this->swiftMessage->setReplyTo($addresses); + $this->replyTo = $addresses; return $this; } /** * Returns the Reply-To address of this message - * - * @return array */ - public function getReplyTo() { - return $this->swiftMessage->getReplyTo(); + public function getReplyTo(): array { + return $this->replyTo; } /** - * Set the to addresses of this message. + * Set the to-addresses of this message. * * @param array $recipients Example: array('recipient@domain.org', 'other@domain.org' => 'A name') - * @return $this */ - public function setTo(array $recipients) { - $recipients = $this->convertAddresses($recipients); + public function setTo(array $recipients): Message { + $this->message->to(...$this->convertAddresses($recipients)); - $this->swiftMessage->setTo($recipients); + $this->to = $recipients; return $this; } @@ -141,82 +117,68 @@ public function setTo(array $recipients) { * * @return array */ - public function getTo() { - return $this->swiftMessage->getTo(); + public function getTo(): array { + return $this->to; } /** * Set the CC recipients of this message. * * @param array $recipients Example: array('recipient@domain.org', 'other@domain.org' => 'A name') - * @return $this */ - public function setCc(array $recipients) { - $recipients = $this->convertAddresses($recipients); + public function setCc(array $recipients): Message { + $this->message->cc(...$this->convertAddresses($recipients)); - $this->swiftMessage->setCc($recipients); + $this->cc = $recipients; return $this; } /** * Get the cc address of this message. - * - * @return array */ - public function getCc() { - return $this->swiftMessage->getCc(); + public function getCc(): array { + return $this->cc; } /** * Set the BCC recipients of this message. * * @param array $recipients Example: array('recipient@domain.org', 'other@domain.org' => 'A name') - * @return $this */ - public function setBcc(array $recipients) { - $recipients = $this->convertAddresses($recipients); + public function setBcc(array $recipients): Message { + $this->message->bcc(...$this->convertAddresses($recipients)); - $this->swiftMessage->setBcc($recipients); + $this->bcc = $recipients; return $this; } /** * Get the Bcc address of this message. - * - * @return array */ - public function getBcc() { - return $this->swiftMessage->getBcc(); + public function getBcc(): array { + return $this->bcc; } /** * Set the subject of this message. - * - * @param $subject - * @return $this */ - public function setSubject($subject) { - $this->swiftMessage->setSubject($subject); + public function setSubject(string $subject): Message { + $this->message->subject($subject); return $this; } /** - * Get the from subject of this message. - * - * @return string + * Get the subject of this message. */ - public function getSubject() { - return $this->swiftMessage->getSubject(); + public function getSubject(): string { + return $this->message->getSubject(); } /** * Set the plain-text body of this message. - * - * @param string $body - * @return $this */ - public function setPlainBody($body) { - $this->swiftMessage->setBody($body); + public function setPlainBody(string $body): Message { + $this->message->text($body); return $this; } @@ -225,8 +187,8 @@ public function setPlainBody($body) { * * @return string */ - public function getPlainBody() { - return $this->swiftMessage->getBody(); + public function getPlainBody(): string { + return $this->message->getTextBody() ?? ''; } /** @@ -235,26 +197,27 @@ public function getPlainBody() { * @param string $body * @return $this */ - public function setHtmlBody($body) { - $this->swiftMessage->addPart($body, 'text/html'); + public function setHtmlBody(string $body): Message { + $this->message->html($body); return $this; } - /** - * Get's the underlying SwiftMessage - * @return Swift_Message - */ - public function getSwiftMessage() { - return $this->swiftMessage; + public function getMessage(): Email { + return $this->message; } - /** - * @param string $body - * @param string $contentType - * @return $this - */ - public function setBody($body, $contentType) { - $this->swiftMessage->setBody($body, $contentType); + public function setBody(string $body, string $contentType): Message { + if ($contentType === 'text/html') { + $this->message->html($body); + } else { + $this->message->text($body); + } + + return $this; + } + + public function attach($body, string $name = null, string $contentType = null): self { + $this->message->attach($body, $name, $contentType); return $this; } } diff --git a/lib/private/Memcache/APCu.php b/lib/private/Memcache/APCu.php index c3fdc6f15b9b..b14c53763767 100644 --- a/lib/private/Memcache/APCu.php +++ b/lib/private/Memcache/APCu.php @@ -35,7 +35,7 @@ class APCu extends Cache implements IMemcache { use CADTrait; - public function get($key) { + public function get($key): mixed { $result = \apcu_fetch($this->getPrefix() . $key, $success); if (!$success) { return null; @@ -43,7 +43,7 @@ public function get($key) { return $result; } - public function set($key, $value, $ttl = 0) { + public function set($key, $value, $ttl = 0): mixed { return \apcu_store($this->getPrefix() . $key, $value, $ttl); } @@ -58,7 +58,8 @@ public function remove($key) { public function clear($prefix = '') { $ns = $this->getPrefix() . $prefix; $ns = \preg_quote($ns, '/'); - $iter = new \APCuIterator('/^' . $ns . '/', APC_ITER_KEY); + $iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY); + return \apcu_delete($iter); } @@ -105,7 +106,7 @@ public function dec($key, $step = 1) { * @param mixed $new * @return bool */ - public function cas($key, $old, $new) { + public function cas($key, $old, $new): bool { // apc only does cas for ints if (\is_int($old) && \is_int($new)) { return \apcu_cas($this->getPrefix() . $key, $old, $new); @@ -117,7 +118,7 @@ public function cas($key, $old, $new) { /** * @return bool */ - public static function isAvailable() { + public static function isAvailable(): bool { if (!\extension_loaded('apcu')) { return false; } diff --git a/lib/private/Memcache/ArrayCache.php b/lib/private/Memcache/ArrayCache.php index b5e0bd8b2604..41d164c4758f 100644 --- a/lib/private/Memcache/ArrayCache.php +++ b/lib/private/Memcache/ArrayCache.php @@ -28,14 +28,14 @@ class ArrayCache extends Cache implements IMemcache { /** @var array Array with the cached data */ - protected $cachedData = []; + protected array $cachedData = []; use CADTrait; /** * {@inheritDoc} */ - public function get($key) { + public function get($key): mixed { if ($this->hasKey($key)) { return $this->cachedData[$key]; } @@ -45,7 +45,7 @@ public function get($key) { /** * {@inheritDoc} */ - public function set($key, $value, $ttl = 0) { + public function set($key, $value, $ttl = 0): mixed { $this->cachedData[$key] = $value; return true; } @@ -94,9 +94,9 @@ public function add($key, $value, $ttl = 0) { // since this cache is not shared race conditions aren't an issue if ($this->hasKey($key)) { return false; - } else { - return $this->set($key, $value, $ttl); } + + return $this->set($key, $value, $ttl); } /** @@ -111,10 +111,10 @@ public function inc($key, $step = 1) { if (\is_int($oldValue)) { $this->set($key, $oldValue + $step); return $oldValue + $step; - } else { - $success = $this->add($key, $step); - return ($success) ? $step : false; } + + $success = $this->add($key, $step); + return ($success) ? $step : false; } /** @@ -129,9 +129,9 @@ public function dec($key, $step = 1) { if (\is_int($oldValue)) { $this->set($key, $oldValue - $step); return $oldValue - $step; - } else { - return false; } + + return false; } /** @@ -145,15 +145,12 @@ public function dec($key, $step = 1) { public function cas($key, $old, $new) { if ($this->get($key) === $old) { return $this->set($key, $new); - } else { - return false; } + + return false; } - /** - * {@inheritDoc} - */ - public static function isAvailable() { + public static function isAvailable(): bool { return true; } } diff --git a/lib/private/Memcache/Cache.php b/lib/private/Memcache/Cache.php index 99692026edd5..40696920f6ae 100644 --- a/lib/private/Memcache/Cache.php +++ b/lib/private/Memcache/Cache.php @@ -24,31 +24,23 @@ namespace OC\Memcache; -abstract class Cache implements \ArrayAccess, \OCP\ICache { - /** - * @var string $prefix - */ - protected $prefix; +use OCP\ICache; - /** - * @param string $prefix - */ - public function __construct($prefix = '') { +abstract class Cache implements \ArrayAccess, ICache { + protected string $prefix; + + public function __construct(string $prefix = '') { $this->prefix = $prefix; } /** * @return string Prefix used for caching purposes */ - public function getPrefix() { + public function getPrefix(): string { return $this->prefix; } - /** - * @param string $key - * @return mixed - */ - abstract public function get($key); + abstract public function get($key): mixed; /** * @param string $key @@ -56,7 +48,7 @@ abstract public function get($key); * @param int $ttl * @return mixed */ - abstract public function set($key, $value, $ttl = 0); + abstract public function set($key, $value, $ttl = 0): mixed; /** * @param string $key @@ -78,19 +70,19 @@ abstract public function clear($prefix = ''); //implement the ArrayAccess interface - public function offsetExists($offset) { + public function offsetExists($offset): bool { return $this->hasKey($offset); } - public function offsetSet($offset, $value) { + public function offsetSet($offset, $value): void { $this->set($offset, $value); } - public function offsetGet($offset) { + public function offsetGet($offset): mixed { return $this->get($offset); } - public function offsetUnset($offset) { + public function offsetUnset($offset): void { $this->remove($offset); } } diff --git a/lib/private/Memcache/Memcached.php b/lib/private/Memcache/Memcached.php index 5d80de578af6..337938ecc013 100644 --- a/lib/private/Memcache/Memcached.php +++ b/lib/private/Memcache/Memcached.php @@ -96,16 +96,16 @@ protected function getNamespace() { return $this->prefix; } - public function get($key) { + public function get($key): mixed { $result = self::$cache->get($this->getNamespace() . $key); - if ($result === false and self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) { + if ($result === false && self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) { return null; - } else { - return $result; } + + return $result; } - public function set($key, $value, $ttl = 0) { + public function set($key, $value, $ttl = 0): mixed { if ($ttl > 0) { $result = self::$cache->set($this->getNamespace() . $key, $value, $ttl); } else { diff --git a/lib/private/Memcache/NullCache.php b/lib/private/Memcache/NullCache.php index 792410710258..49c9aa6b2d19 100644 --- a/lib/private/Memcache/NullCache.php +++ b/lib/private/Memcache/NullCache.php @@ -25,12 +25,14 @@ namespace OC\Memcache; -class NullCache extends Cache implements \OCP\IMemcache { - public function get($key) { +use OCP\IMemcache; + +class NullCache extends Cache implements IMemcache { + public function get($key): mixed { return null; } - public function set($key, $value, $ttl = 0) { + public function set($key, $value, $ttl = 0): mixed { return true; } diff --git a/lib/private/Memcache/Redis.php b/lib/private/Memcache/Redis.php index d92bc5941221..67615b8655d3 100644 --- a/lib/private/Memcache/Redis.php +++ b/lib/private/Memcache/Redis.php @@ -45,33 +45,37 @@ protected function getNameSpace() { return $this->prefix; } - public function get($key) { + public function get($key): mixed { $result = self::$cache->get($this->getNameSpace() . $key); if ($result === false && !self::$cache->exists($this->getNameSpace() . $key)) { return null; - } else { - return \json_decode($result, true); } + + return \json_decode($result, true); } - public function set($key, $value, $ttl = 0) { + public function set($key, $value, $ttl = 0): mixed { if ($ttl > 0) { return self::$cache->setex($this->getNameSpace() . $key, $ttl, \json_encode($value)); - } else { - return self::$cache->set($this->getNameSpace() . $key, \json_encode($value)); } + + return self::$cache->set($this->getNameSpace() . $key, \json_encode($value)); } - public function hasKey($key) { - return self::$cache->exists($this->getNameSpace() . $key); + public function hasKey($key): bool { + $val = self::$cache->exists($this->getNameSpace() . $key); + if (\is_bool($val)) { + return $val; + } + return (int)$val > 0; } public function remove($key) { if (self::$cache->del($this->getNameSpace() . $key)) { return true; - } else { - return false; } + + return false; } public function clear($prefix = '') { diff --git a/lib/private/Preview.php b/lib/private/Preview.php index e9641e7b6e97..afc89b57236e 100644 --- a/lib/private/Preview.php +++ b/lib/private/Preview.php @@ -1099,7 +1099,7 @@ private function generatePreview() { $previewProviders = \OC::$server->getPreviewManager() ->getProviders(); foreach ($previewProviders as $supportedMimeType => $providers) { - if (!\preg_match($supportedMimeType, $this->mimeType)) { + if (!\preg_match($supportedMimeType, $this->mimeType ?? '')) { continue; } diff --git a/lib/private/Preview/Bitmap.php b/lib/private/Preview/Bitmap.php index d00058495181..f92316ab6fb2 100644 --- a/lib/private/Preview/Bitmap.php +++ b/lib/private/Preview/Bitmap.php @@ -54,7 +54,7 @@ public function getThumbnail(File $file, $maxX, $maxY, $scalingUp) { //new bitmap image object $image = new \OC_Image(); - $image->loadFromData($bp); + $image->loadFromData((string)$bp); //check if image object is valid return $image->valid() ? $image : false; } diff --git a/lib/private/Preview/Image.php b/lib/private/Preview/Image.php index ab2c3dd217b8..c6f6fdfabc47 100644 --- a/lib/private/Preview/Image.php +++ b/lib/private/Preview/Image.php @@ -44,7 +44,7 @@ public function getThumbnail(File $file, $maxX, $maxY, $scalingUp) { $image = new \OC_Image(); $handle = $file->fopen('r'); - $image->load($handle); + $image->loadFromFileHandle($handle); $image->fixOrientation(); if (!$this->validateImageDimensions($image)) { return false; diff --git a/lib/private/Preview/Office.php b/lib/private/Preview/Office.php index 0684d71b21fc..7c07be1d5f8d 100644 --- a/lib/private/Preview/Office.php +++ b/lib/private/Preview/Office.php @@ -75,7 +75,7 @@ public function getThumbnail(File $file, $maxX, $maxY, $scalingUp) { } $image = new \OC_Image(); - $image->loadFromData($pdf); + $image->loadFromData((string)$pdf); \unlink($pdfPreview); diff --git a/lib/private/Preview/SVG.php b/lib/private/Preview/SVG.php index 5bb7301b6219..7f6a3217f822 100644 --- a/lib/private/Preview/SVG.php +++ b/lib/private/Preview/SVG.php @@ -64,7 +64,7 @@ public function getThumbnail(File $file, $maxX, $maxY, $scalingUp) { //new image object $image = new \OC_Image(); - $image->loadFromData($svg); + $image->loadFromData((string)$svg); //check if image object is valid if ($image->valid()) { $image->scaleDownToFit($maxX, $maxY); diff --git a/lib/private/Search/Result/File.php b/lib/private/Search/Result/File.php index 371e3f117617..17df1bd8efd6 100644 --- a/lib/private/Search/Result/File.php +++ b/lib/private/Search/Result/File.php @@ -67,6 +67,16 @@ class File extends \OCP\Search\Result { */ public $permissions; + /** + * @var float + */ + public $score; + + /** + * @var string[] + */ + public $highlights; + /** * Create a new file search result * @param FileInfo $data file data given by provider diff --git a/lib/private/Security/Crypto.php b/lib/private/Security/Crypto.php index 9e0ac67e7a4d..8ecac526bc43 100644 --- a/lib/private/Security/Crypto.php +++ b/lib/private/Security/Crypto.php @@ -112,12 +112,13 @@ public function encrypt($plaintext, $password = '') { /** * Decrypts a value and verifies the HMAC (Encrypt-Then-Mac) + * * @param string $authenticatedCiphertext * @param string $password Password to encrypt, if not specified the secret from config.php will be taken * @return string plaintext * @throws \Exception If the HMAC does not match */ - public function decrypt($authenticatedCiphertext, $password = '') { + public function decrypt(string $authenticatedCiphertext, string $password = ''): string { if ($password === '') { $password = $this->config->getSystemValue('secret'); } diff --git a/lib/private/Server.php b/lib/private/Server.php index 46172e9f0d97..3cc8bfa8cd78 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -730,9 +730,7 @@ public function __construct($webRoot, \OC\Config $config) { 'server' => $_SERVER, 'env' => $_ENV, 'cookies' => $_COOKIE, - 'method' => (isset($_SERVER, $_SERVER['REQUEST_METHOD'])) - ? $_SERVER['REQUEST_METHOD'] - : null, + 'method' => $_SERVER['REQUEST_METHOD'] ?? 'GET', 'urlParams' => $urlParams, ], $this->getSecureRandom(), diff --git a/lib/private/Session/CryptoSessionData.php b/lib/private/Session/CryptoSessionData.php index 233ba5f025c4..e989b1638014 100644 --- a/lib/private/Session/CryptoSessionData.php +++ b/lib/private/Session/CryptoSessionData.php @@ -33,16 +33,11 @@ * @package OC\Session */ class CryptoSessionData implements \ArrayAccess, ISession { - /** @var ISession */ - protected $session; - /** @var \OCP\Security\ICrypto */ - protected $crypto; - /** @var string */ - protected $passphrase; - /** @var array */ - protected $sessionValues; - /** @var bool */ - protected $isModified = false; + protected ISession $session; + protected ICrypto $crypto; + protected string $passphrase; + protected array $sessionValues; + protected bool $isModified = false; public const encryptedSessionName = 'encrypted_session_data'; /** @@ -67,20 +62,20 @@ public function __construct( public function __destruct() { try { $this->close(); - } catch (SessionNotAvailableException $e) { + } catch (SessionNotAvailableException) { // This exception can occur if session is already closed // So it is safe to ignore it and let the garbage collector to proceed } } - protected function initializeSession() { - $encryptedSessionData = $this->session->get(self::encryptedSessionName); + protected function initializeSession(): void { + $encryptedSessionData = $this->session->get(self::encryptedSessionName) ?? ''; try { $this->sessionValues = \json_decode( $this->crypto->decrypt($encryptedSessionData, $this->passphrase), true - ); - } catch (\Exception $e) { + ) ?? []; + } catch (\Exception) { $this->sessionValues = []; } } @@ -91,23 +86,16 @@ protected function initializeSession() { * @param string $key * @param mixed $value */ - public function set($key, $value) { + public function set($key, $value): void { $this->sessionValues[$key] = $value; $this->isModified = true; } /** * Get a value from the session - * - * @param string $key - * @return string|null Either the value or null */ - public function get($key) { - if (isset($this->sessionValues[$key])) { - return $this->sessionValues[$key]; - } - - return null; + public function get(string $key): mixed { + return $this->sessionValues[$key] ?? null; } /** @@ -116,7 +104,7 @@ public function get($key) { * @param string $key * @return bool */ - public function exists($key) { + public function exists($key): bool { return isset($this->sessionValues[$key]); } @@ -125,7 +113,7 @@ public function exists($key) { * * @param string $key */ - public function remove($key) { + public function remove($key): void { $this->isModified = true; unset($this->sessionValues[$key]); $this->session->remove(self::encryptedSessionName); @@ -134,7 +122,7 @@ public function remove($key) { /** * Reset and recreate the session */ - public function clear() { + public function clear(): void { $this->sessionValues = []; $this->isModified = true; $this->session->clear(); @@ -146,7 +134,7 @@ public function clear() { * @param bool $deleteOldSession Whether to delete the old associated session file or not. * @return void */ - public function regenerateId($deleteOldSession = true) { + public function regenerateId($deleteOldSession = true): void { $this->session->regenerateId($deleteOldSession); } @@ -157,14 +145,14 @@ public function regenerateId($deleteOldSession = true) { * @throws SessionNotAvailableException * @since 9.1.0 */ - public function getId() { + public function getId(): string { return $this->session->getId(); } /** * Close the session and release the lock, also writes all changed data in batch */ - public function close() { + public function close(): void { if ($this->isModified) { $encryptedValue = $this->crypto->encrypt(\json_encode($this->sessionValues), $this->passphrase); $this->session->set(self::encryptedSessionName, $encryptedValue); @@ -177,15 +165,15 @@ public function close() { * @param mixed $offset * @return bool */ - public function offsetExists($offset) { + public function offsetExists($offset): bool { return $this->exists($offset); } /** * @param mixed $offset - * @return mixed + * @return string|null */ - public function offsetGet($offset) { + public function offsetGet($offset): ?string { return $this->get($offset); } @@ -193,14 +181,14 @@ public function offsetGet($offset) { * @param mixed $offset * @param mixed $value */ - public function offsetSet($offset, $value) { + public function offsetSet($offset, mixed $value): void { $this->set($offset, $value); } /** * @param mixed $offset */ - public function offsetUnset($offset) { + public function offsetUnset($offset): void { $this->remove($offset); } } diff --git a/lib/private/Session/Internal.php b/lib/private/Session/Internal.php index 560410b576d7..2d4f91b83f0c 100644 --- a/lib/private/Session/Internal.php +++ b/lib/private/Session/Internal.php @@ -70,7 +70,7 @@ public function set($key, $value) { * @param string $key * @return mixed */ - public function get($key) { + public function get(string $key): mixed { if (!$this->exists($key)) { return null; } @@ -102,7 +102,7 @@ public function clear() { $_SESSION = []; } - public function close() { + public function close(): void { \session_write_close(); parent::close(); } diff --git a/lib/private/Session/Memory.php b/lib/private/Session/Memory.php index c9349a750bc7..307f0ad889c8 100644 --- a/lib/private/Session/Memory.php +++ b/lib/private/Session/Memory.php @@ -37,7 +37,7 @@ * @package OC\Session */ class Memory extends Session { - protected $data; + protected array $data; public function __construct() { //no need to use $name since all data is already scoped to this instance @@ -57,7 +57,7 @@ public function set($key, $value) { * @param string $key * @return mixed */ - public function get($key) { + public function get(string $key): mixed { if (!$this->exists($key)) { return null; } diff --git a/lib/private/Session/Session.php b/lib/private/Session/Session.php index 8875dbb27077..fd1ef1397618 100644 --- a/lib/private/Session/Session.php +++ b/lib/private/Session/Session.php @@ -23,19 +23,17 @@ namespace OC\Session; +use ArrayAccess; use OCP\ISession; -abstract class Session implements \ArrayAccess, ISession { - /** - * @var bool - */ - protected $sessionClosed = false; +abstract class Session implements ArrayAccess, ISession { + protected bool $sessionClosed = false; /** * @param mixed $offset * @return bool */ - public function offsetExists($offset) { + public function offsetExists(mixed $offset): bool { return $this->exists($offset); } @@ -43,7 +41,7 @@ public function offsetExists($offset) { * @param mixed $offset * @return mixed */ - public function offsetGet($offset) { + public function offsetGet(mixed $offset): mixed { return $this->get($offset); } @@ -51,21 +49,21 @@ public function offsetGet($offset) { * @param mixed $offset * @param mixed $value */ - public function offsetSet($offset, $value) { + public function offsetSet(mixed $offset, mixed $value): void { $this->set($offset, $value); } /** * @param mixed $offset */ - public function offsetUnset($offset) { + public function offsetUnset(mixed $offset): void { $this->remove($offset); } /** * Close the session and release the lock */ - public function close() { + public function close(): void { $this->sessionClosed = true; } } diff --git a/lib/private/Setup.php b/lib/private/Setup.php index 52d8bd276048..4ea2e394f2aa 100644 --- a/lib/private/Setup.php +++ b/lib/private/Setup.php @@ -92,19 +92,21 @@ public function __construct( /** * Wrapper around the "class_exists" PHP function to be able to mock it + * * @param string $name * @return bool */ - protected function IsClassExisting($name) { + protected function IsClassExisting(string $name): bool { return \class_exists($name); } /** * Wrapper around the "is_callable" PHP function to be able to mock it + * * @param string $name * @return bool */ - protected function is_callable($name) { + protected function is_callable(string $name): bool { return \is_callable($name); } @@ -113,7 +115,7 @@ protected function is_callable($name) { * * @return array */ - protected function getAvailableDbDriversForPdo() { + protected function getAvailableDbDriversForPdo(): array { return \PDO::getAvailableDrivers(); } @@ -124,7 +126,7 @@ protected function getAvailableDbDriversForPdo() { * @return array * @throws Exception */ - public function getSupportedDatabases($allowAllDatabases = false) { + public function getSupportedDatabases(bool $allowAllDatabases = false): array { $availableDatabases = [ 'sqlite' => [ 'type' => 'class', @@ -190,7 +192,7 @@ public function getSupportedDatabases($allowAllDatabases = false) { * @return array of system info, including an "errors" value * in case of errors/warnings */ - public function getSystemInfo($allowAllDatabases = false) { + public function getSystemInfo(bool $allowAllDatabases = false): array { $databases = $this->getSupportedDatabases($allowAllDatabases); $dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data'); @@ -205,7 +207,7 @@ public function getSystemInfo($allowAllDatabases = false) { } if (\is_dir($dataDir) && \is_writable($dataDir)) { // Protect data directory here, so we can test if the protection is working - \OC\Setup::protectDataDirectory(); + self::protectDataDirectory(); } if (!\OC_Util::runningOn('linux')) { @@ -247,11 +249,7 @@ public function getSystemInfo($allowAllDatabases = false) { ]; } - /** - * @param $options - * @return array - */ - public function install($options) { + public function install(array $options): array { $l = $this->l10n; $error = []; @@ -288,7 +286,7 @@ public function install($options) { // validate the data directory if ( - (!\is_dir($dataDir) and !\mkdir($dataDir)) or + (!\is_dir($dataDir) && !\mkdir($dataDir)) || !\is_writable($dataDir) ) { $error[] = $l->t("Can't create or write into the data directory %s", [$dataDir]); @@ -302,7 +300,7 @@ public function install($options) { // validate the apps-external directory if ( - (!\is_dir($appsExternalDir) and !\mkdir($appsExternalDir)) or + (!\is_dir($appsExternalDir) && !\mkdir($appsExternalDir)) || !\is_writable($appsExternalDir) ) { $htmlAppsExternalDir = \htmlspecialchars_decode($appsExternalDir); @@ -324,7 +322,7 @@ public function install($options) { } //use sqlite3 when available, otherwise sqlite2 will be used. - if ($dbType=='sqlite' and $this->IsClassExisting('SQLite3')) { + if ($dbType === 'sqlite' && $this->IsClassExisting('SQLite3')) { $dbType='sqlite3'; } @@ -397,9 +395,9 @@ public function install($options) { && \is_writable(self::pathToHtaccess()) ) { // Update .htaccess files - Setup::updateHtaccess(); + self::updateHtaccess(); } - Setup::protectDataDirectory(); + self::protectDataDirectory(); //try to write logtimezone if (\date_default_timezone_get()) { @@ -443,21 +441,21 @@ public function install($options) { return $error; } - public static function installBackgroundJobs() { + public static function installBackgroundJobs(): void { \OC::$server->getJobList()->add('\OC\Authentication\Token\DefaultTokenCleanupJob'); } /** * @return string Absolute path to htaccess */ - public static function pathToHtaccess() { + public static function pathToHtaccess(): string { return \OC::$SERVERROOT.'/.htaccess'; } /** * Append the correct ErrorDocument path for Apache hosts */ - public static function updateHtaccess() { + public static function updateHtaccess(): void { $config = \OC::$server->getConfig(); $il10n = \OC::$server->getL10N('lib'); @@ -468,7 +466,11 @@ public static function updateHtaccess() { return; } $webRoot = \parse_url($webRoot, PHP_URL_PATH); - $webRoot = \rtrim($webRoot, '/'); + if (\is_string($webRoot)) { + $webRoot = \rtrim($webRoot, '/'); + } else { + $webRoot = ''; + } } else { $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/'; } @@ -541,7 +543,7 @@ public static function updateHtaccess() { } } - public static function protectDataDirectory() { + public static function protectDataDirectory(): void { //Require all denied $now = \date('Y-m-d H:i:s'); $content = "# Generated by ownCloud on $now\n"; diff --git a/lib/private/Setup/MySQL.php b/lib/private/Setup/MySQL.php index 876fa94ba7d1..d0161c1357ef 100644 --- a/lib/private/Setup/MySQL.php +++ b/lib/private/Setup/MySQL.php @@ -54,7 +54,7 @@ public function setupDatabase($username) { $query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?'; $result = $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']); $row = $result->fetch(); - if (!$row or $row['count(*)'] === '0') { + if (!$row || $row['count(*)'] === 0) { \OC_DB::createDbFromStructure($this->dbDefinitionFile); } } @@ -69,7 +69,7 @@ private function createDatabase($connection) { //we can't use OC_DB functions here because we need to connect as the administrative user. $characterSet = $this->config->getSystemValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8'; $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE {$characterSet}_bin;"; - $connection->executeUpdate($query); + $connection->executeStatement($query); } catch (\Exception $ex) { $this->logger->error('Database creation failed: {error}', [ 'app' => 'mysql.setup', @@ -81,7 +81,7 @@ private function createDatabase($connection) { try { //this query will fail if there aren't the right permissions, ignore the error $query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'"; - $connection->executeUpdate($query); + $connection->executeStatement($query); } catch (\Exception $ex) { $this->logger->debug('Could not automatically grant privileges, this can be ignored if database user already had privileges: {error}', [ 'app' => 'mysql.setup', @@ -100,9 +100,9 @@ private function createDBUser($connection) { // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one, // the anonymous user would take precedence when there is one. $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'"; - $connection->executeUpdate($query); + $connection->executeStatement($query); $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'"; - $connection->executeUpdate($query); + $connection->executeStatement($query); } /** diff --git a/lib/private/Share20/DefaultShareProvider.php b/lib/private/Share20/DefaultShareProvider.php index d30f5ce72b22..9c00689ef935 100644 --- a/lib/private/Share20/DefaultShareProvider.php +++ b/lib/private/Share20/DefaultShareProvider.php @@ -552,7 +552,7 @@ public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offs * @inheritdoc */ public function getShareById($id, $recipientId = null) { - if (!ctype_digit($id)) { + if (!ctype_digit((string)$id)) { // share id is defined as a field of type integer // if someone calls the API asking for a share id like "abc" // then there is no point trying to query the database, diff --git a/lib/private/Share20/Manager.php b/lib/private/Share20/Manager.php index 22283779bc9b..4918a7259c99 100644 --- a/lib/private/Share20/Manager.php +++ b/lib/private/Share20/Manager.php @@ -1199,7 +1199,7 @@ public function deleteShare(\OCP\Share\IShare $share) { $deletedShares[] = $share; //Format hook info - $formattedDeletedShares = \array_map('self::formatUnshareHookParams', $deletedShares); + $formattedDeletedShares = \array_map(self::formatUnshareHookParams(...), $deletedShares); $hookParams['deletedShares'] = $formattedDeletedShares; diff --git a/lib/private/Template/JSResourceLocator.php b/lib/private/Template/JSResourceLocator.php index d73038c6c4e6..14925f9a4baa 100644 --- a/lib/private/Template/JSResourceLocator.php +++ b/lib/private/Template/JSResourceLocator.php @@ -39,7 +39,7 @@ public function doFind($script) { $webRoot = \substr($this->theme->getWebPath(), 0, -\strlen($themeDirectory)); } - if (\strpos($script, '/l10n/') !== false) { + if (str_contains($script, '/l10n/')) { $app = \substr($fullScript, 0, \strpos($fullScript, '/')); $appFolderLocation = \explode('/', $this->appManager->getAppWebPath($app))[1] ?? 'apps'; diff --git a/lib/private/URLGenerator.php b/lib/private/URLGenerator.php index a6367adea3e0..34abd493fc9e 100644 --- a/lib/private/URLGenerator.php +++ b/lib/private/URLGenerator.php @@ -96,7 +96,7 @@ public function linkToRoute($route, $parameters = []) { * * Returns an absolute url to the given route. */ - public function linkToRouteAbsolute($routeName, $arguments = []) { + public function linkToRouteAbsolute($routeName, $arguments = []): string { return $this->getAbsoluteURL($this->linkToRoute($routeName, $arguments)); } @@ -237,7 +237,7 @@ private function getImagePathOrFallback($file) { * @param string $url the url in the ownCloud host * @return string the absolute version of the url */ - public function getAbsoluteURL($url) { + public function getAbsoluteURL($url): string { $webRoot = $this->environmentHelper->getWebRoot(); $separator = $url[0] === '/' ? '' : '/'; diff --git a/lib/private/Updater/VersionCheck.php b/lib/private/Updater/VersionCheck.php index 9269717c6341..062a196e0f9f 100644 --- a/lib/private/Updater/VersionCheck.php +++ b/lib/private/Updater/VersionCheck.php @@ -78,9 +78,7 @@ public function check() { $tmp = []; $xml = $this->getUrlContent($url); if ($xml) { - $loadEntities = \libxml_disable_entity_loader(true); $data = @\simplexml_load_string($xml); - \libxml_disable_entity_loader($loadEntities); if ($data !== false) { $tmp['version'] = (string)$data->version; $tmp['versionstring'] = (string)$data->versionstring; diff --git a/lib/private/User/Database.php b/lib/private/User/Database.php index c522f50f95b9..238fb43b128e 100644 --- a/lib/private/User/Database.php +++ b/lib/private/User/Database.php @@ -167,7 +167,7 @@ public function setDisplayName($uid, $displayName) { */ public function getDisplayName($uid) { $this->loadUser($uid); - if (\strlen($this->cache[$uid]['displayname']) === 0) { + if (($this->cache[$uid]['displayname'] ?? '') === '') { return $uid; } diff --git a/lib/private/User/Sync/BackendUsersIterator.php b/lib/private/User/Sync/BackendUsersIterator.php index 25b5d748e523..062374bfaefe 100644 --- a/lib/private/User/Sync/BackendUsersIterator.php +++ b/lib/private/User/Sync/BackendUsersIterator.php @@ -23,33 +23,30 @@ use OCP\UserInterface; class BackendUsersIterator extends UsersIterator { - /** - * @var UserInterface - */ - private $backend; + private UserInterface $backend; /** * @var int the current data position, * we need to track it independently of parent::$position to handle data sets larger thin LIMIT properly */ - private $dataPos = 0; + private int $dataPos = 0; /** * @var int to cache the count($this->data) calculations */ - private $endPos = 0; + private int $endPos = 0; /** @var bool false if the backend returned less than LIMIT results */ - private $hasMoreData = false; + private bool $hasMoreData = false; /** @var string search for the uid string in backend */ - private $search; + private string $search; - public function __construct(UserInterface $backend, $filterUID = '') { + public function __construct(UserInterface $backend, string $filterUID = '') { $this->backend = $backend; $this->search = $filterUID; } - public function rewind() { + public function rewind(): void { parent::rewind(); $this->data = $this->backend->getUsers($this->search, self::LIMIT, 0); $this->dataPos = 0; @@ -57,7 +54,7 @@ public function rewind() { $this->hasMoreData = $this->endPos >= self::LIMIT; } - public function next() { + public function next(): void { $this->position++; $this->dataPos++; if ($this->hasMoreData && $this->dataPos >= $this->endPos) { @@ -70,7 +67,7 @@ public function next() { } } - protected function currentDataPos() { + protected function currentDataPos(): int { return $this->dataPos; } } diff --git a/lib/private/User/Sync/SeenUsersIterator.php b/lib/private/User/Sync/SeenUsersIterator.php index f4af918c0a98..53e331c2c018 100644 --- a/lib/private/User/Sync/SeenUsersIterator.php +++ b/lib/private/User/Sync/SeenUsersIterator.php @@ -23,26 +23,20 @@ use OC\User\AccountMapper; class SeenUsersIterator extends UsersIterator { - /** - * @var AccountMapper - */ - private $mapper; - /** - * @var string class name - */ - private $backend; + private AccountMapper $mapper; + private string $backend; - public function __construct(AccountMapper $mapper, $backend) { + public function __construct(AccountMapper $mapper, string $backend) { $this->mapper = $mapper; $this->backend = $backend; } - public function rewind() { + public function rewind(): void { parent::rewind(); $this->data = $this->mapper->findUserIds($this->backend, true, self::LIMIT, 0); } - public function next() { + public function next(): void { $this->position++; if ($this->currentDataPos() === 0) { $this->page++; diff --git a/lib/private/User/Sync/UsersIterator.php b/lib/private/User/Sync/UsersIterator.php index 9a97aae64abe..486c552b7fb9 100644 --- a/lib/private/User/Sync/UsersIterator.php +++ b/lib/private/User/Sync/UsersIterator.php @@ -21,32 +21,32 @@ namespace OC\User\Sync; abstract class UsersIterator implements \Iterator { - protected $position = 0; + protected int $position = 0; protected $page; protected $data; public const LIMIT = 500; - public function rewind() { + public function rewind(): void { $this->position = 0; $this->page = 0; } - public function current() { + public function current(): mixed { return $this->data[$this->currentDataPos()]; } - public function key() { + public function key(): mixed { return $this->position; } - abstract public function next(); + abstract public function next(): void; - public function valid() { + public function valid(): bool { return isset($this->data[$this->currentDataPos()]); } - protected function currentDataPos() { + protected function currentDataPos(): int { return $this->position % self::LIMIT; } } diff --git a/lib/private/User/User.php b/lib/private/User/User.php index a252016b2dd4..3739570ab5db 100644 --- a/lib/private/User/User.php +++ b/lib/private/User/User.php @@ -191,9 +191,9 @@ public function setUserName($userName) { * * @return string */ - public function getDisplayName() { - $displayName = $this->account->getDisplayName(); - if (\strlen($displayName) === 0) { + public function getDisplayName(): string { + $displayName = $this->account->getDisplayName() ?? ''; + if ($displayName === '') { $displayName = $this->getUID(); } return $displayName; diff --git a/lib/private/legacy/app.php b/lib/private/legacy/app.php index 994d7e7a902c..0b6e3ff27fa7 100644 --- a/lib/private/legacy/app.php +++ b/lib/private/legacy/app.php @@ -128,7 +128,7 @@ public static function loadApps($types = null) { \ob_end_clean(); // once all authentication apps are loaded we can validate the session - if ($types === null || \in_array('authentication', $types)) { + if ($types === null || \in_array('authentication', \is_array($types) ? $types : [$types], true)) { if (\OC::$server->getUserSession()) { $request = \OC::$server->getRequest(); $session = \OC::$server->getUserSession(); diff --git a/lib/private/legacy/helper.php b/lib/private/legacy/helper.php index 25d4f5701d5f..0e59a26e5bc8 100644 --- a/lib/private/legacy/helper.php +++ b/lib/private/legacy/helper.php @@ -195,11 +195,12 @@ public static function copyr($src, $dest) { /** * Recursive deletion of folders + * * @param string $dir path to the folder * @param bool $deleteSelf if set to false only the content of the folder will be deleted * @return bool */ - public static function rmdirr($dir, $deleteSelf = true) { + public static function rmdirr(string $dir, bool $deleteSelf = true): bool { if (\is_dir($dir)) { $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS), @@ -533,13 +534,6 @@ public static function findBinaryPath($program) { $exeSniffer = new ExecutableFinder(); // Returns null if nothing is found $result = $exeSniffer->find($program); - if (empty($result)) { - $command = 'find ' . self::getCleanedPath(\getenv('PATH')) . ' -name ' . \escapeshellarg($program) . ' 2> /dev/null'; - \exec($command, $output, $returnCode); - if (\count($output) > 0) { - $result = \escapeshellcmd($output[0]); - } - } } // store the value for 5 minutes $memcache->set($program, $result, 300); @@ -556,7 +550,7 @@ public static function findBinaryPath($program) { * @param string $path * @return string|null */ - public static function getCleanedPath($path = '') { + public static function getCleanedPath(string $path = ''): ?string { $pattern = "((\/[\w\d]*)+)"; if (\preg_match_all($pattern, $path, $matches) > 0) { diff --git a/lib/private/legacy/image.php b/lib/private/legacy/image.php index 8844710a3f56..d08416585972 100644 --- a/lib/private/legacy/image.php +++ b/lib/private/legacy/image.php @@ -42,8 +42,7 @@ * Class for basic image manipulation */ class OC_Image implements \OCP\IImage { - /** @var false|resource */ - protected $resource = false; // tmp resource. + protected ?\GdImage $resource = null; // tmp resource. /** @var int */ protected $imageType = IMAGETYPE_PNG; // Default to png if file type isn't evident. /** @var string */ @@ -107,11 +106,10 @@ public function __construct($imageRef = null, $logger = null, $config = null) { /** * Determine whether the object contains an image resource. - * - * @return bool */ - public function valid() { // apparently you can't name a method 'empty'... - return \is_resource($this->resource); + public function valid(): bool { + // apparently you can't name a method 'empty'... + return $this->resource instanceof \GdImage; } /** @@ -218,7 +216,9 @@ public function save($filePath = null, $mimeType = null) { if ($filePath === null && $this->filePath === null) { $this->logger->error(__METHOD__ . '(): called with no path.', ['app' => 'core']); return false; - } elseif ($filePath === null && $this->filePath !== null) { + } + + if ($filePath === null && $this->filePath !== null) { $filePath = $this->filePath; } return $this->_output($filePath, $mimeType); @@ -240,7 +240,9 @@ private function _output($filePath = null, $mimeType = null) { if (!\is_writable(\dirname($filePath))) { $this->logger->error(__METHOD__ . '(): Directory \'' . \dirname($filePath) . '\' is not writable.', ['app' => 'core']); return false; - } elseif (\is_writable(\dirname($filePath)) && \file_exists($filePath) && !\is_writable($filePath)) { + } + + if (\is_writable(\dirname($filePath)) && \file_exists($filePath) && !\is_writable($filePath)) { $this->logger->error(__METHOD__ . '(): File \'' . $filePath . '\' is not writable.', ['app' => 'core']); return false; } @@ -316,10 +318,7 @@ public function __invoke() { return $this->show(); } - /** - * @return resource Returns the image resource in any. - */ - public function resource() { + public function resource(): ?GdImage { return $this->resource; } @@ -491,18 +490,18 @@ public function fixOrientation() { \imagedestroy($this->resource); $this->resource = $res; return true; - } else { - $this->logger->debug('OC_Image->fixOrientation() Error during alpha-saving', ['app' => 'core']); - return false; } - } else { - $this->logger->debug('OC_Image->fixOrientation() Error during alpha-blending', ['app' => 'core']); + + $this->logger->debug('OC_Image->fixOrientation() Error during alpha-saving', ['app' => 'core']); return false; } - } else { - $this->logger->debug('OC_Image->fixOrientation() Error during orientation fixing', ['app' => 'core']); + + $this->logger->debug('OC_Image->fixOrientation() Error during alpha-blending', ['app' => 'core']); return false; } + + $this->logger->debug('OC_Image->fixOrientation() Error during orientation fixing', ['app' => 'core']); + return false; } return false; } @@ -510,22 +509,27 @@ public function fixOrientation() { /** * Loads an image from a local file, a base64 encoded string or a resource created by an imagecreate* function. * - * @param resource|string $imageRef The path to a local file, a base64 encoded string or a resource created by an imagecreate* function or a file resource (file handle ). - * @return resource|false An image resource or false on error + * @param GdImage|resource|string $imageRef The path to a local file, a base64 encoded string or a resource created by an imagecreate* function or a file resource (file handle ). + * @return GdImage|false An image resource or false on error */ public function load($imageRef) { + if ($imageRef instanceof \GdImage) { + $this->resource = $imageRef; + return $this->resource; + } if (\is_resource($imageRef)) { - if (\get_resource_type($imageRef) == 'gd') { - $this->resource = $imageRef; - return $this->resource; - } elseif (\in_array(\get_resource_type($imageRef), ['file', 'stream'])) { - return $this->loadFromFileHandle($imageRef); - } - } elseif ($this->loadFromBase64($imageRef) !== false) { + return $this->loadFromFileHandle($imageRef); + } + + if ($this->loadFromBase64($imageRef) !== false) { return $this->resource; - } elseif ($this->loadFromFile($imageRef) !== false) { + } + + if ($this->loadFromFile($imageRef) !== false) { return $this->resource; - } elseif ($this->loadFromData($imageRef) !== false) { + } + + if ($this->loadFromData($imageRef) !== false) { return $this->resource; } $this->logger->debug(__METHOD__ . '(): could not load anything. Giving up!', ['app' => 'core']); @@ -537,9 +541,9 @@ public function load($imageRef) { * It is the responsibility of the caller to position the pointer at the correct place and to close the handle again. * * @param resource $handle - * @return resource|false An image resource or false on error + * @return GdImage|false|null An image resource or false on error */ - public function loadFromFileHandle($handle) { + public function loadFromFileHandle($handle): GdImage|false|null { $contents = \stream_get_contents($handle); if ($this->loadFromData($contents)) { $this->adjustStreamChunkSize($handle); @@ -667,7 +671,10 @@ public function loadFromFile($imagePath = false) { } break; case IMAGETYPE_BMP: - $this->resource = $this->imagecreatefrombmp($imagePath); + $resource = $this->imagecreatefrombmp($imagePath); + if ($resource !== false) { + $this->resource = $resource; + } break; /* case IMAGETYPE_TIFF_II: // (intel byte order) @@ -714,61 +721,55 @@ public function loadFromFile($imagePath = false) { * Loads an image from a string of data. * * @param string $str A string of image data as read from a file. - * @return bool|resource An image resource or false on error + * @return bool An image resource or false on error */ public function loadFromData($str) { - if (\is_resource($str)) { + if (!\is_string($str)) { return false; } - $this->resource = @\imagecreatefromstring($str); + $resource = @\imagecreatefromstring($str); if ($this->fileInfo) { $this->mimeType = $this->fileInfo->buffer($str); } - if (\is_resource($this->resource)) { - \imagealphablending($this->resource, false); - \imagesavealpha($this->resource, true); - } - - if (!$this->resource) { + if (!$resource) { $this->logger->debug('OC_Image->loadFromFile, could not load', ['app' => 'core']); return false; } - return $this->resource; + $this->resource = $resource; + \imagealphablending($this->resource, false); + \imagesavealpha($this->resource, true); + + return true; } /** * Loads an image from a base64 encoded string. * * @param string $str A string base64 encoded string of image data. - * @return bool|resource An image resource or false on error + * @return bool An image resource or false on error */ - public function loadFromBase64($str) { + public function loadFromBase64(string $str): bool { if (!\is_string($str)) { return false; } $data = \base64_decode($str); if ($data) { // try to load from string data - $this->resource = @\imagecreatefromstring($data); + $resource = @\imagecreatefromstring($data); if ($this->fileInfo) { $this->mimeType = $this->fileInfo->buffer($data); } - if (!$this->resource) { + if ($resource === false) { $this->logger->debug('OC_Image->loadFromBase64, could not load', ['app' => 'core']); return false; } - return $this->resource; - } else { - return false; + $this->resource = $resource; + return true; } + + return false; } - /** - * Create a new image from file or URL - * @param string $fileName

- * Path to the BMP image. - * @return bool|resource an image resource identifier on success, FALSE on errors. - */ - private function imagecreatefrombmp($fileName) { + private function imagecreatefrombmp(string $fileName): GdImage|bool { try { $bmp = new BmpToResource($fileName); $imageHandle = $bmp->toResource(); @@ -823,9 +824,8 @@ public function preciseResize($width, $height) { $heightOrig = \imagesy($this->resource); $process = \imagecreatetruecolor($width, $height); - if ($process == false) { + if ($process === false) { $this->logger->error(__METHOD__ . '(): Error creating true color image', ['app' => 'core']); - \imagedestroy($process); return false; } @@ -836,8 +836,8 @@ public function preciseResize($width, $height) { \imagesavealpha($process, true); } - \imagecopyresampled($process, $this->resource, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig); - if ($process == false) { + $result = \imagecopyresampled($process, $this->resource, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig); + if ($result === false) { $this->logger->error(__METHOD__ . '(): Error re-sampling process image', ['app' => 'core']); \imagedestroy($process); return false; @@ -883,7 +883,6 @@ public function centerCrop($size = 0) { $process = \imagecreatetruecolor($targetWidth, $targetHeight); if ($process == false) { $this->logger->error('OC_Image->centerCrop, Error creating true color image', ['app' => 'core']); - \imagedestroy($process); return false; } @@ -894,8 +893,8 @@ public function centerCrop($size = 0) { \imagesavealpha($process, true); } - \imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $targetWidth, $targetHeight, $width, $height); - if ($process == false) { + $result = \imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $targetWidth, $targetHeight, $width, $height); + if ($result === false) { $this->logger->error('OC_Image->centerCrop, Error re-sampling process image ' . $width . 'x' . $height, ['app' => 'core']); \imagedestroy($process); return false; @@ -920,9 +919,8 @@ public function crop($x, $y, $w, $h) { return false; } $process = \imagecreatetruecolor($w, $h); - if ($process == false) { + if ($process === false) { $this->logger->error(__METHOD__ . '(): Error creating true color image', ['app' => 'core']); - \imagedestroy($process); return false; } @@ -933,8 +931,8 @@ public function crop($x, $y, $w, $h) { \imagesavealpha($process, true); } - \imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h); - if ($process == false) { + $result = \imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h); + if ($result === false) { $this->logger->error(__METHOD__ . '(): Error re-sampling process image ' . $w . 'x' . $h, ['app' => 'core']); \imagedestroy($process); return false; @@ -994,7 +992,7 @@ public function scaleDownToFit($maxWidth, $maxHeight) { /** * Destroys the current image and resets the object */ - public function destroy() { + public function destroy(): void { if ($this->valid()) { \imagedestroy($this->resource); } @@ -1015,7 +1013,7 @@ public function __destruct() { * @link http://www.programmierer-forum.de/imagebmp-gute-funktion-gefunden-t143716.htm * @author mgutt * @version 1.00 - * @param resource $im + * @param \GdImage $im * @param string $fileName [optional]

The path to save the file to.

* @param int $bit [optional]

Bit depth, (default is 24).

* @param int $compression [optional] @@ -1069,6 +1067,7 @@ function imagebmp($im, $fileName = '', $bit = 24, $compression = 0) { $index = \imagecolorat($im, $i, $j); if ($index !== $lastIndex || $sameNum > 255) { if ($sameNum != 0) { + /** @phan-suppress-next-line PhanTypeMismatchArgumentInternalReal */ $bmpData .= \chr($sameNum) . \chr($lastIndex); } $lastIndex = $index; diff --git a/lib/private/legacy/l10n/string.php b/lib/private/legacy/l10n/string.php index fbfd94860ded..ee1f58f8279f 100644 --- a/lib/private/legacy/l10n/string.php +++ b/lib/private/legacy/l10n/string.php @@ -1,4 +1,7 @@ * @author Bernhard Posselt @@ -26,25 +29,17 @@ */ class OC_L10N_String implements JsonSerializable { - /** @var \OC\L10N\L10N */ - protected $l10n; + protected L10N $l10n; - /** @var string */ - protected $text; + protected string $text; /** @var array */ - protected $parameters; + protected array $parameters; /** @var integer */ - protected $count; + protected int $count; - /** - * @param \OC\L10N\L10N $l10n - * @param string|string[] $text - * @param array $parameters - * @param int $count - */ - public function __construct($l10n, $text, $parameters, $count = 1) { + public function __construct(L10N $l10n, string $text, array $parameters, int $count = 1) { $this->l10n = $l10n; $this->text = $text; $this->parameters = $parameters; @@ -66,13 +61,14 @@ public function __toString() { // Replace %n first (won't interfere with vsprintf) $text = \str_replace('%n', $this->count, $text); - $text = @\vsprintf($text, $this->parameters); + if (\count($this->parameters) === 0) { + return (string)$text; + } - // If vsprintf fails, return untranslated string - return $text === false ? $this->text : $text; + return \vsprintf($text, $this->parameters); } - public function jsonSerialize() { + public function jsonSerialize(): string { return $this->__toString(); } } diff --git a/lib/public/AppFramework/Controller.php b/lib/public/AppFramework/Controller.php index d69f4f5c1d5b..def3a5803c4a 100644 --- a/lib/public/AppFramework/Controller.php +++ b/lib/public/AppFramework/Controller.php @@ -100,11 +100,12 @@ public function __construct( /** * Parses an HTTP accept header and returns the supported responder type + * * @param string $acceptHeader * @return string the responder type * @since 7.0.0 */ - public function getResponderByHTTPHeader($acceptHeader) { + public function getResponderByHTTPHeader(string $acceptHeader): string { $headers = \explode(',', $acceptHeader); // return the first matching responder diff --git a/lib/public/Files/External/Auth/AuthMechanism.php b/lib/public/Files/External/Auth/AuthMechanism.php index b637b9b8de0a..00c6592e562d 100644 --- a/lib/public/Files/External/Auth/AuthMechanism.php +++ b/lib/public/Files/External/Auth/AuthMechanism.php @@ -96,7 +96,7 @@ public function setScheme($scheme) { * @return array * @since 10.0 */ - public function jsonSerialize() { + public function jsonSerialize(): array { $data = $this->jsonSerializeDefinition(); $data += $this->jsonSerializeIdentifier(); diff --git a/lib/public/Files/External/Backend/Backend.php b/lib/public/Files/External/Backend/Backend.php index e11856d65cc6..4288bb60fe0f 100644 --- a/lib/public/Files/External/Backend/Backend.php +++ b/lib/public/Files/External/Backend/Backend.php @@ -118,7 +118,7 @@ public function addAuthScheme($scheme) { * @return array * @since 10.0 */ - public function jsonSerialize() { + public function jsonSerialize(): array { $data = $this->jsonSerializeDefinition(); $data += $this->jsonSerializeIdentifier(); diff --git a/lib/public/Files/External/DefinitionParameter.php b/lib/public/Files/External/DefinitionParameter.php index ed00e2c1d9c9..7ccf7ae8fbd2 100644 --- a/lib/public/Files/External/DefinitionParameter.php +++ b/lib/public/Files/External/DefinitionParameter.php @@ -157,10 +157,9 @@ public function isFlagSet($flag) { /** * Serialize into JSON for client-side JS * - * @return string * @since 10.0 */ - public function jsonSerialize() { + public function jsonSerialize(): array { return [ 'value' => $this->getText(), 'flags' => $this->getFlags(), diff --git a/lib/public/Files/External/IStorageConfig.php b/lib/public/Files/External/IStorageConfig.php index 8405968f726d..e04c9b29ace5 100644 --- a/lib/public/Files/External/IStorageConfig.php +++ b/lib/public/Files/External/IStorageConfig.php @@ -248,5 +248,5 @@ public function setType($type); * @return array * @since 10.0 */ - public function jsonSerialize(); + public function jsonSerialize(): array; } diff --git a/lib/public/IDBConnection.php b/lib/public/IDBConnection.php index 0b444cb6df8a..8e2d0ff30eba 100644 --- a/lib/public/IDBConnection.php +++ b/lib/public/IDBConnection.php @@ -299,7 +299,7 @@ public function tableExists($table); * @return string * @since 9.0.0 */ - public function escapeLikeParameter($param); + public function escapeLikeParameter(string $param): string; /** * Create the schema of the connected database diff --git a/lib/public/IL10N.php b/lib/public/IL10N.php index 933ce1f75d7a..a8cc30f5a23c 100644 --- a/lib/public/IL10N.php +++ b/lib/public/IL10N.php @@ -44,15 +44,16 @@ interface IL10N { /** * Translating + * * @param string $text The text we need a translation for - * @param array $parameters default:array() Parameters for sprintf - * @return \OC_L10N_String Translation or the same text + * @param array|mixed $parameters default:array() Parameters for sprintf + * @return string Translation or the same text * * Returns the translation. If no translation is found, $text will be * returned. * @since 6.0.0 */ - public function t($text, $parameters = []); + public function t(string $text, $parameters = []): string; /** * Translating diff --git a/lib/public/IRequest.php b/lib/public/IRequest.php index 31987599591e..27b28a297a49 100644 --- a/lib/public/IRequest.php +++ b/lib/public/IRequest.php @@ -80,11 +80,11 @@ public function getHeader(string $name): ?string; * 1. URL parameters * 2. POST parameters * 3. GET parameters - * @param mixed $default If the key is not found, this value will be returned + * @param mixed|null $default If the key is not found, this value will be returned * @return mixed the content of the array * @since 6.0.0 */ - public function getParam($key, $default = null); + public function getParam(string $key, mixed $default = null): mixed; /** * Returns all params that were received, be it from the request @@ -94,7 +94,7 @@ public function getParam($key, $default = null); * @return array the array with all parameters * @since 6.0.0 */ - public function getParams(); + public function getParams(): array; /** * Returns the method of the request @@ -102,7 +102,7 @@ public function getParams(); * @return string the method of the request (POST, GET, etc) * @since 6.0.0 */ - public function getMethod(); + public function getMethod(): string; /** * Shortcut for accessing an uploaded file through the $_FILES array diff --git a/lib/public/ISession.php b/lib/public/ISession.php index 66f477c9fd1a..2f732f67cafa 100644 --- a/lib/public/ISession.php +++ b/lib/public/ISession.php @@ -58,7 +58,7 @@ public function set($key, $value); * @return mixed should return null if $key does not exist * @since 6.0.0 */ - public function get($key); + public function get(string $key): mixed; /** * Check if a named key exists in the session diff --git a/lib/public/IURLGenerator.php b/lib/public/IURLGenerator.php index 481e5f60d1e2..76798c5aff6b 100644 --- a/lib/public/IURLGenerator.php +++ b/lib/public/IURLGenerator.php @@ -53,7 +53,7 @@ public function linkToRoute($routeName, $arguments = []); * @return string the absolute url * @since 8.0.0 */ - public function linkToRouteAbsolute($routeName, $arguments = []); + public function linkToRouteAbsolute($routeName, $arguments = []): string; /** * Returns an URL for an image or file diff --git a/lib/public/Lock/LockedException.php b/lib/public/Lock/LockedException.php index 87d7c1970f2b..fd1667e91c6b 100644 --- a/lib/public/Lock/LockedException.php +++ b/lib/public/Lock/LockedException.php @@ -46,7 +46,7 @@ class LockedException extends \Exception { * @since 8.1.0 */ public function __construct($path, \Exception $previous = null) { - $message = \OC::$server->getL10N('lib')->t('"%s" is locked', $path); + $message = \OC::$server->getL10N('lib')->t('"%s" is locked', [$path]); parent::__construct($message, 0, $previous); $this->path = $path; } diff --git a/lib/public/Mail/IMailer.php b/lib/public/Mail/IMailer.php index 333e961d071c..070dc42737ea 100644 --- a/lib/public/Mail/IMailer.php +++ b/lib/public/Mail/IMailer.php @@ -51,7 +51,7 @@ interface IMailer { * @return Message * @since 8.1.0 */ - public function createMessage(); + public function createMessage(): Message; /** * Send the specified message. Also sets the from address to the value defined in config.php @@ -64,7 +64,7 @@ public function createMessage(); * has been supplied.) * @since 8.1.0 */ - public function send(Message $message); + public function send(Message $message): array; /** * Checks if an e-mail address is valid @@ -73,5 +73,5 @@ public function send(Message $message); * @return bool True if the mail address is valid, false otherwise * @since 8.1.0 */ - public function validateMailAddress($email); + public function validateMailAddress(string $email): bool; } diff --git a/lib/public/Security/ICrypto.php b/lib/public/Security/ICrypto.php index 4a905dc292b5..405c9e349d45 100644 --- a/lib/public/Security/ICrypto.php +++ b/lib/public/Security/ICrypto.php @@ -53,11 +53,12 @@ public function encrypt($plaintext, $password = ''); /** * Decrypts a value and verifies the HMAC (Encrypt-Then-Mac) + * * @param string $authenticatedCiphertext * @param string $password Password to encrypt, if not specified the secret from config.php will be taken * @return string plaintext * @throws \Exception If the HMAC does not match * @since 8.0.0 */ - public function decrypt($authenticatedCiphertext, $password = ''); + public function decrypt(string $authenticatedCiphertext, string $password = ''): string; } diff --git a/settings/ChangePassword/Controller.php b/settings/ChangePassword/Controller.php index 487777b718c3..ea367c476e72 100644 --- a/settings/ChangePassword/Controller.php +++ b/settings/ChangePassword/Controller.php @@ -213,7 +213,7 @@ private static function sendNotificationMail($username) { $mailer->send($message); } catch (\Exception $e) { throw new \Exception($l10n->t( - 'Couldn\'t send reset email. Please contact your administrator.' + "Couldn't send reset email. Please contact your administrator." )); } } diff --git a/settings/Controller/MailSettingsController.php b/settings/Controller/MailSettingsController.php index 9e6e3287e1d4..9f89b3e311d2 100644 --- a/settings/Controller/MailSettingsController.php +++ b/settings/Controller/MailSettingsController.php @@ -85,7 +85,6 @@ public function __construct( * @param string $mail_smtpmode * @param string $mail_smtpsecure * @param string $mail_smtphost - * @param string $mail_smtpauthtype * @param int $mail_smtpauth * @param string $mail_smtpport * @return array @@ -96,7 +95,6 @@ public function setMailSettings( $mail_smtpmode, $mail_smtpsecure, $mail_smtphost, - $mail_smtpauthtype, $mail_smtpauth, $mail_smtpport ) { @@ -162,36 +160,35 @@ public function sendTestMail() { $email = $this->userSession->getUser()->getEMailAddress(); } - if (!empty($email)) { - try { - $message = $this->mailer->createMessage(); - $message->setTo([$email => $this->userSession->getUser()->getDisplayName()]); - $message->setFrom([$this->defaultMailAddress]); - $message->setSubject($this->l10n->t('test email settings')); - $message->setPlainBody('If you received this email, the settings seem to be correct.'); - $this->mailer->send($message); - } catch (\Exception $e) { - return [ - 'data' => [ - 'message' => (string) $this->l10n->t('A problem occurred while sending the email. Please revise your settings. (Error: %s)', [$e->getMessage()]), - ], - 'status' => 'error', - ]; - } + if (empty($email)) { + return ['data' => + ['message' => + (string) $this->l10n->t('You need to set your user email before being able to send test emails.'), + ], + 'status' => 'error' + ]; + } + try { + $message = $this->mailer->createMessage(); + $message->setTo([$email => $this->userSession->getUser()->getDisplayName()]); + $message->setFrom([$this->defaultMailAddress]); + $message->setSubject($this->l10n->t('test email settings')); + $message->setPlainBody('If you received this email, the settings seem to be correct.'); + $this->mailer->send($message); return ['data' => ['message' => (string) $this->l10n->t('Email sent') ], 'status' => 'success' ]; + } catch (\Exception $e) { + return [ + 'data' => [ + 'message' => (string) $this->l10n->t('A problem occurred while sending the email. Please revise your settings. (Error: %s)', [$e->getMessage()]), + ], + 'status' => 'error', + ]; } - - return ['data' => - ['message' => - (string) $this->l10n->t('You need to set your user email before being able to send test emails.'), - ], - 'status' => 'error' - ]; } } diff --git a/settings/Controller/UsersController.php b/settings/Controller/UsersController.php index 76cfca776cf4..955c9e5ec07e 100644 --- a/settings/Controller/UsersController.php +++ b/settings/Controller/UsersController.php @@ -268,7 +268,7 @@ private function checkEmailChangeToken($token, $userId) { throw new \Exception($this->l10n->t('Couldn\'t change the email address because the user does not exist')); } - $splittedToken = \explode(':', $this->config->getUserValue($userId, 'owncloud', 'changeMail', null)); + $splittedToken = \explode(':', $this->config->getUserValue($userId, 'owncloud', 'changeMail', null) ?? ''); if (\count($splittedToken) !== 3) { $this->config->deleteUserValue($userId, 'owncloud', 'changeMail'); throw new \Exception($this->l10n->t('Couldn\'t change the email address because the token is invalid')); diff --git a/settings/Panels/Admin/Mail.php b/settings/Panels/Admin/Mail.php index 4a86cb8b34fc..0c75b63a9f61 100644 --- a/settings/Panels/Admin/Mail.php +++ b/settings/Panels/Admin/Mail.php @@ -61,7 +61,6 @@ public function getPanel() { $template->assign('mail_smtpsecure', $this->config->getSystemValue("mail_smtpsecure", '')); $template->assign('mail_smtphost', $this->config->getSystemValue("mail_smtphost", '')); $template->assign('mail_smtpport', $this->config->getSystemValue("mail_smtpport", '')); - $template->assign('mail_smtpauthtype', $this->config->getSystemValue("mail_smtpauthtype", '')); $template->assign('mail_smtpauth', $this->config->getSystemValue("mail_smtpauth", false)); $template->assign('mail_smtpname', $this->config->getSystemValue("mail_smtpname", '')); $template->assign('mail_user_email', $this->userSession->getUser()->getEMailAddress()); diff --git a/settings/Panels/Admin/SecurityWarning.php b/settings/Panels/Admin/SecurityWarning.php index 0af9f8d1e528..dd6f92a69831 100644 --- a/settings/Panels/Admin/SecurityWarning.php +++ b/settings/Panels/Admin/SecurityWarning.php @@ -95,7 +95,7 @@ public function getPanel() { } $template->assign('OutdatedCacheWarning', $outdatedCaches); $template->assign('has_fileinfo', $this->helper->fileInfoLoaded()); - $databaseOverload = (\strpos($this->config->getSystemValue('dbtype'), 'sqlite') !== false); + $databaseOverload = (\strpos($this->config->getSystemValue('dbtype') ?? '', 'sqlite') !== false); $template->assign('databaseOverload', $databaseOverload); if ($this->lockingProvider instanceof NoopLockingProvider) { $template->assign('fileLockingType', 'none'); diff --git a/settings/templates/panels/admin/mail.php b/settings/templates/panels/admin/mail.php index 8604fb4d9a25..45394de5ffc9 100644 --- a/settings/templates/panels/admin/mail.php +++ b/settings/templates/panels/admin/mail.php @@ -1,15 +1,8 @@ $l->t('None'), - 'LOGIN' => $l->t('Login'), - 'PLAIN' => $l->t('Plain'), - 'NTLM' => $l->t('NT LAN Manager'), -]; $mail_smtpsecure = [ '' => $l->t('None'), 'ssl' => $l->t('SSL/TLS'), - 'tls' => $l->t('STARTTLS'), ]; $mail_smtpmode = [ 'php', @@ -80,17 +73,6 @@