Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions docs/API_v3.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Some requests succeed with their usual status, and their payload keeps its shape

| Key | Value | Set by | Meaning |
|-----|-------|--------|---------|
| `removed-jumps` | Inner list of question ids, e.g. `(3 7)` | Updating, reordering and copying questions; deleting options; changing the bounds of a linear scale | Jumps to the question itself or to an earlier question, jumps of the deleted option or of options that are not options of the question, or jumps for values outside the scale, were removed from the `extraSettings` of these questions, see [Jumps](DataStructure.md#jumps) |
| `removed-jumps` | Inner list of question ids, e.g. `(3 7)` | Updating, reordering and copying questions; deleting the first section of a form; deleting options; changing the bounds of a linear scale | Jumps to the question itself or to an earlier question, jumps of the deleted option or of options that are not options of the question, or jumps for values outside the scale, were removed from the `extraSettings` of these questions, see [Jumps](DataStructure.md#jumps) |

```
X-Forms-Adjusted: removed-jumps=(3 7)
Expand Down Expand Up @@ -395,7 +395,7 @@ Returns the questions and options of the given form (without submissions).
| _subtype_ | String | yes | _Optional_ The sub type, stored as `extraSettings.questionType`: the cell type for `grid` (`checkbox`, `number` or `radio`), `rating` (a 1 to N scale drawn as icons) or `promoter` (a fixed 0 to 10 scale) for `linearscale`. Any other value is rejected. |
| _text_ | String | yes | _Optional_ The text of the new question. |
| _position_ | Integer | yes | _(optional)_ 1-based position to insert the new question. When omitted the question is appended at the end. |
- Restrictions: A `grid` question needs its cell type as _subtype_. A _subtype_ for a question type without sub types is rejected with **400 Bad Request**.
- Restrictions: A `grid` question needs its cell type as _subtype_. A _subtype_ for a question type without sub types is rejected with **400 Bad Request**. In a form with sections every question is in a section (see [Sections](DataStructure.md#sections)): a question or section that would add to the questions before the first section, for example a section appended below the questions of a form without sections, is rejected with **400 Bad Request** "Every question must be in a section".
- Response: The new question object.

```
Expand Down Expand Up @@ -494,7 +494,7 @@ Reorders all Questions of a single form
| Parameter | Type | Description |
|-----------|---------|-------------|
| _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.
- Restrictions: The Array **must** contain all Question-IDs corresponding to the specified form and **must not** contain any duplicates. An order that puts more questions before the first section than before is rejected with **400 Bad Request** "Every question must be in a section" (see [Sections](DataStructure.md#sections)).
- Response: Array of questionIDs and their corresponding order. Jumps that would go to the question itself or to an earlier question are removed (see [Jumps](DataStructure.md#jumps)): the questions concerned also carry their new `extraSettings`, and the response header `X-Forms-Adjusted` then lists their ids, e.g. `X-Forms-Adjusted: removed-jumps=(3 7)`, or holds `removed-jumps` alone for more than 100 questions (see [Adjustments by the server](#adjustments-by-the-server)).
An id of a deleted question gets a **Not Found** response.

Expand All @@ -521,7 +521,7 @@ Reorders all Questions of a single form
|-----------|---------|-------------|
| _formId_ | Integer | ID of the form containing the question |
| _questionId_ | Integer | ID of the question to delete |
- Response: **Status-Code OK**, as well as the id of the deleted question.
- Response: **Status-Code OK**, as well as the id of the deleted question. Deleting the first section moves the next section up to its place, so its questions stay in a section (see [Sections](DataStructure.md#sections)); jumps that become backward by this are removed, and the response header `X-Forms-Adjusted` then lists their questions, e.g. `X-Forms-Adjusted: removed-jumps=(3 7)` (see [Adjustments by the server](#adjustments-by-the-server)).

```
"data": 4
Expand Down Expand Up @@ -740,7 +740,7 @@ Get all Submissions to a Form
| _query_ | String | Phrase for full text search |
| _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.
- Response: An Array of all submissions, sorted as newest first, as well as an array of the corresponding questions, without sections.
Answers to deleted questions are left out, and the search does not match them.

```
Expand Down Expand Up @@ -845,7 +845,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, 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.
- 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. There is one column per question; sections have no column.

```
"User display name","Timestamp","Question 1","Question 2"
Expand Down Expand Up @@ -981,6 +981,7 @@ Store Submission to Database
- For File-Uploads, the array contains objects with `uploadedFileId` and `uploadToken` (both from the [Upload a file] endpoint for the same `questionId`).
- Answers to questions that the [jumps](DataStructure.md#jumps) of the answers skip are ignored, and a skipped required question needs no answer. The path ends at a question that has no answer and a jump per answer past the following question, so the questions after an optional one left empty need no answer either.
- An answer "Other" is `system-other-answer:` followed by its text. The text must not be empty where the question has a jump for the answer "Other", as the answer decides the path there.
- A `section` takes no answer: a non-empty array of values for a section on the respondent's path, even `[""]`, is rejected with **400 Bad Request** "Section "…" cannot have answers." An answer that is not an array of values gets the usual "Invalid answer for question "…".", and answers to sections the jumps skip are ignored like those to skipped questions.

```
{
Expand Down
9 changes: 9 additions & 0 deletions docs/DataStructure.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,15 @@ Currently supported Question-Types are:
| `linearscale` | A linear or Likert scale question where you choose an option that best fits your opinion |
| `color` | A color answer, hex string representation (e. g. `#123456`) |
| `ranking` | Using pre-defined options, the user ranks them from most to least preferred. Needs at least one option available. Answers are stored in ranked order (one answer row per option). |
| `section` | A structural element to group questions into sections. It cannot be answered and has no options. |

### Sections

Once a form has a section, every question is in a section: the form starts with a section, and each question belongs to the section before it.

- A request that would put more questions before the first section is rejected, see [Create a new question](API_v3.md#create-a-new-question) and [Reorder questions](API_v3.md#reorder-questions). To add the first section below existing questions, first insert a section at position 1, so that it holds them. The editor does this by itself, with the title "Untitled section" filled in; the title can be changed or cleared like any other.
- Deleting the first section moves the next section up to its place, so the questions of the deleted section join the next section. Deleting any other section lets its questions join the section before it. Deleting the only section leaves a form without sections.
- A form whose questions were stored before the first section by an earlier version keeps them there, and requests that do not add to them keep working.

## Extra Settings

Expand Down
4 changes: 3 additions & 1 deletion lib/Constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ class Constants {
];

/**
* !! Keep in sync with src/models/AnswerTypes.js !!
* !! Keep in sync with src/models/AnswerTypes.ts !!
*/

// Available AnswerTypes
Expand All @@ -111,6 +111,7 @@ class Constants {
public const ANSWER_TYPE_MULTIPLE = 'multiple';
public const ANSWER_TYPE_MULTIPLEUNIQUE = 'multiple_unique';
public const ANSWER_TYPE_RANKING = 'ranking';
public const ANSWER_TYPE_SECTION = 'section';
public const ANSWER_TYPE_SHORT = 'short';
public const ANSWER_TYPE_TIME = 'time';

Expand Down Expand Up @@ -150,6 +151,7 @@ class Constants {
self::ANSWER_TYPE_MULTIPLE,
self::ANSWER_TYPE_MULTIPLEUNIQUE,
self::ANSWER_TYPE_RANKING,
self::ANSWER_TYPE_SECTION,
self::ANSWER_TYPE_SHORT,
self::ANSWER_TYPE_TIME,
];
Expand Down
78 changes: 76 additions & 2 deletions lib/Controller/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,7 @@ public function getQuestion(int $formId, int $questionId): DataResponse {
* @return DataResponse<Http::STATUS_CREATED, FormsQuestion, array{X-Forms-Adjusted?: string, Access-Control-Expose-Headers?: string}>
* @throws OCSBadRequestException Invalid type
* @throws OCSBadRequestException Invalid subtype
* @throws OCSBadRequestException Every question must be in a section
* @throws OCSBadRequestException Datetime question type no longer supported
* @throws OCSForbiddenException User has no permissions to get this form
* @throws OCSForbiddenException This form is archived and can not be modified
Expand Down Expand Up @@ -606,6 +607,7 @@ public function newQuestion(int $formId, ?string $type = null, ?string $subtype

// Retrieve all active questions sorted by Order.
$questions = $this->questionMapper->findByForm($formId);
self::checkInsertKeepsSections($questions, (string)$type, $position);

if ($position !== null) {
$position = $this->shiftQuestionsForInsert($questions, $position);
Expand Down Expand Up @@ -656,6 +658,7 @@ public function newQuestion(int $formId, ?string $type = null, ?string $subtype
}

$allQuestions = $this->questionMapper->findByForm($formId);
self::checkInsertKeepsSections($allQuestions, $sourceQuestion->getType(), $position);

$questionData = $sourceQuestion->read();
unset($questionData['id']);
Expand Down Expand Up @@ -834,9 +837,11 @@ public function updateQuestion(int $formId, int $questionId, array $keyValuePair
/**
* Delete a question
*
* Deleting the first section moves the next section up to its place, so its questions stay in a section; jumps that become backward are removed, and the header `X-Forms-Adjusted` then holds `removed-jumps` with the ids of their questions
*
* @param int $formId the form id
* @param int $questionId the question id
* @return DataResponse<Http::STATUS_OK, int, array{}>
* @return DataResponse<Http::STATUS_OK, int, array{X-Forms-Adjusted?: string, Access-Control-Expose-Headers?: string}>
* @throws OCSBadRequestException Question doesn\'t belong to given Form
* @throws OCSForbiddenException This form is archived and can not be modified
* @throws OCSForbiddenException User has no permissions to get this form
Expand Down Expand Up @@ -875,6 +880,7 @@ public function deleteQuestion(int $formId, int $questionId): DataResponse {

// Store Order of deleted Question
$deletedOrder = $question->getOrder();
$deletedType = $question->getType();

// Mark question as deleted
$question->setOrder(0);
Expand All @@ -898,13 +904,15 @@ public function deleteQuestion(int $formId, int $questionId): DataResponse {
}
}

$headers = $deletedType === Constants::ANSWER_TYPE_SECTION ? $this->moveNextSectionUp($formQuestions, $deletedOrder) : [];

if ($form->getConfirmationEmailQuestionId() === $questionId) {
$form->setConfirmationEmailQuestionId(null);
}

$this->formMapper->update($form);

return new DataResponse($questionId);
return new DataResponse($questionId, Http::STATUS_OK, $headers);
}

/**
Expand All @@ -917,6 +925,7 @@ public function deleteQuestion(int $formId, int $questionId): DataResponse {
* @return DataResponse<Http::STATUS_OK, array<string, FormsQuestionOrder>, array{X-Forms-Adjusted?: string, Access-Control-Expose-Headers?: string}>
* @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 Every question must be in a section
* @throws OCSBadRequestException Question doesn't belong to given Form
* @throws OCSForbiddenException This form is archived and can not be modified
* @throws OCSForbiddenException User has no permissions to get this form
Expand Down Expand Up @@ -955,6 +964,7 @@ public function reorderQuestions(int $formId, array $newOrder): DataResponse {
$this->logger->debug('The length of the given array does not match the number of stored questions');
throw new OCSBadRequestException('The length of the given array does not match the number of stored questions');
}
$typesBefore = array_map(static fn (Question $question) => $question->getType(), $questions);

$questions = []; // Clear Array of Entities
$response = []; // Array of ['questionId' => ['order' => newOrder]]
Expand Down Expand Up @@ -986,6 +996,8 @@ public function reorderQuestions(int $formId, array $newOrder): DataResponse {
}
}

self::checkQuestionsStayInSections($typesBefore, array_map(static fn (Question $question) => $question->getType(), $questions));

$changedQuestions = JumpHelper::removeBackwardJumps($questions);

// Write to Database
Expand Down Expand Up @@ -1408,6 +1420,11 @@ public function getSubmissions(int $formId, ?string $query = null, ?int $limit =
}
$questions = [];
foreach ($this->formsService->getQuestions($formId) as $question) {
// Sections are structural elements and cannot be answered
if ($question['type'] === Constants::ANSWER_TYPE_SECTION) {
continue;
}

$questions[$question['id']] = $question;
}

Expand Down Expand Up @@ -2337,6 +2354,63 @@ private function logFormUpdate(Form $form, array $previousAccess, ?int $previous
}
}

/**
* Move the next section up to the place of a deleted section that was the first section, so the questions of the deleted section join the next section; jumps that become backward are removed
*
* @param list<Question> $questions the remaining questions of the form in their order
* @param int $order the order of the deleted section
* @return array{X-Forms-Adjusted?: string, Access-Control-Expose-Headers?: string} the header listing the questions whose jumps were removed
*/
private function moveNextSectionUp(array $questions, int $order): array {
$first = FormsService::countQuestionsOutsideSections(array_map(static fn (Question $question) => $question->getType(), $questions));
if ($first <= $order - 1) {
return [];
}
array_splice($questions, $order - 1, 0, array_splice($questions, $first, 1));
$moved = [];
foreach ($questions as $index => $question) {
if ($question->getOrder() !== $index + 1) {
$question->setOrder($index + 1);
$moved[] = $question;
}
}
$changed = JumpHelper::removeBackwardJumps($questions);
foreach ($questions as $question) {
if (in_array($question, $moved, true) || in_array($question, $changed, true)) {
$this->questionMapper->update($question);
}
}
return self::getRemovedJumpsHeaders(array_map(static fn (Question $question): int => $question->getId(), $changed));
}

/**
* Throw when inserting a question would put more questions outside any section
*
* @param list<Question> $questions the questions of the form in their order
* @param string $type the type of the new question
* @param ?int $position the 1-based position of the new question, null to append it
* @throws OCSBadRequestException Every question must be in a section
*/
private static function checkInsertKeepsSections(array $questions, string $type, ?int $position): void {
$types = array_map(static fn (Question $question) => $question->getType(), $questions);
$after = $types;
array_splice($after, $position === null ? count($types) : max(0, min($position - 1, count($types))), 0, [$type]);
self::checkQuestionsStayInSections($types, $after);
}

/**
* Throw when a change puts more questions before the first section than before the change
*
* @param list<string> $before the question types of the form in their order before the change
* @param list<string> $after the question types of the form in their order after the change
* @throws OCSBadRequestException Every question must be in a section
*/
private static function checkQuestionsStayInSections(array $before, array $after): void {
if (FormsService::countQuestionsOutsideSections($after) > FormsService::countQuestionsOutsideSections($before)) {
throw new OCSBadRequestException('Every question must be in a section');
}
}

/**
* Shift existing question orders to make room for an insertion at $position.
* Normalizes the given $position to the valid range and updates all questions
Expand Down
2 changes: 1 addition & 1 deletion lib/ResponseDefinitions.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
* extraSettings?: FormsQuestionExtraSettings|\stdClass,
* }
*
* @psalm-type FormsQuestionType = "dropdown"|"multiple"|"multiple_unique"|"date"|"time"|"short"|"long"|"file"|"datetime"|"grid"|"linearscale"|"color"|"ranking"
* @psalm-type FormsQuestionType = "dropdown"|"multiple"|"multiple_unique"|"date"|"time"|"short"|"long"|"file"|"datetime"|"grid"|"linearscale"|"color"|"ranking"|"section"
* @psalm-type FormsQuestionSubtype = "checkbox"|"number"|"radio"|"rating"|"promoter"
*
* @psalm-type FormsQuestion = array{
Expand Down
11 changes: 11 additions & 0 deletions lib/Service/FormsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -1147,6 +1147,17 @@ public function removeJumpsOfMissingOptions(Question $question): bool {
return true;
}

/**
* The number of questions before the first section, 0 for a form without sections
*
* @param list<string> $types the question types of the form in their order
* @return int the number of questions outside any section
*/
public static function countQuestionsOutsideSections(array $types): int {
$first = array_search(Constants::ANSWER_TYPE_SECTION, $types, true);
return $first === false ? 0 : $first;
}

/**
* Get list of forms
*
Expand Down
Loading
Loading