Passed
Push — develop-0.9 ( 8f11fc...a39c73 )
by René
02:58
created

PageController::__construct()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 29
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 13
nc 1
nop 14
dl 0
loc 29
ccs 14
cts 14
cp 1
crap 1
rs 8.8571
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/**
3
 * @copyright Copyright (c) 2017 Vinzenz Rosenkranz <[email protected]>
4
 *
5
 * @author Vinzenz Rosenkranz <[email protected]>
6
 *
7
 * @license GNU AGPL version 3 or any later version
8
 *
9
 *  This program is free software: you can redistribute it and/or modify
10
 *  it under the terms of the GNU Affero General Public License as
11
 *  published by the Free Software Foundation, either version 3 of the
12
 *  License, or (at your option) any later version.
13
 *
14
 *  This program is distributed in the hope that it will be useful,
15
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 *  GNU Affero General Public License for more details.
18
 *
19
 *  You should have received a copy of the GNU Affero General Public License
20
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 *
22
 */
23
24
namespace OCA\Polls\Controller;
25
26
use OCA\Polls\Db\Comment;
27
use OCA\Polls\Db\CommentMapper;
28
use OCA\Polls\Db\Event;
29
use OCA\Polls\Db\EventMapper;
30
use OCA\Polls\Db\Notification;
31
use OCA\Polls\Db\NotificationMapper;
32
use OCA\Polls\Db\Options;
33
use OCA\Polls\Db\OptionsMapper;
34
use OCA\Polls\Db\Votes;
35
use OCA\Polls\Db\VotesMapper;
36
use OCP\AppFramework\Controller;
37
use OCP\AppFramework\Db\DoesNotExistException;
38
use OCP\AppFramework\Http\ContentSecurityPolicy;
39
use OCP\AppFramework\Http\JSONResponse;
40
use OCP\AppFramework\Http\RedirectResponse;
41
use OCP\AppFramework\Http\TemplateResponse;
42
use OCP\IAvatarManager;
43
use OCP\IGroupManager;
44
use OCP\IL10N;
45
use OCP\ILogger;
46
use OCP\IRequest;
47
use OCP\IURLGenerator;
48
use OCP\IUserManager;
49
use OCP\Mail\IMailer;
50
use OCP\Security\ISecureRandom;
51
use OCP\User; //To do: replace according to API
52
use OCP\Util;
53
54
class PageController extends Controller {
55
56
	private $userId;
57
	private $commentMapper;
58
	private $eventMapper;
59
	private $notificationMapper;
60
	private $optionsMapper;
61
	private $votesMapper;
62
	private $urlGenerator;
63
	private $userMgr;
64
	private $avatarManager;
65
	private $logger;
66
	private $trans;
67
	private $groupManager;
68
69
	/**
70
	 * PageController constructor.
71
	 * @param string $appName
72
	 * @param IRequest $request
73
	 * @param IUserManager $userMgr
74
	 * @param IGroupManager $groupManager
75
	 * @param IAvatarManager $avatarManager
76
	 * @param ILogger $logger
77
	 * @param IL10N $trans
78
	 * @param IURLGenerator $urlGenerator
79
	 * @param string $userId
80
	 * @param CommentMapper $commentMapper
81
	 * @param EventMapper $eventMapper
82
	 * @param NotificationMapper $notificationMapper
83
	 * @param OptionsMapper $optionsMapper
84
	 * @param VotesMapper $VotesMapper
85
	 */
86 1
	public function __construct(
87
		$appName,
88
		IRequest $request,
89
		IUserManager $userMgr,
90
		IGroupManager $groupManager,
91
		IAvatarManager $avatarManager,
92
		ILogger $logger,
93
		IL10N $trans,
94
		IURLGenerator $urlGenerator,
95
		$userId,
96
		CommentMapper $commentMapper,
97
		OptionsMapper $optionsMapper,
98
		EventMapper $eventMapper,
99
		NotificationMapper $notificationMapper,
100
		VotesMapper $VotesMapper
101
	) {
102 1
		parent::__construct($appName, $request);
103 1
		$this->userMgr = $userMgr;
104 1
		$this->groupManager = $groupManager;
105 1
		$this->avatarManager = $avatarManager;
106 1
		$this->logger = $logger;
107 1
		$this->trans = $trans;
108 1
		$this->urlGenerator = $urlGenerator;
109 1
		$this->userId = $userId;
110 1
		$this->commentMapper = $commentMapper;
111 1
		$this->eventMapper = $eventMapper;
112 1
		$this->notificationMapper = $notificationMapper;
113 1
		$this->optionsMapper = $optionsMapper;
114 1
		$this->votesMapper = $VotesMapper;
115 1
	}
116
117
	/**
118
	 * @NoAdminRequired
119
	 * @NoCSRFRequired
120
	 */
121 1
	public function index() {
122 1
		$polls = $this->eventMapper->findAllForUserWithInfo($this->userId);
123 1
		$comments = $this->commentMapper->findDistinctByUser($this->userId);
124 1
		$votes = $this->votesMapper->findDistinctByUser($this->userId);
125 1
		$response = new TemplateResponse('polls', 'main.tmpl', [
126 1
			'polls' => $polls,
127 1
			'comments' => $comments,
128 1
			'votes' => $votes,
129 1
			'userId' => $this->userId,
130 1
			'userMgr' => $this->userMgr,
131 1
			'urlGenerator' => $this->urlGenerator
132
		]);
133 1
		$csp = new ContentSecurityPolicy();
134 1
		$response->setContentSecurityPolicy($csp);
135 1
		return $response;
136
	}
137
138
	/**
139
	 * @param int $pollId
140
	 * @param string $from
141
	 */
142
	private function sendNotifications($pollId, $from) {
143
		$poll = $this->eventMapper->find($pollId);
144
		$notifications = $this->notificationMapper->findAllByPoll($pollId);
145
		foreach ($notifications as $notification) {
146
			if ($from === $notification->getUserId()) {
147
				continue;
148
			}
149
			$email = \OC::$server->getConfig()->getUserValue($notification->getUserId(), 'settings', 'email');
150
			if ($email === null || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
151
				continue;
152
			}
153
			$url = $this->urlGenerator->getAbsoluteURL(
154
				$this->urlGenerator->linkToRoute('polls.page.goto_poll',
155
					array('hash' => $poll->getHash()))
156
			);
157
158
			$recUser = $this->userMgr->get($notification->getUserId());
159
			$sendUser = $this->userMgr->get($from);
160
			$rec = '';
161
			if ($recUser !== null) {
162
				$rec = $recUser->getDisplayName();
163
			}
164
			$sender = $from;
165
			if ($sendUser !== null) {
166
				$sender = $sendUser->getDisplayName();
167
			}
168
			$msg = $this->trans->t('Hello %s,<br/><br/><strong>%s</strong> participated in the poll \'%s\'.<br/><br/>To go directly to the poll, you can use this <a href="%s">link</a>',
169
				array(
170
					$rec,
171
					$sender,
172
					$poll->getTitle(),
173
					$url
174
				));
175
176
			$msg .= '<br/><br/>';
177
178
			$toName = $this->userMgr->get($notification->getUserId())->getDisplayName();
179
			$subject = $this->trans->t('Polls App - New Activity');
180
			$fromAddress = Util::getDefaultEmailAddress('no-reply');
181
			$fromName = $this->trans->t('Polls App') . ' (' . $from . ')';
182
183
			try {
184
				/** @var IMailer $mailer */
185
				$mailer = \OC::$server->getMailer();
186
				/** @var \OC\Mail\Message $message */
187
				$message = $mailer->createMessage();
188
				$message->setSubject($subject);
189
				$message->setFrom(array($fromAddress => $fromName));
190
				$message->setTo(array($email => $toName));
191
				$message->setHtmlBody($msg);
192
				$mailer->send($message);
193
			} catch (\Exception $e) {
194
				$message = 'Error sending mail to: ' . $toName . ' (' . $email . ')';
195
				Util::writeLog('polls', $message, Util::ERROR);
196
			}
197
		}
198
	}
199
200
	/**
201
	 * @NoAdminRequired
202
	 * @NoCSRFRequired
203
	 * @PublicPage
204
	 * @param string $hash
205
	 * @return TemplateResponse
206
	 */
207
	public function gotoPoll($hash) {
208
		try {
209
			$poll = $this->eventMapper->findByHash($hash);
210
		} catch (DoesNotExistException $e) {
211
			return new TemplateResponse('polls', 'no.acc.tmpl', []);
212
		}
213
		$options = $this->optionsMapper->findByPoll($poll->getId());
214
		$votes = $this->votesMapper->findByPoll($poll->getId());
215
		$participants = $this->votesMapper->findParticipantsByPoll($poll->getId());
216
		$comments = $this->commentMapper->findByPoll($poll->getId());
217
218
		try {
219
			$notification = $this->notificationMapper->findByUserAndPoll($poll->getId(), $this->userId);
220
		} catch (DoesNotExistException $e) {
221
			$notification = null;
222
		}
223
		if ($this->hasUserAccess($poll)) {
224
			return new TemplateResponse('polls', 'goto.tmpl', [
225
				'poll' => $poll,
226
				'options' => $options,
227
				'comments' => $comments,
228
				'votes' => $votes,
229
				'participant' => $participants,
230
				'notification' => $notification,
231
				'userId' => $this->userId,
232
				'userMgr' => $this->userMgr,
233
				'urlGenerator' => $this->urlGenerator,
234
				'avatarManager' => $this->avatarManager
235
			]);
236
		} else {
237
			User::checkLoggedIn();
238
			return new TemplateResponse('polls', 'no.acc.tmpl', []);
239
		}
240
	}
241
242
	/**
243
	 * @NoAdminRequired
244
	 * @NoCSRFRequired
245
	 * @param int $pollId
246
	 * @return TemplateResponse|RedirectResponse
247
	 */
248
	public function deletePoll($pollId) {
249
		$pollToDelete = $this->eventMapper->find($pollId);
250
		if ($this->userId !== $pollToDelete->getOwner()) {
251
			return new TemplateResponse('polls', 'no.delete.tmpl');
252
		}
253
		$poll = new Event();
254
		$poll->setId($pollId);
255
		$this->eventMapper->delete($poll);
256
		$this->optionsMapper->deleteByPoll($pollId);
257
		$this->votesMapper->deleteByPoll($pollId);
258
		$this->commentMapper->deleteByPoll($pollId);
259
		$url = $this->urlGenerator->linkToRoute('polls.page.index');
260
		return new RedirectResponse($url);
261
	}
262
263
	/**
264
	 * @NoAdminRequired
265
	 * @NoCSRFRequired
266
	 * @param string $hash
267
	 * @return TemplateResponse
268
	 */
269
	public function editPoll($hash) {
270
		$poll = $this->eventMapper->findByHash($hash);
271
		if ($this->userId !== $poll->getOwner()) {
272
			return new TemplateResponse('polls', 'no.create.tmpl');
273
		}
274
		$options = $this->optionsMapper->findByPoll($poll->getId());
275
		return new TemplateResponse('polls', 'create.tmpl', [
276
			'poll' => $poll,
277
			'options' => $options,
278
			'userId' => $this->userId,
279
			'userMgr' => $this->userMgr,
280
			'urlGenerator' => $this->urlGenerator
281
		]);
282
	}
283
284
	/**
285
	 * @NoAdminRequired
286
	 * @NoCSRFRequired
287
	 * @param int $pollId
288
	 * @param string $pollType
289
	 * @param string $pollTitle
290
	 * @param string $pollDesc
291
	 * @param string $userId
292
	 * @param string $chosenOptions
293
	 * @param int $expireTs
294
	 * @param string $accessType
295
	 * @param string $accessValues
296
	 * @param bool $isAnonymous
297
	 * @param bool $hideNames
298
	 * @return RedirectResponse
299
	 */
300
	public function updatePoll(
301
		$pollId,
302
		$pollType,
303
		$pollTitle,
304
		$pollDesc,
305
		$chosenOptions,
306
		$expireTs,
307
		$accessType,
308
		$accessValues,
309
		$isAnonymous,
310
		$hideNames
311
	) {
312
313
314
		$event = $this->eventMapper->find($pollId);
315
		$event->setTitle($pollTitle);
316
		$event->setDescription($pollDesc);
317
		$event->setIsAnonymous($isAnonymous ? 1 : 0);
318
		$event->setFullAnonymous($isAnonymous && $hideNames ? 1 : 0);
319
320
		if ($accessType === 'select') {
321
			if (isset($accessValues)) {
322
				$accessValues = json_decode($accessValues);
323
				if ($accessValues !== null) {
324
					$groups = array();
325
					$users = array();
326
					if ($accessValues->groups !== null) {
327
						$groups = $accessValues->groups;
328
					}
329
					if ($accessValues->users !== null) {
330
						$users = $accessValues->users;
331
					}
332
					$accessType = '';
333
					foreach ($groups as $gid) {
334
						$accessType .= $gid . ';';
335
					}
336
					foreach ($users as $uid) {
337
						$accessType .= $uid . ';';
338
					}
339
				}
340
			}
341
		}
342
		$event->setAccess($accessType);
343
		/** @var string[] $chosenOptions */
344
		$chosenOptions = json_decode($chosenOptions, true);
0 ignored issues
show
Bug introduced by
$chosenOptions of type string[] is incompatible with the type string expected by parameter $json of json_decode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

344
		$chosenOptions = json_decode(/** @scrutinizer ignore-type */ $chosenOptions, true);
Loading history...
345
346
		$expire = null;
347
		if ($expireTs !== 0 && $expireTs !== '') {
348
			$expire = date('Y-m-d H:i:s', $expireTs);
349
		}
350
		$event->setExpire($expire);
351
352
		$this->optionsMapper->deleteByPoll($pollId);
353
		if ($pollType === 'event') {
354
			$event->setType(0);
355
			$this->eventMapper->update($event);
356
			sort($chosenOptions);
357
			foreach ($chosenOptions as $optionElement) {
358
				$option = new Options();
359
				$option->setPollId($pollId);
360
				$option->setPollOptionText(date('Y-m-d H:i:s', (int)$optionElement));
361
				$this->optionsMapper->insert($option);
362
			}
363
		} else {
364
			$event->setType(1);
365
			$this->eventMapper->update($event);
366
			foreach ($chosenOptions as $optionElement) {
367
				$option = new Options();
368
				$option->setPollId($pollId);
369
				$option->setpollOptionText($optionElement);
370
				$this->optionsMapper->insert($option);
371
			}
372
		}
373
		$url = $this->urlGenerator->linkToRoute('polls.page.index');
374
		return new RedirectResponse($url);
375
	}
376
377
	/**
378
	 * @NoAdminRequired
379
	 * @NoCSRFRequired
380
	 */
381
	public function createPoll() {
382
		return new TemplateResponse('polls', 'create.tmpl',
383
			['userId' => $this->userId, 'userMgr' => $this->userMgr, 'urlGenerator' => $this->urlGenerator]);
384
	}
385
386
	/**
387
	 * @NoAdminRequired
388
	 * @NoCSRFRequired
389
	 * @param string $pollType
390
	 * @param string $pollTitle
391
	 * @param string $pollDesc
392
	 * @param string $userId
393
	 * @param string $chosenOptions
394
	 * @param int $expireTs
395
	 * @param string $accessType
396
	 * @param string $accessValues
397
	 * @param bool $isAnonymous
398
	 * @param bool $hideNames
399
	 * @return RedirectResponse
400
	 */
401
	public function insertPoll(
402
		$pollType,
403
		$pollTitle,
404
		$pollDesc,
405
		$userId,
406
		$chosenOptions,
407
		$expireTs,
408
		$accessType,
409
		$accessValues,
410
		$isAnonymous,
411
		$hideNames
412
	) {
413
		$event = new Event();
414
		$event->setTitle($pollTitle);
415
		$event->setDescription($pollDesc);
416
		$event->setOwner($userId);
417
		$event->setCreated(date('Y-m-d H:i:s'));
418
		$event->setHash(\OC::$server->getSecureRandom()->generate(
419
			16,
420
			ISecureRandom::CHAR_DIGITS .
421
			ISecureRandom::CHAR_LOWER .
422
			ISecureRandom::CHAR_UPPER
423
		));
424
		$event->setIsAnonymous($isAnonymous ? 1 : 0);
425
		$event->setFullAnonymous($isAnonymous && $hideNames ? 1 : 0);
426
427
		if ($accessType === 'select') {
428
			if (isset($accessValues)) {
429
				$accessValues = json_decode($accessValues);
430
				if ($accessValues !== null) {
431
					$groups = array();
432
					$users = array();
433
					if ($accessValues->groups !== null) {
434
						$groups = $accessValues->groups;
435
					}
436
					if ($accessValues->users !== null) {
437
						$users = $accessValues->users;
438
					}
439
					$accessType = '';
440
					foreach ($groups as $gid) {
441
						$accessType .= $gid . ';';
442
					}
443
					foreach ($users as $uid) {
444
						$accessType .= $uid . ';';
445
					}
446
				}
447
			}
448
		}
449
		$event->setAccess($accessType);
450
		/** @var string[] $chosenOptions */
451
		$chosenOptions = json_decode($chosenOptions, true);
0 ignored issues
show
Bug introduced by
$chosenOptions of type string[] is incompatible with the type string expected by parameter $json of json_decode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

451
		$chosenOptions = json_decode(/** @scrutinizer ignore-type */ $chosenOptions, true);
Loading history...
452
453
		$expire = null;
454
		if ($expireTs !== 0 && $expireTs !== '') {
455
			$expire = date('Y-m-d H:i:s', $expireTs);
456
		}
457
		$event->setExpire($expire);
458
459
		if ($pollType === 'event') {
460
			$event->setType(0);
461
			$ins = $this->eventMapper->insert($event);
462
			$pollId = $ins->getId();
463
			sort($chosenOptions);
464
			foreach ($chosenOptions as $optionElement) {
465
				$option = new Options();
466
				$option->setPollId($pollId);
467
				$option->setPollOptionText(date('Y-m-d H:i:s', (int)$optionElement));
468
				$this->optionsMapper->insert($option);
469
			}
470
		} else {
471
			$event->setType(1);
472
			$ins = $this->eventMapper->insert($event);
473
			$pollId = $ins->getId();
474
			foreach ($chosenOptions as $optionElement) {
475
				$option = new Options();
476
				$option->setPollId($pollId);
477
				$option->setpollOptionText($optionElement);
478
				$this->optionsMapper->insert($option);
479
			}
480
		}
481
		$url = $this->urlGenerator->linkToRoute('polls.page.index');
482
		return new RedirectResponse($url);
483
	}
484
485
	/**
486
	 * @NoAdminRequired
487
	 * @NoCSRFRequired
488
	 * @PublicPage
489
	 * @param int $pollId
490
	 * @param string $userId
491
	 * @param string $answers
492
	 * @param string $options
493
	 * @param bool $receiveNotifications
494
	 * @param bool $changed
495
	 * @return RedirectResponse
496
	 */
497
	public function insertVote($pollId, $userId, $answers, $options, $receiveNotifications, $changed) {
498
		if ($this->userId !== null) {
0 ignored issues
show
introduced by
The condition $this->userId !== null can never be false.
Loading history...
499
			if ($receiveNotifications) {
500
				try {
501
					//check if user already set notification for this poll
502
					$this->notificationMapper->findByUserAndPoll($pollId, $userId);
503
				} catch (DoesNotExistException $e) {
504
					//insert if not exist
505
					$not = new Notification();
506
					$not->setUserId($userId);
507
					$not->setPollId($pollId);
508
					$this->notificationMapper->insert($not);
509
				}
510
			} else {
511
				try {
512
					//delete if entry is in db
513
					$not = $this->notificationMapper->findByUserAndPoll($pollId, $userId);
514
					$this->notificationMapper->delete($not);
515
				} catch (DoesNotExistException $e) {
516
					//doesn't exist in db, nothing to do
517
				}
518
			}
519
		}
520
		$poll = $this->eventMapper->find($pollId);
521
		
522
		if ($changed) {
523
			// $dates = json_decode($dates);
524
			// $types = json_decode($types);
525
			$options = json_decode($options);
526
			$answers = json_decode($answers);
527
			$count_options = count($options);
528
			$this->votesMapper->deleteByPollAndUser($pollId, $userId);
529
			
530
			for ($i = 0; $i < $count_options; $i++) {
531
				$vote = new Votes();
532
				$vote->setPollId($pollId);
533
				$vote->setUserId($userId);
534
				// $part->setDt(date('Y-m-d H:i:s', $options[$i]));
535
				// $part->setType($types[$i]);
536
				// $vote->setVoteOptionId($options[$i]); //Todo
537
				// $vote->setVoteOptionText($poll->getOptionTextFromId($options[$i])); //Todo
538
				// $vote->setVoteType($types[$i]); //needed?
539
				$vote->setVoteOptionText($options[$i]);
540
				$vote->setVoteAnswer($answers[$i]);
541
				$this->votesMapper->insert($vote);
542
543
			}
544
			$this->sendNotifications($pollId, $userId);
545
		}
546
		$hash = $poll->getHash();
547
		$url = $this->urlGenerator->linkToRoute('polls.page.goto_poll', ['hash' => $hash]);
548
		return new RedirectResponse($url);
549
	}
550
551
	/**
552
	 * @NoAdminRequired
553
	 * @NoCSRFRequired
554
	 * @PublicPage
555
	 * @param int $pollId
556
	 * @param string $userId
557
	 * @param string $commentBox
558
	 * @return JSONResponse
559
	 */
560
	public function insertComment($pollId, $userId, $commentBox) {
561
		$comment = new Comment();
562
		$comment->setPollId($pollId);
563
		$comment->setUserId($userId);
564
		$comment->setComment($commentBox);
565
		$comment->setDt(date('Y-m-d H:i:s'));
566
		$this->commentMapper->insert($comment);
567
		$this->sendNotifications($pollId, $userId);
568
		$timeStamp = time();
569
		$relativeNow = $this->trans->t('just now');
0 ignored issues
show
Unused Code introduced by
The assignment to $relativeNow is dead and can be removed.
Loading history...
570
		$displayName = $userId;
571
		$user = $this->userMgr->get($userId);
572
		if ($user !== null) {
573
			$displayName = $user->getDisplayName();
574
		}
575
		return new JSONResponse(array(
576
			'userId' => $userId,
577
			'displayName' => $displayName,
578
			'timeStamp' => $timeStamp *100, 
579
			'date' => date('Y-m-d H:i:s', $timeStamp),
580
			'relativeNow' => $this->trans->t('just now'),
581
			'comment' => $commentBox
582
		));
583
	}
584
585
	/**
586
	 * @NoAdminRequired
587
	 * @NoCSRFRequired
588
	 * @param string $searchTerm
589
	 * @param string $groups
590
	 * @param string $users
591
	 * @return array
592
	 */
593
	public function search($searchTerm, $groups, $users) {
594
		return array_merge($this->searchForGroups($searchTerm, $groups), $this->searchForUsers($searchTerm, $users));
595
	}
596
597
	/**
598
	 * @NoAdminRequired
599
	 * @NoCSRFRequired
600
	 * @param string $searchTerm
601
	 * @param string $groups
602
	 * @return array
603
	 */
604
	public function searchForGroups($searchTerm, $groups) {
605
		$selectedGroups = json_decode($groups);
606
		$groups = $this->groupManager->search($searchTerm);
607
		$gids = array();
608
		$sgids = array();
609
		foreach ($selectedGroups as $sg) {
610
			$sgids[] = str_replace('group_', '', $sg);
611
		}
612
		foreach ($groups as $g) {
613
			$gids[] = $g->getGID();
614
		}
615
		$diffGids = array_diff($gids, $sgids);
616
		$gids = array();
617
		foreach ($diffGids as $g) {
618
			$gids[] = ['gid' => $g, 'isGroup' => true];
619
		}
620
		return $gids;
621
	}
622
623
	/**
624
	 * @NoAdminRequired
625
	 * @NoCSRFRequired
626
	 * @param string $searchTerm
627
	 * @param string $users
628
	 * @return array
629
	 */
630
	public function searchForUsers($searchTerm, $users) {
631
		$selectedUsers = json_decode($users);
632
		Util::writeLog('polls', print_r($selectedUsers, true), Util::ERROR);
633
		$userNames = $this->userMgr->searchDisplayName($searchTerm);
634
		$users = array();
635
		$sUsers = array();
636
		foreach ($selectedUsers as $su) {
637
			$sUsers[] = str_replace('user_', '', $su);
638
		}
639
		foreach ($userNames as $u) {
640
			$alreadyAdded = false;
641
			foreach ($sUsers as &$su) {
642
				if ($su === $u->getUID()) {
643
					unset($su);
644
					$alreadyAdded = true;
645
					break;
646
				}
647
			}
648
			if (!$alreadyAdded) {
649
				$users[] = array('uid' => $u->getUID(), 'displayName' => $u->getDisplayName(), 'isGroup' => false);
650
			} else {
651
				continue;
652
			}
653
		}
654
		return $users;
655
	}
656
657
	/**
658
	 * @NoAdminRequired
659
	 * @NoCSRFRequired
660
	 * @param string $username
661
	 * @return string
662
	 */
663
	public function getDisplayName($username) {
664
		return $this->userMgr->get($username)->getDisplayName();
665
	}
666
667
	/**
668
	 * @return \OCP\IGroup[]
669
	 */
670
	private function getGroups() {
671
		if (class_exists('\OC_Group')) {
672
			// Nextcloud <= 11, ownCloud
673
			return \OC_Group::getUserGroups($this->userId);
0 ignored issues
show
Bug introduced by
The type OC_Group was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
674
		}
675
		// Nextcloud >= 12
676
		$groups = $this->groupManager->getUserGroups(\OC::$server->getUserSession()->getUser());
677
		return array_map(function ($group) {
678
			return $group->getGID();
679
		}, $groups);
680
	}
681
682
	/**
683
	 * @param Event $poll
684
	 * @return bool
685
	 */
686
	private function hasUserAccess($poll) {
687
		$access = $poll->getAccess();
688
		$owner = $poll->getOwner();
689
		if ($access === 'public' || $access === 'hidden') {
690
			return true;
691
		}
692
		if ($this->userId === null) {
0 ignored issues
show
introduced by
The condition $this->userId === null can never be true.
Loading history...
693
			return false;
694
		}
695
		if ($access === 'registered') {
696
			return true;
697
		}
698
		if ($owner === $this->userId) {
699
			return true;
700
		}
701
		Util::writeLog('polls', $this->userId, Util::ERROR);
702
		$userGroups = $this->getGroups();
703
		$arr = explode(';', $access);
704
		foreach ($arr as $item) {
705
			if (strpos($item, 'group_') === 0) {
706
				$grp = substr($item, 6);
707
				foreach ($userGroups as $userGroup) {
708
					if ($userGroup === $grp) {
709
						return true;
710
					}
711
				}
712
			} else {
713
				if (strpos($item, 'user_') === 0) {
714
					$usr = substr($item, 5);
715
					if ($usr === $this->userId) {
716
						return true;
717
					}
718
				}
719
			}
720
		}
721
		return false;
722
	}
723
}
724