diff --git a/docs/API_v3.md b/docs/API_v3.md index 604af503d..46d6aae5e 100644 --- a/docs/API_v3.md +++ b/docs/API_v3.md @@ -480,6 +480,7 @@ Reorders all Questions of a single form | _newOrder_ | Array | Array of **all** Question-IDs, ordered in the desired order | - Restrictions: The Array **must** contain all Question-IDs corresponding to the specified form and **must not** contain any duplicates. - Response: Array of questionIDs and their corresponding order. + An id of a deleted question gets a **Not Found** response. ``` "data": { @@ -598,6 +599,7 @@ Update a single or all properties of an option-object | _questionId_ | Integer | ID of the question, the new option will belong to | | _optionId_ | Integer | ID of the option to delete | - Response: **Status-Code OK**, as well as the id of the deleted option. + An option or question that does not exist, and a deleted question, get a **Not Found** response. ``` "data": 7 @@ -723,6 +725,7 @@ Get all Submissions to a Form | _limit_ | Integer | How many items to get | | _offset_ | Integer | How many items to skip for a pagination | - Response: An Array of all submissions, sorted as newest first, as well as an array of the corresponding questions. + Answers to deleted questions are left out, and the search does not match them. ``` "data": { @@ -826,7 +829,7 @@ Returns all submissions to the form in form of a csv-file. |--------------|---------|-------------| | _formId_ | Integer | Id of the form to get the submissions for | | _fileFormat_ | String | `csv|ods|xlsx` | -- Response: A Data Download Response containing the headers `Content-Disposition: attachment; filename="Form 1 (responses).csv"` and `Content-Type: text/csv;charset=UTF-8`. The actual data contains all submissions to the referred form, formatted as comma separated and escaped csv. For file format `ods` or `xlsx` the Download Response contains an Open Document Spreadsheet or an Office Open XML Spreadsheet file. +- Response: A Data Download Response containing the headers `Content-Disposition: attachment; filename="Form 1 (responses).csv"` and `Content-Type: text/csv;charset=UTF-8`. The actual data contains all submissions to the referred form, without answers to deleted questions, formatted as comma separated and escaped csv. For file format `ods` or `xlsx` the Download Response contains an Open Document Spreadsheet or an Office Open XML Spreadsheet file. ``` "User display name","Timestamp","Question 1","Question 2" @@ -888,6 +891,7 @@ Upload a file to a file question before form submission. Each uploaded file is s | _files_ | Array of files | Files to upload | | _shareHash_ | String | optional, only necessary for uploads on a public share link | - Response: **Status-Code OK**, as well as a list of uploaded files. + An upload for a question that is not a file question gets a **Bad Request** response, and a deleted question gets a **Not Found** response. ``` "data": [ diff --git a/lib/Controller/ApiController.php b/lib/Controller/ApiController.php index 9b0a7c2d9..157732f9b 100644 --- a/lib/Controller/ApiController.php +++ b/lib/Controller/ApiController.php @@ -510,7 +510,7 @@ public function getQuestion(int $formId, int $questionId): DataResponse { } $question = $this->formsService->getQuestion($questionId); - if ($question === null || $question['order'] === 0) { + if ($question === null) { throw new OCSNotFoundException('Question doesn\'t exist'); } @@ -633,9 +633,6 @@ public function newQuestion(int $formId, ?string $type = null, ?string $subtype if ($sourceQuestion->getFormId() !== $formId) { throw new OCSBadRequestException('Question doesn\'t belong to given form'); } - if ($sourceQuestion->getOrder() === 0) { - throw new OCSNotFoundException('Could not find question'); - } $sourceOptions = $this->optionMapper->findByQuestion($fromId); } catch (IMapperException) { $this->logger->debug('Could not find question'); @@ -735,10 +732,6 @@ public function updateQuestion(int $formId, int $questionId, array $keyValuePair throw new OCSBadRequestException('Question doesn\'t belong to given Form'); } - if ($question->getOrder() === 0) { - throw new OCSNotFoundException('Could not find question'); - } - // Don't allow empty array if (count($keyValuePairs) === 0) { $this->logger->info('Empty keyValuePairs, will not update.'); @@ -825,10 +818,6 @@ public function deleteQuestion(int $formId, int $questionId): DataResponse { throw new OCSBadRequestException('Question doesn\'t belong to given Form'); } - if ($question->getOrder() === 0) { - throw new OCSNotFoundException('Could not find question'); - } - // Store Order of deleted Question $deletedOrder = $question->getOrder(); @@ -872,7 +861,6 @@ public function deleteQuestion(int $formId, int $questionId): DataResponse { * @throws OCSBadRequestException The given array contains duplicates * @throws OCSBadRequestException The length of the given array does not match the number of stored questions * @throws OCSBadRequestException Question doesn't belong to given Form - * @throws OCSBadRequestException One question has already been marked as deleted * @throws OCSForbiddenException This form is archived and can not be modified * @throws OCSForbiddenException User has no permissions to get this form * @throws OCSNotFoundException Could not find form @@ -933,16 +921,8 @@ public function reorderQuestions(int $formId, array $newOrder): DataResponse { throw new OCSBadRequestException('Question doesn\'t belong to given Form'); } - // Abort if a question is already marked as deleted (order==0) - $oldOrder = $questions[$arrayKey]->getOrder(); - if ($oldOrder === 0) { - $this->logger->debug('This question has already been marked as deleted: Id: {questionId}', [ - 'questionId' => $questions[$arrayKey]->getId() - ]); - throw new OCSBadRequestException('One question has already been marked as deleted'); - } - // Only set order, if it changed. + $oldOrder = $questions[$arrayKey]->getOrder(); if ($oldOrder !== $arrayKey + 1) { // Set Order. ArrayKey counts from zero, order counts from 1. $questions[$arrayKey]->setOrder($arrayKey + 1); @@ -1017,10 +997,6 @@ public function newOption(int $formId, int $questionId, array $optionTexts, ?str throw new OCSBadRequestException('This question is not part ot the given form'); } - if ($question->getOrder() === 0) { - throw new OCSNotFoundException('Could not find question'); - } - $allowedOptionTypes = Constants::OPTION_TYPES_PER_ANSWER_TYPE[$question->getType()] ?? []; if ($allowedOptionTypes === []) { $this->logger->debug('This question type takes no options'); @@ -1117,10 +1093,6 @@ public function updateOption(int $formId, int $questionId, int $optionId, array throw new OCSBadRequestException('The given option id doesn\'t match the question or form.'); } - if ($question->getOrder() === 0) { - throw new OCSNotFoundException('Could not find question'); - } - // Don't allow empty array if (count($keyValuePairs) === 0) { $this->logger->info('Empty keyValuePairs, will not update'); @@ -1182,7 +1154,7 @@ public function deleteOption(int $formId, int $questionId, int $optionId): DataR $question = $this->questionMapper->findById($questionId); } catch (IMapperException) { $this->logger->debug('Could not find option or question'); - throw new OCSBadRequestException('Could not find option or question'); + throw new OCSNotFoundException('Could not find option or question'); } if ($option->getQuestionId() !== $questionId || $question->getFormId() !== $formId) { @@ -1190,10 +1162,6 @@ public function deleteOption(int $formId, int $questionId, int $optionId): DataR throw new OCSBadRequestException('The given option id doesn\'t match the question or form.'); } - if ($question->getOrder() === 0) { - throw new OCSNotFoundException('Could not find question'); - } - $this->optionMapper->delete($option); // Reorder the remaining options @@ -1252,10 +1220,6 @@ public function reorderOptions(int $formId, int $questionId, array $newOrder, ?s throw new OCSBadRequestException('The given question id doesn\'t match the form.'); } - if ($question->getOrder() === 0) { - throw new OCSNotFoundException('Could not find question'); - } - // Check if array contains duplicates if (array_unique($newOrder) !== $newOrder) { $this->logger->debug('The given array contains duplicates'); @@ -1790,6 +1754,7 @@ public function exportSubmissionsToCloud(int $formId, string $path, string $file * @return DataResponse, array{}> * @throws OCSBadRequestException No files provided * @throws OCSBadRequestException Question doesn't belong to the given form + * @throws OCSBadRequestException Wrong question type * @throws OCSBadRequestException Invalid file provided * @throws OCSBadRequestException Failed to upload the file * @throws OCSBadRequestException File size exceeds the maximum allowed size @@ -1844,6 +1809,11 @@ public function uploadFiles(int $formId, int $questionId, string $shareHash = '' throw new OCSBadRequestException('Question doesn\'t belong to the given form'); } + if ($question->getType() !== Constants::ANSWER_TYPE_FILE) { + $this->logger->debug('Question {questionId} is no file question', ['questionId' => $questionId]); + throw new OCSBadRequestException('Wrong question type'); + } + $path = $this->formsService->getTemporaryUploadedFilePath($form, $question); $response = []; diff --git a/lib/Db/QuestionMapper.php b/lib/Db/QuestionMapper.php index c705ac3c1..d1db60cad 100644 --- a/lib/Db/QuestionMapper.php +++ b/lib/Db/QuestionMapper.php @@ -72,8 +72,9 @@ public function deleteByForm(int $formId): void { } /** - * Find Question by its ID + * Find Question by its ID, unless it is deleted * @param int|float $questionId The question ID (int but for 32bit systems PHP uses float) + * @throws DoesNotExistException if the question does not exist or is deleted */ public function findById(int|float $questionId): Question { $qb = $this->db->getQueryBuilder(); @@ -82,6 +83,9 @@ public function findById(int|float $questionId): Question { ->from($this->getTableName()) ->where( $qb->expr()->eq('id', $qb->createNamedParameter($questionId, IQueryBuilder::PARAM_INT)) + ) + ->andWhere( + $qb->expr()->neq('order', $qb->createNamedParameter(0, IQueryBuilder::PARAM_INT)) ); return $this->findEntity($qb); diff --git a/lib/Db/SubmissionMapper.php b/lib/Db/SubmissionMapper.php index b0c104337..eb4246827 100644 --- a/lib/Db/SubmissionMapper.php +++ b/lib/Db/SubmissionMapper.php @@ -25,12 +25,14 @@ class SubmissionMapper extends QBMapper { * SubmissionMapper constructor. * @param IDBConnection $db * @param AnswerMapper $answerMapper + * @param QuestionMapper $questionMapper * @param FilePathHelper $filePathHelper * @param LoggerInterface $logger */ public function __construct( IDBConnection $db, private readonly AnswerMapper $answerMapper, + private readonly QuestionMapper $questionMapper, private readonly FilePathHelper $filePathHelper, private readonly LoggerInterface $logger, ) { @@ -69,25 +71,44 @@ public function findByForm(int $formId, ?string $userId = null, ?string $searchS ->setFirstResult($offset) ->setMaxResults($limit); - // If a query is provided, join the answers table and filter by the query text if (!is_null($searchString) && $searchString !== '') { - $qb->join( - 'submissions', - $this->answerMapper->getTableName(), - 'answers', - $qb->expr()->eq('submissions.id', 'answers.submission_id') - ) - ->andWhere( - $qb->expr()->orX( - $qb->expr()->iLike('submissions.user_id', $qb->createNamedParameter('%' . $searchString . '%')), - $qb->expr()->iLike('answers.text', $qb->createNamedParameter('%' . $searchString . '%')), - ), - ); + $this->filterBySearch($qb, $searchString); } return $this->findEntities($qb); } + /** + * Restricts the submissions to those whose user id or an answer to a question that is not deleted contains the search string + * + * @param IQueryBuilder $qb query on the submissions table with the alias `submissions` + * @param string $searchString the search string + */ + private function filterBySearch(IQueryBuilder $qb, string $searchString): void { + $pattern = $qb->createNamedParameter('%' . $searchString . '%'); + $qb->join( + 'submissions', + $this->answerMapper->getTableName(), + 'answers', + $qb->expr()->eq('submissions.id', 'answers.submission_id') + ) + ->join( + 'answers', + $this->questionMapper->getTableName(), + 'questions', + $qb->expr()->eq('answers.question_id', 'questions.id') + ) + ->andWhere( + $qb->expr()->orX( + $qb->expr()->iLike('submissions.user_id', $pattern), + $qb->expr()->andX( + $qb->expr()->iLike('answers.text', $pattern), + $qb->expr()->neq('questions.order', $qb->createNamedParameter(0, IQueryBuilder::PARAM_INT)), + ), + ), + ); + } + /** * @param int $id * @return Submission @@ -194,18 +215,7 @@ protected function countSubmissionsWithFilters(int $formId, ?string $userId = nu } if (!is_null($searchString) && $searchString !== '') { - $query->join( - 'submissions', - $this->answerMapper->getTableName(), - 'answers', - $qb->expr()->eq('submissions.id', 'answers.submission_id') - ) - ->andWhere( - $qb->expr()->orX( - $qb->expr()->iLike('submissions.user_id', $qb->createNamedParameter('%' . $searchString . '%')), - $qb->expr()->iLike('answers.text', $qb->createNamedParameter('%' . $searchString . '%')), - ), - ); + $this->filterBySearch($query, $searchString); } if ($limit !== -1) { diff --git a/lib/Service/ConfirmationEmailService.php b/lib/Service/ConfirmationEmailService.php index dcdb85b3c..bd2276ef0 100644 --- a/lib/Service/ConfirmationEmailService.php +++ b/lib/Service/ConfirmationEmailService.php @@ -115,7 +115,6 @@ public function validateRecipientQuestionId(Form $form, mixed $recipientId): voi } if ($question->getFormId() !== $form->getId() - || $question->getOrder() === 0 || !$question->isEmailType()) { throw new \InvalidArgumentException('Invalid confirmationEmailQuestionId'); } diff --git a/lib/Service/SubmissionService.php b/lib/Service/SubmissionService.php index 3d7f78b90..b379b9752 100644 --- a/lib/Service/SubmissionService.php +++ b/lib/Service/SubmissionService.php @@ -81,13 +81,17 @@ public function __construct( * Get all the answers of a given submission * * @param int $submissionId the submission id + * @param array $activeQuestionIds ids of the active questions as keys, to filter answers * @return list */ - private function getAnswers(int $submissionId): array { + private function getAnswers(int $submissionId, array $activeQuestionIds): array { $answerList = []; try { $answerEntities = $this->answerMapper->findBySubmission($submissionId); foreach ($answerEntities as $answerEntity) { + if (!isset($activeQuestionIds[$answerEntity->getQuestionId()])) { + continue; + } $answerList[] = $answerEntity->read(); } } catch (DoesNotExistException) { @@ -97,6 +101,16 @@ private function getAnswers(int $submissionId): array { } } + /** + * Get the ids of the given questions as keys + * + * @param list $questions questions that are not deleted + * @return array the question ids as keys + */ + private function getActiveQuestionIds(array $questions): array { + return array_fill_keys(array_map(static fn (Question $question) => $question->getId(), $questions), true); + } + /** * Get all submissions of a form * @@ -124,12 +138,17 @@ public function getSubmissions(int $formId, ?string $userId = null, ?string $que $answersBySubmission[$answer->getSubmissionId()][] = $answer; } + $activeQuestionIds = $this->getActiveQuestionIds($this->questionMapper->findByForm($formId)); + foreach ($submissionEntities as $submissionEntity) { $submission = $submissionEntity->read(); - $submission['answers'] = array_map( - static fn (Answer $answer) => $answer->read(), - $answersBySubmission[$submission['id']] ?? [] - ); + $answers = []; + foreach ($answersBySubmission[$submission['id']] ?? [] as $answer) { + if (isset($activeQuestionIds[$answer->getQuestionId()])) { + $answers[] = $answer->read(); + } + } + $submission['answers'] = $answers; $submissionList[] = $submission; } } catch (DoesNotExistException) { @@ -155,7 +174,8 @@ public function getSubmission(int $submissionId): ?array { try { $submissionEntity = $this->submissionMapper->findById($submissionId); $submission = $submissionEntity->read(); - $submission['answers'] = $this->getAnswers($submission['id']); + $activeQuestionIds = $this->getActiveQuestionIds($this->questionMapper->findByForm($submission['formId'])); + $submission['answers'] = $this->getAnswers($submission['id'], $activeQuestionIds); return $submission; } catch (DoesNotExistException) { return null; @@ -249,6 +269,9 @@ public function getSubmissionsData(Form $form, string $fileFormat, ?File $file = $submissionEntities = array_reverse($submissionEntities); $questions = $this->questionMapper->findByForm($form->getId()); + + $activeQuestionIds = $this->getActiveQuestionIds($questions); + $defaultTimeZone = $this->config->getSystemValueString('default_timezone', 'UTC'); if (!$this->currentUser) { @@ -261,6 +284,9 @@ public function getSubmissionsData(Form $form, string $fileFormat, ?File $file = $submissionIds = array_map(static fn (Submission $submission) => $submission->getId(), $submissionEntities); $answersBySubmission = []; foreach ($this->answerMapper->findBySubmissions($submissionIds) as $answer) { + if (!isset($activeQuestionIds[$answer->getQuestionId()])) { + continue; + } $answersBySubmission[$answer->getSubmissionId()][] = $answer; } @@ -271,9 +297,8 @@ public function getSubmissionsData(Form $form, string $fileFormat, ?File $file = } // Fetch all options of the form's questions at once, grouped by question - $questionIds = array_map(static fn (Question $question) => $question->getId(), $questions); $optionsByQuestion = []; - foreach ($this->optionMapper->findByQuestions($questionIds) as $option) { + foreach ($this->optionMapper->findByQuestions(array_keys($activeQuestionIds)) as $option) { $optionsByQuestion[$option->getQuestionId()][] = $option; } diff --git a/openapi.json b/openapi.json index d97ee439c..58430d3e1 100644 --- a/openapi.json +++ b/openapi.json @@ -1997,7 +1997,7 @@ } }, "400": { - "description": "One question has already been marked as deleted", + "description": "Question doesn't belong to given Form", "content": { "application/json": { "schema": { diff --git a/tests/Integration/Api/ApiV3Test.php b/tests/Integration/Api/ApiV3Test.php index 0a9483cb8..1cfdbfa30 100644 --- a/tests/Integration/Api/ApiV3Test.php +++ b/tests/Integration/Api/ApiV3Test.php @@ -1072,6 +1072,54 @@ public function testDeleteFileQuestion() { $this->assertNotContains($fileQuestionId, $questionIds); } + public static function dataMissingQuestion(): array { + return [ + 'deleted question' => [true], + 'unknown question' => [false], + ]; + } + + /** + * @dataProvider dataMissingQuestion + */ + public function testQuestionEndpointsRejectMissingQuestion(bool $deleted): void { + $formId = $this->testForms[0]['id']; + $questions = $this->testForms[0]['questions']; + $questionId = $deleted ? $questions[1]['id'] : 2147483647; + $optionId = $questions[1]['options'][0]['id']; + if ($deleted) { + $resp = $this->http->request('DELETE', "api/v3/forms/{$formId}/questions/{$questionId}"); + $this->assertEquals(200, $resp->getStatusCode()); + } + $newOrder = $deleted ? [$questions[0]['id'], $questionId] : [$questions[0]['id'], $questionId, $questions[2]['id']]; + + $requests = [ + 'get question' => ['GET', "api/v3/forms/{$formId}/questions/{$questionId}", []], + 'update question' => ['PATCH', "api/v3/forms/{$formId}/questions/{$questionId}", ['json' => ['keyValuePairs' => ['text' => 'New text']]]], + 'delete question' => ['DELETE', "api/v3/forms/{$formId}/questions/{$questionId}", []], + 'clone question' => ['POST', "api/v3/forms/{$formId}/questions", ['json' => ['fromId' => $questionId]]], + 'reorder questions' => ['PATCH', "api/v3/forms/{$formId}/questions", ['json' => ['newOrder' => $newOrder]]], + 'new option' => ['POST', "api/v3/forms/{$formId}/questions/{$questionId}/options", ['json' => ['optionTexts' => ['New option']]]], + 'update option' => ['PATCH', "api/v3/forms/{$formId}/questions/{$questionId}/options/{$optionId}", ['json' => ['keyValuePairs' => ['text' => 'New text']]]], + 'delete option' => ['DELETE', "api/v3/forms/{$formId}/questions/{$questionId}/options/{$optionId}", []], + 'reorder options' => ['PATCH', "api/v3/forms/{$formId}/questions/{$questionId}/options", ['json' => ['newOrder' => [$optionId]]]], + 'upload file' => ['POST', "api/v3/forms/{$formId}/submissions/files/{$questionId}", ['multipart' => [['name' => 'files[]', 'contents' => 'test file content', 'filename' => 'test.txt']]]], + ]; + foreach ($requests as $name => [$method, $url, $options]) { + $resp = $this->http->request($method, $url, $options + ['http_errors' => false]); + $this->assertEquals(404, $resp->getStatusCode(), $name); + } + } + + public function testUploadFileRejectsNonFileQuestion(): void { + $resp = $this->http->request('POST', "api/v3/forms/{$this->testForms[0]['id']}/submissions/files/{$this->testForms[0]['questions'][0]['id']}", [ + 'multipart' => [['name' => 'files[]', 'contents' => 'test file content', 'filename' => 'test.txt']], + 'http_errors' => false, + ]); + + $this->assertEquals(400, $resp->getStatusCode()); + } + public function testCloneQuestion() { $resp = $this->http->request('POST', "api/v3/forms/{$this->testForms[0]['id']}/questions?fromId=" . $this->testForms[0]['questions'][0]['id']); $data = $this->OcsResponse2Data($resp); diff --git a/tests/Integration/DB/QuestionMapperTest.php b/tests/Integration/DB/QuestionMapperTest.php new file mode 100644 index 000000000..1eb1d93e7 --- /dev/null +++ b/tests/Integration/DB/QuestionMapperTest.php @@ -0,0 +1,93 @@ + 'Test user', + ]; + + public function setUp(): void { + $this->testForms = [ + [ + 'hash' => 'question_mapper_form', + 'title' => 'Question mapper form', + 'description' => '', + 'owner_id' => 'test', + 'access_enum' => 0, + 'created' => 12345, + 'expires' => 0, + 'state' => 0, + 'is_anonymous' => false, + 'submit_multiple' => false, + 'show_expiration' => false, + 'last_updated' => 123456789, + 'submission_message' => '', + 'file_id' => null, + 'file_format' => null, + 'allow_comments' => false, + 'questions' => [ + [ + 'type' => 'short', + 'text' => 'Active question', + 'isRequired' => false, + 'name' => '', + 'order' => 1, + 'options' => [], + 'accept' => [], + 'description' => '', + 'extraSettings' => [], + ], + [ + 'type' => 'short', + 'text' => 'Deleted question', + 'isRequired' => false, + 'name' => '', + 'order' => 0, + 'options' => [], + 'accept' => [], + 'description' => '', + 'extraSettings' => [], + ], + ], + 'shares' => [], + 'submissions' => [], + ], + ]; + parent::setUp(); + + $this->questionMapper = \OCP\Server::get(QuestionMapper::class); + } + + public function testFindByIdFindsActiveQuestion(): void { + $question = $this->questionMapper->findById($this->testForms[0]['questions'][0]['id']); + + $this->assertSame('Active question', $question->getText()); + } + + public function testFindByIdSkipsDeletedQuestion(): void { + $this->expectException(DoesNotExistException::class); + $this->questionMapper->findById($this->testForms[0]['questions'][1]['id']); + } + + public function testFindByIdThrowsForUnknownQuestion(): void { + $this->expectException(DoesNotExistException::class); + $this->questionMapper->findById(2147483647); + } +} diff --git a/tests/Integration/DB/SubmissionMapperTest.php b/tests/Integration/DB/SubmissionMapperTest.php index 7f76fa218..51db8d39b 100644 --- a/tests/Integration/DB/SubmissionMapperTest.php +++ b/tests/Integration/DB/SubmissionMapperTest.php @@ -55,6 +55,17 @@ private function setTestForms() { 'accept' => [], 'description' => 'Please answer this.', 'extraSettings' => [] + ], + [ + 'type' => 'short', + 'text' => 'Deleted Question?', + 'isRequired' => false, + 'name' => '', + 'order' => 0, + 'options' => [], + 'accept' => [], + 'description' => '', + 'extraSettings' => [] ] ], 'shares' => [], @@ -76,6 +87,10 @@ private function setTestForms() { [ 'questionIndex' => 0, 'text' => 'Answer 2' + ], + [ + 'questionIndex' => 1, + 'text' => 'Deleted term' ] ] ], @@ -121,9 +136,10 @@ public function setUp(): void { $db = \OCP\Server::get(IDBConnection::class); $answerMapper = \OCP\Server::get(\OCA\Forms\Db\AnswerMapper::class); + $questionMapper = \OCP\Server::get(\OCA\Forms\Db\QuestionMapper::class); $filePathHelper = \OCP\Server::get(\OCA\Forms\Helper\FilePathHelper::class); $logger = \OCP\Server::get(\Psr\Log\LoggerInterface::class); - $this->submissionMapper = new SubmissionMapper($db, $answerMapper, $filePathHelper, $logger); + $this->submissionMapper = new SubmissionMapper($db, $answerMapper, $questionMapper, $filePathHelper, $logger); } public function testFindByFormBasic(): void { @@ -150,6 +166,10 @@ public function testFindByFormWithSearchQuery(): void { $this->assertEquals('user2', $submissions[0]->getUserId()); } + public function testFindByFormSearchSkipsAnswersToDeletedQuestions(): void { + $this->assertCount(0, $this->submissionMapper->findByForm($this->testForms[0]['id'], null, 'Deleted term')); + } + public function testFindByFormWithLimit(): void { $submissions = $this->submissionMapper->findByForm($this->testForms[0]['id'], null, null, 2); @@ -180,6 +200,10 @@ public function testCountSubmissionsWithSearch(): void { $this->assertEquals(1, $count); } + public function testCountSubmissionsSearchSkipsAnswersToDeletedQuestions(): void { + $this->assertEquals(0, $this->submissionMapper->countSubmissions($this->testForms[0]['id'], null, 'Deleted term')); + } + public function testCountSubmissionsEmptyForm(): void { $count = $this->submissionMapper->countSubmissions($this->testForms[1]['id']); diff --git a/tests/Unit/Controller/ApiControllerTest.php b/tests/Unit/Controller/ApiControllerTest.php index 19961f113..53181b547 100644 --- a/tests/Unit/Controller/ApiControllerTest.php +++ b/tests/Unit/Controller/ApiControllerTest.php @@ -771,7 +771,7 @@ public function testUploadFiles() { $form->setId(1); $form->setHash('hash'); $form->setOwnerId('currentUser'); - $question = Question::fromParams(['formId' => 1]); + $question = Question::fromParams(['formId' => 1, 'type' => Constants::ANSWER_TYPE_FILE]); $this->formsService->expects($this->once()) ->method('loadFormForSubmission') @@ -832,6 +832,48 @@ public function testUploadFiles() { $this->apiController->uploadFiles(1, 10, ''); } + public static function dataUploadFilesNoFileQuestion(): array { + return [ + 'short question' => [Constants::ANSWER_TYPE_SHORT, false, OCSBadRequestException::class], + 'deleted file question' => [Constants::ANSWER_TYPE_FILE, true, OCSNotFoundException::class], + ]; + } + + /** + * @dataProvider dataUploadFilesNoFileQuestion + */ + public function testUploadFilesNoFileQuestion(string $type, bool $deleted, string $exception): void { + $form = new Form(); + $form->setId(1); + $form->setHash('hash'); + $form->setOwnerId('currentUser'); + + $this->formsService->method('loadFormForSubmission') + ->with(1) + ->willReturn($form); + $this->formsService->method('canSubmit') + ->willReturn(true); + $lookup = $this->questionMapper->method('findById')->with(10); + if ($deleted) { + $lookup->willThrowException(new DoesNotExistException('Question is deleted')); + } else { + $lookup->willReturn(Question::fromParams(['formId' => 1, 'type' => $type])); + } + $this->request->method('getUploadedFile') + ->with('files') + ->willReturn([ + 'size' => [100], + 'tmp_name' => [tempnam('/tmp', 'test')], + 'name' => ['file.txt'], + 'error' => [0], + ]); + $this->storage->expects($this->never()) + ->method('getUserFolder'); + + $this->expectException($exception); + $this->apiController->uploadFiles(1, 10, ''); + } + public function testNewSubmission_answers() { $form = new Form(); $form->setId(1); @@ -1371,28 +1413,22 @@ public function testUpdateFormRejectsInvalidConfirmationEmailQuestionId(string $ public static function dataChangeDeletedQuestion(): array { return [ - 'update question' => ['updateQuestion', [1, 7, ['text' => 'New text']]], - 'new option' => ['newOption', [1, 7, ['New option']]], - 'update option' => ['updateOption', [1, 7, 3, ['text' => 'New text']]], - 'delete option' => ['deleteOption', [1, 7, 3]], - 'reorder options' => ['reorderOptions', [1, 7, [3]]], + 'update question' => ['updateQuestion', [1, 7, ['text' => 'New text']], OCSNotFoundException::class], + 'new option' => ['newOption', [1, 7, ['New option']], OCSNotFoundException::class], + 'update option' => ['updateOption', [1, 7, 3, ['text' => 'New text']], OCSNotFoundException::class], + 'delete option' => ['deleteOption', [1, 7, 3], OCSNotFoundException::class], + 'reorder options' => ['reorderOptions', [1, 7, [3]], OCSNotFoundException::class], ]; } /** * @dataProvider dataChangeDeletedQuestion */ - public function testChangeDeletedQuestion(string $method, array $arguments): void { + public function testChangeDeletedQuestion(string $method, array $arguments, string $exception): void { $form = new Form(); $form->setId(1); $form->setOwnerId('currentUser'); - $question = new Question(); - $question->setId(7); - $question->setFormId(1); - $question->setType(Constants::ANSWER_TYPE_MULTIPLE); - $question->setOrder(0); - $this->formsService ->method('getFormIfAllowed') ->with(1, Constants::PERMISSION_EDIT) @@ -1404,7 +1440,7 @@ public function testChangeDeletedQuestion(string $method, array $arguments): voi $this->questionMapper ->method('findById') ->with(7) - ->willReturn($question); + ->willThrowException(new DoesNotExistException('Question not found')); $this->optionMapper ->method('findById') ->with(3) @@ -1415,7 +1451,7 @@ public function testChangeDeletedQuestion(string $method, array $arguments): voi $this->optionMapper->expects($this->never())->method('delete'); $this->formMapper->expects($this->never())->method('update'); - $this->expectException(OCSNotFoundException::class); + $this->expectException($exception); $this->apiController->$method(...$arguments); } @@ -1690,14 +1726,9 @@ public function testDeleteQuestionRejectsDeletedQuestion(): void { $form->setId(1); $form->setOwnerId('currentUser'); - $question = new Question(); - $question->setId(7); - $question->setFormId(1); - $question->setOrder(0); - $this->formsService->method('getFormIfAllowed')->with(1, Constants::PERMISSION_EDIT)->willReturn($form); $this->formsService->method('isFormArchived')->with($form)->willReturn(false); - $this->questionMapper->method('findById')->with(7)->willReturn($question); + $this->questionMapper->method('findById')->with(7)->willThrowException(new DoesNotExistException('Question not found')); $this->questionMapper->expects($this->never())->method('update'); $this->formMapper->expects($this->never())->method('update'); @@ -1800,14 +1831,9 @@ public function testCloneQuestionRejectsDeletedQuestion(): void { $form->setId(1); $form->setOwnerId('currentUser'); - $question = new Question(); - $question->setId(7); - $question->setFormId(1); - $question->setOrder(0); - $this->formsService->method('getFormIfAllowed')->with(1, Constants::PERMISSION_EDIT)->willReturn($form); $this->formsService->method('isFormArchived')->with($form)->willReturn(false); - $this->questionMapper->method('findById')->with(7)->willReturn($question); + $this->questionMapper->method('findById')->with(7)->willThrowException(new DoesNotExistException('Question not found')); $this->questionMapper->expects($this->never())->method('insert'); $this->expectException(OCSNotFoundException::class); @@ -2208,7 +2234,7 @@ public function testGetDeletedQuestion(): void { ->willReturn(true); $this->formsService->method('getQuestion') ->with(2) - ->willReturn(['id' => 2, 'formId' => 1, 'order' => 0, 'text' => 'Deleted', 'extraSettings' => []]); + ->willReturn(null); $this->expectException(OCSNotFoundException::class); $this->apiController->getQuestion(1, 2); diff --git a/tests/Unit/Service/ConfirmationEmailServiceTest.php b/tests/Unit/Service/ConfirmationEmailServiceTest.php index afc819872..df0ee7aad 100644 --- a/tests/Unit/Service/ConfirmationEmailServiceTest.php +++ b/tests/Unit/Service/ConfirmationEmailServiceTest.php @@ -423,13 +423,7 @@ public function testValidateRecipientQuestionIdRejectsDeletedQuestion(): void { $form = new Form(); $form->setId(1); - $question = new Question(); - $question->setFormId(1); - $question->setOrder(0); - $question->setType(Constants::ANSWER_TYPE_SHORT); - $question->setExtraSettings(['validationType' => 'email']); - - $this->questionMapper->method('findById')->willReturn($question); + $this->questionMapper->method('findById')->willThrowException(new DoesNotExistException('Question not found')); $this->expectException(\InvalidArgumentException::class); $this->service->validateRecipientQuestionId($form, 7); } diff --git a/tests/Unit/Service/SubmissionServiceTest.php b/tests/Unit/Service/SubmissionServiceTest.php index 9159359b3..c151c34b8 100644 --- a/tests/Unit/Service/SubmissionServiceTest.php +++ b/tests/Unit/Service/SubmissionServiceTest.php @@ -144,6 +144,16 @@ public function testGetSubmissions() { $submission_2->setUserId('someOtherUser'); $submission_2->setTimestamp(1234); + $question_1 = new Question(); + $question_1->setId(422); + $question_1->setFormId(5); + $question_1->setOrder(1); + + $question_2 = new Question(); + $question_2->setId(423); + $question_2->setFormId(5); + $question_2->setOrder(2); + $this->submissionMapper->expects($this->any()) ->method('findByForm') ->willReturnCallback(function ($formId, $userId = null) use ($submission_1, $submission_2) { @@ -163,6 +173,11 @@ public function testGetSubmissions() { return []; }); + $this->questionMapper->expects($this->any()) + ->method('findByForm') + ->with(5) + ->willReturn([$question_1, $question_2]); + $expected = [ [ 'id' => 42, @@ -218,6 +233,16 @@ public function testGetSubmission() { $answer_2->setQuestionId(423); $answer_2->setText('Just some more Text'); + $question_1 = new Question(); + $question_1->setId(422); + $question_1->setFormId(5); + $question_1->setOrder(1); + + $question_2 = new Question(); + $question_2->setId(423); + $question_2->setFormId(5); + $question_2->setOrder(2); + $this->submissionMapper->expects($this->once()) ->method('findById') ->with(42) @@ -229,6 +254,11 @@ public function testGetSubmission() { [42, [$answer_1, $answer_2]] ]); + $this->questionMapper->expects($this->any()) + ->method('findByForm') + ->with(5) + ->willReturn([$question_1, $question_2]); + $expected = [ 'id' => 42, 'formId' => 5,