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
218 changes: 193 additions & 25 deletions lib/Controller/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -151,23 +155,39 @@ 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<string, mixed> $formData (optional) The formdata to import
* @return DataResponse<Http::STATUS_CREATED, FormsForm, array{}>
* @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
*/
#[CORS()]
#[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());
Expand All @@ -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);
Expand Down Expand Up @@ -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<Http::STATUS_OK, FormsForm, array{}>
* @param ?bool $export if the form should get exported
* @return DataResponse<Http::STATUS_OK, FormsForm, array{}>|DataDownloadResponse<Http::STATUS_OK, 'application/json', array{}>
* @throws OCSBadRequestException Could not find form
* @throws OCSForbiddenException User has no permissions to get this form
*
Expand All @@ -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));
}

Expand Down
3 changes: 3 additions & 0 deletions lib/Controller/PageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
Expand All @@ -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 {
Expand Down
Loading
Loading