-
-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathApiController.php
More file actions
730 lines (622 loc) 路 32.9 KB
/
Copy pathApiController.php
File metadata and controls
730 lines (622 loc) 路 32.9 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
<?php
namespace App\Controller\Api;
use App\Entity\Calendar;
use App\Entity\CalendarInstance;
use App\Entity\CalendarSubscription;
use App\Entity\Principal;
use App\Entity\User;
use App\Services\Utils;
use Doctrine\Persistence\ManagerRegistry;
use Sabre\DAV\Sharing\Plugin as SharingPlugin;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
#[Route('/api/v1', name: 'api_v1_')]
class ApiController extends AbstractController
{
/**
* Validates the provided username.
*
* @param string $username The username to validate
*
* @return bool True if the username is valid, false otherwise
*/
private function validateUsername(string $username): bool
{
return Utils::isValidUsername($username);
}
/**
* Gets the current timestamp in ISO 8601 format.
*
* @return string The current timestamp
*/
private function getTimestamp(): string
{
return date('c');
}
/**
* Resolves a User entity from a userId, or returns a JSON error response.
*
* @return User|null The User entity, or null if not found
*/
private function resolveUser(ManagerRegistry $doctrine, int $userId): ?User
{
return $doctrine->getRepository(User::class)->findOneById($userId);
}
/**
* Resolves a calendar instance that belongs to the principal *as an owner*
* (a calendar merely shared with the principal does not qualify).
*/
private function resolveOwnerInstance(ManagerRegistry $doctrine, int $calendarInstanceId, string $principalUri): ?CalendarInstance
{
$instance = $doctrine->getRepository(CalendarInstance::class)->findOneForPrincipal($calendarInstanceId, $principalUri);
return $instance && !$instance->isShared() ? $instance : null;
}
/**
* Health check endpoint.
*
* @param Request $request The HTTP GET request
*
* @return JsonResponse A JSON response indicating the health status
*/
#[Route('/health', name: 'health', methods: ['GET'])]
public function healthCheck(Request $request): JsonResponse
{
return $this->json(['status' => 'OK', 'timestamp' => $this->getTimestamp()], 200);
}
/**
* Retrieves a list of users (with their user_id, principal_id, uri, username, and displayname).
*
* @param Request $request The HTTP GET request
*
* @return JsonResponse A JSON response containing the list of users
*/
#[Route('/users', name: 'users', methods: ['GET'])]
public function getUsers(Request $request, ManagerRegistry $doctrine): JsonResponse
{
$results = $doctrine->getRepository(Principal::class)->findAllMainPrincipalsWithUserIds();
$users = [];
foreach ($results as $result) {
$principal = $result[0];
$users[] = [
'user_id' => $result['userId'],
'principal_id' => $principal->getId(),
'uri' => $principal->getUri(),
'username' => $principal->getUsername(),
];
}
$response = [
'status' => 'success',
'data' => $users,
'timestamp' => $this->getTimestamp(),
];
return $this->json($response, 200);
}
/**
* Retrieves details of a specific user (user_id, principal_id, uri, username, displayname, email).
*
* @param Request $request The HTTP GET request
* @param int $userId The ID of the user whose details are to be retrieved
*
* @return JsonResponse A JSON response containing the user details
*/
#[Route('/users/{userId}', name: 'user_detail', methods: ['GET'], requirements: ['userId' => '\d+'])]
public function getUserDetails(Request $request, ManagerRegistry $doctrine, int $userId): JsonResponse
{
$user = $this->resolveUser($doctrine, $userId);
if (!$user) {
return $this->json(['status' => 'error', 'message' => 'User Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$principal = $doctrine->getRepository(Principal::class)->findOneByUri($user->getPrincipalUri());
if (!$principal) {
return $this->json(['status' => 'error', 'message' => 'Principal Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$data = [
'user_id' => $user->getId(),
'principal_id' => $principal->getId(),
'uri' => $principal->getUri(),
'username' => $principal->getUsername(),
'displayname' => $principal->getDisplayName(),
'email' => $principal->getEmail(),
];
$response = [
'status' => 'success',
'data' => $data,
'timestamp' => $this->getTimestamp(),
];
return $this->json($response, 200);
}
/**
* Retrieves a list of calendars for a specific user, including user calendars, shared calendars, and subscriptions.
*
* @param Request $request The HTTP GET request
* @param int $userId The ID of the user whose calendars are to be retrieved
*
* @return JsonResponse A JSON response containing the list of calendars for the specified user
*/
#[Route('/calendars/{userId}', name: 'calendars', methods: ['GET'], requirements: ['userId' => '\d+'])]
public function getUserCalendars(Request $request, int $userId, ManagerRegistry $doctrine): JsonResponse
{
$user = $this->resolveUser($doctrine, $userId);
if (!$user) {
return $this->json(['status' => 'error', 'message' => 'User Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$principalUri = $user->getPrincipalUri();
if (!$doctrine->getRepository(Principal::class)->findOneByUri($principalUri)) {
return $this->json(['status' => 'error', 'message' => 'Principal Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$allCalendars = $doctrine->getRepository(CalendarInstance::class)->findByPrincipalUri($principalUri);
$allSubscriptions = $doctrine->getRepository(CalendarSubscription::class)->findByPrincipalUri($principalUri);
$calendars = [];
$sharedCalendars = [];
foreach ($allCalendars as $calendar) {
$objectCounts = $doctrine->getRepository(CalendarInstance::class)->getObjectCountsByComponentType($calendar->getCalendar()->getId());
$eventsCount = $calendar->getCalendar()->isComponentEnabled(Calendar::COMPONENT_EVENTS) ? $objectCounts['events'] : null;
$notesCount = $calendar->getCalendar()->isComponentEnabled(Calendar::COMPONENT_NOTES) ? $objectCounts['notes'] : null;
$tasksCount = $calendar->getCalendar()->isComponentEnabled(Calendar::COMPONENT_TODOS) ? $objectCounts['tasks'] : null;
$calendarData = [
'id' => $calendar->getId(),
'uri' => $calendar->getUri(),
'displayname' => $calendar->getDisplayName(),
'events' => $eventsCount,
'notes' => $notesCount,
'tasks' => $tasksCount,
];
if (!$calendar->isShared()) {
$calendars[] = $calendarData;
} else {
$sharedCalendars[] = $calendarData;
}
}
$subscriptions = [];
foreach ($allSubscriptions as $subscription) {
// A subscription is a remote feed: it has no local calendar, hence no object counts
$subscriptions[] = [
'id' => $subscription->getId(),
'uri' => $subscription->getUri(),
'displayname' => $subscription->getDisplayName(),
'events' => null,
'notes' => null,
'tasks' => null,
];
}
$response = [
'status' => 'success',
'data' => [
'user_calendars' => $calendars,
'shared_calendars' => $sharedCalendars,
'subscriptions' => $subscriptions,
],
'timestamp' => $this->getTimestamp(),
];
return $this->json($response, 200);
}
/**
* Retrieves details of a specific calendar for a specific user (id, uri, displayname, description, number of events, notes, and tasks).
*
* @param Request $request The HTTP GET request
* @param int $userId The ID of the user whose calendar details are to be retrieved
* @param int $calendar_id The ID of the calendar whose details are to be retrieved
*
* @return JsonResponse A JSON response containing the calendar details
*/
#[Route('/calendars/{userId}/{calendar_id}', name: 'calendar_details', methods: ['GET'], requirements: ['calendar_id' => '\d+', 'userId' => '\d+'])]
public function getUserCalendarDetails(Request $request, int $userId, int $calendar_id, ManagerRegistry $doctrine): JsonResponse
{
$user = $this->resolveUser($doctrine, $userId);
if (!$user) {
return $this->json(['status' => 'error', 'message' => 'User Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$principalUri = $user->getPrincipalUri();
if (!$doctrine->getRepository(Principal::class)->findOneByUri($principalUri)) {
return $this->json(['status' => 'error', 'message' => 'Principal Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$allCalendars = $doctrine->getRepository(CalendarInstance::class)->findByPrincipalUri($principalUri);
$calendar_details = [];
foreach ($allCalendars as $calendar) {
if (!$calendar->isShared() && $calendar->getId() === $calendar_id) {
$objectCounts = $doctrine->getRepository(CalendarInstance::class)->getObjectCountsByComponentType($calendar->getCalendar()->getId());
$calendar_details = [
'id' => $calendar->getId(),
'uri' => $calendar->getUri(),
'displayname' => $calendar->getDisplayName(),
'description' => $calendar->getDescription(),
'events' => [
'enabled' => $calendar->getCalendar()->isComponentEnabled(Calendar::COMPONENT_EVENTS),
'count' => $objectCounts['events'],
],
'notes' => [
'enabled' => $calendar->getCalendar()->isComponentEnabled(Calendar::COMPONENT_NOTES),
'count' => $objectCounts['notes'],
],
'tasks' => [
'enabled' => $calendar->getCalendar()->isComponentEnabled(Calendar::COMPONENT_TODOS),
'count' => $objectCounts['tasks'],
],
];
}
}
$response = [
'status' => 'success',
'data' => $calendar_details,
'timestamp' => $this->getTimestamp(),
];
return $this->json($response, 200);
}
/**
* Creates a new calendar for a specific user.
*
* @param Request $request The HTTP POST request
* @param int $userId The ID of the user for whom the calendar is to be created
*
* @return JsonResponse A JSON response indicating the success or failure of the operation
*/
#[Route('/calendars/{userId}/create', name: 'calendar_create', methods: ['POST'], requirements: ['userId' => '\d+'])]
public function createNewUserCalendar(Request $request, int $userId, ManagerRegistry $doctrine): JsonResponse
{
$user = $this->resolveUser($doctrine, $userId);
if (!$user) {
return $this->json(['status' => 'error', 'message' => 'User Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$principalUri = $user->getPrincipalUri();
if (!$doctrine->getRepository(Principal::class)->findOneByUri($principalUri)) {
return $this->json(['status' => 'error', 'message' => 'Principal Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
// Parse JSON body
$data = json_decode($request->getContent(), true);
if (JSON_ERROR_NONE !== json_last_error()) {
return $this->json(['status' => 'error', 'message' => 'Invalid JSON', 'timestamp' => $this->getTimestamp()], 400);
}
$calendarName = $data['name'] ?? null;
if (empty($calendarName) || 1 !== preg_match('/^[a-zA-Z0-9 ._-]{1,64}$/', $calendarName)) {
return $this->json(['status' => 'error', 'message' => 'Invalid Calendar Name', 'timestamp' => $this->getTimestamp()], 400);
}
$calendarURI = $data['uri'] ?? null;
if (empty($calendarURI) || 1 !== preg_match('/^[a-z0-9_-]{1,128}$/', $calendarURI)) {
return $this->json(['status' => 'error', 'message' => 'Invalid Calendar URI', 'timestamp' => $this->getTimestamp()], 400);
}
$uriCheck = $doctrine->getRepository(CalendarInstance::class)->findOneBy([
'principalUri' => $principalUri,
'uri' => $calendarURI,
]);
if ($uriCheck) {
return $this->json(['status' => 'error', 'message' => 'Calendar URI Already Exists', 'timestamp' => $this->getTimestamp()], 400);
}
$calendarDescription = $data['description'] ?? '';
if (!empty($calendarDescription) && 1 !== preg_match('/^[a-zA-Z0-9 ._-]{1,256}$/', $calendarDescription)) {
return $this->json(['status' => 'error', 'message' => 'Invalid Calendar Description', 'timestamp' => $this->getTimestamp()], 400);
}
$entityManager = $doctrine->getManager();
$calendarInstance = new CalendarInstance();
$calendar = new Calendar();
$calendarInstance->setCalendar($calendar);
$calendarComponents = [];
$eventsSupport = $data['events_support'] ?? true;
if (true === $eventsSupport || 'true' === $eventsSupport) {
$calendarComponents[] = Calendar::COMPONENT_EVENTS;
}
$notesSupport = $data['notes_support'] ?? false;
if (true === $notesSupport || 'true' === $notesSupport) {
$calendarComponents[] = Calendar::COMPONENT_NOTES;
}
$tasksSupport = $data['tasks_support'] ?? false;
if (true === $tasksSupport || 'true' === $tasksSupport) {
$calendarComponents[] = Calendar::COMPONENT_TODOS;
}
// Validate that at least one component is selected
if (empty($calendarComponents)) {
return $this->json(['status' => 'error', 'message' => 'At least one calendar component must be enabled (events, notes, or tasks)', 'timestamp' => $this->getTimestamp()], 400);
}
$calendar->setComponents(implode(',', $calendarComponents));
try {
$calendarInstance
->setCalendar($calendar)
->setAccess(SharingPlugin::ACCESS_SHAREDOWNER)
->setDescription($calendarDescription)
->setDisplayName($calendarName)
->setUri($calendarURI)
->setPrincipalUri($principalUri);
$entityManager->persist($calendarInstance);
$entityManager->flush();
} catch (\Exception $e) {
return $this->json(['status' => 'error', 'message' => 'Failed to Create Calendar', 'timestamp' => $this->getTimestamp()], 500);
}
$response = [
'status' => 'success',
'data' => [
'calendar_id' => $calendarInstance->getId(),
'calendar_uri' => $calendarInstance->getUri(),
],
'timestamp' => $this->getTimestamp(),
];
return $this->json($response, 200);
}
/**
* Edits an existing calendar for a specific user.
*
* @param Request $request The HTTP POST request
* @param int $userId The ID of the user whose calendar is to be edited
* @param int $calendar_id The ID of the calendar to be edited
*
* @return JsonResponse A JSON response indicating the success or failure of the operation
*/
#[Route('/calendars/{userId}/{calendar_id}', name: 'calendar_edit', methods: ['PUT', 'PATCH'], requirements: ['calendar_id' => '\d+', 'userId' => '\d+'])]
public function editUserCalendar(Request $request, int $userId, int $calendar_id, ManagerRegistry $doctrine): JsonResponse
{
$user = $this->resolveUser($doctrine, $userId);
if (!$user) {
return $this->json(['status' => 'error', 'message' => 'User Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$principalUri = $user->getPrincipalUri();
if (!$doctrine->getRepository(Principal::class)->findOneByUri($principalUri)) {
return $this->json(['status' => 'error', 'message' => 'Principal Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
// Only the owner of a calendar can edit it (a sharee's instance is not theirs to change)
$calendarInstance = $this->resolveOwnerInstance($doctrine, $calendar_id, $principalUri);
if (!$calendarInstance) {
return $this->json(['status' => 'error', 'message' => 'Invalid Calendar ID', 'timestamp' => $this->getTimestamp()], 400);
}
// Parse JSON body
$data = json_decode($request->getContent(), true);
if (JSON_ERROR_NONE !== json_last_error()) {
return $this->json(['status' => 'error', 'message' => 'Invalid JSON', 'timestamp' => $this->getTimestamp()], 400);
}
$calendarName = $data['name'] ?? null;
if (empty($calendarName) || 1 !== preg_match('/^[a-zA-Z0-9 ._-]{1,64}$/', $calendarName)) {
return $this->json(['status' => 'error', 'message' => 'Invalid Calendar Name', 'timestamp' => $this->getTimestamp()], 400);
}
$calendarDescription = $data['description'] ?? '';
if (!empty($calendarDescription) && 1 !== preg_match('/^[a-zA-Z0-9 ._-]{1,256}$/', $calendarDescription)) {
return $this->json(['status' => 'error', 'message' => 'Invalid Calendar Description', 'timestamp' => $this->getTimestamp()], 400);
}
$entityManager = $doctrine->getManager();
$calendarInstance->setDisplayName($calendarName);
$calendarInstance->setDescription($calendarDescription);
$calendarComponents = [];
$eventsSupport = $data['events_support'] ?? true;
if (true === $eventsSupport || 'true' === $eventsSupport) {
$calendarComponents[] = Calendar::COMPONENT_EVENTS;
}
$notesSupport = $data['notes_support'] ?? false;
if (true === $notesSupport || 'true' === $notesSupport) {
$calendarComponents[] = Calendar::COMPONENT_NOTES;
}
$tasksSupport = $data['tasks_support'] ?? false;
if (true === $tasksSupport || 'true' === $tasksSupport) {
$calendarComponents[] = Calendar::COMPONENT_TODOS;
}
// Validate that at least one component is selected
if (empty($calendarComponents)) {
return $this->json(['status' => 'error', 'message' => 'At least one calendar component must be enabled (events, notes, or tasks)', 'timestamp' => $this->getTimestamp()], 400);
}
$calendarInstance->getCalendar()->setComponents(implode(',', $calendarComponents));
try {
$entityManager->persist($calendarInstance);
$entityManager->flush();
} catch (\Exception $e) {
return $this->json(['status' => 'error', 'message' => 'Failed to Edit Calendar', 'timestamp' => $this->getTimestamp()], 500);
}
return $this->json(['status' => 'success', 'timestamp' => $this->getTimestamp()], 200);
}
/**
* Deletes a specific calendar for a specific user.
*
* @param Request $request The HTTP POST request
* @param int $userId The ID of the user whose calendar is to be deleted
* @param int $calendar_id The ID of the calendar to be deleted
*
* @return JsonResponse A JSON response indicating the success or failure of the operation
*/
#[Route('/calendars/{userId}/{calendar_id}', name: 'calendar_delete', methods: ['DELETE'], requirements: ['calendar_id' => '\d+', 'userId' => '\d+'])]
public function deleteUserCalendar(Request $request, int $userId, int $calendar_id, ManagerRegistry $doctrine): JsonResponse
{
$user = $this->resolveUser($doctrine, $userId);
if (!$user) {
return $this->json(['status' => 'error', 'message' => 'User Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$principalUri = $user->getPrincipalUri();
if (!$doctrine->getRepository(Principal::class)->findOneByUri($principalUri)) {
return $this->json(['status' => 'error', 'message' => 'Principal Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$instance = $doctrine->getRepository(CalendarInstance::class)->findOneForPrincipal($calendar_id, $principalUri);
if (!$instance) {
return $this->json(['status' => 'error', 'message' => 'Invalid Instance Not Found', 'timestamp' => $this->getTimestamp()], 400);
}
try {
$entityManager = $doctrine->getManager();
// A calendar shared *with* this user is not theirs to delete: only drop their access to it
if ($instance->isShared()) {
$entityManager->remove($instance);
$entityManager->flush();
return $this->json(['status' => 'success', 'timestamp' => $this->getTimestamp()], 200);
}
// Scheduling objects attached to the calendar objects of this calendar only
$schedulingObjects = $doctrine->getRepository(CalendarInstance::class)->findAllSchedulingObjectsForCalendar($instance->getId(), $principalUri);
foreach ($schedulingObjects ?? [] as $object) {
$entityManager->remove($object);
}
foreach ($instance->getCalendar()->getObjects() ?? [] as $object) {
$entityManager->remove($object);
}
foreach ($instance->getCalendar()->getChanges() ?? [] as $change) {
$entityManager->remove($change);
}
// Remove the original calendar instance
$entityManager->remove($instance);
// Remove shared instances of the calendar
$sharedInstances = $doctrine->getRepository(CalendarInstance::class)->findSharedInstancesOfInstance($instance->getCalendar()->getId(), false);
foreach ($sharedInstances as $sharedInstance) {
$entityManager->remove($sharedInstance);
}
$entityManager->remove($instance->getCalendar());
$entityManager->flush();
} catch (\Exception $e) {
return $this->json(['status' => 'error', 'message' => 'Failed to Delete Calendar', 'timestamp' => $this->getTimestamp()], 500);
}
return $this->json(['status' => 'success', 'timestamp' => $this->getTimestamp()], 200);
}
/**
* Retrieves a list of shares for a specific calendar of a specific user (id, username, displayname, email, write_access).
*
* @param Request $request The HTTP GET request
* @param int $userId The ID of the user whose calendar shares are to be retrieved
* @param int $calendar_id The ID of the calendar whose shares are to be retrieved
*
* @return JsonResponse A JSON response containing the list of calendar shares
*/
#[Route('/calendars/{userId}/shares/{calendar_id}', name: 'calendars_shares', methods: ['GET'], requirements: ['calendar_id' => '\d+', 'userId' => '\d+'])]
public function getUserCalendarsShares(Request $request, int $userId, int $calendar_id, ManagerRegistry $doctrine): JsonResponse
{
$user = $this->resolveUser($doctrine, $userId);
if (!$user) {
return $this->json(['status' => 'error', 'message' => 'User Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$principalUri = $user->getPrincipalUri();
if (!$doctrine->getRepository(Principal::class)->findOneByUri($principalUri)) {
return $this->json(['status' => 'error', 'message' => 'Principal Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$ownerInstance = $this->resolveOwnerInstance($doctrine, $calendar_id, $principalUri);
if (!$ownerInstance) {
return $this->json(['status' => 'error', 'message' => 'Invalid Calendar ID/Username', 'timestamp' => $this->getTimestamp()], 400);
}
// This fixes the issue where shared calendars are not being retrieved properly
$instances = $doctrine->getRepository(CalendarInstance::class)->findSharedInstancesOfInstance($ownerInstance->getCalendar()->getId(), true);
$calendars = [];
foreach ($instances as $instance) {
$principalId = $doctrine->getRepository(Principal::class)->findOneByUri($instance[0]['principalUri']);
$instanceUsername = mb_substr($instance[0]['principalUri'], strlen(Principal::PREFIX));
// A sharee principal may have no user row (deleted user, external principal)
$instanceUserId = $doctrine->getRepository(User::class)->findOneByUsername($instanceUsername)?->getId();
$calendars[] = [
'username' => $instanceUsername,
'user_id' => $instanceUserId,
'principal_id' => $principalId?->getId() ?? null,
'displayname' => $instance['displayName'],
'email' => $instance['email'],
'write_access' => SharingPlugin::ACCESS_READWRITE === $instance[0]['access'],
];
}
$response = [
'status' => 'success',
'data' => $calendars,
'timestamp' => $this->getTimestamp(),
];
return $this->json($response, 200);
}
/**
* Sets or updates a share for a specific calendar of a specific user.
*
* @param Request $request The HTTP POST request
* @param int $userId The ID of the user whose calendar share is to be set or updated
* @param string $calendar_id The ID of the calendar whose share is to be set or updated
*
* @return JsonResponse A JSON response indicating the success or failure of the operation
*/
#[Route('/calendars/{userId}/share/{calendar_id}/add', name: 'calendars_share', methods: ['POST'], requirements: ['calendar_id' => '\d+', 'userId' => '\d+'])]
public function setUserCalendarsShare(Request $request, int $userId, int $calendar_id, ManagerRegistry $doctrine): JsonResponse
{
$user = $this->resolveUser($doctrine, $userId);
if (!$user) {
return $this->json(['status' => 'error', 'message' => 'User Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$principalUri = $user->getPrincipalUri();
if (!$doctrine->getRepository(Principal::class)->findOneByUri($principalUri)) {
return $this->json(['status' => 'error', 'message' => 'Principal Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$instance = $this->resolveOwnerInstance($doctrine, $calendar_id, $principalUri);
if (!$instance) {
return $this->json(['status' => 'error', 'message' => 'Invalid Calendar ID and User ID', 'timestamp' => $this->getTimestamp()], 400);
}
// Parse JSON body
$data = json_decode($request->getContent(), true);
if (JSON_ERROR_NONE !== json_last_error()) {
return $this->json(['status' => 'error', 'message' => 'Invalid JSON', 'timestamp' => $this->getTimestamp()], 400);
}
$shareeUsername = $data['username'] ?? null;
$writeAccess = $data['write_access'] ?? null;
if (!$this->validateUsername($shareeUsername) || !in_array($writeAccess, [true, false, 'true', 'false'], true)) {
return $this->json(['status' => 'error', 'message' => 'Invalid Sharee ID/Write Access Value', 'timestamp' => $this->getTimestamp()], 400);
}
$newShareeToAdd = $doctrine->getRepository(Principal::class)->findOneByUri(Principal::PREFIX.$shareeUsername);
if (!$newShareeToAdd) {
return $this->json(['status' => 'error', 'message' => 'Calendar Instance/User Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
if ($newShareeToAdd->getUri() === $principalUri) {
return $this->json(['status' => 'error', 'message' => 'A Calendar Cannot Be Shared With Its Owner', 'timestamp' => $this->getTimestamp()], 400);
}
$existingSharedInstance = $doctrine->getRepository(CalendarInstance::class)->findSharedInstanceOfInstanceFor($instance->getCalendar()->getId(), $newShareeToAdd->getUri());
$accessLevel = (true === $writeAccess || 'true' === $writeAccess ? SharingPlugin::ACCESS_READWRITE : SharingPlugin::ACCESS_READ);
$entityManager = $doctrine->getManager();
try {
if ($existingSharedInstance) {
$existingSharedInstance->setAccess($accessLevel);
} else {
$sharedInstance = new CalendarInstance();
$sharedInstance->setTransparent(1)
->setCalendar($instance->getCalendar())
->setShareHref('mailto:'.$newShareeToAdd->getEmail())
->setDescription($instance->getDescription())
->setDisplayName($instance->getDisplayName())
->setCalendarColor($instance->getCalendarColor())
->setUri(\Sabre\DAV\UUIDUtil::getUUID())
->setPrincipalUri($newShareeToAdd->getUri())
->setAccess($accessLevel);
$entityManager->persist($sharedInstance);
}
$entityManager->flush();
} catch (\Exception $e) {
return $this->json(['status' => 'error', 'message' => 'Failed to Edit Calendar', 'timestamp' => $this->getTimestamp()], 500);
}
return $this->json(['status' => 'success', 'timestamp' => $this->getTimestamp()], 200);
}
/**
* Removes a share for a specific calendar of a specific user.
*
* @param Request $request The HTTP POST request
* @param int $userId The ID of the user whose calendar share is to be removed
* @param string $calendar_id The ID of the calendar whose share is to be removed
*
* @return JsonResponse A JSON response indicating the success or failure of the operation
*/
#[Route('/calendars/{userId}/share/{calendar_id}/remove', name: 'calendars_share_remove', methods: ['POST'], requirements: ['calendar_id' => '\d+', 'userId' => '\d+'])]
public function removeUserCalendarsShare(Request $request, int $userId, int $calendar_id, ManagerRegistry $doctrine): JsonResponse
{
$user = $this->resolveUser($doctrine, $userId);
if (!$user) {
return $this->json(['status' => 'error', 'message' => 'User Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$principalUri = $user->getPrincipalUri();
if (!$doctrine->getRepository(Principal::class)->findOneByUri($principalUri)) {
return $this->json(['status' => 'error', 'message' => 'Principal Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
$instance = $this->resolveOwnerInstance($doctrine, $calendar_id, $principalUri);
if (!$instance) {
return $this->json(['status' => 'error', 'message' => 'Invalid Calendar ID', 'timestamp' => $this->getTimestamp()], 400);
}
// Parse JSON body
$data = json_decode($request->getContent(), true);
if (JSON_ERROR_NONE !== json_last_error()) {
return $this->json(['status' => 'error', 'message' => 'Invalid JSON', 'timestamp' => $this->getTimestamp()], 400);
}
$shareeUsername = $data['username'] ?? null;
if (!$this->validateUsername($shareeUsername)) {
return $this->json(['status' => 'error', 'message' => 'Invalid Username', 'timestamp' => $this->getTimestamp()], 400);
}
$shareeToRemove = $doctrine->getRepository(Principal::class)->findOneByUri(Principal::PREFIX.$shareeUsername);
if (!$shareeToRemove) {
return $this->json(['status' => 'error', 'message' => 'Calendar Instance/User Not Found', 'timestamp' => $this->getTimestamp()], 404);
}
try {
$existingSharedInstance = $doctrine->getRepository(CalendarInstance::class)->findSharedInstanceOfInstanceFor($instance->getCalendar()->getId(), $shareeToRemove->getUri());
if ($existingSharedInstance) {
$entityManager = $doctrine->getManager();
$entityManager->remove($existingSharedInstance);
$entityManager->flush();
}
} catch (\Exception $e) {
return $this->json(['status' => 'error', 'message' => 'Failed to Remove Share', 'timestamp' => $this->getTimestamp()], 500);
}
return $this->json(['status' => 'success', 'timestamp' => $this->getTimestamp()], 200);
}
}