From 34c53372b76c979c0f867c0f820ddf4485b668f5 Mon Sep 17 00:00:00 2001 From: Christian Hartmann Date: Tue, 24 Nov 2026 19:53:41 +0100 Subject: [PATCH] fix: unify checks for deleted questions and don't load submissions to deleted questions Signed-off-by: Christian Hartmann only file questions take uploads Signed-off-by: Christian Hartmann test(question): expect the status of each endpoint for deleted questions With deleted questions filtered in QuestionMapper::findById(), each endpoint answers a deleted question like an unknown one: deleteOption with 400, as it always did for an unknown question, and the others with 404, so the expected exception is set per data set. testUploadFiles now uploads for a file question, as uploads for other question types are rejected, and a new test covers both rejections: a short question (400) and a deleted file question (404). Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger fix(api): document the rejected question type of an upload as @throws The tag was spelled @htrows, so the OpenAPI extractor took the line for part of the endpoint description instead of a documented response. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger fix(submission): leave answers to deleted questions out of the search The results list and the export no longer show answers to deleted questions, but the search still matched them, so a search for a word that only appears in such an answer returned the submission without any visible match. The search now joins the questions and only matches answers to questions that are not deleted, for the list and the count alike. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger perf(submission): look up the active questions of answers by key Each answer was checked with in_array against all question ids of the form, which grows with answers times questions on every results load and export. The ids are now keys of an array, and the export reuses the id list it builds for the options anyway. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger fix(api): answer a missing option or question of deleteOption with 404 deleteOption documents "Could not find question or option" as a 404, like updateOption, but threw a 400. With deleted questions filtered in QuestionMapper::findById(), a deleted question would also have changed from 404 to 400 there; now all option and question endpoints answer a deleted or unknown question with 404. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger refactor(question): always skip deleted questions in findById No caller loads a deleted question by id, so the loadDeleted option goes, and an integration test checks against the database that findById finds an active question and skips a deleted one, which every endpoint now relies on. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger refactor(submission): build the lookup of active questions in one place getSubmissionsData built the same id lookup as the helper next to it. The helper now takes the questions, so all three callers share it, and the comments that repeated the code are gone. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger refactor(submission): take the questions table of the search from its mapper The search joined the answers table through its mapper but the questions table by a literal name. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger test(question): drop the unused deleted questions of the rejection tests findById() is mocked to throw in these tests, so the question objects with order 0 they built were never read. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger docs(api): describe the responses for deleted questions and non-file uploads Reordering with a deleted question and deleting an option of a deleted question now answer with Not Found, an upload for a question that is not a file question with Bad Request, and submissions, search and exports leave out answers to deleted questions. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger docs(question): state that findById does not find deleted questions Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger refactor(submission): require the active questions when reading answers The only caller of getAnswers always passes them, so the optional null case never ran. The confirmation email test uses the imported DoesNotExistException like the rest of the file. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger test(question): reject deleted and unknown questions on every endpoint The controller unit tests mock findById(), where a deleted and an unknown question look the same. Against the database, the API now gets a deleted question (deleted through the API first) and an id that does not exist on every question and option endpoint and on the upload, and expects 404 for both; an upload for a short question gets 400. The mapper test covers an unknown id next to an active and a deleted question. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger --- docs/API_v3.md | 6 +- lib/Controller/ApiController.php | 48 ++-------- lib/Db/QuestionMapper.php | 6 +- lib/Db/SubmissionMapper.php | 60 +++++++----- lib/Service/ConfirmationEmailService.php | 1 - lib/Service/SubmissionService.php | 41 ++++++-- openapi.json | 2 +- tests/Integration/Api/ApiV3Test.php | 48 ++++++++++ tests/Integration/DB/QuestionMapperTest.php | 93 +++++++++++++++++++ tests/Integration/DB/SubmissionMapperTest.php | 26 +++++- tests/Unit/Controller/ApiControllerTest.php | 82 ++++++++++------ .../Service/ConfirmationEmailServiceTest.php | 8 +- tests/Unit/Service/SubmissionServiceTest.php | 30 ++++++ 13 files changed, 339 insertions(+), 112 deletions(-) create mode 100644 tests/Integration/DB/QuestionMapperTest.php diff --git a/docs/API_v3.md b/docs/API_v3.md index 604af503db..46d6aae5e4 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 9b0a7c2d98..157732f9b2 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 c705ac3c1e..d1db60cadc 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 b0c104337f..eb4246827b 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 dcdb85b3c0..bd2276ef0b 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 3d7f78b90b..b379b97529 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 d97ee439c5..58430d3e15 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 0a9483cb8f..1cfdbfa30b 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 0000000000..1eb1d93e70 --- /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 7f76fa218f..51db8d39b7 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 19961f1135..53181b547a 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 afc8198724..df0ee7aad9 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 9159359b36..c151c34b85 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,