-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSisPresenter.php
More file actions
647 lines (558 loc) · 21.2 KB
/
SisPresenter.php
File metadata and controls
647 lines (558 loc) · 21.2 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
<?php
namespace App\V1Module\Presenters;
use App\Helpers\MetaFormats\Attributes\Post;
use App\Helpers\MetaFormats\Attributes\Path;
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\Exceptions\ApiException;
use App\Exceptions\BadRequestException;
use App\Exceptions\ForbiddenRequestException;
use App\Exceptions\InvalidApiArgumentException;
use App\Exceptions\NotFoundException;
use App\Helpers\SisCourseRecord;
use App\Helpers\SisHelper;
use App\Model\Entity\Group;
use App\Model\Entity\LocalizedGroup;
use App\Model\Entity\SisGroupBinding;
use App\Model\Entity\SisValidTerm;
use App\Model\Entity\User;
use App\Model\Repository\ExternalLogins;
use App\Model\Repository\Groups;
use App\Model\Repository\Instances;
use App\Model\Repository\SisGroupBindings;
use App\Model\Repository\SisValidTerms;
use App\Model\View\GroupViewFactory;
use App\Security\ACL\ISisPermissions;
use App\Security\ACL\SisGroupContext;
use App\Security\ACL\SisIdWrapper;
use DateTime;
use Exception;
/**
* @LoggedIn
* @deprecated Use the new SIS extension instead
*/
class SisPresenter extends BasePresenter
{
/**
* @var SisHelper
* @inject
*/
public $sisHelper;
/**
* @var ExternalLogins
* @inject
*/
public $externalLogins;
/**
* @var Groups
* @inject
*/
public $groups;
/**
* @var Instances
* @inject
*/
public $instances;
/**
* @var SisGroupBindings
* @inject
*/
public $sisGroupBindings;
/**
* @var SisValidTerms
* @inject
*/
public $sisValidTerms;
/**
* @var GroupViewFactory
* @inject
*/
public $groupViewFactory;
/**
* @var ISisPermissions
* @inject
*/
public $sisAcl;
/**
* Check SIS status for the current user.
* @deprecated Use the new SIS extension instead
* @GET
* @throws ForbiddenRequestException
*/
public function actionStatus()
{
$login = $this->externalLogins->findByUser($this->getCurrentUser(), "cas-uk");
$now = new DateTime();
$terms = [];
/** @var SisValidTerm $term */
foreach ($this->sisValidTerms->findAll() as $term) {
$month = intval($now->format('w'));
$terms[] = [
'year' => $term->getYear(),
'term' => $term->getTerm(),
'isAdvertised' => $term->isAdvertised($now)
];
}
$this->sendSuccessResponse(
[
"accessible" => $login !== null,
"terms" => $terms
]
);
}
public function checkGetTerms()
{
if (!$this->sisAcl->canViewTerms()) {
throw new ForbiddenRequestException();
}
}
/**
* Get a list of all registered SIS terms
* @deprecated Use the new SIS extension instead
* @GET
*/
public function actionGetTerms()
{
$this->sendSuccessResponse($this->sisValidTerms->findAll());
}
public function checkRegisterTerm()
{
if (!$this->sisAcl->canCreateTerm()) {
throw new ForbiddenRequestException();
}
}
/**
* Register a new term
* @deprecated Use the new SIS extension instead
* @POST
* @throws InvalidApiArgumentException
* @throws ForbiddenRequestException
* @throws BadRequestException
*/
#[Post("year", new VMixed(), nullable: true)]
#[Post("term", new VMixed(), nullable: true)]
public function actionRegisterTerm()
{
$year = intval($this->getRequest()->getPost("year"));
$term = intval($this->getRequest()->getPost("term"));
if ($this->sisValidTerms->isValid($year, $term)) {
$this->sendSuccessResponse("OK");
}
// Throws InvalidApiArgumentException when given term is invalid
$this->sisHelper->getCourses($this->getSisUserIdOrThrow($this->getCurrentUser()), $year, $term);
$termEntity = new SisValidTerm($year, $term);
$this->sisValidTerms->persist($termEntity);
$this->sendSuccessResponse($termEntity);
}
public function checkEditTerm(string $id)
{
$term = $this->sisValidTerms->findOrThrow($id);
if (!$this->sisAcl->canEditTerm($term)) {
throw new ForbiddenRequestException();
}
}
/**
* Set details of a term
* @deprecated Use the new SIS extension instead
* @POST
* @throws InvalidApiArgumentException
* @throws NotFoundException
*/
#[Post("beginning", new VTimestamp())]
#[Post("end", new VTimestamp())]
#[Post("advertiseUntil", new VTimestamp())]
#[Path("id", new VString(), required: true)]
public function actionEditTerm(string $id)
{
$term = $this->sisValidTerms->findOrThrow($id);
$beginning = DateTime::createFromFormat("U", $this->getRequest()->getPost("beginning"));
$end = DateTime::createFromFormat("U", $this->getRequest()->getPost("end"));
$advertiseUntil = null;
if ($this->getRequest()->getPost("advertiseUntil") !== null) {
$advertiseUntil = DateTime::createFromFormat("U", $this->getRequest()->getPost("advertiseUntil"));
}
if ($beginning > $end) {
throw new InvalidApiArgumentException('beginning', "The beginning must precede the end");
}
if ($advertiseUntil !== null && ($advertiseUntil > $end || $advertiseUntil < $beginning)) {
throw new InvalidApiArgumentException(
'advertiseUntil',
"The 'advertiseUntil' timestamp must be within the semester"
);
}
$term->setBeginning($beginning);
$term->setEnd($end);
$term->setAdvertiseUntil($advertiseUntil);
$this->sisValidTerms->persist($term);
$this->sendSuccessResponse($term);
}
public function checkDeleteTerm(string $id)
{
$term = $this->sisValidTerms->findOrThrow($id);
if (!$this->sisAcl->canDeleteTerm($term)) {
throw new ForbiddenRequestException();
}
}
/**
* Delete a term
* @deprecated Use the new SIS extension instead
* @DELETE
* @throws NotFoundException
*/
#[Path("id", new VString(), required: true)]
public function actionDeleteTerm(string $id)
{
$term = $this->sisValidTerms->findOrThrow($id);
$this->sisValidTerms->remove($term);
$this->sendSuccessResponse("OK");
}
public function checkSubscribedGroups($userId, $year, $term)
{
$user = $this->users->findOrThrow($userId);
$sisUserId = $this->getSisUserIdOrThrow($user);
if (!$this->sisAcl->canViewCourses(new SisIdWrapper($sisUserId))) {
throw new ForbiddenRequestException();
}
}
/**
* Get all courses subscirbed by a student and corresponding ReCodEx groups.
* Organizational and archived groups are filtered out from the result.
* Each course holds bound group IDs and group objects are returned in a separate array.
* Whole ancestral closure of groups is returned, so the webapp may properly assemble hiarichial group names.
* @deprecated Use the new SIS extension instead
* @GET
* @throws InvalidApiArgumentException
* @throws BadRequestException
*/
#[Path("userId", new VString(), required: true)]
#[Path("year", new VInt(), required: true)]
#[Path("term", new VInt(), required: true)]
public function actionSubscribedCourses($userId, $year, $term)
{
$user = $this->users->findOrThrow($userId);
$sisUserId = $this->getSisUserIdOrThrow($user);
// we separate groups and courses (courses hold only groupIds), to avoid duplicit groups in the output
$groups = [];
$courses = [];
foreach ($this->sisHelper->getCourses($sisUserId, $year, $term) as $course) {
if (!$course->isOwnerStudent()) {
continue;
}
$bindings = $this->sisGroupBindings->findByCode($course->getCode());
$courseGroupIds = [];
foreach ($bindings as $binding) {
if ($binding->getGroup() !== null && !$binding->getGroup()->isArchived()) {
/** @var Group $group */
$group = $binding->getGroup();
if (
!array_key_exists($group->getId(), $groups)
&& !$group->isOrganizational() && !$group->isArchived()
) {
$groups[$group->getId()] = $group;
$courseGroupIds[] = $group->getId();
}
}
}
$courses[] = [
'course' => $course,
'groups' => $courseGroupIds,
];
}
// and we need to perform ancestral closure to make sure the student can assemlbe complete hiarichal names
$groups = $this->groups->groupsAncestralClosure($groups);
$this->sendSuccessResponse([
'courses' => $courses, // courses info + bound groups (referenced by ids)
'groups' => $this->groupViewFactory->getGroups($groups),
]);
}
public function checkSupervisedCourses($userId, $year, $term)
{
$user = $this->users->findOrThrow($userId);
$sisUserId = $this->getSisUserIdOrThrow($user);
if (!$this->sisAcl->canViewCourses(new SisIdWrapper($sisUserId))) {
throw new ForbiddenRequestException();
}
}
/**
* Get supervised SIS courses and corresponding ReCodEx groups.
* Each course holds bound group IDs and group objects are returned in a separate array.
* Whole ancestral closure of groups is returned, so the webapp may properly assemble hiarichial group names.
* @deprecated Use the new SIS extension instead
* @GET
* @throws InvalidApiArgumentException
* @throws NotFoundException
* @throws BadRequestException
*/
#[Path("userId", new VString(), required: true)]
#[Path("year", new VInt(), required: true)]
#[Path("term", new VInt(), required: true)]
public function actionSupervisedCourses($userId, $year, $term)
{
$user = $this->users->findOrThrow($userId);
$sisUserId = $this->getSisUserIdOrThrow($user);
$groups = [];
$courses = [];
foreach ($this->sisHelper->getCourses($sisUserId, $year, $term) as $course) {
if (!$course->isOwnerSupervisor()) {
continue;
}
$bindings = $this->sisGroupBindings->findByCode($course->getCode());
$courseGroupIds = [];
foreach ($bindings as $binding) {
if ($binding->getGroup() !== null && !$binding->getGroup()->isArchived()) {
/** @var Group $group */
$group = $binding->getGroup();
$groups[$group->getId()] = $group;
$courseGroupIds[] = $group->getId();
}
}
$courses[] = [
'course' => $course,
'groups' => $courseGroupIds,
];
}
// and we need to perform ancestral closure to make sure the student can assemble complete hierarchical names
$groups = $this->groups->groupsAncestralClosure($groups);
$this->sendSuccessResponse([
'courses' => $courses, // courses info + bound groups (referenced by ids)
'groups' => $this->groupViewFactory->getGroups($groups),
]);
}
/**
* @param array $captions List of captions [ lang => caption ].
* @param string $suffix Suffix expected to be appended to captions of all languages.
* @param Group $parentGroup The uniqueness is ensured only amongst the siblings.
* @return bool True if at least one caption is in conflict.
*/
private function areCaptionsDuplicit(array $captions, string $suffix, Group $parentGroup)
{
foreach ($captions as $lang => $caption) {
if (
count(
$this->groups->findByName($lang, $caption . $suffix, $parentGroup->getInstance(), $parentGroup)
) > 0
) {
return true;
}
}
return false;
}
/**
* Make sure new group captions (in all languages) are unique.
* If not, new unique names are created by appending value of a counter.
* @param array $captions List of captions [ lang => caption ].
* @param Group $parentGroup The uniqueness is ensured only amongst the siblings.
*/
private function makeCaptionsUnique(array &$captions, Group $parentGroup)
{
// Trial and error approach to find suitable suffix to make the captions unique (starting with empty suffix).
$counter = 1;
$suffix = '';
while ($this->areCaptionsDuplicit($captions, $suffix, $parentGroup)) {
++$counter;
$suffix = " [$counter]";
}
// Acceptable suffix was found, lets append it...
foreach ($captions as &$caption) {
$caption .= $suffix;
}
}
/**
* Create a new group based on a SIS group
* @deprecated Use the new SIS extension instead
* @POST
* @throws BadRequestException
* @throws ForbiddenRequestException
* @throws InvalidApiArgumentException
* @throws Exception
*/
#[Post("parentGroupId", new VMixed(), nullable: true)]
#[Path("courseId", new VString(), required: true)]
public function actionCreateGroup($courseId)
{
$user = $this->getCurrentUser();
$sisUserId = $this->getSisUserIdOrThrow($user);
$request = $this->getRequest();
$parentGroupId = $request->getPost("parentGroupId");
$parentGroup = $this->groups->findOrThrow($parentGroupId);
if ($parentGroup->isArchived()) {
throw new InvalidApiArgumentException(
'parentGroupId',
"It is not permitted to create subgroups in archived groups"
);
}
$remoteCourse = $this->findRemoteCourseOrThrow($courseId, $sisUserId);
if (!$this->sisAcl->canCreateGroup(new SisGroupContext($parentGroup, $remoteCourse), $remoteCourse)) {
throw new ForbiddenRequestException();
}
$group = new Group($remoteCourse->getCourseId(), $parentGroup->getInstance(), $user, $parentGroup);
$captions = [];
foreach (["en", "cs"] as $language) {
// Assemble new group name from course data....
$schedulingInfo = [];
if ($remoteCourse->getDayOfWeek() !== null) {
$schedulingInfo[] = $timeInfo = $this->dayToString($remoteCourse->getDayOfWeek(), $language);
}
if ($remoteCourse->getTime() !== null) {
$schedulingInfo[] = $remoteCourse->getTime();
}
if ($remoteCourse->isFortnightly()) {
$schedulingInfo[] = $this->oddWeeksToString($remoteCourse->getOddWeeks(), $language);
}
if ($remoteCourse->getRoom() !== null) {
$schedulingInfo[] = $remoteCourse->getRoom();
}
if ($schedulingInfo) {
$captions[$language] = sprintf(
"%s (%s)",
$remoteCourse->getCaption($language),
join(', ', $schedulingInfo)
);
} else {
$captions[$language] = $remoteCourse->getCaption($language);
}
}
$this->makeCaptionsUnique($captions, $parentGroup);
foreach ($captions as $language => $caption) {
$localization = new LocalizedGroup($language, $caption, $remoteCourse->getAnnotation($language));
$group->addLocalizedText($localization);
$this->groups->persist($localization, false);
}
$this->groups->persist($group, false);
$binding = new SisGroupBinding($group, $remoteCourse->getCode());
$this->sisGroupBindings->persist($binding, true);
$this->sendSuccessResponse($this->groupViewFactory->getGroup($group));
}
/**
* Bind an existing local group to a SIS group
* @deprecated Use the new SIS extension instead
* @POST
* @throws ApiException
* @throws ForbiddenRequestException
* @throws BadRequestException
*/
#[Post("groupId", new VMixed(), nullable: true)]
#[Path("courseId", new VString(), required: true)]
public function actionBindGroup($courseId)
{
$user = $this->getCurrentUser();
$sisUserId = $this->getSisUserIdOrThrow($user);
$remoteCourse = $this->findRemoteCourseOrThrow($courseId, $sisUserId);
$group = $this->groups->findOrThrow($this->getRequest()->getPost("groupId"));
if ($group->isArchived()) {
throw new InvalidApiArgumentException(
'groupId',
"It is not permitted to create subgroups in archived groups"
);
}
if (!$this->sisAcl->canBindGroup($group, $remoteCourse)) {
throw new ForbiddenRequestException();
}
if ($this->sisGroupBindings->findByGroupAndCode($group, $remoteCourse->getCode())) {
throw new ApiException("The group is already bound to the course");
}
$binding = new SisGroupBinding($group, $remoteCourse->getCode());
$this->sisGroupBindings->persist($binding);
$this->sendSuccessResponse($this->groupViewFactory->getGroup($group));
}
/**
* Delete a binding between a local group and a SIS group
* @deprecated Use the new SIS extension instead
* @DELETE
* @throws BadRequestException
* @throws ForbiddenRequestException
* @throws InvalidApiArgumentException
* @throws NotFoundException
*/
#[Path("courseId", new VString(), "an identifier of a SIS course", required: true)]
#[Path("groupId", new VString(), "an identifier of a local group", required: true)]
public function actionUnbindGroup($courseId, $groupId)
{
$user = $this->getCurrentUser();
$sisUserId = $this->getSisUserIdOrThrow($user);
$remoteCourse = $this->findRemoteCourseOrThrow($courseId, $sisUserId);
$group = $this->groups->findOrThrow($groupId);
if (!$this->sisAcl->canUnbindGroup($group, $remoteCourse)) {
throw new ForbiddenRequestException();
}
$groupBinding = $this->sisGroupBindings->findByGroupAndCode($group, $remoteCourse->getCode());
if (!$groupBinding) {
throw new NotFoundException();
}
$this->sisGroupBindings->remove($groupBinding);
$this->sendSuccessResponse("OK");
}
/**
* Find groups that can be chosen as parents of a group created from given SIS group by current user
* @deprecated Use the new SIS extension instead
* @GET
* @throws ApiException
* @throws ForbiddenRequestException
* @throws BadRequestException
*/
#[Path("courseId", new VString(), required: true)]
public function actionPossibleParents($courseId)
{
$sisUserId = $this->getSisUserIdOrThrow($this->getCurrentUser());
$remoteCourse = $this->findRemoteCourseOrThrow($courseId, $sisUserId);
$groups = array_values(
array_filter(
$this->groups->findAll(),
function (Group $group) use ($remoteCourse) {
return $this->sisAcl->canCreateGroup(
new SisGroupContext($group, $remoteCourse),
$remoteCourse
) && !$group->isArchived();
}
)
);
$this->sendSuccessResponse($this->groupViewFactory->getGroups($groups));
}
/**
* @throws BadRequestException
*/
protected function getSisUserIdOrThrow(User $user)
{
$login = $this->externalLogins->findByUser($user, "cas-uk");
if ($login === null) {
throw new BadRequestException(sprintf("User %s is not bound to a CAS UK account", $user->getId()));
}
return $login->getExternalId();
}
/**
* @param string $remoteGroupId
* @param string $sisUserId
* @return SisCourseRecord|mixed
* @throws BadRequestException
* @throws InvalidApiArgumentException
*/
private function findRemoteCourseOrThrow($remoteGroupId, $sisUserId)
{
foreach ($this->sisValidTerms->findAll() as $term) {
foreach ($this->sisHelper->getCourses($sisUserId, $term->getYear(), $term->getTerm()) as $course) {
if ($course->getCode() === $remoteGroupId) {
return $course;
}
}
}
throw new BadRequestException(sprintf("Sis course %s was not found", $remoteGroupId));
}
private function dayToString($day, $language)
{
static $dayLabels = [
'en' => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
'cs' => ['Po', 'Út', 'St', 'Čt', 'Pá', 'So', 'Ne']
];
return $dayLabels[$language][$day];
}
private function oddWeeksToString($oddWeeks, $language)
{
static $labels = [
'en' => ['Even weeks', 'Odd weeks'],
'cs' => ['Sudé týdny', 'Liché týdny']
];
return $labels[$language][$oddWeeks];
}
}