-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathGroupsPresenter.php
More file actions
1410 lines (1231 loc) · 49.6 KB
/
GroupsPresenter.php
File metadata and controls
1410 lines (1231 loc) · 49.6 KB
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
namespace App\V1Module\Presenters;
use App\Helpers\MetaFormats\Attributes\Post;
use App\Helpers\MetaFormats\Attributes\Query;
use App\Helpers\MetaFormats\Attributes\Path;
use App\Helpers\MetaFormats\Attributes\ResponseFormat;
use App\Helpers\MetaFormats\FormatDefinitions\GroupFormat;
use App\Helpers\MetaFormats\Validators\VArray;
use App\Helpers\MetaFormats\Validators\VBool;
use App\Helpers\MetaFormats\Validators\VInt;
use App\Helpers\MetaFormats\Validators\VMixed;
use App\Helpers\MetaFormats\Validators\VString;
use App\Helpers\MetaFormats\Validators\VTimestamp;
use App\Helpers\MetaFormats\Validators\VUuid;
use App\Exceptions\InvalidApiArgumentException;
use App\Exceptions\NotFoundException;
use App\Exceptions\BadRequestException;
use App\Exceptions\ForbiddenRequestException;
use App\Exceptions\FrontendErrorMappings;
use App\Helpers\Localizations;
use App\Model\Entity\Assignment;
use App\Model\Entity\ShadowAssignment;
use App\Model\Entity\Group;
use App\Model\Entity\GroupExamLock;
use App\Model\Entity\Instance;
use App\Model\Entity\LocalizedGroup;
use App\Model\Entity\GroupMembership;
use App\Model\Entity\AssignmentSolution;
use App\Model\Repository\Assignments;
use App\Model\Repository\Groups;
use App\Model\Repository\GroupExams;
use App\Model\Repository\GroupExamLocks;
use App\Model\Repository\Users;
use App\Model\Repository\Instances;
use App\Model\Repository\GroupMemberships;
use App\Model\Repository\AssignmentSolutions;
use App\Model\Repository\SecurityEvents;
use App\Model\View\AssignmentViewFactory;
use App\Model\View\AssignmentSolutionViewFactory;
use App\Model\View\ShadowAssignmentViewFactory;
use App\Model\View\GroupViewFactory;
use App\Model\View\UserViewFactory;
use App\Security\ACL\IAssignmentPermissions;
use App\Security\ACL\IAssignmentSolutionPermissions;
use App\Security\ACL\IShadowAssignmentPermissions;
use App\Security\ACL\IGroupPermissions;
use App\Security\Identity;
use App\Security\Loader;
use App\Security\UserStorage;
use DateTime;
use Nette\Application\Request;
/**
* Endpoints for group manipulation
* @LoggedIn
*/
class GroupsPresenter extends BasePresenter
{
/**
* @var Groups
* @inject
*/
public $groups;
/**
* @var GroupExams
* @inject
*/
public $groupExams;
/**
* @var GroupExamLocks
* @inject
*/
public $groupExamLocks;
/**
* @var Instances
* @inject
*/
public $instances;
/**
* @var Users
* @inject
*/
public $users;
/**
* @var GroupMemberships
* @inject
*/
public $groupMemberships;
/**
* @var Assignments
* @inject
*/
public $assignments;
/**
* @var AssignmentSolutions
* @inject
*/
public $assignmentSolutions;
/**
* @var SecurityEvents
* @inject
*/
public $securityEvents;
/**
* @var IGroupPermissions
* @inject
*/
public $groupAcl;
/**
* @var IAssignmentPermissions
* @inject
*/
public $assignmentAcl;
/**
* @var IAssignmentSolutionPermissions
* @inject
*/
public $assignmentSolutionAcl;
/**
* @var IShadowAssignmentPermissions
* @inject
*/
public $shadowAssignmentAcl;
/**
* @var Loader
* @inject
*/
public $aclLoader;
/**
* @var UserStorage
* @inject
*/
public $userStorage;
/**
* @var GroupViewFactory
* @inject
*/
public $groupViewFactory;
/**
* @var UserViewFactory
* @inject
*/
public $userViewFactory;
/**
* @var AssignmentViewFactory
* @inject
*/
public $assignmentViewFactory;
/**
* @var AssignmentSolutionViewFactory
* @inject
*/
public $solutionsViewFactory;
/**
* @var ShadowAssignmentViewFactory
* @inject
*/
public $shadowAssignmentViewFactory;
/**
* Get a list of all non-archived groups a user can see. The return set is filtered by parameters.
* @GET
*/
#[Query("instanceId", new VString(), "Only groups of this instance are returned.", required: false, nullable: true)]
#[Query(
"ancestors",
new VBool(false),
"If true, returns an ancestral closure of the initial result set. "
. "Included ancestral groups do not respect other filters (archived, search, ...).",
required: false,
)]
#[Query(
"search",
new VString(),
"Search string. Only groups containing this string as a substring of their names are returned.",
required: false,
nullable: true,
)]
#[Query("archived", new VBool(false), "Include also archived groups in the result.", required: false)]
#[Query(
"onlyArchived",
new VBool(false),
"Automatically implies \$archived flag and returns only archived groups.",
required: false,
)]
public function actionDefault(
?string $instanceId = null,
bool $ancestors = false,
?string $search = null,
bool $archived = false,
bool $onlyArchived = false
) {
$user = $this->groupAcl->canViewAll() ? null : $this->getCurrentUser(); // user for membership restriction
$groups = $this->groups->findFiltered($user, $instanceId, $search, $archived, $onlyArchived);
if ($ancestors) {
$groups = $this->groups->groupsAncestralClosure($groups);
}
$this->sendSuccessResponse($this->groupViewFactory->getGroups($groups, false));
}
/**
* Helper method that handles updating points limit and threshold to a group entity (from a request).
* @param Request $req request data
* @param Group $group to be updated
*/
private function setGroupPoints(Request $req, Group $group): void
{
$threshold = $req->getPost("threshold");
$pointsLimit = $req->getPost("pointsLimit");
if ($threshold !== null && $pointsLimit !== null) {
throw new InvalidApiArgumentException(
'threshold',
"A group may have either a threshold or points limit, not both."
);
}
if ($threshold !== null) {
if ($threshold <= 0 || $threshold > 100) {
throw new InvalidApiArgumentException('threshold', "A threshold must be in the (0, 100] (%) range.");
}
$group->setThreshold($threshold / 100);
} else {
$group->setThreshold(null);
}
if ($pointsLimit !== null) {
if ($pointsLimit <= 0) {
throw new InvalidApiArgumentException('pointsLimit', "A points limit must be a positive number.");
}
$group->setPointsLimit($pointsLimit);
} else {
$group->setPointsLimit(null);
}
}
/**
* Create a new group
* @POST
* @throws ForbiddenRequestException
* @throws InvalidApiArgumentException
*/
#[Post("instanceId", new VUuid(), "An identifier of the instance where the group should be created")]
#[Post(
"externalId",
new VMixed(),
"An informative, human readable identifier of the group",
required: false,
nullable: true,
)]
#[Post(
"parentGroupId",
new VUuid(),
"Identifier of the parent group (if none is given, a top-level group is created)",
required: false,
)]
#[Post("publicStats", new VBool(), "Should students be able to see each other's results?", required: false)]
#[Post("detaining", new VBool(), "Are students prevented from leaving the group on their own?", required: false)]
#[Post("isPublic", new VBool(), "Should the group be visible to all student?", required: false)]
#[Post(
"isOrganizational",
new VBool(),
"Whether the group is organizational (no assignments nor students).",
required: false,
)]
#[Post("isExam", new VBool(), "Whether the group is an exam group.", required: false)]
#[Post("localizedTexts", new VArray(), "Localized names and descriptions", required: false)]
#[Post("threshold", new VInt(), "A minimum percentage of points needed to pass the course", required: false)]
#[Post("pointsLimit", new VInt(), "A minimum of (absolute) points needed to pass the course", required: false)]
#[Post(
"noAdmin",
new VBool(),
"If true, no admin is assigned to group (current user is assigned as admin by default.",
required: false,
)]
#[ResponseFormat(GroupFormat::class)]
public function actionAddGroup()
{
$req = $this->getRequest();
$instanceId = $req->getPost("instanceId");
$parentGroupId = $req->getPost("parentGroupId");
$user = $this->getCurrentUser();
/** @var Instance $instance */
$instance = $this->instances->findOrThrow($instanceId);
$parentGroup = !$parentGroupId ? $instance->getRootGroup() : $this->groups->findOrThrow($parentGroupId);
if ($parentGroup->isArchived()) {
throw new InvalidApiArgumentException(
'parentGroupId',
"It is not permitted to create subgroups in archived groups"
);
}
if (!$this->groupAcl->canAddSubgroup($parentGroup)) {
throw new ForbiddenRequestException("You are not allowed to add subgroups to this group");
}
$externalId = $req->getPost("externalId") === null ? "" : $req->getPost("externalId");
$publicStats = filter_var($req->getPost("publicStats"), FILTER_VALIDATE_BOOLEAN);
$detaining = filter_var($req->getPost("detaining"), FILTER_VALIDATE_BOOLEAN);
$isPublic = filter_var($req->getPost("isPublic"), FILTER_VALIDATE_BOOLEAN);
$isOrganizational = filter_var($req->getPost("isOrganizational"), FILTER_VALIDATE_BOOLEAN);
$isExam = filter_var($req->getPost("isExam"), FILTER_VALIDATE_BOOLEAN);
$noAdmin = filter_var($req->getPost("noAdmin"), FILTER_VALIDATE_BOOLEAN);
if ($isOrganizational && $isExam) {
throw new InvalidApiArgumentException(
'isOrganizational, isExam',
"A group cannot be both organizational and exam."
);
}
$group = new Group(
$externalId,
$instance,
$noAdmin ? null : $user,
$parentGroup,
$publicStats,
$isPublic,
$isOrganizational,
$detaining,
$isExam,
);
$this->setGroupPoints($req, $group);
$this->updateLocalizations($req, $group);
$this->groups->persist($group, false);
$this->groups->flush();
$this->sendSuccessResponse($this->groupViewFactory->getGroup($group));
}
/**
* Validate group creation data
* @POST
* @throws ForbiddenRequestException
*/
#[Post("name", new VMixed(), "Name of the group", nullable: true)]
#[Post("locale", new VMixed(), "The locale of the name", nullable: true)]
#[Post("instanceId", new VMixed(), "Identifier of the instance where the group belongs", nullable: true)]
#[Post("parentGroupId", new VMixed(), "Identifier of the parent group", required: false, nullable: true)]
public function actionValidateAddGroupData()
{
$req = $this->getRequest();
$name = $req->getPost("name");
$locale = $req->getPost("locale");
$parentGroupId = $req->getPost("parentGroupId");
$instance = $this->instances->findOrThrow($req->getPost("instanceId"));
$parentGroup = $parentGroupId !== null ? $this->groups->findOrThrow($parentGroupId) : $instance->getRootGroup();
if (!$this->groupAcl->canAddSubgroup($parentGroup)) {
throw new ForbiddenRequestException();
}
$this->sendSuccessResponse(
[
"groupNameIsFree" => count($this->groups->findByName($locale, $name, $instance, $parentGroup)) === 0
]
);
}
public function checkUpdateGroup(string $id)
{
$group = $this->groups->findOrThrow($id);
if (!$this->groupAcl->canUpdate($group)) {
throw new ForbiddenRequestException();
}
}
/**
* Update group info
* @POST
* @throws InvalidApiArgumentException
*/
#[Post(
"externalId",
new VMixed(),
"An informative, human readable identifier of the group",
required: false,
nullable: true,
)]
#[Post("publicStats", new VBool(), "Should students be able to see each other's results?")]
#[Post("detaining", new VBool(), "Are students prevented from leaving the group on their own?", required: false)]
#[Post("isPublic", new VBool(), "Should the group be visible to all student?")]
#[Post("threshold", new VInt(), "A minimum percentage of points needed to pass the course", required: false)]
#[Post("pointsLimit", new VInt(), "A minimum of (absolute) points needed to pass the course", required: false)]
#[Post("localizedTexts", new VArray(), "Localized names and descriptions")]
#[Path("id", new VUuid(), "An identifier of the updated group", required: true)]
#[ResponseFormat(GroupFormat::class)]
public function actionUpdateGroup(string $id)
{
$req = $this->getRequest();
$publicStats = filter_var($req->getPost("publicStats"), FILTER_VALIDATE_BOOLEAN);
$detaining = filter_var($req->getPost("detaining"), FILTER_VALIDATE_BOOLEAN);
$isPublic = filter_var($req->getPost("isPublic"), FILTER_VALIDATE_BOOLEAN);
$group = $this->groups->findOrThrow($id);
$group->setExternalId($req->getPost("externalId"));
$group->setPublicStats($publicStats);
$group->setDetaining($detaining);
$group->setIsPublic($isPublic);
$this->setGroupPoints($req, $group);
$this->updateLocalizations($req, $group);
$this->groups->persist($group);
$this->sendSuccessResponse($this->groupViewFactory->getGroup($group));
}
public function checkSetOrganizational(string $id)
{
$group = $this->groups->findOrThrow($id);
if (!$this->groupAcl->canSetOrganizational($group)) {
throw new ForbiddenRequestException();
}
if ($group->isExam()) {
throw new BadRequestException("Organizational group must not be exam group.");
}
}
/**
* Set the 'isOrganizational' flag for a group
* @POST
* @throws BadRequestException
* @throws NotFoundException
*/
#[Post("value", new VBool(), "The value of the flag", required: true)]
#[Path("id", new VUuid(), "An identifier of the updated group", required: true)]
#[ResponseFormat(GroupFormat::class)]
public function actionSetOrganizational(string $id)
{
$group = $this->groups->findOrThrow($id);
$isOrganizational = filter_var($this->getRequest()->getPost("value"), FILTER_VALIDATE_BOOLEAN);
if ($isOrganizational) {
if ($group->getStudents()->count() > 0) {
throw new BadRequestException("The group already contains students");
}
if ($group->getAssignments()->count() > 0) {
throw new BadRequestException("The group already contains assignments");
}
}
$group->setOrganizational($isOrganizational);
$this->groups->persist($group);
$this->sendSuccessResponse($this->groupViewFactory->getGroup($group));
}
public function checkSetArchived(string $id)
{
$group = $this->groups->findOrThrow($id);
if (!$this->groupAcl->canArchive($group)) {
throw new ForbiddenRequestException();
}
}
/**
* Set the 'isArchived' flag for a group
* @POST
* @throws NotFoundException
*/
#[Post("value", new VBool(), "The value of the flag", required: true)]
#[Path("id", new VUuid(), "An identifier of the updated group", required: true)]
#[ResponseFormat(GroupFormat::class)]
public function actionSetArchived(string $id)
{
$group = $this->groups->findOrThrow($id);
$archive = filter_var($this->getRequest()->getPost("value"), FILTER_VALIDATE_BOOLEAN);
if ($archive) {
$group->archive(new DateTime());
// snapshot the inherited membership-relations
$typePriorities = array_flip(GroupMembership::INHERITABLE_TYPES);
// this is actually a hack for PHP Stan (can be removed when there will be more than 1 inheritable type)
$typePriorities[''] = -1; // adding a fake priority for fake type
$membershipsToInherit = []; // aggregated memberships from all ancestors, key is user ID
// scan ancestors and aggregate memberships by priorities
$g = $group; // current group is included as well to remove redundant relations
while ($g !== null) {
$memberships = $g->getMemberships(...GroupMembership::INHERITABLE_TYPES);
foreach ($memberships as $membership) {
$userId = $membership->getUser()->getId();
if (
!empty($membershipsToInherit[$userId])
&& $typePriorities[$membershipsToInherit[$userId]->getType()]
> $typePriorities[$membership->getType()] // lower value = higher priority
) {
continue; // existing membership with higher priority is already recorded
}
$membershipsToInherit[$userId] = $membership;
}
$g = $g->getParentGroup();
}
// create inherited membership records in the database
foreach ($membershipsToInherit as $membership) {
// direct memberships are ignored, they were just used to remove redundant relations
if ($membership->getGroup()->getId() !== $group->getId()) {
$group->inheritMembership($membership);
}
}
} else {
$group->undoArchiving();
// remove inherited memberships what so ever
$memberships = $group->getInheritedMemberships(...GroupMembership::INHERITABLE_TYPES);
foreach ($memberships as $membership) {
$group->removeMembership($membership);
$this->groupMemberships->remove($membership);
}
}
$this->groups->persist($group);
$this->sendSuccessResponse($this->groupViewFactory->getGroup($group));
}
public function checkSetExam(string $id)
{
$group = $this->groups->findOrThrow($id);
if (!$group->getChildGroups()->isEmpty()) {
throw new BadRequestException("Exam group must have no sub-groups.");
}
if ($group->isOrganizational()) {
throw new BadRequestException("Exam group must not be organizational.");
}
if (!$this->groupAcl->canSetExamFlag($group)) {
throw new ForbiddenRequestException();
}
}
/**
* Change the group "exam" indicator. If denotes that the group should be listed in exam groups instead of
* regular groups and the assignments should have "isExam" flag set by default.
* @POST
* @throws BadRequestException
* @throws NotFoundException
*/
#[Post("value", new VBool(), "The value of the flag", required: true)]
#[Path("id", new VUuid(), "An identifier of the updated group", required: true)]
#[ResponseFormat(GroupFormat::class)]
public function actionSetExam(string $id)
{
$group = $this->groups->findOrThrow($id);
$isExam = filter_var($this->getRequest()->getPost("value"), FILTER_VALIDATE_BOOLEAN);
$group->setExam($isExam);
$this->groups->persist($group);
$this->sendSuccessResponse($this->groupViewFactory->getGroup($group));
}
public function checkSetExamPeriod(string $id)
{
$group = $this->groups->findOrThrow($id);
if (!$this->groupAcl->canSetExamPeriod($group)) {
throw new ForbiddenRequestException();
}
}
/**
* Set an examination period (in the future) when the group will be secured for submitting.
* Only locked students may submit solutions in the group during this period.
* This endpoint is also used to update already planned exam period, but only dates in the future
* can be edited (e.g., once an exam begins, the beginning may no longer be updated).
* @POST
* @throws NotFoundException
*/
#[Post(
"begin",
new VTimestamp(),
"When the exam begins (unix ts in the future, optional if update is performed).",
required: false,
nullable: true,
)]
#[Post(
"end",
new VTimestamp(),
"When the exam ends (unix ts in the future, no more than a day after 'begin').",
required: true,
)]
#[Post("strict", new VBool(), "Whether locked users are prevented from accessing other groups.", required: false)]
#[Path("id", new VUuid(), "An identifier of the updated group", required: true)]
#[ResponseFormat(GroupFormat::class)]
public function actionSetExamPeriod(string $id)
{
$group = $this->groups->findOrThrow($id);
$req = $this->getRequest();
$beginTs = (int)$req->getPost("begin");
$endTs = (int)$req->getPost("end");
$strict = $req->getPost("strict") !== null
? filter_var($req->getPost("strict"), FILTER_VALIDATE_BOOLEAN) : null;
$now = (new DateTime())->getTimestamp();
$nowTolerance = 60; // 60s is a tolerance when comparing with "now"
if ($strict === null) {
if ($group->hasExamPeriodSet()) {
$strict = $group->isExamLockStrict(); // flag is not present -> is not changing
} else {
throw new BadRequestException("The strict flag must be present when new exam is being set.");
}
}
// beginning must be in the future (or must not be modified)
if ((!$group->hasExamPeriodSet() || $beginTs) && $beginTs < $now - $nowTolerance) {
throw new BadRequestException("The exam must be set in the future.");
}
// if begin was not sent, or the exam already started, use old begin value
$beginTs = ($group->hasExamPeriodSet() && (!$beginTs || $group->getExamBegin()->getTimestamp() <= $now))
? $group->getExamBegin()->getTimestamp() : $beginTs;
// an exam should not last more than a day (yes, we hardcode the day interval here for safety)
if ($beginTs >= $endTs || $endTs - $beginTs > 86400) {
throw new BadRequestException("The [begin,end] interval must be valid and less than a day wide.");
}
// the end should also be in the future (this is necessary only for updates)
if ($endTs < $now - $nowTolerance) {
throw new BadRequestException("The exam end must be set in the future.");
}
$begin = DateTime::createFromFormat('U', $beginTs);
$end = DateTime::createFromFormat('U', $endTs);
if ($group->hasExamPeriodSet()) {
if ($group->getExamBegin()->getTimestamp() <= $now) { // ... already begun
if ($strict !== $group->isExamLockStrict()) {
throw new BadRequestException("The strict flag cannot be changed once the exam begins.");
}
// the exam already begun, we need to fix any group-locked users
foreach ($group->getStudents() as $student) {
if ($student->getGroupLock()?->getId() === $id) {
$student->setGroupLock($group, $end, $strict);
if ($student->isIpLocked()) {
$student->setIpLock($student->getIpLockRaw(), $end);
}
$this->users->persist($student, false);
}
}
// we need to fix deadlines of all aligned exam assignments
foreach ($group->getAssignments() as $assignment) {
if (
$assignment->isExam() &&
$assignment->getFirstDeadline()->getTimestamp() === $group->getExamEnd()->getTimestamp()
) {
$assignment->setFirstDeadline($end);
$this->assignments->persist($assignment, false);
}
}
} elseif ($group->getExamBegin() !== $begin) {
// we also need to fix times of appearance for scheduled assignments
foreach ($group->getAssignments() as $assignment) {
if (
$assignment->isExam() && $assignment->isPublic() &&
$assignment->getVisibleFrom()?->getTimestamp() === $group->getExamBegin()->getTimestamp()
) {
$assignment->setVisibleFrom($now < $beginTs ? $begin : null);
$this->assignments->persist($assignment, false);
}
}
}
}
$exam = $this->groupExams->findPendingForGroup($group);
if ($exam) {
$exam->update($begin, $end, $strict);
$this->groupExams->persist($exam, false);
}
$group->setExamPeriod($begin, $end, $strict);
$this->groups->persist($group);
$this->sendSuccessResponse($this->groupViewFactory->getGroup($group));
}
public function checkRemoveExamPeriod(string $id)
{
$group = $this->groups->findOrThrow($id);
if (!$group->hasExamPeriodSet()) {
throw new BadRequestException("The group has no exam period set.");
}
if (!$this->groupAcl->canRemoveExamPeriod($group)) {
throw new ForbiddenRequestException();
}
}
/**
* Change the group back to regular group (remove information about an exam).
* @DELETE
* @throws NotFoundException
*/
#[Path("id", new VUuid(), "An identifier of the updated group", required: true)]
#[ResponseFormat(GroupFormat::class)]
public function actionRemoveExamPeriod(string $id)
{
$group = $this->groups->findOrThrow($id);
$group->removeExamPeriod();
$this->groups->persist($group);
$this->sendSuccessResponse($this->groupViewFactory->getGroup($group));
}
public function checkRelocate(string $id, string $newParentId)
{
$group = $this->groups->findOrThrow($id);
$newParent = $this->groups->findOrThrow($newParentId);
if ($group->isArchived() || $newParent->isArchived()) {
throw new BadRequestException(
"Cannot manipulate with archived group.",
FrontendErrorMappings::E400_501__GROUP_ARCHIVED
);
}
if (
!$this->groupAcl->canRelocate($group)
|| !$this->groupAcl->canAddSubgroup($newParent)
) {
throw new ForbiddenRequestException();
}
}
public function checkGetExamLocks(string $id, string $examId)
{
$groupExam = $this->groupExams->findOrThrow($examId);
if ($groupExam->getGroup()?->getId() !== $id) {
throw new BadRequestException(
"Exam $examId is not in group $id.",
FrontendErrorMappings::E400_500__GROUP_ERROR
);
}
$group = $this->groups->findOrThrow($id);
if (!$this->groupAcl->canViewExamLocks($group)) {
throw new ForbiddenRequestException();
}
}
/**
* Retrieve a list of locks for given exam
* @GET
*/
#[Path("id", new VUuid(), "An identifier of the related group", required: true)]
#[Path("examId", new VInt(), "An identifier of the exam", required: true)]
public function actionGetExamLocks(string $id, string $examId)
{
$group = $this->groups->findOrThrow($id);
$exam = $this->groupExams->findOrThrow($examId);
$locks = $this->groupExamLocks->findBy(["groupExam" => $exam]);
$this->sendSuccessResponse($this->groupViewFactory->getGroupExamLocks($group, $locks));
}
/**
* Relocate the group under a different parent.
* @POST
* @throws NotFoundException
* @throws BadRequestException
*/
#[Path("id", new VUuid(), "An identifier of the relocated group", required: true)]
#[Path("newParentId", new VUuid(), "An identifier of the new parent group", required: true)]
public function actionRelocate(string $id, string $newParentId)
{
$group = $this->groups->findOrThrow($id);
$newParent = $this->groups->findOrThrow($newParentId);
if ($group->getInstance() !== null && $group->getInstance()->getRootGroup() === $group) {
throw new BadRequestException(
"The root group of an instance cannot relocate.",
FrontendErrorMappings::E400_502__GROUP_INSTANCE_ROOT_CANNOT_RELOCATE,
['groupId' => $id, 'instanceId' => $group->getInstance()->getId()]
);
}
foreach ($this->groups->groupsAncestralClosure([$newParent]) as $parent) {
if ($parent->getId() === $id) { // group cannot be relocated under its descendant
throw new BadRequestException(
"The relocation would create a loop in the group hierarchy.",
FrontendErrorMappings::E400_503__GROUP_RELOCATION_WOULD_CREATE_LOOP,
['groupId' => $id, 'newParentId' => $newParentId]
);
}
}
$group->setParentGroup($newParent);
$this->groups->persist($group);
$this->forward(
'Groups:',
['instanceId' => $newParent->getInstance()->getId(), 'ancestors' => true]
); // return all groups
}
public function checkRemoveGroup(string $id)
{
$group = $this->groups->findOrThrow($id);
if (!$this->groupAcl->canRemove($group)) {
throw new ForbiddenRequestException();
}
if ($group->getChildGroups()->count() !== 0) {
throw new ForbiddenRequestException("There are subgroups of group '$id'. Please remove them first.");
} else {
if ($group->getInstance() !== null && $group->getInstance()->getRootGroup() === $group) {
throw new ForbiddenRequestException(
"Group '$id' is the root group of instance '"
. $group->getInstance()->getId()
. "' and root groups cannot be deleted."
);
}
}
}
/**
* Delete a group
* @DELETE
*/
#[Path("id", new VUuid(), "Identifier of the group", required: true)]
public function actionRemoveGroup(string $id)
{
$group = $this->groups->findOrThrow($id);
$this->groups->remove($group);
$this->groups->flush();
$this->sendSuccessResponse("OK");
}
public function checkDetail(string $id)
{
$group = $this->groups->findOrThrow($id);
if (!$this->groupAcl->canViewPublicDetail($group)) {
throw new ForbiddenRequestException();
}
}
/**
* Get details of a group
* @GET
*/
#[Path("id", new VUuid(), "Identifier of the group", required: true)]
#[ResponseFormat(GroupFormat::class)]
public function actionDetail(string $id)
{
$group = $this->groups->findOrThrow($id);
$this->sendSuccessResponse($this->groupViewFactory->getGroup($group));
}
public function checkSubgroups(string $id)
{
/** @var Group $group */
$group = $this->groups->findOrThrow($id);
if (!$this->groupAcl->canViewDetail($group)) {
throw new ForbiddenRequestException();
}
}
/**
* Get a list of subgroups of a group
* @GET
* @deprecated Subgroup list is part of group view.
*/
#[Path("id", new VUuid(), "Identifier of the group", required: true)]
public function actionSubgroups(string $id)
{
/** @var Group $group */
$group = $this->groups->findOrThrow($id);
$subgroups = array_values(
array_filter(
$group->getAllSubgroups(),
function (Group $subgroup) {
return $this->groupAcl->canViewPublicDetail($subgroup);
}
)
);
$this->sendSuccessResponse($this->groupViewFactory->getGroups($subgroups));
}
public function checkMembers(string $id)
{
$group = $this->groups->findOrThrow($id);
if (!$this->groupAcl->canViewDetail($group)) {
throw new ForbiddenRequestException();
}
}
/**
* Get a list of members of a group
* @GET
* @deprecated Members are listed in group view.
*/
#[Path("id", new VUuid(), "Identifier of the group", required: true)]
public function actionMembers(string $id)
{
$group = $this->groups->findOrThrow($id);
$this->sendSuccessResponse(
[
"admins" => $this->userViewFactory->getUsers($group->getPrimaryAdmins()->getValues()),
"supervisors" => $this->userViewFactory->getUsers($group->getSupervisors()->getValues()),
]
);
}
public function checkAddMember(string $id, string $userId)
{
$user = $this->users->findOrThrow($userId);
$group = $this->groups->findOrThrow($id);
/** @var IGroupPermissions $userAcl */
$userAcl = $this->aclLoader->loadACLModule(
IGroupPermissions::class,
$this->authorizator,
new Identity($user, null)
);
if (!$this->groupAcl->canAddMember($group, $user) || !$userAcl->canBecomeMember($group)) {
throw new ForbiddenRequestException();
}
}
/**
* Add/update a membership (other than student) for given user
* @POST
*/
#[Post("type", new VString(1), "Identifier of membership type (admin, supervisor, ...)", required: true)]
#[Path("id", new VUuid(), "Identifier of the group", required: true)]
#[Path("userId", new VUuid(), "Identifier of the supervisor", required: true)]
#[ResponseFormat(GroupFormat::class)]
public function actionAddMember(string $id, string $userId)
{
$user = $this->users->findOrThrow($userId);
$group = $this->groups->findOrThrow($id);
$type = $this->getRequest()->getPost("type");
if ($type === GroupMembership::TYPE_STUDENT || !in_array($type, GroupMembership::KNOWN_TYPES)) {
throw new InvalidApiArgumentException('type', "Unknown membership type '$type'");
}
$membership = $group->getMembershipOfUser($user);
if ($membership) {
// update type of existing membership (if it is not a student)
if ($membership->getType() === GroupMembership::TYPE_STUDENT) {
throw new InvalidApiArgumentException(
'userId',
"The user is a student of the group and students cannot be made also members"
);
}
$membership->setType($type);
} else {
// create new membership
$membership = new GroupMembership($group, $user, $type);
$group->addMembership($membership);
}
$this->groupMemberships->persist($membership);
$this->sendSuccessResponse($this->groupViewFactory->getGroup($group));
}
public function checkRemoveMember(string $id, string $userId)
{
$user = $this->users->findOrThrow($userId);
$group = $this->groups->findOrThrow($id);
if (!$this->groupAcl->canRemoveMember($group, $user)) {
throw new ForbiddenRequestException();