diff --git a/lib/Controller/ApiController.php b/lib/Controller/ApiController.php index 43aefe0b9..702480db5 100644 --- a/lib/Controller/ApiController.php +++ b/lib/Controller/ApiController.php @@ -25,12 +25,14 @@ use OCA\Forms\Db\UploadedFile; use OCA\Forms\Db\UploadedFileMapper; use OCA\Forms\Exception\NoSuchFormException; +use OCA\Forms\Helper\FilePathHelper; use OCA\Forms\Helper\JumpHelper; use OCA\Forms\ResponseDefinitions; use OCA\Forms\Service\ConfigService; use OCA\Forms\Service\ConfirmationEmailService; use OCA\Forms\Service\FormsService; use OCA\Forms\Service\SubmissionService; +use OCP\App\IAppManager; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Db\IMapperException; use OCP\AppFramework\Http; @@ -82,6 +84,7 @@ public function __construct( IRequest $request, IUserSession $userSession, private readonly AnswerMapper $answerMapper, + private readonly FilePathHelper $filePathHelper, private readonly FormMapper $formMapper, private readonly OptionMapper $optionMapper, private readonly QuestionMapper $questionMapper, @@ -92,6 +95,7 @@ public function __construct( private readonly SubmissionService $submissionService, private readonly IL10N $l10n, private readonly LoggerInterface $logger, + private readonly IAppManager $appManager, private readonly IUserManager $userManager, private readonly IRootFolder $rootFolder, private readonly UploadedFileMapper $uploadedFileMapper, @@ -151,8 +155,19 @@ public function getForms(string $type = 'owned'): DataResponse { * Return a copy of the form if the parameter $fromId is set * * @param ?int $fromId (optional) Id of the form that should be cloned + * @param ?bool $import (optional) If it should import the form from post body + * @param ?array $formData (optional) The formdata to import * @return DataResponse * @throws OCSForbiddenException The user is not allowed to create forms + * @throws OCSBadRequestException Cannot use both fromId and import parameters + * @throws OCSBadRequestException Invalid form data: missing questions + * @throws OCSBadRequestException Invalid form data: unknown properties + * @throws OCSBadRequestException Invalid question data: missing id + * @throws OCSBadRequestException Invalid question data: unknown properties + * @throws OCSBadRequestException Invalid question data: invalid type + * @throws OCSBadRequestException Invalid question data: datetime type no longer supported + * @throws OCSBadRequestException Invalid question data: invalid extraSettings + * @throws OCSBadRequestException Invalid option data: unknown properties * * 201: the created form */ @@ -160,14 +175,19 @@ public function getForms(string $type = 'owned'): DataResponse { #[NoAdminRequired()] #[BruteForceProtection(action: 'form')] #[ApiRoute(verb: 'POST', url: '/api/v3/forms')] - public function newForm(?int $fromId = null): DataResponse { + public function newForm(?int $fromId = null, ?bool $import = false, ?array $formData = []): DataResponse { // Check if user is allowed if (!$this->configService->canCreateForms()) { $this->logger->debug('This user is not allowed to create Forms.'); throw new OCSForbiddenException('This user is not allowed to create Forms.'); } - if ($fromId === null) { + // Validate mutually exclusive parameters + if ($fromId !== null && $import === true) { + throw new OCSBadRequestException('Cannot use both fromId and import parameters'); + } + + if ($fromId === null && $import !== true) { // Create Form $form = new Form(); $form->setOwnerId($this->currentUser->getUID()); @@ -191,34 +211,121 @@ public function newForm(?int $fromId = null): DataResponse { 'ownerId' => $form->getOwnerId(), 'sourceFormId' => null, ]); + } elseif ($import === true) { + if (!isset($formData['questions']) || !\is_array($formData['questions'])) { + throw new OCSBadRequestException('Invalid form data: missing questions'); + } + $questions = $formData['questions']; + $oldConfirmationEmailQuestionId = $formData['confirmationEmailQuestionId'] ?? null; + unset($formData['questions']); + + // Validate form data whitelist + $allowedFormProperties = [ + 'title', 'description', 'access', 'expires', 'opens', 'isAnonymous', + 'submitMultiple', 'allowEditSubmissions', 'showExpiration', + 'submissionMessage', 'maxSubmissions', 'confirmationEmailEnabled', + 'confirmationEmailSubject', 'confirmationEmailBody', 'confirmationEmailQuestionId', + 'allowComments', + ]; + $invalidKeys = array_diff(array_keys($formData), $allowedFormProperties); + if (!empty($invalidKeys)) { + throw new OCSBadRequestException('Invalid form data: unknown properties: ' . implode(', ', $invalidKeys)); + } + + // Validate all questions and options before inserting anything, + // so an invalid file does not leave a partially imported form behind + $allowedQuestionProperties = ['id', 'order', 'type', 'isRequired', 'text', 'name', 'description', 'extraSettings', 'options']; + $allowedOptionProperties = ['id', 'text', 'order', 'optionType']; + foreach ($questions as $question) { + if (!\is_array($question) || !\is_int($question['id'] ?? null)) { + throw new OCSBadRequestException('Invalid question data: missing id'); + } + + $invalidQuestionKeys = array_diff(array_keys($question), $allowedQuestionProperties); + if (!empty($invalidQuestionKeys)) { + throw new OCSBadRequestException('Invalid question data: unknown properties: ' . implode(', ', $invalidQuestionKeys)); + } + + $type = $question['type'] ?? null; + if (!\in_array($type, Constants::ANSWER_TYPES, true)) { + throw new OCSBadRequestException('Invalid question data: invalid type'); + } + + if ($type === Constants::ANSWER_TYPE_DATETIME) { + throw new OCSBadRequestException('Invalid question data: datetime type no longer supported'); + } + + $extraSettings = $question['extraSettings'] ?? []; + if (!\is_array($extraSettings) + || (!empty($extraSettings) && !$this->formsService->areExtraSettingsValid($extraSettings, $type))) { + throw new OCSBadRequestException('Invalid question data: invalid extraSettings'); + } + + $options = $question['options'] ?? []; + if (!\is_array($options)) { + throw new OCSBadRequestException('Invalid option data: unknown properties'); + } + foreach ($options as $option) { + $invalidOptionKeys = \is_array($option) ? array_diff(array_keys($option), $allowedOptionProperties) : ['(not an object)']; + if (!empty($invalidOptionKeys)) { + throw new OCSBadRequestException('Invalid option data: unknown properties: ' . implode(', ', $invalidOptionKeys)); + } + } + } + + $formData = $this->setDefaults($formData); + + $form = Form::fromParams($formData); + $this->formMapper->insert($form); + + $questionIdMap = []; + $optionIdMaps = []; + $newQuestions = []; + foreach ($questions as $questionData) { + $oldQuestionId = $questionData['id']; + $options = $questionData['options'] ?? []; + unset($questionData['id'], $questionData['options']); + + $questionData['formId'] = $form->getId(); + $newQuestion = Question::fromParams($questionData); + $this->questionMapper->insert($newQuestion); + $questionIdMap[$oldQuestionId] = $newQuestion->getId(); + $newQuestions[] = $newQuestion; + + if ($oldConfirmationEmailQuestionId !== null && $oldConfirmationEmailQuestionId === $oldQuestionId) { + $form->setConfirmationEmailQuestionId($newQuestion->getId()); + } + + foreach ($options as $optionData) { + $oldOptionId = $optionData['id'] ?? null; + unset($optionData['id']); + $optionData['questionId'] = $newQuestion->getId(); + $newOption = Option::fromParams($optionData); + $this->optionMapper->insert($newOption); + if (\is_int($oldOptionId)) { + $optionIdMaps[$newQuestion->getId()][$oldOptionId] = $newOption->getId(); + } + } + } + + foreach (JumpHelper::mapJumpsOfCopies($newQuestions, $questionIdMap, $optionIdMaps) as $newQuestion) { + $this->questionMapper->update($newQuestion); + } + + $this->formMapper->update($form); + $this->auditLogger->log(Operation::FormCreated, 'Form %s was created by "%s"', [ + 'formId' => $form->getId(), + 'ownerId' => $form->getOwnerId(), + 'sourceFormId' => null, + ]); } else { $oldForm = $this->formsService->getFormIfAllowed($fromId, Constants::PERMISSION_EDIT); // Read old form, (un)set new form specific data, extend title $formData = $oldForm->read(); - unset($formData['id']); - unset($formData['created']); - unset($formData['lastUpdated']); - unset($formData['state']); - unset($formData['fileId']); - unset($formData['fileFormat']); - unset($formData['lockedBy']); - unset($formData['lockedUntil']); - unset($formData['confirmationEmailQuestionId']); - $formData['ownerId'] = $this->currentUser->getUID(); - $formData['hash'] = $this->formsService->generateFormHash(); + $formData = $this->setDefaults($formData); // TRANSLATORS Appendix to the form Title of a duplicated/copied form. $formData['title'] .= ' - ' . $this->l10n->t('Copy'); - $formData['access'] = [ - 'permitAllUsers' => false, - 'showToAllUsers' => false, - ]; - $formData['submitMultiple'] = false; - $formData['allowEditSubmissions'] = false; - $formData['showExpiration'] = false; - $formData['expires'] = 0; - $formData['opens'] = 0; - $formData['isAnonymous'] = false; $form = Form::fromParams($formData); $this->formMapper->insert($form); @@ -272,11 +379,39 @@ public function newForm(?int $fromId = null): DataResponse { return new DataResponse($this->formsService->getForm($form), Http::STATUS_CREATED); } + private function setDefaults(array $formData): array { + // Remove unused data + unset($formData['id']); + unset($formData['created']); + unset($formData['lastUpdated']); + unset($formData['state']); + unset($formData['fileId']); + unset($formData['fileFormat']); + unset($formData['lockedBy']); + unset($formData['lockedUntil']); + unset($formData['confirmationEmailQuestionId']); + $formData['ownerId'] = $this->currentUser->getUID(); + $formData['hash'] = $this->formsService->generateFormHash(); + + $formData['access'] = [ + 'permitAllUsers' => false, + 'showToAllUsers' => false, + ]; + $formData['submitMultiple'] = false; + $formData['allowEditSubmissions'] = false; + $formData['showExpiration'] = false; + $formData['expires'] = 0; + $formData['opens'] = 0; + $formData['isAnonymous'] = false; + return $formData; + } + /** * Read all information to edit a Form (form, questions, options, except submissions/answers) * * @param int $formId Id of the form - * @return DataResponse + * @param ?bool $export if the form should get exported + * @return DataResponse|DataDownloadResponse * @throws OCSBadRequestException Could not find form * @throws OCSForbiddenException User has no permissions to get this form * @@ -286,9 +421,42 @@ public function newForm(?int $fromId = null): DataResponse { #[NoAdminRequired()] #[BruteForceProtection(action: 'form')] #[ApiRoute(verb: 'GET', url: '/api/v3/forms/{formId}')] - public function getForm(int $formId): DataResponse { + public function getForm(int $formId, ?bool $export = false): DataResponse|DataDownloadResponse { $form = $this->formsService->getFormIfAllowed($formId, Constants::PERMISSION_SUBMIT); + if ($export) { + $formData = $this->formsService->getPublicForm($form); + unset($formData['hash']); + unset($formData['created']); + unset($formData['lastUpdated']); + unset($formData['lockedBy']); + unset($formData['lockedUntil']); + unset($formData['permissions']); + unset($formData['canSubmit']); + unset($formData['isMaxSubmissionsReached']); + unset($formData['submissionCount']); + unset($formData['filePath']); + unset($formData['state']); + unset($formData['id']); + + $formData['questions'] = array_map(static function (array $question): array { + unset($question['formId'], $question['accept']); + $question['options'] = array_map(static function (array $option): array { + unset($option['questionId']); + return $option; + }, $question['options']); + return $question; + }, $formData['questions']); + + $exportFile = ['form' => $formData, 'appVersion' => $this->appManager->getAppVersion('forms')]; + // TRANSLATORS File name of an exported form without a title, as shown in the navigation + $title = (string)$form->getTitle() !== '' ? $form->getTitle() : $this->l10n->t('New form'); + $fileName = $this->filePathHelper->normalizeFileName($title . '.json'); + + return new DataDownloadResponse( + json_encode($exportFile, JSON_THROW_ON_ERROR), $fileName, 'application/json'); + } + return new DataResponse($this->formsService->getForm($form)); } diff --git a/lib/Controller/PageController.php b/lib/Controller/PageController.php index ef0b54e5b..c807fa8e2 100644 --- a/lib/Controller/PageController.php +++ b/lib/Controller/PageController.php @@ -14,6 +14,7 @@ use OCA\Forms\Service\ConfigService; use OCA\Forms\Service\FormsService; use OCP\Accounts\IAccountManager; +use OCP\App\IAppManager; use OCP\AppFramework\Controller; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Http\Attribute\BruteForceProtection; @@ -55,6 +56,7 @@ public function __construct( private readonly IUrlGenerator $urlGenerator, private readonly IUserManager $userManager, private readonly IUserSession $userSession, + private readonly IAppManager $appManager, ) { parent::__construct($appName, $request); } @@ -74,6 +76,7 @@ public function index(?string $hash = null): TemplateResponse { $this->insertHeaderOnIos(); $this->initialState->provideInitialState('maxStringLengths', Constants::MAX_STRING_LENGTHS); $this->initialState->provideInitialState('appConfig', $this->configService->getAppConfig()); + $this->initialState->provideInitialState('appVersion', $this->appManager->getAppVersion($this->appName)); if (isset($hash)) { try { diff --git a/openapi.json b/openapi.json index f3c485d94..c86cbc0f6 100644 --- a/openapi.json +++ b/openapi.json @@ -971,6 +971,21 @@ "nullable": true, "default": null, "description": "(optional) Id of the form that should be cloned" + }, + "import": { + "type": "boolean", + "nullable": true, + "default": false, + "description": "(optional) If it should import the form from post body" + }, + "formData": { + "type": "object", + "nullable": true, + "default": {}, + "description": "(optional) The formdata to import", + "additionalProperties": { + "type": "object" + } } } } @@ -1048,6 +1063,34 @@ } } }, + "400": { + "description": "Invalid option data: unknown properties", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, "401": { "description": "Current user is not logged in", "content": { @@ -1103,6 +1146,16 @@ "format": "int64" } }, + { + "name": "export", + "in": "query", + "description": "if the form should get exported", + "schema": { + "type": "boolean", + "nullable": true, + "default": false + } + }, { "name": "OCS-APIRequest", "in": "header", @@ -1120,27 +1173,35 @@ "content": { "application/json": { "schema": { - "type": "object", - "required": [ - "ocs" - ], - "properties": { - "ocs": { + "anyOf": [ + { "type": "object", "required": [ - "meta", - "data" + "ocs" ], "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { - "$ref": "#/components/schemas/Form" + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/Form" + } + } } } + }, + { + "type": "string", + "format": "binary" } - } + ] } } } diff --git a/package-lock.json b/package-lock.json index 344d05152..098aa9a99 100644 --- a/package-lock.json +++ b/package-lock.json @@ -26,6 +26,7 @@ "markdown-it": "^15.0.3", "p-queue": "^10.0.0", "qrcode": "^1.5.4", + "semver": "^7.8.6", "vue": "^3.5.46", "vue-draggable-plus": "^0.6.1", "vue-router": "^5.5.1" @@ -452,7 +453,6 @@ "cpu": [ "ppc64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -469,7 +469,6 @@ "cpu": [ "arm" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -486,7 +485,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -503,7 +501,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -520,7 +517,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -537,7 +533,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -554,7 +549,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -571,7 +565,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -588,7 +581,6 @@ "cpu": [ "arm" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -605,7 +597,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -622,7 +613,6 @@ "cpu": [ "ia32" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -639,7 +629,6 @@ "cpu": [ "loong64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -656,7 +645,6 @@ "cpu": [ "mips64el" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -673,7 +661,6 @@ "cpu": [ "ppc64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -690,7 +677,6 @@ "cpu": [ "riscv64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -707,7 +693,6 @@ "cpu": [ "s390x" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -724,7 +709,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -741,7 +725,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -758,7 +741,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -775,7 +757,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -792,7 +773,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -809,7 +789,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -826,7 +805,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -843,7 +821,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -860,7 +837,6 @@ "cpu": [ "ia32" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -877,7 +853,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -1973,7 +1948,6 @@ "version": "2.5.6", "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.5.6.tgz", "integrity": "sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==", - "dev": true, "hasInstallScript": true, "license": "MIT", "optional": true, @@ -2014,7 +1988,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2036,7 +2009,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2058,7 +2030,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2080,7 +2051,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2102,7 +2072,6 @@ "cpu": [ "arm" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2124,7 +2093,6 @@ "cpu": [ "arm" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2146,7 +2114,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2168,7 +2135,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2190,7 +2156,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2212,7 +2177,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2234,7 +2198,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2256,7 +2219,6 @@ "cpu": [ "ia32" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2278,7 +2240,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2469,7 +2430,6 @@ "cpu": [ "arm" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2483,7 +2443,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2497,7 +2456,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2511,7 +2469,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2525,7 +2482,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2539,7 +2495,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2553,7 +2508,6 @@ "cpu": [ "arm" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2567,7 +2521,6 @@ "cpu": [ "arm" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2581,7 +2534,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2595,7 +2547,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2609,7 +2560,6 @@ "cpu": [ "loong64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2623,7 +2573,6 @@ "cpu": [ "loong64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2637,7 +2586,6 @@ "cpu": [ "ppc64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2651,7 +2599,6 @@ "cpu": [ "ppc64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2665,7 +2612,6 @@ "cpu": [ "riscv64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2679,7 +2625,6 @@ "cpu": [ "riscv64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2693,7 +2638,6 @@ "cpu": [ "s390x" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2707,7 +2651,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2721,7 +2664,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2735,7 +2677,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2749,7 +2690,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2763,7 +2703,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2777,7 +2716,6 @@ "cpu": [ "ia32" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2791,7 +2729,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -2805,7 +2742,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -3134,7 +3070,7 @@ "version": "26.6.6", "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "undici-types": "~8.9.0" @@ -4892,7 +4828,7 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", - "dev": true, + "devOptional": true, "license": "MIT", "peer": true, "dependencies": { @@ -5473,7 +5409,6 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, "license": "Apache-2.0", "optional": true, "peer": true, @@ -6718,7 +6653,6 @@ "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, "hasInstallScript": true, "license": "MIT", "optional": true, @@ -7282,7 +7216,7 @@ "version": "5.1.9", "resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.9.tgz", "integrity": "sha512-m8nVez3rwrgmWxtLMt1ZYXB2Lv7OKYn/disyxAlSDYAlKSlFoPPfIAmAM/M5xqL4m4C/wAPw7S2/CNaUii1Hxg==", - "dev": true, + "devOptional": true, "license": "MIT", "peer": true }, @@ -7468,7 +7402,7 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, + "devOptional": true, "license": "MIT", "peer": true, "engines": { @@ -7508,7 +7442,7 @@ "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, + "devOptional": true, "license": "MIT", "peer": true, "dependencies": { @@ -9021,7 +8955,6 @@ "version": "7.1.1", "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", - "dev": true, "license": "MIT", "optional": true, "peer": true @@ -10733,7 +10666,7 @@ "version": "1.100.0", "resolved": "https://registry.npmjs.org/sass/-/sass-1.100.0.tgz", "integrity": "sha512-B5j0rYMlinhhOo9tjQebMVVn0TfyXAF+wB3b2ggZUuJ/is/Y+7+JGjirAMxHZ9Z3hIP98NPfamlAkBHa1lAaXQ==", - "dev": true, + "devOptional": true, "license": "MIT", "peer": true, "dependencies": { @@ -10767,9 +10700,9 @@ "license": "MIT" }, "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -12063,7 +11996,7 @@ "version": "8.9.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/unicorn-magic": { @@ -12546,7 +12479,6 @@ "cpu": [ "ppc64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12563,7 +12495,6 @@ "cpu": [ "arm" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12580,7 +12511,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12597,7 +12527,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12614,7 +12543,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12631,7 +12559,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12648,7 +12575,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12665,7 +12591,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12682,7 +12607,6 @@ "cpu": [ "arm" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12699,7 +12623,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12716,7 +12639,6 @@ "cpu": [ "ia32" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12733,7 +12655,6 @@ "cpu": [ "loong64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12750,7 +12671,6 @@ "cpu": [ "mips64el" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12767,7 +12687,6 @@ "cpu": [ "ppc64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12784,7 +12703,6 @@ "cpu": [ "riscv64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12801,7 +12719,6 @@ "cpu": [ "s390x" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12818,7 +12735,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12835,7 +12751,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12852,7 +12767,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12869,7 +12783,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12886,7 +12799,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12903,7 +12815,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12920,7 +12831,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12937,7 +12847,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12954,7 +12863,6 @@ "cpu": [ "ia32" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -12971,7 +12879,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -13027,7 +12934,6 @@ "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, "hasInstallScript": true, "license": "MIT", "optional": true, diff --git a/package.json b/package.json index b7e1156aa..52f14964c 100644 --- a/package.json +++ b/package.json @@ -49,6 +49,7 @@ "markdown-it": "^15.0.3", "p-queue": "^10.0.0", "qrcode": "^1.5.4", + "semver": "^7.8.6", "vue": "^3.5.46", "vue-draggable-plus": "^0.6.1", "vue-router": "^5.5.1" diff --git a/playwright/e2e/download-import-form.spec.ts b/playwright/e2e/download-import-form.spec.ts new file mode 100644 index 000000000..25008e9e9 --- /dev/null +++ b/playwright/e2e/download-import-form.spec.ts @@ -0,0 +1,309 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { expect, mergeTests } from '@playwright/test' +import { test as formTest } from '../support/fixtures/form.ts' +import { test as appNavigationTest } from '../support/fixtures/navigation.ts' +import { test as randomUserTest } from '../support/fixtures/random-user.ts' +import { QuestionType } from '../support/sections/QuestionType.ts' + +const test = mergeTests(randomUserTest, appNavigationTest, formTest) + +test.describe('Export form', () => { + test.beforeEach(async ({ page }) => { + await page.goto('apps/forms', { waitUntil: 'networkidle' }) + await page.waitForURL(/apps\/forms\/$/) + }) + + test('Export a form as JSON file', async ({ page, appNavigation, form }) => { + await appNavigation.clickNewForm() + await form.fillTitle('Export test') + await page.getByRole('button', { name: 'Add a question' }).click() + await page.getByRole('menuitem', { name: 'Checkboxes' }).click() + await page + .getByRole('textbox', { name: 'Title of question number 1' }) + .fill('A') + await page + .getByRole('listitem', { name: 'Question number 1' }) + .getByPlaceholder('Add a new answer option') + .fill('B') + await page + .getByRole('listitem', { name: 'Question number 1' }) + .getByPlaceholder('Add a new answer option') + .press('Enter') + await page.waitForTimeout(100) + + await page + .getByRole('listitem', { name: 'Question number 1' }) + .getByPlaceholder('Add a new answer option') + .fill('C') + await page + .getByRole('listitem', { name: 'Question number 1' }) + .getByPlaceholder('Add a new answer option') + .press('Enter') + await page.waitForTimeout(100) + + await page + .getByRole('listitem', { name: 'Question number 1' }) + .getByPlaceholder('Add a new answer option') + .fill('D') + await page + .getByRole('listitem', { name: 'Question number 1' }) + .getByPlaceholder('Add a new answer option') + .press('Enter') + await page.waitForTimeout(100) + + const downloadPromise = page.waitForEvent('download') + + // Hover over the form to make the actions button visible + await appNavigation.getOwnForm('Export test').hover() + await page.getByRole('button', { name: 'Form actions' }).click() + + // Click Export form in the popover menu + await page.getByRole('menuitem', { name: 'Export form' }).click() + + const download = await downloadPromise + expect(download.suggestedFilename()).toMatch(/^Export test.*\.json$/) + + const stream = await download.createReadStream() + const json = await new Promise((resolve, reject) => { + let raw = '' + stream.on('data', (chunk) => (raw += chunk)) + stream.on('end', () => resolve(JSON.parse(raw))) + stream.on('error', reject) + }) + expect(json.form).toBeDefined() + expect(json.form.questions).toHaveLength(1) + expect(json.appVersion).toBeDefined() + // Deepen: verify the JSON content matches what we created + expect(json.form.title).toBe('Export test') + expect(json.form.questions[0].type).toBe('multiple') + expect(json.form.questions[0].text).toBe('A') + expect(json.form.questions[0].options).toHaveLength(3) + expect(json.form.questions[0].options[0].text).toBe('B') + expect(json.form.questions[0].options[1].text).toBe('C') + expect(json.form.questions[0].options[2].text).toBe('D') + // Verify stripped fields are absent + expect(json.form.id).toBeUndefined() + expect(json.form.hash).toBeUndefined() + expect(json.form.ownerId).toBeUndefined() + }) + + test('Export a form with multiple question types', async ({ + page, + appNavigation, + form, + }) => { + await appNavigation.clickNewForm() + await form.fillTitle('Multi type form') + await form.addQuestion(QuestionType.ShortAnswer) + const q1 = await form.getQuestions() + await q1[0].fillTitle('Name') + await form.addQuestion(QuestionType.Dropdown) + const q2 = await form.getQuestions() + await q2[1].fillTitle('Country') + await q2[1].addAnswer('DE') + await q2[1].addAnswer('FR') + await q2[1].addAnswer('IT') + + await page.waitForLoadState('networkidle') + const downloadPromise = page.waitForEvent('download') + + await appNavigation.getOwnForm('Multi type form').hover() + await page.getByRole('button', { name: 'Form actions' }).click() + await page.getByRole('menuitem', { name: 'Export form' }).click() + + const download = await downloadPromise + const stream = await download.createReadStream() + const json = await new Promise((resolve, reject) => { + let raw = '' + stream.on('data', (chunk) => (raw += chunk)) + stream.on('end', () => resolve(JSON.parse(raw))) + stream.on('error', reject) + }) + expect(json.form.questions).toHaveLength(2) + expect(json.form.questions[0].type).toBe('short') + expect(json.form.questions[0].text).toBe('Name') + expect(json.form.questions[1].type).toBe('dropdown') + expect(json.form.questions[1].text).toBe('Country') + expect(json.form.questions[1].options).toHaveLength(3) + }) +}) + +test.describe('Import form', () => { + test.beforeEach(async ({ page }) => { + await page.goto('apps/forms', { waitUntil: 'networkidle' }) + await page.waitForURL(/apps\/forms\/$/) + }) + + test('Import a form from JSON file', async ({ page, appNavigation }) => { + // Prepare JSON data matching the export format + const formData = { + appVersion: '5.3.0-rc.0', + form: { + title: 'Imported test form', + description: 'Description', + questions: [ + { + id: 52, + order: 1, + type: 'multiple', + isRequired: false, + text: 'Checkbox', + name: '', + description: '', + extraSettings: [], + options: [ + { + order: 1, + text: 'A', + optionType: 'choice', + }, + { + order: 2, + text: 'B', + optionType: 'choice', + }, + ], + }, + { + id: 53, + order: 2, + type: 'short', + isRequired: false, + text: 'Text', + name: '', + description: '', + extraSettings: [], + options: [], + }, + ], + }, + } + + const jsonContent = JSON.stringify(formData) + + // Set up file chooser handler before clicking import + const fileChooserPromise = page.waitForEvent('filechooser') + + // Click the Import form button in the navigation + await page.getByRole('button', { name: 'Import a form' }).click() + + const fileChooser = await fileChooserPromise + await fileChooser.setFiles({ + name: 'imported-form.json', + mimeType: 'application/json', + buffer: Buffer.from(jsonContent), + }) + + // Wait for the imported form to appear in the navigation + await expect(appNavigation.getOwnForm('Imported test form')).toBeVisible({ + timeout: 10000, + }) + + await expect( + page.getByRole('textbox', { name: 'Title of question number 1' }), + ).toHaveValue('Checkbox') + await expect( + page.getByRole('textbox', { name: 'Description', exact: true }), + ).toHaveValue('Description') + await expect( + page.getByRole('textbox', { name: 'The text of option 1' }), + ).toHaveValue('A') + await expect( + page.getByRole('textbox', { name: 'The text of option 2' }), + ).toHaveValue('B') + await expect( + page.getByRole('textbox', { name: 'Title of question number 2' }), + ).toHaveValue('Text') + }) + + test('Import a form with a long text question', async ({ + page, + appNavigation, + }) => { + const formData = { + appVersion: '5.3.0-rc.0', + form: { + title: 'Long answer form', + description: 'Testing long text import', + questions: [ + { + id: 10, + order: 1, + type: 'long', + text: 'Your biography', + isRequired: true, + options: [], + }, + ], + }, + } + + const jsonContent = JSON.stringify(formData) + + const fileChooserPromise = page.waitForEvent('filechooser') + + // Click the Import form button in the navigation + await page.getByRole('button', { name: 'Import a form' }).click() + + const fileChooser = await fileChooserPromise + await fileChooser.setFiles({ + name: 'long-text.json', + mimeType: 'application/json', + buffer: Buffer.from(jsonContent), + }) + + await expect(appNavigation.getOwnForm('Long answer form')).toBeVisible() + await expect( + page.getByRole('textbox', { name: 'Title of question number 1' }), + ).toHaveValue('Your biography') + await expect( + page.getByRole('textbox', { name: 'Description', exact: true }), + ).toHaveValue('Testing long text import') + }) + + test('Import a form with confirmation email question remapping', async ({ + page, + appNavigation, + }) => { + const formData = { + appVersion: '5.3.0-rc.0', + form: { + title: 'Email confirmation', + description: '', + confirmationEmailQuestionId: 99, + questions: [ + { + id: 99, + order: 1, + type: 'short', + text: 'Your email', + options: [], + }, + ], + }, + } + + const jsonContent = JSON.stringify(formData) + + const fileChooserPromise = page.waitForEvent('filechooser') + + // Click the Import form button in the navigation + await page.getByRole('button', { name: 'Import a form' }).click() + + const fileChooser = await fileChooserPromise + await fileChooser.setFiles({ + name: 'email-confirm.json', + mimeType: 'application/json', + buffer: Buffer.from(jsonContent), + }) + + await expect(appNavigation.getOwnForm('Email confirmation')).toBeVisible() + await expect( + page.getByRole('textbox', { name: 'Title of question number 1' }), + ).toHaveValue('Your email') + }) +}) diff --git a/src/Forms.vue b/src/Forms.vue index 7e3dfbb53..370afaae3 100644 --- a/src/Forms.vue +++ b/src/Forms.vue @@ -20,8 +20,15 @@ isHeading class="forms-navigation__list-heading" headingId="forms-navigation-your-forms" - :name="t('forms', 'Your forms')"> + :name="t('forms', 'Your forms')" + :inline="2"> @@ -171,6 +188,30 @@ @update:active="sidebarActive = $event" /> + + + + + + ([]) const showArchivedForms = ref(false) const filterText = ref('') + const showVersionMismatch = ref(false) + let formForImport: Record | undefined + const appVersion = loadState(formsAppName, 'appVersion', '') as string const appConfig = loadState(formsAppName, 'appConfig') as { canCreateForms?: boolean allowComments?: boolean @@ -606,6 +655,84 @@ export default defineComponent({ } } + const onImportForm = async () => { + showVersionMismatch.value = false + try { + const response = await axios.post( + generateOcsUrl('apps/forms/api/v3/forms?import=1'), + { formData: formForImport }, + ) + const newForm = OcsResponse2Data(response) + forms.value.unshift(newForm) + router.push({ + name: 'edit', + params: { hash: newForm.hash }, + }) + mobileCloseNavigation() + } catch (error) { + logger.error(`Unable to import form`, { error }) + showError(t('forms', 'Unable to import form')) + } + } + + const onUploadForm = () => { + // Open file pickers + const fileInput = document.createElement('input') + fileInput.type = 'file' + fileInput.accept = '.json,application/json' + + fileInput.addEventListener('change', () => { + const file = fileInput.files?.[0] + if (!file) return + const isJson = + file.type === 'application/json' + || (file.type === '' + && file.name.toLowerCase().endsWith('.json')) + if (!isJson || file.size > 1000 * 1000) { + showError(t('forms', 'Invalid file type or file too large')) + return + } + + const reader = new FileReader() + reader.addEventListener('load', async () => { + let formObject + try { + formObject = JSON.parse( + (reader.result as string | null) ?? '', + ) + } catch (error) { + logger.error('Invalid JSON in uploaded file', { error }) + showError(t('forms', 'Invalid JSON file')) + return + } + if ( + !semverValid(formObject?.appVersion) + || typeof formObject.form !== 'object' + || formObject.form === null + ) { + showError(t('forms', 'Invalid form file format')) + return + } + formForImport = formObject.form + if ( + !semverValid(appVersion) + || semverCompare(appVersion, formObject.appVersion) === -1 + ) { + showVersionMismatch.value = true + } else { + await onImportForm() + } + }) + reader.readAsText(file) + }) + fileInput.click() + } + + const closeModal = () => { + showVersionMismatch.value = false + formForImport = undefined + } + const onDeleteForm = async (id: number): Promise => { const formIndex = forms.value.findIndex((form) => form.id === id) if (formIndex < 0) { @@ -700,6 +827,7 @@ export default defineComponent({ showArchivedForms, filterText, hasNoFilterResults, + showVersionMismatch, canCreateForms, allowComments, isMobile, @@ -717,10 +845,14 @@ export default defineComponent({ loadForms, onNewForm, onCloneForm, + onUploadForm, onDeleteForm, + onImportForm, + closeModal, onLastUpdatedByEventBus, IconPlus, IconArchive, + IconUpload, FormsIcon, } }, @@ -728,6 +860,12 @@ export default defineComponent({