-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathPollService.php
More file actions
486 lines (414 loc) · 13.4 KB
/
Copy pathPollService.php
File metadata and controls
486 lines (414 loc) · 13.4 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
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2017 Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Polls\Service;
use OCA\Polls\Db\Poll;
use OCA\Polls\Db\PollMapper;
use OCA\Polls\Db\UserMapper;
use OCA\Polls\Db\VoteMapper;
use OCA\Polls\Event\PollArchivedEvent;
use OCA\Polls\Event\PollCloseEvent;
use OCA\Polls\Event\PollCreatedEvent;
use OCA\Polls\Event\PollDeletedEvent;
use OCA\Polls\Event\PollOwnerChangeEvent;
use OCA\Polls\Event\PollReopenEvent;
use OCA\Polls\Event\PollRestoredEvent;
use OCA\Polls\Event\PollUpdatedEvent;
use OCA\Polls\Exceptions\AlreadyDeletedException;
use OCA\Polls\Exceptions\EmptyTitleException;
use OCA\Polls\Exceptions\ForbiddenException;
use OCA\Polls\Exceptions\InvalidAccessException;
use OCA\Polls\Exceptions\InvalidPollTypeException;
use OCA\Polls\Exceptions\InvalidShowResultsException;
use OCA\Polls\Exceptions\InvalidUsernameException;
use OCA\Polls\Exceptions\NotFoundException;
use OCA\Polls\Exceptions\UserNotFoundException;
use OCA\Polls\Model\Settings\AppSettings;
use OCA\Polls\Model\UserBase;
use OCA\Polls\UserSession;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Search\ISearchQuery;
class PollService {
/** @psalm-suppress PossiblyUnusedMethod */
public function __construct(
private AppSettings $appSettings,
private IEventDispatcher $eventDispatcher,
private Poll $poll,
private PollMapper $pollMapper,
private UserMapper $userMapper,
private UserSession $userSession,
private VoteMapper $voteMapper,
) {
}
/**
* Get list of polls including Threshold for "relevant polls"
*/
public function list(): array {
$pollList = $this->pollMapper->findForMe($this->userSession->getCurrentUserId());
if ($this->userSession->getCurrentUser()->getIsAdmin()) {
return $pollList;
}
return array_values(array_filter($pollList, function (Poll $poll): bool {
return $poll->getIsAllowed(Poll::PERMISSION_POLL_VIEW);
}));
}
/**
* Get list of polls
*/
public function search(ISearchQuery $query): array {
$pollList = [];
try {
$polls = $this->pollMapper->search($query);
foreach ($polls as $poll) {
try {
$poll->request(Poll::PERMISSION_POLL_VIEW);
$pollList[] = $poll;
} catch (ForbiddenException $e) {
continue;
}
}
} catch (DoesNotExistException $e) {
// silent catch
}
return $pollList;
}
/**
* Get list of polls
* @return Poll[]
*/
public function listForAdmin(): array {
$pollList = [];
if ($this->userSession->getCurrentUser()->getIsAdmin()) {
try {
$pollList = $this->pollMapper->findForAdmin($this->userSession->getCurrentUserId());
} catch (DoesNotExistException $e) {
// silent catch
}
}
return $pollList;
}
/**
* @return Poll[]
* @psalm-return array<Poll>
*/
public function transferPolls(string $sourceUserId, string $targetUserId): array {
try {
$targetUser = $this->userMapper->getUserFromUserBase($targetUserId);
} catch (UserNotFoundException $e) {
throw new InvalidUsernameException('The user id "' . $targetUserId . '" for the target user is not valid.');
}
$pollsToTransfer = $this->pollMapper->listByOwner($sourceUserId);
foreach ($pollsToTransfer as &$poll) {
$poll = $this->transferPoll($poll, $targetUser);
}
return $pollsToTransfer;
}
/**
* Update poll configuration
* @return Poll
*/
public function takeover(int $pollId, ?UserBase $targetUser = null): Poll {
if ($targetUser === null) {
$targetUser = $this->userSession->getCurrentUser();
}
return $this->transferPoll($pollId, $targetUser);
}
/**
* Transfer ownership of a poll
* @param int|Poll $poll poll or pollId of poll to transfer ownership
* @param string|UserBase $targetUser User to transfer polls to. If null the current user will be used
*/
public function transferPoll(int|Poll $poll, string|UserBase $targetUser): Poll {
if (!($poll instanceof Poll)) {
$poll = $this->pollMapper->find($poll);
}
$poll->request(Poll::PERMISSION_POLL_CHANGE_OWNER);
if (!($targetUser instanceof UserBase)) {
$userId = $targetUser;
try {
$targetUser = $this->userMapper->getUserFromUserBase($userId);
} catch (UserNotFoundException $e) {
// to keep psalm quiet
throw new InvalidUsernameException('The user id "' . $userId . '" for the target user is not valid.');
}
}
$oldOwner = $poll->getOwner();
$poll->setOwner($targetUser->getId());
$poll = $this->pollMapper->update($poll);
$this->eventDispatcher->dispatchTyped(new PollOwnerChangeEvent($poll, $oldOwner, $poll->getOwner()));
return $poll;
}
/**
* get poll configuration
* @return Poll
*/
public function get(int $pollId) {
try {
$this->poll = $this->pollMapper->find($pollId);
$this->poll->request(Poll::PERMISSION_POLL_VIEW);
return $this->poll;
} catch (DoesNotExistException $e) {
throw new NotFoundException('Poll not found');
}
}
/**
* Add poll
*/
public function add(string $type, string $title, string $votingVariant = Poll::VARIANT_SIMPLE): Poll {
if (!$this->appSettings->getPollCreationAllowed()) {
throw new ForbiddenException('Poll creation is disabled');
}
// Validate valuess
if (!in_array($type, $this->getValidPollType())) {
throw new InvalidPollTypeException('Invalid poll type');
}
if (!$title) {
throw new EmptyTitleException('Title must not be empty');
}
$timestamp = time();
$this->poll = new Poll();
$this->poll->setType($type);
$this->poll->setVotingVariant($votingVariant);
$this->poll->setTitle($title);
$this->poll->setCreated($timestamp);
$this->poll->setLastInteraction($timestamp);
$this->poll->setOwner($this->userSession->getCurrentUserId());
// create new poll before resetting all values to
// ensure that the poll has all required values and an id
// latter checks mai fail if the poll has no id
$this->poll = $this->pollMapper->insert($this->poll);
$this->poll->setDescription('');
$this->poll->setAccess(Poll::ACCESS_PRIVATE);
$this->poll->setExpire(0);
$this->poll->setAnonymousSafe(0);
$this->poll->setAllowMaybe(0);
$this->poll->setVoteLimit(0);
$this->poll->setShowResults(Poll::SHOW_RESULTS_ALWAYS);
$this->poll->setDeleted(0);
$this->poll->setAdminAccess(0);
$this->pollMapper->update($this->poll);
$this->eventDispatcher->dispatchTyped(new PollCreatedEvent($this->poll));
return $this->poll;
}
/**
* Update poll configuration
* @return Poll
*/
public function update(int $pollId, array $pollConfiguration): Poll {
$this->poll = $this->pollMapper->find($pollId);
$this->poll->request(Poll::PERMISSION_POLL_EDIT);
// Validate valuess
if (isset($pollConfiguration['showResults']) && !in_array($pollConfiguration['showResults'], $this->getValidShowResults())) {
throw new InvalidShowResultsException('Invalid value for prop showResults');
}
if (isset($pollConfiguration['title']) && !$pollConfiguration['title']) {
throw new EmptyTitleException('Title must not be empty');
}
if (isset($pollConfiguration['anonymous'])
&& $pollConfiguration['anonymous'] === 0
&& $this->poll->getAnonymous() < 0
) {
throw new ForbiddenException('Deanonimization is not allowed');
}
if (isset($pollConfiguration['access'])) {
if (!in_array($pollConfiguration['access'], $this->getValidAccess())) {
throw new InvalidAccessException('Invalid value for prop access ' . $pollConfiguration['access']);
}
if ($pollConfiguration['access'] === (Poll::ACCESS_OPEN)) {
$this->appSettings->getAllAccessAllowed();
}
}
// Set the expiry time to the actual servertime to avoid an
// expiry misinterpration when using permission checks
if (isset($pollConfiguration['expire']) && $pollConfiguration['expire'] < 0) {
$pollConfiguration['expire'] = time();
}
$this->poll->deserializeArray($pollConfiguration);
$this->poll = $this->pollMapper->update($this->poll);
$this->eventDispatcher->dispatchTyped(new PollUpdatedEvent($this->poll));
return $this->poll;
}
/**
* Manually lock anonymization
* @return Poll
*/
public function lockAnonymous(int $pollId): Poll {
$this->poll = $this->pollMapper->find($pollId);
// Only possible, if poll is already anonymized
if ($this->poll->getAnonymous() < 1) {
throw new ForbiddenException('Anonymization is not allowed');
}
// Only possible, if user is allowed to deanonymize
$this->poll->request(Poll::PERMISSION_DEANONYMIZE);
$this->poll->setAnonymous(-1);
$this->poll = $this->pollMapper->update($this->poll);
$this->eventDispatcher->dispatchTyped(new PollUpdatedEvent($this->poll));
return $this->poll;
}
/**
* Update timestamp for last interaction with polls
*/
public function setLastInteraction(int $pollId): void {
if ($pollId) {
$this->pollMapper->setLastInteraction($pollId);
}
}
/**
* Move to archive or restore
* @return Poll
*/
public function toggleArchive(int $pollId): Poll {
$this->poll = $this->pollMapper->find($pollId);
$this->poll->request(Poll::PERMISSION_POLL_DELETE);
$this->poll->setDeleted($this->poll->getDeleted() ? 0 : time());
$this->poll = $this->pollMapper->update($this->poll);
if ($this->poll->getDeleted()) {
$this->eventDispatcher->dispatchTyped(new PollArchivedEvent($this->poll));
} else {
$this->eventDispatcher->dispatchTyped(new PollRestoredEvent($this->poll));
}
return $this->poll;
}
/**
* Delete poll
* @return Poll
*/
public function delete(int $pollId): Poll {
try {
$this->poll = $this->pollMapper->find($pollId);
} catch (DoesNotExistException $e) {
throw new AlreadyDeletedException('Poll not found, assume already deleted');
}
$this->poll->request(Poll::PERMISSION_POLL_DELETE);
$this->eventDispatcher->dispatchTyped(new PollDeletedEvent($this->poll));
$this->pollMapper->delete($this->poll);
return $this->poll;
}
/**
* Close poll
* @return Poll
*/
public function close(int $pollId): Poll {
$this->pollMapper->find($pollId)->request(Poll::PERMISSION_POLL_EDIT);
return $this->toggleClose($pollId, time() - 5);
}
/**
* Reopen poll
* @return Poll
*/
public function reopen(int $pollId): Poll {
$this->pollMapper->find($pollId)->request(Poll::PERMISSION_POLL_EDIT);
return $this->toggleClose($pollId, 0);
}
/**
* Close poll
* @return Poll
*/
private function toggleClose(int $pollId, int $expiry): Poll {
$this->poll = $this->pollMapper->find($pollId);
$this->poll->request(Poll::PERMISSION_POLL_EDIT);
$this->poll->setExpire($expiry);
if ($expiry > 0) {
$this->eventDispatcher->dispatchTyped(new PollCloseEvent($this->poll));
} else {
$this->eventDispatcher->dispatchTyped(new PollReopenEvent($this->poll));
}
$this->poll = $this->pollMapper->update($this->poll);
return $this->poll;
}
/**
* Clone poll
* @return Poll
*/
public function clone(int $pollId): Poll {
$origin = $this->pollMapper->find($pollId);
$origin->request(Poll::PERMISSION_POLL_VIEW);
$this->appSettings->getPollCreationAllowed();
$this->poll = new Poll();
$this->poll->setCreated(time());
$this->poll->setOwner($this->userSession->getCurrentUserId());
$this->poll->setTitle('Clone of ' . $origin->getTitle());
$this->poll->setDeleted(0);
$this->poll->setAccess(Poll::ACCESS_PRIVATE);
$this->poll->setType($origin->getType());
$this->poll->setVotingVariant($origin->getVotingVariant());
$this->poll->setDescription($origin->getDescription());
$this->poll->setExpire($origin->getExpire());
// deanonymize cloned polls by default, to avoid locked anonymous polls
$this->poll->setAnonymous(0);
$this->poll->setAllowMaybe($origin->getAllowMaybe());
$this->poll->setVoteLimit($origin->getVoteLimit());
$this->poll->setShowResults($origin->getShowResults());
$this->poll->setAdminAccess($origin->getAdminAccess());
$this->poll = $this->pollMapper->insert($this->poll);
$this->eventDispatcher->dispatchTyped(new PollCreatedEvent($this->poll));
return $this->poll;
}
/**
* Collect email addresses from particitipants
*
*/
public function getParticipantsEmailAddresses(int $pollId): array {
$this->poll = $this->pollMapper->find($pollId);
$this->poll->request(Poll::PERMISSION_POLL_EDIT);
$votes = $this->voteMapper->findParticipantsByPoll($this->poll->getId());
$list = [];
foreach ($votes as $vote) {
$user = $vote->getUser();
$list[] = [
'displayName' => $user->getDisplayName(),
'emailAddress' => $user->getEmailAddress(),
'combined' => $user->getEmailAndDisplayName(),
];
}
return $list;
}
/**
* Get valid values for configuration options
*
* @return array
*
* @psalm-return array{pollType: mixed, access: mixed, showResults: mixed}
*/
public function getValidEnum(): array {
return [
'pollType' => $this->getValidPollType(),
'access' => $this->getValidAccess(),
'showResults' => $this->getValidShowResults()
];
}
/**
* Get valid values for pollType
*
* @return string[]
*
* @psalm-return array{0: string, 1: string}
*/
private function getValidPollType(): array {
return [Poll::TYPE_DATE, Poll::TYPE_TEXT];
}
/**
* Get valid values for access
*
* @return string[]
*
* @psalm-return array{0: string, 1: string}
*/
private function getValidAccess(): array {
return [Poll::ACCESS_PRIVATE, Poll::ACCESS_OPEN];
}
/**
* Get valid values for showResult
*
* @return string[]
*
* @psalm-return array{0: string, 1: string, 2: string}
*/
private function getValidShowResults(): array {
return [Poll::SHOW_RESULTS_ALWAYS, Poll::SHOW_RESULTS_CLOSED, Poll::SHOW_RESULTS_NEVER];
}
}