-
Notifications
You must be signed in to change notification settings - Fork 98
/
ApiController.php
1542 lines (1318 loc) Β· 51.4 KB
/
ApiController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @copyright Copyright (c) 2017 Vinzenz Rosenkranz <[email protected]>
*
* @author affan98 <[email protected]>
* @author Christian Hartmann <[email protected]>
* @author Ferdinand Thiessen <[email protected]>
* @author Jan-Christoph Borchardt <[email protected]>
* @author John Molakvoæ (skjnldsv) <[email protected]>
* @author Jonas Rittershofer <[email protected]>
* @author Roeland Jago Douma <[email protected]>
*
* @license AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Forms\Controller;
use OCA\Forms\Constants;
use OCA\Forms\Db\Answer;
use OCA\Forms\Db\AnswerMapper;
use OCA\Forms\Db\Form;
use OCA\Forms\Db\FormMapper;
use OCA\Forms\Db\Option;
use OCA\Forms\Db\OptionMapper;
use OCA\Forms\Db\Question;
use OCA\Forms\Db\QuestionMapper;
use OCA\Forms\Db\ShareMapper;
use OCA\Forms\Db\Submission;
use OCA\Forms\Db\SubmissionMapper;
use OCA\Forms\Db\UploadedFile;
use OCA\Forms\Db\UploadedFileMapper;
use OCA\Forms\Service\ConfigService;
use OCA\Forms\Service\FormsService;
use OCA\Forms\Service\SubmissionService;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\IMapperException;
use OCP\AppFramework\Http\Attribute\ApiRoute;
use OCP\AppFramework\Http\Attribute\CORS;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
use OCP\AppFramework\Http\Attribute\PublicPage;
use OCP\AppFramework\Http\DataDownloadResponse;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\OCS\OCSBadRequestException;
use OCP\AppFramework\OCS\OCSForbiddenException;
use OCP\AppFramework\OCS\OCSNotFoundException;
use OCP\AppFramework\OCSController;
use OCP\Files\IMimeTypeDetector;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\IL10N;
use OCP\IRequest;
use OCP\IUser;
use OCP\IUserManager;
use OCP\IUserSession;
use Psr\Log\LoggerInterface;
class ApiController extends OCSController {
private ?IUser $currentUser;
public function __construct(
string $appName,
IRequest $request,
IUserSession $userSession,
private AnswerMapper $answerMapper,
private FormMapper $formMapper,
private OptionMapper $optionMapper,
private QuestionMapper $questionMapper,
private ShareMapper $shareMapper,
private SubmissionMapper $submissionMapper,
private ConfigService $configService,
private FormsService $formsService,
private SubmissionService $submissionService,
private IL10N $l10n,
private LoggerInterface $logger,
private IUserManager $userManager,
private IRootFolder $rootFolder,
private UploadedFileMapper $uploadedFileMapper,
private IMimeTypeDetector $mimeTypeDetector,
) {
parent::__construct($appName, $request);
$this->currentUser = $userSession->getUser();
}
// CORS preflight
/**
* Handle CORS options request by calling parent function
*/
#[ApiRoute(verb: 'OPTIONS', url: Constants::API_BASE . '{path}', requirements: Constants::API_V3_REQUIREMENTS)]
public function preflightedCors() {
parent::preflightedCors();
}
// API v3 methods
// Forms
/**
* Read Form-List of owned forms
* Return only with necessary information for Listing.
* @return DataResponse
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'GET', url: Constants::API_BASE . 'forms', requirements: Constants::API_V3_REQUIREMENTS)]
public function getForms(string $type = 'owned'): DataResponse {
if ($type === 'owned') {
$forms = $this->formMapper->findAllByOwnerId($this->currentUser->getUID());
$result = [];
foreach ($forms as $form) {
$result[] = $this->formsService->getPartialFormArray($form);
}
return new DataResponse($result);
} elseif ($type === 'shared') {
$forms = $this->formsService->getSharedForms($this->currentUser);
$result = array_values(array_map(fn (Form $form): array => $this->formsService->getPartialFormArray($form), $forms));
return new DataResponse($result);
} else {
throw new OCSBadRequestException();
}
}
/**
* Create a new Form and return the Form to edit.
* Return a cloned Form if the parameter $fromId is set
*
* @param int $fromId (optional) ID of the Form that should be cloned
* @return DataResponse
* @throws OCSBadRequestException
* @throws OCSForbiddenException
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'POST', url: Constants::API_BASE . 'forms', requirements: Constants::API_V3_REQUIREMENTS)]
public function newForm(?int $fromId = null): DataResponse {
// Check if user is allowed
if (!$this->configService->canCreateForms()) {
$this->logger->debug('This user is not allowed to create Forms.');
throw new OCSForbiddenException();
}
if ($fromId === null) {
// Create Form
$form = new Form();
$form->setOwnerId($this->currentUser->getUID());
$form->setHash($this->formsService->generateFormHash());
$form->setTitle('');
$form->setDescription('');
$form->setAccess([
'permitAllUsers' => false,
'showToAllUsers' => false,
]);
$form->setSubmitMultiple(false);
$form->setShowExpiration(false);
$form->setExpires(0);
$form->setIsAnonymous(false);
$this->formMapper->insert($form);
} else {
$oldForm = $this->getFormIfAllowed($fromId);
// Read Form, set new Form specific data, extend Title.
$formData = $oldForm->read();
unset($formData['id']);
unset($formData['created']);
unset($formData['lastUpdated']);
$formData['hash'] = $this->formsService->generateFormHash();
// TRANSLATORS Appendix to the form Title of a duplicated/copied form.
$formData['title'] .= ' - ' . $this->l10n->t('Copy');
$form = Form::fromParams($formData);
$this->formMapper->insert($form);
// Get Questions, set new formId, reinsert
$questions = $this->questionMapper->findByForm($oldForm->getId());
foreach ($questions as $oldQuestion) {
$questionData = $oldQuestion->read();
unset($questionData['id']);
$questionData['formId'] = $form->getId();
$newQuestion = Question::fromParams($questionData);
$this->questionMapper->insert($newQuestion);
// Get Options, set new QuestionId, reinsert
$options = $this->optionMapper->findByQuestion($oldQuestion->getId());
foreach ($options as $oldOption) {
$optionData = $oldOption->read();
unset($optionData['id']);
$optionData['questionId'] = $newQuestion->getId();
$newOption = Option::fromParams($optionData);
$this->optionMapper->insert($newOption);
}
}
}
return $this->getForm($form->getId());
}
/**
* Read all information to edit a Form (form, questions, options, except submissions/answers).
*
* @param int $formId Id of the form
* @return DataResponse
* @throws OCSBadRequestException
* @throws OCSForbiddenException
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'GET', url: Constants::API_BASE . 'forms/{formId}', requirements: Constants::API_V3_REQUIREMENTS)]
public function getForm(int $formId): DataResponse {
try {
$form = $this->formMapper->findById($formId);
} catch (IMapperException $e) {
$this->logger->debug('Could not find form');
throw new OCSBadRequestException();
}
if (!$this->formsService->hasUserAccess($form)) {
$this->logger->debug('User has no permissions to get this form');
throw new OCSForbiddenException();
}
$formData = $this->formsService->getForm($form);
return new DataResponse($formData);
}
/**
* Writes the given key-value pairs into Database.
*
* @param int $formId FormId of form to update
* @param array $keyValuePairs Array of key=>value pairs to update.
* @return DataResponse
* @throws OCSBadRequestException
* @throws OCSForbiddenException
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'PATCH', url: Constants::API_BASE . 'forms/{formId}', requirements: Constants::API_V3_REQUIREMENTS)]
public function updateForm(int $formId, array $keyValuePairs): DataResponse {
$this->logger->debug('Updating form: formId: {formId}, values: {keyValuePairs}', [
'formId' => $formId,
'keyValuePairs' => $keyValuePairs
]);
$form = $this->getFormIfAllowed($formId);
// Don't allow empty array
if (sizeof($keyValuePairs) === 0) {
$this->logger->info('Empty keyValuePairs, will not update.');
throw new OCSForbiddenException();
}
// Process owner transfer
if (sizeof($keyValuePairs) === 1 && key_exists('ownerId', $keyValuePairs)) {
$this->logger->debug('Updating owner: formId: {formId}, userId: {uid}', [
'formId' => $formId,
'uid' => $keyValuePairs['ownerId']
]);
$user = $this->userManager->get($keyValuePairs['ownerId']);
if ($user == null) {
$this->logger->debug('Could not find new form owner');
throw new OCSBadRequestException('Could not find new form owner');
}
// update form owner
$form->setOwnerId($keyValuePairs['ownerId']);
// Update changed Columns in Db.
$this->formMapper->update($form);
return new DataResponse($form->getOwnerId());
}
// Don't allow to change params id, hash, ownerId, created, lastUpdated, fileId
if (
key_exists('id', $keyValuePairs) || key_exists('hash', $keyValuePairs) ||
key_exists('ownerId', $keyValuePairs) || key_exists('created', $keyValuePairs) ||
isset($keyValuePairs['fileId']) || key_exists('lastUpdated', $keyValuePairs)
) {
$this->logger->info('Not allowed to update id, hash, ownerId, created, fileId or lastUpdated');
throw new OCSForbiddenException();
}
// Process file linking
if (isset($keyValuePairs['path']) && isset($keyValuePairs['fileFormat'])) {
$file = $this->submissionService->writeFileToCloud($form, $keyValuePairs['path'], $keyValuePairs['fileFormat']);
$form->setFileId($file->getId());
$form->setFileFormat($keyValuePairs['fileFormat']);
}
// Process file unlinking
if (key_exists('fileId', $keyValuePairs) && key_exists('fileFormat', $keyValuePairs) && !isset($keyValuePairs['fileId']) && !isset($keyValuePairs['fileFormat'])) {
$form->setFileId(null);
$form->setFileFormat(null);
}
unset($keyValuePairs['path']);
unset($keyValuePairs['fileId']);
unset($keyValuePairs['fileFormat']);
// Create FormEntity with given Params & Id.
foreach ($keyValuePairs as $key => $value) {
$method = 'set' . ucfirst($key);
$form->$method($value);
}
// Update changed Columns in Db.
$this->formMapper->update($form);
return new DataResponse($form->getId());
}
/**
* Delete a form
*
* @param int $formId the form id
* @return DataResponse
* @throws OCSBadRequestException
* @throws OCSForbiddenException
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'DELETE', url: Constants::API_BASE . 'forms/{formId}', requirements: Constants::API_V3_REQUIREMENTS)]
public function deleteForm(int $formId): DataResponse {
$this->logger->debug('Delete Form: {formId}', [
'formId' => $formId,
]);
$form = $this->getFormIfAllowed($formId);
$this->formMapper->deleteForm($form);
return new DataResponse($formId);
}
// Questions
/**
* Read all questions (including options)
*
* @param int $formId FormId
* @return DataResponse
* @throws OCSBadRequestException
* @throws OCSForbiddenException
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'GET', url: Constants::API_BASE . 'forms/{formId}/questions', requirements: Constants::API_V3_REQUIREMENTS)]
public function getQuestions(int $formId): DataResponse {
try {
$form = $this->formMapper->findById($formId);
} catch (IMapperException $e) {
$this->logger->debug('Could not find form');
throw new OCSBadRequestException();
}
if (!$this->formsService->hasUserAccess($form)) {
$this->logger->debug('User has no permissions to get this form');
throw new OCSForbiddenException();
}
$questionData = $this->formsService->getQuestions($formId);
return new DataResponse($questionData);
}
/**
* Read a specific question (including options)
*
* @param int $formId FormId
* @param int $questionId QuestionId
* @return DataResponse
* @throws OCSBadRequestException
* @throws OCSForbiddenException
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'GET', url: Constants::API_BASE . 'forms/{formId}/questions/{questionId}', requirements: Constants::API_V3_REQUIREMENTS)]
public function getQuestion(int $formId, int $questionId): DataResponse {
try {
$form = $this->formMapper->findById($formId);
} catch (IMapperException $e) {
$this->logger->debug('Could not find form');
throw new OCSBadRequestException();
}
if (!$this->formsService->hasUserAccess($form)) {
$this->logger->debug('User has no permissions to get this form');
throw new OCSForbiddenException();
}
$question = $this->formsService->getQuestion($questionId);
if ($question['formId'] !== $formId) {
throw new OCSBadRequestException('Question doesn\'t belong to given Form');
}
return new DataResponse($question);
}
/**
* Add a new question
*
* @param int $formId the form id
* @param string $type the new question type
* @param string $text the new question title
* @param int $fromId (optional) id of the question that should be cloned
* @return DataResponse
* @throws OCSBadRequestException
* @throws OCSForbiddenException
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'POST', url: Constants::API_BASE . 'forms/{formId}/questions', requirements: Constants::API_V3_REQUIREMENTS)]
public function newQuestion(int $formId, ?string $type = null, string $text = '', ?int $fromId = null): DataResponse {
$form = $this->getFormIfAllowed($formId);
if ($this->formsService->isFormArchived($form)) {
$this->logger->debug('This form is archived and can not be modified');
throw new OCSForbiddenException();
}
if ($fromId === null) {
$this->logger->debug('Adding new question: formId: {formId}, type: {type}, text: {text}', [
'formId' => $formId,
'type' => $type,
'text' => $text,
]);
if (array_search($type, Constants::ANSWER_TYPES) === false) {
$this->logger->debug('Invalid type');
throw new OCSBadRequestException('Invalid type');
}
// Block creation of datetime questions
if ($type === 'datetime') {
$this->logger->debug('Datetime question type no longer supported');
throw new OCSBadRequestException('Datetime question type no longer supported');
}
// Retrieve all active questions sorted by Order. Takes the order of the last array-element and adds one.
$questions = $this->questionMapper->findByForm($formId);
$lastQuestion = array_pop($questions);
if ($lastQuestion) {
$questionOrder = $lastQuestion->getOrder() + 1;
} else {
$questionOrder = 1;
}
$question = new Question();
$question->setFormId($formId);
$question->setOrder($questionOrder);
$question->setType($type);
$question->setText($text);
$question->setDescription('');
$question->setIsRequired(false);
$question->setExtraSettings([]);
$question = $this->questionMapper->insert($question);
$response = $question->read();
$response['options'] = [];
$response['accept'] = [];
} else {
$this->logger->debug('Question to be cloned: {fromId}', [
'fromId' => $fromId
]);
try {
$sourceQuestion = $this->questionMapper->findById($fromId);
$sourceOptions = $this->optionMapper->findByQuestion($fromId);
} catch (IMapperException $e) {
$this->logger->debug('Could not find question');
throw new OCSNotFoundException('Could not find question');
}
$allQuestions = $this->questionMapper->findByForm($formId);
$questionData = $sourceQuestion->read();
unset($questionData['id']);
$questionData['order'] = end($allQuestions)->getOrder() + 1;
$newQuestion = Question::fromParams($questionData);
$this->questionMapper->insert($newQuestion);
$response = $newQuestion->read();
$response['options'] = [];
$response['accept'] = [];
foreach ($sourceOptions as $sourceOption) {
$optionData = $sourceOption->read();
unset($optionData['id']);
$optionData['questionId'] = $newQuestion->getId();
$newOption = Option::fromParams($optionData);
$insertedOption = $this->optionMapper->insert($newOption);
$response['options'][] = $insertedOption->read();
}
}
$this->formMapper->update($form);
return new DataResponse($response);
}
/**
* Writes the given key-value pairs into Database.
* Key 'order' should only be changed by reorderQuestions() and is not allowed here.
*
* @param int $formId the form id
* @param int $questionId id of question to update
* @param array $keyValuePairs Array of key=>value pairs to update.
* @return DataResponse
* @throws OCSBadRequestException
* @throws OCSForbiddenException
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'PATCH', url: Constants::API_BASE . 'forms/{formId}/questions/{questionId}', requirements: Constants::API_V3_REQUIREMENTS)]
public function updateQuestion(int $formId, int $questionId, array $keyValuePairs): DataResponse {
$this->logger->debug('Updating question: formId: {formId}, questionId: {questionId}, values: {keyValuePairs}', [
'formId' => $formId,
'questionId' => $questionId,
'keyValuePairs' => $keyValuePairs
]);
try {
$question = $this->questionMapper->findById($questionId);
} catch (IMapperException $e) {
$this->logger->debug('Could not find question');
throw new OCSBadRequestException('Could not find question');
}
if ($question->getFormId() !== $formId) {
throw new OCSBadRequestException('Question doesn\'t belong to given Form');
}
$form = $this->getFormIfAllowed($formId);
if ($this->formsService->isFormArchived($form)) {
$this->logger->debug('This form is archived and can not be modified');
throw new OCSForbiddenException();
}
// Don't allow empty array
if (sizeof($keyValuePairs) === 0) {
$this->logger->info('Empty keyValuePairs, will not update.');
throw new OCSForbiddenException();
}
//Don't allow to change id or formId
if (key_exists('id', $keyValuePairs) || key_exists('formId', $keyValuePairs)) {
$this->logger->debug('Not allowed to update \'id\' or \'formId\'');
throw new OCSForbiddenException();
}
// Don't allow to reorder here
if (key_exists('order', $keyValuePairs)) {
$this->logger->debug('Key \'order\' is not allowed on updateQuestion. Please use reorderQuestions() to change order.');
throw new OCSForbiddenException('Please use reorderQuestions() to change order');
}
if (key_exists('extraSettings', $keyValuePairs) && !$this->formsService->areExtraSettingsValid($keyValuePairs['extraSettings'], $question->getType())) {
throw new OCSBadRequestException('Invalid extraSettings, will not update.');
}
// Create QuestionEntity with given Params & Id.
$question = Question::fromParams($keyValuePairs);
$question->setId($questionId);
// Update changed Columns in Db.
$this->questionMapper->update($question);
$this->formMapper->update($form);
return new DataResponse($question->getId());
}
/**
* Delete a question
*
* @param int $formId the form id
* @param int $questionId the question id
* @return DataResponse
* @throws OCSBadRequestException
* @throws OCSForbiddenException
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'DELETE', url: Constants::API_BASE . 'forms/{formId}/questions/{questionId}', requirements: Constants::API_V3_REQUIREMENTS)]
public function deleteQuestion(int $formId, int $questionId): DataResponse {
$this->logger->debug('Mark question as deleted: {questionId}', [
'questionId' => $questionId,
]);
try {
$question = $this->questionMapper->findById($questionId);
} catch (IMapperException $e) {
$this->logger->debug('Could not find question');
throw new OCSBadRequestException('Could not find question');
}
if ($question->getFormId() !== $formId) {
throw new OCSBadRequestException('Question doesn\'t belong to given Form');
}
$form = $this->getFormIfAllowed($formId);
if ($this->formsService->isFormArchived($form)) {
$this->logger->debug('This form is archived and can not be modified');
throw new OCSForbiddenException();
}
// Store Order of deleted Question
$deletedOrder = $question->getOrder();
// Mark question as deleted
$question->setOrder(0);
$this->questionMapper->update($question);
// Update all question-order > deleted order.
$formQuestions = $this->questionMapper->findByForm($formId);
foreach ($formQuestions as $question) {
$questionOrder = $question->getOrder();
if ($questionOrder > $deletedOrder) {
$question->setOrder($questionOrder - 1);
$this->questionMapper->update($question);
}
}
$this->formMapper->update($form);
return new DataResponse($questionId);
}
/**
* Updates the Order of all Questions of a Form.
*
* @param int $formId Id of the form to reorder
* @param Array<int, int> $newOrder Array of Question-Ids in new order.
* @return DataResponse
* @throws OCSBadRequestException
* @throws OCSForbiddenException
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'PATCH', url: Constants::API_BASE . 'forms/{formId}/questions', requirements: Constants::API_V3_REQUIREMENTS)]
public function reorderQuestions(int $formId, array $newOrder): DataResponse {
$this->logger->debug('Reordering Questions on Form {formId} as Question-Ids {newOrder}', [
'formId' => $formId,
'newOrder' => $newOrder
]);
$form = $this->getFormIfAllowed($formId);
if ($this->formsService->isFormArchived($form)) {
$this->logger->debug('This form is archived and can not be modified');
throw new OCSForbiddenException();
}
// Check if array contains duplicates
if (array_unique($newOrder) !== $newOrder) {
$this->logger->debug('The given array contains duplicates');
throw new OCSBadRequestException('The given array contains duplicates');
}
// Check if all questions are given in Array.
$questions = $this->questionMapper->findByForm($formId);
if (sizeof($questions) !== sizeof($newOrder)) {
$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');
}
$questions = []; // Clear Array of Entities
$response = []; // Array of ['questionId' => ['order' => newOrder]]
// Store array of Question-Entities and check the Questions FormId & old Order.
foreach ($newOrder as $arrayKey => $questionId) {
try {
$questions[$arrayKey] = $this->questionMapper->findById($questionId);
} catch (IMapperException $e) {
$this->logger->debug('Could not find question. Id: {questionId}', [
'questionId' => $questionId
]);
throw new OCSBadRequestException();
}
// Abort if a question is not part of the Form.
if ($questions[$arrayKey]->getFormId() !== $formId) {
$this->logger->debug('This Question is not part of the given Form: questionId: {questionId}', [
'questionId' => $questionId
]);
throw new OCSBadRequestException();
}
// 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();
}
// Only set order, if it changed.
if ($oldOrder !== $arrayKey + 1) {
// Set Order. ArrayKey counts from zero, order counts from 1.
$questions[$arrayKey]->setOrder($arrayKey + 1);
}
}
// Write to Database
foreach ($questions as $question) {
$this->questionMapper->update($question);
$response[$question->getId()] = [
'order' => $question->getOrder()
];
}
$this->formMapper->update($form);
return new DataResponse($response);
}
// Options
/**
* Add a new option to a question
*
* @param int $formId id of the form
* @param int $questionId id of the question
* @param array<string> $optionTexts the new option text
* @return DataResponse Returns a DataResponse containing the added options
* @throws OCSBadRequestException
* @throws OCSForbiddenException
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'POST', url: Constants::API_BASE . 'forms/{formId}/questions/{questionId}/options', requirements: Constants::API_V3_REQUIREMENTS)]
public function newOption(int $formId, int $questionId, array $optionTexts): DataResponse {
$this->logger->debug('Adding new options: formId: {formId}, questionId: {questionId}, text: {text}', [
'formId' => $formId,
'questionId' => $questionId,
'text' => $optionTexts,
]);
$form = $this->getFormIfAllowed($formId);
if ($this->formsService->isFormArchived($form)) {
$this->logger->debug('This form is archived and can not be modified');
throw new OCSForbiddenException();
}
try {
$question = $this->questionMapper->findById($questionId);
} catch (IMapperException $e) {
$this->logger->debug('Could not find question');
throw new OCSBadRequestException('Could not find question');
}
if ($question->getFormId() !== $formId) {
$this->logger->debug('This Question is not part of the given Form: questionId: {questionId}', [
'questionId' => $questionId
]);
throw new OCSBadRequestException();
}
// Retrieve all options sorted by 'order'. Takes the order of the last array-element and adds one.
$options = $this->optionMapper->findByQuestion($questionId);
$lastOption = array_pop($options);
if ($lastOption) {
$optionOrder = $lastOption->getOrder() + 1;
} else {
$optionOrder = 1;
}
$addedOptions = [];
foreach ($optionTexts as $text) {
$option = new Option();
$option->setQuestionId($questionId);
$option->setText($text);
$option->setOrder($optionOrder++);
try {
$option = $this->optionMapper->insert($option);
// Add the stored option to the collection of added options
$addedOptions[] = $option->read();
} catch (IMapperException $e) {
$this->logger->error("Failed to add option: {$e->getMessage()}");
// Optionally handle the error, e.g., by continuing to the next iteration or returning an error response
}
}
$this->formMapper->update($form);
return new DataResponse($addedOptions);
}
/**
* Writes the given key-value pairs into Database.
*
* @param int $formId id of form
* @param int $questionId id of question
* @param int $optionId id of option to update
* @param array $keyValuePairs Array of key=>value pairs to update.
* @return DataResponse
* @throws OCSBadRequestException
* @throws OCSForbiddenException
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'PATCH', url: Constants::API_BASE . 'forms/{formId}/questions/{questionId}/options/{optionId}', requirements: Constants::API_V3_REQUIREMENTS)]
public function updateOption(int $formId, int $questionId, int $optionId, array $keyValuePairs): DataResponse {
$this->logger->debug('Updating option: form: {formId}, question: {questionId}, option: {optionId}, values: {keyValuePairs}', [
'formId' => $formId,
'questionId' => $questionId,
'optionId' => $optionId,
'keyValuePairs' => $keyValuePairs
]);
$form = $this->getFormIfAllowed($formId);
if ($this->formsService->isFormArchived($form)) {
$this->logger->debug('This form is archived and can not be modified');
throw new OCSForbiddenException();
}
try {
$option = $this->optionMapper->findById($optionId);
$question = $this->questionMapper->findById($questionId);
} catch (IMapperException $e) {
$this->logger->debug('Could not find option or question');
throw new OCSBadRequestException('Could not find option or question');
}
if ($option->getQuestionId() !== $questionId || $question->getFormId() !== $formId) {
$this->logger->debug('The given option id doesn\'t match the question or form.');
throw new OCSBadRequestException();
}
// Don't allow empty array
if (sizeof($keyValuePairs) === 0) {
$this->logger->info('Empty keyValuePairs, will not update.');
throw new OCSForbiddenException();
}
//Don't allow to change id or questionId
if (key_exists('id', $keyValuePairs) || key_exists('questionId', $keyValuePairs)) {
$this->logger->debug('Not allowed to update id or questionId');
throw new OCSForbiddenException();
}
// Create OptionEntity with given Params & Id.
$option = Option::fromParams($keyValuePairs);
$option->setId($optionId);
// Update changed Columns in Db.
$this->optionMapper->update($option);
$this->formMapper->update($form);
return new DataResponse($option->getId());
}
/**
* Delete an option
*
* @param int $formId id of form
* @param int $questionId id of question
* @param int $optionId id of option to update
* @return DataResponse
* @throws OCSBadRequestException
* @throws OCSForbiddenException
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'DELETE', url: Constants::API_BASE . 'forms/{formId}/questions/{questionId}/options/{optionId}', requirements: Constants::API_V3_REQUIREMENTS)]
public function deleteOption(int $formId, int $questionId, int $optionId): DataResponse {
$this->logger->debug('Deleting option: {optionId}', [
'optionId' => $optionId
]);
$form = $this->getFormIfAllowed($formId);
if ($this->formsService->isFormArchived($form)) {
$this->logger->debug('This form is archived and can not be modified');
throw new OCSForbiddenException();
}
try {
$option = $this->optionMapper->findById($optionId);
$question = $this->questionMapper->findById($questionId);
} catch (IMapperException $e) {
$this->logger->debug('Could not find form, question or option');
throw new OCSBadRequestException('Could not find form, question or option');
}
if ($option->getQuestionId() !== $questionId || $question->getFormId() !== $formId) {
$this->logger->debug('The given option id doesn\'t match the question or form.');
throw new OCSBadRequestException();
}
$this->optionMapper->delete($option);
// Reorder the remaining options
$options = array_values($this->optionMapper->findByQuestion($questionId));
foreach ($options as $order => $option) {
// Always start order with 1
$option->setOrder($order + 1);
$this->optionMapper->update($option);
}
$this->formMapper->update($form);
return new DataResponse($optionId);
}
/**
* Reorder options for a given question
* @param int $formId id of form
* @param int $questionId id of question
* @param Array<int, int> $newOrder Order to use
*/
#[CORS()]
#[NoAdminRequired()]
#[ApiRoute(verb: 'PATCH', url: Constants::API_BASE . 'forms/{formId}/questions/{questionId}/options', requirements: Constants::API_V3_REQUIREMENTS)]
public function reorderOptions(int $formId, int $questionId, array $newOrder) {
$form = $this->getFormIfAllowed($formId);
if ($this->formsService->isFormArchived($form)) {
$this->logger->debug('This form is archived and can not be modified');
throw new OCSForbiddenException();
}
try {
$question = $this->questionMapper->findById($questionId);
} catch (IMapperException $e) {
$this->logger->debug('Could not find form or question', ['exception' => $e]);
throw new OCSNotFoundException('Could not find form or question');
}
if ($question->getFormId() !== $formId) {
$this->logger->debug('The given question id doesn\'t match the form.');
throw new OCSBadRequestException();
}
// Check if array contains duplicates
if (array_unique($newOrder) !== $newOrder) {
$this->logger->debug('The given array contains duplicates');
throw new OCSBadRequestException('The given array contains duplicates');
}
$options = $this->optionMapper->findByQuestion($questionId);
if (sizeof($options) !== sizeof($newOrder)) {
$this->logger->debug('The length of the given array does not match the number of stored options');
throw new OCSBadRequestException('The length of the given array does not match the number of stored options');
}
$options = []; // Clear Array of Entities
$response = []; // Array of ['optionId' => ['order' => newOrder]]
// Store array of Option entities and check the Options questionId & old order.
foreach ($newOrder as $arrayKey => $optionId) {
try {
$options[$arrayKey] = $this->optionMapper->findById($optionId);
} catch (IMapperException $e) {
$this->logger->debug('Could not find option. Id: {optionId}', [
'optionId' => $optionId
]);
throw new OCSBadRequestException();
}
// Abort if a question is not part of the Form.
if ($options[$arrayKey]->getQuestionId() !== $questionId) {
$this->logger->debug('This Option is not part of the given Question: formId: {formId}', [
'formId' => $formId
]);
throw new OCSBadRequestException();
}
// Abort if a question is already marked as deleted (order==0)
$oldOrder = $options[$arrayKey]->getOrder();
// Only set order, if it changed.
if ($oldOrder !== $arrayKey + 1) {
// Set Order. ArrayKey counts from zero, order counts from 1.
$options[$arrayKey]->setOrder($arrayKey + 1);